﻿var gCurrentSubCategory;

function OnFailed(result) {
}

function ClearPrices() {

    $("#filterPanelStay #sliderRange_SMI_STAY,  .listingsWrapDiv #sliderRange_SMI_STAY").slider({
        range: true,
        min: 0,
        max: STAYPRICE,
        step: 100,
        values: [0, STAYPRICE],
        stop: function(event, ui) {
            $("#filterPanelStay #amount_SMI_STAY, .listingsWrapDiv #amount_SMI_STAY ").val('$' + ui.values[0] + ' to $' + ui.values[1]);
            $("#filterPanelStay #lowPrice_SMI_STAY, .listingsWrapDiv  #lowPrice_SMI_STAY").val(ui.values[0]);
            $("#filterPanelStay #highPrice_SMI_STAY, .listingsWrapDiv #highPrice_SMI_STAY").val(ui.values[1]);
            getFilteredList();
        }
    });


    $("#filterPanelEat #sliderRange_SMI_EAT, .listingsWrapDiv #sliderRange_SMI_EAT").slider({
        range: true,
        min: 0,
        max: EATPRICE,
        step: 100,
        values: [0, EATPRICE],
        stop: function(event, ui) {
            $("#filterPanelEat #amount_SMI_EAT, .listingsWrapDiv #amount_SMI_EAT").val('$' + ui.values[0] + ' to $' + ui.values[1]);
            $("#filterPanelEat #lowPrice_SMI_EAT, .listingsWrapDiv #lowPrice_SMI_EAT").val(ui.values[0]);
            $("#filterPanelEat #highPrice_SMI_EAT, .listingsWrapDiv #highPrice_SMI_EAT").val(ui.values[1]);

            getFilteredList();
        }
    });


    var tab = getSelectedResultsTab();

    switch (tab) {
        case 'tabStay':

            $("#filterPanelStay #lowPrice_SMI_STAY").val($("#filterPanelStay #sliderRange_SMI_STAY").slider("values", 0));
            $("#filterPanelStay #highPrice_SMI_STAY").val($("#filterPanelStay #sliderRange_SMI_STAY").slider("values", 1));

            $("#filterPanelStay #amount_SMI_STAY").val('$' + $("#filterPanelStay #sliderRange_SMI_STAY").slider("values", 0) + ' to $' + $("#filterPanelStay #sliderRange_SMI_STAY").slider("values", 1));

            $("#filterPanelStay #lowPrice_SMI_STAY").val(null);
            $("#filterPanelStay #highPrice_SMI_STAY").val(null);

            break;
        case 'tabEat':
            $("#filterPanelEat #lowPrice_SMI_EAT").val($("#filterPanelEat #sliderRange_SMI_EAT").slider("values", 0));
            $("#filterPanelEat #highPrice_SMI_EAT").val($("#filterPanelEat #sliderRange_SMI_EAT").slider("values", 1));

            $("#filterPanelEat #amount_SMI_EAT").val('$' + $("#filterPanelEat #sliderRange_SMI_EAT").slider("values", 0) + ' to $' + $("#filterPanelEat #sliderRange_SMI_EAT").slider("values", 1));

            $("#filterPanelEat #lowPrice_SMI_EAT").val(null);
            $("#filterPanelEat #highPrice_SMI_EAT").val(null);

            break;
        default:
            $(".listingsWrapDiv #lowPrice_SMI_EAT").val($(".listingsWrapDiv #sliderRange_SMI_EAT").slider("values", 0));
            $(".listingsWrapDiv #highPrice_SMI_EAT").val($(".listingsWrapDiv #sliderRange_SMI_EAT").slider("values", 1));

            $(".listingsWrapDiv #amount_SMI_EAT").val('$' + $(".listingsWrapDiv #sliderRange_SMI_EAT").slider("values", 0) + ' to $' + $(".listingsWrapDiv #sliderRange_SMI_EAT").slider("values", 1));
            $(".listingsWrapDiv #lowPrice_SMI_EAT").val(null);
            $(".listingsWrapDiv #highPrice_SMI_EAT").val(null);

            $(".listingsWrapDiv #lowPrice_SMI_STAY").val($(".listingsWrapDiv #sliderRange_SMI_STAY").slider("values", 0));
            $(".listingsWrapDiv #highPrice_SMI_STAY").val($(".listingsWrapDiv #sliderRange_SMI_STAY").slider("values", 1));

            $(".listingsWrapDiv #amount_SMI_STAY").val('$' + $(".listingsWrapDiv #sliderRange_SMI_STAY").slider("values", 0) + ' to $' + $(".listingsWrapDiv #sliderRange_SMI_STAY").slider("values", 1));
            $(".listingsWrapDiv #lowPrice_SMI_STAY").val(null);
            $(".listingsWrapDiv #highPrice_SMI_STAY").val(null);

    }

    getFilteredList();
}

