﻿// JavaScript Document
var proxyURL = "/scripts/proxy/crossDomainProxy.aspx"
//var proxyURL = "http://10.121.2.100:30102/locator/proxy/crossDomainProxy.aspx";
var usingProxy = true;
//var apiURL = "../LocatorResultsAPI.asp";
var xslLocation = "/xsl/tier4/legacyLocator/";
var debugging = false;
var advancedFormURLMIIsales = "/?xhtml=xhtml/mii/us/en/minisite/sales/default.html&xsl=minisite.xsl";
var advancedFormURLMIIservice = "/?xhtml=xhtml/mii/us/en/minisite/service/default.html&xsl=minisite.xsl";
var advancedFormURLRDIservice = "/?xhtml=xhtml/rdi/us/en/minisite/service/default.html&xsl=minisite.xsl";
var advancedFormURLMBSsales = "/?xhtml=xhtml/mbs/us/en/minisite/salesreps/default.html&xsl=minisite.xsl";
var advancedFormURLMBSservice = "/?xhtml=xhtml/mbs/us/en/minisite/service/default.html&xsl=minisite.xsl";
var advancedFormURLKPRservice = "/?xhtml=xhtml/kpr/us/en/minisite/service/default.html&xsl=minisite.xsl";
var advancedFormURLWELsales = "/?xhtml=xhtml/wel/us/en/general/sales_locator.html";
var advancedFormURLWELservice = "/?xhtml=xhtml/wel/us/en/general/service_locator.html";
var advancedFormURLMCLsales = "/?xhtml=xhtml/mcl/us/en/distributorlocator/sales.html&xsl=distributorlocator.xsl";
var advancedFormURLMCLservice = "/?xhtml=xhtml/mcl/us/en/distributorlocator/service.html&xsl=distributorlocator.xsl";
var advancedFormURLTSTsales = "/?xhtml=xhtml/tst/us/en/minisite/richard/saleslocator.html&xsl=minisite.xsl";
var advancedFormURLTSTservice = "/?xhtml=xhtml/tst/us/en/minisite/richard/servicelocator.html&xsl=minisite.xsl";
//var advancedFormURL = "http://10.121.2.100:30102/locator/html/locatorAdvanced.html";


/////////////////////////////////////////////////////////////////////////////////////
//////////////////////Form Validate & Submit Fucntions///////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////
function processLocator(callType, callLocation, brand)
{
	var query = "";
	var functionWhenDone;
	if(callLocation == 'widget')
	{
		var query = "";
		var country = "";
		if (document.getElementById("countryUS"+callType).checked == true)
			country = "US";
		else
			country = "CA";
		
		if(country == "US")
		{
			var zipCode = document.getElementById("zipCode"+callType).value;
			if(zipCode.length < 5)
			{
				alert("US Zip Code needs to be a minimum of 5 numbers in length.");
				return 0;
			}
			else
				query += "country="+escape(country)+"&PostalCode="+escape(zipCode);
			
		}
		else // Canada
		{
			var city = document.getElementById("city"+callType).value;
			var province = document.getElementById("province"+callType).value;
			if(city.length == 0 || province.length == 0)
			{
				alert("Both City and Province must be selected.");
				return 0;
			}
			else
				query += "country=CA&city="+escape(city)+"&province="+escape(province);
		}
		
		switch(brand+callType)
		{
			case "MIIsales":
				window.location = advancedFormURLMIIsales+"&"+query;
				break;
			case "MIIservice":
				window.location = advancedFormURLMIIservice+"&"+query;
				break;
			case "RDIservice":
				window.location = advancedFormURLRDIservice+"&"+query;
				break;
			case "MBSservice":
				window.location = advancedFormURLMBSservice+"&"+query;
				break;
			case "MBSsales":
				window.location = advancedFormURLMBSsales+"&"+query;
				break;
			case "KPRservice":
				window.location = advancedFormURLKPRservice+"&"+query;
				break;
			case "TSTsales":
				window.location = advancedFormURLTSTsales+"&"+query;
				break;
			case "TSTservice":
				window.location = advancedFormURLTSTservice+"&"+query;
				break;
		}
		
	}
	
}

