
Array.prototype.compare = function(testArr) {
	if (this.length != testArr.length) {
		return false;
	}
	for (var i = 0; i < testArr.length; i++) {
		if (this[i].compare) { 
			if (!this[i].compare(testArr[i])) {
				return false;
			}
		}
		if (this[i] !== testArr[i]) {
			return false;
		}
	}
	return true;
};

Array.prototype.find = function (element)
{
	for (var keys in this)
	{
		if (this[keys] == element)
		{
			return keys;
			break;
		}
	}
	return -1;
};

Array.prototype.partiallyfind = function (element)
{
	for (var keys in this)
	{
		if (typeof this[keys] == 'string') {
			if (this[keys].indexOf(element) != -1) {
				return keys;
				break;
			}
		}
	}
	return -1;
};

var curHash = 'undefined';
var prevHash = Array(window.location.hash.substr(1));
var publications = Object();
var storedForm = Object;
var startRestoreContent = 'undefined';
var lastReplaceID;
var contentInterval;
var systemModules = new Array('pages'); 
var numDefaultTemplates = Array();
var registeredFunctions = Array();

initAjax();

function systemRegisterFormFunction(func) {
	registeredFunctions[registeredFunctions.length] = func;
}

function systemUnregisterFormFunction(func) {
	registeredFunctions.slice(registeredFunctions.find(func), 1);
}

function systemIsIE() {
	if (navigator.appName == "Microsoft Internet Explorer") {
		return true;
	} else {
		return false;
	}
}

function systemIsChrome() {
	if (!systemIsIE()) {
		if (navigator.vendor.indexOf("Google") != -1) {
			return true;
		} else {
			return false;
		}
	}
	return false;
}

function systemFormOnSubmit(form) {
  	action = storedForm[form.name];
	var root = window.location.href;
	var rootIndex = root.indexOf('#') == -1 ? root.length : root.indexOf('#') ;
	if (action.substr(0,rootIndex) != root.substr(0,rootIndex)) {
		form.action = action;
		form.setAttribute('onSubmit', '');
		form.submit();
	} else {
		var poststr = '';
	    for (i=0; i<form.elements.length; i++) {
	    	if (form.elements[i].name.length > 0) {
	    		if (poststr != '') {
	    			poststr += '&';
	    		}
	    		switch (form.elements[i].type) {
		    		case 'file': {
		    			body = document.getElementsByTagName("body")[0];
			        	
			        	form.action = action.replace('/go/','/api/get/');
			        	form.setAttribute('target', 'ajaxFilePostIframe');
			        	form.setAttribute('onSubmit', '');
			        	
			        	currentfr = document.getElementById('ajaxFilePostIframe');
			        	if (currentfr.addEventListener) {
							currentfr.addEventListener("load", function(){ systemReplaceContentIframe(action); }, false);
						} else if (currentfr.attachEvent) {
							currentfr.detachEvent("onload", function(){ systemReplaceContentIframe(action); }); // Bug fix line
							currentfr.attachEvent("onload", function(){ systemReplaceContentIframe(action); });
						}
						form.submit();
			        	return;
		    		}break;
		    		case 'radio': {
						if (form.elements[i].checked)  {
							poststr += form.elements[i].name+"="+encodeURI(form.elements[i].value);
						}
		    		}break;
		    		default: {
		    			poststr += form.elements[i].name+"="+encodeURI(form.elements[i].value);
		    		}
	    		}
	    	}
	    }
	    if (form.method.toUpperCase() == 'GET') {
	    	method = 'GET';
	    } else {
	    	method = 'POST';
	    }
	    if (systemCheckForQueryString() == '') {
	    	querystring = true;
	    } else {
	    	querystring = false;
	    }
	    url = systemCreateContentUrl(action, querystring);
	   	systemXmlHttp.request(method, url, true, null, null, poststr, this, systemReplaceContent);
   	}
}

