var ajaxReq          = null;
var ajaxDoc          = new newajaxDoc();
var IE;

/* functions to extend string handling */

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

// JavaScript Document
// Global vars for setting map center and radius
// used in previous iteration (< 6.1.0 dll) of navigation & distance sort
// var gmylat = '';
// var gmylong = '';
// var gradius = '40';

/* legacy -- Do Not Use -- 
function setGeoFromURL() {
	var myURL = document.location.href;
	var domain1 = /finditwhistler/i;
	var domain2 = /finditsquamish/i;
	
	if (myURL.search(domain1) != -1) {
		gmylat = '50.119571';
		gmylong = '-122.954084';
	}
	else if (myURL.search(domain2) != -1) {
		gmylat = '49.749674';
		gmylong = '-123.135975';
	}
	else {
		gmylat = '49.401486';
		gmylong = '-123.511432';
	}
}
*/

/* legacy -- Do Not Use -- 
function assembleDistURL(linktarget,linktype,linksubtype) {
	pattern = /(?:.*)(?:.com)/i;
	mydomain = pattern.exec(linktarget);
	setGeoFromURL();
	qlat = '&latitude=' + gmylat;
	qlong = '&longitude=' + gmylong;
	// qsrt = '&distancesort=1';
	qunit = '&distanceunit=miles';
	qrad = '&distance=' + gradius;
	
	if (mydomain != '' && linktype != '' && linksubtype != '') {
		completeurl = mydomain + '/apps/pbcs.dll/cce?module=99&class=999' + '&type=' + linktype + '&subtype=' + linksubtype + qlat + qlong + qunit + qrad;
	}
	else if (mydomain != '' && linktype != '') {
		completeurl = mydomain + '/apps/pbcs.dll/cce?module=99&class=999' + '&type=' + linktype + qlat + qlong + qunit + qrad;
	}
	else {
		alert("empty");
	}
	//alert(qlat);
	//alert(qlong);
	//alert(qrad);

	return completeurl;
}
*/

function modifyField(field)  {
	if (field.value=='Search')	{
		field.value='';
	} else {
		if (field.value=='')  {
			field.value='Search';	
		}		
	}
}

function newajaxDoc() {
	this.response = {};
	this.lat = "";
	this.lon = "";
	this.ajaxDocError = "";
}

function validateBasicSearch()  {
	var arrSearchTerms = new Array();
	// PM added code to strip leading and trailing spaces before split
	
	 
		var srch= document.basicSearchForm.txtSearch.value.trim();
		if (srch)
		{
		//("["+srch+"]");
		srch = srch.replace(/\s+/g,' ');
		//alert("["+srch+"]");
	arrSearchTerms = srch.split(' ');
		
	
	//Not sure whether to do And or Or searches.  We'll start with And.
	document.basicSearchForm.txtSearchFastFormatted.value ="xml#"+arrSearchTerms.join(' and xml#');
	// alert(document.basicSearchForm.txtSearchFastFormatted.value);
	  }
	
	
	if (document.basicSearchForm.chkOnlyCoupons.checked == true)  {
		document.basicSearchForm.txtOnlyCoupons.value = '1';
	}
	
	// 'I'm looking for...' form handling
	if (document.basicSearchForm.txtSearchFastFormatted.value == '')  {
		//document.basicSearchForm.Distance.value = '';
		// document.basicSearchForm.DistanceSort.value = '0';
	}
		



	// 'Near...' form handling	
	if (document.basicSearchForm.originZip.value == '')	{
		/* setGeoFromURL();	 Replaced by global lat/long assignment */		
		document.basicSearchForm.Latitude.value = mpg_lat_js;
		document.basicSearchForm.Longitude.value = mpg_long_js;
		//alert(document.basicSearchForm.Latitude.value);
		//alert(document.basicSearchForm.Longitude.value);
	} 
	else {
		//alert(document.basicSearchForm.Latitude.value);
		//alert(document.basicSearchForm.Longitude.value);
	}			
	//alert(document.basicSearchForm.Distance.value);
}

function validateBasicSearchWDistanceFrom()  {
	var arrSearchTerms = new Array();	
	
	arrSearchTerms = document.basicSearchForm.txtSearch.value.split(' ');	
	
	//Not sure whether to do And or Or searches.  We'll start with And.
	document.basicSearchForm.txtSearchFastFormatted.value = arrSearchTerms.join(' and ');
	
	if (document.basicSearchForm.chkOnlyCoupons.checked == true)  {
		document.basicSearchForm.txtOnlyCoupons.value = '1';
	}
	
	$(function()
	{
		alert("anything.");
		/*
		$.post("http://maps.google.com/maps/geo?q=01255&key=ABQIAAAACwPcDlsk_B_OErICnm18HRQy7kmNP43PvjpUJkNs8-gGJC2XSxQVAY6AicW4I1kMg7t7d9JBlwR3YQ&sensor=flase&output=json", function(data){			
			alert(data);			
			// setLatLonFromJSON(data);
		}, "json")
		*/
	}); 
	/* processGeocodeRequest(document.basicSearchForm.origintxt.value); */
	
}

