/**
*	geofellowsFunctions.js
*
*	JavaScript methods to power GeolSoc fellows search via 
*	AJAX / Web 2.0 methods.
*
*	AJAX functions built around the DWR libraries
*
*	@author ian.stapleton
*/

///Core Functionality

/** geofel_handleSearchByAjax()
* 
* Performs basic validation & initiates a search using DWR calls
*/
function geofel_handleSearchByAjax() {
  ///Warmup Tasks
	//Start the spinner
	geofel_beginAjaxActivity();
	
	//Disable the form submit control
	var submitControl = document.SearchForm.searchSubmit;
	submitControl.disabled = true;
	
	//Remove Form Errors display
	geofel_clearFormErrors();
	
	//Clear old results display
	document.getElementById("fellowSearchResultsContainer").innerHTML = "";			
		
  ///Action tasks
   	//Get the values for the relevant fields
  	var surnameTerm = document.SearchForm.surname.value;
  	var forenameTerm = document.SearchForm.forename.value;
  	var townTerm = document.SearchForm.town.value;  	
  	var organisationTerm = document.SearchForm.organisation.value;
  	
  	//Bit of work to get out select elements and Booleans
  	var countryTerm = document.SearchForm.country.options[document.SearchForm.country.selectedIndex].value;  	
  	  	
  	var charteredTerm = false;
  	if (document.SearchForm.chartered.checked) {
  		charteredTerm = true;
  	}
  	
  	//Even more as this is multiple
 	var areasOfExpertiseTerm = new Array();
 	var areasOfExpertiseElement = document.SearchForm.areasOfExpertise;
 	for (var eCount = 0; eCount < areasOfExpertiseElement.length; eCount++) { 	
 		if (areasOfExpertiseElement.options[eCount].selected) {
 			 areasOfExpertiseTerm.push(areasOfExpertiseElement.options[eCount].value);
 		} 	
 	}
 	
	//Basic validation to ensure we have something to search on
	var validSearch = false;
    var errorMsg = "";
    	
    if (surnameTerm.length > 0) { validSearch = true };
    if (forenameTerm.length > 0) { validSearch = true };
    if (townTerm.length > 0) { validSearch = true };
    if (organisationTerm.length > 0) { validSearch = true };
    if (countryTerm > 0) { validSearch = true };
    if (areasOfExpertiseTerm.length > 0) { validSearch = true };
    
    if (validSearch == true) {
    	//Good to go - remaining validation occurs server-side
    	
    	//Server side failures are caught by DWR Exceptions	    	
    	FellowActions.searchAction(surnameTerm, forenameTerm, 
    		townTerm, areasOfExpertiseTerm, organisationTerm, countryTerm,
    		charteredTerm, geofel_userIsAdmin, geofel_searchCallBack);	
   	} else {
   		//Throw this off to our error handler!
		if (errorMsg == "") {
			dwrErrorHandler(geofel_langArray["errors"]["noFields"]);
		} else {
			dwrErrorHandler(errorMsg);
		}
   	}
    
    ///Cooldown Tasks: enable the form submit control, hide the ticker
	//Enable submit control
	submitControl.disabled = false;				
	
	//Set Timer method to remove ticker ("fake" delay)
	geofel_ajaxActivityTimer = setTimeout("geofel_endAjaxActivity()", ajaxFakeDelay);	  
    
  //Return
	//Return false to cancel the form submit we've stolen    	    
    return false; 
}

function geofel_processAdditionalDetailsRequest(fellowId, cvDataId) {
	
	//clear out these variables
	geofel_cv_lookingForEmployment = null;
  	geofel_cv_offeringConsultancy = null;	
	
	//Start the spinner
	geofel_beginAjaxActivity();
	
	//Start DWR Requests
	FellowActions.getFellowAction(fellowId, geofel_getExtendedCallBack)
	
	if (cvDataId > 0) {
		//Disable the "view CV button"
		//alert('disable cCV button');
		geofel_showCVControl = false;
		geofel_additionalDetailHeaderText = "&nbsp;Fellow CV details";
		FellowActions.getCvDataAction(cvDataId, geofel_getCvDataCallBack)
		geofel_cv_currentFellow = fellowId;		
	} else {
		//alert('enable cCV button');
		geofel_showCVControl = true;
		geofel_additionalDetailHeaderText = "&nbsp;Extended Fellow details"; 
		geofel_cv_currentFellow = null;
	}
	
	//Turn on the required page controls etc.
	
	
	
	//Set Timer method to remove ticker ("fake" delay)
	geofel_ajaxActivityTimer = setTimeout("geofel_endAjaxActivity()", ajaxFakeDelay);	  
}

