/*
'Author					: Stefan Kruger
'Date Created			: 28-Jul-2005
'Last Changed by		: Stefan Kruger
'Date Changed			: 28-Jul-2005
'Version				: 1.0.28072005
'Comments:
'Date:			Desc:
'--------------------------------------------------------------------------------------------
'28-Jul-2005	Code update run completed

'ToDoList:
'Date:			Desc:																Status:
'------------------------------------------------------------------------------------------------
'28-Jul-2005	Find a cleaner tab loading / parameter replacement methodology if
'				possible															Not done
*/

//////////////////////////////////////////////////////////////////////////////////////////////
//CONSTANTS
//////////////////////////////////////////////////////////////////////////////////////////////
/*
Defines some extra string functionality
*/
String.prototype.trim = new Function("return this.replace(/^\\s+|\\s+$/g,'')");

/*
Defines different page loaders that can be used in the genericSubmit function
*/
var regularloadingstring = "<TABLE WIDTH=100% HEIGHT=100%><TR VALIGN=MIDDLE><TD ALIGN=CENTER height=200><IMG border=0 SRC='images/preloader_normal.gif'></TD></TR></TABLE>";
var tabloadingstring = "<TABLE WIDTH=100% HEIGHT=100%><TR VALIGN=MIDDLE><TD ALIGN=LEFT height=18><IMG border=0 SRC='images/preloader_greenbar.gif'></TD></TR></TABLE>";

/*
Defines different error page notification display messages used in the pageLoadChecker function
*/
var servererror = "There has been a server error while processing your request.|^^|Click <a href='javascript:void(0)' onclick='alert(lasterror);'>here</a> to view the complete error.";
var error404 = "The page you requested cannot be found.|^^|Click <a href='javascript:void(0)' onclick='alert(lasterror);'>here</a> to view the complete error.";
var error403 = "You do not have permission to view the page you requested. Method|^^|Click <a href='javascript:void(0)' onclick='alert(lasterror);'>here</a> to view the complete error.";
var error405 = "Access to the resource you requested not allowed.|^^|Click <a href='javascript:void(0)' onclick='alert(lasterror);'>here</a> to view the complete error.";
var lasterror = "";

/*
Defines common regular expressions
*/
var spaceregex = / /g;
var singlequoteregex = /\'/g;
var stefanregex = /\|\^\^\|/g;
var inversestefanregex = /\^\|\|\^/g;
var compidmarkerregex = /\^ComponentIDMarker\^/g;
var compnamemarkerregex = /\^ComponentNameMarker\^/g;
var compurlmarkerregex = /\^ComponentURLMarker\^/g;
var posnamemarkerregex = /\^PositionNameMarker\^/g;
var pageidmarkerregex = /\^PageIDMarker\^/g;
var comptitlemarkerregex = /\^ComponentTitleMarker\^/g;
var gqsmarkerregex = /\^GQSMarker\^/g;

//////////////////////////////////////////////////////////////////////////////////////////////
//MOUSE CURSOR HANDLING
//////////////////////////////////////////////////////////////////////////////////////////////
/*
Mouse cursor handling functions (Used in submissions to display activity)
*/

function busyCursor(){
	try { document.body.style.cursor = "wait";}
	catch(e) {alert(e);}
}

function regularCursor(){
	try { document.body.style.cursor = "auto";}
	catch(e) {alert(e);}
}

function toggle_advanced(){
		$("#advancedsearch").slideToggle();
}

function searchGrid_Region(evt){
	if (isEnterKey(evt) || isTabKey(evt) || evt == "nonevent"){
	
	document.getElementById("RegionID").value = "";
	
	var gridpage = "modules/search/searchGrid_region.asp";
	var foundvalue = popUpSearch($("#RegionName").val(),gridpage,"region");
	
	//alert(foundvalue);
	if (foundvalue) {
	var arr = new Array();
	arr = foundvalue.split("|^^|")
		document.getElementById("RegionID").value = arr[0];
		document.getElementById("RegionName").value = arr[1];
	}
	//document.getElementById("RegionName").disabled = true;
	}
}

