/* 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').css('z-index','24000');
	}
	if ($('#yui-uploader-panel_mask') != null) {
		$('#yui-uploader-panel_mask').css('z-index','24000');
	}
	if ($('#yui-imagepicker-panel_mask') != null) {
		$('#yui-imagepicker-panel_mask').css('z-index','24000');
	}

	if ($('#yui-imagepicker-panel_c') != null) {
		$('#yui-imagepicker-panel_c').css('z-index','450000');
	}
	if ($('#yui-uploader-panel_c') != null) {
		$('#yui-uploader-panel_c').css('z-index','460000');
	}
	if ($('#yui-dialog-texteditor_c') != null) {
		$('#yui-dialog-texteditor_c').css('z-index','25000');
	}
}

function showPleaseWait() {

}

function hidePleaseWait() {

}

function qwFetchImages(path, cb) {
	if (path != "" && path != null) {
		url = "/fetchimages/" + path + "/";
	} else {
		url = "/fetchimages/";
	}

	$.ajax(url, {
		type:'post',
		success: function(transport) {
			var files = $.evalJSON(transport);
			cb(files);
		}
	});
}

function qwCommit(op, value) {
	op.value = value;
	url = "/set/" + op.name + "/";
	$.ajax(url, {
		type:'post',
		data: {
			value: value
		}
	});
}

function qwSet(op, value) {

	try {
		target = op.target;
		if(op.target.indexOf("[target]") >= 0) {
			if($.string(op.scope).startsWith('$')) {
				var scope = op.scope.replace(/\$\(/,'').replace(/\)/,'');
				var attr =  $('#' + scope).attr('id');

				if (typeof attr !== 'undefined' && attr !== false) {
					target = attr;
				}
			} else {
				target = op.target.replace("[target]", $('#' + op.scope).attr('id'));
			}

		}

		var scope = op.scope;

		if ($.string(op.scope).startsWith('$') == false && op.scope != "document") {
			$('#' + scope).css(op.target, value);
			return;
		} else {
			scope = op.scope.replace(/\$\(/,'').replace(/\)/,'');
			if (op.scope == "document") {
				scope = "body";
			}
			$(scope).css(op.target, value);
			return;
		}
	} catch(e) {
		return;
	}
}

function qwSetImage(op, value) {

	target = op.target.replace("[target]", $('#' + op.scope).attr('id'));

	scope = op.scope;

	var imgvalue = "url('" + value + "')";
	if ($.string(op.scope).startsWith('$') == false && op.scope != "document") {
		$('#' + scope).css(op.target, imgvalue);
		return;
	} else {
		scope = op.scope.replace(/\$\(/,'').replace(/\)/,'');
		if (op.scope == "document") {
			scope = "body";
		}
		$(scope).css(op.target, imgvalue);
		return;
	}
}

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.data().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.data('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.parent();
	if (u.hasClass('qwapplet')) {
		e = u;
	}

	if ($(btn).data().overlay == null) {
		var overlay = $("<div/>");
		overlay.attr('class','qwOverlay');
		overlay.css('display','none');
		overlay.css('position','absolute');
		overlay.offset(e.offset());
		overlay.width(e.width());
		overlay.height(e.height());

		$(document.documentElement).append(overlay);
		$(btn).data('overlay',overlay);
		overlay.fadeTo(0,0);
		overlay.fadeTo("slow",.3);
	} else {
		var overlay = $(btn).data().overlay;
		overlay.css('left',e.offset().left);
		overlay.css('top',e.offset().top);
		overlay.width(e.width());
		overlay.height(e.height());
		overlay.fadeTo(0,0);
		overlay.fadeTo("slow",.3);
	}

}

function dimButton(btn, op) {

	if ($(btn).data().overlay != null) {
		$(btn).data().overlay.fadeTo("slow",0);
		$(btn).data().overlay.hide();
	}
}

function toggleButtons() {
	qwContainers.each( function(i,b) {
		b.toggle()
	});
}

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

function showButtons() {
	qwContainers.each( function(i,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 (typeof(op.choices) != 'string') {
		if (op.choices.color != null) {
			doColorDialog(op);
			return;
		}

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

}

var applets = $A()

function renderApplets() {
	$('div.qwOverlay').hide();
	$('div.qwOpContainer').remove();
	applets.each( function(i,a) {
		renderApplet(a)
	});
}

function renderApplet(configop) {

	// GET ELEMENT

	var e = $('#' + configop.scope);
	if (e.size() == 0) {
		return;
	}

	u = e.parent();

	if (u.hasClass('qwapplet')) {
		e = u;
	}

	var ops = $A(configop.ops);

	// CREATE BUTTON CONTAINER

	var opContainer = $("<div id='qwOpContainer" + e.attr('id') + "' class='qwOpContainer' ></div>");
	e.data('qwOpContainer',opContainer);

	$(document.body).append(opContainer);

	var width = e.width();
	opContainer.width(width);
	offset = e.offset();
	offset.top -= 24;

	opContainer.offset(offset);

	width = opContainer.width();
	minWidth = (ops.length + 6) * 24;

	if (width < minWidth) {
		opContainer.width(minWidth);
	}

	qwContainers.push(opContainer);

	// CREATE BUTTONS

	ops.each( function(i,op) {

		op.scope = configop.scope;
		op.applet = configop.applet;
		var btn;
		if (op.icon) {
			btn = $('<img/>');
			btn.attr('id',"opBtn" + configop.scope + op.title);
			btn.attr('src',"/media/images/" + op.icon);
			btn.attr('class',"qwIconButton");
			btn.attr('title',op.title);
			btn.attr('width',18);
			btn.attr('height',18);
		} else {
			btn = $('<span/>');
			btn.attr('id',"opBtn" + configop.scope + op.title);
			btn.attr('class',"qwButton");

			btn.html(op.title);
		}
		opContainer.append(btn);
		qwButtons.push(btn);

		btn.data('op',op);
		btn.click( function(e) {
			onButtonClick($(e.currentTarget).data().op);
			return false;
		});
		btn.mouseover( function(e) {
			lightButton(e.currentTarget, $(e.currentTarget).data().op);
			return false;
		});
		btn.mouseout( function(e) {
			dimButton(e.currentTarget, $(e.currentTarget).data().op);
			return false;
		});
	});
	
	// ADD APPEARANCE

	var op = {
		title: "Appearance"
	}
	op.choices = {
		parameters: {
			_pageview: 'appletappearance',
			appletId: configop.applet,
			sections: arrayToString(sections)
		}
	}
	op.scope = configop.scope;
	op.applet = -1;
	var btn = $('<img/>');
	btn.attr('id',"opBtn" + configop.scope + op.title);
	btn.attr('src',"/media/images/appearance.png");
	btn.attr('class',"qwIconButton");
	btn.attr('title',op.title);
	btn.attr('width',18);
	btn.attr('height',18);
	
	opContainer.append(btn);

	btn.data('op',op);
	btn.click( function(e) {
		onButtonClick($(e.currentTarget).data().op);
		return false;
	});
	btn.mouseover( function(e) {
		lightButton(e.currentTarget, $(e.currentTarget).data().op);
		return false;
	});
	btn.mouseout( function(e) {
		dimButton(e.currentTarget, $(e.currentTarget).data().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 = $('<img/>');
	btn.attr('id',"opBtn" + configop.scope + op.title);
	btn.attr('src',"/media/images/higher.png");
	btn.attr('class',"qwIconButton");
	btn.attr('title',op.title);
	btn.attr('width',18);
	btn.attr('height',18);
	
	opContainer.append(btn);

	btn.data('op',op);
	btn.click( function(e) {
		onButtonClick($(e.currentTarget).data().op);
		return false;
	});
	btn.mouseover( function(e) {
		lightButton(e.currentTarget, $(e.currentTarget).data().op);
		return false;
	});
	btn.mouseout( function(e) {
		dimButton(e.currentTarget, $(e.currentTarget).data().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 = $('<img/>');
	btn.attr('id',"opBtn" + configop.scope + op.title);
	btn.attr('src',"/media/images/lower.png");
	btn.attr('class',"qwIconButton");
	btn.attr('title',op.title);
	btn.attr('width',18);
	btn.attr('height',18);
	
	opContainer.append(btn);

	btn.data('op',op);
	btn.click( function(e) {
		onButtonClick($(e.currentTarget).data().op);
		return false;
	});
	btn.mouseover( function(e) {
		lightButton(e.currentTarget, $(e.currentTarget).data().op);
		return false;
	});
	btn.mouseout( function(e) {
		dimButton(e.currentTarget, $(e.currentTarget).data().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 = $('<img/>');
	btn.attr('id',"opBtn" + configop.scope + op.title);
	btn.attr('src',"/media/images/delete.png");
	btn.attr('class',"qwIconButton");
	btn.attr('title',op.title);
	btn.attr('width',18);
	btn.attr('height',18);
	
	opContainer.append(btn);

	btn.data('op',op);
	btn.click( function(e) {
		onButtonClick($(e.currentTarget).data().op);
		return false;
	});
	btn.mouseover( function(e) {
		lightButton(e.currentTarget, $(e.currentTarget).data().op);
		return false;
	});
	btn.mouseout( function(e) {
		dimButton(e.currentTarget, $(e.currentTarget).data().op);
		return false;
	});
	qwButtons.push(btn);
	
	// ADD COPY

	op = {
		title: "Copy"
	}
	op.choices = {
		parameters: {
			_pageview: 'copyapplet',
			appletId: configop.applet
		},
		confirm: 'Are you sure you wish to copy this content?'

	}
	op.scope = configop.scope;
	op.applet = -1;
	var btn = $('<img/>');
	btn.attr('id',"opBtn" + configop.scope + op.title);
	btn.attr('src',"/media/images/copy.png");
	btn.attr('class',"qwIconButton");
	btn.attr('title',op.title);
	btn.attr('width',18);
	btn.attr('height',18);
	
	opContainer.append(btn);

	btn.data('op',op);
	btn.click( function(e) {
		onButtonClick($(e.currentTarget).data().op);
		return false;
	});
	btn.mouseover( function(e) {
		lightButton(e.currentTarget, $(e.currentTarget).data().op);
		return false;
	});
	btn.mouseout( function(e) {
		dimButton(e.currentTarget, $(e.currentTarget).data().op);
		return false;
	});
	qwButtons.push(btn);


	// ADD SEQUENCE

	var seq = $("<span/>");
	seq.attr("style","position:relative;top:2px;float:right;display:block;height:18px;margin-top:0;font-size:12px;color:#ffffff");
	seq.html("(" + configop.sequence + ")&nbsp;");

	opContainer.append(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;
	var add = true;
	applets.each(function(i,c){
		if(c.scope == configop.scope)
		{
			add = false;
		}
	});
	if(add)
	{
		applets.push(configop);
	}

}

var sections = $A()

function addSection(section) {
	sections.push(section);
	sections.sort( function(a, b) {
		var compA = a.toUpperCase();
		var compB = b.toUpperCase();
		var ret = (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
		if(a.toUpperCase() == 'MAIN') {
			ret = -1;
		}
		return ret;
	});
}

function createSlug(source, target) {
	var url = $("#" + source).val();
	url = $.string(url).gsub(" ", "-").str;
	url = $.string(url).gsub("_", "-").str;
	url = $.string(url).gsub(",", "-").str;
	url = $.string(url).gsub("&", "-").str;
	url = $.string(url).gsub("!", "-").str;
	url = $.string(url).gsub("@", "-").str;
	url = $.string(url).gsub("#", "-").str;
	url = $.string(url).gsub("$", "-").str;
	url = $.string(url).gsub("%", "-").str;
	url = $.string(url).gsub("^", "-").str;
	url = $.string(url).gsub("*", "-").str;
	url = url.toLowerCase();
	$("#" + target).val(url);
}

function arrayToString(array) {
	var res = "[";
	array.each( function(i,v) {
		res += '"' + v + '",';
	});
	res += "]";
	return res;
}

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

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

function refreshApplet(appletId, params) {
	if (!params) {
		$('#qwcontent_id' + appletId).load('/ajax/' + appletId + '/');
	} else {
		$('#qwcontent_id' + appletId).load('/ajax/' + appletId + '/' + params);
	}
}

function removeApplet(appletId) {
	$("#qwapplet_id" + appletId).remove();
	$("#qwOpContainerqwapplet_id" + appletId).remove();
	$.jGrowl("Applet removed from page.", {
		theme:'success'
	});
	renderApplets();
}

function refreshSection(section,message) {
	var asection = $("#marker"+section);
	var psection = $(asection.parent());
	
	var page = asection.attr('href');
	
	psection.load('/fetchsection/' + page + '/' + section + '/', function() {
			renderApplets();
			if(message) {
				$.jGrowl(message);
			}
		});
}

function updateControlPanels() {

	applets.each( function(i,configop) {

		var e = $('#' + configop.scope);
		
		if (e == null || e.size() == 0) {
			return;
		}
		var u = e.parent();
		if (u.hasClass('qwapplet')) {
			e = u;
		}

		var opContainer = e.data().qwOpContainer;
		var width = e.width();
		opContainer.width(width);
		offset = e.offset();
		offset.top -= 24;

		opContainer.offset(offset);

	});
}

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

function addLayoutItem(op,title) {
	siteitems.push({
		text: title,
		onclick: {
			fn: function() {
				onOpPick(op);
			}
		}
	});
}
