﻿/*jslint devel: true, undef: true, sloppy: true, unparam: true, maxerr: 50, indent: 4 */
/*global document: false, jCore: false, jill:false, JILL:false, JILLPOPUP: false, jWin: false, jHref: false, jForm: false, jDialog: false, jillPopup: false, window:false, isNull:false */

var jControls = {
		enabled: function (pId, pEnabled) {
			jill("." + pId).parent("div").css(" disabled", (pEnabled ? JILL.REMOVE : JILL.APPEND));
			jill("." + pId).enabled(pEnabled);
		},
		// hide the control's warning control
		hideWarning: function (pId) {
			jill("." + pId + "_Warning").css(" hidden", JILL.APPEND);
		},
		// show the control's warning control with the desired message 
		showWarning: function (pId, pMsg, pSuccess) {
			pSuccess = (isNull(pSuccess) ? JILL.FAIL : pSuccess);
			jill("." + pId + "_Warning").find("td>@warning-message").text(pMsg);
			jill("." + pId + "_Warning").css("warning" + (pSuccess === JILL.SUCCESS ? " success" : ""));
		}
	},
	JHREF = {
		EXTERNAL: 1,
		LOCALLINK: 2,
		LOCALDOCUMENT: 3,
		NEWLOCALURL: 4
	};

jControls.incText = function (pId, pMin, pMax, pInc) {
	var retObj = {},
		getInput = function () {
			return jill("." + pId).object;
		};

	pMin = pMin || 0;
	pMax = pMax || 10000;
	pInc = pInc || 1;

	retObj.down = function () {
		var value = parseInt(getInput().value, 10);

		if ((value - pInc) >= pMin) {
			getInput().value = value - pInc;
		}
	};

	retObj.up = function () {
		var value = parseInt(getInput().value, 10);

		if ((value + pInc) <= pMax) {
			getInput().value = value + pInc;
		}
	};

	return retObj;
};


jControls.listView = function (pId) {
	var retObj = {},
		getValue = function () {
			var val = "," + jill("." + pId + "_Selected").object.value + ","; return val.replace(",,", ",");
		},
		getRow = function (pRowId) {
			var options = jill("." + pId).find("table>@listview-data>tr"), i;

			for (i = 0; i < options.length; i += 1) {
				if (options.inx(i).attr("data-value") === pRowId) {
					return options.inx(i);
				}
			}

			return null;
		},
		setValue = function (pVal) {
			pVal = pVal.substring(1, pVal.length - 1); if (pVal === ",") { pVal = ""; } jill("." + pId + "_Selected").object.value = pVal;
		},
		add = function (pVal) {
			var val = getValue();

			if (val.indexOf("," + pVal + ",") < 0) { val += pVal + ","; }

			setValue(val);
		},
		remove = function (pVal) {
			var val = getValue();

			if (val.indexOf("," + pVal + ",") >= 0) { val = val.replace("," + pVal + ",", ","); }

			setValue(val);
		},
		clearSelected = function (pVal) {
			var options = jill("." + pId).find("table>@listview-data>tr"), i, val;

			for (i = 0; i < options.length; i += 1) {
				if (options.inx(i).object.className.indexOf(" selected") >= 0) {
					val = options.inx(i).attr("data-value");
					options.inx(i).css(" selected", JILL.REMOVE);
					remove(val);
				}
			}
		};

	// Initialize the list view control
	retObj.init = function () {
		var dCells = jill("." + pId).find("table>@listview-data>tr").inx(0).find("td"),
			hCells = jill("." + pId).find("table>@listview-header>tr").inx(0).find("td"),
			container = jill("." + pId).find("div>@listview-data"),
			data = jill("." + pId).find("table>@listview-data"),
			header = jill("." + pId).find("table>@listview-header"),
			parent = jill("." + pId).parent("table"),
			isHidden = (parent.object.style["display"] === "none"),
			isOverflowed = false,
			i,
			max,
			full = 0;

		if (dCells.length < 2 || isHidden) { return; }

		container.style("height", jill("." + pId).size().height - (header.size().height + 5));
		isOverflowed = (container.size().height < data.size().height);

		for (i = 0; i < hCells.length; i += 1) {
			max = Math.max(hCells.inx(i).size().width, dCells.inx(i).size().width);
			hCells.inx(i).style("width", max);
			dCells.inx(i).style("width", (i === (hCells.length - 1) && isOverflowed ? max - 16 : max));
			full += max;
		}

		header.style("width", full);
		data.style("width", (isOverflowed ? full - 16 : full));
	};

	retObj.addRow = function (pNewId, pCells, pOnClick) {
		var row = jill("." + pId).find("table>@listview-data").insert("tr"), i;

		for (i = 0; i < pCells.length; i += 1) {
			row.insert("td").text(pCells[i]);
		}

		row.event("onclick", "jControls.listView('" + pId + "').select(this);" + (pOnClick || "")).attr("data-value", pNewId);

		this.init();
	};

	// Handles the event when a user clicks on one of the list view item rows
	retObj.select = function (pObj, pMultiple) {
		var css = " selected", selected = pObj.className.indexOf(css) >= 0, val = jill(pObj).attr("data-value");

		if (!pMultiple) {
			clearSelected();
			selected = false;
		}

		jill(pObj).css(css, (selected ? JILL.REMOVE : JILL.APPEND));

		if (selected) { remove(val); } else { add(val); }
	};

	// Get the current comma seperated list of selected items
	retObj.selected = function () { return jill("." + pId + "_Selected").object.value; };

	// Set the items matching the pids as selected
	retObj.setSelected = function (pIds) {
		var ids = pIds.split(","), i, row;

		clearSelected();

		for (i = 0; i < ids.length; i += 1) {
			row = getRow(ids[i]); if (!isNull(row)) { row.css(" selected", JILL.APPEND); }
		}

		jill("." + pId + "_Selected").object.value = pIds;
	};

	// Update the list view control by removing the submitted ids
	retObj.update = function (pIds) {
		var removeIds = function () {
				var ids = pIds.split(","), row, i;

				for (i = 0; i < ids.length; i += 1) {
					row = getRow(ids[i]);
					if (!isNull(row)) {
						row.remove();
						remove(ids[i]);
					}
				}
			},
			updateRow = function () {
				var row = getRow(pIds[0]), i;
				if (!isNull(row)) {
					for (i = 1; i < pIds.length; i += 1) {
						row.find("td").inx(i - 1).text(pIds[i]);
					}
				}
			};

		if (typeof pIds === "string") { removeIds(); } else { updateRow(); }
	};

	return retObj;
};

