// Global variables
// Labels
//var lblEnterPostCode = "Enter Postcode...";
//var lblPostCodeNotFound = "Postcode not found!";
//var lblDistanceInputErrorMessage = "Please check you have selected your post code and distance";
//var lblLoading = "Loading...";
//var lblBasketFull = "Your comparison basket is full. Please remove an item before adding a new one.";
//var lblSelectionDescription = "(Select up to {0} from the list below - You have selected {1})";
//var lblYes = "Yes";
//var lblNo = "No";
//var lblRoomsAndChalets = " rooms and chalets";
//var lblChalets = " chalets";
//var lblRooms = " rooms";
//var lblHours = "hr";
//var lblMinutes = "mins";
//var lblMiles = "miles";
//var lblCheckAvailabilty = "Check Availabilty";

var lblEnterPostCode = "Enter Postcode...";
var lblPostCodeNotFound = "Postcode not found!";
var lblDistanceInputErrorMessage = "Please check you have selected your post code and distance";
var lblLoading = "Loading...";
var lblBasketFull = "Your comparison basket is full. Please remove an item before adding a new one.";
var lblSelectionDescription = "(Select up to {0} from the list below - You have selected {1})";
var lblYes = "Yes";
var lblNo = "No";
var lblRoomsAndChalets = " rooms and chalets";
var lblChalets = " chalets";
var lblRooms = " rooms";
var lblHours = "hr";
var lblMinutes = "mins";
var lblMiles = "miles";
var lblCheckAvailabilty = "Check Availability";

// Ajax User Controls to Load
var lblCompareHotelsPopupPage = "/Ajax.svc/RenderUserControl?path=~/_Controls/SiteComparisonList.ascx&";
var lblFilterResultsPage = "/Ajax.svc/RenderUserControl?path=~/_Controls/SiteComparisonFilterResults.ascx&";
var lblFilterToolsPage = "/Ajax.svc/RenderUserControl?path=~/_Controls/SiteComparisonFilterTool.ascx&";
var lblSaveStatePage = "/Ajax.svc/RenderUserControl?path=~/_Controls/SiteComparisonSaveState.ascx&";
var lblItemAsJsonPage = "/Ajax.svc/RenderUserControl?path=~/_Controls/SiteComparisonItemAsJSON.ascx&";

// Images to be pre-loaded
//var lblOverlayBlackBackgroundImage = "/images/trans-black.png";
//var lblOverlayWhiteBackgroundImage = "/images/trans-white.png";
//var lblOverlayBlackLodaingImage = "/images/black-ajax-loader.gif";
//var lblOverlayWhiteLodaingImage = "/images/white-ajax-loader.gif";
//var lblOverlayLogoImage = "/images/overlay-logo.gif";
//var lblOverlayMainLoadingImage = "/images/ajax-loader.gif";

var lblOverlayBlackBackgroundImage = "/images/35-45297trans-black.png";
var lblOverlayWhiteBackgroundImage = "/images/35-45298trans-white.png";
var lblOverlayBlackLodaingImage = "/images/35-45278black-ajax-loader.gif";
var lblOverlayWhiteLodaingImage = "/images/35-45300white-ajax-loader.gif";
var lblOverlayLogoImage = "/images/35-45291overlay-logo.gif";
var lblOverlayMainLoadingImage = "/images/35-45277ajax-loader.gif";

// Images used in overlay
//var lblOneRosetteImage = "/images/one-rosette-icon.png";
//var lblTwoRosetteImage = "/images/two-rosette-icon.png";
//var lblYesImage = "/images/yes-icon.gif";
//var lblNoImage = "/images/no-icon.gif";
//var lblInfoImage = "/images/info-icon.gif";
//var lblCheckAvailabiltyImage = "/images/check-availabilty-btn.gif";

var lblOneRosetteImage = "/images/35-45290one-rosette-icon.png";
var lblTwoRosetteImage = "/images/35-45299two-rosette-icon.png";
var lblGoldStarImage = "/images/35-50167gold-star-icon.png";
var lblWhiteStarImage = "/images/35-50168white-star-icon.png";
var lblYesImage = "/images/35-45301yes-icon.gif";
var lblNoImage = "/images/35-45289no-icon.gif";
var lblInfoImage = "/images/35-45287info-icon.gif";
var lblCheckAvailabiltyImage = "/images/35-45279check-availability-btn.gif";

// Html chunks
var selectedResultsOverlayHtml = '<span class="overlay-selected">&#160;</span>';
var removeLinkHtml = '<a href="{0}" class="remove-from-comparison remove-property" rel="{1}">Remove</a>';
var offerTextHtml = '<p class="offer">{0}</p>';
var imgHtml = '<img src="{0}" alt="{1}">';
var yesSpanHtml = '<span class="yes">{0}</span>';
var noSpanHtml = '<span class="no">{0}</span>';
var infoSpanHtml = '<span class="info-icon" title="{0}">{1}</span>';
var propertyItemHtml = '<div class="property-item">{0}</div>'
var emptyTableCellHtml = '<td>&#160;</td>';
var emptyBasketItemHtml = '<li class="property-item empty">&#160;</li>';
var overlayLoadingHtml = '<div class="overlay"><div class="loader">{0}</div></div>';
var propertyItemEmptyHtml = '<td class="property-column-empty">&#160;</td>';
var checkavailabiltyHtml = '<a class="property-check-availability-link" href="{0}"><img alt="'+lblCheckAvailabilty+'" src="'+lblCheckAvailabiltyImage+'"></a>';

var distanceFormat = "{0}{1} {2}";

// Global parameters
var maxItemsInBasket = 4;

// Google Search Parameters
//array of property geo locations
//var hotelGeos = new Array("53.085294,-2.502827", "50.685566,-1.070969", "53.260998,-3.501757", "52.513551,1.748117", "50.87322,-2.893838", "52.505235,1.737488", "52.01743036932765,-2.6499366760253906", "50.78363651282668,-0.9614324569702148", "51.431263,-1.562171", "54.041963,-1.543037", "50.706021,-1.513444", "50.792468,-1.012256", "53.233574,-1.044931");
//var lblGoogleGeoCodeErrorMessage = "Sorry, we were unable to geocode address";
//var lblGoogleNoFilterResultsMessage = "No results to Filter";
var lblGoogleGeoCodeErrorMessage = "Sorry, we were unable to geocode address";
var lblGoogleNoFilterResultsMessage = "No results to Filter";

