﻿/** 
* Google Maps Clinic Locator
* @projectDescription 	Clinic Locator
*
* @author	Tom Newton tnewton@rosettamarketing.com
* @version	1.0b 
*
* NAMESPACE SET IN CONFIG FILE: @constructor Locator
=====================================================*/

//Properties
Locator.optionValues = ["breast","facial"]; //DO NOT EDIT OR TRANSLATE - values of treatment type select box.
Locator.dataPathVars = []; // Empty array to store query string values to pass to the server
Locator.numberOfPages = null;
Locator.enterKeyListener = {};
Locator.currentPage = null;
Locator.intervalId = null;
Locator.firstTabSet = false;
Locator.openWinId = null;
Locator.intervalTimeout = 0; //# of times function can run before timing out.
Locator.resultPages = [];
Locator.treatmentTypeValues = [Locator.Config.optionNames,Locator.optionValues];
Locator.Utils = Locator.Utils || {}; //Create Utils namespace

//Methods
Locator.initFormValues = function() {
	// populate radius drop down
    var tmpSearchRadius = document.getElementById("searchRadius");
    for (var a=0, radVal_len=Locator.Config.radiusValues.length; a<radVal_len; a++) {
        var tmpRadOption = document.createElement("option");
        tmpRadOption.text = Locator.Config.radiusValues[a] + Locator.Config.distanceUnitOfMeasure;
        tmpRadOption.value = Locator.Config.radiusValues[a];
        if (Locator.Config.radiusValues[a] == Locator.Config.defaultRadius) {
            tmpRadOption.selected = true;
        }
        try {
            tmpSearchRadius.add(tmpRadOption, null); 
        } catch (ex) {
            tmpSearchRadius.add(tmpRadOption); 
        }
    }
    // Populate Treatment Type Drop Down
    var tmpTreatmentType = document.getElementById("searchTreatment");  
    for (var b=0, ttv_len = Locator.treatmentTypeValues.length; b<ttv_len; b++) {
        var tmpTreatmentOption = document.createElement("option");
        tmpTreatmentOption.text = Locator.treatmentTypeValues[0][b];
        tmpTreatmentOption.value = Locator.treatmentTypeValues[1][b];
        if (Locator.Config.defaultTreatmentType == Locator.treatmentTypeValues[1][b]) {
            tmpTreatmentOption.selected = true;
        }
        try {
            tmpTreatmentType.add(tmpTreatmentOption, null); 
        } catch (exc) {
            tmpTreatmentType.add(tmpTreatmentOption); 
        }
    }
	// POSTAL and CITY search type radio buttons
    // Make radio button areas clickable
    var tmpPostalSet = document.getElementById("sbPostalSet");
    tmpPostalSet.style.cursor = "pointer";
    tmpPostalSet.onclick = function(){ Locator.changeSearchType('postal'); };
    
    var tmpCitySet = document.getElementById("sbCitySet");
    tmpCitySet.style.cursor = "pointer";
    tmpCitySet.onclick = function(){ Locator.changeSearchType('city'); };
    // set default search type
    if (Locator.Config.appSearchType === "postal"){
        Locator.changeSearchType("postal");
    } else {
        Locator.changeSearchType("city");
    }

	// GERMANY / UK ONLY:
	
	// Create and inject the country selector drop down
	var countryListContainer = document.getElementById("selectTreatment");
	countryListContainer.appendChild(Locator.buildCountrySelector());

	// event listener for country selection
	//var tmpCountrySelect = document.getElementById("countrySelect");
	YAHOO.util.Event.addListener("countrySelect", "change", Locator.changeCountry);
    
    // change listener for london postal codes
    YAHOO.util.Event.addListener("searchZip", "keyup", Locator.defaultLondon);
};
Locator.defaultLondon = function() {
	var setRadius = Locator.Config.defaultRadius;
	if (this.value.indexOf("W1G") >= 0 || this.value.indexOf("w1g") >= 0) {
		setRadius = "1";
	}
	// loop through radius values and select appropriate radius
	var el = new YAHOO.util.Element("searchRadius");
	var options = el.getElementsByTagName("option");
	for(i=0, optionsLength = options.length;i<optionsLength;i++){ 
		if(options[i].value == setRadius){
			options[i].selected = true;
			break;
		}
	}
};
// changes the search type between postal code and city
Locator.changeSearchType = function(sType){
    var tmpInputField = document.getElementById("searchZip");
    //tmpInputField.style.background = Locator.Config.searchInputPreBackground;
    tmpInputField.style.color = Locator.Config.searchInputPreColor;
    tmpInputField.maxLength = "50";
    if (sType === "city") {
        Locator.Config.appSearchType = "city";
        document.getElementById("rbstCity").checked = "true";
        tmpInputField.value = Locator.Config.citySearchInstructions;
        ACJSArray.oAutoComp.minQueryLength = 1;
        
    } else if (sType === "postal") {
        Locator.Config.appSearchType = "postal";
        document.getElementById("rbstPostal").checked = "true";
        tmpInputField.value = Locator.Config.pcSearchInstructions;
        ACJSArray.oAutoComp.minQueryLength = -1;
    }
};
// clears the default text and styles from the search box
Locator.focusSearch = function(){
    var tmpInputField = document.getElementById("searchZip");
    // empty the field if the instructions are in it
    if(tmpInputField.value == Locator.Config.citySearchInstructions || tmpInputField.value == Locator.Config.pcSearchInstructions){
        tmpInputField.value = "";
        //tmpInputField.style.background = Locator.Config.searchInputDefaultBackground;
        tmpInputField.style.color = Locator.Config.searchInputDefaultColor;
        // set the maxlength for the search type
        if(Locator.Config.appSearchType === "postal"){
            tmpInputField.maxLength = "10";
        } else {
            tmpInputField.maxLength = "50";
        }
    }
    
};
// checks the search input for user input after focus
// if input box is empty puts the instructions back
Locator.blurSearch = function(){
    var checkField = document.getElementById("searchZip");
    if (checkField.value === ""){
        Locator.changeSearchType(Locator.Config.appSearchType);
    }
};

