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 imgPath = '/VailResorts/sites/keystone/assets/img/';
var timeDelay = 0;
window.filterTabsCreated = false;
var lodgingMerchantInQueryString=false;

function loadMap(_xmlPath) {

    if ($.browser.msie6 == true && _xmlPath.indexOf('merchantType') > -1 ) {
  
        timeDelay = 7000;
    }
    else if (jQuery.browser.msie && _xmlPath.indexOf('merchantType') && (jQuery.browser.version >= 7)) {
        timeDelay = 3000;
    }
    else {
        timeDelay = 100;
        
    }
   
        //timeDelay = 7000;
    setTimeout(function() {
        if (GBrowserIsCompatible()) {
        
            var mapGMap = document.getElementById("map");
            if (mapGMap) {
                map = new GMap2(mapGMap);
                // bind a search control to the map, suppress result list
                //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", handleErrors);
                GEvent.addListener(gdir, "addoverlay", onGDirectionsLoad);
                selectedIcon = new GIcon();
                selectedIcon.shadow = imgPath + "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 = imgPath + "marker_selected.png";

                GDownloadUrl(_xmlPath, buildMarkers);
            }
        }
    }, timeDelay);
}


function buildMarkers(data, responseCode) {
    merchantArray = new Array();
    
    var xml = GXml.parse(data);

    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");
    if (_isUberMap) {
        var neighborhoods = xml.documentElement.getElementsByTagName("Neighborhood");
        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 (_isUberMap) {
        // the map icon in the location filter section
        document.getElementById("mapThumbnailImg").src = docRootNode.getAttribute("MapImage");
        // map instructions
        document.getElementById("mapInstructions").innerHTML = GXml.value(docRootNode.getElementsByTagName("MapInstructions")[0]);


        if (neighborhoods.length == 0) {
            document.getElementById("neighborhoods").style.display = "none";
        }
        else {
            document.getElementById("neighborhoods").style.display = "block";
            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")+"?x=.png",
                    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();
        }
    }
    else {
        // nothing, because the neighborhood section is hidden here
    }

    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")+"?x=.png";
        var markerWidth = thisType.getAttribute("MarkerWidth");
        var markerHeight = thisType.getAttribute("MarkerHeight");
        var merchantIcon = thisType.getAttribute("Icon")+"?x=.png";
        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];
            
            if (thisMerchant.getAttribute("Latitude") != "0" && thisMerchant.getAttribute("Longitude") != "0") {
            
				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"),
					merchantDetailUrl: thisMerchant.getAttribute("MerchantDetailUrl"),
					merchantSaveUrl: thisMerchant.getAttribute("MerchantSaveUrl"),
					merchantBookUrl: thisMerchant.getAttribute("MerchantBookUrl"),               
					website: thisMerchant.getAttribute("WebSiteUrl"),
					hours: thisMerchant.getAttribute("Hours"),
					reservationLink: thisMerchant.getAttribute("ReservationLink"),
					reservationLinkInternal: thisMerchant.getAttribute("IsReservationLinkInternal"),
					featuredMerchant: thisMerchant.getAttribute("IsFeaturedMerchant"),
					price: thisMerchant.getAttribute("Expense"),
					systemName: thisMerchant.getAttribute("SystemName"),
					ratingImageUrl : thisMerchant.getAttribute("RatingImageUrl"),
					myTripFolderGUID: thisMerchant.getAttribute("MyTripFolderGUID"),
					Id: thisMerchant.getAttribute("ProductId")
				};

				// 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) {
            createMerchantTypeTab(merchantTypeObj);
        }
    }
	
	window.filterTabsCreated = true;

    if (_isUberMap) {
        setupFilterTabs();
        setupLocations();
    }
    drawResults();

	if ( lodgingMerchantInQueryString || !window.lodgingDataAvailable ){
		setupSlider();
	}

	if(window.filterState.location.length > 0)
	{
	selectLocations();
	}
	
	if(window.filterState.showmerchantfilter.length > 0)
	{
	selectFilters();
}
}

function selectLocations(){
	$("#neighborhoodListLeft input:checkbox, #neighborhoodListRight input:checkbox").each(function(){
//	debugger;
	var found = false;
	for ( var x = 0; x < window.filterState.location.length; x++ ){
		if ( window.filterState.location[x] ==  $(this).val().toLowerCase() ){
		    found = true;
		    break;
		}
	}
		if ( found ){
			$(this).attr("checked", true);
			filterByLocation(this.value, true, true);
			//$(this).trigger("click");
		} else {
			$(this).attr("checked", false);
			filterByLocation(this.value, false, true);
		}
	});
}

