var receiveReq = getXmlHttpRequestObject();
var receiveReq_keepalive = getXmlHttpRequestObject();
var keep_alive_url = "ajax/keepalive.php";
var do_keep_alive = true;
var window_height = 0;
var window_width = 0;
var current_popup = "";
var header_written = false;

/** Detecting browser **/
if(navigator.userAgent.indexOf('Trident') != -1 || navigator.userAgent.indexOf('MSIE') != -1){var browser = "ie";}
else{var browser = "not ie";}
/** And browser version **/
if(navigator.appVersion.indexOf('MSIE 8.0') != -1){var browser_version = 8;}
else if(navigator.appVersion.indexOf('MSIE 7.0') != -1){var browser_version = 7;}
else if(navigator.appVersion.indexOf('MSIE 6.0') != -1){var browser_version = 6;}
else{var browser_version = 'not ie';}

/** Can be used when you want to use window.onload from several different files **/
/** What it does is to continually increase the amount of information stored in window.onload, and when we're done loading, execute it **/
/** Example: window.onload = joinFunctions(window.onload, myNewFunction ); **/
function joinFunctions(function1, function2) 
{
    return function() {
        if (function1)
            function1();
        if (function2)
            function2();
    }
}

function createOverlay(action, div_width, div_height)
{
	if (receiveReq.readyState == 4 || receiveReq.readyState == 0) 
	{
		var body_dom = document.getElementsByTagName('body')[0];
		
		/** Updating window dimensions **/
		updateWindowDimensions();
		
		/** We make sure that the correct styles are set **/
		writeOverlayHeader();
				
		/** We create the protective layer that will make sure that the user cannot click on anything except our overlay **/
		var protective_div = document.createElement('div');
		protective_div.id = 'protective_div';				
		protective_div.className = 'opaque';
		
		/** Styling the protective div **/
		if(BrowserDetect.browser != "Explorer")
		{
			protective_div.style.top = "0px";
			protective_div.style.position = "fixed";			
		}
				
		protective_div.style.left = "0px";		
		protective_div.style.width = "100%";
		protective_div.style.height = "100%";
		protective_div.style.backgroundColor = "#000000";
		protective_div.style.zIndex = "999998";
		protective_div.style.opacity = ".5";
		
		/** Prepending it to the body **/
		body_dom.insertBefore(protective_div, document.body.childNodes[0]);
		
		/** Creating an overlay **/		
		var overlay_div = document.createElement('div');
		overlay_div.id = 'overlay_div';
		
		/** Now to style the div **/
		if(div_width == "")
		{
			div_width = 900;
		}
		
		if(div_height == "")
		{
			div_height = 600;
		}
		
		overlay_div.style.position = "absolute";
		overlay_div.style.left = (window_width/2)-(div_width/2)+"px";
		overlay_div.style.top = (window_height/2)-(div_height/2)+"px";
		if(parseInt(overlay_div.style.top) < 0)
		{
			overlay_div.style.top = "0px";
		}		
		overlay_div.style.border = "2px solid black";
		overlay_div.style.backgroundColor = "#667E96";
		overlay_div.style.width = div_width+"px";
		overlay_div.style.height = div_height+"px";
		overlay_div.style.zIndex = "999999";
		
		/** Close button **/
		overlay_div.innerHTML  = '<div align="right"><span onclick="closeOverlay(); if(typeof specificOverlayCloseFunction == \'function\'){specificOverlayCloseFunction(\''+action+'\');}" style="cursor: pointer;">[X]</span></div>';
		/** Loading animation **/
		overlay_div.innerHTML += '<div id="overlay_data" align="center" style="height:'+(div_height-15)+'px; width:'+div_width+'px;overflow-y:auto;overflow-x:hidden;"><img src="images/layout/ajax-loader_large.gif"></div>';
		
		/** Now we append it to the body **/
		body_dom.appendChild(overlay_div);
		
		/** Getting the data **/
		if(action == undefined){action = "";}
		else{action = "?action="+action;}
		
		receiveReq.open('GET', ajax_file_path+action, true);
		receiveReq.onreadystatechange = handleCreateOverlay;
		receiveReq.send(null);
	}		
}

function handleCreateOverlay()
{
	if (receiveReq.readyState == 4)
	{
		var data = JSON.parse(receiveReq.responseText);
		var obj = document.getElementById("overlay_data");
		obj.innerHTML = html_entity_decode(data);		
	}
}