jControls.modules = {
	init: function (pId) {
		var retObj = {},
			getModuleControl = function (sub) {
				return jill(".Theme_Container_" + pId + "_" + sub);
			};

		retObj.Title = getModuleControl("Title");
		retObj.Content = getModuleControl("Content");
		retObj.Options = getModuleControl("Options");
		retObj.Module = jill(".Theme_Container_" + pId);
		retObj.setContent = function (pAlign, opac) {
			this.Content.css("theme-module-content " + pAlign); //.opacity(opac);
		};
		retObj.setTitle = function (pTitle, pClass) {
			this.Title.text(pTitle).css("theme-module-title " + pClass);
		};
		retObj.setWrapper = function (pWidth, pClass) {
		};
		return retObj;
	},

	addCss: function (pUrl) {
		var links = document.getElementsByTagName("link"),
			i,
			newLink;

		for (i = 0; i < links.lenght; i += 1) {
			if (jill(links[i]).attr("href") === pUrl) {
				return;
			}
		}

		newLink = jill(document.getElementsByTagName("head")[0]).insert("link", 0);
		newLink.attr("href", pUrl).attr("rel", "stylesheet").attr("type", "text/css");
	},

	// Moves the module to another location within the current page
	move: function (pId, pType, pWhere) {
		var mod = jControls.modules.init(pId);

		if (/Up|Down/i.test(pType)) {
			mod.Module.move(pType === "Up" ? JILL.UP : JILL.DOWN);
		} else {
			mod.Module.remove(); jill(".Theme_" + pWhere + "Panel").insert(mod.Module.object, 0);
		}
	},

	// Removes the current module from the DOM
	remove: function (pId) {
		var onComplete = function (pRes) {
				if (pRes === "SUCCESS") {
					var mod = jControls.modules.init(pId);

					mod.Module.remove();
					jControls.admin.recycler.fill();
				}
			},
			onConfirm = function (pRes) {
				if (pRes === JILLPOPUP.YES) {
					jForm.post("Theme$Container_" + pId + "$Menu$DeleteModule", "", "Theme$Container_" + pId, jWin.url, onComplete);
				}
			};

		jDialog.AreYouSure("You are about to delete the module", onConfirm);

		return false;
	},
	// Remove the module's item
	removeItem: function (pModId, pId) {
		var onComplete = function (pRes) {
				if (pRes === "SUCCESS") {
					jill(".Theme_Container_" + pModId + "_Module_Item_" + pId).remove();
				} else {
					alert(pRes);
				}
			},
			onConfirm = function (pRes) {
				if (pRes === JILLPOPUP.YES) {
					jForm.post("Theme$Container_" + pModId + "$Module$Item_" + pId + "$itemRemove", pId, "Theme$Container_" + pModId, jWin.url, onComplete);
				}
			};
		
		jDialog.AreYouSure("You are about to delete the item", onConfirm);

		return false;
	},

	// Updates the modules base setings (title, style, alignment, width, visibility)
	updateSettings: function (pArgs) {
		var opac = (pArgs.Visible ? 100 : 30),
			mod = jControls.modules.init(pArgs.Id);

		pArgs.Width += (pArgs.Width.length > 0 ? "px" : "");
		mod.setContent(pArgs.Align + (pArgs.Visible ? "" : " Invisible"), opac);
		mod.setTitle(pArgs.Title, pArgs.TitleClass);
		mod.setWrapper(pArgs.Width, pArgs.ModClass);
	}
};