/********************************************/
/*           AJAX SUPPORT METHODS           */
/********************************************/
function GetCategoriesHTML(successFunction) {
    $.ajax({
        type: "POST",
        url: "/Linked/WebService/ILNYFilterListing.asmx/GetCategoriesHTML",
        data: "",
        dataType: "xml",
        success: successFunction,
        error: OnFailed
    });
    return false;
}

function GetAmenitiesHTML(params, successFunction) {
    $.ajax({
        type: "POST",
        url: "/Linked/WebService/ILNYFilterListing.asmx/GetAmenitiesHTML",
        data: params,
        dataType: "xml",
        success: successFunction,
        error: OnFailed
    });
    return false;
}

function GetThemesHTML(successFunction) {
    $.ajax({
        type: "POST",
        url: "/Linked/WebService/ILNYFilterListing.asmx/GetThemesHTML",
        data: "",
        dataType: "xml",
        success: successFunction,
        error: OnFailed
    });
    return false;
}

function ResetPagerListSearch(pagerId, currentPage, pageCount, resultsPerPage, totalResultCount) {

    var targetURL = "javascript(0)";
    SetPageTotalPageCount(pagerId, totalResultCount);
    $('#' + pagerId + ' .Paging').pager({ pagenumber: currentPage, pagecount: pageCount, buttonClickCallback: pagerWhereToStayClick, targetURL: targetURL, recordsPerPage: resultsPerPage });
}
function GetFilteredResults(params, successFunction) {
    if ($('input.resultsFunc').length > 0) {
        var resultsFunc = eval($('input.resultsFunc'));
        return resultsFunc(params, successFunction);
    } else {
        $.ajax({
            type: "POST",
            url: "/Linked/WebService/ILNYFilterListing.asmx/GetResults",
            data: params,
            dataType: "xml",
            success: successFunction,
            error: OnFailed
        });
    }
    return false;
}