function geofel_processPagedResults(pageNumber) { 
  ///Setup
  	//Gather page elements for the results
	var resultsContainer = document.getElementById("fellowSearchResultsContainer");
    
    //Start Spinner
	geofel_beginAjaxActivity();		    
    //Blank the currently displayed page
    resultsContainer.innerHTML = "";
    
    //Remove any CMS content
    document.getElementById("geofel_contentFromJahia").style.display = "none";
           
    //Reset the summary ordering array
    geofel_placementOrder = new Array();
        	    
	//Calculate start and end points for this page
    geofel_pagingStartRecord = (geofel_pagingPerPage * pageNumber);
    geofel_pagingEndRecord = geofel_pagingStartRecord + parseInt(geofel_pagingPerPage);
    
    //Check to prevent out-of-range issues
    if (geofel_pagingEndRecord > geofel_searchResults.length) {
	    geofel_pagingEndRecord = geofel_searchResults.length;
	}		
	
	//Store the current page for use by the Paging Control
	geofel_searchCurrentPage = pageNumber;
	 
  ///Generate page	
	//Display the top paging bar
	geofel_generatePagingControl("geofel_topPaging");		
	
	//For each result on the page, put in an asynchronous call to show summary data
	for (var currentRecord = geofel_pagingStartRecord; currentRecord < geofel_pagingEndRecord; currentRecord++) {
		//We need to make sure the summary is ordered correctly
		//Store the record number of this record into a mapping array
		geofel_placementOrder[geofel_searchResults[currentRecord]] = currentRecord;		
		
		//Create a container element to hold the summary results.
		containerElement = document.createElement("div");
        containerElement.setAttribute("id", "geofel_record_"+currentRecord);
        resultsContainer.appendChild(containerElement);
		
		//Finally dispatch the AJAX request
		FellowActions.getFellowAction(geofel_searchResults[currentRecord], geofel_getFellowCallBack);
	}		
	
	// Display the bottom paging bar.  In the JSP it is called something else, 
	// so find it and give it a proper id
	var elementToRename = document.getElementById("geofel_bottomPaging_with_nothing_in");
	if (elementToRename != null) {
		elementToRename.id = "geofel_bottomPaging";
	}
	geofel_generatePagingControl("geofel_bottomPaging");	
	
	//Display the bottom paging bar
	geofel_generatePagingControl("geofel_bottomPaging");	

  ///Finalise	
	//Set Timer method to remove ticker ("fake" delay)
	geofel_ajaxActivityTimer = setTimeout("geofel_endAjaxActivity()", ajaxFakeDelay);
	
	//Returning false should kill browser history issues
	return false;	
}

///BEGIN DWR CALLBACK FUNCTIONS
/*
* These functions are called by the DWR framework following a
* completed xmlhttp request to a remote method.
*/

/** geofel_keywordCallBack()
*
* Method called by DWR following a sucessful keyword search
* Handles storing results into application variables & fires display routines
*/	
var geofel_searchCallBack = function(Data) {		
		
	if (Data.length > 0) {
		//Store the returned results and process the first page
		geofel_searchResults = Data;			
		geofel_processPagedResults(0);			
	} else {
		dwrErrorHandler("Your search returned no results");
	}	
}