// Lineage Control object to manipulate the lineage control(s)
jControls.lineage = function (pId) {
	var retObj = {},
		list = jill("." + pId + "_ItemList"),
		selectedItem = list.find("div>@*selected"),
		getAttr = function (pItem) {
			var id = "",
				jCon = null,
				getInput = function (pName) {
					return jill("." + id + "_" + pName).object;
				};

			if (isNull(pItem)) {
				id = selectedItem.id();
				jCon = selectedItem;
			} else if (typeof pItem === "string") {
				id = "." + pId + "_Item_" + pItem;
				jCon = jill(id);
			} else {
				id = pItem.id();
				jCon = pItem;
			}

			return {
				control: jCon,
				span: jCon.find("span"),
				order: getInput("Order"),
				parent: getInput("Parent"),
				id: getInput("Id"),
				upSib: jCon.sibling(JILL.UP),
				downSib: jCon.sibling(JILL.DOWN)
			};
		},
		getIndent = function (pText) {
			return (pText.span.text().split("...").length - 1);
		},
		validate = function (pItem) {
			var sibling = getAttr(pItem.upSib),
				siblingIndent = 0,
				indent = getIndent(pItem),
				setInxRemoval = function (pNum) {
					var i,
						inx = "";

					for (i = 0; i < pNum; i += 1) {
						inx += "...";
					}

					if (inx.length > 0) {
						pItem.span.text(pItem.span.text().replace(inx, ""));
					}

					return pNum;
				};

			if (!isNull(pItem.upSib)) {
				siblingIndent = getIndent(sibling);

				if (indent > (siblingIndent + 1)) {
					indent -= setInxRemoval(indent - (siblingIndent + 1));
				}

				if (indent === 0) {
					pItem.parent.value = "0";
				} else if (indent === siblingIndent) {
					pItem.parent.value = sibling.parent.value;
				} else if (indent > siblingIndent) {
					pItem.parent.value = sibling.id.value;
				} else {
					while (!isNull(sibling.upSib)) {
						sibling = getAttr(sibling.upSib);
						siblingIndent = getIndent(sibling);

						if (siblingIndent === indent) {
							pItem.parent.value = sibling.parent.value;
							sibling.upSib = null;
						} else if (siblingIndent === (indent - 1)) {
							pItem.parent.value = sibling.id.value;
							sibling.upSib = null;
						}
					}
				}
			} else {
				indent -= setInxRemoval(indent);
				pItem.parent.value = "0";
			}
		},
		complete = function (pItem, pPost) {
			validate(pItem);

			while (!isNull(pItem.downSib)) {
				pItem = getAttr(pItem.downSib);
				validate(pItem);
			}

			jForm.post(pPost.Target, pPost.Argument, pPost.Control, pPost.Url);
		},
		validateSelection = function () {
			if (selectedItem === null) {
				jControls.showWarning(pId, "Please Select an Item First");
				return null;
			} else {
				return getAttr();
			}
		},
		insert = function (pOrd, pParId, pUrl) {
			pUrl = pUrl.queryString("AtOrder", pOrd).queryString("ParId", pParId).queryString("LcId", pId);
			jForm.popup({ Caption: "New Item", Url: pUrl });
		},
		move = function (pDir, pPost) {
			var item = validateSelection(),
				sibling,
				t;

			if (!isNull(item)) {
				sibling = (pDir === JILL.UP ? item.upSib : item.downSib);

				if (!isNull(sibling)) {
					item.control.move(pDir);
					t = item.order.value;
					item.order.value = getAttr(sibling).order.value;
					getAttr(sibling).order.value = t;
					complete(validateSelection(), pPost);
				}
			}
			return false;
		};

	// Edit the selected page
	retObj.edit = function (pUrl) {
		var item = validateSelection(), attr, url = pUrl.queryString("ItemId", "{0}").queryString("LcId", pId);

		if (!isNull(item)) {
			attr = getAttr(); url = url.format(attr.id.value); jForm.popup({ Caption: "Edit Item", Url: url });
		}

		return false;
	};
	// Insert a new page above the selected page
	retObj.insertAbove = function (pUrl) {
		insert(getAttr().order.value, getAttr(getAttr().upSib).id.value, pUrl);
		return false;
	};
	// Insert a new page below the selected page
	retObj.insertBelow = function (pUrl) {
		insert(getAttr(getAttr().downSib).order.value, getAttr().id.value, pUrl);
		return false;
	};
	// Move the selected item down in the lineage list
	retObj.moveDown = function (pPost) {
		move(JILL.DOWN, pPost); return false;
	};
	// Outdent the selected item in the lineage list
	retObj.moveLeft = function (pPost) {
		var item = validateSelection();

		if (!isNull(item)) {
			if (getIndent(item) > 0) {
				item.span.text(item.span.text().replace("...", ""));
				complete(item, pPost);
			}
		}

		return false;
	};
	// Indent the selected item int he lineage list
	retObj.moveRight = function (pPost) {
		var item = validateSelection();

		if (!isNull(item)) {
			if (!isNull(item.upSib)) {
				item.span.text("..." + item.span.text());
				complete(item, pPost);
			}
		}

		return false;
	};
	// Move the selected item up in the lineage list
	retObj.moveUp = function (pPost) {
		move(JILL.UP, pPost); return false;
	};
	// Remove the selected page
	retObj.remove = function () {
		var item = validateSelection();

		if (!isNull(item)) {
			return item.id.value;
		} else {
			return "";
		}
	};
	// Selected a ne wlineage item
	retObj.select = function (pObj) {
		list.find("div>@*selected").css(" selected", JILL.REMOVE);
		jill(pObj).css(" selected", JILL.APPEND);
		jControls.hideWarning(pId);
		return false;
	};
	// Update the lineage list of items from a JillPost (occurs after an "EditPage" has been updated)
	retObj.update = function (pText) {
		list.text(pText);
	};

	return retObj;
};

