/*
GENERAL TODOs
- get more data for other merchant types
- services
- transportation
- mtn facilities
- lodging
	
GENERAL WEB COUNCIL PRESENTATION NOTES
- show defining a neighborhood
- show adding a restaurant, using latlon.html
- snack cart at Keystone Ranch
- show geocode lookup using a real address
- blue moon in dillon?
- show how that new restaurant also on snow.com now
- show how alpenglow stube is mis-plotted
- use latlon.html to use hybrid view to re-plot it.
- everything optional (don't need to define neighborhoods if it doesn't make sense)
	
*/

var polygon;
var map;
var map2
var neighborhood;
var neighborhoodsArray = new Array();
var merchantArray = new Array();
var selectedIcon;
var _isUberMap = false;
var _displayedMarkerCount = 0;
var gdir;
var geocoder = null;
var addressMarker;
var openMerchantTypes = new Array();
var ratingEnd=5;
var ratingStart=0;
var xml = "";

function load(mapXml) {
$("#maptoLoad").showLoading();
    setTimeout(function() {
        
        if (GBrowserIsCompatible()) {
        $("#map").css("display","block");
        //$("#map").css("zoom","1");
            map = new GMap2(document.getElementById("map"));
            //map.addControl(new google.maps.LocalSearch(), new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10, 20)));
            map.setUIToDefault();
            map.disableDoubleClickZoom();
            map.disableScrollWheelZoom();
            map2 = new GMap2(document.getElementById("map2"));
            map2.addControl(new GSmallMapControl());
            gdir = new GDirections(map2, document.getElementById("directions"));
            GEvent.addListener(gdir, "error", handle_Ubermap3_Errors);
            GEvent.addListener(gdir, "addoverlay", onGDirectionsLoad);
            selectedIcon = new GIcon();
            selectedIcon.shadow = "marker_shadow.png";
            selectedIcon.iconSize = new GSize(25, 30);
            selectedIcon.shadowSize = new GSize(39, 12);
            selectedIcon.iconAnchor = new GPoint(19, 26);
            selectedIcon.infoWindowAnchor = new GPoint(15, 2);
            selectedIcon.infoShadowAnchor = new GPoint(22, 8);
            selectedIcon.image = "marker_selected.png";

            prepareMarkers(mapXml);
            $("#maptoLoad").hideLoading();
        } 
        $("#divLodgingDetailMapLoad").hideLoading();
        
    }, 7000);
}

//Rating Slider Control
 $("#starRatingFilter").slider({
		animate: true,
		range: true,
		min: 1,
		max: 5,
		step: 0.5,
		values: [1,5],
		slide: function(event, ui) {
			ratingStart = ui.values[0];
			ratingEnd = ui.values[1];
			 SelectedValue = $(".lodgingListFilter select").val();
             dropdown=document.getElementById('ddlResultPerPage');
             SelectListFilters();
            selectedIndex=dropdown.selectedIndex;
            PageTo = $("#ddlResultPerPage").val(); 
            ResultPerPage= $("#ddlResultPerPage").val(); 
            PageFrom=0;
             RenderOutput();
		}
	});
	
	
	
	function GetMapFilter()
	{
	var chkboxid=document.getElementById('chkAll');
	selectedNeighbours='';
    selectedLodgingType='';
    selectedAmenities='';
    var documentInput=document.getElementsByTagName("input");
    var unCheckedLocationCounter=0;
    for (var counter=0;counter<documentInput.length;counter++) 
    { 
        var Comparision = documentInput[counter]; 
       if (Comparision.className == 'chkBox chkboxNeighbours') 
        { 
            if (Comparision.checked==true)
            {
                selectedNeighbours+=Comparision.value +','
                
            } 
            else
            {
            unCheckedLocationCounter=unCheckedLocationCounter+1;
            }
        }
        else if (Comparision.className == 'chkBox checkboxLodgingType') 
        { 
            if (Comparision.checked==true)
            {
                selectedLodgingType+=Comparision.value +','
                
            } 
        }
        else if (Comparision.className == 'chkBox checkboxAmenities') 
        { 
            if (Comparision.checked==true)
            {
                selectedAmenities+=Comparision.value +','
            } 
        }
    } 
        if (chkboxid.checked==true)
                {
                selectedNeighbours=='';
                }
                
                 if (unCheckedLocationCounter>0)
                {
                    chkboxid.checked=false;

                }
                else
                {
                    chkboxid.checked=true;
                }
    
    selectedNeighbours = (selectedNeighbours=='') ? selectedNeighbours : selectedNeighbours.substring(0,(selectedNeighbours.length-1))+'|';
    selectedLodgingType = (selectedLodgingType=='') ? selectedLodgingType : selectedLodgingType.substring(0,(selectedLodgingType.length-1))+'|';
    selectedAmenities = (selectedAmenities=='') ? selectedAmenities : selectedAmenities.substring(0,(selectedAmenities.length-1))+'|';
    if (selectedNeighbours=='' || selectedLodgingType=='')
    {
        filterCriteria='0|0|';
    }
    else
    {
        filterCriteria=selectedNeighbours+selectedLodgingType+selectedAmenities;
    }
$.ajax({
        type: "POST",
        url: "/vailresorts/sites/PlanningAndBooking/WebServices/LodgingWebService.svc/GetLodgingPropertyListMapXml",
       data: "{\"filterCriteria\" : \""+filterCriteria+"\",\"ratingStart\" : \""+ratingStart+"\",\"ratingEnd\" : \""+ratingEnd+"\"}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            load(msg.d);
        },
		error: function(xhr, status, error) {
			handle_Ubermap3_Error(xhr, status, error);
		}
        });

}
	function SelectListFilters()
	{
	if($("ul.mainTabsPnB li:first").hasClass("tabs-selected"))
	    {
	       FillConditionalFilter();
	    }
	    else
	    {
	        GetMapFilter();
	    }
	}
	
	
	function CheckedAllLocation(chkboxid)
  {
	if($("ul.mainTabsPnB li:first").hasClass("tabs-selected"))
	    {
	       CheckedAllLocationTab(chkboxid);
	    }
	    else
	    {
	        CheckedAllLocationMap(chkboxid);
	    }
	}

