initializeWindows = function() {
	sessionRefresh();
}

//#####################################################################################
//#####################################################################################
//#####################################################################################
//#####################################################################################
//##################################################################################### 
 
// Initialize MochaUI when the DOM is ready
window.addEvent('domready', function(){
	MochaUI.Desktop = new MochaUI.Desktop();
	MochaUI.Dock = new MochaUI.Dock({
		dockPosition: 'bottom'
	});
	MochaUI.Modal = new MochaUI.Modal();
	
	MochaUI.Desktop.desktop.setStyles({
		'background': '#fff',
		'visibility': 'visible'
	});
	
	initializeWindows();
});

// This runs when a person leaves your page.
window.addEvent('unload', function(){
	if (MochaUI) MochaUI.garbageCleanUp();
});

//#####################################################################################
//#####################################################################################
//#####################################################################################
//#####################################################################################
//#####################################################################################

var Session_Timer = null;

//#####################################################################################
//#####################################################################################
//#####################################################################################
//#####################################################################################
//#####################################################################################

function systemErrorhandler(errorTitle, errorContent) {
	var growlQueue = new Notimoo();
	var errorType = 'notimoo';
	var errorSticky = false;
	
	if (errorTitle == 'Fatal Error') {
		errorType = 'notimoo_error';
		errorSticky = true;
	} else if (errorTitle == 'Warning') {
		errorType = 'notimoo_warning';
	}
	
	growlQueue.show({ title: errorTitle, message: errorContent, sticky: errorSticky, customClass: errorType });
}

function systemEventhandler(formTarget, formVars) {
	// STRIP TARGET WIDTH AND HEIGHT FROM HANDLER
	var targetArray = formTarget.split('::');
	var windowTarget = targetArray[0];
	var windowWidth = 950;
	var windowHeight = 500;
	if (targetArray[1]) {
		var windowWidth = targetArray[1];
	}
	if (targetArray[2]) {
		var windowHeight = targetArray[2];
	}
	
	// STRIP FORM VARS OUT OF COMMAND
	var formRes = decodeSearchString(formVars);
	if (formRes['Sys_Name']) {
		formRes['Sys_Name'] = urldecode(formRes['Sys_Name']);
	}
	if (!formRes['Sys_Set']) {
		formRes['Sys_Set'] = formRes['Sys_Action'];
	}
	
	// SET-UP WINDOW ID'S AND NAME
	var windowId = formRes['Sys_Set']+'window';
	var windowName = formRes['Sys_Name'];
	
	// CHECK EVENT TYPE
	if ((formRes['Sys_Type'] == "Popup") || (formRes['Sys_Type'] == "RedirectPopup")) {
		if ($(windowId)) {
			MochaUI.updateContent({
				element: $(windowId),
				title: windowName,
				loadMethod: 'xhr',
				url: 'index.php?'+formVars,
				method: 'post',
			});
		} else {
			new MochaUI.Window({
				id: windowId,
				title: windowName,
				loadMethod: 'xhr',
				evalScripts: true,
				evalResponse: false,
				method: 'post',
				toolbar: true,
				toolbarURL: 'functions/elements/element_blank.php',
				contentURL: 'index.php?'+formVars,
				width: windowWidth,
				height: windowHeight,
				y: 80,
				padding: { top: 10, right: 10, bottom: 10, left: 10 },
			});
		}
		
		sessionRefresh();
	} else if (formRes['Sys_Type'] == "Main") {
		// LOAD MAIN
		var request = new Request.HTML({
			url: 'index.php?'+formVars,
			method: 'post',
			evalScripts: true,
			evalResponse: false,
			onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript) {
				$('page').set('html', responseHTML);
				$exec(responseJavaScript);
			}
		}).send();
		
		// REFRESH MENU
		var request = new Request.HTML({
			url: 'index.php?Sys_Action=External_Menu&Sys_Type=System_Refresh',
			method: 'post',
			evalScripts: true,
			evalResponse: false,
			onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript) {
				$('desktopHeader').set('html', responseHTML);
				$exec(responseJavaScript);
			}
		}).send();
		
		sessionRefresh();
	} else if (formRes['Sys_Type'] == "System_Refresh") {
		if (windowTarget != '_none') {
			// REFRESH TARGET LAYER
			var request = new Request.HTML({
				url: 'index.php?content=test&'+formVars,
				method: 'post',
				evalScripts: true,
				evalResponse: false,
				onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript) {
					$(windowTarget).set('html', responseHTML);
					$exec(responseJavaScript);
				}
			}).send();
		} else {
			// LOAD REFRESH FUNCTION
			var request = new Request.HTML({
				url: 'index.php?'+formVars,
				method: 'post',
				evalScripts: true,
				evalResponse: false,
				onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript) {
					$exec(responseJavaScript);
				}
			}).send();
		}
	}
}