function writeOverlayHeader()
{
	if(!header_written)
	{
		var head_dom = document.getElementsByTagName('head')[0];	
		/** If this browser is IE we write a special header that will make our protective layer work properly **/
		if(BrowserDetect.browser == "Explorer")
		{			
			var style_element = document.createElement('style');
			var style_rules = document.createTextNode("#protective_div{position: absolute;top: expression( ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ) + 'px' );} .opaque{filter: alpha(opacity=50);}");
			style_element.type = 'text/css';
			if(style_element.styleSheet){style_element.styleSheet.cssText = style_rules.nodeValue;}
			else{style_element.appendChild(style_rules);}
			head_dom.appendChild(style_element);
		}	
		
		header_written = true;	
	}
}

function closeOverlay()
{
	removeElementFromDom("overlay_div");
	removeElementFromDom("protective_div");
}

function removeElementFromDom(id_or_dom_element)
{
	if(typeof(id_or_dom_element) != 'object')
	{
		id_or_dom_element = document.getElementById(id_or_dom_element);
	}
	
	if(id_or_dom_element != undefined)
	{
		id_or_dom_element.parentNode.removeChild(id_or_dom_element);
	}
}

function remObj(id_or_dom_element)
{
	removeElementFromDom(id_or_dom_element);
}

function updateWindowDimensions()
{	
	if (parseInt(navigator.appVersion)>3) 
	{
		if (navigator.appName=="Netscape") 
		{
			window_width = window.innerWidth;
			window_height = window.innerHeight;
		}
		if (navigator.appName.indexOf("Microsoft")!=-1) 
		{
			window_width = document.body.offsetWidth;
			window_height = document.body.offsetHeight;
		}
	}
//	window_height = document.documentElement.clientHeight;
//	window_width = document.documentElement.clientWidth;
}

function popupWindow(theURL, winName, width, height) 
{	
	var features = "width="+width+", height="+height;
	/** We make sure that the popup opens in the middle of the users screen **/
	updateWindowDimensions();
	var top = (window_height/2)-(height/2);
	var left = (window_width/2)-(width/2);	
	features += ", top="+top+", left="+left;
	
	current_popup = window.open(theURL, winName, features);	
	if(current_popup == null)
	{
		/** Popup was catched by a popup blocker **/
		alert("Popup caught by popup blocker");
	}
	else
	{
		if(typeof popupSpecificFunction == 'function')
		{
			window.onfocus = popupSpecificFunction;
		}
		current_popup.focus();				
	}	
}

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

function switchVisibiltyOfTheseObjects(obj_to_show, obj_to_hide, focus_this_object)
{
	if(typeof obj_to_show != "object")
	{
		obj_to_show = document.getElementById(obj_to_show);
	}
	
	if(typeof obj_to_hide != "object")
	{
		obj_to_hide = document.getElementById(obj_to_hide);
	}
	
	obj_to_show.style.display = 'inline';
	obj_to_hide.style.display = 'none';
	
	if(focus_this_object != undefined)
	{		
		if(typeof focus_this_object != "object")
		{
			focus_this_object = document.getElementById(focus_this_object);
		}	
		focus_this_object.focus();
//		focus_this_object.onblur = function()
//		{
//			switchVisibiltyOfTheseObjects(obj_to_hide, obj_to_show);
//		};
	}
}

function genericAjaxCall(ajax_script_string, function_to_call_on_ready_state_change)
{
	if (receiveReq.readyState == 4 || receiveReq.readyState == 0) 
	{		
		receiveReq.open('GET', ajax_script_string, true);
		receiveReq.onreadystatechange = function()
		{
			if(receiveReq.readyState == 4 && function_to_call_on_ready_state_change != undefined)
			{
				function_to_call_on_ready_state_change();
			}
		}
		receiveReq.send(null);
	}		
}

function getXmlHttpRequestObject() 
{
	if (window.XMLHttpRequest) 
	{
		return new XMLHttpRequest();
	}
	else if(window.ActiveXObject) 
	{
		return new ActiveXObject('Microsoft.XMLHTTP');
	}
	else 
	{
		document.getElementById('p_status').innerHTML = 'Status: Cound not create XmlHttpRequest Object.' +	'Consider upgrading your browser.';	
	}
}

function unset(array, item_to_remove)
{
	/** Getting the array position of the element and removing it when found **/
	for(x in array)
	{
		if(array[x] == item_to_remove)
		{
			/** Removing the element from the array **/
			array.splice(x, 1);
			break;
		}
	}
	
	return array;
}