function salesWidgetResults(xmlDoc, xslDoc)
{
	// Check if xmlDoc is okay, if so then transform 
	var results = getTransformedNodeHTML(xmlDoc, xslDoc);
	document.getElementById('salesWidgetResults').innerHTML = results + '<br /><input type="button" value="Back" onclick="resetSalesWidget()" />';
	document.getElementById('salesWidgetForm').style.display = "none";
	document.getElementById('salesWidgetResults').style.display = "block";
	setMessage("", false);
	
}

function resetSalesWidget()
{
	document.getElementById('salesWidgetResults').style.display = "none";
	document.getElementById('salesWidgetForm').style.display = "block";
}

function submitForm()
{
	// Error checking before submission
	var error = "Please address the following and re-submit:\n";
	var locationString = "";
	var country = document.getElementById('country').value;
	if(country == "US" || country == "CA")
	{
		var city = document.getElementById('city').value;
		if(country == "US")
		{
			var zipCode = document.getElementById('zipCode').value;
			var state = document.getElementById('state').value;
			
			locationString += "country=US"
			
			if(zipCode.length <= 4 && (city.length == 0 || state.length == 0))
				error += "-Must enter either Zip Code or City and State\n";
			else
			{
				if(zipCode.length > 4)
					locationString += "&PostalCode="+zipCode;
				else
					locationString += "&city="+escape(city)+"&state="+escape(state);
			}
		}
		else
		{
			var province = document.getElementById('province').value;
			if(city.length == 0 || province.length == 0)
				error += "-Must enter City and Province\n";
			else
				locationString += "country=CA&city="+escape(city)+"&province="+escape(province);
		}
	}
	else
	{
		if(country.length == 0)
			error += "-Must select a Country\n";
		else
			locationString += "country="+escape(country);
	}
	
	// now have locationString, check for errors, if none then compile rest of query
	if (error != "Please address the following and re-submit:\n")
	{
		alert(error);
		return;
	}

	// Compiile other parameters of the form and send
	var queryString = locationString;
	if(document.getElementById('serviceTypeSales').checked) queryString += "&contact=SALES";
	if(document.getElementById('serviceTypeService').checked) queryString += "&contact=SERVICE";
	
	for(var i=1; i<10; i++)
		if(document.getElementById('productType'+i).checked) queryString += "&product="+escape(document.getElementById('productType'+i).value);
	
	if(usingProxy)
	{
		query = "?keyword=locator";
		query  += "&parameters="+escape(queryString);
		var xmlObject = new xmlObjectClass(proxyURL+query, "xml", "locator");
	}
	else
	{
		query = "?"+queryString;
		var xmlObject = new xmlObjectClass(apiURL+query, "xml", "locator");
	}
	if(debugging) alert(query);
	hideForm();
	setMessage("Sending Request...", true);
	var xslObject = new xmlObjectClass(xslLocation+"fullResults.xsl", "xsl", "locator");
	processXMLandXSLT(xmlObject, xslObject, genericOnStateChange, locatorResults);
}

function locatorResults(xmlDoc, xslDoc)
{
	var results = getTransformedNodeHTML(xmlDoc, xslDoc);
	document.getElementById('locatorResults').innerHTML = results;
	document.getElementById('locatorResults').style.display = "block";
	setMessage("", false);
	
}

function resetForm()
{
	// Opens the Sales and 
	setMoreInfo("advancedImage", "advancedOptions", true);
	setMoreInfo("locationImage", "locationOptions", true);
	// Remove any content in the results
	document.getElementById('locatorResults').innerHTML = "";
	
}
function hideForm()
{
	setMoreInfo("advancedImage", "advancedOptions", false);
	setMoreInfo("locationImage", "locationOptions", false);
}