// Called when marker in Available Consultants list is clicked
Locator.viewOverlay = function(i, officeTitle, isTier, oE) {
    // track physician/clinic click
    Locator.stopTimer();
	//Get element triggering the click
	if(oE){
		oE = Locator.Utils.getEvent(oE); 
		var target = Locator.Utils.getTarget(oE);
		//Only Track phone click
	    if(target.id == Locator.Config.ctbcIconId && Locator.Config.enableTracking){ 
	    	scAjaxEvent(Locator.Config.scPhoneClick, Locator.Config.scEvarDisplayName, clinicResults[i].displayName, Locator.Config.scEvarPractitionerName,clinicResults[i].practitionerName, Locator.Config.scEvarAccountNumber, clinicResults[i].officeDeptId);
	   	} else {
			s.pageName = scPageName + " : Address";
    		scAjaxEvent(Locator.Config.scViewEvent, Locator.Config.scEvarAccountNumber, clinicResults[i].officeDeptId, Locator.Config.scEvarDisplayName, clinicResults[i].displayName, Locator.Config.scEvarPractitionerName, clinicResults[i].practitionerName);
			s.pageName = "";
		}
    }
    
    Locator.trackClinic(i,"view");
    Locator.openWinId = i;
    if(i>=Locator.Config.resultLimit){ // view overlay for tiers not on list
        //Locator.stopTimer()//clear any running intervals
        Locator.deactivate_markers();
        var tmpMarkerIndex = i - Locator.Config.resultLimit;
        infoTabs = Locator.buildInfoTabs(tierResults[tmpMarkerIndex], officeTitle);
        tmarkers[tmpMarkerIndex].openInfoWindowTabsHtml(infoTabs);
	    var tmpPoint = tmarkers[tmpMarkerIndex].getPoint();
	    map.setCenter(tmpPoint);
	    var tmpToken = GEvent.addListener(map, "moveend", function() {
          Locator.moveMap(0, 50);
          GEvent.removeListener(tmpToken);
        });
        if (tierResults[tmpMarkerIndex].officeHasPhoto === "True") {
		    Locator.showPanelPhoto();
		}
        
    } else { // view overlay for results on list
        //Locator.stopTimer()//clear any running intervals
        Locator.deactivate_markers();
        if(clinicResults[i].officeTierType === "a" || clinicResults[i].officeTierType === "b"){
	        infoTabs = Locator.buildInfoTabs(clinicResults[i], officeTitle);
	    } else {
	        infoTabs = Locator.buildNTInfoTabs(clinicResults[i], officeTitle);
	    }
	    gmarkers[i].openInfoWindowTabsHtml(infoTabs);
	    var tmpPoint = gmarkers[i].getPoint();
	    map.setCenter(tmpPoint);
	    var tmpToken = GEvent.addListener(map, "moveend", function() {
          Locator.moveMap(0, 50);
          GEvent.removeListener(tmpToken);
        });
    	if (clinicResults[i].officeHasPhoto == "True") {
			Locator.showPanelPhoto();
		}
	    Element.addClassName("listresult" + i, 'selected');
    }
};

Locator.moveMap = function(dx, dy){
    map.panBy(new GSize(dx, dy));
};

Locator.deactivate_markers = function(){
    Locator.closeMapOverlay();
    for (var f=0, cr_len = clinicResults.length; f<cr_len; f++) {
        Element.removeClassName("listresult" + f, 'selected');
    }
};
Locator.showLoader = function(dispLoading) {
    var tmpLoadingDiv = document.getElementById("loadingScreen");
    if(dispLoading) {
        tmpLoadingDiv.style.display = "block";
    } else {
        tmpLoadingDiv.style.display = "none";
    }
};
// shows an error message in the list results area
Locator.showErrorMsg = function(displayMsg) {
    document.getElementById('locatorResults').style.backgroundImage = "url(/Style%20Library/images/bkg_results-before.jpg)";
    var tmpHeaderErrorDiv = document.getElementById("resultsHeader");
    tmpHeaderErrorDiv.style.visibility = "hidden";
    tmpHeaderErrorDiv.innerHTML = ""; //clear anything in there
    tmpHeaderErrorDiv.style.fontWeight = "bold";
    
    var tmpHeaderErrorDivText = document.createTextNode(Locator.Config.noResultsHeadline);
    tmpHeaderErrorDiv.appendChild(tmpHeaderErrorDivText);
    
    //Clear any results
    document.getElementById("resultList").innerHTML = "";
    var tmpErrorArea = document.getElementById("errorArea");
    var tmpErrorAreaText = document.createTextNode(displayMsg);
    tmpErrorArea.appendChild(tmpErrorAreaText);
    tmpErrorArea.style.display = "block";
    tmpHeaderErrorDiv.style.visibility = "visible";
};

Locator.buildResultHeader = function(currentResults, totalResults) {
    var tmpHeaderDiv = document.getElementById("resultsHeader");
    tmpHeaderDiv.style.visibility = "hidden";
    tmpHeaderDiv.innerHTML = ""; //clear anything in there
    tmpHeaderDiv.style.fontWeight = "normal";
    var tmpResultInfo = document.createElement("b");
    tmpResultInfo.appendChild(document.createTextNode(currentResults + Locator.Config.resultInfoSeperator + totalResults));
    
    tmpHeaderDiv.appendChild(document.createTextNode(Locator.Config.listresultsHeadline));
    tmpHeaderDiv.appendChild(tmpResultInfo);
    tmpHeaderDiv.style.visibility = "visible";
};

Locator.buildResultSet = function(page) {
	//Clear the results
	document.getElementById("resultList").innerHTML = "";
	document.getElementById('locatorResults').style.backgroundImage = "url(/Style%20Library/images/bkg_results-after.jpg)";
	var aProducts = [];
	// Build the new one
	for (var f=1, page_len=page.length; f<page_len; f++) {
	    if(f==page_len-1){
	        document.getElementById("resultList").appendChild(page[f].returnRow(true));
	        if(Locator.Config.enableTracking){
	        	aProducts.push(page[f].officeDeptId);
	        }
	    }else{
	    	document.getElementById("resultList").appendChild(page[f].returnRow());
			if(Locator.Config.enableTracking){
				aProducts.push(page[f].officeDeptId); 
			}
	    }
	}
		
	// Set result tools styles based on Locator.currentPage
	if (Locator.currentPage >= 1) {
		var tmpPrevious = Locator.currentPage - 1;
		var tmpNext = Locator.currentPage + 1;
		
		if (Locator.currentPage > 1) {
			document.getElementById("previousSet").style.display = "block";
			document.getElementById("previousSet").childNodes[0].innerHTML = "";
			document.getElementById("previousSet").childNodes[0].href = "javascript: Locator.prevPage(" + Locator.currentPage + ");";
			document.getElementById("previousSet").style.backgroundImage = "url(/Style%20Library/images/btn_viewPrev.gif)";
			var mtcPrevious = document.createElement("a");
			mtcPrevious.href = "javascript: Locator.prevPage(" + Locator.currentPage + ");";
			mtcPrevious.appendChild(document.createTextNode(Locator.Config.mtControl.labelPrevious));
			document.getElementById("mtcResultsText").appendChild(mtcPrevious);
			document.getElementById("mtcResultsText").innerHTML += " - ";
		} else {
			if (document.getElementById("previousSet")) {
				document.getElementById("previousSet").style.display = "block";
				document.getElementById("previousSet").childNodes[0].style.display = "none";
			}
	        document.getElementById("mtcResultsText").appendChild(document.createTextNode(Locator.Config.mtControl.labelPrevious));
	        document.getElementById("mtcResultsText").innerHTML += " - ";
		}
		
		if (tmpNext <= Locator.numberOfPages) {
			document.getElementById("nextSet").style.display = "block";
			document.getElementById("nextSet").childNodes[0].innerHTML = "";
			document.getElementById("nextSet").childNodes[0].href = "javascript: Locator.nextPage(" + Locator.currentPage + ");";
	        document.getElementById("nextSet").style.backgroundImage = "url(/Style%20Library/images/btn_viewNext.gif)";
	        var mtcNext = document.createElement("a");
	        mtcNext.href = "javascript: Locator.nextPage(" + Locator.currentPage + ");";
	        mtcNext.appendChild(document.createTextNode(Locator.Config.mtControl.labelNext));
	        document.getElementById("mtcResultsText").appendChild(mtcNext);
	        document.getElementById("mtcResultsText").innerHTML += " >";		
		} else {
			if (document.getElementById("nextSet")) {
				document.getElementById("nextSet").style.display = "block";
				document.getElementById("nextSet").childNodes[0].style.display = "none";
				document.getElementById("nextSet").style.backgroundImage = "url(/Style%20Library/images/btn_viewNext_off.gif)";
			}
			document.getElementById("mtcResultsText").appendChild(document.createTextNode(Locator.Config.mtControl.labelNext));
	        document.getElementById("mtcResultsText").innerHTML += " >";
		}	
	}
	
	//Track Results display
	//Track physician view event
	if(Locator.Config.enableTracking){
		//define private variables
		var sSearchText = Locator.trimInputText(document.getElementById('searchZip').value),
			sSearchEvar = null,
			sSearchRadius = document.getElementById('searchRadius').value;
			iTotalResults = 0;
		
		if (Locator.Config.appSearchType === "postal"){ // Process postal code submissions			
			sSearchEvar = Locator.Config.scEvarZipCode;
			s.zip = sSearchText; //track zip property for geo location
	    } else if (Locator.Config.appSearchType === "city") { // Process city or text based submissions
			sSearchEvar = Locator.Config.scEvarCity;
	    }
	    if(typeof(page[1]) !== 'undefined'){
	    	iTotalResults = page[1].totalResults || 0;
	    }
    	
	    if(aProducts.length > 0){
	    	s.products = ';' + aProducts.join(',;');
	    }
		scAjaxEvent(Locator.Config.scSearchResults + ",prodView", sSearchEvar, sSearchText, Locator.Config.scEvarRadius, sSearchRadius, Locator.Config.scPropSearchRadius, sSearchRadius, Locator.Config.scEvarTotalResultsCount, iTotalResults);
		s.products = ''; //clear s.products
		s.zip = ''; //clear s.zip
	}
};

