var ajaxUrl = "";
var searchZip = "";
var searchBrand = "";
var searchRadius = "0";
var searchSortBy = "";
var searchFilter = "";
var searchType = "";

function ajaxRefresh(newSearchType) {
   // active dealer results div
   window.scrollTo(0,0);
   document.getElementById("dealerresultsloading").style.display = "block";
   document.getElementById("dealerresultswrapper").style.display = "none";
   searchSortBy=document.getElementById("searchSortBy").value;

   //the searchRadius select object must exist
   searchRadius=document.getElementById("searchRadius").value;
   if (newSearchType != null && newSearchType != '') {
	   searchType = newSearchType;
   }

   //show the radius dropdown for all Generator Proximity searches; hide it for all others
   var searchRadiusLabelObj = getSearchRadiusLabelElement();
   if (searchRadiusLabelObj != null) {
	   if (searchType == 'Proximity' && searchFilter == "Generator") {
		   searchRadiusLabelObj.style.display = 'block';
	   } else {
		   searchRadiusLabelObj.style.display = 'none';
	   }
   }

   ajaxRequest("dealersearchresults", "generatorDealerSearchMessage", "searchRadiusUsed");
}

function getDealerResults(showShortTitle) {

   // get params
   var FORM_DATA = createRequestObject();
   searchZip = FORM_DATA["searchZip"];
   searchSortBy = FORM_DATA["searchSortBy"];
   if(FORM_DATA["searchFilter"] != undefined) {
   	searchFilter = FORM_DATA["searchFilter"];
   }
   searchType = FORM_DATA["searchType"];
   searchBrand = "CA";
   var title;

   // check for home page zip
   if(FORM_DATA["zipcode"]) {
      searchZip = FORM_DATA["zipcode"];
   }

   //check the zip form data value if there is no searchZip value
   if (searchZip == null || searchZip == "") {
	   searchZip = FORM_DATA["zip"];
   }

   //show the radius dropdown for all Generator Proximity searches; hide it for all others
   var searchRadiusLabelObj = getSearchRadiusLabelElement();
   if (searchRadiusLabelObj != null) {
	   if (searchType == 'Proximity' && searchFilter == "Generator") {
		   searchRadiusLabelObj.style.display = 'block';
	   } else {
		   searchRadiusLabelObj.style.display = 'none';
	   }
   }

   // generator search 
   if(searchFilter == "Generator") {
	   if (searchRadiusLabelObj != null) {
		   searchRadiusLabelObj.style.display = 'none';
	   }
	  if (showShortTitle) {
		  title = "<h2>Dealers In Your Area &mdash; " + searchZip + "</h2>";
	  } else {
		  title = "<h1>Carrier Home Generator Dealer Locator</h1><h2>Dealers In Your Area &mdash; " + searchZip + "</h2>";
	  }

      if(searchRadius == undefined) {
         searchRadius = "50";
      }
   // FAD
   } else if(searchFilter == "FADOnly") {
	  if (showShortTitle) {
		  title = "<h2>Dealers In Your Area &mdash; " + searchZip + "</h2>";
	  } else {
		  title = "<h1>Carrier Factory Authorized Dealer Locator</h1><h2>Dealers In Your Area &mdash; " + searchZip + "</h2>";
	  }
      
      if(searchRadius == undefined) {
         searchRadius = "25";
      }
   // normal
   } else {
      if (showShortTitle) {
         title = "<h2>Dealers In Your Area &mdash; " + searchZip + "</h2>";
      } else {
         title = "<h1>Carrier Dealer Locator</h1><h2>Dealers In Your Area &mdash; " + searchZip + "</h2>";
      }
	  
      if(searchRadius == undefined) {
         searchRadius = "25";
      }
   }
 
   document.getElementById("dealerresultswrapper").innerHTML = title +  document.getElementById("dealerresultswrapper").innerHTML;

   // set sort by
   if(searchSortBy) {
      document.getElementById("searchSortBy").value = searchSortBy;
   }

   ajaxRequest('dealersearchresults', 'generatorDealerSearchMessage', 'searchRadiusUsed'); 
}

