var Last_AjaxDiv;
var Last_AjaxUrl;
var Last_AjaxTimestamp;
var VisibleLoadingDiv = 0;
var KeyPress;
var google_updateclicked = 0;

function RefreshPage(){
	window.location.href = unescape(window.location);
}

function PreloadImg() { 
/*
	Preload the Loading images so the Loading Div doesn't look weird.
*/
  var args = PreloadImg.arguments;
  document.imageArray = new Array(args.length);
  for(var i=0; i<args.length; i++)
  {
    document.imageArray[i] = new Image;
    document.imageArray[i].src = args[i];
  }
}

function ShowImageDiv(Id, Visiblity){
	if(document.getElementById('ImageDiv_' + Id)){
		if(Visiblity){
			document.getElementById('ImageDiv_' + Id).style.visibility = 'visible';
		}
		else {
			document.getElementById('ImageDiv_' + Id).style.visibility = 'hidden';
		}
	}
}

function randomString() {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var string_length = 20;
	var randomstring = '';
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	r_Timestamp = new Date();
	return randomstring + '-' + r_Timestamp.getHours() + '-' + r_Timestamp.getMinutes() + '-' + r_Timestamp.getSeconds();
}

function DataReplace(Old,New,Data){
	while(Data.match(Old)){
		Data = Data.replace(Old,New);
	}
	return Data;
}

function AjaxSelect(Select,FullURL){
	if(!document.getElementById(Select)){
		return;	
	}

	if(VisibleLoadingDiv){
//stop the loading bar from disappearing
		clearTimeout(VisibleLoadingDiv);
	}
	if(document.getElementById('LoadingPage')){ document.getElementById('LoadingPage').style.display = 'block'; }

	var xmlhttp=false;
        try {
                xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
        } catch (e) {
                try {
                        xmlhttp = new
                        ActiveXObject('Microsoft.XMLHTTP');
            } catch (E) {
                xmlhttp = false;
                        }
        }
        if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
                xmlhttp = new XMLHttpRequest();
        }
    xmlhttp.open('GET', FullURL + "&RandomString=" + randomString(), true);
    xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4) {
			var content = xmlhttp.responseText;
			if( content && document.getElementById(Select) ){
				document.getElementById(Select).options.length = 0;
				items = content.split("[|]");
				document.getElementById(Select).options.length = items.length;
				for(i = 0; i < items.length; i++){
					if(items[i]){
						data = items[i].split("[-]");
						if(data[0] && data[1]){
							if(data[0].match("[|selected|]")){
								data[0] = data[0].replace("[|selected|]","")
								document.getElementById(Select).options[i].selected = true;
							}
							document.getElementById(Select).options[i].value = data[0];
							document.getElementById(Select).options[i].text = data[1];
						}
					}
				}
				if(document.getElementById('LoadingPage')){
					VisibleLoadingDiv = setTimeout("document.getElementById('LoadingPage').style.display = 'none';",500);
				}
			}
		}
	}
    xmlhttp.send(null)
	return;
}