function searchGrid_Owner(evt){
    if (isEnterKey(evt) || isTabKey(evt) || evt == "nonevent") {
	
	document.getElementById("OwnerID").value = "";
		
	var gridpage = "modules/search/searchGrid_Owner.asp";
	var foundvalue = popUpSearch($("#Owner").val(),gridpage,"owner");
	
	//alert(foundvalue);
	if (foundvalue) {	
	var arr = new Array();
	arr = foundvalue.split("|^^|")
		document.getElementById("OwnerID").value = arr[0];
		document.getElementById("Owner").value = arr[1];
	}
	//document.getElementById("Owner").disabled = true;
	}
}

function searchGrid_Mineral(evt){
    if (isEnterKey(evt) || isTabKey(evt) || evt == "nonevent") {
	
	document.getElementById("mineralisationid").value = "";
	
	var gridpage = "modules/search/searchGrid_Mineral.asp";
	var foundvalue = popUpSearch($("#Mineral").val(),gridpage,"mineral");

	//alert(foundvalue);
	if (foundvalue) {	
	var arr = new Array();
	arr = foundvalue.split("|^^|")
		document.getElementById("mineralisationid").value = arr[1];
		document.getElementById("Mineral").value = arr[0];
	}
	//document.getElementById("Mineral").disabled = true;
	}
}

function popUpSearch(searchvalue,page,mode){
	var returnid;
	var setMatchFound = function (oXML) {
		var retvalue = oXML.responseText;
		if (retvalue != ""){
			returnid = retvalue;
		}
		regularCursor();
		oXML = null;
	}

	if (searchvalue != ""){
		data = "action=" + mode + "&searchvalue=" + encodeURIComponent(searchvalue);
		checkpage = "modules/search/loadsearch.asp";
		hiddenSubmit(checkpage,data,setMatchFound,0,null,false);
	}
		
	if (!returnid){
		returnid = createModalWin(page,480,400,searchvalue);
	}
	return returnid;
}

//////////////////////////////////////////////////////////////////////////////////////////////
//GENERAL STRING HANDLING
//////////////////////////////////////////////////////////////////////////////////////////////
/*
Function to fix single quotes for database use (ie:replace one with two)
*/
function fixSingleQuote(strMessage){
	return strMessage.replace(singlequoteregex,"''");
}

//////////////////////////////////////////////////////////////////////////////////////////////
//COMPONENT LOADING FUNCTIONS
//////////////////////////////////////////////////////////////////////////////////////////////
/*
Load the most recent XMLHTTP object available for IE or XMLHttpRequest for Mozilla
*/
function createXMLHttp(){
	var myobj;
	try {myobj = new ActiveXObject("Msxml2.XMLHTTP.4.0");}
	catch (ex) { try {myobj = new ActiveXObject("Msxml2.XMLHTTP.3.0");}
	catch (ex) { try {myobj = new ActiveXObject("Msxml2.XMLHTTP");}
	catch (ex) { try {myobj = new ActiveXObject("Microsoft.XMLHTTP");}
	catch (ex) { try {myobj = new XMLHttpRequest();}
	catch (ex) { myobj = false; alert("Could not load XMLHTTP component");}}}}}
	return myobj;
}

//////////////////////////////////////////////////////////////////////////////////////////////
//PREDEFINED USER FUNCTIONS USED IN THE POST-LOADING OF PAGES
//////////////////////////////////////////////////////////////////////////////////////////////
/*
This function is used when displaying a database defined load  (--> getPage)
*/
var loadContent = function (oXML,gqs) {
	//Check for expiry of content before loading	
	if (oXML.responseText.substr(2,35) == "<!-- Message box start delimiter-->"){
		expireSession();
	}
	else {
		var retar = new Array();
		retar = (oXML.responseText).split("|^^|");
		//alert(retar);
		//bottomcontent.innerHTML = oXML.responseText;
		if ((retar.length >= 10) && ((retar.length - 2) % 8 == 0)){
			//Process Page Preload
			try {
				//Substitute the pageID(first found at arrayvalue 3 and then repeated every 8 into pagepreloadexecute when needed
				retar[0] = retar[0].replace(pageidmarkerregex,[retar[3]]);
				eval(retar[0]);
			}
			catch (ex) {}
			//Load each component of page
			for (k = 2; k < retar.length; k++){
			
				//Substitute the common identifiers (page and component) into componentpreloadexecute when needed
				retar[k+3] = retar[k+3].replace(compurlmarkerregex,[retar[k]]);
				retar[k+3] = retar[k+3].replace(pageidmarkerregex,[retar[k+1]]);
				retar[k+3] = retar[k+3].replace(compidmarkerregex,[retar[k+2]]);
				retar[k+3] = retar[k+3].replace(posnamemarkerregex,[retar[k+4]]);
				retar[k+3] = retar[k+3].replace(compnamemarkerregex,[retar[k+5]]);
				retar[k+3] = retar[k+3].replace(comptitlemarkerregex,[retar[k+7]]);
				retar[k+3] = retar[k+3].replace(gqsmarkerregex,gqs);
				//alert("Preload is :" + retar[k+3]);
				genericSubmit(retar[k],gqs + "&gridfunction=" + retar[1] + "&pageid=" + retar[++k] + "&compid=" + retar[++k] + "&loadedin=" + retar[k+2],retar[++k],retar[++k],completedSingleLoad,regularloadingstring,eval((retar[k+2].toString()).toLowerCase()));
				//Increment to get past componentName,isGrid and Title.
				k += 3;
			}
		}
		else {
			getMessageBox("Page Load Error","Page not loaded.|^^|Reason: Invalid array received from the page template loader.","topcontent");
		}
	}
	regularCursor();
	oXML = null;
};

