// JavaScript Document
/*************************
* 
*  Misc functions
*
***************************/

// trim function used to trim leading and traing blans from text string
$(document).ready(function(){ 
	document.getElementById("CitySearch").value='';
	document.getElementById("StateSearch").selectedIndex=0;
	$('#CitySearch').attr('disabled', 'disabled');
	$('#StateSearch').attr('disabled', 'disabled');
	$('#ZipSearch').attr('disabled', '');
	//$('fieldset').corner("5px");
	//$('#countryBox').corner("5px");
	//$('#submituglocator').corner("2px");
}); 



String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ReplaceAll = function(stringToFind,stringToReplace){
    var temp = this;
    var index = temp.indexOf(stringToFind);
        while(index != -1){
            temp = temp.replace(stringToFind,stringToReplace);
            index = temp.indexOf(stringToFind);
        }
        return temp;
		//alert(temp);
 }
/*******************************************************************
*
* funtcion to set enter key as a onclick event for a given button as 
* forms are not 'submited', they are processed by an onclick event.
*
*********************************************************************/
//function searchKeyPress(e)   { 
//          if (window.event) { e = window.event; } 
//       if (e.keyCode == 13) 
//        { 
 //          document.getElementById('submituglocator').click(); 
 //        } 
 //} 


/*******************
*
* Set Global vars
*
********************/
var mapObj = new mapquestCFC();

/**************************************************
*
* Method to get all POI's (Points of interest)
* from database based on country and zip,
* or city or address
* country will alwys be required
* method can accept zip or (address and city) or city
*
*****************************************************/

getPOI_noMap = function() {
	mapObj.setCallbackHandler(poi_nomapHandler);
	//mapObj.getPOI(getDTStyle_type(),getVARCountry(),getVARZip(),getVARAddress(),getVARCity());
	mapObj.getPOI_noMap(getDTStyle_type(),getVARCountry());
	}

poi_nomapHandler = function(returndata) {
	var poiDiv = document.getElementById("poi_list");
	x='';
	for(i=0;i<returndata.length;i++) {
	newImage1= "url(/includes/uglocator/images/"+getImageName(returndata[i].DTSTYLE)+".png)  no-repeat";
	x =	x + '<div style="background:url(/includes/uglocator/images/'+getImageName(returndata[i].DTSTYLE)+'.png)"  id="VARline'+(parseInt(i)+1)+'" class="certtype" >'+(parseInt(i)+1)+'</div>' +'<div class="addressDiv">&nbsp;<a href="/swugn/calendar/ugdetails.htm?id='+returndata[i].ID+'">'+ returndata[i].COMPANYNAME+'</a><br />';
	
	x =	x + '<strong>'+returndata[i].GROUPCITY+'</strong><br />';
	x =	x + returndata[i].ADDRESS1+'<br />';
	x =	x + returndata[i].CITY+'';
	if (returndata[i].CITY.trim() !='') {
	x =	x + ', '+returndata[i].STATE;
	} 
	x =	x + '</div><br style="clear:both" />';

	}
	poiDiv.innerHTML=x;
}




getPOI = function() {
	mapObj.setCallbackHandler(poiHandler);
	mapObj.getPOI(getDTStyle_type(),document.getElementById('poiform').CountrySearch.value,document.getElementById('poiform').ZipSearch.value,document.getElementById('poiform').CitySearch.value,document.getElementById('poiform').StateSearch.value, document.getElementById('poiform').latitude.value, document.getElementById('poiform').longitude.value, document.getElementById('poiform').id.value);
	}