function systemAddFormFunctions(div, requestUrl, objectid) {
	forms = div.getElementsByTagName('form');
			
	for (i=0; i<forms.length; i++) {
		if ((forms[i].name.length <= 0) && (forms[i].id.length <= 0)) {
			tempName = 'customFormName'+objectid;
			forms[i].name = tempName;
			forms[i].id = tempName;
		} else if (forms[i].name.length <= 0) {
			forms[i].name = forms[i].id;
		} else if (forms[i].id.length <= 0) {
			forms[i].id = forms[i].name;
		}
		if (forms[i].action.length > 0) {
			storedForm[forms[i].name] = forms[i].action;
		} else {
			storedForm[forms[i].name] = requestUrl.replace('/api/get/','/go/');
		}
		forms[i].setAttribute('enctype','multipart/form-data');
		forms[i].action = 'javascript:systemFormOnSubmit(document.getElementById("'+forms[i].id+'"));';
		forms[i].onSubmit = 'return false;';
		for (j=0; j<registeredFunctions.length; j++) {
			registeredFunctions[j](forms[i],forms[i].id);
		}
		
	}
}
 
function systemAddEvent(object, event, fn, option)
{
	if (object.addEventListener)
	{
		object.addEventListener(event, fn, option);
	}
	else
	{
		object.attachEvent('on' + event, fn);
	}
}

function systemAddLoadEvent(func) {
  	var oldonload = window.onload;
  	if (typeof window.onload != 'function') {
    	window.onload = func;
  	} else {
    	window.onload = function() {
	      	if (oldonload) {
	        	oldonload();
	      	}
	      	func();
    	}
  	}
}

function initAjax()
{
	systemAddEvent(document, 'click', systemPrepareLoadContent, true);
	systemAddLoadEvent(systemFirstContent);
	//contentTimeout = setTimeout('systemFirstContent()', 100);
}

function systemFirstContent() {
	body = document.getElementsByTagName("body")[0];
	if (systemIsIE()) {
		var rem = document.createElement("div")
			rem.innerHTML = '<iframe style="display:none" src="about:blank" id="ajaxIframe" name="ajaxIframe"></iframe>'
		body.appendChild(rem);
	}
	var rem = document.createElement("div")
		rem.innerHTML = '<iframe style="display:none" src="about:blank" id="ajaxFilePostIframe" name="ajaxFilePostIframe"></iframe>'
	body.appendChild(rem);

	contentInterval = setInterval('systemRestoreContent()', 200);
}

function systemReplaceInnerHTML(objectid, html, requestUrl) {
	tempObjectidArray = String(objectid).split(/\|/gi);
						
	for (var o=0; o<tempObjectidArray.length; o++) {
		if ((document.getElementById('ajax'+tempObjectidArray[o])) && (document.getElementById('ajax'+tempObjectidArray[o]).innerHTML != html)) {
			
			var tempParent = document.getElementById('ajax'+tempObjectidArray[o]).parentNode;
			
			var span = document.createElement("span");
       		span.innerHTML = html;
			span.setAttribute('id', 'ajax'+tempObjectidArray[o]);
			tempParent.replaceChild(span,document.getElementById('ajax'+tempObjectidArray[o]));
			//tempParent.replaceChild(span,document.getElementById('ajax'+tempObjectidArray[o]));
			
			head = document.getElementsByTagName("head")[0];
			
			//first remove prev loaded scripts
			var currScript = head.getElementsByTagName("script");   
			var j=0;
			while(currScript[j]) {
				if (currScript[j].id.substring(currScript[j].id.indexOf('loaded'),currScript[j].id.indexOf('by')) == 'loaded'+tempObjectidArray[o]) {
					currScript[j].parentNode.removeChild(currScript[j]);
					j--;
				}
				j++;
			}
			var script = document.getElementById('ajax'+tempObjectidArray[o]).getElementsByTagName("script");   
			for(var i=0;i<script.length;i++) {  
	        	var scr = document.createElement("script");
	        	scr.id = 'loaded'+tempObjectidArray[o]+'byajax'+i;
	        	scr.type = 'text/javascript';
	        	if (script[i].src) {
	        		scr.src = script[i].src;
	        	} else {
	        		scr.text = script[i].text;
	        	}
	        	head.appendChild(scr);
	        	
			} 
			while(script[0]) {
				script[0].parentNode.removeChild(script[0]);
			}
			systemAddFormFunctions(document.getElementById('ajax'+tempObjectidArray[o]),requestUrl,tempObjectidArray[o]);
		}
	}
}

