/*************** START DYNAMIC YRKESKATEGORIER FUNCTIONS *****************/

debugDiv = document.getElementById('debug');

/* Initiates the dropdown lists, sets onchange handlers, fills and enables lbyk dropdown etc. */
/* YrkeskategoriString and ykSelectedIndex are generated in .sol-file under cjSnabbsok */
function initiateYrkeskategorier(yrkeskategoriString, ykSelectedIndex) {
	var ygDropdown = document.getElementById('lbyg');
	var ykDropdown = document.getElementById('lbyk');
	
	/* Set yg variable in lbyg to an array of Yrkeskategorier */
	ygDropdown.yk = createYrkeskategoriArray(yrkeskategoriString);
	
	/* Set event on change of lbyg to run fillYrkeskategorier. fillYrkeskategorier fills lbyk dropdown with new options*/
//	ygDropdown.onchange = fillYrkeskategorier;
	
	/* Fill the lbyk dropdown at pageload time if an lbyg is selected */
	fillYrkeskategorier();
	
	/* Enable or disable lbyk whether a lbyg is selected */
	if (ygDropdown[ygDropdown.selectedIndex].value=='-1') ykDropdown.disabled = true;
	else ykDropdown.disabled = false;
		
	/* Finds and selects the option for the submitted value from the form */
	for (var i=0 ; i<ykDropdown.length ; i++)
		if (ykDropdown[i].value == ykSelectedIndex)
			ykDropdown.selectedIndex = i;
}

/* Fills lbyk-dropdown with new options after removign the old ones */
function fillYrkeskategorier() {
	var ygDropdown = document.getElementById('lbyg');
	var ykDropdown = document.getElementById('lbyk');
	var ygSelectedIndex = ygDropdown[ygDropdown.selectedIndex].value
	
	/* Delete all old select options */
	for (var i=1 ; i<ykDropdown.length ; i=i)
		ykDropdown.options[i] = null;
		
	if (ygSelectedIndex<0) {
		/* Disable lbyk dropdown */
		ykDropdown.selectedIndex = 0;
		ykDropdown.disabled = true;
	} else {
		/* Fill lbyk dropdown with new options */
		/* lbyg.yk was created in initiateYrkeskategorier */
		var a=ygDropdown.yk[ygSelectedIndex]
		ykDropdown.disabled = false;
		
		/* Go through the lbyg.yk array and create the options */
		for (var i=0, len=a.length ; i<len ; i++)
			ykDropdown.options[i+1] = new Option('- '+a[i]['thetitle'], a[i]['ykid']);
	}
}

function createYrkeskategoriArray(yrkeskategoriString) {
		var yk = new Array();
		
		// addNew function adds a new array item
		yk.addNew = pushYrkeskategoriArray;
		
		for (var i=0, a=yrkeskategoriString.split('$'), alen=a.length ; i < alen ; i++) {
			b=a[i].split('|');
			yk.addNew(b[0], b[1], b[2]);
		}
		
		// Returns the filled array
		return yk;
}

function pushYrkeskategoriArray(arrayIndex, optionId, optionTitle) {
	if (this[arrayIndex]==undefined)
		this[arrayIndex] = new Array();
	this[arrayIndex].push ({
		ykid:optionId,
		thetitle:optionTitle
	})
}

/*************** START AJAX FUNCTIONS *****************/

/* Create some global variables */
var httpRequests = new Array();
var searchTimeOut;

// AJAX search variables, not used anymore
/*
var lbyg = document.getElementById('lbyg');
var lbyk = document.getElementById('lbyk');
var lbg = document.getElementById('lbg');
var order = document.getElementById('order');
var orderriktning = document.getElementById('orderriktning');
lbyg.onchange = doSearchOnChangeLbyg;
lbyk.onchange = doSearchOnChange;
lbg.onchange = doSearchOnChange;
*/

function doOpacityAnimation(theDivId) {
	theDiv = document.getElementById(theDivId)
	/* Fetch animation variables from vars set in the Div */
	step = theDiv.opacityStep;
	current = theDiv.opacityCurrent;
	goal = theDiv.opacityGoal;
	/* Clear the active timeout, just in case */ 
	clearTimeout(theDiv.opacityTimeout);
	/* If the goal hasn't been reached, change the opacity and callback to this function */
	if ((step<0 && current>goal) || (step>0 && current<goal)) {
		setOpacity(theDiv, theDiv.opacityCurrent+=step)
		theDiv.opacityTimeout = setTimeout("doOpacityAnimation('"+theDivId+"')", 40);
	}
}