$(function() {

    // only used by see and do
    var ilnyfilter_catCode = "";
    var ilnyfilter_subcatCode = "";

    // extends jQuery to return an an array as a joined list
    $.fn.extend({
        joinVals: function(separator) {
            if (!separator) separator = ',';
            return (this.map(function() { return $(this).val(); }).get().join(separator));
        }
    });

    $.fn.extend({
        joinTitles: function(separator) {
            if (!separator) separator = ',';
            return (this.map(function() { return $(this).attr('title'); }).get().join(separator));
        }
    });

    //get the values and update the list
    getFilteredList = function() {
        var params = {
            PageType: '',
            ListingID: '',
            RegionID: '',
            CityName: '',
            CategoryCode: '',
            SubCategoryCode: '',
            AmenityCode: '',
            ThemesID: '',
            featured: '',
            featuredOfferId: '',
            CommunityURL: '',
            latitude: '',
            longitude: '',
            FromDate: '',
            ToDate: '',
            PriceRangeFrom: '',
            PriceRangeTo: '',
            includeLodging: '',
            LodgingType: '',
            PageNumber: arguments.length > 0 ? arguments[0] : 1,
            ListingsPerPage: arguments.length > 1 ? arguments[1] : '10'
        };

        var panl = getFilterPanelParent();  //id of selected panel tab, or document if not a tabbed page

        var regionStr = $("[id^='DDFilterByLocation']", panl).val();
        var regionArr = (regionStr) ? regionStr.split('|') : [-1];

        var catcode = $('.filterCat input:checked', panl).val();
        var lodgecode = $('.filterLodge input:checked', panl).val();
        var includelodge = $('.filterLodging input:checked', panl).val();
        var featured = $('#featuredOffersOptions').val();
        if (!catcode) catcode = ""; //$('.filterCat input', panl).val();

        var tab = getSelectedResultsTab();

        switch (tab) {
            case 'tabSeeAndDo':
                params.PageType = SMI_SEEANDDO;
                break;
            case 'tabEvents':
                params.PageType = SMI_EVENT;
                break;
            case 'tabEat':
                params.PageType = SMI_EAT;
                params.PriceRangeFrom = $("#filterPanelEat #lowPrice_SMI_EAT").val();
                params.PriceRangeTo = $("#filterPanelEat #highPrice_SMI_EAT").val();
                break;
            case 'tabStay':
                params.PageType = SMI_STAY;
                params.PriceRangeFrom = $("#filterPanelStay #lowPrice_SMI_STAY").val();
                params.PriceRangeTo = $("#filterPanelStay #highPrice_SMI_STAY").val();
                break;
            case 'tabDeals':
                params.PageType = SMI_DEAL;
                break;
            default:
                params.PageType = $('input.pagetype').val();

        }
        if (tab == null && $('input.pagetype').val() == 'SMI_EAT') {
            params.PriceRangeFrom = $(".listingsWrapDiv #lowPrice_SMI_EAT").val();
            params.PriceRangeTo = $(".listingsWrapDiv #highPrice_SMI_EAT").val();
        } else {
            if (tab == null || $('input.pagetype').val() == 'SMI_STAY') {
                params.PriceRangeFrom = $(".listingsWrapDiv #lowPrice_SMI_STAY").val();
                params.PriceRangeTo = $(".listingsWrapDiv #highPrice_SMI_STAY").val();
            }
        }

        //remove these 2 lines to turn price filter back on
        params.PriceRangeFrom = '';
        params.PriceRangeTo = '';

        switch (params.PageType) {
            case SMI_EAT:
                params.CategoryCode = 'res';
                params.SubCategoryCode = catcode;
                break;
            case SMI_LOCRESOURCES:
                params.CategoryCode = 'agc';
                params.SubCategoryCode = catcode;
                break;
            case SMI_TRANSPORTATION:
                params.CategoryCode = 'trp';
                params.SubCategoryCode = catcode;
                break;
            case SMI_SEEANDDO:
            case SMI_EVENT:
                if ($('.resultCategoryHdrClick input', panl).val() != undefined)
                    params.CategoryCode = $('.resultCategoryHdrClick input', panl).val();
                else {
                    ilnyfilter_catCode = '';
                    ilnyfilter_subcatCode = '';
                    params.CategoryCode = ilnyfilter_catCode;
                }

                params.SubCategoryCode = ilnyfilter_subcatCode;
                break;
            case SMI_STAY:
                params.CategoryCode = catcode;
                break;
            case SMI_DEAL:
                params.featured = catcode;
                params.CategoryCode = catcode;
                params.LodgingType = lodgecode;
                params.includeLodging = includelodge;
                break;
        }

        params.AmenityCode = $('.filterAmenity > input:checked', panl).joinVals('|');

        if ($('#contentid').length > 0)
            params.ListingID = $('#contentid').val();
        else
            params.ListingID = '';

        params.RegionID = regionArr[0] < 0 ? "" : regionArr[0];
        if (params.RegionID == "") {
            params.RegionID = $('#regionId').val();
        }
        params.CityName = $('input.cityInput', panl).val() == $('input.cityInput', panl).attr('title') ? '' : $('input.cityInput', panl).val();
        if (params.CityName == "") {
            params.CityName = $('#cityname').val();
        }
        params.ThemesID = $('.filterThemes > input:checked', panl).joinVals('|');
        params.featuredOfferId = $('#featuredOffersOptions').val();
        params.featured = '';
        params.CommunityURL = '';
        params.latitude = $('#latitude').val();
        params.longitude = $('#longitude').val();
        if ($('input.startDate', panl).val() == undefined) {
            params.FromDate = "";
        } else {
            params.FromDate = $('input.startDate', panl).val(); // == $('input.startDate', panl).attr('defaultValue') ? '' : $('input.startDate', panl).val();
        }
        if ($('input.endDate', panl).val() == undefined) {
            params.FromDate = "";
        } else {
            params.ToDate = $('input.endDate', panl).val(); // == $('input.endDate', panl).attr('defaultValue') ? '' : $('input.endDate', panl).val();
        }

        region = '';
        city = '';
        if (params.RegionID != undefined) {
            region = regionArr[4];
        }
        if (params.CityName != undefined) {
            city = params.CityName;
        }

        var selectedThemes = $('.filterThemes > input:checked', panl).joinTitles('|');
        var selectedAmenity = $('.filterAmenity > input:checked', panl).joinTitles('|');

        if (tab == null) {
            if (params.PageType != null) {
                pageTracker._trackEvent('FilteredListingsSearch', params.PageType + '_Search', region + '-' + city + '-' + params.CategoryCode + '-' + params.SubCategoryCode + '-' + selectedThemes + '-' + selectedAmenity);
            }
        }
        else {
            pageTracker._trackEvent('FilteredListingsSearch', params.PageType + '_Tabbed_Search', region + '-' + city + '-' + params.CategoryCode + '-' + params.SubCategoryCode + '-' + selectedThemes + '-' + selectedAmenity);
        }

        //send the query to the server
        GetFilteredResults(params, function(xml) {


            //get values off of the return object
            var rpp = $('ResultsPerPage', xml).text();
            var trc = $('TotalResultCount', xml).text();
            var cp = $('CurrentPage', xml).text();
            var htm = $('ObjectListItems', xml).text();
            var htmNoResults = 'No results found.';
            var tpc = parseInt(trc / rpp);
            if (trc % rpp > 0) tpc++;

            //if this is a tabbed listing page, figure out which tab is selected
            var tabid = getSelectedResultsTab();
            if (tabid) {
                // $('div.listResults', '#' + tabid.replace(/^tab/, 'tabContent')).html(htm);

                switch (tabid) {
                    case "tabSeeAndDo":
                        $('div.listResults', '#' + tabid.replace(/^tab/, 'tabContent')).html(htm);
                        ResetPagerListSearch("pagerTopSeeAndDo", cp, tpc, rpp, trc);
                        //ResetPagerSiteSearch("pagerBottomSeeAndDo", currentPage, pageCount, resultsPerPage, totalResultCount)
                        break;
                    case "pagerTopEvents":
                    case "pagerBottomEvents":
                    case "tabEvents":
                        $('div.listResults', '#' + tabid.replace(/^tab/, 'tabContent')).html(htm);
                        ResetPagerListSearch("pagerTopEvents", cp, tpc, rpp, trc);
                        //ResetPagerSiteSearch("pagerBottomEvents", currentPage, pageCount, resultsPerPage, totalResultCount);
                        break;
                    case "tabEat":

                        $('div.listResults', '#' + tabid.replace(/^tab/, 'tabContent')).html(htm);
                        ResetPagerListSearch("pagerTopEat", cp, tpc, rpp, trc);
                        //ResetPagerSiteSearch("pagerBottomEat", currentPage, pageCount, resultsPerPage, totalResultCount);
                        break;
                    case "tabDeals":

                        $('div.listResults', '#' + tabid.replace(/^tab/, 'tabContent')).html(htm);
                        ResetPagerListSearch("pagerTopDeal", cp, tpc, rpp, trc);
                        //ResetPagerSiteSearch("pagerBottomStay", currentPage, pageCount, resultsPerPage, totalResultCount);
                        break;
                    case "tabStay":

                        $('div.listResults', '#' + tabid.replace(/^tab/, 'tabContent')).html(htm);
                        ResetPagerListSearch("pagerTopStay", cp, tpc, rpp, trc);
                        //ResetPagerSiteSearch("pagerBottomStay", currentPage, pageCount, resultsPerPage, totalResultCount);
                        break;
                    case "tabMore":

                        $('div.listResults', '#' + tabid.replace(/^tab/, 'tabContent')).html(htm);
                        ResetPagerListSearch("pagerTopMore", cp, tpc, rpp, trc);
                        //ResetPagerSiteSearch("pagerBottomMore", currentPage, pageCount, resultsPerPage, totalResultCount);
                        break;
                }
                if (htm == htmNoResults) {
                    $('div.listResults').addClass('noResultsListing');
                }
                actionIconsListings(); // also called on initial load
                actionIconsConfirmation();
                plotMarkers(params.latitude, params.longitude);
                $('div.stayResults', '#' + tabid.replace(/^tab/, 'tabContent')).hoverIntent({
                    sensitivity: 7,
                    interval: 100,
                    over: featureOn,
                    timeout: 500,
                    out: featureOff
                }).each(function() {
                    if ($(this).children('a.stayResultsImage').children('img').length) {
                        $(this).children('a.stayResultsImage').css('display', 'block').css('float', 'left').css('margin-right', '10px');
                        $(this).addClass("stayResultsWithImage");
                        if ($(this).children('.bubble').length) {
                            $(this).children('.stayResultsContainer').css('width', '245px');
                            $(this).children('.stayResultsContainer').children('.stayResultsName').css('width', '245px');
                        }
                    }
                });
                //otherwise, it's not a tabbed listing page, so it's a Listings page
            } else {
                $('#listResults').html(htm);
                actionIconsListings(); // also called on initial load
                actionIconsConfirmation();

                plotMarkers(params.latitude, params.longitude);
                $('#pagerTopWhereToStay .pageTotalRecords').val(trc);
                $("#pagerTopWhereToStay .Paging").pager({
                    pagenumber: (isNaN(cp) ? 1 : cp),
                    pagecount: (isNaN(tpc) ? 1 : tpc),
                    recordsPerPage: (isNaN(rpp) ? 10 : rpp),
                    recordCount: (isNaN(trc) ? 1 : trc),
                    buttonClickCallback: pagerWhereToStayClick,
                    targetURL: $('#pagerTopWhereToStay .pageTargetURL').val()
                });
                //apply the hover to the new results
                $(".stayResults").hoverIntent({
                    sensitivity: 7,
                    interval: 100,
                    over: featureOn,
                    timeout: 500,
                    out: featureOff
                }).each(function() {
                    if ($(this).children('a.stayResultsImage').children('img').length) {
                        $(this).addClass("stayResultsWithImage");
                        $(this).children('a.stayResultsImage').css('display', 'block').css('float', 'left').css('margin-right', '10px');
                        if ($(this).children('.bubble').length) {
                            $(this).children('.stayResultsContainer').css('width', '245px');
                            $(this).children('.stayResultsContainer').children('.stayResultsName').css('width', '245px');
                        }
                    }
                });
            }
        });
    }


    //determine which tab is selected
    getSelectedResultsTab = function() {
        if ($('.tabNav a.active').length > 0) {
            return $('.tabNav a.active').attr('id');
        } else return null;
    }

    //determine which filterPanel is current
    getFilterPanelParent = function() {
        var tab = getSelectedResultsTab();
        if (tab) {
            var panel = tab.replace(/^tab/, '#filterPanel');
            return panel;
        } else return document;
    }

    //pulls location (lat/long) data for specified result element
    lcnData = function(el) {
        var data = {
            number: parseInt($('.number', el).text(), 10),
            name: $('.name', el).text(),
            place: $('.place', el).text(),
            latitude: $('.latitude', el).text(),
            longitude: $('.longitude', el).text()
        }
        return data;
    }

    //plot markers for the current set of results
    plotMarkers = function(latitude, longitude) {

        var tabid = getSelectedResultsTab();
        var resultsDiv = (tabid) ? '#' + tabid.replace(/^tab/, 'tabContent') : '#listResults';
        var panl = getFilterPanelParent();

        //stop the rotating images and stay on the map
        ////$('#featuredNav li#map a').click();

        if (window.gmap == null) {
            setMapProperties();
            getGoogleMap();
        }

        //clear any current map markers
        window.gmap.clearOverlays();
        window.geocoder = new GClientGeocoder();

        //create a boundary to contain the map zoom
        var bounds = new GLatLngBounds();

        //loop through the results grabbing lat/long
        $('div.mapmarker', resultsDiv).each(function() {
            var data = lcnData(this);

            if (jQuery.trim(data.latitude).length > 0 || jQuery.trim(data.longitude).length > 0) {
                // Lat-Lng should be stored in the database
                if (!isNaN(data.latitude) && !isNaN(data.longitude)) {
                    if (data.latitude == 0 && data.longitude == 0) {
                    } else {
                        var point = new GLatLng(data.latitude, data.longitude);
                        bounds.extend(point);
                        var marker = createMarker(point, data.number, data.name, data.place);
                        window.gmap.addOverlay(marker);
                    }
                }
            } else {
                // If Lat-Lng isn't stored, we'll geocode the listing
                geocoder.getLatLng(data.name + ' ' + data.place, function(point) {
                    if (point) {
                        var marker = createMarker(point, data.number, data.name, data.place);
                        window.gmap.addOverlay(marker);
                    }
                });
            }
        });
        //center up the display to fit all the results
        if (!bounds.isEmpty()) window.gmap.setCenter(bounds.getCenter(), window.gmap.getBoundsZoomLevel(bounds));
    }

    //recenter and zoom the map for the clicked item
    mapThis = function(el) {
        var data = lcnData(el);
        var point = new GLatLng(data.latitude, data.longitude);
        window.gmap.setCenter(point, 12);

        $('#featuredNav li#map a').click();
    }

    var filtercatCode;

    //update the amenities when a category is clicked... but not on tabbed pages.
    $('.filterCat > .refinerLink').click(function() {
        filtercatCode = '';
        $('.filterCat > input').each(function() {
            $(this).next('.refinerLink').toggleClass('refined', this.checked);
            if (this.checked) {
                filtercatCode = $(this).val();
            }
        });

        var params = '';
        if ($('input.pagetype').val() == "SMI_EAT") {
            var params = { CategoryCode: '', SubCategoryCode: filtercatCode };
            GetAmenitiesHTML(params, function(xml) {
                $("[id^='amenityFilterContainer']").html($('string', xml).text());
                getFilteredList();
            });
        } else if ($('input.pagetype').val() == "SMI_DEAL") {
            var params = { CategoryCode: '', SubCategoryCode: '' };
            GetAmenitiesHTML(params, function(xml) {
                $("[id^='amenityFilterContainer']").html($('string', xml).text());
                getFilteredList();
            });
        } else {
            var params = { CategoryCode: filtercatCode, SubCategoryCode: '' };
            GetAmenitiesHTML(params, function(xml) {
                $("[id^='amenityFilterContainer']").html($('string', xml).text());
                getFilteredList();
            });
        }
    });

    // update when....
    $('.resultCategoryBlock > .resultCategoryHdr').live('click', function() {
        ilnyfilter_catCode = '';
        ilnyfilter_subcatCode = '';
        var params = { CategoryCode: ilnyfilter_catCode, SubCategoryCode: ilnyfilter_subcatCode };
        GetAmenitiesHTML(params, function(xml) {
            $("[id^='amenityFilterContainer']").html($('string', xml).text());
        });

        $('.filterSubcat > input').each(function() {
            $(this).next('.refinerLink').removeClass('refined');
        });
        getFilteredList();
    });


    // update results when a subcategory item is selected (in See & Do)

    $('.filterSubcat > .refinerLink').live('click', function() {
        $('.resultCategoryBlock > .resultCategoryHdr').children('h3').removeClass("selectedCat");
        if (($(this).hasClass('refinerLink')) && ($(this).hasClass('refined'))) {
            ilnyfilter_subcatCode = '';
            $(this).removeClass('refined');
            $('.resultCategoryBlock > .resultCategoryHdr').children('h3').addClass("selectedCat");
            if ($('.tabNav').length == 0) {
                var params = { CategoryCode: '', SubCategoryCode: '' };
                GetAmenitiesHTML(params, function(xml) {
                    $("[id^='amenityFilterContainer']").html($('string', xml).text());
                });
            }
        } else {
            ilnyfilter_subcatCode = $(this).parent('.filterSubcat').find('input').val();
            $(this).addClass('refined');
            $(this).parent('.filterSubcat').siblings('.filterSubcat').children('.refinerLink').removeClass('refined');
            if ($('.tabNav').length == 0) {
                var params = { CategoryCode: ilnyfilter_catCode, SubCategoryCode: ilnyfilter_subcatCode };
                GetAmenitiesHTML(params, function(xml) {
                    $("[id^='amenityFilterContainer']").html($('string', xml).text());
                });
            }
        }
        getFilteredList();
    });

    // update results when an amenity is selected
    $('.filterAmenity > .refinerCheck').live('click', function() {
        $('.filterAmenity > input').each(function() {
            $(this).next('.refinerCheck').toggleClass('amenityBack', this.checked);
        });
        getFilteredList();
    });

    // update results when an theme is selected
    $('.filterThemes > .refinerCheck').live('click', function() {
        $('.filterThemes > input').each(function() {
            $(this).next('.refinerCheck').toggleClass('amenityBack', this.checked);
        });
        getFilteredList();
    });

    // update results with the city textbox is exited
    $('input.cityInput').each(function() {
        if ($(this).val() == '') {
            $(this).attr('value', 'Type in a City');
            $(this).val($(this)[0].title);
        }
    });
    $('div.inputCityClassClick').each(function() {
        // Click Event (Button)
        $(this).children("[id^='citySubmit']").unbind();
        $(this).children("[id^='citySubmit']").click(function() {
            getFilteredList();
            return false;
        });

        // Enter Key
        $(this).children('input.cityInputKeyEvent').bind("keydown", function(event) {
            if (event.keyCode == 13) {
                $(this).siblings("[id^='citySubmit']").click();
                return false;
            } else {
                return true;
            }
        });

        $("[id^='citySubmit'].arrowRight").each(function() {
            $(this).hover(function() {
                $(this).css('background-image', 'url(/Images/arrows-right-over.jpg)');
            }, function() {
                $(this).css('background-image', 'url(/Images/arrows-right.jpg)');
            }).focus(function() {
                $(this).css('background-image', 'url(/Images/arrows-right-over.jpg)');
            }).blur(function() {
                $(this).css('background-image', 'url(/Images/arrows-right.jpg)');
            });
        });
    });

    // update results when an theme is selected
    $('.filterLodge > .refinerLink').click(function() {
        $('.filterLodge > input').each(function() {
            $(this).next('.refinerLink').toggleClass('refined', this.checked);

            if (this.checked)
                filtercatCode = $(this).next().attr("id").replace(/filterLodge-/, '');

        });
        getFilteredList();
    });

    $('input.startDate, input.endDate').each(function() {
        if ($(this).val() == "") {
            $(this).css('background-image', 'url(/Images/datePickerDefault.jpg)');
        }
        $(this).focus(function() {
            $(this).css('background-image', 'none');
        }).blur(function() {
            if ($(this).val() == '') {
                $(this).css('background-image', 'url(/Images/datePickerDefault.jpg)');
            }
        }).change(function() {
            $(this).css('background-image', 'none');
        });
    });

    $('input.startDate').datePicker({
        clickInput: true,
        startDate: '01/01/2009',
        showYearNavigation: false
    }).click(function() {
        $('div#dp-popup').css('margin-left', '140px');
    });

    $('input.endDate').datePicker({
        clickInput: true,
        startDate: '01/01/2009',
        showYearNavigation: false
    }).click(function() {
        $('div#dp-popup').css('margin-left', '140px');
    });

    $('input.startDate').change(function() {
        getFilteredList();
    }).bind("keydown", function(event) {
        if (event.keyCode == 13) {
            getFilteredList();
        }
    });


    // update results when the end date is changed in the filters
    $('#featuredOffersOptions').change(function() {
        if ($(this).val() != '')
            getFilteredList();
    });
    // update results when the end date is changed in the filters
    $('input.endDate').change(function() {
        getFilteredList();
    }).bind("keydown", function(event) {
        if (event.keyCode == 13) {
            getFilteredList();
        }
    });

    //add an everlasting mapthis handler
    $('div.bubble').live('click', function() {
        mapThis($(this).parents('.stayResults'));
    });

    pagerWhereToStayClick = function(p, id) {
        getFilteredList(p);
    }

    $(document).ready(function() {
        if ($('#latitude').val() != '' && $('#longitude').val() != '') {
            plotMarkers($('#latitude').val(), $('#longitude').val());
        }
    });

});