function handle_Ubermap3_Error(xhr, status, error)
{
    var errMsg = getErrorMessage(xhr,status,error);
    if(errMsg != ' ')
    {
	//alert(errMsg);
    }
}
	
	function SelectAllFilterStatus(classNames,checkedStatus,typeofFilter)
  {
	if($("ul.mainTabsPnB li:first").hasClass("tabs-selected"))
	    {
	      SelectAllFilterStatusTab(classNames,checkedStatus,typeofFilter)
	    }
	    else
	    {
	         SelectAllFilterStatusMap(classNames,checkedStatus,typeofFilter)
	    }
	}
	
	function SelectAllFilterStatusMap(classNames,checkedStatus,typeofFilter)
{
        var filterValue = '';
        selectedNeighbours = '';
	    selectedLodgingType = '';
	    selectedAmenities = '';
        var documentInput = document.getElementsByTagName("input");
	    for (var counter = 0; counter < documentInput.length; counter++) 
	    {
		var Comparision = documentInput[counter];
        if (Comparision.className == classNames) 
		{
			if (Comparision.disabled == false) 
			{
			
			    Comparision.checked = checkedStatus;
				
			}
			
			if (Comparision.checked == true) 
			{
				filterValue += Comparision.value + ','

			}
		}
		
		if (Comparision.className == 'chkBox chkboxNeighbours') 
		{
			
				if (Comparision.disabled == false && Comparision.checked == true) 
				{
				    selectedNeighbours += Comparision.value + ','
                }
				
		}
		else if (Comparision.className == 'chkBox checkboxLodgingType') 
		{
			if (Comparision.checked == true) {
				selectedLodgingType += Comparision.value + ','

			}
		}
		else if (Comparision.className == 'chkBox checkboxAmenities') {
			if (Comparision.checked == true) {
				selectedAmenities += Comparision.value + ','

			}
		}
		
	}
		
if  (typeofFilter=='Neighbours')
{
var checkedall=document.getElementById('chkAll');
        checkedall.checked=checkedStatus;
selectedNeighbours=filterValue;
}
else if (typeofFilter=='LodgingType')
{
selectedLodgingType=filterValue;
}
else if (typeofFilter=='Amenities')
{
selectedAmenities=filterValue;
}

		
	selectedNeighbours = (selectedNeighbours == '') ? selectedNeighbours: selectedNeighbours.substring(0, (selectedNeighbours.length - 1)) + '|';
	selectedLodgingType = (selectedLodgingType == '') ? selectedLodgingType: selectedLodgingType.substring(0, (selectedLodgingType.length - 1)) + '|';
	selectedAmenities = (selectedAmenities == '') ? selectedAmenities: selectedAmenities.substring(0, (selectedAmenities.length - 1)) + '|';
	if (selectedNeighbours == '' || selectedLodgingType == '') 
	{
		filterCriteria = '0|0|';
	}
	else {
		filterCriteria = selectedNeighbours + selectedLodgingType + selectedAmenities;
	}
	
 $.ajax({
        type: "POST",
        url: "/vailresorts/sites/PlanningAndBooking/WebServices/LodgingWebService.svc/GetLodgingPropertyListMapXml",
       data: "{\"filterCriteria\" : \""+filterCriteria+"\",\"ratingStart\" : \""+ratingStart+"\",\"ratingEnd\" : \""+ratingEnd+"\"}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            load(msg.d);
        },
		error: function(xhr, status, error) {
			handle_Ubermap3_Error(xhr, status, error);
		}
        });	
	return false;

}
	function CheckedAllLocationMap(chkboxid)
	{
	selectedNeighbours='';
    selectedLodgingType='';
    selectedAmenities='';
    var documentInput=document.getElementsByTagName("input");
for (var counter=0;counter<documentInput.length;counter++) 
{ 
    var Comparision = documentInput[counter]; 
   if (Comparision.className == 'chkBox chkboxNeighbours') 
    { 
           
            if (chkboxid.checked==true)
            {
            if (Comparision.disabled==false)
                {
                Comparision.checked=true;
                }
            }
            else
            {
              Comparision.checked=false;
            }
        if (Comparision.checked==true)
        {
            selectedNeighbours+=Comparision.value +','
            
        } 
    }
    else if (Comparision.className == 'chkBox checkboxLodgingType') 
    { 
        if (Comparision.checked==true)
        {
            selectedLodgingType+=Comparision.value +','
            
        } 
    }
    else if (Comparision.className == 'chkBox checkboxAmenities') 
    { 
        if (Comparision.checked==true)
        {
            selectedAmenities+=Comparision.value +','
            
        } 
    }
} 
selectedNeighbours = (selectedNeighbours=='') ? selectedNeighbours : selectedNeighbours.substring(0,(selectedNeighbours.length-1))+'|';
selectedLodgingType = (selectedLodgingType=='') ? selectedLodgingType : selectedLodgingType.substring(0,(selectedLodgingType.length-1))+'|';
selectedAmenities = (selectedAmenities=='') ? selectedAmenities : selectedAmenities.substring(0,(selectedAmenities.length-1))+'|';
if (selectedNeighbours=='' || selectedLodgingType=='')
{
    filterCriteria='0|0|';
}
else
{
    filterCriteria=selectedNeighbours+selectedLodgingType+selectedAmenities;
}
 $.ajax({
        type: "POST",
        url: "/vailresorts/sites/PlanningAndBooking/WebServices/LodgingWebService.svc/GetLodgingPropertyListMapXml",
       data: "{\"filterCriteria\" : \""+filterCriteria+"\",\"ratingStart\" : \""+ratingStart+"\",\"ratingEnd\" : \""+ratingEnd+"\"}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            load(msg.d);
        },
		error: function(xhr, status, error) {
			handle_Ubermap3_Error(xhr, status, error);
		}
        });	
}


function pnbCallback()
{
	load(xml);
}
   
   function loadGMapScript() 
	{
		if (typeof GMap2 == 'function') 
		{
			pnbCallback();
			return;
		}
		var script = document.createElement('script');
		script.setAttribute('src', 'http://maps.google.com/maps?file=api&v=2.x&key=' + gmapKey + '&async=2&callback=pnbCallback');
		script.setAttribute('type', 'text/javascript');
		document.documentElement.firstChild.appendChild(script);
	}
   
 //This method is used to call the ajax enabled web service to get the map xml
  function GetLodgingMapXMl() {
    SelectListFilters();
    $.ajax({
        type: "POST",
        url: "/vailresorts/sites/PlanningAndBooking/WebServices/LodgingWebService.svc/GetLodgingPropertyListMapXml",
       data: "{\"filterCriteria\" : \""+filterCriteria+"\",\"ratingStart\" : \""+ratingStart+"\",\"ratingEnd\" : \""+ratingEnd+"\"}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
			xml = msg.d;
			loadGMapScript();
            //load(msg.d);
        },
		error: function(xhr, status, error) {
			handle_Ubermap3_Error(xhr, status, error);
		}
        });
}