function selectFilters(){
	$("#vailTabsList .filterMerchantTypeShowHide input:checkbox").each(function(){
	
	var found = false;
	for ( var x = 0; x < window.filterState.showmerchantfilter.length; x++ ){
		if ( window.filterState.showmerchantfilter[x].toLowerCase() == $(this).val().toLowerCase() ){
		    found = true;
		    break;
		}
	}
			if ( !found ){
			$(this).attr("checked", false);
			showHideMerchantType(this, $(this).val(), false);
			//$(this).trigger("click");
		} else {
		        //debugger;
		
			$(this).attr("checked", true);
			showHideMerchantType(this, $(this).val(), true);
		}
	});
}
function buildDirectionsTab(merchant) {
    var addr = xreplace(trim(merchant.address), "<br />", ", ");
    addr = xreplace(addr, "<br>", ", ");
    addr = xreplace(addr, "<br/>", ", ");

    var retHtml = "";

    if (merchant.merchantDetailUrl != null)
        var merchantDetailUrl = merchant.merchantDetailUrl;
    var currentUrl = (location.pathname + location.search).split('#')[0];
    if ((merchant.merchantDetailUrl != null) && (merchant.merchantDetailUrl != currentUrl)) {
        retHtml += "<div class='popupMerchantName'><a href='" + merchant.merchantDetailUrl + "'>" + merchant.name + "</a></div>";
    }
    else {
        retHtml += "<div class='popupMerchantName'><a href='#'>" + merchant.name + "</a></div>";
    }

    //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' autocomplete='off' class='directions' id='fromAddress' name='from' value='' onkeypress='doDirectionSearchKeyPress(event);'/></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' autocomplete='off' class='directions' id='toAddress' name='to' value='' onkeypress='doDirectionSearchKeyPress(event);'/></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 += "<input type='hidden' id='merchantGeocode' value='";
    
    if (merchant.address != "") {
          
        retHtml += xreplace(merchant.address, "<br />", ", ");
    }
    retHtml += " (" + merchant.name + ") @" + merchant.latitude + "," + merchant.longitude + "' />";
    retHtml += "<br />";
    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;
    if (document.getElementById("resultsContainerContents").hasChildNodes()) {
        while (document.getElementById("resultsContainerContents").childNodes.length >= 1) {
            document.getElementById("resultsContainerContents").removeChild(document.getElementById("resultsContainerContents").firstChild);
        }
    }
    var lastType = "";
    var merchantTypeResultContainer = document.createElement("div");
    merchantTypeResultContainer.className = "resultMerchantTypeContainer";
    var merchantTypeResultListContainer = document.createElement("div");
    merchantTypeResultListContainer.className = "merchantTypeResultListContainer";
    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;

                if (merchantTypeResultContainer.getElementsByTagName("div").length > 0) {
                    typeNameDiv.innerHTML += " (" + merchantCount + ")";
                    merchantTypeResultContainer.appendChild(merchantTypeResultListContainer);
                    document.getElementById("resultsContainerContents").appendChild(merchantTypeResultContainer);
                    merchantTypeResultContainer = document.createElement("div");
                    merchantTypeResultContainer.className = "resultMerchantTypeContainer";

                    merchantTypeResultListContainer = document.createElement("div");
                    merchantTypeResultListContainer.className = "merchantTypeResultListContainer";
                }

                merchantTypeResultListContainer.id = "resultList_" + merchantArray[i].typeNoSpaces;

                var typeNameContainer = document.createElement("div");
                typeNameContainer.className = "resultMerchantTypeNameContainer";

                var typeNameDiv = document.createElement("div");
                typeNameDiv.className = "resultMerchantTypeName";
                var typeName = document.createTextNode(lastType);
                typeNameDiv.appendChild(typeName);
                typeNameContainer.appendChild(typeNameDiv);

                var typeCollapseExpandDiv = document.createElement("div");
                typeCollapseExpandDiv.className = "resultMerchantTypeCollapseExpand";

                var typeCollapseExpandImg = document.createElement("img");
                typeCollapseExpandImg.id = "resultImg_" + merchantArray[i].typeNoSpaces;
                typeCollapseExpandImg.onclick = function() { showHideTypeResults(this, true); }
                typeCollapseExpandImg.src = imgPath + "resultMerchantTypePlus.gif";
                typeCollapseExpandDiv.appendChild(typeCollapseExpandImg);

                typeNameContainer.appendChild(typeCollapseExpandDiv);

                merchantTypeResultContainer.appendChild(typeNameContainer);

                merchantCount = 0;
            }

            merchantCount++;
            _displayedMarkerCount++;

            //Identify and highlight featured merchants 
            var resultDiv = document.createElement("div");
            var isFeatured = merchantArray[i].featuredMerchant;
            //if ( i == 0 ) resultDiv.className = "resultMerchantDetailContainer first-child";
            //else resultDiv.className = "resultMerchantDetailContainer";
            if (i == 0 && isFeatured == "true") {
                resultDiv.className = "resultMerchantDetailContainer resortMapFeaturedFirstChild";
            }
            else if (i == 0) {
                resultDiv.className = "resultMerchantDetailContainer first-child";
            }
            else if (isFeatured == "true") {
                resultDiv.className = "resultMerchantDetailContainer resortMapFeatured";
            }
            else {
                resultDiv.className = "resultMerchantDetailContainer";
            }

            var resultDetailsDiv = document.createElement("div");
            resultDetailsDiv.className = "resultMerchantDetailCopy";
            //resultDetailsDiv.style.background = "url(" + merchantArray[i].typeIcon + ")";
            //alert(merchantArray[i].merchantType.merchantTypeIcon);
            //resultDetailsDiv.style.background = "url('" + imgPath + merchantArray[i].merchantType.merchantTypeIcon + "')";
            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);

            var resultNode = document.createElement('z');
            resultNode.innerHTML = 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);
            if (merchantArray[i].merchantDetailUrl != null) {
                detailsHyperlink.href = merchantArray[i].merchantDetailUrl;
                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);

            merchantTypeResultListContainer.appendChild(resultDiv);
        }
    }
    if (typeNameDiv) {
        typeNameDiv.innerHTML += " (" + merchantCount + ")";
    }
    merchantTypeResultContainer.appendChild(merchantTypeResultListContainer);
    document.getElementById("pleaseWaitResults").style.display = "none";
    document.getElementById("pleaseWaitMapOverlay").style.display = "none";
    document.getElementById("resultsContainerContents").appendChild(merchantTypeResultContainer);

    if (_isUberMap) {
        document.getElementById("viewAllResults").style.display = (_displayedMarkerCount > 0) ? "block" : "none";
    }
    // re-open any sections we need to
    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() {

    
   /* if(!lodgingMerchantInQueryString)
    {
	if ( window.lodgingDataAvailable){
		//debugger;
		return false;
	}
   }
    debugger;*/
    $("#neighborhoodListLeft, #neighborhoodListRight").html("");
    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 listLeft = $("#neighborhoodListLeft");
	if ( listLeft.length == 0 ){
		listLeft = $("<div id='neighborhoodListLeft'></div>").prependTo("#neighborhoodListContainer");
	}
	var listRight = $("#neighborhoodListRight");
	if ( listRight.length == 0 ){
		listRight = $("<div id='neighborhoodListRight'></div>").prependTo("#neighborhoodListContainer");
	}
	
    var locationsOnLeftCount = Math.ceil(locationArray.length / 2);

	var strHtmlLeft = ["<ul>"];
	var strHtmlRight = ["<ul>"];
    for (i = 0; i < locationArray.length; i++) {
		if(i < locationsOnLeftCount)
		{
			strHtmlLeft.push([""
				,"<li>"
				,	"<input type='checkbox' value='" + locationArray[i] + "' onclick='filterByLocation(this.value, this.checked, true);' checked>"
				,	"<span> " + locationArray[i] + "</span>"
				,"</li>"
			].join(""));
		}
		else
		{
			strHtmlRight.push([""
				,"<li>"
				,	"<input type='checkbox' value='" + locationArray[i] + "' onclick='filterByLocation(this.value, this.checked, true);' checked>"
				,	"<span> " + locationArray[i] + "</span>"
				,"</li>"
			].join(""));
		}
    }
	strHtmlLeft.push("</ul>");
	listLeft.append(strHtmlLeft.join(""));
  
	strHtmlRight.push("</ul>");
	listRight.append(strHtmlRight.join(""));
	
    document.getElementById("pleaseWaitLocationFilter").style.display = "none";
    document.getElementById("mapThumbnailImg").style.display = "block";
    document.getElementById("neighborhoodListContainer").style.display = "block";
    document.getElementById("mapInstructions").style.display = "block";
    
    //lodgingMerchantInQueryString = false;
}
/*

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);
	}
	document.getElementById("pleaseWaitLocationFilter").style.display = "none";
	document.getElementById("mapThumbnailImg").style.display = "block";
	document.getElementById("neighborhoodListContainer").style.display = "block";
}

*/
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) {

	if ( window.filterTabsCreated ){ return false; }

    // 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(this, 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();

        if (merchantType.nameNoSpaces == 'Lodging') {
            if (merchantType.filterTypes[x].name == "Rating") {

                filterOptionsArray = [0, 1, 2, 3, 4, 5]
            }
        }

        // 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 = imgPath + "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);

        // add a br to clear it all
        /*
        var br = document.createElement("br");
        br.className = "clear";
        filterContainerContentsDiv.appendChild(br);
        */
    }

    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 = imgPath + "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 = imgPath + "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(imgPath + "marker_selected.png");
}
function setNormalIcon(hyperlink) {
    var x = xreplace(hyperlink.id, "result", "");
    merchantArray[x].marker.setImage(merchantArray[x].typeMarker);
}