var currentGeo = 0;
var count = 0;

//google map popup variables
var centerPoint = '53.527247970102465, -3.0322265625';
var zoom = 6;
var mapWidth = 600;
var mapHeight = 500;
var iColour = '0x7F1F46';
var pColour = '0xBDB296';
var pLetter = 'W';

var gdir, geocoder, link, count;

var googleStaticMapLink = 'http://maps.google.com/maps/api/staticmap?center=' + centerPoint + '&zoom=' + zoom + '&size=' + mapWidth + 'x' + mapHeight + '&sensor=false&markers=size:mid|color:'+ iColour +'|{0},{1}&markers=size:mid|color:'+ pColour +'|label:'+ pLetter +'';

$(document).ready(function(){
    
    // initailise everything used by ajax
    init();
    
    // iniailise everything that needs initailising once
    initGoogleMapSearch();
    
    // initailise basket links
    initRemoveFromComaprison();
    
    // change the compare properties link
    updateCompareLink($('.compare-properties a').attr("href"));
    
    $('.remove-all').click(function(){
    
        $('.filter-basket ol li').each(function(){
            $(this).children('a').each(function(){
                showResultsItem($(this).attr("rel"));
            });
            $(this).remove();
        });
        
        for(var i = 0; i < maxItemsInBasket; i++){
            $('.filter-basket ol').append(emptyBasketItemHtml);
        }
        
        $('.filter-basket ol li:first').addClass('first');
        $('.filter-basket ol li:last').addClass('last');
        
        updateBasketStatusText();
        hideBasketOptions();
        
        updateLinksWithBasketAction();
        
        return false;
    });
    
    // assign show/ hide of comparison basket
    $('.filter-basket .handle').click(function(){
		$(this).toggleClass('down').siblings('.toggle').slideToggle();
	})

    // hide basket if empty
	if($('.filter-basket li.empty').length == maxItemsInBasket){
	    $('.filter-basket .toggle').toggle();
	}else{
		$('.filter-basket .handle').addClass('down');
	}
    
    // Pre-load ajax loading images
    var imgOverlayBlackBg = new Image();
    imgOverlayBlackBg.src = lblOverlayBlackBackgroundImage;
    var imgOverlayWhiteBg = new Image();
    imgOverlayWhiteBg.src = lblOverlayWhiteBackgroundImage;
    var imgOverlayBlackLoading = new Image();
    imgOverlayBlackLoading.src = lblOverlayBlackLodaingImage;
    var imgOverlayWhiteLoading = new Image();
    imgOverlayWhiteLoading.src = lblOverlayWhiteLodaingImage;

});

// Initailise all items that are changed using ajax
function init(){
	// print button
	printList();
	// hide/ show of filters
	hideShow();
	//
	if($('.filter-basket').length > 0){
		overlayCompare();
	}
	// initialise filters
    initLinksFilters();
    initHotelFilter();
    initDistanceFilter();
    
    // initailise the 'add to compare' link
    initAddToComparison();
    // set result item to the same height
    $('#filter-list div.property-text-info').equalHeights();
	$('#map-list div.property-text-info').equalHeights();
	$('#list-properties div.property-text-info').equalHeights();
    $('#list-properties .property-item, #filter-list .property-item').equalHeights();
}

 // initailise the 'add to compare' link
function initAddToComparison(){
    $('.add-to-comparison').click(function(e){
		e.preventDefault();
        if($('.filter-basket .empty').length > 0){
        
        	// show buttons if first item in basket
            if($('.filter-basket .empty').length == maxItemsInBasket){
                $('.compare-properties').slideDown();
                $('.remove-all').slideDown();
				if(!$('.filter-basket h2').hasClass('down')){
					$('.filter-basket h2').addClass('down')
					$('.filter-basket .toggle').slideDown();
				}

            }
            
            // get the site code of the basket item
            var siteCode = $(this).attr('rel');
            // create remove link
            var link = removeLinkHtml.replace('{0}', $('.filter-url').val()).replace('{1}', siteCode);
            // get dom objects of results and basket items
            var basketItem = $('.filter-basket .empty:first');
            var resultsItem = $('.results-property-' +siteCode);
            // set the basket html
            basketItem.html(link + resultsItem.children('.property-heading').html());
            // change basket item classes from empty item
            basketItem.removeClass('empty');
            basketItem.addClass('comparison-property-' +siteCode);
            // change results item to a selected state
            resultsItem.addClass('selected');
            resultsItem.append(selectedResultsOverlayHtml);
            
            // update the 'you can 4 items in your basket. you selected x'
            updateBasketStatusText();
            // initiaise remove link
            initRemoveFromComaprison(siteCode);
            // maintain links state on page
            updateLinksWithBasketAction();
            
            if(ie6){
                pngFix();
            }
            
        }else{
        	// alert that the basket is full
            message(lblBasketFull);
        }
        // cancel link action
        return false;
    });
}

// initailise remove from basket link
function initRemoveFromComaprison(siteCode){
	
	// grab single link or all
	var extraSelector = '';
    if(arguments.length > 0){
        extraSelector = "[rel='"+siteCode+"']";
    }
    
    // add click action
    $('.remove-from-comparison'+extraSelector).click(function(){
    	// which item
        var siteCode = $(this).attr('rel');
        // remove item from basket and deselect results item
        removeItemFromBasket(siteCode);
        // cancle link action
        return false;
    });
}

// initailse Google Distance filter
function initDistanceFilter(){
	// show html
    $('.distance-filter').show();
    
    // hide map link
    $('.googlemap-link').hide();
    $('.googlemap-link-container').hide();
	
	// add click action
    //$('.distance-filter-button').click(function(e){
    $('.distance-filter-miles').change(function(e){
    	// call filter
    	e.preventDefault();
        doDistanceFilter();
        // cancel link action
        return false;
    });
    
    // grab the form submit action
    $("#aspnetForm").submit(function (){
    	// cancel form submission
    	doDistanceFilter();
        return false;
    });
	
	// grab enter key input on text field
    $('.distance-filter-post-code').keyup(function (e) {
    	// enter key
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)){
        	// call filter
            $('.distance-filter-button').click();
        }
    });
    
    initGoogleMapLink();
}