function prepareMarkers(mapXml) {
    var xml = GXml.parse(mapXml);
    var docRootNode = xml.documentElement;
    if (docRootNode.getAttribute("IsUberMap") == "true") {

        _isUberMap = true;
        // TODO: if this isn't an uber map??
    }

    var merchantTypes = xml.documentElement.getElementsByTagName("MerchantType");
    var neighborhoods = xml.documentElement.getElementsByTagName("Neighborhood");

if(merchantTypes.length > 0)
{
 var tempMerchantType = merchantTypes[0];
 var tempMerchants = null;
 tempMerchants = tempMerchantType.getElementsByTagName("Merchant");
    // If only single merchant item
     if(tempMerchants != null && tempMerchants.length == 1)
     {
     var merchant = tempMerchants[0];
        // Set merchant Latitude and Longitude as Center of the map.    
        map.setCenter(new GLatLng(parseFloat(merchant.getAttribute("Latitude")), parseFloat(merchant.getAttribute("Longitude"))), parseInt(docRootNode.getAttribute("ZoomLevel")));
        map2.setCenter(new GLatLng(parseFloat(merchant.getAttribute("Latitude")), parseFloat(merchant.getAttribute("Longitude"))), parseInt(docRootNode.getAttribute("ZoomLevel")));
     }
     else
    {
        map.setCenter(new GLatLng(parseFloat(docRootNode.getAttribute("CenterLatitude")), parseFloat(docRootNode.getAttribute("CenterLongitude"))), parseInt(docRootNode.getAttribute("ZoomLevel")));
        map2.setCenter(new GLatLng(parseFloat(docRootNode.getAttribute("CenterLatitude")), parseFloat(docRootNode.getAttribute("CenterLongitude"))), parseInt(docRootNode.getAttribute("ZoomLevel")));
    }
}


    
    switch (docRootNode.getAttribute("MapType")) {
        case "Hybrid":
            map.setMapType(G_HYBRID_MAP);
            break;
        case "Normal":
            map.setMapType(G_NORMAL_MAP);
            break;
        case "Physical":
            map.setMapType(G_PHYSICAL_MAP);
            break;
        case "Satellite":
            map.setMapType(G_SATELLITE_MAP);
            break;
    }
        
    if (neighborhoods.length == 0) {
        //document.getElementById("neighborhoods").style.display = "none";
    }
    else {
        //document.getElementById("neighborhoods").style.display = "block";
        neighborhoodsArray = [];
        for (i = 0; i < neighborhoods.length; i++) {
            var thisHood = neighborhoods[i];
            var points = new Array();
            for (p = 0; p < thisHood.getElementsByTagName("Point").length; p++) {
                var thisPoint = thisHood.getElementsByTagName("Point")[p];
                points.push(new GLatLng(parseFloat(thisPoint.getAttribute("Latitude")), parseFloat(thisPoint.getAttribute("Longitude"))));
            }
            var neighborhood = {
                name: thisHood.getAttribute("Name"),
                icon: thisHood.getAttribute("Icon"),
                markerWidth: thisHood.getAttribute("MarkerWidth"),
                markerHeight: thisHood.getAttribute("MarkerHeight"),
                center: new GLatLng(parseFloat(thisHood.getAttribute("CenterLatitude")), parseFloat(thisHood.getAttribute("CenterLongitude"))),
                fillColor: thisHood.getAttribute("FillColor"),
                lineColor: thisHood.getAttribute("LineColor"),
                opacity: thisHood.getAttribute("Opacity"),
                polyPoints: points
            };
            neighborhood.marker = createNeighborhoodMarker(neighborhood);
            neighborhood.polygon = createNeighborhoodPolygon(neighborhood);
            neighborhoodsArray.push(neighborhood);
        }
        drawNeighborhoods();
    }

    for (i = 0; i < merchantTypes.length; i++) {
        var thisType = merchantTypes[i];
        var merchantType = thisType.getAttribute("Name");
        var merchantTypeNoSpaces = xreplace(merchantType, " ", "");
        var merchants = thisType.getElementsByTagName("Merchant");
        var markerImage = thisType.getAttribute("Marker");
        var markerWidth = thisType.getAttribute("MarkerWidth");
        var markerHeight = thisType.getAttribute("MarkerHeight");
        var merchantIcon = thisType.getAttribute("Icon");
        var icon = buildIcon(markerImage, markerWidth, markerHeight);

        var merchantTypeMerchantArray = new Array();

        var merchantTypeObj = {
            name: merchantType,
            nameNoSpaces: merchantTypeNoSpaces,
            markerImage: markerImage,
            markerWidth: markerWidth,
            markerHeight: markerHeight,
            merchantTypeIcon: merchantIcon,
            icon: icon
        };


        // what are we filtering on?
        var filterTypeArray = new Array();
        var filterTypes = thisType.getElementsByTagName("Filter");
        for (f = 0; f < filterTypes.length; f++) {
            var thisType = {
                name: filterTypes[f].getAttribute("Name"),
                displayName: filterTypes[f].getAttribute("DisplayName")
            };
            filterTypeArray.push(thisType);
        }


        //old: 
        //var filterType = thisType.getElementsByTagName("Filter")[0].getAttribute("Name");
        var filterType = filterTypes[0].getAttribute("Name");
        // now, the subdivs for each filter type will come from the merchants themselves
        var filterOpts = new Array();

        for (m = 0; m < merchants.length; m++) {
            var thisMerchant = merchants[m];

            var merchant = {
                name: thisMerchant.getAttribute("Name"),
                address: trim(GXml.value(thisMerchant.getElementsByTagName("Address")[0])),
                description: GXml.value(thisMerchant.getElementsByTagName("Description")[0]),
                shortDescription: thisMerchant.getAttribute("ShortDescription"),
                location: thisMerchant.getAttribute("Location"),
                type: merchantType,
                typeNoSpaces: merchantTypeNoSpaces,
                typeMarker: markerImage,
                typeIcon: merchantIcon,
                photo: thisMerchant.getAttribute("Photo"),
                //filterValues: thisMerchant.getAttribute(filterType).split("|"),
                phone: trim(thisMerchant.getAttribute("Phone")),
                latitude: thisMerchant.getAttribute("Latitude"),
                longitude: thisMerchant.getAttribute("Longitude"),
                point: new GLatLng(parseFloat(thisMerchant.getAttribute("Latitude")), parseFloat(thisMerchant.getAttribute("Longitude"))),
                currentlyDisplayedByFilters: true,
                currentlyDisplayedByLocation: true,
                currentlyDisplayedByMerchantType: true,
                allowDrivingDirections: thisMerchant.getAttribute("AllowDrivingDirections"),
                merchantType: merchantTypeObj,
                Amenities: thisMerchant.getAttribute("Amenities"),
                UnitSize: thisMerchant.getAttribute("UnitSize"),
                SaveUrl: thisMerchant.getAttribute("MerchantSaveUrl"),
                DetailUrl: thisMerchant.getAttribute("MerchantDetailUrl")
            };
            // dynamically create properties for each of our filter types
            for (fil = 0; fil < filterTypeArray.length; fil++) {
                merchant[filterTypeArray[fil].name] = thisMerchant.getAttribute(filterTypeArray[fil].name);
            }

            merchant.infoWindowHtml = createInfoWindow(merchant);
            var markerOptions = { icon: icon };
            var marker = new GMarker(merchant.point, markerOptions);
            //marker.bindInfoWindowHtml(merchant.infoWindowHtml);
            if (merchant.allowDrivingDirections != "false") {
                var tab1 = new GInfoWindowTab("Details", merchant.infoWindowHtml);
                var tab2 = new GInfoWindowTab("Directions", buildDirectionsTab(merchant));
                var arrTabs = new Array();
                arrTabs.push(tab1);
                arrTabs.push(tab2);
                marker.bindInfoWindowTabsHtml(arrTabs);
                merchant.hasTabs = true;
                merchant.infoWindowTabs = arrTabs;
            }
            else {
                marker.bindInfoWindowHtml(merchant.infoWindowHtml);
                merchant.hasTabs = false;
            }
            merchant.marker = marker;
            map.addOverlay(marker);

            merchantArray.push(merchant);
            merchantTypeMerchantArray.push(merchant);
        }

        // add an object to the merchantTypeObj that has all of the filter types and options
        merchantTypeObj.filterTypes = filterTypeArray;
        merchantTypeObj.merchants = merchantTypeMerchantArray;
        if (_isUberMap) {
            //Commented by Naveen:createMerchantTypeTab(merchantTypeObj);
        }
    }
    drawResults();
}