Locator.determinePagination = function(totalResults, currentResults) {
	// Init current page
	if (!Locator.currentPage) {
	    Locator.currentPage = 1;
	}
	Locator.numberOfPages = (Math.ceil(totalResults/Locator.Config.resultLimit));
	// Build result set info
	var fromX = ((Locator.currentPage * Locator.Config.resultLimit) - (Locator.Config.resultLimit - 1));
	var toY = (Locator.currentPage * Locator.Config.resultLimit);
	if (toY > totalResults) {
	    toY = totalResults
	}
	var tmpCurrentResults = fromX + "-" + toY;
	// Put result set info on map control
	document.getElementById("mtcResultsText").innerHTML = Locator.Config.mtControl.labelNavText1 + tmpCurrentResults + Locator.Config.mtControl.labelNavText2 + totalResults + " < ";
	// Put result set info on result list
	Locator.buildResultHeader(tmpCurrentResults, totalResults);
	
	start=0;
	limit = currentResults;
	
	for(var c=0, pg_len=Locator.numberOfPages; c<pg_len; c++) {
		Locator.resultPages[c] = [];	
		Locator.resultPages[c].push(c);	
		for(d=start; d<limit; d++){
			Locator.resultPages[c].push(clinicResults[d]);
		}
		
		start = start + Locator.Config.resultLimit;
		limit = limit + Locator.Config.resultLimit;
		if (limit > clinicResults.length) {
			limit = clinicResults.length;
		}
	}
	// Init result tools
	var resultTools = document.createElement("ul");
	resultTools.id="resultTools";
	// Previous Link
	var previousSet = document.createElement("li");
	previousSet.id = "previousSet";
	var prevAnchor = document.createElement("a");
	prevAnchor.href = "#";
	var prevAnchorText = document.createTextNode(Locator.Config.resultPrevLabel);
	prevAnchor.appendChild(prevAnchorText);
	previousSet.appendChild(prevAnchor);
	
	// Next Link
	var nextSet = document.createElement("li");
	nextSet.id = "nextSet";
	var nextAnchor = document.createElement("a");
	nextAnchor.href = "javascript: Locator.nextPage(" + Locator.currentPage + ");";
	var nextAnchorText = document.createTextNode(Locator.Config.resultNextLabel);
	nextAnchor.appendChild(nextAnchorText);
	nextSet.appendChild(nextAnchor);
	
	resultTools.appendChild(previousSet);
	resultTools.appendChild(nextSet);
	document.getElementById("resultActions").appendChild(resultTools);	
};

Locator.buildInfoTabs = function (obj, officeTitle) {   
	var infoTabs = [
		new GInfoWindowTab(Locator.Config.tabLabelOne, obj.showAddressPanel()),
		new GInfoWindowTab(Locator.Config.tabLabelTwo, obj.showServicesPanel()),
		new GInfoWindowTab(Locator.Config.tabLabelThree, obj.showOfferPanel())
	];
		
	return infoTabs;
};
Locator.buildNTInfoTabs = function (obj, officeTitle) { 
	var infoTabs = [new GInfoWindowTab(Locator.Config.tabLabelOne, obj.showAddressPanel())];    
	return infoTabs;
};

Locator.submitDirections = function(objID) {
	document.getElementById('gmaps_form_query').value = "from: " + document.getElementById('gmaps_form_query').value + " to: " + document.getElementById('d_daddr').value;
	document.getElementById('getDirections').submit();
	Locator.trackClinic(objID,"directions");
	document.getElementById('gmaps_form_query').value = "";
};

Locator.setActivePrintStyleSheet = function(title) {
   var i, a, main;
   for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
     if(a.getAttribute("media")){
         if(a.getAttribute("media").indexOf("print") != -1 && a.getAttribute("title")) {
           a.disabled = true;
           if(a.getAttribute("title") == title) a.disabled = false;
         }
     }
   }
};

Locator.selTab = function(n, o){
    var infoWin = map.getInfoWindow();
    infoWin.selectTab(n);
    Locator.tabClick("tab"+n, o);
};

Locator.tabClick = function(anchorObj, objID) {
	Locator.createInactiveClass(anchorObj);
	var tmpTabId = anchorObj.substr(3,1);
	
	if(objID || objID == 0){
	    if(tmpTabId == 0){
	        Locator.trackClinic(objID,"address");
	    } else if (tmpTabId == 1){
	        Locator.trackClinic(objID,"treatments");
	    } else if (tmpTabId ==2){
	        Locator.trackClinic(objID,"certview");
	    }
	    
	    //Track tab click as a page view
		if(Locator.Config.enableTracking){
			s.pageName = scPageName + " : " + document.getElementById(anchorObj).innerHTML;
			void(s.t());
		}
	}
};
	
Locator.createInactiveClass = function(anchorObj) {
	var tabs = Locator.getElementsByClassName("tab", "a");
	for (var y=0, tab_len=tabs.length; y<tab_len; y++) {
		tabs[y].className = "inactive";	
	}
	document.getElementById(anchorObj).className = "tab";
};	
	
Locator.getElementsByClassName = function(className, tag, elm){
	var testClass = new RegExp("(^|\\\\s)" + className + "(\\\\s|$)");
	var tag = tag || "*";
	var elm = elm || document;
	var elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
	var returnElements = [];
	var current;
	var length = elements.length;
	for(var i=0; i<length; i++){
		current = elements[i];
		if(testClass.test(current.className)){
			returnElements.push(current);
		}
	}
	return returnElements;
};