var geofel_getFellowCallBack = function(Data) {

	var resultsContainer = document.getElementById("geofel_record_"+geofel_placementOrder[Data.fellowid]);
	var resultsContainerTable = document.createElement("table");
	var recordAttributes = new Array();
	var showingFellowLabel = false;
		
	//Blast through and get all the variables out
	if (Data.title != "") {recordAttributes[recordAttributes.length] = new Array(geofel_langArray["results"]["title"], Data.title);}
	if (Data.forename != "") {recordAttributes[recordAttributes.length] = new Array(geofel_langArray["results"]["forenames"], Data.forename);}
	if (Data.surname != "") {recordAttributes[recordAttributes.length] = new Array(geofel_langArray["results"]["surname"], Data.surname);}	
	if (Data.organisation != "") {recordAttributes[recordAttributes.length] = new Array(geofel_langArray["results"]["organisation"], Data.organisation);}
	if (Data.town != "") {recordAttributes[recordAttributes.length] = new Array(geofel_langArray["results"]["town"], Data.town);}
		
		
	if (Data.countryDisplay == "United Kingdom") {
		if (Data.postaldistrict != "") {recordAttributes[recordAttributes.length] = new Array(geofel_langArray["results"]["postalDistrict"], Data.postaldistrict);}
	}
	
	if (Data.countryDisplay != "") {recordAttributes[recordAttributes.length] = new Array(geofel_langArray["results"]["country"], Data.countryDisplay);}
	if (Data.fellowstatusDisplay != "") {
		recordAttributes[recordAttributes.length] = new Array(geofel_langArray["results"]["fellowshipStatus"], Data.fellowstatusDisplay);
		showingFellowLabel = true;
	}
	
	if (Data.cgeolstatus == true) {
		var cgeolString = "Chartered Geologist";
		
		if (Data.cgeoldate != null) {
			cgeolString += "&nbsp;(" + Data.cgeoldate.getDate() + "/" + (Data.cgeoldate.getMonth()+1) + "/" + Data.cgeoldate.getFullYear() + ")"
		}			
		
		if (showingFellowLabel == true) {
			recordAttributes[recordAttributes.length] = new Array("", cgeolString);
		} else {
			recordAttributes[recordAttributes.length] = new Array(geofel_langArray["results"]["fellowshipStatus"], cgeolString);
			showingFellowLabel = true;
		}
	}
	
	if (Data.cscistatus == true) {
		var csciString = "Chartered Scientist";
		
		if (Data.cscidate != null) {
			csciString += "&nbsp;(" + Data.cscidate.getDate() + "/" + (Data.cscidate.getMonth()+1) + "/" + Data.cscidate.getFullYear() + ")"
		}			
		
		if (showingFellowLabel == true) {
			recordAttributes[recordAttributes.length] = new Array("", csciString);
		} else {
			recordAttributes[recordAttributes.length] = new Array(geofel_langArray["results"]["fellowshipStatus"], csciString);
		}
	}	
	
	
	if (Data.datejoined != null) {recordAttributes[recordAttributes.length] = new Array(geofel_langArray["results"]["joinedDate"], 
							Data.datejoined.getDate() + "/" + (Data.datejoined.getMonth()+1) + "/" + Data.datejoined.getFullYear());}
	
	if (Data.lastYearOfCompletedCPD != "") {recordAttributes[recordAttributes.length] = new Array(geofel_langArray["results"]["lastYearOfCompletedCPD"], Data.lastYearOfCompletedCPD);}
	
	if (Data.areasOfExpertise != null && Data.areasOfExpertise.length > 1) {
		
		var expertiseString = "";
		
		for (var currentExpertise = 0; currentExpertise <  Data.areasOfExpertise.length; currentExpertise++) {
			expertiseString += Data.areasOfExpertise[currentExpertise].name + "<br/>";
		}
	
		recordAttributes[recordAttributes.length] = new Array(geofel_langArray["results"]["areasOfExpertise"], expertiseString);	
	
	}
	
	//CV Data
	if (Data.cvvisible == true && Data.cvdataid > 0) {
		recordAttributes[recordAttributes.length] = new Array("link", '<span class="darkredButton"><input type="button" onClick="geofel_processAdditionalDetailsRequest('+Data.fellowid+','+Data.cvdataid+')" value="View CV" /></span>');
	}
	
	//Extended Info (Admin or User is Fellow and record permits ext data)
	if (geofel_userIsAdmin || (geofel_userIsLoggedInFellow &&  (Data.visibilitystatusid == 5) || (Data.visibilitystatusid == 6 ) )) {
		// The word link is used in the loop below to indicate special treatment of this cell
		recordAttributes[recordAttributes.length] = new Array("link", '<span class="darkredButton"><input type="button" onClick="geofel_processAdditionalDetailsRequest('+Data.fellowid+', 0)" value="Full Contact Details"></span>');
	}
		
	//Insert new rows	
	//Thankyou Mr.Sean
	for (var myNiceCounter = 0; myNiceCounter < recordAttributes.length; myNiceCounter++) {

		var newRowReference = resultsContainerTable.insertRow(myNiceCounter);
		
		var newRowLabel = newRowReference.insertCell(0);
		var newRowData = newRowReference.insertCell(1);
		
		newRowLabel.innerHTML = "<strong>" + recordAttributes[myNiceCounter][0] + "</strong>";
		newRowLabel.style.verticalAlign = "top";
		newRowLabel.width = "30%";
		newRowData.innerHTML = recordAttributes[myNiceCounter][1];
		
		// Right align links
		if (recordAttributes[myNiceCounter][0] == "link") {
			newRowLabel.innerHTML = "";
			newRowData.style.textAlign = "right";
		}
	}
	
	
	resultsContainer.appendChild(resultsContainerTable);
	resultsContainer.appendChild(document.createElement("hr"));
}