function keepAlive()
{
	var timeout_keepalive = setTimeout("keepAlive()", 170000);
	if (receiveReq_keepalive.readyState == 4 || receiveReq_keepalive.readyState == 0) 
	{
		ajaxRequest("GET",keep_alive_url);
		receiveReq_keepalive.open('GET', keep_alive_url, true);
		receiveReq_keepalive.send(null);
	}
}

if(do_keep_alive)
{
	keepAlive();
}

function getPositionOfObject(obj) 
{
	return findPosX(obj)+";"+findPosY(obj);
}

function findPosX(obj) 
{
	var curleft = 0;
	if (obj) {
		if (obj.offsetParent) {
			while (obj.offsetParent) {
				curleft += obj.offsetLeft
				obj = obj.offsetParent;
			}
		}
		else if (obj.x) {
			curleft += obj.x;
		}
	}
	return curleft;
}

function findPosY(obj) 
{
	var curtop = 0;
	if (obj) {
		if (obj.offsetParent) {
			while (obj.offsetParent) {
				curtop += obj.offsetTop
				obj = obj.offsetParent;
			}
		}
		else if (obj.y) {
			curtop += obj.y;
		}
	}
	return curtop;
}

function ajaxRequest(method, url, function_to_call_on_return, send_body)
{
	if(method != undefined)
	{		
		if(send_body == undefined)
		{
			send_body = null;
		}
		
		/** Creating a new object **/
		var ajax_request_object = getXmlHttpRequestObject();
		
		ajax_request_object.open(method, url, true);
		/** Setting the onreadystate function **/
		ajax_request_object.onreadystatechange = function(){ajaxRequestObjectReturn(ajax_request_object, function_to_call_on_return)};
		/** If we're dealing with a post we need to set the headers **/
		if(method.toLowerCase() == 'post')
		{			
			ajax_request_object.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			ajax_request_object.setRequestHeader("Content-length", send_body.length);
			ajax_request_object.setRequestHeader("Connection", "close");
		}
		/** Submitting the request **/
		ajax_request_object.send(send_body);
	}
}

var ajax_request_data = "";
var ajax_request_obj = null;
function ajaxRequestObjectReturn(request_object, function_to_call)
{
	if (request_object.readyState == 4) 
	{		
		ajax_request_data = request_object.responseText;
		ajax_request_obj = request_object;
		if(typeof function_to_call == 'function')
		{
			function_to_call();
		}
		/** Destroying the object **/
		request_object = null;
	}
}

function realCreateOverlay(data)
{
	var body_dom = document.getElementsByTagName('body')[0];
	
	/** Creating an overlay **/		
	var overlay_div = document.createElement('div');
	overlay_div.id = 'overlay_div';
	
	/** A few styles **/
	writeOverlayHeader();
	if(browser != 'ie')
	{		
		overlay_div.style.position = "fixed";
	}
	overlay_div.style.zIndex = "999999";
	
	/** Now we append it to the body **/
	body_dom.appendChild(overlay_div);
	
	/** Inserting the data **/
	if(data != undefined)
	{
		overlay_div.innerHTML = data;	
	}

	/** Starting the onresize function **/
	if(browser != 'ie')
	{
		window.onresize = function(){centerOverlay();};
	}
	centerOverlay();
}

function centerOverlay()
{
	if(browser != 'ie')
	{
		var obj = getElement('overlay_div');
		
		/** Updating window dimensions **/
		updateWindowDimensions();
				
		/** Getting objects dimensions **/
		var width = obj.offsetWidth;
		var height = obj.offsetHeight;		
		
		obj.style.left 	= (window_width/2)-(width/2)+"px";
		obj.style.top 	= (window_height/2)-(height/2)+"px";
		
		if(parseInt(obj.style.top) < 0)
		{
			obj.style.top = '0px';
		}
		if(parseInt(obj.style.left) < 0)
		{
			obj.style.left = '0px';
		}
	}
}

var overlay_header_written = false;

function writeOverlayHeader()
{
	if(!overlay_header_written)
	{		
		/** If this browser is IE we write a special header that will make our protective layer work properly **/
		if(browser == "ie")
		{			
			var head_dom = document.getElementsByTagName('head')[0];
			var style_element = document.createElement('style');
			var style_rules = document.createTextNode("#overlay_div{position: absolute; top: expression( ieCssOverlay('top') ); left: expression( ieCssOverlay('left') ); }");
			style_element.type = 'text/css';
			if(style_element.styleSheet){style_element.styleSheet.cssText = style_rules.nodeValue;}
			else{style_element.appendChild(style_rules);}
			head_dom.appendChild(style_element);
		}	
		
		overlay_header_written = true;	
	}	
}

