﻿//<![CDATA[
    try {
        window.frameElement.height = '480';
    } catch(e) {
    }

    //var iSmallNavHeight = '294px';
    var iSmallNavHeight = '230px';
    //var iBigNavHeight = '434px';
    var iBigNavHeight = '370px';
    var iZoomThreshold = 5;
    var iShadowOffset = 7;
    var iShadowOpacity = 35;
    var sStationWebsiteURL = 'redirect.aspx?sm_id=';    
    var sDirectionsText = 'Address, City, State, or Zip';    

    function drawPinChart() {
        _sHTML = [];        
        _sHTML.unshift('</div>');

		//gSLBrandID is a global variable. assigned to local var for clarity.
		var brandID = gSLBrandID;
        
        var iCurZoom = map.getZoom();
        var x = aStations.length - 1;
        while (x >= 0) {
            var sCurColor;

            var TempImage = new Image();
            TempImage.src = getPinURL(aStations[x]['brand_id'], (iCurZoom >= 12), false);
            
            var curIcon;
            curIcon = new GIcon(G_DEFAULT_ICON, TempImage.src);
            curIcon.shadow = '';
            curIcon.iconSize = new GSize(TempImage.width, TempImage.height);               

            sCurColor = '#56D456';
            var BackgroundImageCSS = "";
            
            //override icon based on brand_id
            if (aStations[x]['brand_id']!=gSLBrandID)
                BackgroundImageCSS="background-image:url('images/" + aStations[x]['brand_id'] + "/station_locator/misc.png');";
            
            var sPopupHTML = [];

            sPopupHTML.push('<div style="height:31px; background:url(images/' + aStations[x]['brand_id'] + '/station_locator/pop_bg.png) repeat-x bottom left; padding-left:10px;"><div class="pop_logo" style="float:left;' + BackgroundImageCSS + '"></div><div id="imgClose" class="x5" style="float:right; padding-top:5px; padding-right:3px; cursor:pointer; position:relative; left:14px; top:-11px;' + BackgroundImageCSS + ' title="Close" alt="Close" onclick="closeIW();"></div><div id="divAmenities">');            

            var bHasServices = false;
            sPopupHTML.push('<div style="clear:both;"></div></div><div style="clear:both;"></div></div><div style="height:84px; padding:10px; padding-top:5px; background:url(images/' + aStations[x]['brand_id'] + '/station_locator/pop_content_bg.png) repeat-x bottom left"><span style="font-size:18px; font-weight:bold; text-transform:capitalize;" class="poptitle">');

            if (iCurZoom >= 0 && iCurZoom <= iZoomThreshold) {
                sPopupHTML.push(aStations[x]['State']);
                sPopupHTML.push('</span><br /><span style="font-size:14px;">');
                sPopupHTML.push(aStations[x]['cnt']);
                sPopupHTML.push(' Locations<p />Zoom in to see individual locations.');
                sPopupHTML.push('</span>');
            } else {
                sPopupHTML.push(aStations[x]['display_nm']);
                sPopupHTML.push('</span><br /><span style="font-size:14px;text-transform:capitalize;">');
                sPopupHTML.push('</span><span class="popupaddress">');
                sPopupHTML.push(aStations[x]['Address']);
                sPopupHTML.push('<br />');
                sPopupHTML.push(aStations[x]['City']);
                sPopupHTML.push(', ');
                sPopupHTML.push(aStations[x]['State']);
                sPopupHTML.push(', ');
                sPopupHTML.push(aStations[x]['Zip']);
                sPopupHTML.push('<br /><div id="divPhone" style="display:inline">');

                if (SCIcon != null) {
                    sPopupHTML.push('<div style="float:right; font-size:11px; line-height:15px;">');
                    sPopupHTML.push(number_format(aStations[x]['Dist'], 2));
                    sPopupHTML.push(' ');
                    sPopupHTML.push(abbreviatedDistanceDescriptor);
                    sPopupHTML.push(' from <img src="images/' + aStations[x]['brand_id'] + '/station_locator/search_center.png" alt="Search"></div>');
                }
                
                sPopupHTML.push(aStations[x]['Phone']);
                sPopupHTML.push('<div style="clear:right;"></div></div></span>');
                sPopupHTML.push('<div id="divDirections">Directions: <a href="javascript:void(0);" onclick="getAddy(1, \'From\');">To Here</a> | <a href="javascript:void(0);" onclick="getAddy(2, \'To\');">From Here</a></div>');
                sPopupHTML.push('<div id="divDirectionAddy" style="display:none;"><div id="divDirectionType" style="display:inline; font-weight:bold;"></div>: <input type="text" id="txtAddy" onkeydown="return trapEnter(event, \'directions_' + x + '\')" onmousedown="if (this.value == sDirectionsText) { this.value = \'\'; this.style.color = \'#000000\'; this.focus(); }"><br /><input type="button" id="btnGetDirections" value="Get Directions" onclick="getDirections(' + x + ');"><input type="button" id="btnCancel" value="Cancel" onclick="cancelDirections();"><input type="hidden" id="hidType"></div>');
                sPopupHTML.push('</div><div class="bottombar">');
                if (aStations[x]['websiteURL'] != "" && aStations[x]['websiteURL'] != "#")
                {
                    sPopupHTML.push('<a href="');
                    sPopupHTML.push(aStations[x]['websiteURL']);   
                    sPopupHTML.push('" target="_blank" class="bottombar_icon"' + ((BackgroundImageCSS=="")?'':' style="' + BackgroundImageCSS + '"') + '>Visit Store Website</a>');
                }
            }
            sPopupHTML.push('</div>');
            
            var marker = createMarker(aStations[x]['lng'], aStations[x]['lat'], curIcon, sPopupHTML.join(''), aStations[x]['id'], x);
            map.addOverlay(marker);
            aStations[x]['marker'] = marker;
            
            var sRow = [];
            
            sRow.push('<div id="td');
            sRow.push(aStations[x]['id']);
            sRow.push('" class="stationLocatorSearchResultRow"');
            if(iCurZoom >= 0 && iCurZoom <= iZoomThreshold){
              sRow.push(' onclick="jumpToState(\'');
              sRow.push(aStations[x]['StateAbbreviation'] + '\'');              
            }
            else{
              sRow.push(' onclick="popup(');
              sRow.push(x);
            }
            sRow.push(');" onmouseover="hiPin(');
            sRow.push(x);
            sRow.push(');" onmouseout="loPin(');
            sRow.push(x);
            sRow.push(');">');
            
            if(iCurZoom >= 0 && iCurZoom <= iZoomThreshold){
                sRow.push('  <div class="srHdrName">');
                sRow.push(aStations[x]['State']);
                sRow.push('  </div>');
                
                sRow.push('  <div>');
                sRow.push(aStations[x]['cnt']);
                sRow.push(' Locations');
                sRow.push('  </div>');
            }
            else{
                sRow.push('  <div class="srHdrName">');
                sRow.push(aStations[x]['display_nm']);
                sRow.push('  </div>');
                
                sRow.push('  <div>');
                sRow.push(aStations[x]['Address']);
                sRow.push('  </div>');
                
                sRow.push('<div>');
                sRow.push('<div class="fl">');
                sRow.push(aStations[x]['City']);
                sRow.push(', ');
                sRow.push(aStations[x]['State']);
                sRow.push('</div>');
                if (SCIcon != null) {
                    sRow.push('<div class="fr tar">');
                    sRow.push(number_format(aStations[x]['Dist'], 2));
                    sRow.push(' ');
                    sRow.push(distanceDescriptor);
                    sRow.push('</div>');                    
                }
                sRow.push('<div class="cb"></div>');
                sRow.push('</div>');
            }
            sRow.push('</div>');

            _sHTML.unshift(sRow.join(''));
            
            x--;
        }

        var sHeight = '';
        if (document.getElementById('divSearch').style.display == 'none') {
            sHeight = iBigNavHeight;
        } else {
            sHeight = iSmallNavHeight;
        }

        _sHTML.unshift('<h2 class="ColorHdrH2" style="padding-left : 10px;line-height:21px;">Search Results</h2><div id="divResults" style="height:' + sHeight + '; overflow-y:scroll; overflow-x:hidden;position:relative;">');
        
        var oDiv = document.getElementById('divPinChart');
        oDiv.innerHTML = _sHTML.join('');
        oDiv.scrollTop = 0;
        
        document.getElementById('divAmenityFilters').style.display = 'block';
        
    }
    
    function getNoStationsHTML() {
        return '<h2 class="ColorHdrH2" style="padding:0; padding-left:5px; line-height:27px;">Search Results</h2><div id="divResults" style="padding:10px;"><b>No locations found in the viewing area.</b></div>';
    }


    // CustomInfoWindow Class
    function CustomInfoWindow(pin, sClassName, html, mapParentDiv, gmGoogleMap, sHotelName) {
        var oThis = this;
        oThis.pin_ = pin;
        oThis.className_ = sClassName;
        oThis.html_ = html;
        oThis.parentDiv_ = mapParentDiv;
        oThis.HotelName_ = sHotelName;
        oThis.map_ = gmGoogleMap;
    }
    CustomInfoWindow.prototype = new GOverlay();

    CustomInfoWindow.prototype.initialize = function(oMap) {
        var oThis = this;
        
        var div = document.createElement('div');
        oThis.map_.getPane(G_MAP_FLOAT_PANE).appendChild(div);
        
        var pointer = document.createElement('div');
        oThis.map_.getPane(G_MAP_FLOAT_PANE).appendChild(pointer);
        
        var divShadow = document.createElement('div');
        oThis.map_.getPane(G_MAP_FLOAT_SHADOW_PANE).appendChild(divShadow);
        
        oThis.map_ = oMap;
        oThis.div_ = div;
        oThis.pointer_ = pointer;
        oThis.pointer_.id = 'divPointer';
        oThis.shadow_ = divShadow;
    }

    CustomInfoWindow.prototype.remove = function() {
        var oThis = this;
        if (oThis.div_) {
            if (oThis.div_.parentNode) { oThis.div_.parentNode.removeChild(oThis.div_); }
            if (oThis.pointer_.parentNode) { oThis.pointer_.parentNode.removeChild(oThis.pointer_); }
            if (oThis.shadow_.parentNode) { oThis.shadow_.parentNode.removeChild(oThis.shadow_); }
        }
        oThis = null;
    }

    CustomInfoWindow.prototype.copy = function() {
        var oThis = this;
        return new CustomInfoWindow(oThis.pin_, oThis.className_, oThis.html_, oThis.parentDiv_, oThis.map_, oThis.HotelName_);
    }

    CustomInfoWindow.prototype.redraw = function(bForce) {
        if (!bForce) return;
        var oThis = this;

        oThis.div_.onmouseover = new function() { oThis.map_.disableDragging(); };
        oThis.div_.onmouseout = new function() { oThis.map_.enableDragging(); };
        oThis.div_.className = oThis.className_;
        oThis.div_.innerHTML = oThis.html_;
        
        var iPointerTop, iPointerLeft;
        var iPointerWidth = 15;
        var iPointerHeight = 15;

        var divPoint = oThis.map_.fromLatLngToDivPixel(oThis.pin_.getPoint());
        var pinOffsetY = divPoint.y;
        var containerPoint = oThis.map_.fromLatLngToContainerPixel(oThis.pin_.getPoint());
        
        var iCurQuadrantX = Math.floor(containerPoint.x / (parseInt(oThis.parentDiv_.offsetWidth) / 3)) + 1;
        if (iCurQuadrantX < 1) { iCurQuadrantX = 1; }
        if (iCurQuadrantX > 3) { iCurQuadrantX = 3; }
        var iCurQuadrantY = Math.floor(containerPoint.y / (parseInt(oThis.parentDiv_.offsetHeight) / 3)) + 1;
        if (iCurQuadrantY < 1) { iCurQuadrantY = 1; }
        if (iCurQuadrantY > 3) { iCurQuadrantY = 3; }
        var iCurQuadrant = iCurQuadrantX + (3 * (iCurQuadrantY - 1));

        var popupX, popupY;
        var popupWidth = parseInt(oThis.div_.offsetWidth);
        var popupHeight = parseInt(oThis.div_.offsetHeight);
        switch (iCurQuadrant) {
            case 1:
                popupX = divPoint.x + iPointerWidth - 1;
                popupY = pinOffsetY;
                iPointerLeft = popupX - iPointerWidth + 1;
                iPointerTop = popupY;
                break;
            case 2: case 5:
                popupX = divPoint.x - (popupWidth / 2) - 1;
                popupY = pinOffsetY + iPointerHeight - 1;
                iPointerLeft = popupX + (popupWidth / 2) - (iPointerWidth / 2) + 1;
                iPointerTop = popupY - iPointerHeight + 1;
                break;
            case 3:
                popupX = divPoint.x - popupWidth - iPointerWidth + 1;
                popupY = pinOffsetY;
                iPointerLeft = popupX + popupWidth - 1;
                iPointerTop = popupY;
                break;
            case 4:
                popupX = divPoint.x + iPointerWidth - 1;
                popupY = pinOffsetY - (popupHeight / 2);
                iPointerLeft = popupX - iPointerWidth + 1;
                iPointerTop = popupY + (popupHeight / 2) - (iPointerHeight / 2) + 1;
                break;
            case 6:
                popupX = divPoint.x - popupWidth - iPointerWidth + 1;
                popupY = pinOffsetY - (popupHeight / 2);
                iPointerLeft = popupX + popupWidth - 1;
                iPointerTop = popupY + (popupHeight / 2) - (iPointerHeight / 2) + 1;
                break;
            case 7:
                popupX = divPoint.x + iPointerWidth - 1;
                popupY = pinOffsetY - popupHeight + 1;
                iPointerLeft = popupX - iPointerWidth + 1;
                iPointerTop = popupY + popupHeight - iPointerHeight;
                break;
            case 8:
                popupX = divPoint.x - (popupWidth / 2);
                popupY = pinOffsetY - popupHeight - iPointerHeight + 1;
                iPointerLeft = popupX + (popupWidth / 2) - (iPointerWidth / 2) + 1;
                iPointerTop = popupY + popupHeight - 1;
                break;
            case 9:
                popupX = divPoint.x - popupWidth - iPointerWidth + 1;
                popupY = pinOffsetY - popupHeight + 1;
                iPointerLeft = popupX + popupWidth - 1;
                iPointerTop = popupY + popupHeight - iPointerHeight;
                break;
            default:
                break;
        }

        var oThisDivStyle = oThis.div_.style;
        var oThisPointerStyle = oThis.pointer_.style;
        if (iCurQuadrant >= 1 && iCurQuadrant <= 9) {
            oThisDivStyle.left = popupX + 'px';
            oThisDivStyle.top = popupY + 'px';

            oThisPointerStyle.position = 'absolute';
            oThisPointerStyle.left = iPointerLeft + 'px';
            oThisPointerStyle.top = iPointerTop + 'px';
            oThis.pointer_.className = 'pointer' + iCurQuadrant;
        }
        
        var oShadowStyle = oThis.shadow_.style;
        oShadowStyle.position = 'absolute';
        oShadowStyle.top = (parseInt(oThisDivStyle.top) + iShadowOffset) + 'px';
        oShadowStyle.left = (parseInt(oThisDivStyle.left) + iShadowOffset) + 'px';
        oShadowStyle.width = oThis.div_.offsetWidth + 'px';
        oShadowStyle.height = oThis.div_.offsetHeight + 'px';
        oShadowStyle.backgroundColor = '#000000';
        oShadowStyle.opacity = iShadowOpacity / 100;
        oShadowStyle.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + iShadowOpacity + ')';
        
        if (document.getElementById('imgClose')) {
            if (iCurQuadrant == 3) {
                document.getElementById('imgClose').style.left = '-' + (oThis.div_.offsetWidth - (document.getElementById('imgClose').offsetWidth / 2) - 3) + 'px';
                document.getElementById('imgClose').className = 'x6';
            } else {
                document.getElementById('imgClose').className = 'x5';
            }
        }
    }
    
    function closeIW() {
        if (currentInfoWindow) { currentInfoWindow.remove(); }
        if (currentNavItem) { currentNavItem.style.backgroundColor = ''; }
        map.enableDragging();
    }

    // variables
    var aStations = [];
    var map;
    var oMap;
    var iBrowser;
    var currentInfoWindow = null;
    var currentNavItem = null;
    var bPanning = false;
    var bFirstPinLoad = true;
    var gdir = null;
    var dCurCenterLat = -1;
    var dCurCenterLong = -1;
    
    var days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
    var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

    var cFuelType = 'A';
    var oCurMarker = null;
    var aListeners = [];
    
    var SCIcon = null; // search center icon
    
    var search_center_icon = new GIcon();
    search_center_icon.image = sImgURL + 'search_center.png';
    search_center_icon.iconSize = new GSize(15,15);
    search_center_icon.iconAnchor = new GPoint(7,7);

    // functions
    function load() {
        if (GBrowserIsCompatible()) {
            dCurCenterLat = dInitLat;
            dCurCenterLong = dInitLong;

            if (parseInt(iInitStationID) == -1) {
                //document.getElementById('tdLegend').style.display = 'block';
                //document.getElementById('tdLegend2').style.display = 'block';
            }
            oMap = document.getElementById('gm_map');

            map = new GMap2(oMap);

            gdir = new GDirections(map, document.getElementById("divDirectionsResults"));
            GEvent.addListener(gdir, "load", onGDirectionsLoad);
            GEvent.addListener(gdir, "error", handleErrors);

            map.checkResize();
            
            if (iInitStationID != -1) {
                map.setCenter(new GLatLng(parseFloat(dInitLat) + 0.0008, dInitLong), iInitZoom, G_NORMAL_MAP);
            } else {
                map.setCenter(new GLatLng(dInitLat, dInitLong), iInitZoom, G_NORMAL_MAP);
            }

            map.addControl(new GLargeMapControl3D());
            map.addControl(new GScaleControl());
            map.addControl(new GMapTypeControl());
            map.enableScrollWheelZoom();

            GEvent.addListener(map, 'moveend', function() {
                if (!bPanning) {
                    GetStationCoordinatesByLLBounds();
                }
                bPanning = false;
            });

            if (sInitTo == '' && sInitFrom == '' && map.getZoom() > 5) {
                SCIcon = new GMarker(new GPoint(dInitLong, dInitLat), search_center_icon);
                map.addOverlay(SCIcon);
            }

            browserCheck();
            GetStationCoordinatesByLLBounds();
            
            if (parseInt(iInitStationID) == -1) {
                document.getElementById('txtCity').focus();
            }
            
            resizeIFrame();
        }
    }

    function browserCheck() {
        if (document.getElementById) {
            navigator.appName == 'Netscape' && parseInt(navigator.appVersion) >= 5 ? iBrowser = 1 : iBrowser = 0;
        } else {
            iBrowser = -1;
        }
    }    			

    function GetStationCoordinatesByLLBounds() {
        toggleLoadingImage(true);
        
        map.checkResize();

        var bounds = map.getBounds();
        var bSW = bounds.getSouthWest();
        var bNE = bounds.getNorthEast();
        var dOffset = .00;

        //if (parseInt(iInitStationID) == -1) {
            //StationWebsites.StationLocator_IFrame.gus(map.getZoom(), bSW.lng() - dOffset, bNE.lng() + dOffset, bSW.lat() - dOffset, bNE.lat() + dOffset, dCurCenterLong, dCurCenterLat, gus_callback);
            StationWebsites.StationLocator_IFrame.gusV2(map.getZoom(), bSW.lng() - dOffset, bNE.lng() + dOffset, bSW.lat() - dOffset, bNE.lat() + dOffset, dCurCenterLong, dCurCenterLat, get_amenity_filters(), gus_callbackv2);
       //} else {
            //StationWebsites.StationLocator_IFrame.gus(map.getZoom(), dInitLong, dInitLong, dInitLat, dInitLat, dInitLong, dInitLat, gus_callback);
         // StationWebsites.StationLocator_IFrame.initGus(map.getZoom(), dInitLong, dInitLat, gus_callbackv2);
        //}
    }
	
	function gus_callbackv2(res) 
	{
	    cleanup();
	    aStations = [];
	    if (res.value && res.value.ResponseCode == 1)
	    {
	        
	        if (res.value.Payload.length > 0)
	        {
	            drawStationsV2(res.value.Payload);
	    
	            if (bFirstPinLoad) {
		            if (iInitStationID != -1) {
		                var x = 0;
		                while (x < aStations.length) {
		                    if (aStations[x]['sm_id'] == iInitStationID) {
                                GEvent.trigger(aStations[x]['marker'], 'click');
		                        break;
		                    }
		                    x++;
		                }
		            } else {
                        if (sInitTo != '' && sInitFrom != '') {
                            //setDirections(sInitFrom, sInitTo, "en_US");
                            setDirections(sInitFrom, sStationLat + ',' + sStationLng, "en_US");
                        }
		            }
                
		    } 
		 }	    
	    else {
		        document.getElementById('divPinChart').innerHTML = getNoStationsHTML();
		        //document.getElementById('divAmenityFilters').style.display = 'none';
		    }
	    
	    if (bFirstPinLoad) { bFirstPinLoad = false; }
	   }
	   
	   toggleLoadingImage(false);
	   
	}
	
	/*	
    function gus_callback(res) {
        cleanup();
        aStations = [];
	    if (res.value && res.value.Tables.length > 0) {
		    if (res.value.Tables[0].Rows.length > 0) {
		        drawStations(res.value.Tables[0]);

                    if (bFirstPinLoad) {
		                if (iInitStationID != -1) {
		                    var x = 0;
		                    while (x < aStations.length) {
		                        if (aStations[x]['sm_id'] == iInitStationID) {
                                    GEvent.trigger(aStations[x]['marker'], 'click');
		                            break;
		                        }
		                        x++;
		                    }
		                } else {
                        if (sInitTo != '' && sInitFrom != '') {
                            //setDirections(sInitFrom, sInitTo, "en_US");
                            setDirections(sInitFrom, sStationLat + ',' + sStationLng, "en_US");
                        }
		            }
                }
		    } else {
		        document.getElementById('divPinChart').innerHTML = getNoStationsHTML();
		    }
	    }
	    
	    if (bFirstPinLoad) { bFirstPinLoad = false; }
    }
    */
    function createMarker(lat, lng, icon, html, sid, x) {
        var point = new GPoint(lat, lng);
        var marker = new GMarker(point, icon);

        aListeners.push(GEvent.addListener(marker, 'click', function() {
            closeIW();
            currentInfoWindow = new CustomInfoWindow(this, 'ciwClass', html, document.getElementById('gm_map'), map, '');
            map.addOverlay(currentInfoWindow);
            
            //if (currentNavItem) { currentNavItem.style.backgroundColor = ''; }
            if (currentNavItem) { currentNavItem.className = 'stationLocatorSearchResultRow'; }
            currentNavItem = document.getElementById('td' + sid);
            //currentNavItem.style.backgroundColor = '#FAFAD2';
            currentNavItem.className += ' stationLocatorSearchResultsRowSel';
            
            var item = document.getElementById('td' + sid);
            var cont = document.getElementById('divResults');
            
            if(item.offsetTop < cont.scrollTop || (item.offsetTop + item.offsetHeight) > (cont.scrollTop + cont.offsetHeight)) {
                cont.scrollTop = item.offsetTop;
            }
                        
            var gLatLng = new GLatLng(lng, lat);
            if (!map.getBounds().containsLatLng(gLatLng)) {
                bPanning = true;
                map.panTo(gLatLng);
            }
        }));

        aListeners.push(GEvent.addListener(marker, 'mouseover', function() {
            hiPin(x);
        }));

        aListeners.push(GEvent.addListener(marker, 'mouseout', function() {
            loPin(x);
        }));

        return marker;
    }

	function cleanup() {
        var x = 0;
        while (x < aListeners.length) {
            GEvent.removeListener(aListeners[x]);
            x++;
        }
        
        x = 0;
        while (x < aStations.length) {
            map.removeOverlay(aStations[x]['marker']);
            x++;
        }
	}

    function jumpToLocation() {
        var sSearch = '';
        var stateLevelSearch = true;
        
        // How should the search be performed for this website: using SearchMode==1 (i.e. use the verbose search inputs), or SearchMode==2 (i.e. the single search box)
        if (searchMode == 1)
        {
            if (document.getElementById('txtAddress').value != '') {
                sSearch += document.getElementById('txtAddress').value;
                stateLevelSearch = false;
            }
            
            if (document.getElementById('txtCity').value != '') {
                if (sSearch.length > 0) { sSearch += ', '; }
                sSearch += document.getElementById('txtCity').value;
                stateLevelSearch = false;
            }
            
            if (document.getElementById('txtState').value != '') {
                if (sSearch.length > 0) { sSearch += ', '; }
                sSearch += document.getElementById('txtState').value;            
            }

            if (document.getElementById('txtZIP').value != '') {
                if (sSearch.length > 0) { sSearch += ', '; }
                sSearch += document.getElementById('txtZIP').value;
                stateLevelSearch = false;
            }
        }
        else if (searchMode == 2)
        {
            stateLevelSearch = false;
            sSearch = getSearchBox().value;
            dismissSearchSuggestions();
        }
        
        if(sSearch==''){
          GetStationCoordinatesByLLBounds();
        }
        else{        
            if(stateLevelSearch){
                //make ajax call to get the center point and zoom level of a state
                StationWebsites.StationLocator_IFrame.getStateCenterPoint(sSearch, getStateCenterPoint_callback);
            }
            else{            
                var geocoder = new GClientGeocoder();
                geocoder.getLatLng(sSearch, setSLMapCenterWrapper);        
            }
        }

        return false;
    }
    
    function getStateCenterPoint_callback(result){
      if(result && result.value && result.value.ResponseCode == 1){
        var item = result.value.Payload;
        
        var point = new GLatLng(item.Latitude, item.Longitude);
        setSLMapCenter(point, item.ZoomLevel);
      }
      else{
        alert('State not found.');
      }
    }
    
    function setSLMapCenterWrapper(point){
      setSLMapCenter(point, 11);
    }
    
    function setSLMapCenter(point, zoomLevel){
        if (!point){
            alert(sSearch + ' not found.');
        }
        else{
            dCurCenterLat = point.lat();
            dCurCenterLong = point.lng();

            map.setCenter(point, zoomLevel);

            if(SCIcon != null){
                map.removeOverlay(SCIcon);
            }
             
            SCIcon = new GMarker(point, search_center_icon);
            map.addOverlay(SCIcon);
        }
    }
    
    function trapEnter(e, sType) {
        var key;
        
        if (window.event) {
            key = window.event.keyCode;
        } else {
            key = e.which;
        }
        
        if (key == 13) {
            if (!sType) {
                jumpToLocation();
            } else if (sType.indexOf('directions') != -1) {
                getDirections(sType.split('_')[1]);
            }
            return false;
        } else {
            return true;
        }
    }
    
    function toggleSearch() {
        var oSearch = document.getElementById('divSearch');
        var oNewSearch = document.getElementById('divNewSearch');
        var oDivResults = document.getElementById('divResults');
        if (oSearch.style.display == 'none') {
            oSearch.style.display = '';
            oNewSearch.style.display = 'none';
            if (oDivResults) { oDivResults.style.height = iSmallNavHeight; }
        } else {
            oSearch.style.display = 'none';
            oNewSearch.style.display = '';
            if (oDivResults) { oDivResults.style.height = iBigNavHeight; }
        }
    }
    
    function popup(x) {
        GEvent.trigger(aStations[x]['marker'], 'click');
    }
    
    function hiPin(x) {
        if (aStations[x]) {
            var iCurZoom = map.getZoom();            
            aStations[x]['marker'].setImage(getPinURL(aStations[x]['brand_id'], (iCurZoom >= 12), true));
        }
    }

    function loPin(x) {
        if (aStations[x]) {
            var iCurZoom = map.getZoom();
            aStations[x]['marker'].setImage(getPinURL(aStations[x]['brand_id'], (iCurZoom >= 12), false));            
        }
    }

    function getPinURL(brand_id, isBig, isHi)
    {
        return "images/" + brand_id + "/station_locator/" + ((isBig)?"big-":"") + "map-pin" + ((isHi)?"-hi":"")+ ".png";
    }
    
    function getAddy(iType, sType) {
        map.disableDragging();
        document.getElementById('hidType').value = iType;
        document.getElementById('divDirections').style.display = 'none';
        document.getElementById('divPhone').style.display = 'none';
        document.getElementById('divDirectionType').innerHTML = sType;
        document.getElementById('divDirectionAddy').style.display = 'block';
        
        document.getElementById('txtAddy').style.color = '#808080';
        document.getElementById('txtAddy').value = sDirectionsText;
        //document.getElementById('txtAddy').focus();
    }
    
    function cancelDirections() {
        map.enableDragging();
        document.getElementById('divDirections').style.display = '';
        document.getElementById('divPhone').style.display = '';
        document.getElementById('divDirectionAddy').style.display = 'none';
    }
    
    function getDirections(sIndex) {
        var sType = document.getElementById('hidType').value;
        var sUserAddy = document.getElementById('txtAddy').value;
        
        var sSearch = [];
        /*sSearch.push(aStations[sIndex]['Address']);
        sSearch.push(', ');
        sSearch.push(aStations[sIndex]['City']);
        sSearch.push(', ');
        sSearch.push(aStations[sIndex]['State']);*/
        sSearch.push(aStations[sIndex]['lat']);
        sSearch.push(',');
        sSearch.push(aStations[sIndex]['lng']);

        if (parseInt(sType) == 1) {
            setDirections(sUserAddy, sSearch.join(''), "en_US");
        } else {
            setDirections(sSearch.join(''), sUserAddy, "en_US");
        }
    }

    function setDirections(fromAddress, toAddress, locale) {
        gdir.load("from: " + fromAddress + " to: " + toAddress, { "locale": locale });
    }

    function handleErrors(){
       if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
         alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
       else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
         alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
       else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
         alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
       else if (gdir.getStatus().code == G_GEO_BAD_KEY)
         alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
       else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
         alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
       else alert("An unknown error occurred.");
    }

    function onGDirectionsLoad() { 
        closeIW();
        map.clearOverlays();
        document.getElementById("divDirectionsResults").innerHTML = '';
        document.getElementById('divDirectionsHeader').style.display = '';
        setTimeout(resizeIFrame, 500);
    }
    
    function resizeIFrame() {
        if (sParentFrameSrc == '') {
            window.frameElement.height = document.body.scrollHeight;
        } else {
            var iframe = document.getElementById( 'inneriframe' );
            var height = Math.max( document.body.offsetHeight, document.body.scrollHeight );
            iframe.src = sParentFrameSrc + '?height='+height;
        }
    }
    
    function hideDirections() {
        document.getElementById('divDirectionsHeader').style.display = 'none';
        map.clearOverlays();
        document.getElementById("divDirectionsResults").innerHTML = '';
        GetStationCoordinatesByLLBounds();
        resizeIFrame();
    }
    /*
    function drawStations(dtStations) {
        var bDrawPinChart = true;
        var x = 0;
        while (x < dtStations.Rows.length) {
            var oRow = dtStations.Rows[x];
            
            aStations[x] = [];

            var iCurZoom = map.getZoom();
            if (iCurZoom >= 0 && iCurZoom <= iZoomThreshold) {
                if (oRow.cnt) { aStations[x]['cnt'] = oRow.cnt; } else { bDrawPinChart = false; break; }
                if (oRow.State) { aStations[x]['State'] = oRow.State; } else { bDrawPinChart = false; break; }
                aStations[x]['brand_id'] = gSLBrandID;
            } else {
                if (oRow.Station) { aStations[x]['Station'] = oRow.Station; } else { bDrawPinChart = false; break; }
                if (oRow.Address) { aStations[x]['Address'] = oRow.Address; } else { bDrawPinChart = false; break; }
                if (oRow.City) { aStations[x]['City'] = oRow.City.replace(/ - [A-Z]+/gi,''); } else { bDrawPinChart = false; break; }
                aStations[x]['Zip'] = oRow.Zip;
                aStations[x]['Phone'] = oRow.Phone;
                if (oRow.State) { aStations[x]['State'] = oRow.State.toUpperCase(); } else { bDrawPinChart = false; break; }
                aStations[x]['sm_id'] = oRow.StationId;
                aStations[x]['brand_id'] = oRow.brand_id;
                aStations[x]['Dist'] = oRow.Dist;
                aStations[x]['display_nm'] = oRow.display_nm;
                aStations[x]['websiteURL'] = oRow.websiteURL;
            }

            if (oRow.id) { aStations[x]['id'] = oRow.id; } else { bDrawPinChart = false; break; }
            if (oRow.Lng) { aStations[x]['lng'] = oRow.Lng; } else { bDrawPinChart = false; break; }
            if (oRow.Lat) { aStations[x]['lat'] = oRow.Lat; } else { bDrawPinChart = false; break; }
            
            x++;
        }

        if (bDrawPinChart) { drawPinChart(); }
    }
    */
    function drawStationsV2(dtStations) {
        var bDrawPinChart = true;
        var x = 0;
        while (x < dtStations.length) {
            var oRow = dtStations[x];
            
            aStations[x] = [];

            var iCurZoom = map.getZoom();
            if (iCurZoom >= 0 && iCurZoom <= iZoomThreshold) {
                if (oRow.StationCount) { aStations[x]['cnt'] = oRow.StationCount; } else { bDrawPinChart = false; break; }
                if (oRow.State) { aStations[x]['State'] = oRow.State; } else { bDrawPinChart = false; break; }
                if (oRow.StateAbbreviation) { aStations[x]['StateAbbreviation'] = oRow.StateAbbreviation; } else { bDrawPinChart = false; break; }
                aStations[x]['brand_id'] = gSLBrandID;
            } else {
                if (oRow.DisplayName) { aStations[x]['Station'] = oRow.DisplayName; } else { bDrawPinChart = false; break; }
                if (oRow.Address) { aStations[x]['Address'] = oRow.Address; } else { bDrawPinChart = false; break; }
                if (oRow.City) { aStations[x]['City'] = oRow.City.replace(/ - [A-Z]+/gi,''); } else { bDrawPinChart = false; break; }
                aStations[x]['Zip'] = oRow.Zip;
                aStations[x]['Phone'] = oRow.PrimaryPhone;
                if (oRow.State) { aStations[x]['State'] = oRow.State.toUpperCase(); } else { bDrawPinChart = false; break; }
                aStations[x]['sm_id'] = oRow.StationId;
                aStations[x]['brand_id'] = oRow.BrandID;
                aStations[x]['Dist'] = oRow.Distance * distanceMultiplier; // convert the current country's distance system
                aStations[x]['display_nm'] = oRow.DisplayName;
                aStations[x]['websiteURL'] = oRow.StationUrl;
                if (oRow.StationId) { aStations[x]['id'] = oRow.StationId; } else { bDrawPinChart = false; break; }
            }

            
            if (oRow.Longitude) { aStations[x]['lng'] = oRow.Longitude; } else { bDrawPinChart = false; break; }
            if (oRow.Latitude) { aStations[x]['lat'] = oRow.Latitude; } else { bDrawPinChart = false; break; }
            
            x++;
        }

        if (bDrawPinChart) { drawPinChart(); }
    }
      
    function number_format(dNumber, iDecimals) {
        var dVal;
        dNumber.toFixed ? dVal = dNumber.toFixed(iDecimals) : dVal = Math.round(dNumber * Math.pow(10, iDecimals)) / Math.pow(10, iDecimals);
        return dVal
    }
    
    function get_amenity_filters ()
    {
        var chkContainer = document.getElementById('divAmenityFilters');
        var amenities = chkContainer.getElementsByTagName('INPUT');
        var i;
        var sb = [];
        
        for (i = 0; i < amenities.length; i++)
        {
            if (amenities[i].checked)
            {
                sb.push(amenities[i].value);
            }
        }
        
        return sb;
        
    }
    
    function toggleLoadingImage(flag){
      var img = document.getElementById('imgLoading');
      if(img){
        img.style.visibility = (flag?'visible':'hidden');
      }
    }
    
    function jumpToState(stateAbbr){
      document.getElementById('txtState').value = stateAbbr;
      jumpToLocation();
    }
    
//]]>