jControls.panels = function (pId) {
	var retObj = {};

	retObj.refresh = function () {
		var url = jWin.getUrl(),
			onComplete = function (pRes) {
				jill(".Theme_" + pId).text(pRes); jill("div|span>@*Invisible*").opacity(30);
			};

		jCore.form.post(url.queryString("RefreshPanel", pId), "", null, onComplete);
	};

	return retObj;
};

jControls.tabber = {
	select: function (pCon) {
		var id = pCon.id.replace("_Link", "_Tab"),
			firstIn = jill("." + id);

		jill(pCon).parent("td").find("a").css(" selected", JILL.REMOVE).parent("table").find("table>@tabber-tab").hide();
		jill(pCon).css(" selected", JILL.APPEND);

		try {
			firstIn.show("table");
		} catch (er) {
			firstIn.show("block");
		}

		jillPopup.center();

		jControls.tabber.setListViews(firstIn);
		jControls.tabber.setInputFocus(firstIn);
	},

	setInputFocus: function (pCont) {
		var ins = pCont.find("input|select");

		if (ins.length > 0) {
			try {
				ins[0].focus(); ins[0].select();
			} catch (fErr) {
			}
		}
	},

	setListViews: function (pCont) {
		var cont = pCont.find("div>@listview"),
			i;

		for (i = 0; i < cont.length; i += 1) {
			jControls.listView(cont.inx(i).id()).init();
		}
	}
};

