/* QW UTILS */

var qwPleaseWait;

function encode(val) {
     encodedHtml = escape(val);
     encodedHtml = encodedHtml.replace(/\//g,"%2F");
     encodedHtml = encodedHtml.replace(/\?/g,"%3F");
     encodedHtml = encodedHtml.replace(/=/g,"%3D");
     encodedHtml = encodedHtml.replace(/&/g,"%26");
     encodedHtml = encodedHtml.replace(/@/g,"%40");
     return encodedHtml;
}

function adjustLayers()
{
	if($('yui-dialog-texteditor_mask') != null)
	{
		$('yui-dialog-texteditor_mask').style.zIndex = '24000';	
	}
	if ($('yui-uploader-panel_mask') != null) 
	{
		$('yui-uploader-panel_mask').style.zIndex = '24000';
	}
	if($('yui-imagepicker-panel_mask') != null)
	{
		$('yui-imagepicker-panel_mask').style.zIndex = '24000';
	}
	
	if($('yui-imagepicker-panel_c') != null)
	{
		$('yui-imagepicker-panel_c').style.zIndex = '450000';	
	}
	if($('yui-uploader-panel_c') != null)
	{
		$('yui-uploader-panel_c').style.zIndex = '460000';	
	}
	if($('yui-dialog-texteditor_c') != null)
	{
		$('yui-dialog-texteditor_c').style.zIndex = '25000';	
	}
}

function showPleaseWait()
{
	qwPleaseWait.center();
	qwPleaseWait.show();	
}

function hidePleaseWait()
{
	qwPleaseWait.hide();	
}

function qwFetchImages(path,cb)
{
	if (path != "" && path != null) {
		url = "/fetchimages/" + path + "/";
	}
	else
	{
		url = "/fetchimages/";
	}
	new Ajax.Request(url,
		{
			method:'get',
			onSuccess:function(transport){
				files = transport.responseText.evalJSON();
				cb(files);
			}
		});
} 
 
function qwCommit(op,value)
{
	op.value = value;
	url = "/set/" + op.name + "/";
	new Ajax.Request(url,{method:'post',parameters:{value:value}});
}

function qwSet(op,value)
{
	target = op.target.replace("[target]","$('"+op.scope+"')");
	
	scope = "$('"+op.scope+"')";
	if(op.scope == "document")
	{
		scope = "document.body";
	}
	
	if(target.indexOf(".") < 0)
	{
		script = scope + ".style." + op.target.camelize() + "='" + value + "'";
	}
	else
	{
		script = op.target.replace("[target]","$('"+scope+"')") + "='" + value + "'";
	}
	
	eval(script);
}

function qwSetImage(op,value)
{

	target = op.target.replace("[target]","$('"+op.scope+"')");
	
	scope = "$('"+op.scope+"')";
	if(op.scope == "document")
	{
		scope = "document.body";
	}
	
	if(target.indexOf(".") < 0)
	{
		var imgvalue = "url('" + value + "')";
		script = scope + ".style." + target.camelize() + "=\"" + imgvalue + "\"";
	}
	else
	{
		script = target + "='" + value + "'";
	}
	eval(script);
}

var qwButtons = $A();
var qwContainers = $A();

function setQWOp(op)
{
	
	// GET ELEMENT
	
	var e = $(op.scope);
		
	if(e == null)
	{
		return;
	}
	
	// CREATE BUTTON CONTAINER
	
	var opContainer = e.qwOpContainer;
	if (opContainer == null) {
		if (op.choices.container == null) {
			opContainer = new Element("div", {
				"id": "qwOpContainer" + e.id,
				"class": "qwOpContainer"
			})
			
			e.qwOpContainer = opContainer;
			e.insert({
				after: opContainer
			})
			opContainer.absolutize();
			try {
				opContainer.clonePosition(e, {
					setLeft: true,
					setTop: true,
					setWidth: true,
					setHeight: false,
					offsetTop: -20
				})
			} 
			catch (err) {
			}
			qwContainers.push(opContainer);
		}
		else{
			var shareId = "qwOpContainer" + op.choices.container;
			opContainer = $(shareId);
			e.qwOpContainer = opContainer;
		}
	}
	
	// CREATE BUTTON
	
	var btn = new Element("span",{"id":"opBtn"+op.name,"class":"qwButton"})
	btn.update(op.title);
	opContainer.insert({bottom:btn});
		
	btn.op = op;
	btn.observe("click",function(e){onButtonClick(e.element().op);return false;});
	btn.observe("mouseover",function(e){lightButton(e.element(),e.element().op);return false;});
	btn.observe("mouseout",function(e){dimButton(e.element(),e.element().op);return false;});
	//btn.setOpacity(.3);
	qwButtons.push(btn);	
}

function lightButton(btn,op) {

	var e = $(op.scope);
	u = e.up("div.qwapplet")
	if(u)
	{
		e = u;
	}
	
	if (btn.overlay == null) {
		var overlay = new Element("div", {
			"class": "qwOverlay"
		});
		e.insert({
			after: overlay
		});
		overlay.setOpacity(.3);
		overlay.absolutize();
		
		overlay.clonePosition(e, {
			setLeft: true,
			setTop: true,
			setWidth: true,
			setHeight: true
		});
		
		btn.overlay = overlay;
		
	}
	else{
		btn.overlay.clonePosition(e, {
			setLeft: true,
			setTop: true,
			setWidth: true,
			setHeight: true
		});
		btn.overlay.show();
	}
	
}

function dimButton(btn,op) {

	btn.overlay.hide();
}


function hideButtons()
{
	qwContainers.each(function(b){b.hide()});
}

function showButtons()
{
	qwContainers.each(function(b){b.show()});
}

function onMenuItemClick(p_sType, p_aArgs, op) {
	onOpPick(op);
}

function onButtonClick(op) {
	onOpPick(op);
}

function onOpPick(op)
{
	if(op.choices.edittext != null && op.choices.edittext==true)
	{
		doEditor(op)
		return;
	}
	if(op.choices.onclick)
	{
		op.choices.onclick(op);
		return;
	}
	if(op.choices.parameters != null)
	{
		if(op.choices.confirm != null)
		{
			if(confirm(op.choices.confirm) == false)
			{
				return;
			}
		}
		doDialog(op)
		return;
	}
	if (op.choices.startsWith == null) {
		if (op.choices.color != null) {
			doColorDialog(op)
		}

		if (op.choices.image != null) {
			doImageDialog(op)
		}
	}
	else {
		if (op.choices == "color") {
			doColorDialog(op)
		}
		if (op.choices.startsWith("choose:")) {
			doChoiceDialog(op)
		}
		if (op.choices.startsWith("image:")) {
			doImageDialog(op)
		}
	}
	
}

var applets = $A()

function renderApplets(){
	applets.each(function(a){renderApplet(a)});
}

function renderApplet(configop)
{
	
	// GET ELEMENT
	
	var e = $(configop.scope);
	
	u = e.up('.qwapplet');
	
	if(u)
	{
		e = u;
	}
	
	if(e == null)
	{
		return;
	}
	
	var ops = $A(configop.ops);
	
	
	// CREATE BUTTON CONTAINER
	
	var opContainer = e.qwOpContainer
	if (opContainer == null) {
		opContainer = new Element("div", {
			"id": "qwOpContainer" + e.id,
			"class": "qwOpContainer"
		})
		
		e.qwOpContainer = opContainer;
		
		e.insert({after:opContainer})
		
		opContainer.absolutize();
		
		
		dim = e.getDimensions();
		opContainer.style.width = dim.width + "px";
		offset = e.cumulativeOffset();
		
		opContainer.style.top = (offset.top - 20) + "px";
		opContainer.style.left = offset.left + "px";

		try {
			opContainer.clonePosition(e, {
				setLeft: true,
				setTop: true,
				setWidth: true,
				setHeight: false,
				offsetTop: -20
			})
		}
		catch(err){}
		
		width = opContainer.getWidth();
		minWidth = (ops.length+6) * 24;
		
		if(width<minWidth)
		{
			opContainer.style.width = minWidth + "px";
		}
		
		/*
		opContainer.observe("mouseover",function(e){
			opc=this;
			qwContainers.each(function(c){
				if(opc.id!=c.id){c.style.zIndex='9998'};
			})
			
			opc.style.zIndex='2000'
			}.bind(opContainer));
		*/
		
		qwContainers.push(opContainer);
	}
	
	// CREATE BUTTONS

	ops.each(function(op){
		
		op.scope = configop.scope;
		op.applet = configop.applet;
		var btn;
		if (op.icon) {
			btn = new Element("img",{"id":"opBtn"+configop.scope+op.title,"src":"http://qw.pagedragon.com/media/images/"+op.icon,"class":"qwIconButton","title":op.title})
		}
		else {
			btn = new Element("span",{"id":"opBtn"+configop.scope+op.title,"class":"qwButton"})
			btn.update(op.title);
		}
		this.insert({bottom:btn});

		btn.op = op;
		btn.observe("click",function(e){onButtonClick(e.element().op);return false;});
		btn.observe("mouseover",function(e){lightButton(e.element(),e.element().op);return false;});
		btn.observe("mouseout",function(e){dimButton(e.element(),e.element().op);return false;});
		btn.setOpacity(.8);
		qwButtons.push(btn);	
	}.bind(opContainer));
	
	// ADD APPEARANCE
	
	op = {title:"Appearance"}
	op.choices = {
		parameters: {
			_pageview: 'appletappearance',
			appletId:configop.applet,
			sections:sections
		}
	}
	op.scope = configop.scope;
	op.applet = -1;
	var btn = new Element("img",{"id":"opBtn"+configop.scope+op.title,"src":"http://qw.pagedragon.com/media/images/appearance.png","class":"qwIconButton","title":op.title})
	opContainer.insert({bottom:btn});

	btn.op = op;
	btn.observe("click",function(e){onButtonClick(e.element().op);return false;});
	btn.observe("mouseover",function(e){lightButton(e.element(),e.element().op);return false;});
	btn.observe("mouseout",function(e){dimButton(e.element(),e.element().op);return false;});
	qwButtons.push(btn);
	
	// ADD MOVE HIGHER
	
	op = {title:"Move Higher"}
	op.choices = {
		parameters: {
			_pageview: 'moveapplethigher',
			appletId:configop.applet
		}
		
	}
	op.scope = configop.scope;
	op.applet = -1;
	var btn = new Element("img",{"id":"opBtn"+configop.scope+op.title,"src":"http://qw.pagedragon.com/media/images/higher.png","class":"qwIconButton","title":op.title})
	opContainer.insert({bottom:btn});

	btn.op = op;
	btn.observe("click",function(e){doAjaxRefresh(e.element().op);return false;});
	btn.observe("mouseover",function(e){lightButton(e.element(),e.element().op);return false;});
	btn.observe("mouseout",function(e){dimButton(e.element(),e.element().op);return false;});
	qwButtons.push(btn);
	
	// ADD MOVE LOWER
	
	op = {title:"Move Lower"}
	op.choices = {
		parameters: {
			_pageview: 'moveappletlower',
			appletId:configop.applet
		}
		
	}
	op.scope = configop.scope;
	op.applet = -1;
	var btn = new Element("img",{"id":"opBtn"+configop.scope+op.title,"src":"http://qw.pagedragon.com/media/images/lower.png","class":"qwIconButton","title":op.title})
	opContainer.insert({bottom:btn});

	btn.op = op;
	btn.observe("click",function(e){doAjaxRefresh(e.element().op);return false;});
	btn.observe("mouseover",function(e){lightButton(e.element(),e.element().op);return false;});
	btn.observe("mouseout",function(e){dimButton(e.element(),e.element().op);return false;});
	qwButtons.push(btn);

	// ADD DELETE
	
	op = {title:"Delete"}
	op.choices = {
		parameters: {
			_pageview: 'deleteapplet',
			appletId:configop.applet
		},
		confirm:'Are you sure you wish to delete this content?'
		
	}
	op.scope = configop.scope;
	op.applet = -1;
	var btn = new Element("img",{"id":"opBtn"+configop.scope+op.title,"src":"http://qw.pagedragon.com/media/images/delete.png","class":"qwIconButton","style":"margin-left:20px","title":op.title})
	opContainer.insert({bottom:btn});

	btn.op = op;
	btn.observe("click",function(e){onButtonClick(e.element().op);return false;});
	btn.observe("mouseover",function(e){lightButton(e.element(),e.element().op);return false;});
	btn.observe("mouseout",function(e){dimButton(e.element(),e.element().op);return false;});
	qwButtons.push(btn);
	
	// ADD SEQUENCE
	
	
	var seq = new Element("span",{"style":"position:relative;top:-18px;float:right;display:block;height:18px;margin-top:0;font-size:12px;color:#ffffff"})
	seq.update("("+configop.sequence+")&nbsp;");
	
	opContainer.insert({bottom:seq});

}

function doAjaxRefresh(op)
{
	this.dialogApplet = op.applet;
	new Ajax.Request('/ajax/' + op.applet + '/', {
		parameters: op.choices.parameters,
		onSuccess: function ()
		{
			refreshPage();
		}
	});	
}

function addApplet(configop,sequence)
{
	configop.sequence = sequence;
	applets.push(configop);
	
}


var sections = $A()

function addSection(section)
{
	sections.push(section);
}

function createSlug(source,target)
{
	var url = $F(source);
	url = url.gsub(" ", "-");
	url = url.toLowerCase();
	$(target).value = url;
}	

function  home()
{
	window.location.href = "/"
}

function  refreshPage()
{
	window.location.href = window.location.pathname;
}

function  refreshApplet(appletId,params)
{
	if (!params) {
		new Ajax.Updater('qwcontent_id' + appletId, '/ajax/' + appletId + '/');
	}
	else{
		new Ajax.Updater('qwcontent_id' + appletId, '/ajax/' + appletId + '/params/'+params);
	}
}

function updateControlPanels()
{

	applets.each(function(configop){
		

		var e = $(configop.scope);
		var u = e.up('.qwapplet');
		if(u)
		{
			e = u;
		}

		if(e == null)
		{
			return;
		}

		e.qwOpContainer.clonePosition(e, {
				setLeft: true,
				setTop: true,
				setWidth: true,
				setHeight: false,
				offsetTop: -20
			})
	});	
}

function findPos(obj){
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        }
        while (obj = obj.offsetParent);
    }
    return [curleft, curtop];
}