function initGoogleMapLink(){
    if(typeof window.getHotelLocations == 'function'
			&& getHotelLocations().length > 0) {
		var locations = getHotelLocations();
		
        if($('select.distance-filter-miles').val().length > 0
            && $('.distance-filter-post-code').val() != lblEnterPostCode 
                && $('.distance-filter-post-code').val() != "" 
                    && $('.distance-filter-distance-results').val() != ""){
           
            var currentLocation = $('.distance-filter-geo-location').val().split(",");
            var link = googleStaticMapLink.format(currentLocation[0], currentLocation[1]);
            
            var selectedLocations = $('.distance-filter-distance-results').val().split("|");
            //alert(selectedLocations.length)
            for(var i = 0; i < selectedLocations.length; i++){
                
                var loc = selectedLocations[i].split(",");
                var geo = "";
                //alert($(".add-to-comparison[rel='"+loc[0]+"']").length);
                if($(".add-to-comparison[rel='"+loc[0]+"']").length > 0){
                    for(var j = 0; j < locations.length; j++){
                    //alert(locations[j][0] +" == "+loc[0]);
                        if(locations[j][0] == loc[0]){
                            geo = locations[j][1];
                            break;
                        }
                    }
                }
                
                if(geo != ""){
                    link += "|" + geo;
                }
            }

            //add .png to end of query string so fancy box treats it as an image    
            $('.googlemap-link-container').show();
            $('.googlemap-link').attr('href',link + '|.png');
            //initilize fancybox for google map
            $('.googlemap-link').show().fancybox({
                width: mapWidth + 20,
                height: mapHeight + 20,
                padding: 0,
                titleShow: false,
                transitionIn: 'none',
				transitionOut: 'none',
				showCloseButton: false,
                hideOnContentClick: false
            });
        }
    }   
}

function initGoogleMapSearch(){
	//add google geogoder and directions
    geocoder = new GClientGeocoder();
    gdir = new GDirections();
    	
    //listener for added directions	
    GEvent.addListener(gdir, "load", function(){
    
        var locations = new Array();
        
        if(typeof window.getHotelLocations == 'function'
			&& getHotelLocations().length > 0) {
			locations = getHotelLocations();
        }
        
	    //current directions driving distance in miles
	    var drivingDist = parseFloat(Math.round(gdir.getDistance().meters / 1609.344)*1) / 1;
    	
	    //current directions driving time in seconds
	    var drivingTime = gdir.getDuration().seconds;
    	
	    //convert seconds to hours and minutes
	    var hours = Math.floor(drivingTime / 3600);
	    var mins = Math.floor(drivingTime / 60) - (hours * 60);
    	
	    //get max miles value
	    var maxMiles = $('select.distance-filter-miles').val();
    	
    	if(currentGeo == 0){
    	    $('.distance-filter-distance-results').val("");
    	    $('.distance-filter-distance-all-results').val("");
    	}
    	
    	var result = "{0},{1},{2},{3}".format(locations[currentGeo][0], drivingDist, hours, mins);
    	var allResults = $('.distance-filter-distance-all-results').val();
    	var appender = (allResults.length == 0) ? "" : "|";
    	
    	$('.distance-filter-distance-all-results').val(allResults + appender + result);
    	
    	var addToResults = false;
    	
	    //check if current property is within range
	    //alert(maxMiles.indexOf(','));
	    if( maxMiles.indexOf('|') < 0
	        && drivingDist <= maxMiles){
    	   	
	       addToResults = true;
		    
	    }else if(maxMiles.indexOf('|') >= 0){
	        var range = maxMiles.split('|');
	        var min = range[0];
	        var max = range[1];
	    
	        if(drivingDist >= min
	            && drivingDist <= max){
	            addToResults = true;
	        }
	    }
    	
    	if(addToResults){
		    var curentResults = $('.distance-filter-distance-results').val();
		    appender = (curentResults.length == 0) ? "" : "|";
		    
		    $('.distance-filter-distance-results').val(curentResults + appender + result);
    	}
    	
	    currentGeo++;
    	
	    //recurse showLocation function for each property
	    if(currentGeo < locations.length) {
		    setTimeout('showLocation(currentGeo)',100);
	    }else{
		    //reset currentGeo
		    currentGeo = 0;
		    
		    /*
		    //add .png to end of query string so fancy box treats it as an image
		    
		    var link = $('.googlemap-link').attr('href');
		    $('.googlemap-link').attr('href',link + '|.png');
		    //initilize fancybox for google map
		    $('.googlemap-link').show().fancybox({
			    'frameWidth': mapWidth + 20,
			    'frameHeight': mapHeight + 20,
			    'padding': 0,
			    'hideOnContentClick': false
		    });
		    */
		    //alert("apply filter");
		    var location = $('.filter-url').val() + getParametersFromFormValues();
		    // call filter
            applyFilter(location);
		    
		    return;
	    }
    	
    });
}

// initialise Hotel filter
function initHotelFilter(){
 	// hide update button
    $('.hotel-filter-button').hide();
	
	// grab onchange action
    $('.hotel-filter').change(function(){
		// build ajax query
        var location = $('.filter-url').val() + getParametersFromFormValues();
		// call filter
        applyFilter(location);
    });
}

// initialise Link Filters
function initLinksFilters(){
	// grab filter link actions
    $('.filter-comparison, .remove-from-filter, .remove-all-from-filter').click(function(){
    	// call filter
        applyFilter($(this).attr("href"));        
        // cancel link action
        return false;
    });
}