function ieCssOverlay(variable)
{
	var obj = getElement('overlay_div');
			
	/** Getting objects dimensions **/
	var width = obj.offsetWidth;
	var height = obj.offsetHeight;
	
	if(variable == 'top')
	{
		var return_variable = ((document.body.clientHeight/2) - (height/2)) + ( document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ) + 'px';
	}
	else
	{
		var return_variable = ((document.body.clientWidth/2) - (width/2)) + ( document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ) + 'px';
	}
	
	if(parseInt(return_variable) < 0)
	{
		return_variable = '0px';
	}
	return return_variable;	
}

function getElement(id_or_dom_element)
{
	if(typeof(id_or_dom_element) != 'object')
	{
		id_or_dom_element = document.getElementById(id_or_dom_element);
	}
	
	if(typeof(id_or_dom_element) != 'object')
	{
		return false;
	}
	else
	{
		return id_or_dom_element;	
	}
}

function hideSelects()
{
	var select_objects = document.getElementsByTagName("select");	
	for(var i=0;i<select_objects.length;i++)
	{
		select_objects[i].style.display = 'none';
	}
}

function showSelects()
{
	var select_objects = document.getElementsByTagName("select");	
	for(var i=0;i<select_objects.length;i++)
	{
		select_objects[i].style.display = 'inline';
	}
}

function fadeElement(obj, current_fade, final_fade, direction, function_to_execute_when_done)
{	
	obj = getElement(obj);
	if(direction == undefined)
	{
		direction = 'in';
	}
	
	/** Setting the fade to current_fade **/
	if(browser == 'ie')
	{
		obj.filters[0].opacity = current_fade;
	}
	else
	{
		obj.style.opacity = current_fade/100;
	}
	
	if(direction == 'in')
	{
		/** Increasing the current_fade by 10% **/
		current_fade += 10;
		
		if(current_fade <= final_fade)
		{
			/** We have some more fading to do **/
			setTimeout(function(){fadeElement(obj, current_fade, final_fade, direction, function_to_execute_when_done)}, 25);
		}
		else if(typeof function_to_execute_when_done == 'function')
		{
			function_to_execute_when_done();
		}
	}
	else
	{
		/** Decreasing the current_fade by 10% **/
		current_fade -= 10;
		
		if(current_fade >= final_fade)
		{
			/** We have some more fading to do **/
			setTimeout(function(){fadeElement(obj, current_fade, final_fade, direction, function_to_execute_when_done)}, 25);
		}
		else if(typeof function_to_execute_when_done == 'function')
		{
			function_to_execute_when_done();
		}
	}
}

function createVeil(final_fade, do_fade, color, function_to_execute_when_done)
{
	var body_dom = document.getElementsByTagName('body')[0];

	/** We make sure that the correct styles are set **/
	writeVeilHeader();
	
	/** Updating window dimensions **/
	updateWindowDimensions();
	
	/** We create the protective layer that will make sure that the user cannot click on anything except our overlay **/
	var protective_div = document.createElement('div');
	protective_div.id = 'protective_div';
	protective_div.style.display = 'inline';
	protective_div.className = 'opaque';
	
	/** Styling the protective div **/
	if(browser != "ie")
	{
		protective_div.style.top = "0px";
		protective_div.style.left = "0px";
		protective_div.style.position = "fixed";
		protective_div.style.width = "100%";
	}
				
	protective_div.style.height = "100%";
	
	if(color == undefined)
	{
		color = "#000000";
	}
	protective_div.style.backgroundColor = color;
	protective_div.style.zIndex = "999998";
	protective_div.style.opacity = 0;
	
	/** Prepending it to the body **/
	body_dom.insertBefore(protective_div, document.body.childNodes[0]);	
	
	if(browser_version == 6)
	{
		hideSelects();
	}
	
	if(final_fade != undefined)
	{
		if(do_fade != undefined && do_fade)
		{
			fadeElement(protective_div, 0, final_fade, 'in', function_to_execute_when_done);
		}
		else
		{
			if(browser == 'ie')
			{
				protective_div.filters[0].opacity = final_fade;
			}
			else
			{
				protective_div.style.opacity = final_fade/100;
			}
			
			if(typeof function_to_execute_when_done == 'function')
			{
				function_to_execute_when_done();
			}
		}
	}
	else
	{
		if(browser == 'ie')
		{
			protective_div.filters[0].opacity = 50;
		}
		else
		{
			protective_div.style.opacity = 0.5;
		}
		
		if(typeof function_to_execute_when_done == 'function')
		{
			function_to_execute_when_done();
		}		
	}
	
	if(browser == 'ie')
	{
		setDocumentHeightAndWidth();
		protective_div.onmousewheel = document.onmousewheel = function(){limitIeScroll(event)};
	}
		
}