Locator.nextPage = function(pageNum) {
    // Hide map temporarily due to screwy display issues when running gload();
    Locator.stopTimer();
    Locator.showMap(false);
    Locator.showLoader(true);
    // Increment the current page
    Locator.currentPage = pageNum + 1;
    // Clear out the result list and page arrays
    clinicResults.length = 0;
    Locator.resultPages.length = 0;
    // Remove results tools div to make way for the new one
    var tmpDiv = document.getElementById('resultTools');
    document.getElementById('resultActions').removeChild(tmpDiv);
    Locator.fixImg("resultList");
	dojo.fx.chain([
    		dojo.fx.wipeOut({ node: "resultList", duration:700})
	]).play();
	Locator.fixImg("resultList");
    // Re-load the map with the new data
    gload(Locator.createXmlPath(false),false); 
};

Locator.prevPage = function(pageNum) {
    // Hide map temporarily due to screwy display issues when running gload();
    Locator.stopTimer();
    Locator.showMap(false);
    Locator.showLoader(true);
    // Decrement the current page
    Locator.currentPage = pageNum - 1;
    // Clear out the result list array
    clinicResults.length = 0;
    Locator.resultPages.length = 0;
    // Remove results tools div to make way for the new one
    var tmpDiv = document.getElementById('resultTools');
    document.getElementById('resultActions').removeChild(tmpDiv);
    Locator.fixImg("resultList");
	dojo.fx.chain([
    		dojo.fx.wipeOut({ node: "resultList", duration:700})
	]).play();
	Locator.fixImg("resultList");
    // Re-load the map with the new data
    gload(Locator.createXmlPath(false),false);
};

// Removes all of the elements inside the passed container obj
Locator.clearContainer = function(tmpContainer) {
    if (tmpContainer.hasChildNodes()) {
        while (tmpContainer.childNodes.length >= 1) {
            tmpContainer.removeChild(tmpContainer.firstChild);
        }
    }
};

Locator.showMap = function(makeMapVisible) {
    if (makeMapVisible) {
        document.getElementById('map').style.visibility = "visible";
    } else {
        document.getElementById('map').style.visibility = "hidden";
    }
};
Locator.closeMapOverlay = function() {
    // Remove any overlay content from memory
    var tmpRemoveContent = document.getElementById('mapOverlayContentArea');
    Locator.clearContainer(tmpRemoveContent);
    // Hide the overlay area
    document.getElementById('mapOverlay').style.display = "none";
    Locator.setActivePrintStyleSheet("overlay");
};
Locator.showBioForm = function(obJID) {
    Locator.stopTimer();
    document.getElementById('mapOverlay').style.display = "block";
    document.getElementById('mapOverlayContentArea').innerHTML = "";
    document.getElementById('mapOverlay').style.visibility = "visible";
    if (obJID >= Locator.Config.resultLimit){
        document.getElementById('mapOverlayContentArea').appendChild(tierResults[obJID-Locator.Config.resultLimit].showBioOverlay());
    } else {
        document.getElementById('mapOverlayContentArea').appendChild(clinicResults[obJID].showBioOverlay());
    }
    Locator.trackClinic(obJID,"bio");
    document.getElementById("mapOverlayContentArea").scrollTop = 0;
    Locator.showBioPhoto();
    
    //Track bio event
	if(Locator.Config.enableTracking){
		s.pageName = scPageName + " : " + Locator.Config.scBioPageName;
    	scAjaxEvent(Locator.Config.scBioEvent, Locator.Config.scEvarAccountNumber, clinicResults[obJID].officeDeptId, Locator.Config.scEvarDisplayName, clinicResults[obJID].displayName, Locator.Config.scEvarPractitionerName, clinicResults[obJID].practitionerName);
	}
};
Locator.showCallForm = function(obJID) {
    Locator.stopTimer();
    document.getElementById('mapOverlay').style.display = "block";
    document.getElementById('mapOverlayContentArea').innerHTML = "";
    document.getElementById('mapOverlay').style.visibility = "visible";
    if (obJID >= Locator.Config.resultLimit){
        document.getElementById('mapOverlayContentArea').appendChild(tierResults[obJID-Locator.Config.resultLimit].showCallOverlay());
    } else {
        document.getElementById('mapOverlayContentArea').appendChild(clinicResults[obJID].showCallOverlay());
    }
    document.getElementById('fname').focus();
    document.getElementById("mapOverlayContentArea").scrollTop = 0;
    
    //Track tab click as a page view
    if(Locator.Config.enableTracking){
	  	s.pageName = scPageName + " : " + Locator.Config.scCtbcPageName;
	  	void(s.t());
    }
};
Locator.showOfferForm = function(obJID) {
    //Send data to server and await response
    document.getElementById('mapOverlay').style.display = "block";
    document.getElementById('mapOverlay').style.visibility = "hidden";
    document.getElementById('mapOverlayContentArea').innerHTML = "";
    document.getElementById('mapOverlayContentArea').appendChild(clinicResults[obJID].showOfferVoucher());
    document.getElementById("mapOverlayContentArea").scrollTop = 0;
	  //Load our voucher Style Sheet
    Locator.setActivePrintStyleSheet("voucher");
    //Print Window
    window.print()
    Locator.trackClinic(obJID,"certprint");
    //Reload stylesheet for map
    setTimeout("Locator.setActivePrintStyleSheet('overlay')",3000);
    
    //create a hidden div via dom to output the server reponse page to for sc purposes
	if(Locator.Config.enableTracking){
		var tmpDiv = document.createElement("div");
		tmpDiv.style.visibility = "hidden";
		document.getElementById("mapOverlayContentArea").appendChild(tmpDiv);
			
		//Media tracking tags
		var trackingImg = document.createElement("img");
		trackingImg.width = "1";
		trackingImg.height = "1";
		trackingImg.style.position = "absolute";
		trackingImg.style.left = "-10000";
		trackingImg.src = "http://switch.atdmt.com/action/umcall_080718printingoffreeoffer_1";
		tmpDiv.appendChild(trackingImg);
	}
};
Locator.showBioPhoto = function() {
	Locator.intervalId = setInterval("Locator.checkBioPhotoLoaded()", 500);
};
Locator.showPanelPhoto = function() {
    Locator.intervalId = setInterval("Locator.checkPhotoLoaded()", 500); 
};
Locator.checkPhotoLoaded = function(){
    Locator.intervalTimeout += 1;
    var tmpPhotoDiv = document.getElementById("addressPhoto");
    var photoObj = document.getElementById("photoDrop").getElementsByTagName("img");
    if (photoObj[0] && tmpPhotoDiv){
        if (photoObj[0].clientWidth > 30){
            var scaleObj = Locator.scaleClientImage(140, 120, photoObj[0]);
            tmpPhotoDiv.style.width = scaleObj.width + "px";
            tmpPhotoDiv.style.height = scaleObj.height + "px";
            tmpPhotoDiv.style.borderWidth = "2px";
            tmpPhotoDiv.appendChild(scaleObj.image);
            Locator.stopTimer();
        }
    }
    if (Locator.intervalTimeout == 10){
        Locator.stopTimer();
    }
};
Locator.checkBioPhotoLoaded = function(){
    Locator.intervalTimeout += 1;
    var tmpPhotoDiv = document.getElementById("clinicPhoto"); 
    var photoObj = document.getElementById("photoDrop").getElementsByTagName("img");
    if (photoObj[0] && tmpPhotoDiv){
        if (photoObj[0].clientWidth > 30){
            var scaleObj = Locator.scaleClientImage(Locator.Config.bioPhotoMaxWidth, Locator.Config.bioPhotoMaxHeight, photoObj[0]);
            tmpPhotoDiv.style.width = scaleObj.width + "px";
            tmpPhotoDiv.style.height = scaleObj.height + "px";
            tmpPhotoDiv.appendChild(scaleObj.image);
            Locator.stopTimer();
        }
    }
    if (Locator.intervalTimeout == 10){
        Locator.stopTimer();
    }
};

