﻿/*jslint devel: true, undef: true, sloppy: true, unparam: true, maxerr: 50, indent: 4 */
/*global jill:false, window:false, isNull:false, document:false, jillPopup:false, ect:false, jWin:false, browser:false, escape:false */

var JILLPOPUP = { YES: "Yes", NO: "No", OK: "OK", CANCEL: "Cancel", RETRY: "Retry", ABORT: "Abort" };

var jDrag = {
	startX: 0,
	startY: 0,
	offsetX: 0,
	offsetY: 0,
	dragObj: null,
	origZIndex: 0,

	mouseUp: function (e) {
		var back = jillPopup.getBack().object;

		if (!isNull(jDrag.dragObj)) {
			document.onmousemove = null;
			document.onselectstart = null;
			
			if (!isNull(back)) {
				back.onmousemove = null;
			}

			jDrag.dragObj.style("zIndex", jDrag.origZIndex);
			jDrag.dragObj.object.ondragstart = null;
			jDrag.dragObj = null;
		}
	},
	mouseMove: function (e) {
		var mouse = jMouse(e).coords();
		if (!isNull(jDrag.dragObj)) {
			jDrag.dragObj.location((jDrag.offsetX + mouse.x - jDrag.startX), (jDrag.offsetY + mouse.y - jDrag.startY));
			if (jDrag.dragObj.object === jillPopup.getTable().object) {
				jillPopup.moved[jillPopup.popupCount - 1] = true;
			}
		}
	},
	mouseDown: function (e) {
		var mouse = jMouse(e),
			coords = mouse.coords(),
			css = mouse.target.className;

		if (mouse.leftButton) {
			if (css.indexOf("draggable") > 0) {
				if (css.indexOf("jPopup") >= 0) {
					jDrag.dragObj = jillPopup.getTable();
				} else {
					jDrag.dragObj = jill(target);
				}

				jDrag.startX = coords.x;
				jDrag.startY = coords.y;
				jDrag.offsetX = jDrag.dragObj.location().left;
				jDrag.offsetY = jDrag.dragObj.location().top;
				jDrag.origZIndex = jDrag.dragObj.style("zIndex");
				jDrag.dragObj.style("zIndex", 10000);
				jDrag.dragObj.object.onmousemove = jDrag.mouseMove;

				jillPopup.getBack().object.onmousemove = jDrag.mouseMove;
				document.onmousemove = jDrag.mouseMove;
				document.body.focus();
				document.onselectstart = function () { return false; };

				jDrag.dragObj.object.ondragstart = function () { return false; };

				return false;
			}
		}
	}
};