function limitIeScroll(event)
{	
	if(event.wheelDelta < 0)
	{
		if(document_total_height < (document.body.scrollTop*1+document.body.clientHeight*1))
		{
			event.returnValue = false;
		}		
	}
}

var veil_header_written = false;

function writeVeilHeader()
{
	if(!veil_header_written)
	{		
		/** If this browser is IE we write a special header that will make our protective layer work properly **/
		if(browser == "ie")
		{			
			var head_dom = document.getElementsByTagName('head')[0];
			var style_element = document.createElement('style');
			var style_rules = document.createTextNode("#protective_div{position: absolute; width: expression( ieCssVeilWidth() ); top: expression( ieCssVeilPositions('top') ); left: expression( ieCssVeilPositions('left') ); } .opaque{filter: alpha(opacity=0);}");
			style_element.type = 'text/css';
			if(style_element.styleSheet){style_element.styleSheet.cssText = style_rules.nodeValue;}
			else{style_element.appendChild(style_rules);}
			head_dom.appendChild(style_element);
		}	
		
		veil_header_written = true;	
	}
}

function ieCssVeilPositions(variable)
{
	if(variable == 'top')
	{
		return document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop + 'px';
	}
	else
	{
		return document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft + 'px';
	}
}

function ieCssVeilWidth()
{
	return document.body.clientWidth+'px';
}

function realCloseOverlay(fadeout)
{
	removeElementFromDom("overlay_div");
	removeElementFromDom("overlay_div_at_object");
	var protective_div = getElement('protective_div');
	if(fadeout != undefined && fadeout)
	{		
		var current_fade = 0;
		
		if(browser == 'ie')
		{
			current_fade = protective_div.filters[0].opacity;
		}
		else
		{
			current_fade = protective_div.style.opacity*100;
		}
		
		fadeElement(protective_div, current_fade, 0, 'out', function(){ removeElementFromDom("protective_div"); });
	}
	else
	{		
		removeElementFromDom("protective_div");
	}

	
	if(browser_version == 6)
	{
		showSelects();
	}
	
	
	if(browser != 'ie')
	{
		/** Stopping the onresize function **/
		window.onresize = "";
	}
	else
	{
		if(protective_div != undefined)
		{
			/** Stopping the onscroll function **/
			protective_div.onmousewheel = document.onmousewheel = '';
		}
	}
}

var document_total_height = "";
var document_total_width = "";

function setDocumentHeightAndWidth()
{
	var body = document.body, html = document.documentElement;
	
	document_total_height = Math.max( body.scrollHeight, body.offsetHeight,  html.clientHeight, html.scrollHeight, html.offsetHeight );
	document_total_width = Math.max( body.scrollWidth, body.offsetWidth,  html.clientWidth, html.scrollWidth, html.offsetWidth );
}

function toggleDisplayOfObject(obj)
{
	var obj = getElement(obj);
	if(obj.style.display == 'none')
	{
		obj.style.display = 'inline';
	}
	else
	{
		obj.style.display = 'none';
	}
}

function fadeInFadeOutAndRemove(data, time_to_display, fade_in_time, fade_out_time, position, top, left, function_to_run_when_done)
{
	if(time_to_display == undefined)
	{
		time_to_display = 2000;
	}
	if(fade_in_time == undefined)
	{
		fade_in_time = 75;
	}
	if(fade_out_time == undefined)
	{
		fade_out_time = 75;
	}
	
	if(position == undefined)
	{
		position = 'fixed';
	}
	
	createOverlay(data, position, top, left);
	fadeElement("overlay_div", 0, 100, "in", function(){setTimeout(function(){fadeElement("overlay_div", 100, 0, "out", function(){remObj("overlay_div"); if(function_to_run_when_done != undefined){function_to_run_when_done();}}, fade_out_time);}, time_to_display);}, fade_in_time);	
}