Locator.animateNewResults = function(results) {
	Locator.fixImg("resultList");
	dojo.fx.chain([
    		dojo.fx.wipeOut({ node: "resultList", duration:700, onEnd: function(){Locator.buildResultSet(results);} }),
    		dojo.fx.wipeIn({ node: "resultList", duration:700})
	]).play();
	Locator.fixImg("resultList");
	setTimeout("Locator.showMap(true)", 500);
};

// The next function is necessary because of the relative positioning of all links due to PNG transparency in IE, 
// we need to change the position to allow dojo animation to work, we then change it back when it finishes

Locator.fixImg = function(nodeName) {
	var totalImages = document.getElementById(nodeName).getElementsByTagName("img");
	for(var x = 0, totalImagesLength = totalImages.length; x < totalImagesLength ; x++) {
		if(totalImages[x].parentNode.href) {
			if (totalImages[x].parentNode.style.position === "relative") {
			totalImages[x].parentNode.style.position = "static";	
			} else {
			totalImages[x].parentNode.style.position = "relative";	
			}	
		}
	}
};

Locator.checkPostCode = function(toCheck) {

  // Permitted letters depend upon their position in the postcode.
  var alpha1 = "[abcdefghijklmnoprstuwyz]";                       // Character 1
  var alpha2 = "[abcdefghklmnopqrstuvwxy]";                       // Character 2
  var alpha3 = "[abcdefghjkstuw]";                                // Character 3
  var alpha4 = "[abehmnprvwxy]";                                  // Character 4
  var alpha5 = "[abdefghjlnpqrstuwxyz]";                          // Character 5
  
  // Array holds the regular expressions for the valid postcodes
  var pcexp = [];

  // Expression for postcodes: AN NAA, ANN NAA, AAN NAA, and AANN NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1,2})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
  // Expression for postcodes: ANA NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}[0-9]{1}" + alpha3 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
  // Expression for postcodes: AANA  NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1}" + alpha4 +"{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
  // Exception for the special postcode GIR 0AA
  pcexp.push (/^(GIR)(\s*)(0AA)$/i);
  // Standard BFPO numbers
  pcexp.push (/^(bfpo)(\s*)([0-9]{1,4})$/i);
  // c/o BFPO numbers
  pcexp.push (/^(bfpo)(\s*)(c\/o\s*[0-9]{1,3})$/i);
  // Load up the string to check
  var postCode = toCheck;
  var valid = false;
  // Check the string against the types of post codes
  for (var i=0,ex_len=pcexp.length; i<ex_len; i++) {
    if (pcexp[i].test(postCode)) {
      // The post code is valid - split the post code into component parts
      pcexp[i].exec(postCode);
      // Copy it back into the original string, converting it to uppercase and
      // inserting a space between the inward and outward codes
      postCode = RegExp.$1.toUpperCase() + " " + RegExp.$3.toUpperCase();
      // If it is a BFPO c/o type postcode, tidy up the "c/o" part
      postCode = postCode.replace (/C\/O\s*/,"c/o ");
      // Load new postcode back into the form element
      valid = true;
      // Remember that we have found that the code is valid and break from loop
      break;
    }
  }
  // Return with either the reformatted valid postcode or the original invalid 
  // postcode
  if (valid) {return postCode;} else return false;
}

// Returns a URL Query String Value from a passed paramname
Locator.getUrlParam = function(name) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(decodeURIComponent(window.location.href));
  if( results == null ){return "";}
  else{ return results[1];}
};
Locator.readCookie = function(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0, ca_len=ca.length;i < ca_len;i++){
		var c = ca[i];
		while (c.charAt(0)==' '){ c = c.substring(1,c.length);}
		if (c.indexOf(nameEQ) == 0){ return c.substring(nameEQ.length,c.length);}
	}
	return null;
};
// Returns a completed datafile path on either A. Form Submission or B. Next/Prev Nav
Locator.createXmlPath = function(useFormVals, GeoLat, GeoLon) {
    if (!Locator.currentPage){ 
        Locator.currentPage = 1;
    }
    var returnPath = Locator.Config.baseDataPath;
    var tmpRandomNum = "?uniq=" + Math.round(Math.random()*10000);
    var tmpSessionId = "&sessionid=" + Locator.getSessionId();
    var tmpSearchRadius;
    var tmpMode;
    var tmpPageNum;
    var tmpSearchTreatment;
    var tmpPostalCode
    
    // Map Interaction; clear any active overlay
    Locator.closeMapOverlay();
    
    if (useFormVals) {
        // Use form field values
        // Wipe any db entries
        Locator.dataPathVars.length = 0;
        // Compile Query Strings
        tmpSearchRadius = "&radius=" + document.getElementById('searchRadius').value;
        var tmpLat = "&lat=" + GeoLat;
        var tmpLon = "&lon=" + GeoLon;
        tmpSearchTreatment = "&treatmenttype=" + document.getElementById('searchTreatment').value;
        tmpPageNum = "&pagenum=1";
        tmpMode = "&mode=s"; // mode = 's' search for form submissions 
        tmpPostalCode = "&postal=" + document.getElementById('searchZip').value;
        // Repopulate Array
        Locator.dataPathVars.push(tmpRandomNum, tmpSessionId, tmpSearchRadius, tmpLat, tmpLon, tmpSearchTreatment, tmpPageNum, tmpMode, tmpPostalCode);
    } else {
        // build the array
        if (Locator.dataPathVars.length == 0){
            // this condition should only happen on init page load if query params are passed/verified
            // so it should be ok to grab them from the url
            tmpSearchRadius = "&radius=" + Locator.getUrlParam("radius");
            tmpLat = "&lat=" + searchLat;
            tmpLon = "&lon=" + searchLon;
            tmpSearchTreatment = "&treatmenttype=" + Locator.getUrlParam("treatmenttype");
            // if page is specified in URL, setpage and mode=p
            if (Locator.getUrlParam("page")) {
                tmpPageNum = "&pagenum=" + Locator.getUrlParam("page"); 
                tmpMode = "&mode=p"; 
                if (!Locator.currentPage) {
	                Locator.currentPage = Locator.getUrlParam("page");
	            } else {
	                Locator.currentPage = Locator.getUrlParam("page");
	            }
            } else {
                tmpPageNum = "&pagenum=1"; //on pageload only so, 1, naturally...
                tmpMode = "&mode=s"; //'s' since this is being processed in url from a form elsewhere...
            }
            tmpPostalCode = "&postal=" + Locator.getUrlParam("postalcode");
            Locator.dataPathVars.push(tmpRandomNum, tmpSessionId, tmpSearchRadius, tmpLat, tmpLon, tmpSearchTreatment, tmpPageNum, tmpMode, tmpPostalCode);
        } else {
            // Re-use array and update for pagination only
            Locator.dataPathVars[6] = "&pagenum=" + Locator.currentPage;
            Locator.dataPathVars[7] = "&mode=p"; // mode = 'p' for page nav
        }
    }
    // Create XML Path
    for (var h=0, dvar_len=Locator.dataPathVars.length; h<dvar_len; h++) {
        returnPath = returnPath + Locator.dataPathVars[h];
    }
    
    //Return Test XML path for debugging if set to true
    if (Locator.Config.useTestXml) {
        returnPath = Locator.Config.testXmlPath;
    }
    
    //Show XML Path In Target Div for Debugging;
    if (Locator.Config.showXmlPath){
        document.getElementById(Locator.Config.debugDivId).innerHTML = returnPath;
    }
    
    return returnPath;
};