function systemFormsubmit(formName) {
	var valState = systemFormvalidate(formName);
	if(valState != false) {
		if((objForm = $(formName))) {
			// PROCESS
			var wndMessage = new MochaUI.Window({
				id: "wndProcess",
				title: "Information",
				type: "modal",
				content: "<div class=\"ajaxModalMessage\">Processing...</div>",
				width: 250,
				height: 36,
				onContentLoaded: function(windowEl){
					var request = new Request.HTML({
						method: 'post',
						url: "index.php",
						data: $(objForm),
						evalScripts: false,
						evalResponse: true,
						onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript){
							$exec(responseJavaScript);
							//alert(responseHTML);
							MochaUI.closeWindow(MochaUI.currentModal);
						}
					}).post($(objForm)); 
					
					/*
					var request = new Request.HTML({
						url: "index.php",
						evalScripts: false,
						evalResponse: true,
						onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript){
							$exec(responseJavaScript);
							MochaUI.closeWindow(MochaUI.currentModal);
						}
					});
				   
					request.post(objForm);
					*/
				},
				onFailure: function(instance){
					MochaUI.closeWindow(MochaUI.currentModal);
					MochaUI.notification("Fatal Error.");
				}
			});
		}
	}
}

function systemFormvalidate(formName) {
	var form = $(formName);
	var formFields = form.elements;
	var formCheck = true;
	
	for (var index = 0; index < formFields.length; ++index) {
		var formItem = formFields[index];
		
		////////////////////////////////////VALIDATE////////////////////////////////////////////////
		
		if ($(formItem.id+'_Required')) {
			if (formItem.value == '') {
				$(formItem.id+'_Required').set('html', 'This field is required.');
				$(formItem.id+'_Required').style.display = 'block';
				formCheck = false;
			} else {
				$(formItem.id+'_Required').style.display = 'none';
			}
		} else if ($(formItem.id+'_Limit')) {
			if (formItem.value.length > $(formItem.id+'_Limitlength').value) {
				$(formItem.id+'_Limit').set('html', 'This value can be no longer than '+$(formItem.id+'_Limitlength').value+' characters.');
				$(formItem.id+'_Limit').style.display = 'block';
				formCheck = false;
			} else {
				$(formItem.id+'_Limit').style.display = 'none';
			}
		} else if ($(formItem.id+'_Sameas')) {
			if (formItem.value == '') {
				$(formItem.id+'_Sameas').set('html', 'This field is required.');
				$(formItem.id+'_Sameas').style.display = 'block';
				formCheck = false;
			} else if (formItem.value != $($(formItem.id+'_Sameasprimary').value).value) {
				$(formItem.id+'_Sameas').set('html', 'These fields must match.');
				$(formItem.id+'_Sameas').style.display = 'block';
				formCheck = false;
			} else {
				$(formItem.id+'_Sameas').style.display = 'none';
			}
		}
		
		////////////////////////////////////VALIDATE////////////////////////////////////////////////
	}
	
	return formCheck;
}

function sessionRefresh() {
	systemEventhandler('_none','Sys_Action=ExternalAction_SessionMaintain&Sys_Type=System_Refresh');
	
	// REFRESH THE SESSION TIMEOUT
	clearTimeout(Session_Timer);
	Session_Timer = setTimeout("sessionRefresh();",2701000);
}

