﻿/*jslint plusplus: true, devel: true, undef: true, sloppy: true, unparam: true, maxerr: 50, indent: 4 */
/*global jill:false, jWin:false, jDialog:false, jCore:false, jPopup:false, jillPopup:false, document:false, clearInterval:false, setInterval:false, setTimeout:false, isNull:false, window:false */

var jForm = {
	// trigger a click event on the desired control
	click: function (pId) {
		"use strict";
		var con = jill(jForm.getControlId(pId)).object;
		if (!isNull(con)) {
			if (con.click) {
				con.click();
			} else {
				con.onclick();
			}
		}
	},

	// set the focus on the desired control
	focus: function (pId) {
		"use strict";
		var con;

		if (isNull(pId)) {
			return;
		} else {
			con = jill(jForm.getControlId(pId)).object;
			if (!isNull(con)) {
				con.focus();
				try {
					con.select();
				} catch (e) {
				}
			}
		}
	},

	// get the currently pressed key code
	getKeyPress: function (e) {
		"use strict";
		return (window.event ? window.event.keyCode : e.keyCode);
	},

	// get the control's id as a Jill-compliant id (prefix of ".")
	getControlId: function (pId) {
		if (typeof pId === "string") {
			if (pId.indexOf(".") === 0) {
				return pId;
			} else {
				return "." + pId;
			}
		} else {
			return pId;
		}
	},

	// hide the desired form control
	hideControl: function (pId) {
		"use strict";
		if (isNull(pId)) {
			return;
		} else {
			jill(jForm.getControlId(pId)).parent("div").hide();
		}
	},

	// show the deisred form control
	showControl: function (pId) {
		"use strict";
		if (isNull(pId)) {
			return;
		} else {
			jill(jForm.getControlId(pId)).parent("div").show();
		}
	},

	// Gets a value indicating whether the ENTER key has been pressed
	onKeyEnter: function (e, func) {
		"use strict";
		if (jForm.getKeyPress(e) === 13) {
			func();
			return false;
		} else {
			return true;
		}
	},

	// load and show a popup dialog
	popup: function (pArgs) {
		var popup = function (pUrl) {
				var control = jCore.form.post(pUrl, "");

				jPopup({ Message: jCore.form.parse(control), Caption: pArgs.Caption });
				jCore.form.runEvents();

				if (pArgs.OnComplete) {
					jillPopup.setOnComplete(pArgs.OnComplete);
				}
			},
			url = pArgs.Url;

		if (isNull(url)) { url = pArgs.url; }
		
		if (/popup/i.test(url)) {
			popup(pArgs.Url);
		} else if (/dialog/i.test(url)) {
			pArgs.cx.disabled = true;
			jDialog.context(pArgs);
		} else {
			jWin.href(url + jWin.returnUrl());
		}
		return false;
	},

	post2Frame: function (pTarget, pArgument, pUrl, pOnCompl) {
		var frameName = pUrl.replace("Frame:", ""),
			frameId = "." + frameName.replace(/\$/g, "_"),
			frame = null,
			origTarget = document.forms[0].target,
			origAction = document.forms[0].action,
			origParent = null,
			interval = null,
			reset = function () {
				frame = jill(frameId).remove(true).object;
				origParent.insert(frame);
				jill(frameId).hide();
				return true;
			},
			getFrame = function () {
				var obj = null;
				try {
					obj = jill(frameId).object.contentWindow.document.body;
				} catch (e) {
				}
				return obj;
			},
			scrollFrame = function () {
				var cntBody = getFrame();

				if (!isNull(cntBody)) {
					cntBody.scrollTop = cntBody.scrollHeight;
				}
			},
			completed = function () {
				clearInterval(interval);
				scrollFrame();
				document.forms[0].action = origAction;
				document.forms[0].target = origTarget;

				if (pOnCompl) {
					pOnCompl();
				}
			},
			init = function () {
				jPopup({ Message: "", OnComplete: reset });
				jill(".__EVENTTARGET").object.value = pTarget;
				jill(".__EVENTARGUMENT").object.value = pArgument;
				jill(frameId).event("onload", completed).show();

				origParent = jill(frameId).parent();
				frame = jill(frameId).remove(true).object;
				jillPopup.setContent(frame);
			},
			peek = function () {
				scrollFrame();
			};

		init();
		interval = setInterval(peek, 100);

		document.forms[0].action = jWin.getUrl(null);
		document.forms[0].target = frameName;
		document.forms[0].submit();
	},

	// Post the event target, event argument to the desired url
	post: function (pTarget, pArgument, pControl, pUrl, pOnComp) {
		var formData = "",
			onComplete = function (pRes) {
				pRes = jCore.form.parse(pRes);
				if (pOnComp) {
					pOnComp(pRes);
				}
				jCore.form.runEvents();
			};

		pUrl = jWin.getUrl(pUrl);

		if (pUrl.indexOf("Frame:") === 0) {
			formData = jCore.form.getForm(pTarget, pArgument, document.forms[0]);
			jForm.post2Frame(pTarget, pArgument, pUrl, pOnComp);
		} else {	
			formData = jCore.form.getForm(pTarget, pArgument, pControl);
			jCore.form.post(pUrl, formData, null, onComplete);
		}

		return false;
	},

	postClick: function (pCon, pArgument, pUrl) {
		var form = pCon.name.replace(/\$Module\$Item_\d{1,6}\$.*$/, ""),
			formData = jCore.form.getForm(pCon.name, pArgument, form),
			onCompl = function (pRes) { jWin.href(pUrl); };
			
		jCore.form.post(jWin.url, formData, null, onCompl);

		return false;
	}
};