function initiateOpacityAnimation(theDiv, start, step, goal) {
	clearTimeout(theDiv.opacityTimeout);
	theDiv.opacityCurrent = start;
	theDiv.opacityStep = step;
	theDiv.opacityGoal = goal;
	setOpacity(theDiv, start);
	theDiv.opacityTimeout = setTimeout("doOpacityAnimation('"+theDiv.id+"')", 0);
}

function setOpacity(theDiv, theOpacity) {
	theDiv.style.filter = 'alpha(opacity='+theOpacity+')';
	theDiv.style['-moz-opacity'] = theOpacity/100;
	theDiv.style.opacity = theOpacity/100;
}

function toggleLoadingStatus(toggleTo, resultsDiv, loadingDiv) {
	/* Initiate opacity value to 100% */
	if (resultsDiv.opacityCurrent==undefined) 
		resultsDiv.opacityCurrent = 100;
	if (toggleTo=='loading') {
		// Show "Loading" text and start fading out search results
		if (loadingDiv) loadingDiv.style.display = 'block';
		initiateOpacityAnimation(resultsDiv, resultsDiv.opacityCurrent, -10, 20);
	} else {
		// Hide "Loading" text and start fading in search results
		if (loadingDiv) loadingDiv.style.display = 'none';
		initiateOpacityAnimation(resultsDiv, resultsDiv.opacityCurrent, 20, 100);
	}
}

/*
function findInArrayByName(theArray, theFieldvalue) {
	return findInArrayByField(theArray, 'name', theFieldvalue)
}
function findInArrayByField(theArray, theFieldname, theFieldvalue) {
	var result = null;
	for (var i=0, abort=false ; i<theArray.length || abort==true ; i++)
		if (theArray[i][theFieldname] == theFieldvalue) {
			result = theArray[i];
			abort=true;
		}
	return result;
}
*/

function findObjectInArray(theArray, theId, deleteObject) {
	var result;
	for (var i=0 ; i<theArray.length ; i++)
		if (theArray[i].id == theId) {
			if (deleteObject==true) {
				theArray[i].abort();
				theArray.pop(i);
			//	alert(i)
			} else {
				result = theArray[i].object;
			}
			return result;
		}
	return 0;
}

function makeGetRequest(httpRequestId, uri, parameters, onSuccess, onFail) {
	makeAjaxRequest(httpRequestId, uri, parameters, onSuccess, loadingDivId, 0)
}

function makePostRequest(httpRequestId, uri, parameters, onSuccess, onFail) {
	makeAjaxRequest(httpRequestId, uri, parameters, onSuccess, onFail, 1)
}

function makeAjaxRequestPageClosure(httpRequestId, uri, parameters, resultsDivId, loadingDivId, usePost, closure) {
	var resultsDiv = document.getElementById(resultsDivId);
	var loadingDiv = document.getElementById(loadingDivId);
	var postBack = postBack;
	
	if (!resultsDiv) return 0;
	
	/* Initiate loading animation */
	if (loadingDiv)
		toggleLoadingStatus('loading', resultsDiv, loadingDiv);
	
	onSuccess = function(httpRequest) {
		if (loadingDiv)
			toggleLoadingStatus('done', resultsDiv, loadingDiv);
		resultsDiv.innerHTML = httpRequest.responseText;
		if (closure)
			closure();
	}
	onFail = function(httpRequest) {
		if (loadingDiv)
			toggleLoadingStatus('done', resultsDiv, loadingDiv);
		//resultsDiv.innerHTML = httpRequest.responseText; //'Ett fel uppstod. Var vänlig försök igen.'
		resultsDiv.innerHTML = 'An error occured, please try again.<br> '+ httpRequest.responseText;
	}
	
	makeAjaxRequest(httpRequestId, uri, parameters, onSuccess, onFail, usePost)
}

function makeAjaxRequestPage(httpRequestId, uri, parameters, resultsDivId, loadingDivId, usePost) {
	makeAjaxRequestPageClosure(httpRequestId, uri, parameters, resultsDivId, loadingDivId, usePost, '')
}

function findHttpRequest(httpRequestId) {
	return findObjectInArray(httpRequests, httpRequestId, '');
}

function deleteHttpRequest(httpRequestId) {
	return findObjectInArray(httpRequests, httpRequestId, true);
}