poiHandler = function(returndata) {
	var poiDiv = document.getElementById("poi_list");
	x='';
	for(i=0;i<returndata.length;i++) {
		//newImage1= "url(/includes/uglocator/images/"+getImageName(returndata[i].DTSTYLE)+".png)  no-repeat";
		if (returndata[i].SINGLEPOI == 0) {
			newImage1= "url(/includes/uglocator/images/"+getImageName(returndata[i].DTSTYLE)+".png)  no-repeat";
			x =	x + '<div style="background:url(/includes/uglocator/images/'+getImageName(returndata[i].DTSTYLE)+'.png)"  id="VARline'+(parseInt(i)+1)+'" class="certtype" >'+(parseInt(i)+1)+'</div>' +'<div class="addressDiv">&nbsp;<a href="/swugn/calendar/ugdetails.htm?id='+returndata[i].ID+'">'+ returndata[i].COMPANYNAME+'</a><br />';
		} else {
			x =	x + '<div style="background:url(/includes/uglocator/images/'+getSinglePOIImage()+'.png)"  id="VARline'+(parseInt(i)+1)+'" class="certtype" ></div>' +'<div class="addressDiv">&nbsp;'+ returndata[i].COMPANYNAME+'<br />';
			
		}
		x =	x + '<strong>'+returndata[i].GROUPCITY+'</strong>';
		//x =	x + returndata[i].CITY+'';
		if (returndata[i].GROUPSTATE.trim() !='') {
			x =	x + ', <strong>'+returndata[i].GROUPSTATE+'</strong>';
		} 
		x =	x +'<br />'
		if (returndata[i].SINGLEPOI == 0) {
			if (returndata[i].COUNTRY=='United States') {
				x =	x + returndata[i].DIST+' Miles away<br />';
			} else {
				x =	x + returndata[i].DIST+' Kilometers away<br />';	
			}
		}
		if (returndata[i].SINGLEPOI == 1) {
			x =	x + returndata[i].ADDRESS1+'<br />';
			if (returndata[i].ZIP !='') {
			x =	x + returndata[i].ZIP+'<br />';
			}
		}
		
			x =	x + '</div><br style="clear:both" />';
	}
	poiDiv.innerHTML=x;
}

/*******************************************************
* Methods used to process maps
********************************************************/
// method used when click on a specific zoom level on the zoom slider
getMapZoom = function(zoom) {
	
	if (zoom <=14 || zoom >=1) { // only zoom if valid zoom range
		document.getElementById('mapview').slider.value=zoom;
		ColdFusion.Ajax.submitForm('mapview','/includes/uglocator/CFC/maps.cfc?method=buildmapsession&returnformat=JSON', resultRegHandler, editErrorHandler); 
	}
	
}	
// method used when zooming in and zooming out
zoomInOut = function(zoom) {
	
	var strZoom=zoom;
	intSlider=document.getElementById('mapview').slider.value;
	if ((strZoom == 'in' && intSlider !=0 )|| (strZoom == 'out' && intSlider !=14)) {
		if (strZoom == 'in') {
			document.getElementById('mapview').slider.value=parseInt(intSlider)-1;
		} else {
				document.getElementById('mapview').slider.value=parseInt(intSlider)+1;
		}
	ColdFusion.Ajax.submitForm('mapview','/includes/uglocator/CFC/maps.cfc?method=buildmapsession&returnformat=JSON', resultRegHandler, editErrorHandler);
	
	} 
}	
// method used when click on the East, West, North, or South Navigation divs
panMap = function(direction) {
	
	if (direction=='E' || direction =='W' | direction=='N' | direction=='S') { // only pan if valid direction
		var strDirection=direction;
		//intSlider=document.getElementById('mapview').slider.value;
		document.getElementById('mapview').pan.value=strDirection;
		ColdFusion.Ajax.submitForm('mapview','/includes/uglocator/CFC/maps.cfc?method=buildmapsession&returnformat=JSON', resultRegHandler, editErrorHandler);
	} 
}	