// Use google geocoder to return lat/lon of postal code in search form
Locator.geocodeZip = function(tmpZip, reloadMap, getTiers) {
    tmpZip = Locator.stripSpaces(tmpZip);
    tmpZip += ", " + Locator.Config.searchProperCountry[Locator.Config.activeIndex]; 
    var geocoder2 = new GClientGeocoder();
    geocoder2.setBaseCountryCode(Locator.Config.googleBaseMapUrl[Locator.Config.activeIndex]);
    geocoder2.getLatLng(
		tmpZip, 
		function(point){
			if (!point) {
			    Locator.createEmptyMap = createEmptyMap;
			    Locator.createEmptyMap(Locator.Config.msgBadPostal);
			} else {
			    // Postal code is valid and Geocoded
			    if (reloadMap) {
                    clinicResults.length = 0;
                    // Remove results tools div to make way for the new one
                    var tmpDiv = document.getElementById('resultTools');
                    if (tmpDiv) {
                        document.getElementById('resultActions').removeChild(tmpDiv);
                    }
                    Locator.currentPage = 1;		
			        if(getTiers){		
			            gload(Locator.createXmlPath(true,point.lat(),point.lng()),true);
			        } else {
			            gload(Locator.createXmlPath(true,point.lat(),point.lng()),false);
			        }
			    } else {
			        Locator.outputLatLon(point.lat(),point.lng());
			    }
			}
		}
	);
};
// function looks for user input country code in the search string
// and if it doesn't find it, returns a new string with the proper 
// country code attached for proper geocoding.
Locator.formatInputText = function(tmpText){
    tmpText = tmpText.toLowerCase();
    var tmpStartIndex1 = tmpText.indexOf(", " + Locator.Config.searchProperCountry[Locator.Config.activeIndex]);
    var tmpStartIndex2 = tmpText.indexOf("," + Locator.Config.searchProperCountry[Locator.Config.activeIndex]);
    var returnText = tmpText;
    if (tmpStartIndex1 == -1 || tmpStartIndex2 == -1){
        returnText = tmpText + ", " + Locator.Config.searchProperCountry[Locator.Config.activeIndex];
    }    
    if (tmpStartIndex1 != -1){
        var findString = tmpText.substr(tmpStartIndex1, Locator.Config.searchProperCountry[Locator.Config.activeIndex].length + 2);
        if (findString.length > (Locator.Config.searchProperCountry[Locator.Config.activeIndex].length + 2)){
            returnText += ", " + Locator.Config.searchProperCountry[Locator.Config.activeIndex];
        }  
    } else if (tmpStartIndex2 != -1){
        var findString = tmpText.substr(tmpStartIndex2, Locator.Config.searchProperCountry[Locator.Config.activeIndex].length + 1);
        if (findString.length > (Locator.Config.searchProperCountry[Locator.Config.activeIndex].length + 1)){
            returnText += ", " + Locator.Config.searchProperCountry[Locator.Config.activeIndex];
        }
    }
    return returnText;
};
// Use google geocoder to return lat/lon of postal code in search form
Locator.geocodeText = function(tmpText, reloadMap, getTiers) {
    tmpText = Locator.formatInputText(tmpText);
    var geocoder3 = new GClientGeocoder();
    geocoder3.setBaseCountryCode(Locator.Config.googleBaseMapUrl[Locator.Config.activeIndex]);
    geocoder3.getLatLng(
		tmpText, 
		function(point){
			if (!point) {
			    Locator.createEmptyMap = createEmptyMap;
			    Locator.createEmptyMap(Locator.Config.msgBadSearchText);
			} else {
			    if (reloadMap) {
                    clinicResults.length = 0;
                    // Remove results tools div to make way for the new one
                    var tmpDiv = document.getElementById('resultTools');
                    if (tmpDiv) {
                        document.getElementById('resultActions').removeChild(tmpDiv);
                    }
                    Locator.currentPage = 1;
                    if(getTiers){		
			            gload(Locator.createXmlPath(true,point.lat(),point.lng()),true);
			        } else {
			            gload(Locator.createXmlPath(true,point.lat(),point.lng()),false);
			        }
			    } else {
			        Locator.outputLatLon(point.lat(),point.lng());
			    }
			}
		}
	);
};
// Outputs geocode lat/lon to app vars from geocoder which wont let you assign lat and lon to a variable
// from inside the function for some reason.  Stupid geocoder...
Locator.outputLatLon = function(lat, lon) {
    searchLat = lat;
    searchLon = lon;
};

// Since geocoder make take up to a few sec to actually output to the vars, lets write a function that
// returns a response code when those variables are ready to be read
Locator.geocodeWait = function() {
    if (!searchLat && !searchLon){
        // do nothing i guess.. must be a better way to formulate...
    } else {
        Locator.stopTimerGo();
    }
};
Locator.startGeoTimer = function(interval, timeout){
    Locator.intervalId = setInterval("Locator.geocodeWait()", interval);
    setTimeout("Locator.stopTimer()", timeout);
};
// this function will be called on timeout and/or if geocode is a no go
Locator.stopTimer = function(){
    clearInterval(Locator.intervalId);
    Locator.intervalTimeout = 0;
};
// this function will be called to stop the timer once the lat/lng vals have been processed and are good
Locator.stopTimerGo = function(){
    clearInterval(Locator.intervalId); // stop the timer
    // compile xmlpath string and GLOAD BABY!!!
    gload(Locator.createXmlPath(false));
};
// removes leading and trailing spaces from any passed string
Locator.trimInputText = function(strText) { 
    // this will get rid of leading spaces 
    while (strText.substring(0,1) == ' '){ 
        strText = strText.substring(1, strText.length);
	}
    // this will get rid of trailing spaces 
    while (strText.substring(strText.length-1,strText.length) == ' '){
        strText = strText.substring(0, strText.length-1);
    }
    return strText;
};