var geofel_getExtendedCallBack = function(Data) {
	
	//Need to do this first to fudge things!
	geofel_cv_lookingForEmployment = Data.lookingforemployment;
  	geofel_cv_offeringConsultancy = Data.offeringconsultancy;	
	
	//Clear the Extended Details column
	var extendedContainer = document.getElementById("geofel_extendedDetailContainer");	
	extendedContainer.innerHTML = "";
	
	//Toggle the interface	
	geofel_showAdditionalInterface();

	//Spoof an anchor to allow this page to be bookmarked
	window.location.hash = "viewDetail=" + Data.fellowid;
	
	var extendedContainerTable = document.createElement("table");
	extendedContainerTable.style.width = "100%";
	var recordAttributes = new Array();
		
	//Blast through and get all the variables out
	if (Data.title != "") {recordAttributes[recordAttributes.length] = new Array(geofel_langArray["results"]["title"], Data.title);}
	if (Data.forename != "") {recordAttributes[recordAttributes.length] = new Array(geofel_langArray["results"]["forenames"], Data.forename);}
	if (Data.surname != "") {recordAttributes[recordAttributes.length] = new Array(geofel_langArray["results"]["surname"], Data.surname);}	
	if (Data.organisation != "") {recordAttributes[recordAttributes.length] = new Array(geofel_langArray["results"]["organisation"], Data.organisation);}
	
	if (Data.address != "") {recordAttributes[recordAttributes.length] = new Array(geofel_langArray["results"]["postalAddress"], Data.address);}
	if (Data.town != "") {recordAttributes[recordAttributes.length] = new Array(geofel_langArray["results"]["town"], Data.town);}	
	if (Data.county != "") {recordAttributes[recordAttributes.length] = new Array(geofel_langArray["results"]["county"], Data.county);}
	if (Data.postcode != "") {recordAttributes[recordAttributes.length] = new Array(geofel_langArray["results"]["postCode"], Data.postcode);}
	if (Data.countryDisplay != "") {recordAttributes[recordAttributes.length] = new Array(geofel_langArray["results"]["country"], Data.countryDisplay);}
	if (Data.emailAddress != "") {recordAttributes[recordAttributes.length] = new Array(geofel_langArray["results"]["emailAddress"], 
		'<a href="mailto:'+Data.emailAddress+'">'+Data.emailAddress+'</a>');}
		
	if (Data.fellowstatusDisplay != "") {
		recordAttributes[recordAttributes.length] = new Array(geofel_langArray["results"]["fellowshipStatus"], Data.fellowstatusDisplay);
		var showingFellowLabel = false;
	}
	
	if (Data.cgeolstatus == true) {
		var cgeolString = "Chartered Geologist";
		
		if (Data.cgeoldate != null) {
			cgeolString += "&nbsp;(" + Data.cgeoldate.getDate() + "/" + (Data.cgeoldate.getMonth()+1) + "/" + Data.cgeoldate.getFullYear() + ")"
		}			
		
		if (showingFellowLabel == true) {
			recordAttributes[recordAttributes.length] = new Array("", cgeolString);
		} else {
			recordAttributes[recordAttributes.length] = new Array(geofel_langArray["results"]["fellowshipStatus"], cgeolString);
			showingFellowLabel = true;
		}
	}
	
	if (Data.cscistatus == true) {
		var csciString = "Chartered Scientist";
		
		if (Data.cscidate != null) {
			csciString += "&nbsp;(" + Data.cscidate.getDate() + "/" + (Data.cscidate.getMonth()+1) + "/" + Data.cscidate.getFullYear() + ")"
		}			
		
		if (showingFellowLabel == true) {
			recordAttributes[recordAttributes.length] = new Array("", csciString);
		} else {
			recordAttributes[recordAttributes.length] = new Array(geofel_langArray["results"]["fellowshipStatus"], cgeolString);
			showingFellowLabel = true;
		}
	}	
	
	if (Data.datejoined != null) {recordAttributes[recordAttributes.length] = new Array(geofel_langArray["results"]["joinedDate"], 
							Data.datejoined.getDate() + "/" + (Data.datejoined.getMonth()+1) + "/" + Data.datejoined.getFullYear());}
	
	if (Data.lastYearOfCompletedCPD != "") {recordAttributes[recordAttributes.length] = new Array(geofel_langArray["results"]["lastYearOfCompletedCPD"], Data.lastYearOfCompletedCPD);}
 
	
	if (Data.areaOfExpertise != null && Data.areaOfExpertise.length > 1) {
		
		var expertiseString = "";
		
		for (var currentExpertise = 0; currentExpertise <  Data.areaOfExpertise.length; currentExpertise++) {
			expertiseString += Data.areaOfExpertise[currentExpertise].name + "<br /";
		}
	
		recordAttributes[recordAttributes.length] = new Array(geofel_langArray["results"]["areasOfExpertise"], expertiseString);	
	
	}		
		
	//Insert new rows	
	//Thankyou Mr.Sean
	for (var myNiceCounter = 0; myNiceCounter < recordAttributes.length; myNiceCounter++) {

		var newRowReference = extendedContainerTable.insertRow(myNiceCounter);
		
		var newRowLabel = newRowReference.insertCell(0);
		var newRowData = newRowReference.insertCell(1);
		
		newRowLabel.innerHTML = "<strong>" + recordAttributes[myNiceCounter][0] + "</strong>";
		newRowLabel.style.verticalAlign = "top";
		newRowLabel.width = "30%";
		newRowData.innerHTML = recordAttributes[myNiceCounter][1];
	}
		
	extendedContainer.appendChild(extendedContainerTable);	
	
	//Sort out the interface controls
	var controlsContainer = document.getElementById("geofel_extendedControlsContainer");
	controlsContainer.innerHTML = "";
	
	controlsContainer.innerHTML += '<span class="darkredButton"><input type="button" onClick="geofel_returnToResults()" value="Back to Results" /></span>';
	
	if (geofel_showCVControl && Data.cvvisible == true && Data.cvdataid > 0) {
		controlsContainer.innerHTML += '<span class="darkredButton"><input type="button" onClick="geofel_processAdditionalDetailsRequest('+Data.fellowid+','+Data.cvdataid+')" value="View Fellow\'s CV" /></span><br />';
	}	
	
}