// initialise adding property to comparison in overlay mode 
function initOverlayPropertyAddLinks(position){
	// all or single link(s)
    var extraSelector = '';
    if(arguments.length > 0){
        extraSelector = '.empty-cell-'+position+' ';
    }

	// grab click
    $(extraSelector +".property-dropdown a").click(function(){

        // get query string params
        var location = $(this).attr("href");
        var params = location.substring(location.indexOf("?") + 1, location.length);  
        // find column position 
        var topCell = $(this).parents('.property-column-empty');
        
        // load property information (JSON Object)
		$.ajax({ 
	        url: lblItemAsJsonPage + params, 
	        context: document.body, 
	        success: function(output){
	          // convert string to JSON
	          var obj = eval("(" + output + ')');
	          // display property details 
	          loadNewOverlayProperty(obj, topCell.attr("rel"));
	        }
    	});
            

        // cancel link action
        return false;
    });
}

// display dynamically loaded property
function loadNewOverlayProperty(obj, count){

	// set hotel object 
    var hotel = obj.Sites.Site[0];
    
    // loop cells of the selected column
    $('.empty-cell-' + count).each(function() {
        // change classes from empty to used
        $(this).removeClass('empty-cell-' + count);
        $(this).removeClass('property-column-empty');
        $(this).addClass('property-cell-' + hotel.site_code);
        $(this).attr("rel", "p-" + hotel.site_code);

        // show map icon
        $("#icon-p-" + hotel.site_code).show();

        // decide what data to display
        var identity = $(this).parents('tr:eq(0)').attr("rel");
        switch (identity) {
            // general hotel information 
            case "intro":
                showComparisonIntro(this, hotel);
                break;
            // hotel type 
            case "type":
                $(this).text(hotel.Types[0].Type[hotel.Types[0].Type.length - 1]);
                break;
            // hotel region 
            case "region":
                $(this).text(hotel.region);
                break;
            // number of rooms 
            case "number-of-rooms":
                $(this).text(numberOfRoomsOrChalets(hotel));
                break;
            // number of disability accessible rooms 
            case "disabled-rooms":
                $(this).text(hotel.disabilityaccessrooms);
                break;
            // hotel fine dining option 
            case "fine-dining":
                $(this).html(yesOrNoImage(hasDiningOption(hotel, "finedining")));
                break;
            // hotel cabret dinig option 
            case "cabaret-dining":
                $(this).html(yesOrNoImage(hasDiningOption(hotel, "cabaretdining")));
                break;
            // hotel main restaurant option 
            case "main-restaurant":
                $(this).html(yesOrNoImage(hasDiningOption(hotel, "mainrestaurant")));
                break;
            // hotel what is special     
            case "whats-special":
                $(this).html(hotel.WhatMakesUsSpecial);
                break;
            // hotel local attractions    
            case "local-attractions":
                $(this).html(hotel.LocalAttractions);
                break;
            // hotel activities and features 
            case "feature":
                yesOrNoToFeature(hotel, this);
                $(this).find('span.info-icon').tooltip({
                    delay: 0,
                    showURL: false,
                    top: 25,
                    left: -65,
                    track: true
                }).find('img').attr('alt', '');
                break;
            // hotel activities and features 
            case "distance":
                $(this).text(getOverlayDistanceAndTimes(hotel));
                break;
            // hotel prices 
            case "break-prices":
                $(this).text("from �" + hotel.pricesfrom + "pp");
                break;
            case "availability":
                var url = replaceHrefParameter($('.comparison-check-availability-link').val(), "ht", hotel.site_code);
                $(this).html(checkavailabiltyHtml.format(url));
                break;
        }

    });
    
    // set remove link rel value
    $('.property-cell-'+hotel.site_code+' .remove-property').attr("rel", hotel.site_code);
    
    // update the hotels in comparison
    updateHotelsInComparisonFormValue();
    // update remove links
    updateRemoveFromComparisonLinks();
    // update empty columns names
    updateEmptyColumnClass();
    // generate dropdowns
    replaceOverlayDropDowns();
    // initailise remove link
    initOverlayRemoveFromComparison(hotel.site_code);
    // set the height of the overlayer
    fixHeight();
    
    if(ie6){
        pngFix();
    }
    
    setOverlayEqualHeight();
    //propertyDropdown();
}

function getOverlayDistanceAndTimes(hotel){
    var allLocations = $('.distance-filter-distance-all-results').val().split("|");
    
    for(var i = 0; i < allLocations.length; i++){
        var loc = allLocations[i].split(",");
        if(loc[0] == hotel.site_code){
            var time = "";
            if(loc[2].length > 0 
                && loc[3].length <= 0){
                time = "("+loc[2]+ lblHours+")";
            }else if(loc[2].length <= 0 
                    && loc[3].length > 0){
                time = "("+loc[3]+ lblMinutes+")";
            }else {
                time = "("+loc[2]+ lblHours+" "+loc[3]+ lblMinutes+")";
            }
            
            return distanceFormat.format(loc[1], lblMiles, time);
        }
    }
    
    return "";
}

function setOverlayEqualHeight(){
    $('.comparison-table-table div.property-text-info').equalHeights();
	$('.comparison-table-table .property-item').equalHeights();
}

// initlialise remove from overlay link
function initOverlayRemoveFromComparison(siteCode){
    $('#comparison-table .remove-property[rel='+siteCode+']').click(function (){

        // get current site code
        var siteCode = $(this).attr("rel");
        // remove property from the table
        $('.property-cell-'+siteCode).remove();
        
        // create new empty column
        $('.data-row').each(function(){
            
            var identity = $(this).attr("rel");
            switch(identity){
                case "intro" :
                    $(this).append(propertyItemEmptyHtml);
                    break;
                default:
                    $(this).append(emptyTableCellHtml);
                    break;
            }
            
        });
        
        // hide map icon
        $("#icon-p-"+siteCode).hide();
        
        // update the hotels in comparison
        updateHotelsInComparisonFormValue();
        // update remove links
        updateRemoveFromComparisonLinks();
        // update empty columns
        updateEmptyColumnClass();
        // generate 
        replaceOverlayDropDowns();
        fixHeight();
        setOverlayEqualHeight();
        saveComparisonState($(this).attr("href"));
        
        return false;
    });
}