function systemCheckForQueryString() {
	queryArray = Array();
	endUrl = window.location.hash.split('|');
	if (endUrl.length == 1) {
		if (endUrl[0].length == 0) {
			return '';
		}
	}
	for (i=0;i<endUrl.length;i++) {
		if (endUrl[i].indexOf('?') != -1) {
			queryArray[queryArray.length] = endUrl[i].substr(endUrl[i].indexOf('?')+1);
		}
	}
	if (queryArray.length > 0) {
		return '?'+queryArray.join('&');
	} else {
		return '';
	}
}

function systemCreateContentUrl(url, addQueryString) {
	returnArray = Array();
	queryString = systemCheckForQueryString();
	if (url) {
		if (url.indexOf('?teaser') != -1) {
			return url.replace('/go/', '/api/get/');
		} else {
			return url.replace('/go/', '/api/get/')+(addQueryString ? queryString : '');
		}
	} else {
		var root = window.location.href;
	}
	var addArray = root.split('.');
	if (addArray[addArray.length-1].substr(0,3) == 'web' || addArray[addArray.length-1].substr(0,4) == 'html') {
		addArray.pop(); 
	}
	root = addArray.join('.'); 
	
	var rootIndex = root.indexOf('#') == -1 ? root.length : root.indexOf('#') ;
		
	startUrl = root.substring(0,rootIndex);
	endUrl = root.substring(rootIndex+1,root.length).split('|');
	if (endUrl.length == 1) {
		if (endUrl[0].length == 0) {
			return returnArray;
		}
	}
	for (i=0;i<endUrl.length;i++) {
		var endUrlArray = endUrl[i].split('.');
		if (endUrlArray[endUrlArray.length-1].substr(0,3) == 'web' || endUrlArray[endUrlArray.length-1].substr(0,4) == 'html') {
			endUrlArray.pop(); 
		}
		endUrl[i] = endUrlArray.join('.'); 
		if (endUrl[i].indexOf('?') != -1) {
			endUrl[i] = endUrl[i].substr(0,endUrl[i].indexOf('?'));
			if (endUrl[i].length == 0) {
				continue;
			}
		}
		contentUrl = startUrl+endUrl[i]+'.web'+(addQueryString ? queryString : '')
		returnArray[returnArray.length] = contentUrl.replace('/go/', '/api/get/');
	}
	
	return returnArray;
}