function buildDirectionsTab(merchant) {
    var addr = xreplace(trim(merchant.address), "<br />", ", ");
    addr = xreplace(addr, "<br>", ", ");
    addr = xreplace(addr, "<br/>", ", ");
    
    var retHtml = "";
    //var retHtml = "<form action='#' onsubmit=''>";
    retHtml += "<div class='dirHeader'>Get Directions ";
    retHtml += "<a id='dirTo' href='javascript:setDirectionsTo()'>To</a>";
    retHtml += "<span id='spnDirTo' class='dirSel'>To</span>";
    retHtml += " | ";
    retHtml += "<a id='dirFrom' href='javascript:setDirectionsFrom()'>From</a>";
    retHtml += "<span id='spnDirFrom' class='dirSel'>From</span>";
    retHtml += "&nbsp;&nbsp;" + merchant.name + "</div>";
    retHtml += "<br class='clear' />";
    retHtml += "<div class='dirLabel'>From:</div>";
    retHtml += "<div class='dirInput' id='dirInputFromForm'><input type='text' class='directions' id='fromAddress' name='from' /></div>";
    retHtml += "<div class='dirInput' id='dirInputFromLabel'>" + merchant.name + "</div>";
    retHtml += "<br class='clear'/>";
    retHtml += "<div class='dirLabel'>To:</div>";
    retHtml += "<div class='dirInput' id='dirInputToForm'><input type='text' class='directions' id='toAddress' name='to' /></div>";
    //retHtml += "<div class='dirInput'><input type='text' class='directions' id='toAddress' name='to' value='" + merchant.latitude + ", " + merchant.longitude + "'></div>";
    retHtml += "<div class='dirInput' id='dirInputToLabel'>" + merchant.name + "</div>";
    retHtml += "<br class='clear' />";
    //retHtml += "<input type='submit' value='Get Directions'>";
    retHtml += "<input type='hidden' id='direction' value='To' />";
    //retHtml += "<input type='hidden' id='merchantGeocode' value='" + merchant.latitude + ", " + merchant.longitude + "' />";
    //710 N Summit Blvd # 101, Frisco, CO (Starbucks) @39.576783,-106.092512
    retHtml += "<div id='merchantGeocode' style = 'display:none'>";
    
    if(merchant.address != "")
    {
        retHtml += xreplace(merchant.address, "<br />", ", ");
    }
    
    retHtml += " ("+ merchant.name +") @" + merchant.latitude + "," + merchant.longitude + "</div>";
    retHtml += "<br />";
    // Add button Container | Anuj Rastogi
    retHtml += "<span class='button'><a href='javascript:setDirections()' class='btnPlus'>Get Directions</a></span>";
    return retHtml;
    
}
function setDirectionsTo() {
    document.getElementById("dirTo").style.display = "none";
    document.getElementById("dirFrom").style.display = "inline";
    document.getElementById("spnDirTo").style.display = "inline";
    document.getElementById("spnDirFrom").style.display = "none";
    document.getElementById("direction").value = "To";
    document.getElementById("dirInputFromForm").style.display = "block";
    document.getElementById("dirInputToForm").style.display = "none";
    document.getElementById("dirInputFromLabel").style.display = "none";
    document.getElementById("dirInputToLabel").style.display = "block";
}
function setDirectionsFrom() {
    document.getElementById("dirTo").style.display = "inline";
    document.getElementById("dirFrom").style.display = "none";
    document.getElementById("spnDirTo").style.display = "none";
    document.getElementById("spnDirFrom").style.display = "inline";
    document.getElementById("direction").value = "From";
    document.getElementById("dirInputFromForm").style.display = "none";
    document.getElementById("dirInputToForm").style.display = "block";
    document.getElementById("dirInputFromLabel").style.display = "block";
    document.getElementById("dirInputToLabel").style.display = "none";
}
function drawResults() {
    _displayedMarkerCount = 0;

    var lastType = "";
    var merchantCount = 0;

    for (i = 0; i < merchantArray.length; i++) {
        if (merchantArray[i].currentlyDisplayedByFilters == true &&
			merchantArray[i].currentlyDisplayedByMerchantType == true &&
			merchantArray[i].currentlyDisplayedByLocation == true) {

            if (lastType != merchantArray[i].type) {
                lastType = merchantArray[i].type;
                merchantCount = 0;
            }

            merchantCount++;
            _displayedMarkerCount++;

            var resultDiv = document.createElement("div");
            resultDiv.className = "resultMerchantDetailContainer";

            var resultDetailsDiv = document.createElement("div");
            resultDetailsDiv.className = "resultMerchantDetailCopy";
            
            resultDetailsDiv.style.background = "url('" + merchantArray[i].merchantType.merchantTypeIcon + "')";
            resultDetailsDiv.style.backgroundRepeat = "no-repeat";

            var resultHyperlink = document.createElement("a");
            resultHyperlink.id = "result" + i;
            resultHyperlink.href = "javascript:showMerchantInfo(" + i + ")";
            resultHyperlink.className = "resultMerchantName";
            resultHyperlink.onmouseover = function() { setSelectedIcon(this) };
            resultHyperlink.onmouseout = function() { setNormalIcon(this) };
            var resultNode = document.createTextNode(merchantArray[i].name);
            resultHyperlink.appendChild(resultNode);
            resultDetailsDiv.appendChild(resultHyperlink);

            var sdText = "";
            if (merchantArray[i].type == "Lodging") {
                sdText = buildLodgingFeatureBlurb(merchantArray[i]);
            }
            else if (merchantArray[i].shortDescription != null && merchantArray[i].shortDescription != "") {
                sdText = merchantArray[i].shortDescription;
            }
            if (sdText != "") {
                var shortDescriptionDiv = document.createElement("div");
                shortDescriptionDiv.className = "resultMerchantShortDescription";
                shortDescriptionDiv.innerHTML = sdText;
                resultDetailsDiv.appendChild(shortDescriptionDiv);
            }

            var addressDiv = document.createElement("div");
            addressDiv.className = "resultMerchantAddress";
            addressDiv.innerHTML = merchantArray[i].address;
            if (merchantArray[i].phone != "") {
                if (merchantArray[i].address != "") {
                    addressDiv.innerHTML += "<br />";
                }
                addressDiv.innerHTML += merchantArray[i].phone;
            }
            resultDetailsDiv.appendChild(addressDiv);

            var linksDiv = document.createElement("div");
            linksDiv.className = "resultMerchantLinks";

            // details hyperlink
            var detailsHyperlink = document.createElement("a");
            var detailsText = document.createTextNode("Details");
            detailsHyperlink.appendChild(detailsText);
            detailsHyperlink.href = "javascript:alert('Coming soon')";
            linksDiv.appendChild(detailsHyperlink);

            // view on map hyperlink
            var viewOnMapHyperlink = document.createElement("a");
            var viewOnMapText = document.createTextNode("View on Map");
            viewOnMapHyperlink.appendChild(viewOnMapText);
            viewOnMapHyperlink.href = "javascript:showMerchantInfo(" + i + ")";
            viewOnMapHyperlink.className = "second";
            linksDiv.appendChild(viewOnMapHyperlink);

            resultDetailsDiv.appendChild(linksDiv);

            resultDiv.appendChild(resultDetailsDiv);
        }
    }
    document.getElementById("pleaseWaitMapOverlay").style.display = "none";
    var typesToKeep = new Array();
    for (arl = 0; arl < openMerchantTypes.length; arl++) {
        if (document.getElementById("resultImg_" + openMerchantTypes[arl])) {
            showHideTypeResults(document.getElementById("resultImg_" + openMerchantTypes[arl]), false);
            typesToKeep.push(openMerchantTypes[arl]);
        }
    }
    openMerchantTypes.length = 0;
    for (omt = 0; omt < typesToKeep.length; omt++) {
        openMerchantTypes.push(typesToKeep[omt]);
    }

    // if not an ubermap, then zoom/center the map
    if (_isUberMap == false) {
        showAll();
    }
}