function replaceOverlayDropDowns(){
    $('.property-column-empty').each(function (){
        $(this).html($('.hotel-options-placeholder').html());
    });
    propertyDropdown();
    initOverlayPropertyAddLinks();
    updateFromAddToComparisonDropDownLinks();

     
    var currentHotels = $("input[name='comparison-hotels']").val().split(",");
    
    for(var i = 0; i < currentHotels.length; i++){
        removeFromAddToComparisonDropDownList(currentHotels[i]);
    }
}

function updateEmptyColumnClass(){
//alert($('.property-column-empty').length);
    $('.property-column-empty').each(function(index){
        
        var count = index + 1;
        var currentPosition = $(this).attr("rel");
        
        var tableIndex = $('.data-row td').index(this);
        $('.data-row').each(function(){
            $(this).find('td').eq(tableIndex).removeClass('empty-cell-' +currentPosition);
        });

        $('.data-row').each(function(){
            $(this).find('td').eq(tableIndex).addClass('empty-cell-' +count);
        });
        
        $(this).attr("rel", count);
        
    });
}

function updateHotelsInComparisonFormValue(){
    var value = "";
    var appender = "";
    $('#comparison-table .remove-property').each(function(){
        value += appender + $(this).attr("rel");
        if(appender == ""){
            appender = ",";
        }
    });
    //alert(value);
    
    $("input[name='comparison-hotels']").attr("value", value);
}

function updateRemoveFromComparisonLinks(){
    var currentBasket = $("input[name='comparison-hotels']").val()

    $('#comparison-table .remove-property').each(function(){
        var link = $(this).attr("href");
        var page = (link.indexOf("?") >= 0) ? link.substring(0, link.indexOf("?")) : link;
        var hotelParam = removeParameterValue($(this).attr("rel"), currentBasket);
        
        $(this).attr("href", page +"?ht="+ hotelParam);
    });
}

function updateFromAddToComparisonDropDownLinks(){
    var currentBasket = $("input[name='comparison-hotels']").val();
    $('#comparison-table .property-column-empty li a').each(function (){
        //$(this).remove();
        var link = $(this).attr("href");
        var page = (link.indexOf("?") >= 0) ? link.substring(0, link.indexOf("?")) : link;
        var hotelParam = addParameterValue($(this).attr("rel"), currentBasket);
        $(this).attr("href", page +"?ht="+ hotelParam);
    });
}

function numberOfRoomsOrChalets(hotel){
    if(hotel.hotelrooms == 'true' 
        && hotel.chalets == 'true'){
        return hotel.rooms + lblRoomsAndChalets;
    }   
    if(hotel.hotelrooms == 'true' ){
        return hotel.rooms + lblRooms;
    }
    
    if(hotel.chalets == 'true' ){
        return hotel.rooms + lblChalets;
    }
}


function yesOrNoToFeature(hotel, obj){
    var searchFor = $(obj).parents('tr:eq(0)').text().trim();
    var searchObj = hotel.ActivitiesFacilities[0].ActivitiesFacility;
    
    for(var i = 0; i < searchObj.length; i++){
    //alert(searchFor +" : "+ searchObj[i].value +" : "+searchObj[i]);
        if(searchFor.indexOf(searchObj[i].value) >= 0){
			//alert(searchObj[i].info);
            var infoHtml = "";
           
            //alert($(obj).find('.info-icon').html())
			if(searchObj[i].info != ""){
				infoHtml = infoSpanHtml.format(searchObj[i].info ,imgHtml.format(lblInfoImage, "i"));
				//$(obj).attr("title", searchObj[i].info);
                //modalExtras();
		        
			}
			$(obj).html(yesOrNoImage(true) + infoHtml);
	        return;
        }
        
        if(searchFor.indexOf(searchObj[i].toString()) >= 0){
            $(obj).html(yesOrNoImage(true));
            return;
        }
    }
    
    $(obj).html(yesOrNoImage(false));

}

function yesOrNoImage(isYes){
    if(isYes){
        return yesSpanHtml.format(imgHtml.format(lblYesImage, lblYes));
    }else{
        return noSpanHtml.format(imgHtml.format(lblNoImage, lblNo));
    }
}

function hasDiningOption(hotel, option){
    var searchFor = option;
    var searchObj = hotel.Restaurants[0].Restaurant;
    for(var i = 0; i < searchObj.length; i++){
        if(searchObj[i][searchFor] == 'true'){
            return true;
        }
    }
    
    return false;
}

function removeFromAddToComparisonDropDownList(siteCode){
    $('.property-column-empty li a[rel='+siteCode+']').each(function (){
        $(this).parent('li').remove();
    });
}

function showComparisonIntro(obj, hotel) {
    //remove the Star text from the rating
    hotel.rating = hotel.rating.split(' ')[0];
    var isCountryHotel = isCountry(hotel);
    var isHotel = isWarnerHotel(hotel);
    var hasAwards = (hotel.number_of_rosettes > 0 || hotel.rating > 0) ? true : false;
    $(obj).html(propertyItemHtml.format($('.intro-placeholder .property-item').html()));

    var heading = $(obj).find('.property-heading h3');

    heading.removeClass('has-awards');
    heading.removeClass('coastal');
    heading.removeClass('country');

    if (isCountryHotel) {
        heading.addClass('country');
    } else {
        heading.addClass('coastal');
    }

    if (hasAwards) {
        heading.addClass('has-awards');

        if (hotel.rating < 1) {
            $(obj).find('.gold-star-image').remove();
            $(obj).find('.white-star-image').remove();
            $(obj).find('.aa-image').remove();
            $(obj).find('.etb-image').remove();
        }
        else if (hotel.rating > 0) {
            var html = '';
            if (isHotel) {
                $(obj).find('.etb-image').remove();
                if (hotel.rating > 1) {
                    var n = 1;
                    for (n = 1; n <= hotel.rating; n++) {
                        $(obj).find('.stars').append('<img src="' + lblGoldStarImage + '" class="gold-star-image" />');
                    }
                }
            } else {
                $(obj).find('.aa-image').remove();
                if (hotel.rating > 1) {
                    var n = 1;
                    for (n = 1; n <= hotel.rating; n++) {
                        $(obj).find('.stars').append('<img src="' + lblWhiteStarImage + '" class="white-star-image" />');
                    }
                }
            }

        }

        if (hotel.number_of_rosettes == 0) {
            $(obj).find('.rosette-image').remove();
        }

        if (hotel.number_of_rosettes > 0
            && hotel.number_of_rosettes == 1) {
            $(obj).find('.rosette-image').attr("src", lblOneRosetteImage);
        }

        if (hotel.number_of_rosettes > 0
            && hotel.number_of_rosettes == 2) {
            $(obj).find('.rosette-image').attr("src", lblTwoRosetteImage);
        }
    } else {
        $(obj).find('.property-awards').remove();
    }

    $(obj).find('.property-title').text(hotel.name);
    $(obj).find('.property-heading h4').text(hotel.region);
    $(obj).find('.property-image img').attr("src", hotel.src);
    $(obj).find('.property-description').text(hotel.Description);

    $(obj).find('.offer').remove();
    if (hotel.show_offer_text == 'true'
        && hotel.OfferText.length > 0) {
        $(obj).find('.property-description').after(offerTextHtml.replace("{0}", hotel.OfferText));
    }

    if ($(obj).find('.property-check-availability-link').length > 0) {
        $(obj).find('.property-check-availability-link').attr("href", replaceHrefParameter($(obj).find('.property-check-availability-link').attr("href"), "ht", hotel.site_code));
    }

    $(obj).find('.property-view-hotel-link').attr("href", hotel.link[0].href);
}