// Refine Search Form Submission
Locator.refineSearch = function() {
	var sSearchEvar = null; //only used if tracking is enabled
	var sSearchProp = null; //"" ""
    var tmpSearchText = Locator.trimInputText(document.getElementById('searchZip').value);
    document.getElementById('searchZip').value = tmpSearchText; //puts the cleaned up text in the search field
    // Process by search type (city or postal)
    if (Locator.Config.appSearchType === "postal"){ // Process postal code submissions
        Locator.prepSearch();
        Locator.geocodeZip(Locator.checkPostCode(tmpSearchText),true,true);
 		sSearchEvar = Locator.Config.scEvarZipCode;
 		sSearchProp = Locator.Config.scPropSearchPostalCode;
		s.zip = tmpSearchText; //track zip property for geo location
    }
    
    if (Locator.Config.appSearchType === "city") { // Process city or text based submissions
        Locator.prepSearch();
        Locator.geocodeText(tmpSearchText,true,true);
        sSearchEvar = Locator.Config.scEvarCity;
     	sSearchProp = Locator.Config.scPropSearchCity
    }
    
    //Track search event
	if(Locator.Config.enableTracking){
		var sEvts = Locator.Config.scSearchEvent + "," + Locator.Config.scSearchEvent2;
		scAjaxEvent(sEvts, sSearchEvar, tmpSearchText, Locator.Config.scPropSearchParams, Locator.Config.appSearchType, sSearchProp, tmpSearchText, Locator.Config.scEvarRadius, document.getElementById("searchRadius").value);
		s.zip = ''; //clear s.zip
	}
};
// common things to do while geocoding and prepping the map
Locator.prepSearch = function(){
    document.getElementById("locatorResults").style.backgroundImage = "url(/Style%20Library/images/bkg_results-before.jpg)";
    Locator.showMap(false);
    Locator.showLoader(true);
    // If error area detected clear it
    var tmpRemErrorDiv = document.getElementById("errorArea");
    tmpRemErrorDiv.innerHTML = "";
    tmpRemErrorDiv.style.display = "none";
    //Clear the results
    document.getElementById("resultList").innerHTML = "";
    /* OK, here's the deal with the results header; in FireFox Only: if there is no data in the resultsHeader Div, it displays a gap between the search form above and the results area till the header data is populated.  It just looks crappy, so we put some scrap data in the div and hide it till it gets populated by either the buildheader function or error msg functions.. yeah, it's a hack - but I've been messing with it for too long now. */
    document.getElementById("resultsHeader").style.visibility = "hidden";
    document.getElementById("resultsHeader").innerHTML = "m";
};

Locator.URLDecode = function(psEncodeString){
  // Create a regular expression to search all +s in the string
  var lsRegExp = /\+/g;
  // Return the decoded string
  return unescape(String(psEncodeString).replace(lsRegExp, " "));
};

// Checks URL for query strings for proper data required to return results
// if any of those query strings are valid, will set the proper session types
Locator.checkInitData = function() {
    var allCheck = false;
    var postalCodeCheck = false, radiusCheck = false, treattype = false;
    
    
	

    // REQUIRED: POSTALCODE, RADIUS, TREATMENT TYPE
    // OPTIONAL (will not be set or affect scope or validated): PAGE

	// validates the search string is not empty
    if (Locator.getUrlParam("postalcode").length > 0) {
        
        var tmpPVal = Locator.URLDecode(Locator.getUrlParam("postalcode"));

       // check proper searchtype is passed, and if so, set the app scope accordingly
        if (Locator.getUrlParam("searchtype") === "postal") {
            Locator.Config.appSearchType = "postal";
            // Put postal code value in search field
            var tmpPCodeText = tmpPVal;
            document.getElementById('searchZip').value = tmpPCodeText.toUpperCase();
            //document.getElementById('searchZip').style.background = Locator.Config.searchInputDefaultBackground;
            document.getElementById('searchZip').style.color = Locator.Config.searchInputDefaultColor;
            //allCheck = true;
            postalCodeCheck = true;
        } else if(Locator.getUrlParam("searchtype") === "city") {
            Locator.Config.appSearchType = "city";
            var tmpPCodeText = tmpPVal;
            document.getElementById('searchZip').value = tmpPCodeText;
            //document.getElementById('searchZip').style.background = Locator.Config.searchInputDefaultBackground;
            document.getElementById('searchZip').style.color = Locator.Config.searchInputDefaultColor;
            //allCheck = true;
            postalCodeCheck = true;
        }
    }

	// validates proper radius value specified, if specified
    if (Locator.getUrlParam("radius").length > 0) {
        // check against Locator.Config.radiusValues Array Obj
        for (a=0;a<Locator.Config.radiusValues.length;a++) {
            if (Locator.getUrlParam("radius") == Locator.Config.radiusValues[a]) {
                //allCheck = true;
                radiusCheck = true;
                Locator.Config.defaultRadius = Locator.getUrlParam("radius"); //selects the passed radius option on the form
            }
        }
    }

	// validates proper treatment type is specified and sets the app scope
    if (Locator.getUrlParam("treatmenttype").length > 0) {
        // check against Locator.treatmentTypeValues
        for (b=0;b<Locator.treatmentTypeValues.length;b++) {
            if (Locator.getUrlParam("treatmenttype") == Locator.treatmentTypeValues[1][b]) {
                //allCheck = true;
                treattype = true;
                Locator.Config.defaultTreatmentType = Locator.getUrlParam("treatmenttype"); //selects treatment type passed on the form
            }
        }
    }

	allCheck =  postalCodeCheck && radiusCheck && treattype;
	return allCheck;
};


// Scales an image to a specified size
// This works best if the maxHeight and maxWidth of the container object are specified in the
// style sheet.  Also works with implicitly specified container height and width but not recomended.
Locator.scaleClientImage = function(maxWidth, maxHeight, imgObj) {
    //Create return object
    var returnData = {};

    //Get IMG dimensions
    var imgH = imgObj.height;
    var imgW = imgObj.width;
    
    //Find which dim is scaled the most
    var scaleH = maxHeight / imgObj.height;
    var scaleW = maxWidth / imgObj.width;
    
    //Do the scaling and populate the return obj
    if (scaleH < scaleW) {
        returnData.height = maxHeight;
        returnData.width = Math.round(imgW * scaleH);
    } else {
        returnData.width = maxWidth;
        returnData.height = Math.round(imgH * scaleW);
    }
    
    //Give the image the new width and height values
    if (imgH > returnData.height || imgW > returnData.width) {
        imgObj.style.width = returnData.width + "px";
        imgObj.style.height = returnData.height + "px";
    } else {
        returnData.width = imgW;
        returnData.height = imgH;
    }
    returnData.image = imgObj;
    
    return returnData;
};
Locator.getSessionId = function(){
    if(Locator.getUrlParam("sessionid")){
        return Locator.getUrlParam("sessionid");
    } else if (Locator.readCookie("sessionId")) {
        return Locator.readCookie("sessionId");
    } else {
        return null;
    }
};
// Clinic Tracking
Locator.trackClinic = function(objID, mode){
	if(Locator.Config.enableTracking){
		var tmpPath = Locator.Config.trackingDataPath;
		var tmpSessionId = "?sessionId=" + Locator.getSessionId();
		var tmpInstId = "&institutionId=";
		var tmpDeptId = "&departmentId=";
		var tmpPhysId = "&physicianId=";
		var tmpMode = "&mode=" + mode;
		var tmpName;
		if (objID >= Locator.Config.resultLimit){
			//tierResults[obJID-resultLimit].showBioOverlay()
			tmpInstId += tierResults[objID-Locator.Config.resultLimit].officeInstitutionId;
			tmpDeptId += tierResults[objID-Locator.Config.resultLimit].officeDeptId;
			tmpPhysId += tierResults[objID-Locator.Config.resultLimit].physicianId;
			tmpName = tierResults[objID-Locator.Config.resultLimit].showDisplayName();
		} else {
			//clinicResults[obJID].showBioOverlay()
			tmpInstId += clinicResults[objID].officeInstitutionId;
			tmpDeptId += clinicResults[objID].officeDeptId;
			tmpPhysId += clinicResults[objID].physicianId;
			tmpName = clinicResults[objID].showDisplayName();
		}
		// assemble the path
		tmpPath += tmpSessionId + tmpInstId + tmpDeptId + tmpPhysId + tmpMode + "&uniq=" + Math.round(Math.random()*10000);;
		
		GDownloadUrl(tmpPath, function(data, responseCode) {
			if (responseCode == 200) {
				//alert("Success. Mode = " + mode + "Name = " + tmpName);
				//document.getElementById(Locator.Config.debugDivId).innerHTML = "";
				//document.getElementById(Locator.Config.debugDivId).innerHTML = tmpPath;
			} else {
				//alert("you have failed miserably");
				//document.getElementById(Locator.Config.debugDivId).innerHTML = "";
				//document.getElementById(Locator.Config.debugDivId).innerHTML = tmpPath;
			}
		});
	}
};
Locator.validateSearch = function(){
    var tmpSearchText = Locator.trimInputText(document.getElementById('searchZip').value);
    // Process by search type (city or postal)
    if (Locator.Config.appSearchType === "postal"){ // Process postal code submissions
        // Check valid postal code
        if (Locator.checkPostCode (tmpSearchText)) {
            // Postal Code is Valid! Go Go GeoCode and Reload Map!
            return true;
        } else {
            // Postal Code is inValid
            alert(Locator.Config.alrtInvalidPostal);
            document.getElementById('searchZip').focus();
            document.getElementById('searchZip').select();
            return false;
        }
    } else if (Locator.Config.appSearchType === "city") { // Process city or text based submissions
        if (tmpSearchText.length > 0 && tmpSearchText != Locator.Config.citySearchInstructions && tmpSearchText != Locator.Config.pcSearchInstructions) {
            return true;
        } else {
            // No text entered - nothing to search for:
            alert(Locator.Config.alrtInvalidSearchText);
            return false;
        }
    }
};
Locator.goClick = function(){	
	 var valid = Locator.validateSearch();
	 if (valid === false){ return;}
	
	 if(Locator.Config.enableTracking){
	 	scAjaxEvent('event10'); //track if valid search
	 }
	 
	var queryString = 'searchtype=' + Locator.Config.appSearchType +
	                  '&postalcode=' + Locator.trimInputText(document.getElementById('searchZip').value) +
	                  '&radius=' + document.getElementById("searchRadius").value +
	                  '&treatmenttype=' + document.getElementById("searchTreatment").value +
	 	 		      '&activeindex=' + Locator.Config.activeIndex;
	window.location = '?' + queryString;
};
//stripSpaces trims ALL spaces
Locator.stripSpaces = function(string){
	return string.split(' ').join('');
};