//#####################################################################################
//#####################################################################################
//#####################################################################################
//#####################################################################################
//#####################################################################################

function systemSectiondisplay(sectionName, themePath, iconType) {
	if ($('div_'+sectionName).style.display == 'none') { 
		$('div_'+sectionName).style.display = '';
		if (iconType != 1) {
			$('icon_'+sectionName).src = img_src = 'resources/themes/'+themePath+'/rowhide_icon.png';
		} else {
			$('icon_'+sectionName).src = img_src = 'resources/themes/'+themePath+'/ui_theme/icons/tree/minus.gif';
		}
		$('gui_display_'+sectionName).value = '1';
	} else {
		$('div_'+sectionName).style.display = 'none';
		if (iconType != 1) {
			$('icon_'+sectionName).src = img_src = 'resources/themes/'+themePath+'/rowshow_icon.png';
		} else {
			$('icon_'+sectionName).src = img_src = 'resources/themes/'+themePath+'/ui_theme/icons/tree/plus.gif';
		}
		$('gui_display_'+sectionName).value = '0';
	}
}

function setFocus(formName) {
	var formName = $(formName);
	var i;
	if (formName != null) {
		var max = formName.length;
		for(i = 0; i < max; i++) {
			if( formName.elements[i].type != "hidden" &&
				!formName.elements[i].disabled &&
				!formName.elements[i].readOnly) {
				formName.elements[i].focus();
				break;
			}
		}
	}
}

function decodeSearchString(searchStr) {
   var searchRes = new Array();
   if (searchStr) {
       var formElement = searchStr.split("&");
       var tmpArray = new Array();
       for (k = 0; k < formElement.length; k++) {
            tmpArray = formElement[k].split("=");
            searchRes[tmpArray[0]] = tmpArray[1];
       }
   }
   return searchRes;
}

function stripHTML(stripStr){
	return stripStr.replace(/[^A-Za-z]/g, "");
}

function urlencode(str) {
    var hexStr = function (dec) {
        return '%' + dec.toString(16).toUpperCase();
    };

    var ret = '',
            unreserved = /[\w.-]/; // A-Za-z0-9_.- // Tilde is not here for historical reasons; to preserve it, use rawurlencode instead
    str = (str+'').toString();

    for (var i = 0, dl = str.length; i < dl; i++) {
        var ch = str.charAt(i);
        if (unreserved.test(ch)) {
            ret += ch;
        }
        else {
            var code = str.charCodeAt(i);
            // Reserved assumed to be in UTF-8, as in PHP
            if (code === 32) {
                ret += '+'; // %20 in rawurlencode
            }
            else if (code < 128) { // 1 byte
                ret += hexStr(code);
            }
            else if (code >= 128 && code < 2048) { // 2 bytes
                ret += hexStr((code >> 6) | 0xC0);
                ret += hexStr((code & 0x3F) | 0x80);
            }
            else if (code >= 2048 && code < 65536) { // 3 bytes
                ret += hexStr((code >> 12) | 0xE0);
                ret += hexStr(((code >> 6) & 0x3F) | 0x80);
                ret += hexStr((code & 0x3F) | 0x80);
            }
            else if (code >= 65536) { // 4 bytes
                ret += hexStr((code >> 18) | 0xF0);
                ret += hexStr(((code >> 12) & 0x3F) | 0x80);
                ret += hexStr(((code >> 6) & 0x3F) | 0x80);
                ret += hexStr((code & 0x3F) | 0x80);
            }
        }
    }
    return ret;
}