function isCountry(hotel){
    var searchFor = "Country";
    var searchObj = hotel.Types[0].Type;
    for(var i = 0; i < searchObj.length; i++){
        if(searchObj[i].indexOf(searchFor) >= 0){
            return true;
        }
    }
    
    return false;
}

function isWarnerHotel(hotel) {
    var searchFor = "Hotel";
    var searchObj = hotel.Types[0].Type;
    for (var i = 0; i < searchObj.length; i++) {
        if (searchObj[i].indexOf(searchFor) >= 0) {
            return true;
        }
    }

    return false;
}

var overLaysCount = 0;
var overLaysMax = 2;
    
function filterLoadComplete(){
    overLaysCount++;
    //alert(overLaysCount);
    if(overLaysCount >= overLaysMax){
        //alert("remove over lays and setting links");
        removeOverlays();
        init(); 
        updateBasketRemoveLinks();
        updateCompareLink(getParametersFromFormValues());
        overLaysCount = 0;
    }
}

function saveComparisonState(location){

    var params = location.substring(location.indexOf("?") + 1, location.length);   

    $.ajax({ 
        url: lblSaveStatePage + params, 
        context: document.body, 
        success: function(output){
          
        }
    });
}

function applyFilter(location){
    //alert("");
    var params = location.substring(location.indexOf("?") + 1, location.length);   

    addOverlays();   
    
    $.ajax({ 
        url: lblFilterToolsPage + params, 
        context: document.body, 
        success: function(output){
           $('#filter-options-display').html(output);
           $('.hotel-filter-button').hide();
           filterLoadComplete();
        }
    });

    $.ajax({ 
        url: lblFilterResultsPage + params, 
        context: document.body, 
        success: function(output){
            $('#filter-list').html(output);          
            filterLoadComplete();
        }
    });
          
    //document.location = location;
}

function getParametersFromFormValues(){
  var location = "";
  var appender = "?";
  
  $('.filter-input').each(function(){
    if($(this).val() != "" && $(this).val() != lblEnterPostCode){
        location += appender +$(this).attr("name") +"="+ $(this).val();
        if(appender == "?"){
            appender = "&";
        }
    } 
  });
  
  return location;
}

function message(msg){
    //alert(msg);
    $('body').append('<a href="#fb-message-box" style="display:none" id="fb-hidden-link"></a><div id="fb-message-box" style="display:none"><div class="wl-modal-header"><div class="wl-modal-close"><a class="close_modal" href="#">Close</a> or ESC Key</div></div><div class="wl-modal-container"><p>'+msg+'</p></div></div>');
    setTimeout(function(){
        $('#fb-hidden-link').fancybox({
                width: 350,
                height: 125,
                titleShow: false,
				showCloseButton: false,
                overlayShow: true,
		        overlayColor: '#DED6C4',
		        overlayOpacity: 0.6,
		        hideOnContentClick: false,
		        padding: 0,
		        transitionIn: 'none',
				transitionOut: 'none',
		        enableEscapeButton: true,
		        centerOnScroll: true,
			    onClosed: function(){
			        $('#fb-hidden-link, #fb-message-box').remove();
			    },
			    onComplete: function(){
			    	$('#fb-message-box').show();
			        $(".close_modal").click(function(e){
		                $.fancybox.close();
	                });
			    }
        });
        $('#fb-hidden-link').trigger('click');
    },100);

}

function updateBasketStatusText(){
    $('.select-info').html(lblSelectionDescription.replace('{0}', maxItemsInBasket).replace('{1}', maxItemsInBasket - $('.filter-basket .empty').length));
}

function removeItemFromBasket(siteCode){

    var basketItem = $('.comparison-property-' +siteCode);

    basketItem.remove();
    $('.filter-basket ol li').each(function(){
        $(this).removeClass('last');
    });
    
    $('.filter-basket ol li:first').addClass('first');
    $('.filter-basket ol').append(emptyBasketItemHtml);
    
    showResultsItem(siteCode);

    updateBasketStatusText();
    
    if($('.filter-basket .empty').length == maxItemsInBasket){
        hideBasketOptions();
    }
    
    updateLinksWithBasketAction();
}

function updateLinksWithBasketAction(){
    updateHotelsInBasketFormValue();
    
    var location = getParametersFromFormValues();
    
    updateCompareLink(location);
    
    $('.filter-comparison, .remove-from-filter, .remove-all-from-filter').each(function (){
        $(this).attr("href", replaceHrefParameter($(this).attr("href"), "ht", $("input[name='ht']").val()));
    });
    
    updateAddToComparisonLinks();
    updateBasketRemoveLinks();
    
    saveComparisonState(location);
    
}

function updateAddToComparisonLinks(){
    $('.add-to-comparison').each(function (){
        var baseUrl = $('.filter-url').val()+getParametersFromFormValues();
        $(this).attr("href", replaceHrefParameter(baseUrl, "ht", addParameterValue($(this).attr("rel"), $("input[name='ht']").val())));
    });
}