/*
This function is used when displaying a single page load
*/
var completedSingleLoad = function (oXML,outputDiv) {
	var display = pageLoadChecker(oXML,outputDiv)
	if (display) {
		outputDiv.innerHTML = display;
	}
	regularCursor();
	display = null;
	oXML = null;
};

/*
This function is used when simply alerting return values from a background page submission
*/
var alertHiddenResponse = function (oXML) {
	alert(oXML.responseText);
	//document.write (oXML.responseText);
	regularCursor();
	oXML = null;
};

//////////////////////////////////////////////////////////////////////////////////////////////
//CONTENT LOADING FUNCTIONS
//////////////////////////////////////////////////////////////////////////////////////////////

/*
A function to hide and clear the regular content display.
*/
function contentHider(){
	document.getElementById("topcontent").innerHTML = '';
	document.getElementById("topcontent").style.display = 'none';
	document.getElementById("bottomcontent").innerHTML = '';
	document.getElementById("bottomcontent").style.display = 'none';
	try
	{
		nd();
	}
	catch(ex)
	{
		
	}	
}

/*
Wrapper function for action searching
Post-loading is controlled by "useCustomFunction" :
	useCustomFunction = true --> do a custom (usually grid) postload
	useCustomFunction = false --> do a regular postload
*/
var backtoSearch = ""
function checkAction(actionName,compID,formName,useCustomFunction,completionFunction,isModalGrid){
	var execFunction = null;
	if (useCustomFunction){
		if (completionFunction) {
			execFunction = completionFunction;
		}
		else {
			alert("No function for action check specified.");
			return null;
		}
	}
	else {	
		//With this method the form of the calling page should contain all the required fields.
	    execFunction = function(oXML) {
	        replaceString = "''";
	        //alert(oXML.responseText);
	        evalstr = "executePageAction(" + oXML.responseText.replace("^RelationalID^", replaceString) + ",actionName)";
	        try {
	            eval(evalstr);
	        }
	        catch (ex) {
	            alert("Execution of an action failed.");
	        }
	        regularCursor();
	        oXML = null;
	    };
	}
	var data = "action=getcomponentactions&actionname=" + actionName + "&compid=" + compID;
	if (formName) {
		data += "&formname=" + formName;
	}
	else {
		data += "&formname=null";
	}
	//prompt('',data)
	//Pathchange for modal grid
	var pathchange = "";
	if (isModalGrid){
		pathchange = "../../";
	}
	hiddenSubmit(pathchange + "include/navigationfunctions.asp",data,execFunction,0,null,false);	
}

/*
Function to fetch a full list of relations that this component is involved in
*/
function getComponentRelations(componentid,isModalGrid){
	var returnArray = [];
	if (!(isNaN(componentid))) {
		var completedFullRelationList = function (oXML) {
			returnArray = (oXML.responseText).split("|^^|");
			if (!(returnArray.length)) {
				alert("Invalid relation data.");
			}
			regularCursor();
			oXML = null;
		};
		var pathchange = "";
		if (isModalGrid){
			pathchange = "../../";
		}
		hiddenSubmit(pathchange + "include/navigationfunctions.asp","action=getfulllistofcomponentrelations&compid=" + componentid,completedFullRelationList,0,null,false);
	}
	return returnArray;
}