function setupLocations() {
    var locationArray = new Array();

    for (i = 0; i < merchantArray.length; i++) {
        if (merchantArray[i].location != null && trim(merchantArray[i].location) != "") {
            var found = false;
            for (x = 0; x < locationArray.length; x++) {
                if (locationArray[x] == merchantArray[i].location) {
                    found = true;
                }
            }
            if (found == false) {
                locationArray.push(merchantArray[i].location);
            }
        }
    }
    locationArray.sort();
    var locationsOnLeftCount = Math.ceil(locationArray.length / 2);
    var locationsOnRightCount = locationArray.length - locationsOnLeftCount;

    for (i = 0; i < locationArray.length; i++) {
        var parentDiv;
        if (i < locationsOnLeftCount) {
            parentDiv = document.getElementById("neighborhoodListLeft");
        }
        else {
            parentDiv = document.getElementById("neighborhoodListRight");
        }
        var cb = document.createElement("input");
        cb.type = "checkbox";
        cb.value = locationArray[i];
        cb.onclick = function() { filterByLocation(this.value, this.checked, true); };
        parentDiv.appendChild(cb);
        cb.checked = true;
        // label
        var cbLabel = document.createTextNode(" " + locationArray[i]);
        parentDiv.appendChild(cbLabel);
        var br = document.createElement("br");
        parentDiv.appendChild(br);
    }
}
function checkAllLocations(b) {
    document.getElementById("pleaseWaitResults").style.display = "block";
    document.getElementById("pleaseWaitMapOverlay").style.display = "block";
    for (c = 0; c < document.getElementById("neighborhoodListContainer").getElementsByTagName("input").length; c++) {
        if (document.getElementById("neighborhoodListContainer").getElementsByTagName("input")[c].id != "cbNeighborhoods") {
            document.getElementById("neighborhoodListContainer").getElementsByTagName("input")[c].checked = b;
            filterByLocation(document.getElementById("neighborhoodListContainer").getElementsByTagName("input")[c].value, b, false);
        }
    }
    // finally, redraw the results
    drawResults();
}
function createMerchantTypeTab(merchantType) {

    // get the unordered list container
    var tabsUL = document.getElementById("vailTabsList");
    // create the new <li> tag
    var merchantTypeLI = document.createElement("li");
    // set the id
    merchantTypeLI.id = "li_" + merchantType.nameNoSpaces;
    // create the hyperlink
    var merchantTypeHyperlink = document.createElement("a");
    // these have to be of class name "tab" to style appropriately
    merchantTypeHyperlink.className = "tab";
    // add the icon
    var merchantTypeIcon = document.createElement("img");
    merchantTypeIcon.src = merchantType.merchantTypeIcon;
    merchantTypeIcon.align = "absmiddle";
    merchantTypeHyperlink.appendChild(merchantTypeIcon);
    // set the text
    var merchantTypeText = document.createTextNode(" " + merchantType.name);
    merchantTypeHyperlink.appendChild(merchantTypeText);
    // mouseover functionality
    merchantTypeHyperlink.onmouseover = function() { enableFilterTab(merchantType.nameNoSpaces); };
    merchantTypeHyperlink.onmouseout = function() { startTimer(); };
    // append the hyperlink to the <li>
    merchantTypeLI.appendChild(merchantTypeHyperlink);
    // create a <br> to clear things
    var br = document.createElement("br");
    br.className = "clear";
    merchantTypeLI.appendChild(br);
    // create the filter container div
    var filterContainerDiv = document.createElement("div");
    filterContainerDiv.className = "filterContainer";
    filterContainerDiv.id = "filter_" + merchantType.nameNoSpaces;

    // our filter container wrapper div that handles spacing
    var filterContainerContentsDiv = document.createElement("div");
    filterContainerContentsDiv.className = "filterContainerContents";
    // build the title div on the filter container
    var filterMerchantTypeNameDiv = document.createElement("div");
    filterMerchantTypeNameDiv.className = "filterMerchantTypeName";
    var filterMerchantTypeNameDivText = document.createTextNode(merchantType.name + " Filters");
    filterMerchantTypeNameDiv.appendChild(filterMerchantTypeNameDivText);
    // add the name to the container contents div
    filterContainerContentsDiv.appendChild(filterMerchantTypeNameDiv);

    // the "show on map" section
    var showHideDiv = document.createElement("div");
    showHideDiv.className = "filterMerchantTypeShowHide";
    var cbShowHide = document.createElement("input");
    cbShowHide.type = "checkbox";
    cbShowHide.value = merchantType.name;
    cbShowHide.onclick = function() { showHideMerchantType(merchantType.name, this.checked); };
    showHideDiv.appendChild(cbShowHide);
    cbShowHide.checked = true; // have to check it after appending it in IE
    // the text
    var showHideText = document.createTextNode("Show on Map");
    showHideDiv.appendChild(showHideText);
    // append the show/hide checkbox and crap to the container
    filterContainerContentsDiv.appendChild(showHideDiv);

    // build a wrapper div to hold the filter groups
    var filterGroupWrapper = document.createElement("div");
    filterGroupWrapper.id = merchantType.nameNoSpaces + "_filterGroupWrapper";

    // add the filter value sections 
    var theLength = merchantType.filterTypes.length;
    for (x = 0; x < theLength; x++) {
        var thisFilterName = merchantType.filterTypes[x].name;
        var filterOptionsArray = new Array();
        // the container
        var filterGroupContainer = document.createElement("div");
        filterGroupContainer.className = "filterMerchantTypeFilterGroup";
        // display name
        var filterNameDiv = document.createElement("div");
        filterNameDiv.className = "filterMerchantTypeFilterGroupName";
        var filterNameText = document.createTextNode(merchantType.filterTypes[x].displayName);
        filterNameDiv.appendChild(filterNameText);
        // add the name div to the container
        filterGroupContainer.appendChild(filterNameDiv);
        // select all div
        var selectAllDiv = document.createElement("div");
        selectAllDiv.className = "filterMerchantTypeFilterGroupSelectAll";
        var selectAllHyperlink = document.createElement("a");
        selectAllHyperlink.href = "javascript:selectAllFilterValues('filterValues_" + merchantType.nameNoSpaces + "_" + merchantType.filterTypes[x].name + "')";
        var selectAllText = document.createTextNode("Select All");
        selectAllHyperlink.appendChild(selectAllText);
        selectAllDiv.appendChild(selectAllHyperlink);
        // append select all div to container
        filterGroupContainer.appendChild(selectAllDiv);

        // add a br to clear it
        var br = document.createElement("br");
        br.className = "clear";
        filterGroupContainer.appendChild(br);

        var merchantCount = merchantType.merchants.length;
        for (m = 0; m < merchantCount; m++) { // looping each merchant in this type
            // each merchant has a value for each filter, but it may be pipe-delimited
            // like "CuisineType='American|Steaks'"
            // so we need to loop over the filter values, and see if each one
            // is already in our array.  if not, add it
            var filterOpts = merchantType.merchants[m][thisFilterName].split("|");
            for (fo = 0; fo < filterOpts.length; fo++) {
                var found = false;
                for (a = 0; a < filterOptionsArray.length; a++) {
                    if (filterOptionsArray[a] == filterOpts[fo]) {
                        found = true;
                        break;
                    }
                }
                if (found == false) {
                    filterOptionsArray.push(filterOpts[fo]);
                }
            }
        }
        filterOptionsArray.sort();

        // now we loop over each of the filter options and append those
        var filterOptionsContainerDiv = document.createElement("div");
        filterOptionsContainerDiv.id = "filterValues_" + merchantType.nameNoSpaces + "_" + merchantType.filterTypes[x].name;

        for (foa = 0; foa < filterOptionsArray.length; foa++) {
            var cbDiv = document.createElement("div");
            cbDiv.className = "filterValueCheckbox";
            var cb = document.createElement("input");
            cb.type = "checkbox";
            cb.id = merchantType.nameNoSpaces + "|" + merchantType.filterTypes[x].name + "|" + filterOptionsArray[foa];
            cb.value = filterOptionsArray[foa];
            //cb.onclick = function() { showHideMerchantsByFilter(this.value, this.checked); };
            cb.onclick = function() { showHideMerchantsByFilter(this, true); };
            cbDiv.appendChild(cb);
            cb.checked = true;
            filterOptionsContainerDiv.appendChild(cbDiv);

            // the checkbox label
            var cbLabelDiv = document.createElement("div");
            cbLabelDiv.className = "filterValueName";

            if (merchantType.filterTypes[x].name == "Rating") {
                for (rx = 0; rx < parseInt(filterOptionsArray[foa]); rx++) {
                    var star = document.createElement("img");
                    star.src = "star.png";
                    cbLabelDiv.appendChild(star);
                }
            }
            else {
                var cbLabel = document.createTextNode(filterOptionsArray[foa]);
                cbLabelDiv.appendChild(cbLabel);
            }
            filterOptionsContainerDiv.appendChild(cbLabelDiv);
            // and finally, a br to clear
            var br = document.createElement("br");
            br.className = "clear";
            filterOptionsContainerDiv.appendChild(br);
        }

        filterGroupContainer.appendChild(filterOptionsContainerDiv);

        // append the filter group container
        filterGroupWrapper.appendChild(filterGroupContainer);
        //filterContainerContentsDiv.appendChild(filterGroupContainer);
    }

    filterContainerContentsDiv.appendChild(filterGroupWrapper);

    // add the container contents div to the container
    filterContainerDiv.appendChild(filterContainerContentsDiv);

    // finally, append all of this crap to the <li>
    merchantTypeLI.appendChild(filterContainerDiv);

    // append the <li> to the <ul>
    tabsUL.appendChild(merchantTypeLI);
}