jControls.trickler = function (pId, pDir) {
	var retObj = {},
		subItem = function (pCon) {
			var i = 0, sib = jill(pCon).sibling(JILL.UP);

			while (!isNull(sib)) { i += 1; sib = sib.sibling(JILL.UP); }

			return i;
		},
		embedded = function (pCon) {
			var sib = jill(pCon).sibling(JILL.DOWN), ret = [];

			while (!isNull(sib)) {
				if (/select|input|textarea/i.test(sib.object.tagName)) {
					ret.push(sib);
				}
				sib = sib.sibling(JILL.DOWN);
			}

			return ret;
		},
		changeEmbedded = function (pCon, pChecked) {
			var sibs = embedded(pCon), i;

			for (i = 0; i < sibs.length; i += 1) {
				sibs[i].attr("disabled", (pChecked ? "" : "disabled"));
			}
		},
		changeUpStream = function (pCon, pItem, pChecked) {
			var parent = jill(pCon).parent().parent(), check = null;

			if (parent.object.className.startsWith("trickler-items")) {
				check = parent.find("input").inx(pItem);

				if (check.object.checked === pChecked) { check.click(); }
			}
		},
		changeDownStream = function (pCon, pItem, pChecked) {
			var parent = jill(pCon).parent(), child = parent.find("div>@trickler-items"), check, i;

			for (i = 0; i < child.length; i += 1) {
				if (parent.object === child.inx(i).parent().object) {
					check = child.inx(i).find("input").inx(pItem);

					if (check.object.checked === pChecked) { check.click(); }
				}
			}
		};

	retObj.click = function (pCon) {
		var item = subItem(pCon);

		if (pDir === "Up") {
			if (pCon.checked) {
				changeUpStream(pCon, item, false);
			} else {
				changeDownStream(pCon, item, true);
			}
			changeEmbedded(pCon, pCon.checked);
		} else {
			if (pCon.checked) {
				changeDownStream(pCon, item, false);
			} else {
				changeUpStream(pCon, item, true);
			}
			changeEmbedded(pCon, pCon.checked);
		}
	};

	return retObj;
};

function FCKeditor_OnComplete (editorInstance) { jillPopup.center(); };
jControls.textEditor = {
	// Convert the textArea control with a editor instance
	add: function (pId, pWidth, pHeight) {
		var newEditor = new FCKeditor(pId, pWidth, pHeight);

		jill("." + pId).size(300, 200);

		newEditor.Config.CustomConfigurationsPath = "/Includes/Jillian/fckconfig.js?t=14";
		newEditor.ReplaceTextarea();
	}
};

jControls.admin = {
	onLoad: function () {
	},

	panel: {
		showOrHide: function (pShow) {
			var removeAppend = (pShow ? JILL.REMOVE : JILL.APPEND),
				appendRemove = (pShow ? JILL.APPEND : JILL.REMOVE);

			jill("div|span|td>@*ContentPanel*").css(" panel-border", appendRemove);
			jill("div>@panel-caption*").css(" hidden", removeAppend);
			jill("div>@*theme-module-menu*").css(" hidden", removeAppend);
			jill("div>@*theme-module-options*").css(" hidden", removeAppend);
			jill("div>@*theme-module-item-options*").css(" hidden", removeAppend);
			jill(".jjAdminPanel_" + (pShow ? "View" : "Edit")).css(" checked", JILL.REMOVE);
			jill(".jjAdminPanel_" + (pShow ? "Edit" : "View")).css(" checked", JILL.APPEND);
			jill("div|span|td|p>@*Invisible*").css(" hidden", removeAppend);
			jill("div>@theme-module-control*>div>@css-menu*").css(" hidden", removeAppend);
		}
	},

	recycler: {
		empty: function () {
			var bin = jill(".AdminPanel_RecycleBin");

			if (bin !== null) {
				bin.css("Full", JILL.REMOVE).find("span>@*RecycleBin*").css("Full", JILL.REMOVE);
			}
		},

		fill: function () {
			var bin = jill(".AdminPanel_RecycleBin");

			if (bin !== null) {
				bin.css("image image-RecycleBinFull").find("span>@*RecycleBin*").css("image image-RecycleBinFull");
			}
		}
	}
};