/*
This function executes a page action defined in the DB
It can also attach form data (via a form name) that is sent to all pages loading from the definition
in the DB. Now it can also execute default functions assigned to an action in the DB taking the relation values 
as parameters.
*/
function executePageAction(preload,id,defaultFunction,formToSend,relationValueString,actionName){
	//Do Action Preloader
	//alert(relationValueString)
	try {eval(preload);}
	catch (ex) {alert(preload);}
	var relationURLdata = "";
	//If a relation the process it and pass on
	if (relationValueString) {
		//Manage relationValueString to turn it into URL encoding to send as data
		relationURLdata = relationValueString.replace(stefanregex,"&");
		relationURLdata = relationURLdata.replace(inversestefanregex,"=");
		//Do Default function if it is required
		if (defaultFunction) {
			//Split the relationValueString to extract actual values to pass to function
			var functionstring = "";
			var functionstring_array = relationValueString.split("|^^|");
			var functionstring_component_array;
			if (functionstring_array.length){
				for (i = 0; i < functionstring_array.length; i++) {
					functionstring_component_array = functionstring_array[i].split("^||^")
					///Comma seperate values
					if (functionstring != "") {
						functionstring += ",";
					}
					//Add string delimiters to non-number values
					//if (isNaN(functionstring_component_array[1])){
						functionstring += "'" + functionstring_component_array[1].replace(/'/g,"\\'") + "'";
					/*}
					else {
						functionstring += functionstring_component_array[1];
					}*/
				}
			}
			//Now execute default function
			try {
				var exec = defaultFunction + "(" + functionstring + ");"
				eval(exec);
			}
			catch (ex) {
				alert("Failed action execution");
			}
		}
	}
	if (id) {
		var formURLData = "";
		if (formToSend) {
			formURLData = fetchInputFormData(formToSend);
		}
		var gqsdata = (relationURLdata == "") ? formURLData : ((formURLData == "") ? relationURLdata : relationURLdata + "&" + formURLData);
		//alert(gqsdata);
		//prompt('',id);
		if (actionName == "searchmine"){ backtoSearch = gqsdata }
		getPage(id,gqsdata);
	}
}

/*
This would be a content selection from menu i.e. DB specified content
*/
function getPage(id,globalquerystring,skipHistoryWrite){

	//To clear the editor closing error message {Billy Griffiths - 30 October 2006}
	//PreviousEditorID = null;

	var page = "http://www.mining.co.za/template.asp?UniqueID={" + id + "}"
	//Set globalquerystring to "blank" in querystring string if null
	if (!(globalquerystring)) { globalquerystring = ""; }
	//prompt('', page + globalquerystring);
	hiddenSubmit(page,globalquerystring,loadContent,2,null,true);
}

/*
Single page component loader function
Accepts multiple loader strings and can be limited to JS-only by the stopProcessingAfterJS flag.
*/
function genericSubmit(page,data,preload,div,whenDoneRunThis,loaderToUse,stopProcessingAfterJS) {
	//Process preload - accepts a stopProcessing flag from called function if needed;
	/*try {*/eval(preload);//}
	//catch (ex) {alert(preload);alert(ex)}
	//Call page loader
	//contentHider();
	if (!(stopProcessingAfterJS)) {
		//Check for a valid division to load the page in
		try {
			document.getElementById(div).style.display = '';
			document.getElementById(div).innerHTML = loaderToUse;
		}
		catch (ex){alert("Division specified for load was invalid."); return;}
		hiddenSubmit(page,data,whenDoneRunThis,1,div,true);
	}
}

/*
A page loader function that works in the background.
It creates a new request object for each call, allowing for multiple simultaneous page loads,
and runs a user specified function when page load is completed.
It's different modes (specified by "modeDelimiter") are :
	GENERAL (0)			: Just returns the request object to the handling function.
						  (Used for general functions requiring background page calls.)
	SINGLEPAGELOAD (1)	: Returns the entire request object as well as a page division to
						  display its contents in.
						  (Used for loading and displaying a single page component)
	DATABASELOAD (2)	: Returns the entire request object as well as the queryString data to use
						  again on the individual
						  (Used for loading and displaying a DB defined set of page components simultaneously)
	RUNANDIGNORE (3)	: Runs request and then clears the request object upon load completion, without any
						  further action

Synchronisation is controlled by "syncmode" :
	syncmode = true --> asychronous transfer (meaning: processing continues on another thread until request load is complete.)
	syncmode = false --> sychronous transfer (meaning: processing is paused until request is completed.)
*/
/*function hiddenSubmit(page,data,whenDoneRunThis,modeDelimiter,div,syncmode) {
	try {
		var xmlhttp = createXMLHttp();
		//Check for loaded request component
		if (xmlhttp){
			xmlhttp.open("POST", page , syncmode);
			if (data != "") {
				xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				data = data.replace(spaceregex,"%20");
			}
			//This is the case for a call expecting no return whatsoever
			if (modeDelimiter == 3){
				xmlhttp.onreadystatechange = function (){
					if (xmlhttp.readyState == 4){
						regularCursor();
						xmlhttp = null;
					}
				};
			}
			//This is the case for a getPage function with global submission data
			if (modeDelimiter == 2){
				xmlhttp.onreadystatechange = function (){
					if (xmlhttp.readyState == 4){
						whenDoneRunThis(xmlhttp,data);
					}
				};
			}
			//This is the case for a page display submission ie: general case requiring a div to display data in.
			if (modeDelimiter == 1){
				xmlhttp.onreadystatechange = function (){
					if (xmlhttp.readyState == 4){
						whenDoneRunThis(xmlhttp,document.getElementById(div));
					}
				};
			}
			//This is the case for a more general function needing only the return values from a hiddenSubmit to process
			if (modeDelimiter == 0){
				xmlhttp.onreadystatechange = function (){
					if (xmlhttp.readyState == 4){
						whenDoneRunThis(xmlhttp);
					}
				};
			}
			busyCursor();
			xmlhttp.send(data);
		}
		else {
			alert("No XMLHTTP object initialised.");
		}
	}
	catch(e) {
		alert(e);
	}
}*/

function hiddenSubmit(page,data,whenDoneRunThis,modeDelimiter,div,syncmode){
//alert(page)
//alert(data)
//alert(whenDoneRunThis)
	try {
		var xmlhttp = createXMLHttp();
		
		//Check for loaded request component
		if (xmlhttp){
			xmlhttp.open("POST",page ,syncmode);
			if (data != ""){
				xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
			}
			
			//If asynchronous set up postload function
			if (syncmode){
				//alert(xmlhttp.readyState);
				xmlhttp.onreadystatechange = function (){
					if (xmlhttp.readyState == 4){
						execPostLoad(xmlhttp,modeDelimiter,whenDoneRunThis,div,data);
					}
				};
			}
			if (!data) {
				data = "";
			}
			busyCursor();
			xmlhttp.send(data);			
			//If synchronous execute postload function
			if (!(syncmode)){
				execPostLoad(xmlhttp,modeDelimiter,whenDoneRunThis,div,data);
			}
		}
		else {
			alert("No XMLHTTP object initialised.");
		}
	}
	catch(ex){
		alert(ex.message);
	}
}

function execPostLoad(xmlhttp,modeDelimiter,whenDoneRunThis,div,data){
	var continueclear = /http\/1\.1 100 cont[i]nue/ig;
	if ((xmlhttp.responseText).match(continueclear)) {alert("Caught HTTP/1.1 Continue 100")};
	regularCursor();
	
	//This is the case for a call expecting no return whatsoever
	if (modeDelimiter == 3){
		xmlhttp = null;
	}
	//This is the case for a getPage function with global submission data
	if (modeDelimiter == 2){
		whenDoneRunThis(xmlhttp,data);
	}
	//This is the case for a page display submission ie: general case requiring a div to display data in as well as postload execution.
	if (modeDelimiter == 1){
		whenDoneRunThis(xmlhttp,document.getElementById(div));
	}
	//This is the case for a more general function needing only the return values from a hiddenSubmit to process
	if (modeDelimiter == 0){
		whenDoneRunThis(xmlhttp);
	}
}
		
/*
Custom HTML error checking function for some specified errors used to check page load status
before displaying the content in the browser.
*/
function pageLoadChecker(xmlObj,divInCaseOfMessage){
	//Check for null load division and set default
	if (!(divInCaseOfMessage)){
		divInCaseOfMessage = document.getElementById("topcontent");
	}
	//Get status
	var status = xmlObj.status;
	//Status - OK
	if (status == 200){
		return xmlObj.responseText;
	}
	//Status - Server error (likely SQL or ASP sourced)
	/*if (status == 500){
		lasterror = xmlObj.responseText;
		getMessageBox("Server Error",servererror,divInCaseOfMessage.id);
		return;
	}*/
	//Status - Page not found
	if (status == 404){
		lasterror = xmlObj.responseText;
		getMessageBox("File Not Found",error404,divInCaseOfMessage.id);
		return;
	}
	//Status - Permission denied (likely local proxy or remote security)
	if (status == 403){
		lasterror = xmlObj.responseText;
		getMessageBox("Permission Denied",error403,divInCaseOfMessage.id);
		return;
	}
	//Status - Requested Method / Resource not allowed
	if (status == 405){
		lasterror = xmlObj.responseText;
		getMessageBox("Resource Or Request Method not allowed",error405,divInCaseOfMessage.id);
		return;
	}
	//Unhandled status but a page has been loaded so just display and see what happens
	divInCaseOfMessage = null;
	return xmlObj.responseText;
}

/*
Function for managing display window commands
*/
function manageDisplayWindow(divToProcess,manageModifier) {
	var thediv = document.getElementById(divToProcess);
	if (thediv){
		if (manageModifier == "close"){
			thediv.style.innerText = "";
			thediv.style.display = "none";
		}
		if (manageModifier == "toggle") {
			if (thediv.style.display == "none") {
				thediv.style.display = "";
			}
			else {
				thediv.style.display = "none";
			}
		}
	}
	else {
		alert("Division specified was not found in the document.")
	}
	thediv = null;
}

var movedWindow = false;

function moveWindow(sourcediv,destinantiondiv,clearSourceFlag) {
	if (document.getElementById(sourcediv) && document.getElementById(destinantiondiv)) {
		if (!(movedWindow)) {
			document.getElementById(destinantiondiv).innerHTML = document.getElementById(sourcediv).innerHTML;
			if (clearSourceFlag) {
				document.getElementById(sourcediv).innerHTML = "";
			}
			movedWindow = true;
		}
		else {
			//alert("Skipped window move...");
		}
	}
	else {
		alert("Invalid division found in move.");
	}
}

//////////////////////////////////////////////////////////////////////////////////////////////
//SYSTEM INFORMATION HANDLING
//////////////////////////////////////////////////////////////////////////////////////////////
/*
IE modal window creater
*/
/*function createModalWin(page,height,width){
	var modalresult = window.showModalDialog(page,null,'help:no;scroll:no;center:yes;status:no;dialogHeight:' + height + 'px;dialogWidth:' + width + 'px;resizable:no');
	return modalresult;
}*/

function createModalWin(page,height,width,arguments){
	if (!(arguments)){
		arguments = null;
	}
	var modalresult = window.showModalDialog(page,arguments,'help:no;scroll:no;center:yes;status:no;dialogHeight:' + height + 'px;dialogWidth:' + width + 'px;resizable:no');
	return modalresult;
}

/*
A general message box display function

USAGE :
Title			--> Header of Content
Content			--> Content of the messagebox with different bullets seperated by the "|^^|" marker
DivToLoadItIn	--> The page division to show the messagebox in.
*/
function getMessageBox(title,content,divToLoadItIn){
	contentHider();
	var page = "include/messagebox.asp";
	var data = "content=" + encodeURIComponent(content) + "&title=" + encodeURIComponent(title);
	genericSubmit(page,data,null,divToLoadItIn,completedSingleLoad,regularloadingstring,false);
}

/*
Standard currency formatting function to emulate the ASP format function in JS
*/
function currencyFormatter(value){
	var dotspot,workspot,output,flag;
	//2 digit rounding simulator
	value = (Math.round(value * 100))/100;
	value = value.toString();
	//Add cents if required
	if (value.indexOf(".") == -1) {
		value = value.concat(".00");
	}
	dotspot = value.indexOf(".");
	workspot = dotspot;
	flag = true;
	//Add comma every 3 digits
	while (flag) {
		workspot = workspot - 3;
		if (workspot > 0) {
			var part1 = value.substring(0,workspot)
			var part2 = value.substring(workspot,value.length)
			value = part1 + "," + part2
			workspot = value.indexOf(",");
		}
		else {
			flag = false;
		}
	}
	dotspot = value.indexOf(".");
	if (value.substring(dotspot,value.length).length < 3){
		value = value.concat("0");
	}
	//Assumes ZAR output
	output = "R " + value
	return output;
}

/*
A function to check if a system event was the pressing of the enter key.
*/
function isEnterKey(evt){
	if (!evt){
		evt = window.event;
	}
	else if (!evt.keyCode){
		evt.keyCode = evt.which;
	}
	return (evt.keyCode == 13)
}

/*
A function to check if a system event was the pressing of the tab key.
*/
function isTabKey(evt){
	if (!evt){
		evt = window.event;
	}
	else if (!evt.keyCode){
		evt.keyCode = evt.which;
	}
	return (evt.keyCode == 9)
}

//////////////////////////////////////////////////////////////////////////////////////////////
//FORM INPUT HANDLING
//////////////////////////////////////////////////////////////////////////////////////////////

function showHelp(id) {
	alert("Help for component id :" + id)
}


//////////////////////////////////////////////////////////////////////////////////////////////
//FORM INPUT HANDLING
//////////////////////////////////////////////////////////////////////////////////////////////

/*
A generalised form submitting function that returns the contents of a form in URL querystring
*/
function fetchInputFormData(formToProcess){
	var theform;
	if (formToProcess){
		theform = eval("document." + formToProcess)
	}
	else {
		theform = null
	}
	var queryString = ""
	var addString = ""
	if (theform) {
		try {
			for (var i = 0; i < theform.elements.length; i++){
				if (queryString == "") {
					addString = ""
				}
				else {
					addString = "&"
				}
				if (theform.elements[i].type == "radio") {
					if (theform.elements[i].checked){
						addString += theform.elements[i].name + "=" + encodeURIComponent(theform.elements[i].value);
					}
				}
				else {
					if (theform.elements[i].type == "checkbox") {
						if (theform.elements[i].checked) {
							addString += theform.elements[i].name + "=" + 1;
						}
						else {
							addString += theform.elements[i].name + "=" + 0;
						}
					}
					else {
						if (theform.elements[i].type == "select-multiple") {
							for (j = 0; j < theform.elements[i].options.length; j++) {
								if (theform.elements[i].options[j].selected){
									if (addString != "" && addString != "&") {
										addString += "&"
									}
									addString += theform.elements[i].name + "=" + encodeURIComponent(theform.elements[i].options[j].value);
								}
							}
						}
						else {
							//Meaning : Hidden, Text or Single-Select : All treated equally without discrimination... :-)
							addString += theform.elements[i].name + "=" + encodeURIComponent(theform.elements[i].value);
						}
					}
				}
				if (addString != "&") {
					queryString += addString
				}
			}
		}
		catch (ex) { alert("Error processing input form.");}
	}
	else {
		//alert("Invalid input form specified.")
	}
	//alert(queryString);
	theform = null;
	return queryString;
}

//returns true if val is a valid internet e-mail address
function isValidEmail(val){
   re = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
   r = val.match(re);
   if (r == null) {
	return false;
   }
   else {
	return true
   }
}

//returns true if val is an integer
function isInteger(val){
	re = /^[-]?\d+$/;
	r = val.toString().match(re);
	if (r == null) {
		return false;
	}
	else {
		return true
	}
}

//returns true if val is a valid decimal
function isDecimal(val){
	//re = /([.])/;
	re = /^[-]?\d+([.]{1}\d+)?$/;
	r = val.toString().match(re);
	if (r == null) {
		return false;
	}
	else {
		return true
	}
}

//Used with onkeypress event
//takes the current value as input and cancel the event if the entered key makes the new value an invalid decimal
function maskAmount(val) {
	val = val + String.fromCharCode(window.event.keyCode);
	if (val != "") {
		re = /^\d+([.]?\d*)?$/;
		r = val.toString().match(re);
		if (r == null) {
			window.event.returnValue = false;
		}
	}
}

function fetchAndSetTooltip(obj) {
	try {
		obj.title = obj.innerHTML;
	}
	catch (ex) {}
}
function OpenWindow()
{
   window.open('/pdf/African MH Ratecard 2012.pdf');
}

function clearTabStyles(){
	$("img[id='tab_LeftImg']").each(function(el) {
        $(this).attr("src","/images/gray_tab_left.png"); 
    });
    
    $("img[id='tab_RightImg']").each(function(el) {
        $(this).attr("src","/images/gray_tab_right.png"); 
    });
    
    $("div[id='tab_Background']").each(function(el) {
		$(this).removeClass().addClass("float_left gray_tab_bg amo_tab_black");
    });

}

function check_AdvancedSearch() {
    var submitthis = false;

    if ($("#RegionID").val() == "" && $("#RegionName").val() != "") {
        submitthis = false;
        searchGrid_Region("nonevent");
        submitthis = true;
    } else {
        submitthis = true;
    }

    if ($("#OwnerID").val() == "" && $("#Owner").val() != "") {
        submitthis = false;
        searchGrid_Owner("nonevent");
        submitthis = true;
    } else {
        submitthis = true;
    }


    if ($("#mineralisationid").val() == "" && $("#Mineral").val() != "") {
        
        submitthis = false;
        searchGrid_Mineral("nonevent");
        submitthis = true;
    } else {
        submitthis = true;
    }


    if (submitthis) {
        checkAction('searchmine', 14, 'frmAdvancedSearch', false, null, false);
    }
}

function setTabStyle(object){
	clearTabStyles()
    $("div[id='" + object.html() + "'] img[id='tab_LeftImg']").attr("src","/images/green_tab_left.png"); 
	$("div[id='" + object.html() + "'] img[id='tab_RightImg']").attr("src","/images/green_tab_right.png");

	    $("div[rel='tab_Content']").each(function(el) {
	        $(this).hide();
	    });

	    $("div[id='" + object.html() + "']").show();
	
	object.removeClass().addClass("float_left green_tab_bg amo_tab_white");
}

var items = new Array();
function addLastViewed(minename,mineid,regionid){
    var data = minename + '|' + mineid + '|' + regionid
	items.push(data)
	
	//List only 10 last viewed items
	if (items.length > 10){
		//Reverse Array order
		items.reverse()
		//Remove last array (first)
		items.pop()
		//Reverse it again
		items.reverse()
	}
	
	$.post('/modules/search/saveSearchResult.asp', {
		historyviewer: data
	}, function() {
		//Clear HTML already in there
		$("div[id='historyViewer']").html("")
		//Add clickable items onto the history viewer
		$.each(items,
			function( i, value ){
					$("div[id='historyViewer']").append("<div class=green_bar_inner_4><div><a class=last_search href=javascript:getPage('6FCF8D08-658D-471D-B5FC-089572C7558F','historyviewer=" + data + "');>" + value + "</a></div><div class=theplug><!--IE FIX--></div></div>")
				}
		);
	});
	
};


function ChangeMenuState(ObjMenu, State)
{
	var ObjHref = ObjMenu;
	//alert(ObjHref.id);
	if(State == 0)
	{
		ClearSubMenu();
		ObjHref.className = "link_normal_4";
	}
	else
	{
		var SubMenu = document.getElementById('ShowSubMenu').value;
		ClearMainMenu();
		ObjHref.className = "link_normal_bigger_1";
		if(SubMenu == 'True' && ObjMenu.id != 'CMS_ahref')
		{
			ClearSubMenu();
		}
	}
}

function ClearSubMenu()
{
	var CountSpan = document.getElementById('SubMenuCount').value;
	var ObjHref;
	for(var k=1;k<CountSpan;k++)
	{
		MenuName = 'SubMenu_'+k;
		ObjHref = document.getElementById(MenuName);
		ObjHref.className = "link_normal_3";	
	}	
}

function ClearMainMenu()
{
	var CountSpan = 8
	var ObjHref;
	for(var k=1;k<CountSpan;k++)
	{
		MenuName = 'MainMenu_'+k;
		ObjHref = document.getElementById(MenuName);
		ObjHref.className = "link_normal_bigger";	
	}	
	document.getElementById('login_ahref').className = "link_normal_bigger";
	document.getElementById('search_ahref').className = "link_normal_bigger";
	document.getElementById('CMS_ahref').className = "link_normal_bigger";
}