function showHideTypeResults(img, alterArray) {
    // TODO: make this a real accordion instead of this
    // TODO: don't hardcode the image paths.
    var merchantType = xreplace(img.id, "resultImg_", "");
    var typeResultList = document.getElementById("resultList_" + merchantType);
    if (typeResultList.style.display == "block") {
        typeResultList.style.display = "none";
        img.src = "resultMerchantTypePlus.gif";

        if (alterArray) {
            for (al = 0; al < openMerchantTypes.length; al++) {
                if (openMerchantTypes[al] == merchantType) {
                    openMerchantTypes.splice(al, 1);
                    break;
                }
            }
        }
    }
    else {
        typeResultList.style.display = "block";
        img.src = "resultMerchantTypeMinus.gif";
        if (alterArray) {
            openMerchantTypes.push(merchantType);
        }
    }

}
function selectAllFilterValues(containerDiv) {
    document.getElementById("pleaseWaitResults").style.display = "block";
    document.getElementById("pleaseWaitMapOverlay").style.display = "block";
    var checkedBoxes = 0;
    var doCheck = true;
    var cbCount = document.getElementById(containerDiv).getElementsByTagName("input").length;
    for (i = 0; i < cbCount; i++) {
        if (document.getElementById(containerDiv).getElementsByTagName("input")[i].checked == true) {
            checkedBoxes++;
        }
    }
    if (checkedBoxes == cbCount) {
        // they're all checked, so uncheck them all
        doCheck = false;
    }
    // actually do it
    for (safv = 0; safv < cbCount; safv++) {
        var thisCb = document.getElementById(containerDiv).getElementsByTagName("input")[safv];
        if (thisCb.checked != doCheck) {
            // no need to re-check and re-filter if it's already in the state it needs to be in
            thisCb.checked = doCheck;
            showHideMerchantsByFilter(thisCb, false);
        }
    }
    // finally, redraw the results
    drawResults();
}
function setSelectedIcon(hyperlink) {
    var x = xreplace(hyperlink.id, "result", "");
    
    merchantArray[x].marker.setImage("marker_selected.png");
}
function setNormalIcon(hyperlink) {
    var x = xreplace(hyperlink.id, "result", "");
    
    merchantArray[x].marker.setImage(merchantArray[x].typeMarker);
}
function showMerchantInfo(x) {
    try
    {
        if (merchantArray[x].hasTabs == true) {
            merchantArray[x].marker.openInfoWindowTabsHtml(merchantArray[x].infoWindowTabs);
            
        }
        else {
            merchantArray[x].marker.openInfoWindowHtml(merchantArray[x].infoWindowHtml);
        }
    }
    catch (e)
    {
       
    }
}
function showHideMerchantsByFilter(cb, doRedraw) {
    document.getElementById("pleaseWaitResults").style.display = "block";
    document.getElementById("pleaseWaitMapOverlay").style.display = "block";
    // the id of this checkbox will be in the following format:
    // Dining|CuisineType|Italian
    // so split it to get the merchant type, filter group, and filter value
    var merchantType = cb.id.split("|")[0];
    var filterGroup = cb.id.split("|")[1];
    var filterValue = cb.id.split("|")[2];
    var show = cb.checked;

    for (i = 0; i < merchantArray.length; i++) {
        var thisMerchant = merchantArray[i];
        if (thisMerchant.typeNoSpaces == merchantType) {
            //var selectedFilters = 0;

            // we want to keep a merchant on the map if it has at least one value checked
            // for any given filter group.  So, for example, for dining, in the price category
            // as soon as its $ sign is un-checked, remove that marker since it no longer matches
            // any values in the price category/type.  
            var selectedFilterTypes = 0;

            // we know what type of merchant this is, and we know what filter types this merchan type has
            // so, loop over each of those and see how many filters we have checked.			
            var filterTypeCount = thisMerchant.merchantType.filterTypes.length;
            for (ft = 0; ft < filterTypeCount; ft++) {
                var selectedFilters = 0;
                //alert(thisMerchant.merchantType.filterTypes[ft].name);
                // we know that each filter value collection is stored in a div that is named like this:
                // filterValues_Services_Type
                // so get those divs, loop over the cb's, and see if we have matches
                var thisFilterType = thisMerchant.merchantType.filterTypes[ft].name;
                var filterGroupDiv = document.getElementById("filterValues_" + merchantType + "_" + thisFilterType);
                for (c = 0; c < filterGroupDiv.getElementsByTagName("input").length; c++) {
                    var thisCheckbox = filterGroupDiv.getElementsByTagName("input")[c];
                    if (thisCheckbox.type == "checkbox") {
                        // we have a checkbox.  get its value if it's checked to compare to our merchant
                        if (thisCheckbox.checked == true) {
                            // it's checked, so we need to loop over our merchant's values
                            // for this filter type and see if we have a match
                            // remembering that the value of this filter type could contain multiple values, pipe-delimited
                            // e.g. "American|Italian"
                            for (fv = 0; fv < thisMerchant[thisFilterType].split("|").length; fv++) {
                                var thisFV = thisMerchant[thisFilterType].split("|")[fv];
                                if (thisFV == thisCheckbox.value) {
                                    selectedFilters++;
                                    break;
                                }
                            }
                        }
                    }
                }
                // here is we now can look and see if this merchant matched any values in this type
                if (selectedFilters > 0) {
                    selectedFilterTypes++
                }
            }

            if (selectedFilterTypes == filterTypeCount) {
                if (thisMerchant.currentlyDisplayedByLocation == true &&
					thisMerchant.currentlyDisplayedByMerchantType == true &&
					thisMerchant.currentlyDisplayedByFilters == false) {
                    map.addOverlay(thisMerchant.marker);
                }
                thisMerchant.currentlyDisplayedByFilters = true;
            }
            else {
                map.removeOverlay(thisMerchant.marker);
                thisMerchant.currentlyDisplayedByFilters = false;
            }
        }
    }
    if (doRedraw) {
        drawResults();
    }
}