function addPublication(id, url) {
	publications[id] = url;
}
function systemRestoreContent () {
	var newHash = window.location.hash;
	if (systemIsIE()) {
			try {
				iframe = document.getElementById('ajaxIframe').contentWindow.document.body.innerHTML;
				if (iframe.length != 0) {
					if (window.location.hash.substr(1) != iframe) {
						newHash = window.location.hash = iframe;
					}
				} else {
					if (window.location.hash.substr(1).length != 0) {
						iframe = document.getElementById('ajaxIframe');
						startRestoreContent = false;
						iframe.setAttribute('onload', 'javascript:startRestoreContent = true;');
						iframe.src = window.location.protocol+'//'+window.location.hostname+'/ajax.php?hash='+window.location.hash.substr(1);
					}
				}
			} catch(e) {
				//alert(e.text);
			} 
	}
	
	if ((curHash != newHash) ) {
		newContentUrl = systemCreateContentUrl('', true);
		if (newContentUrl.length) {
			if (curHash == 'undefined') {
				for (i=0;i<newContentUrl.length;i++) {
					if (newContentUrl[i] != window.location.href.substr(0,newContentUrl[i].length)) {
						systemXmlHttp.request('GET', newContentUrl[i], true, null, null, '', this, systemReplaceContent);
					}
				}
			} else {
				systemXmlHttp.request('GET', newContentUrl[newContentUrl.length-1], true, null, null, '', this, systemReplaceContent);
			}
		}			
				
		if (curHash != 'undefined') {
			
			var found = prevHash.find(newHash);
			if (found != -1) {
				prevHash.splice(found,1);
				for (var ID in publications) {
					if (parseInt(ID).toString() == ID) {
						defaultContentUrl = systemCreateContentUrl(publications[ID], false);
						if (newContentUrl.partiallyfind(defaultContentUrl) == -1 && (defaultContentUrl.replace('/api/get/', '/go/') != window.location.href.substr(0,defaultContentUrl.replace('/api/get/', '/go/').length))) {
							systemXmlHttp.request('GET', systemCreateContentUrl(publications[ID]+'?teaser=false', true), true, null, null, '', this, systemReplaceContent);
						}
					}
				}
				defaultcounter = 0;
				while (document.getElementById('ajaxdefault'+defaultcounter)) {
					systemReplaceInnerHTML('default'+defaultcounter, '', '');
					defaultcounter++;
				}
				//} else {
				//	for (var ID in publications) {
				//		if (parseInt(ID).toString() == ID) {
				//			systemXmlHttp.request('GET', systemCreateContentUrl(publications[ID], true), true, null, null, '', this, systemReplaceContent);
				//		}
				//	}
				//}
			}
			if ((newHash == '') || (newHash == '#')) {
				window.location.reload();
			}
		}
		curHash = newHash;
	}
}

function systemRemoveElementFromHash(add, currentHash) {
	tempHashArray = currentHash.substr(1).split(/\|/gi);			
	for (i=0;i<tempHashArray.length;i++) {
		if (tempHashArray[i] == add) {
			tempHashArray.splice(i,1);
			i--;		
		} else {
			if (tempHashArray[i].indexOf('?') == -1) {
				tempHashArray2 = tempHashArray[i].split('/');
				tempAddArray = add.split('/');			
				for (j=2;j<tempAddArray.length;j++) {
					if ((systemModules.find(tempAddArray[1]) == -1) && (tempAddArray[j] != tempHashArray2[j]) && ((tempAddArray[1] == tempHashArray2[1]))) {
						tempHashArray.splice(i,1);
						i--;
						break;
					}
				}
			} else {
				if (add.indexOf('?') != -1) {
					tempHashArray2 = tempHashArray[i].substr(1).split('&');
					tempAddArray = add.split('&');			
					for (j=0;j<tempAddArray.length;j++) {
						if ((systemModules.find(tempAddArray[1]) == -1) && tempAddArray[j] != tempHashArray2[j]) {
							tempHashArray.splice(i,1);
							i--;
							break;
						}
					}
				}
			}	
		}		
	}
	return tempHashArray.join('|');
}