// method used to get map of VAR when click on the VAR link in the VAR list
function getVARMap(id,lng,lat,rc) {
	document.getElementById('poiform').latitude.value=lat;
	document.getElementById('poiform').id.value=id;
	document.getElementById('poiform').longitude.value=lng;
	document.getElementById('poiform').result_code.value=rc;
	document.getElementById('mapview').result_code.value=rc;
	document.getElementById('poiform').DTStyle_type.value=getDTStyle_type();
	document.getElementById('mapview').DTStyle_type.value=getDTStyle_type();
	document.getElementById('mapview').longitude.value=lng;
	document.getElementById('mapview').latitude.value=lat;
	document.getElementById('mapview').id.value=id;
	document.getElementById('poiform').certImage.value=getSWImage();
	document.getElementById('poiform').nonCertImage.value=getSimulationImage();
	
	ColdFusion.Ajax.submitForm('poiform','/includes/uglocator/CFC/maps.cfc?method=buildMapLatLng&returnformat=JSON', resultRegHandler2, editErrorHandler);
}

function validateCountry(country) {
	var countryObj = new mapquestCFC();
	countryObj.setCallbackHandler(countryHandler);
	countryObj.validate_Country(countryname=country);
	}


// method used to get data and geocode info to get map default location
// will retrun invalid zip message if zip not retruning valid confidence code by mapquest
// see geoHandler



function validate_zip() {
	var geoObj = new mapquestCFC();
	geoObj.setCallbackHandler(geoHandler);
	geoObj.geocode(countryname=getVARCountry(),zip=getVARZip(),state=getVARState(),city=getVARCity());
	}
// used to center map when click on map location
function getImg (evt) {
	
	var img_x;
	var img_y;
	if (document.all) { // MSIE
		
		img_x = evt.offsetX;
		img_y = evt.offsetY;
	} else { // Netscape, etc.
		
		img_x = mouseX(evt);
		img_y = mouseY(evt);
		for (var offMark = evt.target; offMark;
			offMark = offMark.offsetParent) {
			img_x -= offMark.offsetLeft;
		}
		for (var offMark = evt.target; offMark;
			offMark = offMark.offsetParent) {
			img_y -= offMark.offsetTop;
		}
	}
	
	//if (img_x >=0 && img_x >=0) {
		document.getElementById('mapview').x.value=img_x;
		document.getElementById('mapview').y.value=img_y;
		var coordinates = 'x: ' + img_x + ', y: ' + img_y;
		ColdFusion.Ajax.submitForm('mapview','/includes/uglocator/CFC/maps.cfc?method=buildmapsession&returnformat=JSON', resultRegHandler, editErrorHandler);
	//}
}
/*******************************************************
* Result Handlers 
********************************************************/
/********************************************************************
* Result Handler for getVARMap, zoomInOut, getMapZoom, panMap
**********************************************************************/
function resultRegHandler(x) {
		y=ColdFusion.JSON.decode(x);
		// set pan / zoom form session id to the session id returned whne building map
		// set pan back to blank
		document.getElementById('mapview').pan.value='';
		document.getElementById('mapview').x.value='';
		document.getElementById('mapview').y.value='';
		document.getElementById('mapview').session.value=y.SESSIONID;
		document.getElementById('mapview').longitude.value=y.LONGITUDE;
		document.getElementById('mapview').latitude.value=y.LATITUDE;
		document.getElementById('mapview').DTStyle_type.value=getDTStyle_type();
		var resultDiv = document.getElementById("maparea");
		resultDiv.style.marginLeft='0px';
		resultDiv.style.marginTop='0px';
		resultDiv.innerHTML = '<IMG NAME="xy" SRC="'+y.MAPURL4+'" onClick="getImg(event)" border="0" >';
		getPOI();
		setSlider(y.SLIDER);
	}
	