function filterByLocation(location, show, doRedraw) {
    document.getElementById("pleaseWaitResults").style.display = "block";
    document.getElementById("pleaseWaitMapOverlay").style.display = "block";
    for (i = 0; i < merchantArray.length; i++) {
        var thisMerchant = merchantArray[i];
        if (thisMerchant.location == location) {
            if (show) {
                if (thisMerchant.currentlyDisplayedByMerchantType == true &&
					thisMerchant.currentlyDisplayedByFilters == true &&
					thisMerchant.currentlyDisplayedByLocation == false) {
                    map.addOverlay(thisMerchant.marker);
                }
                thisMerchant.currentlyDisplayedByLocation = true;
            }
            else {
                map.removeOverlay(thisMerchant.marker);
                thisMerchant.currentlyDisplayedByLocation = false;
            }
        }
    }
    if (doRedraw) {
        drawResults();
    }
}
function showHideMerchantType(type, show) {
    document.getElementById("pleaseWaitResults").style.display = "block";
    document.getElementById("pleaseWaitMapOverlay").style.display = "block";
    var filterGroupWrapper = document.getElementById(xreplace(type, " ", "") + "_filterGroupWrapper");
    
    for (i = 0; i < merchantArray.length; i++) {
        var thisMerchant = merchantArray[i];
        if (thisMerchant.type == type) {
            if (show) {
                if (thisMerchant.currentlyDisplayedByLocation == true &&
					thisMerchant.currentlyDisplayedByFilters == true &&
					thisMerchant.currentlyDisplayedByMerchantType == false) {
                    map.addOverlay(thisMerchant.marker);
                }
                thisMerchant.currentlyDisplayedByMerchantType = true;
            }
            else {
                map.removeOverlay(thisMerchant.marker);
                thisMerchant.currentlyDisplayedByMerchantType = false;
            }
        }
    }
    if (show) {
        filterGroupWrapper.style.display = "block";
    }
    else {
        filterGroupWrapper.style.display = "none";
    }
    drawResults();
}
function buildIcon(markerImage, width, height) {
    icon = new GIcon();
    icon.shadow = "marker_shadow.png";
    icon.iconSize = new GSize(width, height);
    //var shadowWidth = parseInt(1.25 * parseInt(width));
    var shadowWidth = 38;
    icon.shadowSize = new GSize(shadowWidth, height);
    //var anchorCenter = parseInt(parseInt(width) / 2);
    var anchorCenter = 19;
    icon.iconAnchor = new GPoint(anchorCenter, height);
    icon.infoWindowAnchor = new GPoint(anchorCenter, 2);
    icon.infoShadowAnchor = new GPoint(width, 8);
    icon.image = markerImage;
    return icon;
}
function drawNeighborhoods() {
    for (i = 0; i < neighborhoodsArray.length; i++) {
        map.addOverlay(neighborhoodsArray[i].marker);
        map.addOverlay(neighborhoodsArray[i].polygon);
    }
}
function createNeighborhoodMarker(hood) {
    var hood_icon = new GIcon();
    hood_icon.image = hood.icon;
    hood_icon.iconSize = new GSize(hood.markerWidth, hood.markerHeight);
    hood_icon.iconAnchor = new GPoint(parseInt(parseInt(hood.markerWidth) / 2), parseInt(parseInt(hood.markerHeight) / 2));
    var markerOpts = { zIndexProcess: zindex, clickable: false };
    markerOpts.icon = hood_icon;
    var hood_marker = new GMarker(hood.center, markerOpts);
    return hood_marker;
}
function zindex() {
    return 1000;
}
function createNeighborhoodPolygon(hood) {
    var polygon = new GPolygon(hood.polyPoints, hood.lineColor, 1, 1, hood.fillColor, hood.opacity);
    return polygon;
}
function createInfoWindow(merchant) {
    var hasPhoto = (merchant.photo && trim(merchant.photo) != "") ? true : false;
    var detailsHTML = "<div class='popup clearfix'>";
    detailsHTML += "<div class='popupMerchantName'>" + merchant.name + "</div>";
    detailsHTML += (hasPhoto == true) ? "<div class='popupMerchantDetails'>" : "<div class='popupMerchantDetailsNoPhoto'>";
    if (trim(merchant.description) != "") {
        merchant.description = merchant.description.replace(/<\!\[CDATA\[/, '');
        merchant.description = merchant.description.replace(/\]\]>/,'');
        detailsHTML += "<div class='popupMerchantDescription'>" + merchant.description + "</div>";
    }

    if (merchant.type == "Lodging") {
        detailsHTML += "<div class='popupMerchantLodgingType'>";
        detailsHTML += buildLodgingFeatureBlurb(merchant);
        detailsHTML += "</div>";
    }
    if (merchant.address != "") {
        merchant.address = merchant.address.replace(/<\!\[CDATA\[/, '');
        merchant.address = merchant.address.replace(/\]\]>/, '');
        detailsHTML += merchant.address + "<br />";
    }
    
    if (merchant.phone == '0000000000')
        merchant.phone = '';
        
    detailsHTML += merchant.phone;
    detailsHTML += "</div>"; // end popupMerchantDetails
    if (hasPhoto) {
        detailsHTML += "<div class='popupMerchantPhoto'><img src='" + merchant.photo + "'></div>";
    }
    detailsHTML += "<br class='clear' /><div class='popupMerchantButtonTabs'>";
    
    if (merchant.SaveUrl == null) {
        merchant.SaveUrl = '#';
    }
    else {
        detailsHTML += "<div class='popupMerchantSaveToTripFolder'><a class='saveLink uberMapSaveModalLink' onclick='bindModalEvent(\"" + merchant.SaveUrl + "\");' href='javascript: void(0);'>Save</a></div>";
    }
    // TODO: implement trip folder integration
    if (merchant.DetailUrl != 'NA') {
        detailsHTML += "<div class='popupMerchantLearnMore'><a href='" + merchant.DetailUrl + "'><img src='/VailResorts/sites/PlanningAndBooking/assets/img/btnLearnMore.gif'></a></div>";
    }
    detailsHTML += "</div></div>";
    return detailsHTML;
}
function buildLodgingFeatureBlurb(merchant) {
    var lodgingRet = "";
    for (rate = 0; rate < parseInt(merchant.Rating); rate++) {
        lodgingRet += "<img src='/VailResorts/sites/PlanningAndBooking/assets/img/star.png'>";
    }
    lodgingRet += "<br />" + xreplace(merchant.type, "|", ", ") + " - ";
    
    lodgingRet += xreplace(merchant.UnitSize, "|", ", ");
    
    lodgingRet += "<br /><br/>";
    var am = merchant.Amenities;
    var str = [];
    str = am.split('|');
    for (var i = 0; i < str.length; i++) {
        if (str[i].toLowerCase().indexOf('hot tub') > -1) {
            lodgingRet += "<img src='/VailResorts/sites/PlanningAndBooking/assets/img/hottub.gif' alt='Hot Tub' class='floatLeft'>";
        }
        if (str[i].toLowerCase().indexOf('close to slopes') > -1) {
            lodgingRet += "<img src='/VailResorts/sites/PlanningAndBooking/assets/img/slopes.gif' alt='Close to Slopes' class='floatLeft' >";
        }
        if (str[i].toLowerCase().indexOf('pool') > -1) {
            lodgingRet += "<img src='/VailResorts/sites/PlanningAndBooking/assets/img/pool.gif' alt='Pool' class='floatLeft' >";
        }
        if (str[i].toLowerCase().indexOf('on-shuttle route') > -1) {
            lodgingRet += "<img src='/VailResorts/sites/PlanningAndBooking/assets/img/shuttle.gif' alt='On Shuttle Route' class='floatLeft' >";
        }
    }
    lodgingRet += "<br/>";
    return lodgingRet;
}
function showHideHoods() {
    var doShow = document.getElementById("cbNeighborhoods").checked;
    if (document.getElementById("cbNeighborhoods").checked == true) {
        for (i = 0; i < neighborhoodsArray.length; i++) {
            map.addOverlay(neighborhoodsArray[i].marker);
            map.addOverlay(neighborhoodsArray[i].polygon);
        }
    }
    else {
        for (i = 0; i < neighborhoodsArray.length; i++) {
            map.removeOverlay(neighborhoodsArray[i].marker);
            map.removeOverlay(neighborhoodsArray[i].polygon);
        }
    }
}
function xreplace(checkMe, toberep, repwith) {
    var temp = checkMe;
    var i = temp.indexOf(toberep);
    while (i > -1) {
        temp = temp.replace(toberep, repwith);
        i = temp.indexOf(toberep, i + repwith.length + 1);
    }
    return temp;
}
function trim(str) {
    if (str != "") {
        return str.replace(/^\s*|\s*$/g, "");
    }
    else {
        return "";
    }
}
function showAll() {
    bounds = new GLatLngBounds();
    for (i = 0; i < merchantArray.length; i++) {
        if (merchantArray[i].currentlyDisplayedByLocation == true &&
			merchantArray[i].currentlyDisplayedByMerchantType == true &&
			merchantArray[i].currentlyDisplayedByFilters == true) {
            bounds.extend(merchantArray[i].point);
        }
    }
    map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
}

