/**
	This script was created by Lasse R. Brock
	 
	The purpose is to provide generic javascript functions that can be used over and over 
	 
	The Ajax Queue System Example:
	 
	[Here we build the request]
		var function_to_call_before_sending = loading();
		var function_to_call_on_return = handleGetMap();
		ajaxQueueCancelThese('map_data'); (Only used if nessesary to cancel other requests of the same tag in the queue)
		ajaxQueueAdd('GET', url, 'map_data', function_to_call_before_sending, function_to_call_on_return, null);
	[Here we recieve the request data]
	****** Notice the use of receiveReq_ajax_queue ******
	function handleGetMap() 
	{	
		var data = receiveReq_ajax_queue.responseText;
	}
**/
var receiveReq = getXmlHttpRequestObject();
var window_height = 0;
var window_width = 0;
var window_scroll_y = 0;
var window_scroll_x = 0;
var current_popup = "";

/** 
	Required JS:
	php.js is required
**/

window.onload = joinFunctions(window.onload, function(){if(typeof is_numeric != 'function')
{
	alert("Husk at include php.js");
}})

/** 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();
    }
}

/** 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';}

var receiveReq_ajax_queue = getXmlHttpRequestObject();
var ajax_queue_array = new Array();
var ajax_queue_timer = "";
var ajax_queue_current_tag = undefined;
var ajax_queue_request_validity = true;

function ajaxQueue()
{	
	if(ajax_queue_array.length > 0)
	{	
		/** We run the next element from the queue **/	
		if (receiveReq_ajax_queue.readyState == 4 || receiveReq_ajax_queue.readyState == 0)
		{		
			/** Running and removing the next element **/
			var ajax_data = ajax_queue_array.shift();
						
			/** Executing the functions **/
			ajax_data[3]();
			receiveReq_ajax_queue.open(ajax_data[0], ajax_data[1], true);
			/** Setting the onreadystate function **/
			receiveReq_ajax_queue.onreadystatechange = function(){ajaxQueueObjectReturn(ajax_data[4])};
			/** If we're dealing with a post we need to set the headers **/
			if(ajax_data[0] == 'post')
			{
				receiveReq_ajax_queue.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				receiveReq_ajax_queue.setRequestHeader("Content-length", ajax_data[5].length);
				receiveReq_ajax_queue.setRequestHeader("Connection", "close");
			}
			/** Submitting the request **/
			receiveReq_ajax_queue.send(ajax_data[5]);
			/** Setting the current tag so that we may invalidate it later if we need to **/
			ajax_queue_current_tag = ajax_data[2];
		}
	}
		
	if(ajax_queue_array.length > 0)
	{
		/** If there's data in the queue we call this function again in 0.5 second **/
		clearTimeout(ajax_queue_timer);
		ajax_queue_timer = setTimeout("ajaxQueue();", 500);
	}
}

function ajaxQueueAdd(method, url, tag, function_to_call_before_sending, function_to_call_on_return, send_body)
{
	if(method != undefined)
	{		
		if(send_body == undefined)
		{
			send_body = null;
		}
		/** Adding the object to the queue **/
		ajax_queue_array.push(new Array(method, url, tag, function_to_call_before_sending, function_to_call_on_return, send_body));
	}
	
	ajaxQueue();
}

var ajax_queue_request_data = "";
var ajax_queue_request_obj = null;

function ajaxQueueObjectReturn(function_to_call)
{
	if (receiveReq_ajax_queue.readyState == 4) 
	{		
		ajax_queue_current_tag = undefined;
		if(ajax_queue_request_validity)
		{
			ajax_queue_request_data = receiveReq_ajax_queue.responseText;
			ajax_queue_request_obj = receiveReq_ajax_queue;
			if(typeof function_to_call == 'function')
			{
				function_to_call();
			}
		}
		else
		{
			ajax_queue_request_validity = true;
		}
	}
}

function ajaxQueueCancelThese(tag)
{	
	for(x in ajax_queue_array)
	{
		if(ajax_queue_array[x][2] == tag)
		{			
			ajax_queue_array.splice(x,1);
		}
	}
	
	if(ajax_queue_current_tag == tag)
	{
		ajax_queue_request_validity = false;
		ajax_queue_current_tag = undefined;
	}	
}

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 == '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 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.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 createOverlayAtObject(obj, data, offset_x, offset_y)
{
	var obj = getElement(obj);
	var body_dom = document.getElementsByTagName('body')[0];
	
	if(!is_numeric(offset_x))
	{
		offset_x = 0;
	}
	if(!is_numeric(offset_y))
	{
		offset_y = 0;
	}
	
	/** Creating an overlay **/		
	var overlay_div = document.createElement('div');
	overlay_div.id = 'overlay_div_at_object';
	
	/** Positioning the overlay **/
	var obj_positions = getPositionOfObject(obj).split(";");
	
	overlay_div.style.position = "absolute";
	overlay_div.style.left = (obj_positions[0]*1+offset_x)+"px";
	overlay_div.style.top = (obj_positions[1]*1+offset_y)+"px";
	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;	
	}
}