function resultRegHandler2(x) {
		y=ColdFusion.JSON.decode(x);
		document.getElementById('mapview').pan.value='';
		document.getElementById('mapview').x.value='';
		document.getElementById('mapview').y.value='';
		document.getElementById('mapview').session.value=y.SESSIONID;
		document.getElementById('mapview').longitude.value=y.LONGITUDE;
		document.getElementById('mapview').latitude.value=y.LATITUDE;
		document.getElementById('mapview').DTStyle_type.value=getDTStyle_type();
		var resultDiv = document.getElementById("maparea");
		resultDiv.style.marginLeft='0px';
		resultDiv.style.marginTop='0px';
		resultDiv.style.display='block';
		//resultDiv.innerHTML = '<INPUT TYPE="image" NAME="xy" SRC="'+y.MAPURL4+'" ISMAP="" onClick="getImg(event)" border="0">';
		resultDiv.innerHTML = '<IMG NAME="xy" SRC="'+y.MAPURL4+'" onClick="getImg(event)" border="0" >';
		
		//getSinglePOI();
		getPOI();
		setSlider(y.SLIDER);
		
		
	}	
/*************************************************
* geoHandler Result Handler for validate_zip
* also validates for valid zip code confdence code retruned from mapquest
*************************************************/
geoHandler = function(returndata) {
	// blank out session on new search 
	document.getElementById('mapview').ZipSearch.value=getVARZip();
	document.getElementById('mapview').CountrySearch.value=getVARCountry();
	document.getElementById('mapview').CitySearch.value=getVARCity();
	document.getElementById('mapview').StateSearch.value=getVARState();
	document.getElementById('mapview').DTStyle_type.value=getDTStyle_type();
	document.getElementById('mapview').session.value='';
	document.getElementById('uglocatorForm').SWImage.value=getSWImage();
	document.getElementById('uglocatorForm').SimulationImage.value=getSimulationImage();
	
if (document.getElementById('uglocatorForm').mapquest.value==1 && getVARCountry()!='Mexico') {
	
	if( (returndata.RESULTCODE.charAt(0)=='Z' && returndata.RESULTCODE.charAt(returndata.RESULTCODE.length-1)=='A') ||
	(returndata.RESULTCODE.charAt(0)=='A' && returndata.RESULTCODE.charAt(1)=='5' && (returndata.RESULTCODE.charAt(returndata.RESULTCODE.length-2)=='A' || returndata.RESULTCODE.charAt(returndata.RESULTCODE.length-2)=='B' || returndata.RESULTCODE.charAt(returndata.RESULTCODE.length-2)=='C')) )
	{
	$('#keyimage').show('fast');
	ColdFusion.Ajax.submitForm('uglocatorForm','/includes/uglocator/CFC/maps.cfc?method=buildMapGeoCode&returnformat=JSON', resultRegHandler1, editErrorHandler);
	} else {
		
		alert("You have entered either: \n\nan invalid Postal Code\nan invalid City and State \nor an invalid City\n\nfor the country =  "+getVARCountry());
		
		// blank out zip and gize aip field focus....
		document.getElementById('uglocatorForm').ZipSearch.value='';
		document.getElementById('uglocatorForm').ZipSearch.focus();

	}
} else// mapquest==1
{ //mapquest=0
getPOI_noMap();
if (getVARCountry()=='Australia' ) {
	var imgname='austrailia.gif'
	}
if ( getVARCountry()=='New Zealand') {
	var imgname='newzealand.gif'
	}
if ( getVARCountry()=='Indonesia') {
	var imgname='Indonesia.gif'
	}
if ( getVARCountry()=='India') {
	var imgname='India.gif'
	}
if (getVARCountry()=='Brazil' || getVARCountry()=='Argentina') {
	var imgname='brazil.gif'
	}
if (getVARCountry()=='Mexico' ) {
	var imgname='mexico.gif'
	}
if (getVARCountry()=='Japan' ) {
	var imgname='japan.gif'
	}
if (getVARCountry()=='China' || getVARCountry()=='India') {
	var imgname='mainasia.gif'
	}
if (getVARCountry()=='Ukraine' || getVARCountry()=='Russia') {
	var imgname='ukraine.gif'
	}	
//$('#keyimage').hide('fast');
$('#keyimage').show('fast');
var resultDiv = document.getElementById("maparea");
resultDiv.style.marginLeft='20px';
resultDiv.style.marginTop='20px';
resultDiv.innerHTML = '<img id="img1" src="/includes/uglocator/images/'+imgname+'" width="400" height="350" />';
document.getElementById('ps').style.display='none';
document.getElementById('pw').style.display='none';
document.getElementById('pe').style.display='none';
document.getElementById('pn').style.display='none';
document.getElementById('mapsliderarea').style.display='none';
	}
}