function InitializeListingsLayout() {
    // All events for listing pages    

    //update the list when various options are clicked
    $("[id^='DDFilterByLocation']").change(function() {

        var regionArr = $("[id^='DDFilterByLocation']").val().split('|');

        var lat = regionArr[1];
        var lon = regionArr[2];
        var zoom = regionArr[3];
        if (!isNaN(lat) && !isNaN(lon) && !isNaN(zoom)) {
            mapload(640, 238, lat, lon, zoom);
        }
        getFilteredList();
    });

    //add default text to the city-input
    $('input.cityInput').focus(function() {
        if ($(this).val() == $(this)[0].title) {
            $(this).removeClass('defaultText');
            $(this).val('');
        }
    });

    $('a.#tabStay').click(function() {
        getFilteredList();
    });
    $('a.#tabDeals').click(function() {
        getFilteredList();
    });

    $('a.#tabAbout').click(function() {
        mapload(638, 238, $('#latitude').val(), $('#longitude').val(), 13, '')
    });

    $('a.#tabEvents').click(function() {
        getFilteredList();
    });

    $('a.#tabEat').click(function() {
        getFilteredList();
    });

    $('a.#tabSeeAndDo').click(function() {
        getFilteredList();
    });

    $(".resultItemsBlock").css("display", "none");


}