function newWindow(mypage,myname,w,h,scroll) {
	LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
	TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
	settings = 'width='+w+',height='+h+',scrollbars='+scroll+',resizable';
	win = window.open(mypage,myname,settings);
}

function checksortsubmit() {
	if (document.frmListSort.listSort.value == 'default')  {
		document.frmListSort.selectedIndex = '0';
	}
	else if (document.frmListSort.listSort.value == 'coupon')  {
		document.frmListSort.selectedIndex = '1';
	}
	else {
		document.frmListSort.selectedIndex = '2';
	}
	document.frmListSort.submit(); 
}

function dosubmit(submittedAction) {
//var hasclicked = 0;
var frmList = document.frmListSort;

//if (hasclicked == 1) {return false;}

if (submittedAction != "") {frmList.action = submittedAction;}
frmList.submit();
//hasclicked = 1;
}

function goBack()
  {
  window.history.back()
  }


 function newRequest() {
    if (IE == true)  {
      return new ActiveXObject("Microsoft.XMLHTTP");    
    } else {
      return new XMLHttpRequest();
    }
  } // newRequest()
  
   function processAjax() {
    if ((ajaxReq.readyState == 4) && (ajaxReq.status == 200)) {
      ajaxDoc.response  = ajaxReq.responseText;
      ggeocoderesponse  = ajaxDoc;
    }
  } // processAjax()  


 function setLatLonFromJSON(data) {
 var latlon;
 
 latlon = data;
 alert(latlon);
}
 	
 function assembleaddress(address) {  	
  	var aCreateUrl     = "http:\/\/maps.google.com\/maps\/geo?q=";
   	var othergeoparams = "&key=ABQIAAAACwPcDlsk_B_OErICnm18HRQy7kmNP43PvjpUJkNs8-gGJC2XSxQVAY6AicW4I1kMg7t7d9JBlwR3YQ&sensor=flase&output=json";
   	var addresstoparse = address;
   
   	aCreateUrl = aCreateUrl + addresstoparse + othergeoparams;
   	//alert(aCreateUrl);
		return aCreateUrl;
}
 	
  
   function processGeocodeRequest(addresstext) {    
   	tmp = assembleaddress(addresstext);
   	alert(tmp);
    try {
        ajaxReq = newRequest();
        ajaxReq.onreadystatechange = processAjax;
        ajaxDoc.response = ajaxReq.open("GET", tmp, true);
        setLatLonFromJSON();
    } catch(e) {
      alert(e);  
    }  
  } 
  
function cleanQryString(qry)
{
	
var start = qry.indexOf("?");
var saxaction= qry.substring(0,(start+1));
var pars = qry.substring((start+1));
var paramArray = pars.split('&');
var cleanStr ='';
var temp = '';
for (var i=0; i < paramArray.length; i++)
		{
		var ta = [];
		ta = paramArray[i].split("=");
		
		if (ta[1] != '')
			{
			
			// rename the search param to our internal name and escape the string 
			if (ta[0] == "Search") { 
				ta[0] = "txtSearchFastFormatted";
				ta[1] = escape(ta[1]);	
				}
			// debug --- temp += ta[0]+"="+ta[1]+"\n";
			paramArray[i] = ta[0]+"="+ta[1];
		  }	
		}
//alert(temp);
return saxaction+(paramArray.join("&"));  
} 

/*
 * Adjust form action / URL.
 * Called from next / previous item listings.
 * Adds origin coordinates, distance args and handles FAST search.
 */
function doNextPrev(nextPrevLink,searchstring) {
	/*
	* pass to a little function to modify the string to add our private search keyword field name
	* this function can be enhanced to conditionally do munging to discreet fields
	* in a way that is a little more straight forward than regular expressions
	*/  
  nextPrevLink = cleanQryString(nextPrevLink);
  //alert(nextPrevLink);return false;
	// set the 

	// code to handle prev/next navigation on type search when no free text search
	try
  {	
  	var typeArg = '';
	  var typ = document.basicSearchForm.temptype.value;
    if (typ != "" && searchstring =="")
    {
      typeArg += "&Type=" + typ;
      nextPrevLink += typeArg;
    }
  }
  catch(error)
	{
	  alert("error setting type from temptype");		
	}

  document.basicSearchForm.action = nextPrevLink 
  document.basicSearchForm.submit();
}