countryHandler = function(returndata) {
	if (returndata.MAPQUEST==0 || returndata.COUNTRY=='Mexico') {
		document.getElementById('uglocatorForm').mapquest.value='0';
		document.getElementById('mapview').mapquest.value='0';
		document.getElementById('poiform').mapquest.value='0';
		//$('#postalDiv').hide('fast');
		//$('#cityDiv').hide('fast');
		$('#locationDiv').hide('fast');
		document.getElementById('buttonDiv').style.marginLeft='90px';
		document.getElementById('uglocatorForm').ZipSearch.value='';
		document.getElementById('mapview').ZipSearch.value='';
		document.getElementById('poiform').ZipSearch.value='';
	} else {
		//$('#postalDiv').show('fast');
		//$('#cityDiv').show('fast');
		$('#locationDiv').show('fast');
		$('#locationtype1').attr('checked', 'checked');
		$('#locationtype0').attr('checked', '');
		document.getElementById('buttonDiv').style.marginLeft='365px';
	
		document.getElementById('uglocatorForm').mapquest.value='1';
		document.getElementById('mapview').mapquest.value='1';
		document.getElementById('poiform').mapquest.value='1';

	}
	if (returndata.COUNTRY=='Canada' || returndata.COUNTRY=='United States' ) {
		//$('#StateSearch').attr('disabled', '');
		$('#stateDiv').show('fast');
	} else {
		//$('#StateSearch').attr('disabled', 'disabled');
		$('#stateDiv').hide('fast');
		
	}
}
/********************************************************************
* Result Handler for geoHandler when zip code confience level is high
**********************************************************************/	
function resultRegHandler1(x) {
		document.getElementById('poiform').id.value='';
		document.getElementById('mapview').id.value='';
		y=ColdFusion.JSON.decode(x);
		document.getElementById('poiform').CountrySearch.value=getVARCountry();
		document.getElementById('poiform').ZipSearch.value=getVARZip();
		document.getElementById('poiform').CitySearch.value=getVARCity();
		document.getElementById('poiform').StateSearch.value=getVARState();
		document.getElementById('poiform').DTStyle_type.value=getDTStyle_type();
		// set pan / zoom form session id to the session id returned whne building map
		document.getElementById('mapview').session.value=y.SESSIONID;
		document.getElementById('mapview').longitude.value=y.LONGITUDE;
		document.getElementById('mapview').latitude.value=y.LATITUDE;
		document.getElementById('mapview').DTStyle_type.value=getDTStyle_type();
		var resultDiv = document.getElementById("maparea");
		resultDiv.style.marginLeft='0px';
		resultDiv.style.marginTop='0px';
		//resultDiv.innerHTML = '<INPUT TYPE="image" NAME="xy" SRC="'+y.MAPURL4+'" ISMAP="" onClick="getImg(event)" border="0" >';
		resultDiv.innerHTML = '<IMG NAME="xy" SRC="'+y.MAPURL4+'" onClick="getImg(event)" border="0" >';
		// gets lisst of poi's
		
		getPOI();
		// sets slider
		setSlider(y.SLIDER);
		
		
	}
/**********************************
*
* Default error Handler whne building 
* maps
* 
***********************************/
function editErrorHandler() {
		alert("Error Occured while processing Map, please try again later");
	}	

/**********************************
*
* Method to get address information 
* from form fields
*
***********************************/
//get country info
getVARCountry = function() {
	var strCountry = document.getElementById('uglocatorForm').CountrySearch.value;
	return strCountry.trim();
	}
// get zip
getVARZip = function() {
	var strZip = document.getElementById('uglocatorForm').ZipSearch.value;
	return strZip.trim();
	}