Locator.Utils.getEvent = function(evt){
	if(typeof(evt) !== 'undefined'){ return evt;}
	else{ 
		if(typeof(window.event) !== 'undefined'){ return window.event;}
		return null;
	}
};

Locator.Utils.getTarget = function(oEvent){
	if(typeof(oEvent.target) !== 'undefined'){ return oEvent.target;}
	else{ 
		if(typeof(oEvent.srcElement) !== 'undefined'){ return oEvent.srcElement;}
		return null;
	}
};
Locator.Utils.convertToMiles = function(kms){
	return Math.round(kms * 0.621371192237);
};

// THE FOLLOWING METHODS ARE FOR THE GERMANY(AUSTRIA, SWITZERLAND) TYPE LOCATOR ONLY!!!
// Method determines whether an active country has been specified in the url and is valid, if so it sets it
// if the activeindex has not been specified (implicitly set by the user), it will then search the url for
// a string that may possible match one of the strings in the searchDomains array that will set the proper
// index based on the url.. if all else fails, the default is 0 =)
Locator.setActiveCountry = function() {
	var tmpMaxIndex = (Locator.Config.searchDomains.length - 1);
	var tmpIndex = Locator.getUrlParam("activeindex");
	// check to see if activeindex is set in the url and that is within the correct bounds
	if (tmpIndex.length > 0 && tmpIndex >= 0 && tmpIndex <= tmpMaxIndex) {
		// supplied active index is valid, set it:
		Locator.Config.activeIndex = tmpIndex;
	// no activeindex query param was specified, attempt to set country based on URL	
	} else {
		// loop through the search domains array and check if string val exists in url and set the proper index
		/*for(i=0;i<Locator.Config.searchDomains.length;i++) {
			if(window.location.href.indexOf(Locator.Config.searchDomains[i]) != -1){
				Locator.Config.activeIndex = i;
				break;
			}
		}*/
		Locator.Config.activeIndex = 0; //Set to UK by default, both Irealnd and UK domains are the same.
	}

	
	return Locator.Config.activeIndex;
};

// Method builds and returns a country selection drop down DOM element
Locator.buildCountrySelector = function() {

	var countryContainer = document.createElement("div");

	// the descriptive label
	var countryLabel = document.createElement("label");
	countryLabel.appendChild(document.createTextNode(Locator.Config.searchSelectorLabel));

	// the select drop down
	var countrySelector = document.createElement("select");
	countrySelector.id = "countrySelect";

	// populate select element option values and inject
	for (var b=0, c_len=Locator.Config.countryNames.length; b<c_len; b++) {
        var tmpCountryOption = document.createElement("option");
        tmpCountryOption.text = Locator.Config.countryNames[b];
        tmpCountryOption.value = b;
		// set the currently active country value as selected
        if (Locator.Config.activeIndex == b) {
            tmpCountryOption.selected = true;
        }
        try {
            countrySelector.add(tmpCountryOption, null); 
        } catch (ex) {
            countrySelector.add(tmpCountryOption); 
        }
    }

	// build
	countryContainer.appendChild(countryLabel);
	countryContainer.appendChild(countrySelector);
	countrySelector.selectedIndex = Locator.Config.activeIndex; //Fix for IE 6 to set active country in select	

	return countryContainer;
};

// callback to fire on country select onchange event
Locator.changeCountry = function() {
	/*var tmpSearchText = Locator.trimInputText(document.getElementById('searchZip').value);
	var queryString = "";
	// if there is a string to search for then lets also do (or re-do) the search
	if (tmpSearchText.length > 0 && tmpSearchText != Locator.Config.citySearchInstructions && tmpSearchText != Locator.Config.pcSearchInstructions) {
		queryString = 'searchtype=' + Locator.Config.appSearchType +
	                   '&postalcode=' + Locator.trimInputText(document.getElementById('searchZip').value) +
	                   '&radius=' + document.getElementById("searchRadius").value +
	                   '&treatmenttype=' + document.getElementById("searchTreatment").value +
					   '&activeindex=' + this.value;
	} else {*/
	var queryString = 'activeindex=' + this.value;
	//}
	window.location = '?' + queryString;
};

var scAjaxEvent = function(evt, sVar, sEvalue){ //can take more than these 3 arguments
	s.events = evt;
    s.eVar1 = Locator.Config.AGNProduct;
        
    if(typeof sVar!== 'undefined' && sVar!== null && sVar!== ''){ //track evar if passed in
    	s[sVar] = sEvalue;
       	if(arguments.length > 3){ //loop through remaining variables, passed in as key-value pairs
       		for(var i = 3, arg_len = arguments.length; i < arg_len; i++){
       			if(i%2 != 0){ //only set if i is an odd #, as evens store values
        			var tmpCntr = i;
	        		s[arguments[i]] = arguments[tmpCntr+1];
        		}
        	}
       	}
    }
    void(s.t());
    //Clear variables
    s.events = "";  
    s[sVar] = "";
    if(arguments.length > 3){
		for(var i = 3, arg_len = arguments.length; i < arg_len; i++){
			if(i%2 != 0){ //only set if i is an odd #, as evens store values
				s[arguments[i]] = "";
			}
		}
    }
};
