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+$/,"");
}

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 = "";
}

/*
 * process and validate the basicSearchForm.
 * Callback function of mapFuncs getSearchLocation() call.
 * @param response Result of the geocoder call.
 */ 
function validateBasicSearch(response)  {

  if (!response || response.Status.code != 200) {
    alert("Error: Geocoder Status Code:" + response.Status.code);
    return;
  }

  var placemark = response.Placemark[0];

  document.basicSearchForm.Latitude.value =  (placemark.Point.coordinates[1]) ? placemark.Point.coordinates[1]: mpg_lat_js;
  document.basicSearchForm.Longitude.value = (placemark.Point.coordinates[0]) ? placemark.Point.coordinates[0]: mpg_long_js;

  document.basicSearchForm.search.value = document.basicSearchForm.txtSearch.value.trim();

  // bst 20090823 added for origin address
  if (placemark.Point.address != '') {
  	document.basicSearchForm.OriginAddress.value = placemark.address;
  } 
  else if (document.basicSearchForm.originZip == '') {
  	document.basicSearchForm.OriginAddress.value = mpg_pubcity_js;
  }

//Pass correct city values
	var CitySelected = document.basicSearchForm.originZip.value;
	if (CitySelected.indexOf("Whistler")==0 || CitySelected.indexOf("Pemberton")==0 || CitySelected.indexOf("D'Arcy")==0 || CitySelected.indexOf("Mount Currie")==0){
		document.basicSearchForm.mpg_cityMultiSearch.value = "D''Arcy,Whistler,Pemberton,Mount Currie";	
	}

	if (CitySelected.indexOf("Sunshine Coast")==0 ||CitySelected.indexOf("Port Mellon")==0 || CitySelected.indexOf("Garden Bay")==0 || CitySelected.indexOf("Egmont")==0 || CitySelected.indexOf("Sechelt")==0 || CitySelected.indexOf("Madeira Park")==0 || CitySelected.indexOf("Roberts Creek")==0 || CitySelected.indexOf("Gibsons")==0 || CitySelected.indexOf("Halfmoon Bay")==0 || CitySelected.indexOf(" Grantham's Landing")==0){
		document.basicSearchForm.mpg_cityMultiSearch.value = "Sunshine Coast,Port Mellon,Garden Bay,Egmont,Sechelt,Madeira Park,Roberts Creek,Wilson Creek, Gibsons,Halfmoon Bay, Grantham''s Landing";	
	}
						
	if (CitySelected.indexOf("Brackendale")==0 || CitySelected.indexOf("Squamish")==0 || CitySelected.indexOf("Garibaldi Highlands")==0 || CitySelected.indexOf("Britannia Beach")==0 || CitySelected.indexOf("Furry Creek")==0){
		document.basicSearchForm.mpg_cityMultiSearch.value = "Brackendale,Squamish,Garibaldi Highlands,Britannia Beach,Furry Creek";	
	}

	if (CitySelected.indexOf("Ashcroft")==0 || CitySelected.indexOf("Barriere")==0 || CitySelected.indexOf("Cache Creek")==0 || CitySelected.indexOf("Chase")==0 || CitySelected.indexOf("Clearwater")==0 || CitySelected.indexOf("Kamloops")==0 || CitySelected.indexOf("Lac Le Jeune")==0 || CitySelected.indexOf("Pinatan Lake")==0 || CitySelected.indexOf("Savona")==0 || CitySelected.indexOf("Sun Peaks")==0){
		document.basicSearchForm.mpg_cityMultiSearch.value = "Ashcroft, Barriere, Cache Creek, Chase, Clearwater, Kamloops, Lac Le Jeune, Pinatan Lake, Savona, Sun Peaks";	
	}

	// don't include mpg_cityMultiSearch if free text search
  if (document.basicSearchForm.search.value != "") {
    document.basicSearchForm.mpg_cityMultiSearch.value = "";  // temp SOLR fix
  }

  document.basicSearchForm.submit();
}

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);  
    }  
  } 

/**
 * OBSOLETED by SOLR
 */
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("&"));  
} 

/*
 * OBSOLETED by SOLR
 * 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();
}