function AjaxData(AjaxDiv,FullURL){
/*
	This function grabs the data from the 'FullURL'.
	Do not use 'http://www.' etc
	Just use: page.php?variable=foo&Variable2=bar
*/

	CurrentTimestamp = new Date();
	if(Last_AjaxDiv !== AjaxDiv || Last_AjaxUrl !== FullURL || (CurrentTimestamp-Last_AjaxTimestamp)>2000){
		Last_AjaxDiv = AjaxDiv;
		Last_AjaxUrl = FullURL;
		Last_AjaxTimestamp = new Date();
	}
	else {
//Do not execute this function again. It was run with exactly the same variables within the last 2 seconds.
		return;
	}
	
	if(VisibleLoadingDiv){
//stop the loading bar from disappearing
		clearTimeout(VisibleLoadingDiv);
	}
	if(document.getElementById('LoadingPage')){ document.getElementById('LoadingPage').style.display = 'block'; }
	

	var xmlhttp=false;
        try {
                xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
        } catch (e) {
                try {
                        xmlhttp = new
                        ActiveXObject('Microsoft.XMLHTTP');
            } catch (E) {
                xmlhttp = false;
                        }
        }
        if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
                xmlhttp = new XMLHttpRequest();
        }
    xmlhttp.open('GET', FullURL + "&RandomString=" + randomString(), true);
    xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4) {
			var content = xmlhttp.responseText;
			if( content ){
				if(document.getElementById(AjaxDiv)){
//hide the loading bar after timer = 0;
					if(document.getElementById('LoadingPage')){
						VisibleLoadingDiv = setTimeout("document.getElementById('LoadingPage').style.display = 'none';",500);
					}
//display content inside div
					document.getElementById(AjaxDiv).innerHTML = content;
				}
			}
		}
	}
    xmlhttp.send(null)
	return;
}

function AjaxGoogleMap(Street_Number,Street_Name,Street_Type,LocationId){

	if(!Street_Number || !Street_Name || !Street_Type || !LocationId || LocationId == '0'){
		alert('Error: You must supply the full address');
		return;
	}
	
	google_updateclicked = 1;
	
	CurrentTimestamp = new Date();
	if(Last_AjaxDiv !== 'GoogleMap' || Last_AjaxUrl !== Street_Number+' '+Street_Name+' '+Street_Type+' '+LocationId || (CurrentTimestamp-Last_AjaxTimestamp)>2000){
		Last_AjaxDiv = 'GoogleMap';
		Last_AjaxUrl = Street_Number+' '+Street_Name+' '+Street_Type+' '+LocationId;
		Last_AjaxTimestamp = new Date();
	}
	else {
//Do not execute this function again. It was run with exactly the same variables within the last 2 seconds.
		return;
	}
	
	if(VisibleLoadingDiv){
//stop the loading bar from disappearing
//		clearTimeout(VisibleLoadingDiv);
	}
//	document.getElementById('LoadingPage').style.visibility = 'visible';
	

	var xmlhttp=false;
        try {
                xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
        } catch (e) {
                try {
                        xmlhttp = new
                        ActiveXObject('Microsoft.XMLHTTP');
            } catch (E) {
                xmlhttp = false;
                        }
        }
        if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
                xmlhttp = new XMLHttpRequest();
        }
    xmlhttp.open('GET', "ajax/locationid.php?LocationId="+LocationId+"&RandomString=" + randomString(), true);
    xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4) {
			var content = xmlhttp.responseText;
			if( content )
			{
				
//hide the loading bar after timer = 0;
//				VisibleLoadingDiv = setTimeout("document.getElementById('LoadingPage').style.visibility = 'hidden';",500);
//display content inside div
//				document.getElementById(AjaxDiv).innerHTML = content;
				geocodeAddress(Street_Number+" "+Street_Name+" "+Street_Type+", "+content,'','');
			}
		}
	}
    xmlhttp.send(null)
	return;
}

function confirmmap(chkbox){
	if(google_updateclicked){
		if(chkbox.checked){
			if(map_loading){
				alert('Please wait until the map finishes loading.');
				chkbox.checked=false;
			}
			else {
				if(map_notfound){
					alert('Your map location is invalid.');
					chkbox.checked=false;
				}
				else {
					chkbox.checked=true;
					document.getElementById('Save').disabled = false;
				}
			}
		}
		else {
			chkbox.checked=false;
			document.getElementById('Save').disabled = true;
		}	
	}
	else {
		if(chkbox.checked){
			alert('You must click the "Update Map" button first.');	
			chkbox.checked = false;
		}
	}
}

function AllowForNewMap(){
	google_updateclicked = 0;
	document.getElementById('ConfirmMap').checked=false;
	document.getElementById('Save').disabled=true;
}