// get address - mostlike used with hong kong and ireland
getVARAddress = function() {
	var strAddress=''
	return strAddress.trim();
	}
// get city	 - mostlike used with hong kong and ireland
getVARCity = function() {
	var strCity=document.getElementById('uglocatorForm').CitySearch.value;
	if (getVARCountry()=='France') {
		strCity=strCity.ReplaceAll(" ", "-");
		}
	
	return strCity.trim();
	}
getVARState = function() {
	var strState=document.getElementById('uglocatorForm').StateSearch.value;
	return strState.trim();
	}
// gets style type to get from DB 3402=all 3400= non cert 3401=cert 
// currently gets 3402 only as this isi in a hidden form field
getDTStyle_type = function() {
	//alert(document.getElementById('uglocatorForm').DTStyle_type.value);
	var strDTStyle=document.getElementById('uglocatorForm').DTStyle_type.value;
	return strDTStyle.trim();
	
	}	
/*********************************************
*
* populates form field for images used in map
* change the image name here if need to change 
* image for certified and non certified VARS
* Also needs to be changed on maps.cfc
*
********************************************/
getImageName = function(dtstyle) {
	if (dtstyle==3301) {
	var i = getSWImage();
	} else {
		var i = getSimulationImage();
		}
	return i;
	}	
getSWImage = function() {
	var i = 'MQ00404';
	return i;
	}	

getSimulationImage = function() {
	var i = 'MQ00403';
	return i;
	}		
getSinglePOIImage = function() {
	var i = 'MQ00031';
	return i;
	}	

//function submitform() {
//	document.getElementById("varlocatorForm").submit();
//}

/********************************************
*
* Misc and supporting functions/  methods
*
************************************************/

// used with getImg() function
function mouseX(evt) {
if (evt.pageX) return evt.pageX;
else if (evt.clientX)
   return evt.clientX + (document.documentElement.scrollLeft ?
   document.documentElement.scrollLeft :
   document.body.scrollLeft);
else return null;
}
function mouseY(evt) {
if (evt.pageY) return evt.pageY;
else if (evt.clientY)
   return evt.clientY + (document.documentElement.scrollTop ?
   document.documentElement.scrollTop :
   document.body.scrollTop);
else return null;
}

// sets slider value used with
// resultHandler() and resultHandler1()
function setSlider(data) {
	var sliderform='';
	document.getElementById('mapview').slider.value=data;
	var i=0
	for(i=0;i<=14;i++) {
		sliderform='slider'+i;
		if (i==data) {
			eval("document.getElementById('"+sliderform+"').className='slideselect';");
			eval("document.getElementById('"+sliderform+"').onmouseout=function() {this.className='slideselect';}");
		} else {
			eval("document.getElementById('"+sliderform+"').className='slidenormal';");
			eval("document.getElementById('"+sliderform+"').onmouseout=function() {this.className='slidenormal';}");
		
		}
		//document.getElementById('mapOpeningDiv').style.display='none';
		//getElementById('mapDiv').style.display='block';
		//document.getElementById('mapareatotal').style.display='block';
		document.getElementById('ps').style.display='block';
		document.getElementById('pw').style.display='block';
		document.getElementById('pe').style.display='block';
		document.getElementById('pn').style.display='block';
		document.getElementById('mapsliderarea').style.display='block';
		
	}
}
displayZip = function(data) {
	if (data == 0) {
		document.getElementById("ZipSearch").value='';
		
		$('#ZipSearch').attr('disabled', 'disabled');
		$('#CitySearch').attr('disabled', '');
		$('#StateSearch').attr('disabled', '');
		} 
	else {
		document.getElementById("CitySearch").value='';
		document.getElementById("StateSearch").selectedIndex=0;
		$('#CitySearch').attr('disabled', 'disabled');
		$('#StateSearch').attr('disabled', 'disabled');
		$('#ZipSearch').attr('disabled', '');
	}
	}