jForm.upload = {
	id: "",
	argument: "",
	complete: null,
	originalTarget: null,
	originalUrl: null,
	newUrl: "",
	interval: null,
	frameName: null,
	form: null,

	// Return the current content of the uploader's iFrame object
	getFrameContent: function () {
		try {
			return jill(jForm.upload.id + "_Frame").object.contentWindow.document.body.innerHTML;
		} catch (e) {
			return "";
		}
	},

	// Initialize the uploader
	init: function (pId) {
		var parent = jill("." + pId);

		jForm.upload.id = "." + pId;

		parent.style("height", 40).style("overflow", "hidden");
		parent.find("div").inx(0).style("height", 40);
		parent.find("div").inx(1).style("height", 40).style("position", "relative").style("top", -40);

		jill(jForm.upload.id + "_FakeFile").style("width", 400).attr("readonly", "true").style("backgroundImage", "url('/Includes/Images/Jill/uploadProgress.gif')")
			.style("backgroundRepeat", "no-repeat").style("backgroundPosition", "-400px 0px");
		jill(jForm.upload.id + "_Frame").hide();
		jill(jForm.upload.id + "_File").style("width", 180).style("fontSize", "22px").opacity(1).object.onchange = function () {
			jill(jForm.upload.id + "_FakeFile").object.value = this.value;
		};

		if (!isNull(document.forms[pId + "_Form"])) {
			jForm.upload.form = document.forms[pId + "_Form"];
		}
		if (jill(".__JILLEVENT").length === 0) {
			parent.insert("input").attr("type", "hidden").attr("name", "__JILLEVENT").id("__JILLEVENT");
		}
	},

	// Reset the uploader
	onFinished: function () {
		jill(jForm.upload.id + "_FakeFile").style("backgroundPosition", "-400px 0px");
	},

	// Handle the event when the uploader is reporting a sucessfully uploaded file
	onComplete: function () {
		clearInterval(jForm.upload.interval);
		jForm.upload.interval = null;

		if (jForm.upload.form === null) {
			document.forms[0].action = jForm.upload.originalUrl;
			document.forms[0].target = jForm.upload.originalTarget;
		} else {
			jill(".__EVENTTARGET").remove();
			jill(".__EVENTARGUMENT").remove();

			jill("div").inx(0)
				.insert("input").attr("type", "hidden").attr("name", "__EVENTTARGET").id("__EVENTTARGET").parent()
				.insert("input").attr("type", "hidden").attr("name", "__EVENTARGUMENT").id("__EVENTARGUMENT");
		}

		jForm.upload.originalTarget = null;
		jForm.upload.originalUrl = null;

		jill(jForm.upload.id + "_FakeFile").style("backgroundPosition", "0px 0px");

		if (!isNull(jForm.upload.complete)) {
			jForm.upload.complete();
		}

		setTimeout(jForm.upload.onFinished, 500);
	},

	// Peek at the uploader's iFrame content to see if the file is uploading, done, or failed
	peek: function () {
		var res = jForm.upload.getFrameContent(), progress, current, total, percent;

		if (res.length > 0) {
			if (res.indexOf("<") >= 0) {
				jCore.form.parse(res);
				jForm.upload.onComplete();
			} else if (res.indexOf(";") > 0) {
				progress = res.split(";");
				total = progress[0];
				current = progress[progress.length - 2];

				if (current === "Done") {
					jForm.upload.onComplete();
				} else {
					percent = (parseInt(current, 10) / parseInt(total, 10));
					jill(jForm.upload.id + "_FakeFile").style("backgroundPosition", "-" + (400 - (400 * percent)) + "px 0px");
				}
			} else {
				jForm.upload.onComplete();
			}
		}
	},

	// Post the uploader's file to the iFrame object by submitting the current form
	post: function () {
		var submit = function (pForm) {
				var url = jForm.upload.newUrl;

				jill(".__JILLEVENT").object.value = "JillPostBack";
				jill(".__EVENTTARGET").object.value = jForm.upload.id.substr(1) + "Upload";

				jForm.upload.interval = setInterval(jForm.upload.peek, 5);

				pForm.action = url;
				pForm.submit();
			};

		jForm.upload.frameName = jill(jForm.upload.id + "_Frame").attr("name");

		if (jForm.upload.form === null) {
			if (isNull(jForm.upload.originalUrl)) {
				jForm.upload.originalUrl = document.forms[0].action;
			}
			if (isNull(jForm.upload.originalTarget)) {
				jForm.upload.originalTarget = document.forms[0].target;
			}

			document.forms[0].target = jForm.upload.frameName;

			submit(document.forms[0]);

		} else {
			jill(".__EVENTTARGET").remove();
			jill(".__EVENTARGUMENT").remove();

			jill(jForm.upload.id)
				.insert("input").attr("type", "hidden").attr("name", "__EVENTTARGET").id("__EVENTTARGET").parent()
				.insert("input").attr("type", "hidden").attr("name", "__EVENTARGUMENT").id("__EVENTARGUMENT");

			submit(jForm.upload.form);
		}
	},

	// Upload the selected file
	upload: function (pUrl, pOnComp) {
		jForm.upload.complete = pOnComp;
		jForm.upload.newUrl = pUrl || jWin.url;

		setTimeout(jForm.upload.post, 10);

		return false;
	}
};