function ReOrder(AjaxId, OrderBy){
//reorder the ajax page data
	var NewOrder = 'ASC'; //default order
	if(AjaxList[AjaxId]['OrderType'] == 'ASC'){ NewOrder = 'DESC'; }
	if(AjaxList[AjaxId]['OrderType'] == 'DESC'){ NewOrder = 'ASC'; }
	AjaxList[AjaxId]['OrderType'] = NewOrder;
	AjaxList[AjaxId]['OrderBy'] = OrderBy;	
	AjaxData("AjaxResults_" + AjaxId,AjaxList[AjaxId]['Url'] + "?CurrentPage=" + PageVars['CurrentPage'] + "&AjaxId=" + AjaxId + "&OrderBy=" + OrderBy + "&OrderType=" + NewOrder);
}

function ChangePage(AjaxId, Page){
	AjaxData("AjaxResults_" + AjaxId,AjaxList[AjaxId]['Url'] + "?CurrentPage=" + PageVars['CurrentPage'] + "&AjaxId=" + AjaxId + "&Page=" + Page);
	AjaxList[AjaxId]['Page'] = Page;
}

function UpdateSearch(SearchQuery){
	SearchQuery = escape(SearchQuery);
	UpdateAjaxDivs(0,0,"&SearchQuery=" + SearchQuery,"");
	if(PageVars['DivFocus'] > 0){
		AjaxList[PageVars['DivFocus']]['SearchQuery'] = SearchQuery;
	}
	else {
		PageVars['SearchQuery'] = SearchQuery;
	}
	setAjaxSearchTitles(PageVars['DivFocus']);	
}

function ChangeResultsPerPage(ResultsPerPage){
	UpdateAjaxDivs(0,0,"&ResultsPerPage=" + ResultsPerPage,"");
	PageVars['ResultsPerPage'] = ResultsPerPage;
}

function ClearSearch(){
	if(document.getElementById('SearchQuery')){ document.getElementById('SearchQuery').value = ''; }
	if(document.getElementById('ResultsPerPage')){ document.getElementById('ResultsPerPage').value = '25'; }
	PageVars['ResultsPerPage'] = 25;
	PageVars['SearchQuery'] = '';
	
	for(i = 1; i <= PageVars['AjaxDivs']; i++){
		AjaxList[i]['SearchQuery'] = '';
	}
	setAjaxSearchTitles(0);	
	
	UpdateAjaxDivs(1,0,"&SearchQuery=&ResultsPerPage=25","");
}

function getSearchQuery(AjaxId){
	if(AjaxId > 0){
		return AjaxList[AjaxId]['SearchQuery'];	
	}
	else {
		return PageVars['SearchQuery'];
	}
}

function getDivName(AjaxId){
	if(AjaxId > 0){
		return AjaxList[AjaxId]['Heading'];	
	}
	else {
		return 'All';
	}
}

function setAjaxSearchTitles(AjaxId){
	for(i = 0; i <= PageVars['AjaxDivs']; i++){
		if(document.getElementById('FocusDivText_' + i)){
			document.getElementById('FocusDivText_' + i).style.fontWeight = 'normal';
			DivName = getDivName(i);
			Search = getSearchQuery(i);
			if(Search){
				DivName = DivName + ": '"+ Search + "'";	
			}
			document.getElementById('FocusDivText_' + i).alt = DivName;
			document.getElementById('FocusDivText_' + i).title = DivName;
		}
	}	
	if(document.getElementById('FocusDivText_' + AjaxId)){
		document.getElementById('FocusDivText_' + AjaxId).style.fontWeight = 'bold';
	}
}

function DivFocus(AjaxId){
	PageVars['DivFocus'] = AjaxId;
	setAjaxSearchTitles(AjaxId);
	if(document.getElementById('SearchQuery')){
		document.getElementById('SearchQuery').focus();
		if(AjaxId == 0){
			ForceAll = 1;
		}
		else {
			ForceAll = 0;	
		}
		document.getElementById('SearchQuery').value = getSearchQuery(AjaxId);
		UpdateAjaxDivs(ForceAll,0,"&SearchQuery=" + getSearchQuery(AjaxId) + "&DivFocus=" + AjaxId,"");			
		document.getElementById('SearchQuery').select();		
	}
}