function urldecode(str) {
    var hash_map = {}, ret = str.toString(), unicodeStr='', hexEscStr='';
    
    var replacer = function (search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The hash_map is identical to the one in urlencode.
    hash_map["'"]   = '%27';
    hash_map['(']   = '%28';
    hash_map[')']   = '%29';
    hash_map['*']   = '%2A';
    hash_map['~']   = '%7E';
    hash_map['!']   = '%21';
    hash_map['%20'] = '+';
    hash_map['\u00DC'] = '%DC';
    hash_map['\u00FC'] = '%FC';
    hash_map['\u00C4'] = '%D4';
    hash_map['\u00E4'] = '%E4';
    hash_map['\u00D6'] = '%D6';
    hash_map['\u00F6'] = '%F6';
    hash_map['\u00DF'] = '%DF';
    hash_map['\u20AC'] = '%80';
    hash_map['\u0081'] = '%81';
    hash_map['\u201A'] = '%82';
    hash_map['\u0192'] = '%83';
    hash_map['\u201E'] = '%84';
    hash_map['\u2026'] = '%85';
    hash_map['\u2020'] = '%86';
    hash_map['\u2021'] = '%87';
    hash_map['\u02C6'] = '%88';
    hash_map['\u2030'] = '%89';
    hash_map['\u0160'] = '%8A';
    hash_map['\u2039'] = '%8B';
    hash_map['\u0152'] = '%8C';
    hash_map['\u008D'] = '%8D';
    hash_map['\u017D'] = '%8E';
    hash_map['\u008F'] = '%8F';
    hash_map['\u0090'] = '%90';
    hash_map['\u2018'] = '%91';
    hash_map['\u2019'] = '%92';
    hash_map['\u201C'] = '%93';
    hash_map['\u201D'] = '%94';
    hash_map['\u2022'] = '%95';
    hash_map['\u2013'] = '%96';
    hash_map['\u2014'] = '%97';
    hash_map['\u02DC'] = '%98';
    hash_map['\u2122'] = '%99';
    hash_map['\u0161'] = '%9A';
    hash_map['\u203A'] = '%9B';
    hash_map['\u0153'] = '%9C';
    hash_map['\u009D'] = '%9D';
    hash_map['\u017E'] = '%9E';
    hash_map['\u0178'] = '%9F';
    hash_map['\u00C6'] = '%C3%86';
    hash_map['\u00D8'] = '%C3%98';
    hash_map['\u00C5'] = '%C3%85';

    for (unicodeStr in hash_map) {
        hexEscStr = hash_map[unicodeStr]; // Switch order when decoding
        ret = replacer(hexEscStr, unicodeStr, ret); // Custom replace. No regexing
    }
    
    // End with decodeURIComponent, which most resembles PHP's encoding functions
    ret = decodeURIComponent(ret);

    return ret;
}

/**
 * Observer - Observe formelements for changes
 *
 * - Additional code from clientside.cnet.com
 *
 * @version		1.1
 *
 * @license		MIT-style license
 * @author		Harald Kirschner <mail [at] digitarald.de>
 * @copyright	Author
 */
var Observer = new Class({

	Implements: [Options, Events],

	options: {
		periodical: 200,
		delay: 200
	},

	initialize: function(el, onFired, options){
		this.element = $(el) || $$(el);
		this.addEvent('onFired', onFired);
		this.setOptions(options);
		this.bound = this.changed.bind(this);
		this.resume();
	},

	changed: function() {
		var value = this.element.get('value');
		if ($equals(this.value, value)) return;
		this.clear();
		this.value = value;
		this.timeout = this.onFired.delay(this.options.delay, this);
	},

	setValue: function(value) {
		this.value = value;
		this.element.set('value', value);
		return this.clear();
	},

	onFired: function() {
		this.fireEvent('onFired', [this.value, this.element]);
	},

	clear: function() {
		$clear(this.timeout || null);
		return this;
	},

	pause: function(){
		if (this.timer) $clear(this.timer);
		else this.element.removeEvent('keyup', this.bound);
		return this.clear();
	},

	resume: function(){
		this.value = this.element.get('value');
		if (this.options.periodical) this.timer = this.changed.periodical(this.options.periodical, this);
		else this.element.addEvent('keyup', this.bound);
		return this;
	}

});

var $equals = function(obj1, obj2) {
	return (obj1 == obj2 || JSON.encode(obj1) == JSON.encode(obj2));
};

//#####################################################################################
//#####################################################################################
//#####################################################################################
//#####################################################################################
//#####################################################################################