var geofel_getCvDataCallBack = function(Data) {
	
	//Clear the Extended Details column
	var cvContainer = document.getElementById("geofel_cvDetailContainer");	
	cvContainer.innerHTML = "";
	cvContainer.style.display = "";
		
	var cvContainerTable = document.createElement("table");	
	cvContainerTable.style.width = "100%";
	var cvAttributes = new Array();

	//Spoof an anchor to allow this page to be bookmarked
	window.location.hash = "viewCV=" + geofel_cv_currentFellow;
		
	//Blast through and get all the variables out
	if (geofel_cv_lookingForEmployment != null && geofel_cv_lookingForEmployment == true) {cvAttributes[cvAttributes.length] = new Array(geofel_langArray["cv"]["lookingForEmployment"], "");}
	if (geofel_cv_offeringConsultancy != null && geofel_cv_offeringConsultancy == true) {cvAttributes[cvAttributes.length] = new Array(geofel_langArray["cv"]["offeringConsultancy"], "");}
	
	if (Data.dateOfBirth != null) {cvAttributes[cvAttributes.length] = new Array(geofel_langArray["cv"]["dateOfBirth"], 
		Data.dateOfBirth.getDate() + "/" + (Data.dateOfBirth.getMonth()+1) + "/" + Data.dateOfBirth.getFullYear());}
	
	if (Data.nationality != "") {cvAttributes[cvAttributes.length] = new Array(geofel_langArray["cv"]["nationality"], Data.nationality);}
	if (Data.personalStatement != "") {cvAttributes[cvAttributes.length] = new Array(geofel_langArray["cv"]["personalStatement"], Data.personalStatement);}
	if (Data.education != "") {cvAttributes[cvAttributes.length] = new Array(geofel_langArray["cv"]["education"], Data.education);}
	
	if (Data.dateOfGraduation != null) {cvAttributes[cvAttributes.length] = new Array(geofel_langArray["cv"]["dateOfGraduation"], 
		Data.dateOfGraduation.getDate() + "/" + (Data.dateOfGraduation.getMonth()+1) + "/" + Data.dateOfGraduation.getFullYear());}
			
	if (Data.highestQualification != "") {cvAttributes[cvAttributes.length] = new Array(geofel_langArray["cv"]["highestQualification"], Data.highestQualification);}
	if (Data.professionalQualifications != "") {cvAttributes[cvAttributes.length] = new Array(geofel_langArray["cv"]["professionalQualifications"], Data.professionalQualifications);}
	if (Data.employmentHistory != "") {cvAttributes[cvAttributes.length] = new Array(geofel_langArray["cv"]["employmentHistory"], Data.employmentHistory);}
	if (Data.skills != "") {cvAttributes[cvAttributes.length] = new Array(geofel_langArray["cv"]["skills"], Data.skills);}
	if (Data.interests != "") {cvAttributes[cvAttributes.length] = new Array(geofel_langArray["cv"]["interests"], Data.interests);}
		
	//Insert new rows	
	//Thankyou Mr.Sean
	for (var myNiceCounter = 0; myNiceCounter < cvAttributes.length; myNiceCounter++) {

		var newRowReference = cvContainerTable.insertRow(myNiceCounter);
		
		var newRowLabel = newRowReference.insertCell(0);
		var newRowData = newRowReference.insertCell(1);
		
		newRowLabel.innerHTML = "<strong>" + cvAttributes[myNiceCounter][0] + "</strong>";
		newRowLabel.style.verticalAlign = "top";
		newRowLabel.width = "30%";
		newRowData.innerHTML = cvAttributes[myNiceCounter][1];
	}
	
	//Add footer text
	var footerRow = cvContainerTable.insertRow(myNiceCounter);
	var footerRowData = footerRow.insertCell(0);
			
	footerRowData.innerHTML = "<br /><span>" + geofel_langArray["cv"]["referenceStatement"] + "</span><br /><br />";
	footerRowData.style.verticalAlign = "top";
	footerRowData.colSpan = "2";	
		
	cvContainer.appendChild(cvContainerTable);

}