function UpdateAjaxDivs(forceall,choosediv,newdata,ignoreupdate){
	if(choosediv){
			AjaxData("AjaxResults_" + choosediv,AjaxList[choosediv]['Url'] + "?CurrentPage=" + PageVars['CurrentPage'] + "&AjaxId=" + choosediv + newdata);		
	}
	else {
		if(PageVars['DivFocus'] > 0 && forceall == '0'){
			AjaxData("AjaxResults_" + PageVars['DivFocus'],AjaxList[PageVars['DivFocus']]['Url'] + "?CurrentPage=" + PageVars['CurrentPage'] + "&AjaxId=" + PageVars['DivFocus'] + newdata);
		}
		else {	
			for(i = 1; i <= PageVars['AjaxDivs']; i++){
//				AjaxData("AjaxResults_" + i,AjaxList[i]['Url'] + "?CurrentPage=" + PageVars['CurrentPage'] + "&AjaxId=" + i + newdata);
				if(""+i+"" !== ""+ignoreupdate+""){
					setTimeout("AjaxData('AjaxResults_" + i + "','" + AjaxList[i]['Url'] + "?CurrentPage=" + PageVars['CurrentPage'] + "&AjaxId=" + i + newdata + "');",100);
				}
			}
		}
	}
}

function FillDiv(Div,Data){
	if(document.getElementById(Div).divopen){
		document.getElementById(Div).divopen = false;
		document.getElementById(Div).innerHTML = document.getElementById(Div).StartData;
	}
	else {
		document.getElementById(Div).divopen = true;
		document.getElementById(Div).StartData = document.getElementById(Div).innerHTML;
		document.getElementById(Div).innerHTML = Data;
	}
}

function HoverDiv(url, title){
	tb_show(title,url+"&keepThis=true&TB_iframe=true",0)
}

function clickAction(Action, AjaxId){
	Action = Action.split("|");	
	
	Allow = true;
	if(Action[0] !== 'HoverDiv'){
		if(Action[2]){
			Action[2] = DataReplace('<br />','\n',Action[2])
			if(!confirm(Action[2])){
				Allow = false;	
			}
		}
	}
	
	if(Allow){
		switch(Action[0]){
			case "Ajax":
				//run ajax command
				UpdateAjaxDivs(0,AjaxId,Action[1],"");
				UpdateAjaxDivs(1,0,'',AjaxId);				
				break;
				
			case "HoverDiv":
				//display div with faded background
				tb_show(Action[2],Action[1]+"&keepThis=true&TB_iframe=true",0);
				break;
		}
	}
}

function runAction(row,form){
	Action = document.getElementById('Action' + row).value;
	Action = Action.split("|");	

	Allow = true;
	if(Action[0] !== 'HoverDiv'){
		if(Action[2]){
			Action[2] = DataReplace('<br />','\n',Action[2])
			Action[2] = DataReplace('<br>','\n',Action[2])
			if(!confirm(Action[2])){
				Allow = false;	
			}
		}
	}
	if(Allow){
		switch(Action[0]){
			case "Link":
				//send the page to the link
				document.getElementById('ActionUrl' + row).value = Action[1];
				form.submit();
				break;
				
			case "Ajax":
				//run ajax command
				AjaxId = row.split("-");
				UpdateAjaxDivs(0,AjaxId[1],Action[1],"");
				UpdateAjaxDivs(1,0,'',AjaxId[1]);				
				break;
				
			case "HoverDiv":
				//display div with faded background
				document.getElementById('Action' + row).focus();
				tb_show(Action[2],Action[1]+"&keepThis=true&TB_iframe=true",0)
				break;
		}
	}
}