function systemPrepareLoadContent(e) {
	startRestoreContent = false;
	var targ;
	if (!e) {
		var e = window.event;
	}
	if (e.target) { 
		targ = e.target;
	} else if (e.srcElement) { 
		targ = e.srcElement;
	}
	if (targ.nodeType == 3) {// defeat Safari bug
		targ = targ.parentNode;
	}
	do {
		if (targ != null) {
			if (targ.nodeName == 'A') {
				var curHref = targ.href;
			} else {
				targ = targ.parentNode;
			}
		}
	} while ((!curHref) && (targ != null) && (targ != '') && (targ != 'undefined'));
	var tempHash = window.location.hash;
	var root = window.location.href;
	var rootIndex = root.indexOf('#') == -1 ? root.length : root.indexOf('#') ;
	root = root.substring(0,rootIndex);
	if (curHref && (curHref.toUpperCase().indexOf('JAVASCRIPT') == -1)) {
		if (curHref.indexOf('#') == -1) {
			var curHrefIndex = curHref.length;
			var curHref = curHref.substring(0, curHrefIndex);
		} else {
			var curHrefIndex = curHref.indexOf('#') ;
			if (curHrefIndex > curHref.length) {
				var curHref = curHref.substring(0, curHrefIndex);
				if (curHref != root) {
					return true;
				}
			} else {
				return true;
			}
		}
		
		var addArray = root.split('.');
		if (addArray[addArray.length-1].substr(-3) == 'web' || addArray[addArray.length-1].substr(-4) == 'html') {
			addArray.pop();
		} 
		root = addArray.join('.'); 
		var rootIndex = root.indexOf('#') == -1 ? root.length : root.indexOf('#') ;
	
		var curHrefIndex = curHref.indexOf('#') == -1 ? curHref.length : curHref.indexOf('#') ;
		var targetHash = curHref.substring(curHrefIndex, curHref.length);
		if (targetHash == '#') {
			targ.href = window.location.href;
			return true;
		}
		if ((targetHash.length > 0) && (targetHash.indexOf('publish') == -1)) {
			var add = targetHash.substr(1);
			var addArray = add.split('.');
			if (addArray[addArray.length-1].substr(-3) == 'web' || addArray[addArray.length-1].substr(-4) == 'html') {
				addArray.pop();
			} 
			add = addArray.join('.'); 
			if (add.length) {
				var addArray = add.split('|');
				for (x=0;x<addArray.length;x++) {
					tempHash = systemRemoveElementFromHash(addArray[x], tempHash);
				}
				//if (tempHash.substr(-3) == 'web' || tempHash.substr(-4) == 'html') {
					var addHash = (add.indexOf('#') == -1 ) ? true : false ;
					curHash = add;
					targ.href = root+(addHash ? '#' : '')+curHash;
					window.location.hash = curHash;
				//} else {
				//	var addHash = (tempHash.indexOf('#') == -1 ) ? true : false ;
				//	curHash = (tempHash ? tempHash+'|' : '')+add;
				//	targ.href = root+(addHash ? '#' : '')+curHash;
				//	window.location.hash = curHash;
				//}
				
			} else {
				targ.href = root;
				curHash = '#';
				window.location.hash = curHash;
			}
		} else {
			curHref = curHref.substring(0,curHrefIndex);
			root = root.substring(0,rootIndex);
			if (curHref.indexOf(root) != -1) {
				var add = curHref.substring(rootIndex, curHref.length);
				var addArray = add.split('.');
				if (addArray[addArray.length-1].substr(-3) == 'web' || addArray[addArray.length-1].substr(-4) == 'html') {
					addArray.pop();
				} 
				add = addArray.join('.'); 
				prevHash[prevHash.length] = curHash;
				if (add.length) {
					tempHash = systemRemoveElementFromHash(add, tempHash);
					//if (tempHash.substr(-3) == 'web' || tempHash.substr(-4) == 'html') {
						var addHash = (targ.href.indexOf('#') == -1 ) ? true : false ;
						curHash = add;
						targ.href = root+(addHash ? '#' : '')+curHash;
						window.location.hash = curHash;
					//} else {
					//	var addHash = (tempHash.indexOf('#') == -1 ) ? true : false ;
					//	curHash = (tempHash ? tempHash+'|' : '')+add;
					//	targ.href = root+(addHash ? '#' : '')+curHash;
					//	window.location.hash = curHash;
					//}
					
				} else {
					targ.href = root;
					curHash = '#';
					window.location.hash = curHash;
				}
				if (systemIsIE()) {
					iframe = document.getElementById('ajaxIframe');
					startRestoreContent = false;
					iframe.setAttribute('onload', 'javascript:startRestoreContent = true;');
					iframe.src = window.location.protocol+'//'+window.location.hostname+'/ajax.php?hash='+curHash;
				}
				//newContentUrl = systemCreateContentUrl('', true);
				//if (newContentUrl.length) {
					//for (i=0;i<newContentUrl.length;i++) {
				//		systemXmlHttp.request('GET', newContentUrl[newContentUrl.length-1], true, null, null, '', this, systemReplaceContent);
					//}
				//}
			}
		}
	}
}