function makeAjaxRequest(httpRequestId, uri, parameters, onSuccess, onFail, usePost) {
	var httpRequest; 
	
	/* Delete HttpRequest if Object exists */
	if (findHttpRequest(httpRequestId))
		deleteHttpRequest(httpRequestId);
	
	/* Create HttpRequest Object */
	if (window.XMLHttpRequest) 
		httpRequest = new XMLHttpRequest();                   // Mozilla, Safari, etc.
	else if (window.ActiveXObject) 
		httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); // IE
	
	/* Abort if there's no div to display the results, or if failed to create XMLHttp Object */
	if (!httpRequest) return 0;
	
	/* Override mime-type if not set, required for some old Mozilla browsers */
	//if (httpRequest.overrideMimeType) httpRequest.overrideMimeType('text/html; charset=iso-8859-1;');
	
	/* Function to activate when a change is received in httpRequest */
	httpRequest.onreadystatechange = function() { 
		hasrequestStateChanged(httpRequest, onSuccess, onFail); 
	};
	
	/* Insert HttpRequest object into httpRequests Array */
	httpRequests[httpRequests.length] = {
		id:httpRequestId,
		object:httpRequest,
		doPost:function() {
			/* Send the POST request */
			this.object.open('POST', uri, true);
//			this.object.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=iso-8859-1');
			this.object.setRequestHeader('Content-length', parameters.length);
			this.object.setRequestHeader('Connection', 'close');
			this.object.send(parameters);
		},
		doGet:function() {
			/* Send the GET request */
			var parameterseparator;
			if (parameters)
				parameterseparator = '?';
			else 
				parameterseparator = '';
				
			this.object.open('GET', uri + parameterseparator + parameters, true);
			this.object.send(null);
		},
		abort:function() {
			/* Delete and abort the httpRequest object */
			this.object.onreadystatechange = function() {};
			this.object.abort();
			delete this.object;
		}
	};
	
	/* Send the Request either as POST or GET*/
	if (usePost==1) 
		httpRequests[httpRequests.length-1].doPost(uri, parameters);
	else 
		httpRequests[httpRequests.length-1].doGet(parameters);
}

function _a(functionName, action, param, section) {
	var frm = document.getElementById("_submitform");
	var act = document.getElementById("_action");
	var prm = document.getElementById("_param");
	if (section != "")
		frm.action += "#" + section;
	act.value = action;
	prm.value = param;
	eval(functionName+"('_action="+action+"&_param="+param+"')");
}

function hasrequestStateChanged(httpRequest, onSuccess, onFail) {
//	if (debugDiv && httpRequest) debugDiv.innerHTML = 'State:' + httpRequest.readyState + 
//	' Status:' + httpRequest.status + ' Statustext:' + httpRequest.statusText;
	if (httpRequest) {
		if (httpRequest.readyState == 4) {
			// Response has been received
			if (httpRequest.status == 200) {
				// Request was completed succesfully
				if (onSuccess)
					onSuccess(httpRequest);
			} else {
				// There was an error in the request
				if (onFail)
					onFail(httpRequest)
			}
		} else {
			// Request is loading
		}
	}
/*
	debugDiv.innerHTML =''
	for (i=0 ; i<httpRequests.length ; i++) {
		debugDiv.innerHTML += httpRequests[i].id + ':' + 
													httpRequests[i].object.status +	', ' ;
	}
*/
}

function doSearchOnChange() {
	if (searchTimeOut) clearTimeout(searchTimeOut)
	searchTimeOut = setTimeout("doSearchChangePage('')", 200);
}

function doSearchOnChangeLbyg() {		 
	fillYrkeskategorier();
	// sidbannersurl definieras i .sol
	makePostRequest('sidbanners', sidbannersurl, getPostValues(), 'sidbannersDiv', 'sidbannersLoadingTextDiv');
	doSearchOnChange();
}

function doSearchChangeOrder(orderValue, orderriktningValue) {
	var order = document.getElementById('order');
	var orderriktning = document.getElementById('orderriktning');
	order.value=orderValue;
	orderriktning.value=orderriktningValue;
	doSearchChangePage('');
}

function doSearchChangePage(formParams) {
	// sokresultaturl definieras i .sol
	makePostRequest('jobsearch', sokresultaturl, getPostValues(formParams), 'searchResultsDiv', 'searchResultsLoadingTextDiv');
}

function getPostValues(formParams) {
	var postvalues;
	postvalues = 'lbyg='+lbyg[lbyg.selectedIndex].value+
							 '&lbyk='+lbyk[lbyk.selectedIndex].value+
							 '&lbg='+lbg[lbg.selectedIndex].value+
							 '&order='+order.value+
							 '&orderriktning='+orderriktning.value+
							 '&'+formParams;
	return postvalues;
}