MOOsem.imgFolder = "../alek/lib/img";

Alek.here = {
	form: null,
	loaded: false,
	changed: false,
	leaving: false,
	savePromptStatus: 0,	// 0 = not asked, 1 = don't save, 2 = save planned, 3 = saved

	init: function() {
		if (typeof tabberObj == "function") {
			if (typeof tabberOptions == "undefined") tabberAutomatic(); else tabberAutomatic(tabberOptions);
		}

		if ($("alekMainForm")) Alek.here.form = $("alekMainForm");

		Alek.initRequests();

		Alek.initEditors();

		if (Alek.cms) {
			//if (typeof Quickboxes != "undefined") var quickboxes = new Quickboxes({ elements: "input[type=checkbox]", mode: "toggle" });

			if (typeof save == "function") {
				_save = save;

				save = function(p) {
					if (typeof p == "undefined") var p = {};
					Alek.checkLoginAnd(function() { Alek.here.savePromptStatus = 3; _save(p); });
				};
			}

			if (typeof init == "function") init();

			window.addEvent("unload", Alek.here.leave);
		}

		Alek.here.loaded = true;
	},

	check: function() {
		if (!Alek.here.loaded) alert("Page is not yet fully loaded. Please wait.");
		return Alek.here.loaded;
	},

	promptSave: function() {
		if (Alek.here.savePromptStatus > 0) return;
		if (Alek.here.changed) {
			if (confirm("Save changes?")) {
				Alek.here.savePromptStatus = 2;
				save();
			} else Alek.here.savePromptStatus = 1;
		}
	},

	postFormDebug: function() {
		Alek.here.form.action = Alek.here.form.action.replace(/&request_mode=yes/gi, "") + "&debug=yes";
		Alek.here.form.method = "post";
		Alek.here.form.submit();
	},

	postForm: function(p) {
		if (typeof p == "undefined") var p = {};
		p.form = getProp(p, "form", Alek.here.form);
		p.url = p.form.action;
		p.target = getProp(p, "target", "boxOutput");
		p.onLoad = getProp(p, "onLoad", function() { Alek.here.changed = false; if (typeof alekFCK != "undefined") alekFCK.resetIsDirty(); });
		p.onLoadMsg = getProp(p, "onLoadMsg", "<span class='sysblu'>saved</span> " + Date());
		p.onError = Alek.here.processReqError;
		Req.post(p);
	},

	leave: function() {
		if (Alek.here.leaving) return false; else Alek.here.leaving = true;
		if (typeof alekFCK != "undefined" && alekFCK.isDirty()) Alek.here.changed = true;
		if (typeof save == "function") Alek.here.promptSave();
		if (typeof leave == "function") leave();
	}
}

window.addEvent("load", Alek.here.init);