function systemReplaceContent(req, url) {
	var responseXML = req.responseXML;
	if( responseXML == null) {
		var data = 0;
		var location = 0;
	} else {
		var data = responseXML.getElementsByTagName('data').item(0).firstChild.nodeValue;
		var location = responseXML.getElementsByTagName('location').item(0).firstChild.nodeValue;
		var remove = responseXML.getElementsByTagName('remove').item(0).firstChild.nodeValue;
		var newHash = window.location.hash;
		
		
		if (remove != 0) {
			if (lastReplaceID) {
				defaultContentUrl = systemCreateContentUrl(publications[lastReplaceID], false);
				if (newContentUrl.partiallyfind(defaultContentUrl) == -1 && (defaultContentUrl.replace('/api/get/', '/go/') != window.location.href.substr(0,defaultContentUrl.replace('/api/get/', '/go/').length))) {
					systemXmlHttp.request('GET', systemCreateContentUrl(publications[lastReplaceID]+'?teaser=false', true), true, null, null, '', this, systemReplaceContent);
				}
			}
//			for (var ID in publications) {
//				if (parseInt(ID).toString() == ID) {
//					defaultContentUrl = systemCreateContentUrl(publications[ID], false);
//					if (newContentUrl.partiallyfind(defaultContentUrl) == -1 && (defaultContentUrl.replace('/api/get/', '/go/') != window.location.href.substr(0,defaultContentUrl.replace('/api/get/', '/go/').length))) {
//						systemXmlHttp.request('GET', systemCreateContentUrl(publications[ID]+'?teaser=false', true), true, null, null, '', this, systemReplaceContent);
//					}
//				}
//			}
			systemReplaceInnerHTML(remove, '', url);
		}
		lastReplaceID = remove;
		
		systemReplaceInnerHTML(location, data, url);
		return;
	}
	 
}

function systemReplaceContentIframe(url) {
	var iframe = document.getElementById('ajaxFilePostIframe');
	if (iframe.contentDocument) {
		var responseXML = iframe.contentDocument;
	} else if (iframe.contentWindow) {
		var responseXML = iframe.contentWindow.document;
	} else {
		var responseXML = window.frames['ajaxFilePostIframe'].document;
	}
	if( responseXML == null) {
		var data = 0;
		var location = 0;
	} else {
		if (systemIsIE()) {
			var responseXML = responseXML.XMLDocument; 
		}
		if (systemIsChrome()) {
			var data = '';
			for (var i=0; i < responseXML.getElementsByTagName('data').item(0).childNodes.length; i++) {
				data += responseXML.getElementsByTagName('data').item(0).childNodes[i].nodeValue;
			}
		} else {
			var data = responseXML.getElementsByTagName('data').item(0).firstChild.nodeValue;
		}
		var location = responseXML.getElementsByTagName('location').item(0).firstChild.nodeValue;
		var remove = responseXML.getElementsByTagName('remove').item(0).firstChild.nodeValue;
		
		if (remove != 0) {
			if (lastReplaceID) {
				defaultContentUrl = systemCreateContentUrl(publications[lastReplaceID], false);
				if (newContentUrl.partiallyfind(defaultContentUrl) == -1 && (defaultContentUrl.replace('/api/get/', '/go/') != window.location.href.substr(0,defaultContentUrl.replace('/api/get/', '/go/').length))) {
					systemXmlHttp.request('GET', systemCreateContentUrl(publications[lastReplaceID]+'?teaser=false', true), true, null, null, '', this, systemReplaceContent);
				}
			}
//			for (var ID in publications) {
//				if (parseInt(ID).toString() == ID) {
//					defaultContentUrl = systemCreateContentUrl(publications[ID], false);
//					if (newContentUrl.partiallyfind(defaultContentUrl) == -1 && (defaultContentUrl.replace('/api/get/', '/go/') != window.location.href.substr(0,defaultContentUrl.replace('/api/get/', '/go/').length))) {
//						systemXmlHttp.request('GET', systemCreateContentUrl(publications[ID]+'?teaser=false', true), true, null, null, '', this, systemReplaceContent);
//					}
//				}
//			}
			systemReplaceInnerHTML(remove, '', url);
		}
		lastReplaceID = remove;
		systemReplaceInnerHTML(location, data, url);
		return;
	}
}