function showErrors(xmlElementArray)
{
	var error = "The following errors occured:\n";
	for(var i=0; i< xmlElementArray.length; i++)
	{
		error += xmlElementArray[i].textContent + "\n";
	}
	alert(error);
}


/////////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////////
////////////////////////////AJAX Related Functions///////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////

function genericOnStateChange(xmlObject)
{
	if(xmlhttp.readyState!=4)
		setMessage("Getting Results...", true);
	if(xmlhttp.readyState==4 && xmlhttp.status!=200)
		{alert("We are experiencing technical difficulities with our database connections that run this program.  We are aware of the situation and the urgency of restoring the locator.  Please be patient as we are addressing this issue and will come to a resolution as soon as possible.");
		document.getElementById("errorDiv").innerHTML = "error";}
		setMessage("", false)
		
}

function testForErrors()
{
	if (document.getElementById("errorDiv").innerHTML != "error")
	{
		var zip = Math.floor(Math.random()*100000)
		if(zip < 100000) zip = ("00000" + zip).slice(-5);
		document.getElementById("zipCode").value = ""+zip;
		submitForm();
		setTimeout(function(){testForErrors()},3500);
	} 
}
function pausecomp(millis)
{
var date = new Date();
var curDate = null;

do { curDate = new Date(); }
while(curDate-date < millis);
} 

/* Sets the message in the bottom left div for ajax status
 * @param message String the the message to put in the message box.
 * @param isVisible Boolean if the box should be visible or not.
 */
function setMessage(message, isVisible)
{
	var messageDiv = document.getElementById("statusMessage");
	var messageDivBlocker = document.getElementById("statusMessageBlocker");
	messageDiv.innerHTML = "<table><tr><td class='messageText'><img src='/images/tier4/iCal/animatedLoad.gif' />  " + message + "</td></tr></table>";
	if(isVisible) {
		messageDiv.style.display = "block";
		messageDivBlocker.style.visibility = "visible";
	}		
	else {
		messageDiv.style.display = "none";
		messageDivBlocker.style.visibility = "hidden";
	}
}
/////////////////////////////////////////////////////////////////////////////////////


/////////////////////////////////////////////////////////////////////////////////////
/////////////////////Form Element Appear / Dissapear functions///////////////////////
/////////////////////////////////////////////////////////////////////////////////////
function changeVisibility(elementName, visible)
{
	var elementsArray = getElementsByName_iefix("div", elementName);
	var setting;
	
	if (visible) setting = "inline";
	else setting = "none";
	
	for (i=0; i< elementsArray.length; i++) {
		elementsArray[i].style.display = setting;
	}
	
}

/* Fix to get all elements with the tag name and element name.
 * @param tag String the html tag (ex: a, div, etc)
 * @param name String the element's Name
 * @return Array the elements that match that tag and name
 */
function getElementsByName_iefix(tag, name) {
  
   var elem = document.getElementsByTagName(tag);
   var arr = new Array();
   for(i = 0,iarr = 0; i < elem.length; i++) {
	   att = elem[i].getAttribute("name");
	   if(att == name) {
		 arr[iarr] = elem[i];
		 iarr++;
	   }
  }
  return arr;
}
/////////////////////////////////////////////////////////////////////////////////////
// Function for + - on results
function toggleMoreInfo(theImage, div1ID, div2ID)
{
	if(theImage.src.indexOf("minus") == -1)
	{
		// Currently on Plus, switch to Minus and show content
		document.getElementById(div1ID).style.display = "block";
		if(typeof(div2ID) != 'undefined') document.getElementById(div2ID).style.display = "block";
		theImage.src = theImage.src.replace("plus", "minus");
	}
	else
	{
		// Currently on Minus, switch to Plus and hide content
		document.getElementById(div1ID).style.display = "none";
		if(typeof(div2ID) != 'undefined') document.getElementById(div2ID).style.display = "none";
		theImage.src = theImage.src.replace("minus", "plus");
	}
}