function ajaxRequest(divId, generatorMessageDivId, searchRadiusUsedDivId)
{ 
    // get the results
   ajaxUrl = '/apps/dealerlocatorws.jsp?searchZip=' + searchZip + '&searchBrand=' + searchBrand + '&searchRadius=' + searchRadius;
   if((searchSortBy != undefined) && (searchSortBy != "Please Select")) {
	   ajaxUrl += "&searchSortBy=" + searchSortBy;
   }
   if((searchFilter != undefined) && (searchFilter != "undefined")) {
	   ajaxUrl += "&searchFilter=" + searchFilter;
   }
   if((searchType != undefined) && (searchType != "undefined")) {
	   ajaxUrl += "&searchType=" + searchType;
   }
   var xhr; 
    try {  xhr = new ActiveXObject('Msxml2.XMLHTTP');   }
    catch (e) 
    {
        try {   xhr = new ActiveXObject('Microsoft.XMLHTTP');    }
        catch (e2) 
        {
          try {  xhr = new XMLHttpRequest();     }
          catch (e3) {  xhr = false;   }
        }
     }
  
    xhr.onreadystatechange  = function()
    { 
         if(xhr.readyState  == 4)
         {
              if(xhr.status  == 200) {
		  if(xhr.responseText.match(/Sorry, there are no dealers that match this criteria/)) {
		  	document.getElementById("sortLabel").style.display = "none";
			var searchRadiusLabelObj = getSearchRadiusLabelElement();
			if (searchRadiusLabelObj != null) {
				searchRadiusLabelObj.style.display = "none";
			}
		  }

		  // populate div with dealer results
		  document.getElementById(divId).innerHTML = xhr.responseText;

		 
		  if (document.getElementById('searchTypeUsed') != null) {
			  if (document.getElementById('searchTypeUsed').innerHTML == 'Proximity') {
				  // need to show the radius select box if this is a generator search
				  var searchRadiusLabelObj = getSearchRadiusLabelElement();
				  if (searchRadiusLabelObj != null && searchFilter == "Generator") {
					  searchRadiusLabelObj.style.display = "block";
				  }
			  }
		  }

		  // extract the actual search radius used and the generator dealer locator message
		  if(searchFilter == "Generator") {
			  // this is how to extract the generator dealer message (if there is one)
			  var noGeneratorDealerMessage = null;
			  if (document.getElementById('noGeneratorDealerMessage') != null) {
				  noGeneratorDealerMessage = document.getElementById('noGeneratorDealerMessage').innerHTML;
				  //alert('noGeneratorDealerMessage=' + noGeneratorDealerMessage);
			  }
			  
			  var genMessageDivId = document.getElementById(generatorMessageDivId);
			  if (genMessageDivId != null) {
				  if (noGeneratorDealerMessage != null && noGeneratorDealerMessage != '') {
					  //ugly hack to get this to render correctly in IE6. It was doing a weird double output of the
					  //content of this div.
					  var parent = genMessageDivId.parentNode;
					  parent.removeChild(genMessageDivId);
					  parent.appendChild(genMessageDivId);
					  genMessageDivId.innerHTML = noGeneratorDealerMessage;
				  } else {
					  genMessageDivId.innerHTML = '';
				  }
			  }

				//update the 'searchRadius' select box, if it exists, to show the actual search radius used
				if (document.getElementById(searchRadiusUsedDivId) != null) {
					var searchRadiusUsed = document.getElementById(searchRadiusUsedDivId).innerHTML;
					var searchRadiusSelect = document.getElementById('searchRadius');
					if (searchRadiusSelect != null) {
						//go through each option and if it's value == searchRadiusUsed, set that as the select's selectedIndex
						for (index = 0; index < searchRadiusSelect.length; index++) {
							if (searchRadiusSelect[index].value == searchRadiusUsed) {
								searchRadiusSelect.selectedIndex = index;
							}
						}
					}
				}

		  }
      
		  // active dealer results div
		  document.getElementById("dealerresultsloading").style.display = "none";
		  document.getElementById("dealerresultswrapper").style.display = "block";
              } else {
                 //alert("Error code " + xhr.status);
		  document.getElementById(divId).innerHTML += "<p>Our Find a Dealer tool is currently experiencing technical difficulties, please try your search again.</p>";

		  // active dealer results div
		  document.getElementById("dealerresultsloading").style.display = "none";
		  document.getElementById("dealerresultswrapper").style.display = "block";
	      }
         }
    }; 

   xhr.open("GET", ajaxUrl,  true); 
   xhr.send(null);
} 

function removeChildren(element) {
	  var children = element.childNodes;
	  var i = children.length;
	  while (i-- > 0) {
		  children[i].parentNode.removeChild(children[i]);
	  }
}

function getSearchRadiusLabelElement() {
	return document.getElementById("searchRadiusLabel");
}

function createRequestObject() {
  
  FORM_DATA = new Object();
    // The Object ("Array") where our data will be stored.
  
  separator = ',';
    // The token used to separate data from multi-select inputs
  
  query = '' + this.location;
 
    
  query = query.substring((query.indexOf('?')) + 1);
    // Keep everything after the question mark '?'.
  
  if (query.length < 1) { return false; }  // Perhaps we got some bad data?
  
  keypairs = new Object();
  numKP = 1;
 
    
  while (query.indexOf('&') > -1) {
    keypairs[numKP] = query.substring(0,query.indexOf('&'));
    query = query.substring((query.indexOf('&')) + 1);
    numKP++;
  
  }

  keypairs[numKP] = query;
    // Store what's left in the query string as the final keypairs[] data.
  
  for (i in keypairs) {
    keyName = keypairs[i].substring(0,keypairs[i].indexOf('='));
      // Left of '=' is name.
    keyValue = keypairs[i].substring((keypairs[i].indexOf('=')) + 1);
      // Right of '=' is value.
    while (keyValue.indexOf('+') > -1) {
      keyValue = keyValue.substring(0,keyValue.indexOf('+')) + ' ' + keyValue.substring(keyValue.indexOf('+') + 1);
        // Replace each '+' in data string with a space.
    }
    
    keyValue = unescape(keyValue);
      // Unescape non-alphanumerics
      
    if (FORM_DATA[keyName]) {
      FORM_DATA[keyName] = FORM_DATA[keyName] + separator + keyValue;
      
    } else {
      FORM_DATA[keyName] = keyValue;
        // Normal case: name gets value.
    }
  }

  return FORM_DATA;
}

// clear form values
<!--
function clearDefault(el) {
    if (el.defaultValue==el.value) el.value = ""
}

function openDealerMap(url) {
    var map = window.open(url,'dealermap','scrollbars=yes,resizable=yes,menubar=yes,width=675,height=525');
    map.focus();
}

function redirectSelect(field) { 
    var index = field.selectedIndex;
    var url = field.options[index].value;
    window.location = url;
    return false;
}

// -->

function DoSubmission() {
document.Search.submit();
document.Find.submit();
}