var filterTimer = null;
function setupFilterTabs() {
    for (i = 0; i < document.getElementById("vailTabsList").getElementsByTagName("li").length; i++) {
        var filterDiv = document.getElementById("vailTabsList").getElementsByTagName("li")[i].getElementsByTagName("div")[0];
        filterDiv.onmouseover = function() {
            cancelTimer();
        }
        filterDiv.onmouseout = function() {
            startTimer();
        }
    }
    document.getElementById("filterInstructions").style.display = "block";
}
function enableFilterTab(merchantType) {
    clearTimeout(filterTimer);
    turnOffAllFilterTabs();
    document.getElementById("li_" + merchantType).className = "on";
    var filterDiv = document.getElementById("filter_" + merchantType);
    filterDiv.style.display = "block";
    filterDiv.style.visibility = "visible";
}
function turnOffAllFilterTabs() {
    // todo: move this into an iteration over an array of known filters
    for (i = 0; i < document.getElementById("vailTabsList").getElementsByTagName("li").length; i++) {
        document.getElementById("vailTabsList").getElementsByTagName("li")[i].className = "";
        var filterDiv = document.getElementById("vailTabsList").getElementsByTagName("li")[i].getElementsByTagName("div")[0];
        filterDiv.style.display = "none";
        filterDiv.style.visibility = "hidden";
    }
}
function cancelTimer() {
    clearTimeout(filterTimer);
}
function startTimer() {
    filterTimer = setTimeout(turnOffAllFilterTabs, 500);
}
function handle_Ubermap3_Errors() {
    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() {
    document.getElementById("directionsOverlay").style.visibility = "visible";
}
function setDirections() {
    var from;
    var to;
    if (document.getElementById("direction").value == "To") {
       // to = document.getElementById("#merchantGeocode").value;
        to = $("#merchantGeocode").html();
        from = document.getElementById("fromAddress").value;
    }
    else {
    //from = document.getElementById("merchantGeocode").value;
        from = $("#merchantGeocode").html();
        to = document.getElementById("toAddress").value;
    }
    //gdir.load("from: " + document.getElementById("fromAddress").value + " to: " + document.getElementById("toAddress").value, { "locale": "en_US" });
    gdir.load("from: " + from + " to: " + to, { "locale": "en_US" });
}
function addImg(url, id) {
    var img = document.createElement("img");
    img.src = url;
    document.getElementById(id).innerHTML = "";
    document.getElementById(id).appendChild(img);
}
function closeDirections() {
    document.getElementById("directionsOverlay").style.visibility = "hidden";
}
function bindModalEvent(url){
	//stopEvent(event);
	
	if ( $("div.ubermapSaveToTripDialog").length == 0 ){
	    $("<div class='ubermapSaveToTripDialog'></div>")
	        .append("<iframe src='' width='950px' height='800px' frameborder='0' marginheight='0' marginwidth='0'></iframe>")
	        .appendTo("body");
	}

    if ( $('.ubermapSaveToTripDialog').length > 0 && $('body > .ui-dialog .ubermapSaveToTripDialog').length == 0 ){
	    $('.ubermapSaveToTripDialog').eq(0).dialog({
		    bgiframe: true,
		    autoOpen: false,
		    width: 950,
		    height: 690,
		    modal: true,
		    resizable: false,
		    position: 'center',
		    zIndex: 9999,
		    closeOnEscape: true,
		    draggable:false    
	    });
    }
    var objDialog = $(' .ui-dialog .ubermapSaveToTripDialog');
    
	//var urlContent = $(" .uberMapSaveModalLink").attr('href');
			
	$('iframe', objDialog)
		.attr('src',url)
		.attr('width','100%')
		.attr('height','100%')
		.attr('scrolling','no');
	try {
		objDialog.dialog('open');
	} catch (e){}

	return false;


}