function switchWidget(itemToShow)
{
	if(itemToShow == "sales")
	{
		addClass(document.getElementById("service"), "ui-tabs-hide");
		removeClass(document.getElementById("dealer"), "ui-tabs-hide");
	}
	else
	{
		addClass(document.getElementById("dealer"), "ui-tabs-hide");
		removeClass(document.getElementById("service"), "ui-tabs-hide");

	}
}
function addClass(ele,cls) {
	if (!this.hasClass(ele,cls)) ele.className += " "+cls;
}
 
function removeClass(ele,cls) {
	if (hasClass(ele,cls)) {
    	var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
		ele.className=ele.className.replace(reg,' ');
	}
}
function hasClass(ele,cls) {
	return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}

// Function to manually set a given div and image, used to bypass the toggle.
function setMoreInfo(theImageDiv, div1ID, isVisibile)
{
	if(isVisibile)
	{
		document.getElementById(theImageDiv).src = document.getElementById(theImageDiv).src.replace("plus", "minus");
		document.getElementById(div1ID).style.display="block";
	}
	else
	{
		document.getElementById(theImageDiv).src = document.getElementById(theImageDiv).src.replace("minus", "plus");
		document.getElementById(div1ID).style.display = "none";
	}
}

function countryChange(countrySelected, type)
{
	if(type == null) type = '';
	
	if(countrySelected == "US" || countrySelected == "CA")
	{
		var isUSA;
		if(countrySelected == "US") 
		{
			isUSA = true; 
			if(document.getElementById('stateProvince'+type) != null) document.getElementById('stateProvince'+type).innerHTML = "State";
		}
		else
		{
			isUSA = false;
			if(document.getElementById('stateProvince'+type) != null) document.getElementById('stateProvince'+type).innerHTML = "Province";
		}
		
		changeVisibility('usaDivs'+type, isUSA);
		changeVisibility('canadaDivs'+type, !isUSA);
		changeVisibility('nonInternationalDiv'+type, true);
	}
	else
	{
		changeVisibility('nonInternationalDiv'+type, false);
	}
}

function setFormSettings(showAdvanced)
{
	// Read the URL, looking for the OC
	var url = window.location.toString();
	url = url.toLowerCase();
	var start = url.indexOf("=xhtml/")+7;
	var OC = url.substring(start,start+3); // Gets the 3 characters after =xhtml/ which will be the OC
	var isSales = (url.indexOf("sale") != -1);
	var isService = (url.indexOf("service") != -1);
	if(!showAdvanced)
	{
		switch(OC)
		{
		case "mii":
			document.getElementById('productType3').checked = "checked";
			document.getElementById('productType5').checked = "checked";
			break;
		case "mbs":
			document.getElementById('productType1').checked = "checked";
			document.getElementById('productType2').checked = "checked";
			document.getElementById('productType4').checked = "checked";
			document.getElementById('productType7').checked = "checked";
			document.getElementById('productType9').checked = "checked";
			break;
		case "rdi":
			document.getElementById('productType8').checked = "checked";
			break;
		case "kpr":
			document.getElementById('productType8').checked = "checked";
			break;
		case "tst":
			document.getElementById('productType1').checked = "checked";
			document.getElementById('productType2').checked = "checked";
			document.getElementById('productType3').checked = "checked";
			document.getElementById('productType5').checked = "checked";
			break;
		case "wel":
			document.getElementById('productType8').checked = "checked";
			break;
		case "mcl":
			document.getElementById('productType6').checked = "checked";
			break;
		}
	}
	if(isSales)
		document.getElementById('serviceTypeSales').checked = "checked";
	if(isService)
		document.getElementById('serviceTypeService').checked = "checked";
}