function updateBasketRemoveLinks(){
    $('.filter-basket ol li a').each(function (){
        $(this).attr("href", replaceHrefParameter($('.filter-url').val()+getParametersFromFormValues(), "ht", removeParameterValue($(this).attr("rel"), $("input[name='ht']").val())))
    });
    $('.remove-all-from-comparison').each(function(){
        $(this).attr("href", replaceHrefParameter($('.filter-url').val()+getParametersFromFormValues(), "ht", ""));
    });
    
}

function addParameterValue(key, value){
    var result = "";
    if(value.indexOf(key) < 0){
        if(value.length == 0){
            result = key;
        }else{
            result = value +","+ key;
        }
    }else{
        result = value;
    }
    return result;
}

function removeParameterValue(key, value){
    var result = "";
    var appender = "";
    //alert(value.indexOf(key));
    if(value.indexOf(key) >= 0){
        var vArray = value.split(",");
        
        for(var i = 0; i < vArray.length; i++){
            if(vArray[i] != key){
                result += appender + vArray[i];
                if(appender == ""){
                    appender = ",";
                }
            }
        }
    }else{
        result = value;
    }
    
    return result;
}

function replaceHrefParameter(target, key, value){
    
    var link = target;
    var page = link.substring(0, link.indexOf("?"));
    var querystring = link.substring(link.indexOf("?") + 1, link.length);
    var location = page;
    var appender = "?";
    
    qArray = querystring.split("&");
    
	var replaced = false;
    for(var i = 0; i < qArray.length; i++){
        parts = qArray[i].split("=");
		if (parts[1] != "") {
			location += appender + parts[0] + "=";
			if (parts[0] == key){
				location += value;
				replaced = true;
			} else {
				location += parts[1];
			}
            if(appender == "?"){
                appender = "&";
            }
		}
    }
	
	if (!replaced) {
		location += appender + key + "=" + value;
	}
	
    return location;

}

function updateCompareLink(location){
    if(location != null){
        var params = location.substring(location.indexOf("?") + 1, location.length);
        $('.compare-properties a').attr("href", lblCompareHotelsPopupPage +  params);
    }
}

function updateHotelsInBasketFormValue(){
    var value = "";
    var appender = "";
    $('.filter-basket ol li a').each(function(){
        value += appender + $(this).attr("rel");
        if(appender == ""){
            appender = ",";
        }
    });
    //alert(value);
    
    $("input[name='ht']").attr("value", value);
}

function showResultsItem(siteCode){
    var resultsItem = $('.results-property-' +siteCode);
    resultsItem.removeClass('selected');
    resultsItem.children('.overlay-selected').remove();

}

function hideBasketOptions(){
    $('.compare-properties').slideUp();
    $('.remove-all').slideUp();
}

/* Google Distance Filter */
/*
var localSearch = new GlocalSearch();

function getPointFromPostcode(postcode, callbackFunction) {	
	
    localSearch.setSearchCompleteCallback(null, 
        function() {
			
	        if (localSearch.results[0])
	        {		
		        var resultLat = localSearch.results[0].lat;
		        var resultLng = localSearch.results[0].lng;
		        var point = new GLatLng(resultLat,resultLng);

		        callbackFunction(point);
	        }else{
		        message(lblPostCodeNotFound);
	        }
        });	
		
    localSearch.execute(postcode + ", UK");
}

function postCodeCallback(point){
    $('.distance-filter-geo-location').val(point.lat() +","+ point.lng() +",0.0");
    var location = $('.filter-url').val();

    location += getParametersFromFormValues();

    applyFilter(location);
}
*/

//function to set directions for each property
function showLocation(i){
	
	//get max miles value
	var maxMiles = $('select.distance-filter-miles').val();
	
	//get postcode
	var postcode = $('input.distance-filter-post-code').val();
	postcode = postcode + ", UK";
	
	if(i == 0){
	    $('.distance-filter-geo-location').val("");
	}
	
	//check if a max distance is selected
	if(maxMiles == ''){
		message(lblDistanceInputErrorMessage);
	}else{
		//check if postcode can be geocoded
		geocoder.getLocations(postcode, function(response){
			if (!response || response.Status.code != 200){
				message(lblGoogleGeoCodeErrorMessage);
				removeOverlays();
			}else{
				//load directions from poscode to current property 
				if(typeof window.getHotelLocations == 'function'
				        && getHotelLocations().length > 0) {
				        
				    var locations = getHotelLocations();
				     
				    gdir.load("from: " + postcode  + " to: " + locations[i][1], { "locale" : "en" });
				    //check if this is the first call
				    if(i == 0){
					    //hide google link
					    $('.googlemap-link').hide();
					    //reset html (remove, used for debugging)
					    $('#results, #count').html('');
					    //get lat/lng from geocoded result
					    var lat = response.Placemark[0].Point.coordinates[1];
					    var lng = response.Placemark[0].Point.coordinates[0];
					    count = 0;
					    
					    $('.distance-filter-geo-location').val(lat +","+ lng);
					    //set up google maps link (uses map variables a top of script)
					    $('.googlemap-link').attr('href', googleStaticMapLink.format(lat, lng));
				    }
				}else{
				    message(lblGoogleNoFilterResultsMessage);
				    removeOverlays();
				}
			}
		});
	}
	
}

function doDistanceFilter(){
    if($('.distance-filter-post-code').val() != ''
        && $('.distance-filter-post-code').val() != lblEnterPostCode
            && $('.distance-filter-miles').val() != ''){
        //getPointFromPostcode($('.distance-filter-post-code').val(), postCodeCallback);
        addOverlays();
        showLocation(0);
    }else{
      message(lblDistanceInputErrorMessage);
    }
}

/* Google Distance Filter */

/* Welshy Methods */

var ie6 = (/MSIE ((5\.5)|6)/.test(navigator.userAgent) && navigator.platform == "Win32")