///BEGIN UTILITY FUNCTIONS
/**
* Helper functions to provide common functions / methods etc.
*/	
	
/** dwrErrorHandler()
*
* Method to handle errors inside DWR related functions.
* Due to nesting, this catches virtually all JS errors in the application.
*/			
function dwrErrorHandler(msg) {
	//Blank the pagnation bars to default
	var topPaging = document.getElementById("geofel_topPaging");					
	var bottomPaging = document.getElementById("geofel_bottomPaging");
	var displayError = "";
	topPaging.innerHTML = " Search Fellows ";	
	bottomPaging.innerHTML = " Search Fellows ";
	
	//The error may be the result of a validation falure, 
	//if so the msg will be of the format "field#message"
	if (msg.indexOf("#") > -1) {
		//We have a field & a message
		var msgComponents = msg.split("#");
		
		document.SearchForm.elements[msgComponents[0]].parentNode.className = "errorField";		
		
		//Set the text for the error	
		displayError = msgComponents[1];	
	} else {
		//Use the raw error message
		displayError = msg;
	}			
	
	//Output the error message
	document.getElementById("fellowSearchErrorText").innerHTML = "";
	
	var errorList = document.createElement("ul");
	var errorItem = document.createElement("li");
	
	errorItem.appendChild(document.createTextNode(displayError));
	errorList.appendChild(errorItem);
	
	document.getElementById("fellowSearchErrorText").appendChild(errorList);	
	document.getElementById("fellowSearchErrorContainer").style.display = "";
	
	//document.getElementById("librarySearchErrorText").innerHTML = "<ul><li>" + displayError + "</ul></li>";
}


//Instruct DWR to use our bespoke error-handler
DWREngine.setErrorHandler(dwrErrorHandler);
	
		
/** geofel_beginAjaxActivity()
*
* Clears any existing timer methods to remove the ajax activity display
* and ensures it is visible
*/
function geofel_beginAjaxActivity() {	
	//Remove any timeouts pending
	clearTimeout(geolfel_ajaxActivityTimer);
	
	//Enable the spinner
	var ajaxSpinnner = document.getElementById("ajaxActivity");
	ajaxSpinnner.style.visibility = 'visible';		
}

/** geofel_endAjaxActivity()
*
* Removes AJAX Activity indicator
*/
function geofel_endAjaxActivity() {	
	//Disable (hide) the spinner
	var ajaxSpinnner = document.getElementById("ajaxActivity");
	ajaxSpinnner.style.visibility = 'hidden';		
}



/** geofel_returnToResults()
*
* Returns to results & search view from 
* extended or CV windows
*/
function geofel_returnToResults() {	
	
	//Hide CV & Extended
	document.getElementById("geofel_extendedDetail").style.display = "none";
	
	//Show all the results etc
	document.getElementById("geofel_columnGap").style.display = "";
	document.getElementById("geofel_searchInterface").style.display = "";
	document.getElementById("geofel_searchResults").style.display = "";
		
}

/** geofel_showAdditionalInterface()
*
* Hides just the results & search columns
* Shows the aditiional data interface for extended or cv data
*/
function geofel_showAdditionalInterface() {
	//Hide all the results etc
	document.getElementById("geofel_columnGap").style.display = "none";
	document.getElementById("geofel_searchInterface").style.display = "none";
	document.getElementById("geofel_searchResults").style.display = "none";
	
	//Set the title
	document.getElementById("geofel_additionalDetailHeader").innerHTML = geofel_additionalDetailHeaderText;
		
	//Show the additional results pane
	document.getElementById("geofel_extendedDetail").style.display = "";	
}