var jillPopup = {
	consts: {
		settings: {
			transparency: "#cc000066"
		},
		id: {
			dialog: "jDialog_Popup_{0}_{1}"
		},
		base: "table",
		background: "backGround",
		style: {
			css: "jPopup-{0}",
			back: "backGround",
			table: "table",
			header: "header",
			caption: "caption jPopup-draggable",
			close: "close jPopup-draggable",
			content: "content",
			outer: "outline",
			inner: "border",
			container: "container",
			type: "type",
			message: "message",
			control: "buttons"
		}
	},

	popupCount: 0,

	onComplete: [],

	moved: [],

	// Get the required control from the popup count stack
	getControl: function (pCnt) { var cnt = "." + jillPopup.consts.id.dialog.format(jillPopup.popupCount - 1, pCnt); return jill(cnt); },

	// Get the table control from the popup count stack
	getTable: function () { return jillPopup.getControl(jillPopup.consts.base); },

	// Get the background control from the popup count stack
	getBack: function () { return jillPopup.getControl(jillPopup.consts.background); },

	// Get the top mose popup control table
	getPopup: function () { return jillPopup.getControl(jillPopup.consts.base)[0]; },

	// Center the current popup window
	center: function () {
		var table = null, panel = null;

		if (jillPopup.popupCount > 0) {
			if (jillPopup.moved[jillPopup.popupCount - 1] === false) {
				table = jillPopup.getTable();
				panel = jill(".jjAdminPanel");
				
				table.center(window);
				
				if (!isNull(panel.object)) {
					table.style("top", table.location().top + (panel.size().height / 2));
				}
			}
		}
	},

	// Close the current popup window and return the clicked button message	
	close: function (pAct) {
		var complete, canClose;

		if (jillPopup.popupCount > 0) {
			complete = jillPopup.onComplete[jillPopup.popupCount - 1];
			canClose = (!isNull(complete) ? complete(pAct) : true);
			if (canClose) {
				jillPopup.getTable().location(-999, -999);
				jillPopup.getTable().remove();
				jillPopup.getBack().remove();
				jillPopup.popupCount -= 1;
			}
		}
	},

	closeFrame: function () {
		jillPopup.getTable().remove();
		jillPopup.getBack().remove();
		jillPopup.popupCount -= 1;
	},

	setContent: function (pObj) {
		var cell = this.getTable().find("td>@jPopup-message");

		if (typeof pObj === "string") {
			cell.text(pObj);
		} else {
			cell.insert(pObj);
		}

		this.center();
	},

	setOnComplete: function (pFunc) { jillPopup.onComplete[jillPopup.popupCount - 1] = pFunc; },

	setTabContainer: function (pId) {
		var panel = jill(".jjAdminPanel"),
			tableHeight = jill("." + pId).size().height,
			tabHeight = jill("." + pId).find("td>@tabber-tabs").size().height,
			container = jill("." + pId).find("div>@tabber-tabs-container"),
			maxHeight = jWin.size().view.height;

		if (!isNull(panel)) {
			maxHeight -= panel.size().height;
		}
		maxHeight -= ((tableHeight - tabHeight) + 32);

		container.style("maxHeight", maxHeight);

		if (browser.msie) {
			container.style("padding", "0px 16px 0px 0px");
		}

		if (parseInt(container.style("max-height"), 10) > container.size().height) {
			container.style("overflow", "auto");
		}
	},

	initComplete: function (pObj) { },

	moveFrame: function (pCon, pSize) {
		var frame = jillPopup.getTable(),
			center = function () {
				var panel = jill(".jjAdminPanel"), maxWidth = jWin.size().view.width, maxHeight = jWin.size().view.height;

				if (!isNull(panel)) {
					maxHeight -= panel.size().height;
				}

				frame.style("left", ((maxWidth - frame.size().width) / 2)).style("top", ((maxHeight - frame.size().height) / 2));
			},
			move = function () {
				var location = jill(pCon).location(), size = jill(pCon).size();

				if ((location.top + frame.size().height + size.height + 4) > jWin.size().view.height) {
					location.top -= (frame.size().height + 2);
				} else {
					location.top += (size.height + 4);
				}

				frame.style("left", location.left - 2).style("top", location.top);
			};

		frame.style("width", pSize.doc.width);
		frame.style("height", frame.object.contentWindow.document.body.scrollHeight);

		if (!isNull(pCon)) {
			move();
		} else {
			center();
		}
	},

	initFrame: function (pArgs) {
		var counter = jillPopup.popupCount * 2,
			backId = jillPopup.consts.id.dialog.format(jillPopup.popupCount, "backGround"),
			frameId = jillPopup.consts.id.dialog.format(jillPopup.popupCount, jillPopup.consts.base),
			url = pArgs.url,
			options = pArgs.params,
			control = pArgs.cx,
			id = control.id,
			value = control.value,
			frame = jill("." + frameId);

		if (frame.length === 0) {
			url = url.queryString("cId", id).queryString("cValue", escape(value)) + (options.length > 0 ? "&" : "") + options;

			frame = jill().insert("div").id(backId).css("jPopup-backGround").style("zIndex", counter + 3000).opacity(1)
				.parent().insert("iframe").id(frameId).css("jPopup-iFrame").style("zIndex", counter + 3001).src(url)
				.attr("scrolling", "no");

			jillPopup.popupCount += 1;
		}
	},

	// initialize a new popup window and add it to the popup count stack
	init: function (pArgs) {
		var retObj = {},
			popup,
			iL,
			counter = jillPopup.popupCount * 2,
			maskId = jillPopup.consts.id.dialog.format(jillPopup.popupCount, jillPopup.consts.background),
			tableId = jillPopup.consts.id.dialog.format(jillPopup.popupCount, jillPopup.consts.base),
			cssFormat = jillPopup.consts.style.css,
			noCaption = (pArgs.NoCaption || false),
			isAlert = false,
			div = null,
			as = null;

		popup = jill().insert("div").id(maskId).css("jPopup-backGround").style("zIndex", counter + 3000).opacity(1);

		popup = popup
			.parent().insert(jillPopup.consts.base).css(cssFormat.format(jillPopup.consts.style.table)).id(tableId).style("zIndex", counter + 3001)
			.attr("cellSpacing", "0").attr("title", "JavaScript-Based Popup Window Object").transparency(jillPopup.consts.settings.transparency)
			.event("onmousedown", jDrag.mouseDown);

		if (!noCaption) {
			popup = popup.insert("thead").insert("tr").css(cssFormat.format(jillPopup.consts.style.header)).insert("td")
				.css(cssFormat.format(jillPopup.consts.style.caption)).insert("span").css("jPopup draggable").text((pArgs.Caption || "Alert")).parent("tr").insert("td")
				.css(cssFormat.format(jillPopup.consts.style.close)).insert("a").attr("title", "Close this Popup").event("onclick", "jillPopup.close('Cancel')")
				.hrefJs("void(0);").parent("table");
		}

		popup = popup.insert("tfoot").insert("tr").insert("td").attr("colSpan", "2").css(cssFormat.format(jillPopup.consts.style.content)).insert("div")
			.css(cssFormat.format(jillPopup.consts.style.outer)).insert("div").css(cssFormat.format(jillPopup.consts.style.inner)).insert("table")
			.css(cssFormat.format(jillPopup.consts.style.container)).insert("thead").insert("tr");

		if (!isNull(pArgs.Style)) {
			isAlert = true;

			popup = popup.insert("td").css(cssFormat.format(jillPopup.consts.style.type) + " " + cssFormat.format(pArgs.Style)).insert("span").text("&#160;").parent("tr")
				.insert("td").style("padding", "7px");
		} else {
			popup = popup.insert("td");
		}

		popup = popup.css(cssFormat.format(jillPopup.consts.style.message)).text(pArgs.Message).parent("table");

		if (!isNull(pArgs.Buttons) && pArgs.Buttons.length > 0) {
			popup = popup.insert("tfoot").insert("tr").insert("td").attr("colSpan", "2").css(cssFormat.format(jillPopup.consts.style.control));
			
			if (isAlert) {
				popup.style("padding", "11px 11px 11px 56px");
			}

			for (iL = 0; iL < pArgs.Buttons.length; iL += 1) {
				popup.insert("a").css("theme-button").text(pArgs.Buttons[iL]).event("onclick", "jillPopup.close('" + pArgs.Buttons[iL] + "')");
			}

			popup = popup.parent(jillPopup.consts.base);
		}

		jillPopup.setTabContainer(tableId);

		div = jill("." + tableId).find("div>@jPopup-buttons");
		as = div.find("a");

		if (jill("." + tableId).find("div>@jPopup-buttons>a").object.length === 0) {
			jill("." + tableId).find("div>@jPopup-buttons").hide();
		}

		jillPopup.onComplete[jillPopup.popupCount] = pArgs.OnComplete;
		jillPopup.moved[jillPopup.popupCount] = false;
		jillPopup.popupCount += 1;
		jillPopup.initComplete(jill("." + tableId)[0]);
		jillPopup.center();

		return retObj;
	}
},

	jPopup = function (pArgs) {
		return jillPopup.init(pArgs);
	},

	jDialog = {
		AreYouSure: function (pMsg, onCompl) {
			var onComplete = function (pRes) {
				onCompl(pRes);
				return true;
			};

			jillPopup.init({ Message: pMsg + "<br/>Are you Sure?", Buttons: ["Yes", "No"], Style: "Warning", OnComplete: onComplete });
		},

		context: function (pArgs) {
			jillPopup.initFrame(pArgs);
		}
	};

jWin.onLoad(function () {
	document.onmouseup = jDrag.mouseUp;
});