function createOverlay(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 closeOverlay(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 = '';
		}
	}
}

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 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 removeElementFromDom(id_or_dom_element)
{
	id_or_dom_element = getElement(id_or_dom_element);
	
	if(id_or_dom_element != undefined)
	{
		id_or_dom_element.parentNode.removeChild(id_or_dom_element);
	}
}

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 updateWindowDimensions()
{	
	if(browser == "ie")
	{
		window_scroll_y = document.body.scrollTop;
		window_scroll_x = document.body.scrollLeft;				
		window_height 	= document.body.clientHeight;
		window_width 	= document.body.clientWidth;
	}
	else
	{
		window_scroll_y = window.pageYOffset;
		window_scroll_x = window.pageXOffset;
		window_width 	= window.innerWidth;
		window_height 	= window.innerHeight;		
	}
}

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 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();				
	}	
}

/** Switches the display of the two provided objects, if the 3rd parameter is sent that object is given focus in the end **/
function sdoto(obj_to_show, obj_to_hide, focus_this_object)
{
	switchDisplayOfTheseObjects(obj_to_show, obj_to_hide, focus_this_object);
}

function switchDisplayOfTheseObjects(obj_to_show, obj_to_hide, focus_this_object)
{
	obj_to_show = getElement(obj_to_show);
	obj_to_hide = getElement(obj_to_hide);
	
	obj_to_show.style.display = 'inline';
	obj_to_hide.style.display = 'none';
	
	if(focus_this_object != undefined)
	{		
		focus_this_object = getElement(focus_this_object);
		focus_this_object.focus();
	}	
}

/** Switches the visibility of the provided object **/
function svote(obj)
{
	switchVisibilityOfThisElement(obj);
}

function switchVisibilityOfThisElement(obj)
{
	obj = getElement(obj);
	if(obj.style.visibility == 'hidden'){obj.style.visibility = 'visible';}	
	else{obj.style.visibility = 'hidden';}	
}

function getXmlHttpRequestObject() 
{
	if (window.XMLHttpRequest) 
	{
		return new XMLHttpRequest();
	}
	else if(window.ActiveXObject) 
	{
		return new ActiveXObject('Microsoft.XMLHTTP');
	}
	else 
	{
		alert('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;
}

window.onload = joinFunctions(window.onload, keepAlive);

function keepAlive()
{ 	
	if(typeof(keep_alive_url) !== 'undefined' && keep_alive_url != "")
	{
		setTimeout("keepAlive()", 600000);
		ajaxRequest('GET', keep_alive_url);
	}
}

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 getSelectValue(select_obj)
{
	var select_obj = getElement(select_obj);
	return select_obj.options[select_obj.selectedIndex].value;
}

function getSelectText(select_obj)
{
	var select_obj = getElement(select_obj);
	return select_obj.options[select_obj.selectedIndex].text;	
}

/** Validation **/
var validation_array = new Array();
function addValidationElement(element_to_validate, type_of_element, alert_on_error, empty_allowed)
{
	if(empty_allowed == undefined)
	{
		empty_allowed = false;
	}
	
	if(alert_on_error == undefined)
	{
		alert_on_error = '';
	}
	
	if(getElement(element_to_validate) && type_of_element != undefined && type_of_element != '')
	{
		validation_array.push(new Array(element_to_validate, type_of_element, alert_on_error, empty_allowed));
	}
}

var validation_error_color = "#D30000";
var validation_ok_color = "";

function doValidation()
{
	var validation_passed = true;

	/** We run through the array, setting all fields to the validation_ok_color **/
	for(x in validation_array)
	{
		if(getElement(validation_array[x][0]))
		{
			var element_to_validate = getElement(validation_array[x][0]);
			var type_of_element = validation_array[x][1];
			
			element_to_validate.style.borderStyle = "";
			element_to_validate.style.borderColor = validation_ok_color;		
		}
	}	
		
	/** Now for the actual validation **/
	for(x in validation_array)
	{
		/** Setting up variables **/
		var element_to_validate = getElement(validation_array[x][0]);
		var type_of_element = validation_array[x][1];
		var alert_on_error = validation_array[x][2];
		var empty_allowed = validation_array[x][3];
		
		if(type_of_element == 'email')
		{						
			var email_validation_string = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/
			
			/** Checks if the element was allowed to be empty **/
			if(empty_allowed && element_to_validate.value == '')
			{
				
			}
			/** Checks if the content is an email **/
			else if(element_to_validate.value.search(email_validation_string) == -1)
			{
				validation_passed = false;
			}
			
		}
		else if(type_of_element == 'text')
		{			
			/** Checks if the element was allowed to be empty **/
			if(empty_allowed && element_to_validate.value == '')
			{
				
			}
			/** Checks if there's content set **/
			else if(element_to_validate.value == "")
			{
				validation_passed = false;
			}			
		}
		else if(type_of_element == 'numeric')
		{
			/** Checks if the element was allowed to be empty **/
			if(empty_allowed && element_to_validate.value == '')
			{
				
			}
			/** Checks if the content is_numeric **/
			else if(!is_numeric(element_to_validate.value))
			{
				validation_passed = false;
			}						
		}
		
		/** Validation failed, we color the field alert the error and stop **/
		if(!validation_passed)
		{
			if(element_to_validate != undefined)
			{
				element_to_validate.focus();
				element_to_validate.style.borderStyle = "solid";
				element_to_validate.style.borderColor = validation_error_color;
			}
						
			if(alert_on_error != '')
			{
				alert(alert_on_error);	
			}			
			break;
		}
	}
	
	return validation_passed;
}

function createSubmitButton(id, value)
{
	var container = getElement(id);
	container.innerHTML = '<input type="submit" value="'+value+'">';
}

/** Deprecated functions **/
function genericAjaxCall(url, function_to_call_on_ready_state_change)
{
	ajaxRequest('GET', url, function_to_call_on_ready_state_change, null);
}