/** geofel_clearFormErrors()
*
* Removes all error Messages and clears Error classes on form elements
*/
function geofel_clearFormErrors() {
	//Remove & Clear the central message display	
	document.getElementById("fellowSearchErrorContainer").style.display = "none";
	document.getElementById("fellowSearchErrorText").innerHTML = "";
	
	//Clear any error classes on individual fields
	document.SearchForm.surname.parentNode.className = "field";
	document.SearchForm.forename.parentNode.className = "field";
	document.SearchForm.town.parentNode.className = "field";
	document.SearchForm.areasOfExpertise.parentNode.className = "field";
	document.SearchForm.organisation.parentNode.className = "field";
	document.SearchForm.country.parentNode.className = "field";
	document.SearchForm.chartered.parentNode.className = "field";
}


/* DO NOT ATTEMPT TO ALTER THE 2 METHODS BELOW UNLESS YOU KNOW WHAT YOU ARE DOING OR ARE SOME SORT OF WIZARD */
/** geofel_generatePagingControl()
*
* Generates the paging control for the *Results List*
*/	
function geofel_generatePagingControl(pagingLocation) {	
	//Get the document element to receive this paging control
	var pagingContainer = document.getElementById(pagingLocation);
	var	numPages = Math.ceil(geofel_searchResults.length / geofel_pagingPerPage);
	
  ///Output the basic X to Y of Z portion
	pagingContainer.innerHTML = "<span style=\"float: left;\">&nbsp;Results " + parseInt(geofel_pagingStartRecord+1) + " to " + 
			geofel_pagingEndRecord +  " of " + geofel_searchResults.length + "</span>";
		
	
  ///Generate the actual clickable links
  	var linksHtml = "";
  	var linksIntro = "<span style=\"float: right;\" class=\"clickableFellowLinks\">";
	var nextLink = "";
	var previousLink = "";


	//Link to first page is always the same
	if (geofel_searchCurrentPage == 0) {
		//Show none-linking first page
		linksHtml += "<strong>1</strong>";
		if (numPages > 1) {
			nextLink = "|&nbsp;" + generateLink(pagingLocation, 1, "Next&nbsp;&gt;&gt;");
		}
	} else {
		//show linking first page
		linksHtml += "<span class=\"darkredAjaxHeaderLinks\" onClick=\"geofel_processPagedResults(0);\">1</span>";
	}
	
	if (numPages > 0) {
	//We have more than one page of results, so here starts the leg work!			
		//If we have 7 or fewer pages, then display is fixed
		if (numPages < 8) {
			//1|2|3|4|5|6|7 (upto)
			for (var aPage = 1; aPage < numPages; aPage++) {
				//Don't link to a page if we are already on it
				if (aPage == geofel_searchCurrentPage) {
					linksHtml += "|<strong>" + parseInt(aPage+1) + "</strong>";

					if ( ((aPage + 1) < numPages) && (numPages > 1)  ) {
						nextLink = "|&nbsp;" + generateLink(pagingLocation, aPage + 1, "Next&nbsp;&gt;&gt;");
					}
				} else {
					linksHtml += "|<span class=\"darkredAjaxHeaderLinks\" onClick=\"geofel_processPagedResults("+ aPage +");\">" + parseInt(aPage+1) + "</span>";
				}		
			}
			if (geofel_searchCurrentPage > 0) {
				previousLink = generateLink(pagingLocation, geofel_searchCurrentPage - 1, "&lt;&lt;&nbsp;Prev") + "&nbsp";
			}
				
			linksHtml = linksHtml + nextLink;
		} 
		else { // so more than 8 pages
			if (geofel_searchCurrentPage < 4) {
				//1|2|3|4|5|5+3 or last-1|last
					
				//Iterate over the first pages
				for (var aPage = 1; aPage < 5; aPage++) {
					//Don't link to a page if we are already on it
					if (aPage == geofel_searchCurrentPage) {
						linksHtml += "|<strong>" + parseInt(aPage+1) + "</strong>";
						if ( (aPage + 1) < numPages  ) {
							nextLink = "|&nbsp;" + generateLink(pagingLocation, aPage + 1, "Next&nbsp;&gt;&gt;");
						}
					} else {
						linksHtml += "|<span class=\"darkredAjaxHeaderLinks\" onClick=\"geofel_processPagedResults("+ aPage +");\">" + parseInt(aPage+1) + "</span>";
					}					
				}
				
				//Work out where the ellipsis link to "next 3" should send us
				if ((geofel_searchCurrentPage + 3) < 5) {
					//Show page 6 anyway
					linksHtml += "|<span class=\"darkredAjaxHeaderLinks\" onClick=\"geofel_processPagedResults(5);\">&hellip;</span>";
				} else {
					//If the link would send us to the last page or beyond, use (last -1)
					if ((geofel_searchCurrentPage + 4) >= numPages) {
						linksHtml += "|<span class=\"darkredAjaxHeaderLinks\" onClick=\"geofel_processPagedResults("+parseInt(numPages - 2)+");\">&hellip;</span>";						
					} else {
						linksHtml += "|<span class=\"darkredAjaxHeaderLinks\" onClick=\"geofel_processPagedResults("+parseInt(geofel_searchCurrentPage + 3)+");\">&hellip;</span>";
					}					
				}	
								
			}
			else if (geofel_searchCurrentPage > (numPages - 4)) {
				//1|x-3 or 2|x|*y*|z|last
				
				//calulate the ellipsis link
				linksHtml += "|<span class=\"darkredAjaxHeaderLinks\" onClick=\"geofel_processPagedResults("+parseInt(numPages -7)+");\">&hellip;</span>";
				
				//Iterate over the last pages					
				for (var aPage = numPages - 5; aPage < numPages-1; aPage++) {
					//Don't link to a page if we are already on it
					if (aPage == geofel_searchCurrentPage) {
						linksHtml += "|<strong>" + parseInt(aPage+1) + "</strong>";
						if ( (aPage + 1) < numPages  ) {
							nextLink = "|&nbsp;" + generateLink(pagingLocation, aPage + 1, "Next&nbsp;&gt;&gt;");
						}
					} else {
						linksHtml += "|<span class=\"darkredAjaxHeaderLinks\" onClick=\"geofel_processPagedResults("+ aPage +");\">" + parseInt(aPage+1) + "</span>";
					}					
				}				
			} 
			else {
				//1|x-3 or 2|x|*y*|z|z+3 or last-1|last
				
				//calulate the previous 3 ellipsis link
				linksHtml += "|<span class=\"darkredAjaxHeaderLinks\" onClick=\"geofel_processPagedResults("+ parseInt(geofel_searchCurrentPage - 3) +");\">&hellip;</span>";
				
				//Add previous, current and next page links
				linksHtml += "|<span class=\"darkredAjaxHeaderLinks\" onClick=\"geofel_processPagedResults("+ parseInt(geofel_searchCurrentPage - 1) +");\">"+ geofel_searchCurrentPage +"</span>";
				linksHtml += "|<strong>" + parseInt(geofel_searchCurrentPage+1) + "</strong>";
				linksHtml += "|<span class=\"darkredAjaxHeaderLinks\" onClick=\"geofel_processPagedResults("+ parseInt(geofel_searchCurrentPage + 1) +");\">"+ parseInt(geofel_searchCurrentPage + 2) +"</span>";
				
				//Add the next 3 ellipsis link
				linksHtml += "|<span class=\"darkredAjaxHeaderLinks\" onClick=\"geofel_processPagedResults("+parseInt(geofel_searchCurrentPage + 3)+");\">&hellip;</span>";
				
				if ( (geofel_searchCurrentPage + 1) < numPages  ) {
					nextLink = "|&nbsp;" + generateLink(pagingLocation, geofel_searchCurrentPage + 1, "Next&nbsp;&gt;&gt;");
				}
			}
			if (geofel_searchCurrentPage > 0) {
				previousLink = generateLink(pagingLocation, geofel_searchCurrentPage - 1, "&lt;&lt;&nbsp;Prev") + "&nbsp";
			}
			
			//Show the last page
			//Always the same :)
			if (geofel_searchCurrentPage == (numPages-1)) {
				//Show none-linking first page
				linksHtml += "|<strong>" + numPages + "</strong>";
			} else {
				//show linking first page
				linksHtml += "|<span class=\"darkredAjaxHeaderLinks\" onClick=\"geofel_processPagedResults("+ parseInt(numPages-1) +");\">" + numPages + "</span>";				
			}
			
			linksHtml = linksHtml + nextLink;
			
		}				
	}
	linksHtml += "</span>";
	linksIntro += previousLink;	
	linksIntro += linksHtml;
	pagingContainer.innerHTML += linksIntro;

	return true;
}

/* Generate link to a next or previous page 
 * in bottom pagination links only
 */
function generateLink(position, page, message) {
	if (position == 'geofel_topPaging') {
		return('');
	}
	link = "<span class=\"darkredAjaxHeaderLinks\" onClick=\"geofel_processPagedResults("+ page +");\">" + message + "</span>";
	return link;
}