String.implement({
	escQuotes: function() {
		return this.replace(/"/g, "\\\"");
	},

	escApos: function() {
		return this.replace(/'/g, "\\'");
	},

	escUnsafe: function() {
		return this.replace(/(\%|\&|\+|;| |#|\<|\>|\||\")/g, function(p0, p1) { return "%" + String(p1).charCodeAt(0).toString(16); });
	},

	escURL: function() {
		return this.escUnsafe().replace(/\.\./g, "^^").replace(/\+/g, "^-^");
	}
});

if (typeof milkbox != "undefined") window.addEvent("load", function() {
	milkbox.changeOptions({
		resizeDuration: 250
	});
});

/* Requests */

Alek.initRequests = function() {
	var requests = $$(".alek_request");
	for (var i = 0; i < requests.length; i++) {
		var el = requests[i];
		el.id = el.getAttribute("id") || ("alek_request_" + i);
		if (el.getAttribute("initialised") != "yes") {
			el.addEvent("send", function() {
				var url = this.getAttribute("url");
				url = url.replace(/{:(.+):}/g, function(p0, p1) {
					try {
						return eval(p1);
					} catch(err) {
						return "";
					}
				});
				Req.get({ url: url, target: this.id, el: this, onLoad: function(p) { p.el.setAttribute("loaded", "yes"); } });
			}).addEvent("refresh", function() {
				this.fireEvent("send");
			});
			el.setAttribute("initialised", "yes");
			el.setAttribute("loaded", el.getAttribute("loaded") || "no");
			var triggers = (el.getAttribute("trigger") || "").split(",");
			if (el.getAttribute("loaded") != "yes") {
				if (triggers.contains("load")) el.fireEvent("send");
				for (var j = 0; j < triggers.length; j++) {
					var tr = triggers[j].split(":");
					if (tr.length > 1) {
						var elTr = $(tr[0]);
						if (elTr != null) {
							elTr.targetID = el.id;
							elTr.addEvent(tr[1], function() {
								$(this.targetID).fireEvent("send");
							});
						}
					}
				}
			}
		}
	}
}

Alek.processReqError = function(req) {
	var code = req.error.code;
	var desc = req.error.description;
	switch(code) {
		case 2101:
			Msg.hide();
			window.pop({ url: "login.asp?pop", width: 400, height: 300, position: "centre" });
			break;
		default: Msg.show("Error " + code + ": " + desc + "<br><br><i>" + req.url + "</i>");
	}
}

Alek.checkLoginAnd = function(f) {
	Req.get({ url: "request_login_check.asp", onLoad: f, onError: Alek.processReqError });
}

/* Navigation */

Alek.refreshMenu = function(folders) {
	if (parent.frames.length == 0) return;
	var fr = parent.frames[0];
	if ($type(folders) == "number") var folders = [folders];
	if ($type(folders) != "array") var folders = [0];
	if (folders.contains(0) || typeof fr.restoreStatus == "undefined") fr.location.replace(fr.location.href); else {
		fr.aFoldersToRestore = folders;
		fr.restoreStatus();
	}
}

Alek.hideInMenu = function(pageID, langID) {
	if (typeof langID == "undefined") var langID = -1;
	if (parent.frames.length == 0) return;
	var fr = parent.frames[0];
	if (typeof fr.hidePage == "function") {
		var el = fr.$("lang");
		var lng = (el == null) ? langID : el[el.selectedIndex].value;
		if (lng == langID) fr.hidePage(pageID);
	} else fr.location.replace(fr.location.href);
}

/* Field groups */

Alek.getFieldGroup = function(className) {
	if (typeof className == "undefined") var className = "parameter";

	var els = $$("." + className);
	var o = {};
	for (var i = 0; i < els.length; i++) {
		var vis = true;
		var parents = els[i].getParents();
		for (var j = 0; j < parents.length; j++) if (parents[j].style.display == "none") {
			vis = false;
			break;
		}
		if (vis) {
			var val = (els[i].selectedIndex) ? (els[i].selectedIndex > -1 ? els[i][els[i].selectedIndex].value : null) : els[i].value;
			if (val != null) o[els[i].id] = val;
		}
	}
	return o;
}

Alek.gatherFieldGroup = function(destFieldName, className) {
	alekFCK.update();

	var s = "";
	var group = Alek.getFieldGroup(className);
	for (var x in group) if (typeof group[x] != "function") {
		s += (s == "" ? "" : "|") + x + "=" + String(group[x]).replace(/\|/g, "&#124;");
	}

	var el;
	el = $(destFieldName);
	if (el == null && Alek.here.form != null) el = Alek.here.form[destFieldName];
	el.value = s;
}

/* Text editors */

Alek.initEditors = function() {
	if (typeof Alek.editors == "undefined") return;

	var basePath = Alek.paths.alek + "/fckeditor/";

	MOOsem.readScreen();

	for (var i = 0; i < Alek.editors.length; i++) if (!Alek.editors[i].initialised) {
		var edHolder = $("edHolder_" + Alek.editors[i].id);
		var editorID = edHolder.id;
		var sepPos = editorID.indexOf("_");
		editorID = editorID.substring(sepPos + 1);

		var width = Alek.editors[i].width;
		if (width == 0) {
			var widthOffset = Alek.editors[i].widthOffset || 80;
			width = Frame.width - widthOffset;
			if (width > 900) width = 900;
		}

		var height = Alek.editors[i].height;
		if (height == 0) {
			var heightOffset = Alek.editors[i].heightOffset || 20;
			height = Frame.height - heightOffset;
			if (height > 550) height = 550;
		}

		Alek.editors[i].plainText = (typeof Alek.editors[i].plainText == "boolean") ? Alek.editors[i].plainText : false;

		if (Alek.editors[i].plainText == false && typeof FCKeditor != "undefined") {
			var FCKed = new FCKeditor(editorID);
			FCKed.BasePath = basePath;
			FCKed.Config["CustomConfigurationsPath"] = Alek.paths.lib + "/fck/config.js";
			FCKed.Config["SkinPath"] = FCKed.BasePath + "editor/skins/silver/";
			if (!Alek.editors[i].ignoreStyleXML) FCKed.Config["StylesXmlPath"] = Alek.paths.storage + "/fckstyles.xml?" + new Date().toUTCString().replace(/ /g, "");
			if (Alek.editors[i].styleFiles) FCKed.Config["EditorAreaCSS"] = Alek.editors[i].styleFiles;
			FCKed.ToolbarSet = Alek.editors[i].toolbarset;
			FCKed.Width = width;
			FCKed.Height = height;
			FCKed.Value = Alek.editors[i].content;
			edHolder.innerHTML = FCKed.CreateHtml();
			if (Alek.editors[i].groupClass) $(editorID).className += " " + Alek.editors[i].groupClass;
		} else {
			edHolder.innerHTML = "<textarea id='" + editorID + "' name='" + editorID + "' class='standard' style='width: " + width + "px; height: " + height + "px'>" + Alek.editors[i].content + "</textarea>";
		}
		Alek.editors[i].initialised = true;
	}
}

alekFCK = {
	resetIsDirty: function() {
		if (typeof FCKeditorAPI != "undefined" && FCKeditorAPI.__Instances) for (var x in FCKeditorAPI.__Instances) try { FCKeditorAPI.__Instances[x].ResetIsDirty(); } catch(err) {}
	},

	isDirty: function() {
		if (typeof FCKeditorAPI != "undefined" && FCKeditorAPI.__Instances) for (var x in FCKeditorAPI.__Instances) try { if (FCKeditorAPI.__Instances[x].IsDirty()) return true; } catch(err) {}
		return false;
	},

	update: function() {
		if (typeof FCKeditorAPI != "undefined" && FCKeditorAPI.__Instances) for (var x in FCKeditorAPI.__Instances) try { FCKeditorAPI.__Instances[x].UpdateLinkedField(); } catch(err) {}
	}
};

/* Forms */

Alek.validateForm = function(form) {
	alekFCK.update();
	var msg = '';
	var els = form.elements;
	for (var i = 0; i < els.length; i++) if ((els[i].getAttribute('required') == 'yes' || els[i].getAttribute('required') == '1') && els[i].value == '') msg += '- ' + (els[i].getAttribute('var_name') || els[i].getAttribute('name')).replace(/_/g, ' ') + '\n';
	if (msg != '') {
		msg = (form.getAttribute('required_fields_message') || 'The following fields are not yet filled in:')+ '\n\n' + msg;
		alert(msg);
		return false;
	}
	return true;
}

Alek.viewSelFile = function(elID) {
	var el = document.getElementById(elID);
	if (el.selectedIndex > 0) {
		var fileName = el[el.selectedIndex].value.escURL();
		var fileExt = fileName.substring(fileName.lastIndexOf('.') + 1);
		if (Alek.extensions.browserImage.indexOf(fileExt) > -1) window.pop({ url: Alek.paths.lib + "/img_popper.html?src=" + Alek.paths.upload.escURL() + "/" + fileName, width: 200, height: 200, resizable: 'yes', scrollbars: 'yes' }); else window.pop({ url: Alek.paths.upload + "/" + fileName, width: 600, height: 400, resizable: 'yes', scrollbars: 'yes' });
	}
}

Alek.selectAssocRadio = function(fieldName, el) {
	var srcName = el.id;
	var els = document.getElementsByName(fieldName + '_RADIO');
	if (els.length == 0) $(fieldName).value = el.value; else {
		for (var i = 0; i < els.length; i++) els[i].checked = (els[i].getAttribute('srcFieldName') == srcName);
		Alek.processMultiFieldRadio(fieldName);
	}
}

Alek.getCheckedRadio = function(fieldName) {
	var els = document.getElementsByName(fieldName + '_RADIO');
	for (var i = 0; i < els.length; i++) if (els[i].checked) return els[i];
	return null;
}

Alek.getCheckedVal = function(el) {
	if (!el) return "";
	if (!el.length) return el.checked ? el.value : "";
	for (var i = 0; i < el.length; i++) if (el[i].checked) return el[i].value;
	return "";
}

Alek.processMultiFieldRadio = function(fieldName) {
	var rad = Alek.getCheckedRadio(fieldName);
	if (rad != null) {
		var srcFieldName = rad.getAttribute('srcFieldName');
		var destFieldName = rad.getAttribute('destFieldName');
		$(destFieldName).value = $(srcFieldName).value;
	}
	changed = true;
}

Alek.compileCheckValues = function(fieldName, nrOfFields) {
	var s = '';
	for (var i = 0; i < nrOfFields; i++) {
		var el = $(fieldName + '_opt' + i);
		if (el.checked) s += (s == '' ? '' : ',') + el.value;
	}
	$(fieldName).value = s;
}

Alek.toggleCheckBoxes = function(fieldName, nrOfFields) {
	var allChecked = true;
	var i = 0;
	while (i < nrOfFields && allChecked) {
		var el = $(fieldName + '_opt' + i);
		if (!el.checked) allChecked = false;
		i++;
	}
	for (var i = 0; i < nrOfFields; i++) {
		var el = $(fieldName + '_opt' + i);
		el.checked = !allChecked;
	}
}

Alek.compileTimeEvent = function(fieldName) {
	var elStart = $(fieldName + '_start');
	var elEnd = $(fieldName + '_end');
	var elEndBox = $(fieldName + '_end_box');
	var elNever = $(fieldName + '_neverEnd');
	var elRepeatEvery = $(fieldName + '_repeat_every');
	var elRepeatUnit = $(fieldName + '_repeat_unit');
	var elRepeatAmount = $(fieldName + '_repeat_amount');
	if (elNever != null && elNever.checked) elEnd.value = dbLibTime.nullString;

	var s = 'start=' + elStart.value + '|end=' + elEnd.value;

	if (elRepeatEvery != null) {
		if (elRepeatAmount.value == 0) elRepeatEvery.value = 0;
		if (elRepeatEvery.value == 0) elRepeatAmount.value = 0;
		s += '|repeatPattern=' + elRepeatUnit.value + elRepeatEvery.value + '|repeatAmount=' + elRepeatAmount.value;
	}
	
	//if (Alek.debug) alert(s);
	$(fieldName).value = s;
}

/* Various */

Alek.go = function(url, trg) {
	if (typeof trg == "undefined") var trg = "_self";
	if (typeof alekFCK != "undefined" && alekFCK.isDirty()) changed = true;
	if (Alek.here.changed) {
		if (confirm("Save changes?")) {
			Alek.here.savePromptStatus = 2;
			save({ redir: url });
		} else Alek.here.savePromptStatus = 1;
	}
	if (Alek.here.savePromptStatus != 2) window.open(url, trg);
}

Alek.go2 = function(url) {
	if (!isNaN(url)) url = "page_edit.asp?db_id=" + url;
	var fr = (parent.frames.length < 2) ? document : parent.frames[1];
	if (typeof fr.Alek == "undefined") Alek.go(url, "alekcms_page_edit"); else fr.Alek.go(url);
}

Alek.pickLanguage = function(langID, trg) {
	if (typeof trg == 'undefined') var trg = '_self';
	var doc = (trg.toLowerCase() == '_self') ? document : (trg.toLowerCase() == '_top') ? top : (trg.toLowerCase() == '_parent') ? parent : parent.frames[trg];
	if (!doc) return false;
	var url = doc.location.href;
	url = url.replace(/[?&]language=([^&])+/g, '');
	url += (url.indexOf('?') == -1) ? '?' : '&';
	url += 'language=' + langID;
	doc.location.replace(url);
	return true;
}

Alek.embedSWF = function(swfNr, src, width, height, par) {
	var swfID = "alekSWF_" + swfNr;
	if (navigator.plugins && navigator.mimeTypes && navigator.mimeTypes.length) {
		var s = "<embed id='" + swfID + "' type='application/x-shockwave-flash' src='" + src + "' width='" + width + "' height='" + height + "' ";
		for (var x in par) if (typeof par[x] != 'function' && x != 'width' && x != 'height' && x != 'movie' && x != 'allowscriptaccess') s += x + "='" + par[x] + "' ";
		s += "quality='high' pluginspage='http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash'></embed>";
	} else {
		var s = "<object id='" + swfID + "' classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0' width='" + width + "' height='" + height + "'><param name='width' value='" + width + "'><param name='height' value='" + height + "'><param name='movie' value='" + src + "'>";
		for (var x in par) if (typeof par[x] != 'function' && x != 'width' && x != 'height') s += "<param name='" + x + "' value='" + par[x] + "'>";
		s += "<param name='quality' value='high'><param name='allowscriptaccess' value='sameDomain'></object>";
	}
	$("alekSWF_holder_" + swfNr).innerHTML = s;
	if (width == 0 && height == 0) Alek.resizeSWF(swfNr);
}

Alek.getSWF = function(swfID) {
	if (window.document[swfID]) return window.document[swfID];
	if (navigator.appName.indexOf("Microsoft Internet") == -1) {
		if (document.embeds && document.embeds[swfID]) return document.embeds[swfID];
	} else return document.getElementById(swfID);
}

Alek.resizeSWF = function(swfNr) {
	var swf = Alek.getSWF("alekSWF_" + swfNr);
	var swfWidth = swf.TGetProperty("/", 8);
	if (swfWidth > 0) {
		swf.width = parseInt(swfWidth, 10);
		swf.height = parseInt(swf.TGetProperty("/", 9), 10);
	} else setTimeout("resizeSWF(" + swfNr + ")", 500);
}

Alek.percBar = function(p) {
	if (typeof p != "object") var p = {};
	p.width = p.width || "200px";
	p.height = p.height || "10px";
	p.colour = p.colour || "";
	p.fillColour = p.fillColour || "#2778B0";
	p.textColour = p.textColour || "white";
	p.textSize = p.textSize || "10px";
	p.text = p.text || "";
	p.count = p.count || 0;
	p.total = p.total || 100;
	if (p.count > p.total) p.count = p.total;
	var perc = parseInt((p.count / p.total) * 100, 10);
	return "<div style='width: " + p.width + "; height: " + p.height + "; background-color: " + p.colour + "; font-size: " + p.textSize + "; color: " + p.fillColour + "'><span style='width: " + p.width + "; overflow: hidden'>" + p.text + "</span>" + (p.text == "" ? "" : "<br>") + "<div style='border: 1px solid " + p.fillColour + "; padding: 1px; margin: 2px'><div style='background-color: " + p.fillColour + "; width: " + perc + "%; height: " + p.height + "; font-size: " + p.textSize + "; color: " + p.textColour + "; overflow-x: hidden'></div></div></div>"
}