function checkQueryString()
{
	// First, see what OC this is pulling from and adjust the products and sales/service selected
	
	var queryArray = getQueryArray();
	var wasQueryString = false;
	var showAdvanced = false;
	// Loop through items in queryArray, if any that apply to the locator, perform action.
	for(var i=0; i< queryArray.length; i++)
	{
		switch(queryArray[i][0])
		{
			case 'contact':
			if(queryArray[i][1].toLowerCase() == "sales") { document.getElementById('serviceTypeSales').checked = "checked";}
			if(queryArray[i][1].toLowerCase() == "service") { document.getElementById('serviceTypeService').checked = "checked";}
			break;
			case 'showAdvanced':
			if(queryArray[i][1].toLowerCase() == "true") showAdvanced = true;
			else showAdvanced = false; 
			break;
			case 'country':
			setSelected('country', queryArray[i][1]);
			countryChange(document.getElementById('country').value);
			wasQueryString = true;
			break;
			case 'state':
			setSelected('state', queryArray[i][1]);
			wasQueryString = true;
			break;
			case 'province':
			setSelected('province', queryArray[i][1]);
			wasQueryString = true;
			break;
			case 'city':
			document.getElementById('city').value = queryArray[i][1];
			wasQueryString = true;
			break;
			case 'PostalCode':
			document.getElementById('zipCode').value = queryArray[i][1];
			wasQueryString = true;
			break;
			case 'product':
			if(queryArray[i][1].toUpperCase() == "COLD PLATE SODA SYSTEM"){ document.getElementById('productType1').checked = "checked"; wasQueryString = true;}
			if(queryArray[i][1].toUpperCase() == "COUNTERTOP ICE ONLY DISPENSERS"){ document.getElementById('productType2').checked = "checked"; wasQueryString = true;}
			if(queryArray[i][1].toUpperCase() == "FLOOR STANDING ICE DISPENSERS"){ document.getElementById('productType3').checked = "checked"; wasQueryString = true;}
			if(queryArray[i][1].toUpperCase() == "GLYCOL BEER SYSTEMS"){ document.getElementById('productType4').checked = "checked"; wasQueryString = true;}
			if(queryArray[i][1].toUpperCase() == "ICE MACHINE"){ document.getElementById('productType5').checked = "checked"; wasQueryString = true;}
			if(queryArray[i][1].toUpperCase() == "REACH-IN"){ document.getElementById('productType6').checked = "checked"; wasQueryString = true;}
			if(queryArray[i][1].toUpperCase() == "RECIRCULATING SODA SYSTEMS"){ document.getElementById('productType7').checked = "checked"; wasQueryString = true;}
			if(queryArray[i][1].toUpperCase() == "WALK-IN/REFRIGERATION SYSTEMS"){ document.getElementById('productType8').checked = "checked"; wasQueryString = true;}
			if(queryArray[i][1].toUpperCase() == "WATER CHILLERS"){ document.getElementById('productType9').checked = "checked"; wasQueryString = true;}
			break;
		}
	}
	if(showAdvanced)
	{
		if(document.getElementById('advancedImage').src.indexOf("minus") == -1)
		{
			document.getElementById('advancedOptions').style.display = "block";
			document.getElementById('advancedImage').src = document.getElementById('advancedImage').src.replace("plus", "minus");
		}
	}
	setFormSettings(showAdvanced);
	if(wasQueryString)
	{	
		resetForm();
		submitForm();
	}
}

function setSelected(dropDownID, val)
{
  for(i=0;i<document.getElementById(dropDownID).length;i++)
  {
	  if(document.getElementById(dropDownID).options[i].value==val)
	  {
		  document.getElementById(dropDownID).selectedIndex=i
	  }
  }
}


function contains(a, obj){
  for(var i = 0; i < a.length; i++) {
    if(a[i] === obj){
      return true;
    }
  }
  return false;
}


function getQueryArray() 
{ 
	var query = window.location.search.substring(1); 
	var vars = query.split("&"); 
	var queryArray = Array();
	for (var i=0;i<vars.length;i++) 
	{ 
		var pair = vars[i].split("="); 
		queryArray[i] = Array(2);
		queryArray[i][0] = unescape(pair[0]);
		queryArray[i][1] = unescape(pair[1]); 
	} 
	return queryArray;
}