function showMerchantInfo(x) {
    if (merchantArray[x].hasTabs == true) {
        merchantArray[x].marker.openInfoWindowTabsHtml(merchantArray[x].infoWindowTabs);
    }
    else {
        merchantArray[x].marker.openInfoWindowHtml(merchantArray[x].infoWindowHtml);
    }

    // Reset the text box in the From/To popup.
    if ($('#fromAddress').length) $('#fromAddress').val('');
    if ($('#toAddress').length) $('#toAddress').val('');

}
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(me, 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();

//debugger;
if(window.filterState.showmerchantfilter.length > 0 )
    {
	if ( show ){
		if ( $.inArray( type, window.filterState.showmerchantfilter ) == -1 ){
			window.filterState.showmerchantfilter.push( type );
		}
	} else {
		var idx = $.inArray( type, window.filterState.showmerchantfilter );
		if ( idx > -1 ){
			window.filterState.showmerchantfilter.splice( idx, 1 );
		}
	}

    
	if ( !window.lodgingDataAvailable && type == "Lodging" && me.checked){
		//debugger;
		loadMap("/vailresorts/HttpHandlers/GMapHandler.ashx");
		window.lodgingDataAvailable = true;
		//return false;
	}
	}
}
function buildIcon(markerImage, width, height) {
    icon = new GIcon();
    icon.shadow = imgPath + "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;
// Add class in Popup | Anuj Rastogi
var detailsHTML = "<div class='popup clearfix'>";
    if (merchant.merchantDetailUrl != null)
        var merchantDetailUrl = merchant.merchantDetailUrl;

    var currentUrl = (location.pathname + location.search).split('#')[0];

    if ((merchant.merchantDetailUrl != null) && (merchant.merchantDetailUrl != currentUrl)) {
        detailsHTML += "<div class='popupMerchantName'><a href='" + merchant.merchantDetailUrl + "'>" + merchant.name + "</a></div>";
    }
    else {
        detailsHTML += "<div class='popupMerchantName'><a href='#'>" + merchant.name + "</a></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 != null && merchant.address != "") {
        merchant.address = merchant.address.replace(/<\!\[CDATA\[/, '');
        merchant.address = merchant.address.replace(/\]\]>/, '');
        detailsHTML += merchant.address + "<br />";
    }

    if (merchant.hours != null && merchant.hours != "") {
        detailsHTML += merchant.hours + "<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' />";

    // Set URL to save activity to Trip Folder    
    //var urlSaveToTrip = merchant.merchantSaveUrl + "?ProductName=" + merchant.name  //Comment by Naveen to remove product name from savetotrip url ;
    var urlSaveToTrip = merchant.merchantSaveUrl;
    if (merchant.type == "Activities") {
        //MKS urlSaveToTrip += "?ProductName=" + merchant.name + "&ProductDescription=" + merchant.description + "&ProductTypeId=" + merchant.type + "&SystemName=" + merchant.systemName +
        //MKS "&Search=NoData" + "&IsBookable=" + (merchant.merchantBookUrl != "#") + "&TargetURL=" + merchant.myTripFolderGUID + "&IsSaveTrip=1";

        urlSaveToTrip += "?ProductId=" + merchant.Id +  "&ProductTypeId=" + merchant.type + 
        "&Search=NoData" + "&TargetURL=" + merchant.myTripFolderGUID + "&IsSaveTrip=1";
    }
    if (merchant.type == "Dining") {
        //MKS  urlSaveToTrip += "?ProductName=" + merchant.name + "&ProductLocation=" + merchant.location +
        //MKS  "&ProductTypeId=" + merchant.type + "&Search=NoData" + "&SystemName=" + merchant.systemName +
        //MKS  "&IsBookable=" + (merchant.reservationLink != "#") + "&TargetURL=" + merchant.myTripFolderGUID + "&IsSaveTrip=1";
        
        urlSaveToTrip += "?ProductId=" + merchant.Id +
        "&ProductTypeId=" + merchant.type + "&Search=NoData" + "&TargetURL=" + merchant.myTripFolderGUID + "&IsSaveTrip=1";
        
    }
    if (merchant.type == "Shopping") {
        //MKS    urlSaveToTrip += "?ProductName=" + merchant.name + "&ProductTypeId=" + merchant.type + "&Search=NoData" + "&SystemName=" + merchant.systemName + "&TargetURL=" + merchant.myTripFolderGUID + "&IsSaveTrip=1";
        urlSaveToTrip += "?ProductId=" + merchant.Id + "&ProductTypeId=" + merchant.type + "&Search=NoData" +  "&TargetURL=" + merchant.myTripFolderGUID + "&IsSaveTrip=1";
    }
// Added Div with Class (popupMerchantButtonTabs) by Anuj Rastogi
detailsHTML += "<div class='popupMerchantButtonTabs'><div class='popupMerchantSaveToTripFolder'>";

    //detailsHTML += "<a href='" + urlSaveToTrip + "' title='Save' class='saveLink'>Save</a></div>";
    if (merchant.type != "Services") {
        detailsHTML += "<a href='" + urlSaveToTrip + "' title='Save' class='saveLink uberMapSaveModalLink' onclick='bindModalEvent(event);'>Save</a></div>";
    }



    // Display Price for Dining
    if (merchant.type == "Dining") {
        var expense = merchant.price;
        if (expense != null && expense.length > 0) {
            var tooltip = "";
            switch (expense) {
                case "1":
                    tooltip = "under $20";
                    break;
                case "2":
                    tooltip = "Between $21-$30";
                    break;
                case "3":
                    tooltip = "Between $31-$40";
                    break;
                case "4":
                    tooltip = "Greater $40";
                    break;
            }

            detailsHTML += "<div class = 'details' title ='" + tooltip + "'><span class='priceBg resortMapPriceBg priceIcon priceTier" + expense + "'/></div>";
        }
    }

    //detailsHTML += "<div class='popupMerchantLearnMore'><img src='btnLearnMore.gif'></div>";

    //var currentUrl = (location.pathname + location.search).split('#')[0];

    if ((merchant.merchantDetailUrl != null) && (merchant.merchantDetailUrl != currentUrl)) {
        detailsHTML += "<a class='diningInfo' href='" + merchant.merchantDetailUrl + "'>" + "More Info</a>";
    }
    else {
        if(!(merchant.merchantType.nameNoSpaces == "Transportation" || merchant.merchantType.nameNoSpaces == "MtnFacilities"))  {	        
			//if($('#middleTabsContainer ul li.first span').length > 0)
			if($('#middleTabsContainer ul li.first span').html() == "Info")
			{
				detailsHTML += "<a class='diningInfo' href='javascript:switchTabs()'>" + "More Info</a>";
			}

	    }
        
    }

    //	// Displaying website address of merchant if exist
    //	if (merchant.website != null && merchant.website != '#')
    //	{
    //	    detailsHTML += "<a href='" + merchant.website +"'>" + merchant.website + "</a>";    
    //	}

    // Display Book it button if ActivityBookingURL field for Activities is defined
    if ((merchant.type == "Activities")) {
        if (merchant.merchantBookUrl != null) {
            var activityBookUrl = merchant.merchantBookUrl;
            var idx = activityBookUrl.indexOf("#");
            if (idx != 0) {
                detailsHTML += "<a href='" + merchant.merchantBookUrl + "' title='Book' class='linkPrimary openResortMapModalLink' onclick='bindBookItModalEvent(event);'>Book It</a>";
            }
        }
    }

    // Display Book it button if ReservationLink field for dining is defined
    if (merchant.type == "Dining") {
        if (merchant.reservationLink != null) {
            var reservationLinkUrl = merchant.reservationLink;
            var idx = reservationLinkUrl.indexOf("#");

            if (idx == -1) {
                if (merchant.reservationLinkInternal == "true") {
                    detailsHTML += "<a href='" + merchant.reservationLink + "' title='Book' class='linkPrimary openResortMapModalLink' onclick='bindBookItModalEvent(event);'>Book It</a>";
                }
                else {
                    detailsHTML += "<a href='" + merchant.reservationLink + "' title='Book' class='bookItButton'>Book It</a>";
                }
            }
        }
    }

    detailsHTML += "</div></div>";
    return detailsHTML;

}
function buildLodgingFeatureBlurb(merchant) {
    var lodgingRet = "";
	//for (rate = 0; rate < parseInt(merchant.Rating); rate++) {
		//lodgingRet += "<img src='" + imgPath + "star.png'>";
		
		lodgingRet += "<img src='" + merchant.ratingImageUrl + "'>";
	//}	

    lodgingRet += "<br />" + xreplace(merchant.type, "|", ", ") + " - ";

    lodgingRet += xreplace(merchant.UnitSize, "|", ", ");
    lodgingRet += "<br />";

    var am = merchant.Amenities;

    am = xreplace(am, "|", " ");
    am = xreplace(am, "Close to Slopes", "<img src='" + imgPath + "slopes.gif' alt='Close to Slopes'>");
    am = xreplace(am, "Hot Tub", "<img src='" + imgPath + "hottub.gif' alt='Hot Tub'>");
    am = xreplace(am, "Pool", "<img src='" + imgPath + "pool.gif' alt='Pool'>");
    am = xreplace(am, "On Shuttle Route", "<img src='" + imgPath + "shuttle.gif' alt='On Shuttle Route'>");
    lodgingRet += am;
    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;
	
	if(temp==null)
	{
	temp="";
	}
	
    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 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() {

    document.getElementById("directionsOverlay").style.visibility = "visible";
}
function setDirections() {
    var from;
    var to;
    if (document.getElementById("direction").value == "To") {
        to = document.getElementById("merchantGeocode").value;
        from = document.getElementById("fromAddress").value;
    }
    else {
        from = document.getElementById("merchantGeocode").value;
        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 doDirectionSearchKeyPress(e) {
    //the purpose of this function is to allow the enter key to 

    //point to the correct button to click.

    var key;

    if (window.event)
        key = window.event.keyCode;     //IE

    else
        key = e.which;     //firefox

    if (key == 13) {
        stopEvent(e);
        setDirections();
    }
}
function stopEvent(e) {
    if (!e) var e = window.event;

    //e.cancelBubble is supported by IE - this will kill the bubbling process.
    e.cancelBubble = true;
    e.returnValue = false;
    //e.stopPropagation works only in Firefox.
    if (e.stopPropagation) {
        e.stopPropagation();
        e.preventDefault();
    }
    return false;
}
function switchTabs() {
    if ($("ul.middleTabs li.first a").length) $("ul.middleTabs li.first a").trigger("click");
	//$('#map').html('');
}
function modalWin(url) {
    window.showModalDialog(url, "name", "dialogWidth:255px;dialogHeight:250px");
}

function setupSlider() {
    if ( $("#sliderBg").length > 0 ){ return false; }

    if ((jQuery.browser.msie) && (parseInt(jQuery.browser.version) == 6)) {
        $('.filterContainer input[type=checkbox]').attr('checked', true);
		$('#neighborhoodListLeft input[type=checkbox]').attr('checked', true);
    }
	
	//pn artf996451 
    $('#li_Lodging .filterMerchantTypeFilterGroupSelectAll').hide();

    //hide checkboxes. filter states will still be maintained by these checkboxes
    $('#filterValues_Lodging_Rating .filterValueCheckbox, #filterValues_Lodging_Rating .filterValueName, #filterValues_Lodging_Rating br.clear').hide();

    var defaultSliderVal;
    //set default state of filters
    if ($('#filterValues_Lodging_Rating .filterValueCheckbox input[type=checkbox]').length)
    { defaultSliderVal = parseInt($('#filterValues_Lodging_Rating .filterValueCheckbox:first-child input[type=checkbox]').val()); }
    else { defaultSliderVal = 1; }

    //create slider element
    $('#filterValues_Lodging_Rating').append('<div id="sliderBg"><div id="slider"></div><br/></div>');

    //set default trigger
    //$('#filterValues_Lodging_Rating .filterValueCheckbox input[type=checkbox][value!=' + defaultSliderVal + ']').trigger('click');

    //slider mechanism

    $("#slider").slider({
        value: defaultSliderVal,
        range: true,
        min: 0,
        max: 5,
        step: 1,
        values: [0, 5],
        stop: function(event, ui) {

            var cb = $('#filterValues_Lodging_Rating .filterValueCheckbox input:checkbox');
            for (var i = 0; i <= 5; i++) {
                // Check if the value of filters lies between the slider range
                if ((i >= ui.values[0]) && (i <= ui.values[1])) {
                    // Check only unchecked boxes and redraw map
                    if (cb.eq(i).attr('checked') == false) {
                        cb.eq(i).attr('checked', true);
                        showHideMerchantsByFilter(cb[i], true);
                    }
                }
                else {
                    // Uncheck only checked boxes and redraw map
                    if (cb.eq(i).attr('checked') == true) {
                        cb.eq(i).attr('checked', false);
                        showHideMerchantsByFilter(cb[i], true);
                    }
                }
            }
        }
    });
}

function bindModalEvent(event) {
    stopEvent(event);

    if ($("div.ubermapSaveToTripDialog").length == 0) {
        $("<div class='ubermapSaveToTripDialog'></div>")
	        .append("<iframe src='' width='950px' height='690px' 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', urlContent)
		.attr('width', '100%')
		.attr('height', '100%')
		.attr('scrolling', 'no');
    try {
        objDialog.dialog('open');
    } catch (e) { }

    return false;


}

function bindBookItModalEvent(event) {
    stopEvent(event);

    if ($("div.ubermapBookItDialog").length == 0) {
        $("<div class='ubermapBookItDialog'></div>")
	        .append("<iframe src='' width='950px' height='800px' frameborder='0' marginheight='0' marginwidth='0'></iframe>")
	        .appendTo("body");
    }

    if ($('.ubermapBookItDialog').length > 0 && $('body > .ui-dialog .ubermapBookItDialog').length == 0) {
        $('.ubermapBookItDialog').eq(0).dialog({
            bgiframe: true,
            autoOpen: false,
            width: 950,
            height: 800,
            modal: true,
            resizable: false,
            position: 'center',
            zIndex: 9999,
            closeOnEscape: true,
            draggable: false
        });
    }
    var objDialog = $(' .ui-dialog .ubermapBookItDialog');

    var urlContent = $(" .openResortMapModalLink").attr('href');

    $('iframe', objDialog)
		.attr('src', urlContent)
		.attr('width', '100%')
		.attr('height', '100%')
		.attr('scrolling', 'no');
    try {
        objDialog.dialog('open');
    } catch (e) { }

    return false;


}


/* Manu */
function parseQueryString(){
	window.filterState = {location:[],showmerchantfilter:[]};

	var url = document.location.href;
	if ( url.indexOf("?") == -1 ){
		return false;
	}
	qs = url.split("?")[1].split("&");
	for ( var x = 0; x < qs.length; x++ ){
		var key = unescape( qs[x].split("=")[0] );
		var values = qs[x].split("=")[1].split(",");
		for ( var y = 0; y < values.length; y++ ){
			values[y] = $.trim( unescape( values[y].toLowerCase() ) );
		}
		
		window.filterState[key] = values;
	}
	
	var found = false;
	for ( var x = 0; x < window.filterState.showmerchantfilter.length; x++ ){
		if ( window.filterState.showmerchantfilter[x].toLowerCase() == "lodging" ){
		    found = true;
		    break;
		}
	}
	if ( !found ){
		window.lodgingDataAvailable = false;
		lodgingMerchantInQueryString = false;
	} else {
		window.lodgingDataAvailable = true;
		lodgingMerchantInQueryString = true;
	}
	
	
}
parseQueryString();