function addOverlays(){

    if($('.overlay').length < 2){
        var overlayHtml = overlayLoadingHtml.format(lblLoading);

        $('#filter-options').append(overlayHtml);
        $('#filter-list').append(overlayHtml);
        
	    var fiterOptionsH = $('#sidebar').height() + 20;
	    $('#filter-options .overlay').css({'height':fiterOptionsH});

	    var propertyListH = $('.property-list').height();
	    $('.property-list .overlay').css({'height':propertyListH});

	    ;
	    if(ie6){
		    $('select').css({'visibility':'hidden'});
	    }
	}
}

function removeOverlays(){
	$('.overlay').remove();
	if(ie6){
		$('select').css({'visibility':'visible'});
	}
}

function hideShow(){
	$('#filter-options .handle').click(function(){
		$(this).toggleClass('down').siblings('.toggle').slideToggle();
	});
}

function printList(){
	$('.print-link a').click(function(e){
		e.preventDefault();
		var refineList = $('.refine-by').html();
		var propList = $('.property-list').html();
		$('body').append('<div id="print-area"></div>');
		$('#print-area').html(refineList + propList);
		
		$('#print-area').printElement({
			//printMode:'popup',
			overrideElementCSS:['/_Styles/comparison-tool-print.css', {href:'/_Styles/comparison-tool-print.css',media:'print'}],
			classNameToAdd : 'print-class',
			iframeElementOptions:{ classNameToAdd : 'print-class' }
		}).remove();
	});
}

function printOverlay(){
	$('a.print-overlay').click(function(e){
		e.preventDefault();
		$('#comparison-table').printElement({
			//printMode:'popup',
			overrideElementCSS:['/_Styles/comparison-tool-print.css', {href:'/_Styles/comparison-tool-print.css',media:'print'}]
		});
	});
}
var op = 0;
function overlayCompare(){
    $('body').append('<div id="modalMessage" style="display:none"><div class="modalheader"><img id="ImageLogo" alt="Warner Leisure Hotels" src="'+ lblOverlayLogoImage +'" style="border-width:0px;" /></div><h1>Loading, Please Wait...</h1><div style="padding-top: 15px; margin-bottom: 15px;"><img id="ModalImage" src="'+ lblOverlayMainLoadingImage +'" style="border-width:0px;" /></div><p>In the event of any problems you may encounter, please contact our<br />support team on <span>0800 13 82 632</span> or email us at<br /><a href="mailto:bookings@warnerleisurehotels.co.uk">bookings@warnerleisurehotels.co.uk</a> with your details.</p></div>');
	$('.compare-properties a').click(function(e){
	     if( (!$.browser.msie && e.button == 0) || ($.browser.msie && e.button == 1) ) {
	        $('#modalMessage').show();
	     }
	}).fancybox({
		type: 'ajax',
		width: 961,
		height: 1500,
		padding: 0,
		titleShow: false,
		showCloseButton: false,
		transitionIn: 'none',
		transitionOut: 'none',
		overlayShow: true,
		overlayColor: '#DED6C4',
		overlayOpacity: 0.8,
		hideOnOverlayClick: false,
		hideOnContentClick: false,
		centerOnScroll: false,
		onComplete: function(){
		    $('#modalMessage').hide();
			modalExtras();
			tableRollover();
			//$('#comparison-table .property-column-empty').each(function (){
			//$(this).attr("rel")
			    propertyDropdown();
			//});
			printOverlay();
			initOverlayPropertyAddLinks();
			$('#comparison-table .remove-property').each(function (){
			    initOverlayRemoveFromComparison($(this).attr("rel"));
			});
            updateRemoveFromComparisonLinks();
            updateFromAddToComparisonDropDownLinks();
            setOverlayEqualHeight();
            op = parseFloat($('#fancybox-wrap').css('top'));
            $('#fancybox-wrap').css({'top': 10 + $(window).scrollTop() +'px'});
            $(window).scroll(function(){
			    if($(this).scrollTop() < op){
					$('#fancybox-wrap').css('top', $(this).scrollTop() + "px");
					op = $(this).scrollTop();
			    }
			});
		}
	});
	
} 

function fixHeight(){
	setTimeout(function(){
		var h = $('#comparison-table').height() + 20;
		$('#fancybox-wrap, #fancybox-inner').css({
			'height': h
		});
	},100);
}

function modalExtras(){
    fixHeight();

	$('.close_modal').click(function(){
		$.fancybox.close();
		saveComparisonState(getParametersFromFormValues()); 
		return false;
	});
	$('.info-icon').tooltip({
		delay: 0, 
		showURL: false,
		top: 25, 
		left: -65,
		track: true
	}).find('img').attr('alt','');
	if(ie6){
		pngfix();
	}
}

function tableRollover(){
	$('#comparison-table td').mouseenter(function(){
		var rel = $(this).attr('rel');
		$('td[rel*='+rel+']').addClass('hover');
		$('#icon-'+rel+' .overlay-map-icon-title').show().parent('.overlay-map-icon').css({'z-index':'2'}).siblings('.overlay-map-icon').css({'z-index':'1'});
	}).mouseleave(function(){
		var rel = $(this).attr('rel');
		$('td[rel*='+rel+']').removeClass('hover');
		$('#icon-'+rel+' .overlay-map-icon-title').hide();
	})
}

function propertyDropdown(position){

    var extraSelector = '';
    if(arguments.length > 0){
        extraSelector = '.empty-cell-'+position+' ';
    }
    //alert(extraSelector);
    
	$(extraSelector+'.property-dropdown ul').hide();
	$(extraSelector+'.property-dropdown h5').click(
		function(){
			$(this).siblings(extraSelector+'.property-dropdown ul').toggle();
			return false;
		}
    );
	$(extraSelector+'.property-dropdown').mouseleave(
		function(){
      		$(this).find('ul').hide();
    	}
    );
}

/*
$(document).ready(function(){
	//addOverlays();
	//setTimeout('removeOverlays()',5000);
	//removeOverlays();
	printList();
	hideShow();
	overlayCompare();
});
*/

/*utils functions*/

String.prototype.format = function() {
    var result = this;
    if(arguments.length > 0){
        for(var i = 0; i < arguments.length; i++){
            result = result.replace("{"+i+"}", arguments[i]);
        }
    }
    
    return result;    
}

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); };

