﻿
jQuery(document).ready(function () {
    SetMenuBar();
    initSearchBox();

    if ($("#booknow").length > 0) 
        InitRatesBox();

    RepositionFooter();
});

var bAdvancedSearch = false;

function SetMenuBar() {

    var mode = "home";

    if ((getQueryVariable('cities')) || (getQueryVariable('town')))
        mode = 'cities';

    if (getQueryVariable('london')) mode = 'london';
    if (getQueryVariable('england')) mode = 'england';
    if (getQueryVariable('france')) mode = 'france';
    if (getQueryVariable('spain')) mode = 'spain';
    if (getQueryVariable('italy')) mode = 'italy';
    if (getQueryVariable('beta')) mode = 'beta';
    
    $("#" + mode).addClass("nav_button_selected");
}

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
}

function getQueryVariable(variable) {
    var query = window.location.href;
    var vars = query.split("/");
    for (var i = 3; i < vars.length; i++) {
        //var pair = vars[i].split("=");
        if (vars[i] == variable) {
            return true;
        }
    }
    return false;
}

function RepositionFooter() {
    var initialDocHeight = jQuery(document).height();
    repositionFooter(initialDocHeight);

    jQuery(window).resize(function() { repositionFooter(initialDocHeight); });
}


function repositionFooter(documentHeight) {
    var windowHeight = jQuery(window).height();

    if (documentHeight > (windowHeight + 5)) {
        jQuery(".footer_links").css("bottom", "");
        jQuery(".footer_links").css("top", (documentHeight + "px"));
    }

    else {
        jQuery(".footer_links").css("top", "");
        jQuery(".footer_links").css("bottom", "3px");
    }
   
}

/* Search Box logic */
function initSearchBox() {

    if (bAdvancedSearch) {
        var select = $("#amount");
        
        var slider = $('<div id="slider"></div>').insertAfter(select).slider({
            range: true,
            min: 0, max: 500,
            values: [35, 120],
            slide: function (event, ui) {
                select.val('£' + ui.values[0] + ' - £' + ui.values[1]);
            }
        });

        select.val('£' + slider.slider("values", 0) + ' - £' + slider.slider("values", 1));

        var select1 = $("#ddlRoomType");

        var slider1 = $('<div id="slider1"></div>').insertAfter(select1).slider({
            min: 1, max: 10,
            range: "min",
            value: select1[0].selectedIndex + 1,
            slide: function (event, ui) {
                select1[0].selectedIndex = ui.value - 1;
            }
        });

        select1.click(function () {
            slider1.slider("value", this.selectedIndex + 1);
        });


        var select2 = $("#ddlNights");

        var slider2 = $('<div id="slider2"></div>').insertAfter(select2).slider({
            min: 1, max: 13,
            range: "min",
            value: select2[0].selectedIndex + 1,
            slide: function (event, ui) {
                select2[0].selectedIndex = ui.value - 1;
            }
        });

        select2.click(function () {
            slider2.slider("value", this.selectedIndex + 1);
        });

        $("#availDate").datepicker({ minDate: 0, numberOfMonths: 3, maxDate: '+6M +1D', dateFormat: "dd M, yy" });
    } // endif advanced search


    $("#search").click(function () { DoSearch("#place"); } );
    //$("#place").focus();

    if ($("#searchBoxLHS").length > 0) {
        initAutoComplete("#place");

        //  $("#place").autocomplete({
        //      source: "/services/autocomplete.ashx"
        //   });

        initLists();

        $("#place").keypress(function (e) {
            if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
                DoSearch("#place");
                return false;
            } else {
                return true;
            }

        });
    }

     }


function initAutoComplete(id) {
    $(id).autocomplete({
        source: function (request, response) {
            $.ajax({

                url: "/services/autocomplete.ashx",
                dataType: "jsonp",
                data: {
                    featureClass: "P",
                    style: "full",
                    maxRows: 12,
                    name_startsWith: request.term
                },

                minLength: 2,delay: 1500,

                //   failure: function () 
                //           { alert('fail');
                //           },
                success: function (data) {
                    response($.map(data, function (item) {
                        return { label: item, value: item }
                    }));
                }

            })
        },

        minLength: 2,

        focus: function (event, ui) {
            $(id).val(ui.item.value.value + ", " + ui.item.value.country );
            return false;
        },


        select: function (event, ui) {
            $(id).val(ui.item.value.value + ", " + ui.item.value.country);
            DoSearch(id);
            return false;
        //log(ui.item ? ("Selected:" + ui.item.label) : "Nothing selected, input was " + this.value);
        }

        /*
        open: function () {
        $(this).removeClass("ui-corner-all").addClass("ui-corner-top");
        },
        close: function () {
        $(this).removeClass("ui-corner-top").addClass("ui-corner-all");
        }
        */

    }).data( "autocomplete" )._renderItem = function( ul, item ) {
	return $( "<li></li>" )
		.data( "item.autocomplete", item )
		.append("<a>" + item.label.name + "<p class='search_subcat'>" + item.label.country + "</p></a>")
		.appendTo( ul );
    };

}

function initLists() {

    if (bAdvancedSearch) {
        var j = {
            v10: "1 person", v20: "2 people", v21: "2 + 1 child",
            v22: "2 + 2 children", v23: "2 + 3 children",
            v30: "3 people", v40: "4-0",
            v40: "4 people", v50: "5 people",
            v60: "6 people", v70: "7 people"
        };

        $.each(j, function (val, text) {
            $('#ddlRoomType').append($('<option></option>').val(val).html(text));
        });


        $('#ddlNights').append($('<option></option>').val(1).html("1 night"));

        for (var k = 2; k <= 14; k++) {
            $('#ddlNights').append($('<option></option>').val(k.toString()).html(k.toString() + " nights"));
        };
    }

  
   if ($.cookie("rs_search_place") != null) {
        $('#place').val($.cookie("rs_search_place"));
        if (bAdvancedSearch) {
            $('#availDate').val($.cookie('rs_search_date'));
            $('#ddlNights').val($.cookie('rs_search_nights'));
            $('#ddlRoomType').val($.cookie('rs_search_roomtype'));
        }
    }
    else {
        if (bAdvancedSearch) {
            var myDate = new Date();
            var prettyDate = $.datepicker.formatDate('dd M, yy', new Date());
            //$("#datepicker").datepicker({ minDate: 0, numberOfMonths: 3, maxDate: '+6M +1D', dateFormat: "dd M, yy" });
            $("#availDate").val(prettyDate);
        }
    }
}

function DoSearch(id) {
    $.cookie('rs_search_place', $(id).val(), { path: '/', expires: 1, domain: 'roomseeker.eu' });

    
    if (bAdvancedSearch) {
        $.cookie('rs_search_date', $('#availDate').val(), { path: '/', expires: 1, domain: 'roomseeker.eu' });
        $.cookie('rs_search_nights', $('#ddlNights').val(), { path: '/', expires: 1, domain: 'roomseeker.eu' });
        $.cookie('rs_search_roomtype', $('#ddlRoomType').val(), { path: '/', expires: 1, domain: 'roomseeker.eu' });
    }

    var place = $(id).val();

    trackEvent("rs", "Search", place );


    if (place.indexOf(',') > 0) {
        country = $.trim( place.substr(place.lastIndexOf(',') + 1)); //.trim();
        place = $.trim(place.substr(0, place.lastIndexOf(','))); //.trim();
        var q = "/place/" + place + "/" + country;
    }
    else
        var q = "/place/" + place; /* + "/" + $('#datepicker').val() + "/" + $('#ddlNights').val() + "/" + $('#ddlRoomType').val(); */

    window.location.href = q;

    
}

function ClearCookies() {
    $.cookie('rs_search_place', null, { path: '/', expires: -10 })
    if (bAdvancedSearch) {
        $.cookie('rs_search_date', null, { path: '/', expires: -10 })
        $.cookie('rs_search_nights', null, { path: '/', expires: -10 })
        $.cookie('rs_search_roomtype', null, { path: '/', expires: -10 })
    }
}


jQuery.cookie = function (name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};


function bindDatepicker($obj) {
    if ($obj == null) $obj = $("input.date");

    $obj.datepicker(
    {
        appendText: '(yyyy-mm-dd)',
        autoSize: true,
        changeMonth: true,
        changeYear: true,
        closeText: 'Done',
        dateFormat: 'yy-mm-dd',
        defaultDate: '+1m',
        minDate: +1,
        numberOfMonths: 2
    }
  );
}


/***** Hotel Logic ******/

       // Set date and nights based on search entry
       function initAvailablity()
       {
        $('#availNights').append($('<option></option>').val(1).html( "1 night"));

        for (var k = 2; k <= 14; k++) { 
            $('#availNights').append($('<option></option>').val(k.toString() ).html(  k.toString() + " nights"));
        };
        $("#availNights option[value='7']").attr('selected', 'selected');

        $("#availDate").datepicker({ minDate: 0, numberOfMonths: 3, maxDate: '+6M +1D', dateFormat: "dd M, yy" });   

        if ($.cookie("rs_search_date") != null) {
        $('#availDate').val($.cookie('rs_search_date'));}
        else { $("#availDate").val(getInitalAvailDate()); }
       }

       function getLRDate() {
       var date = getSearchDate();
       if (date != "" ) date = "?d=" + date;
        return date;
   }

   function getSearchDate()
   {
   try {
            var newDate = $.datepicker.parseDate('dd M, yy', $('#availDate').val());
            return $.datepicker.formatDate("yymmdd", newDate);
           }
           catch(err)  {
           return "";
           }
   }

   function getAvailDate()
   {
   try {
            var newDate = $.datepicker.parseDate('dd M, yy', $('#availDate').val());
            return $.datepicker.formatDate("yy-mm-dd", newDate);
           }
           catch(err)  {
           return "";
           }
   }

   // Get date based on entry in search bar
   function getInitalAvailDate()
   {

   try {

            if ( $.cookie('rs_search_date') != null)
                return $.cookie('rs_search_date');
            else
                return $.datepicker.formatDate('dd M, yy', new Date());
           }
           catch(err)  {
           return "";
           }
   }

   //2010-05-28

   function CheckAvail(hotelIDs) {
        $("#loading").empty().html('<img src="/content/ajax-loader.gif" />')
        $("#rates").empty();

        // Save the cookie
        $.cookie('rs_search_date', $('#availDate').val(), { path: '/', expires: 1, domain: 'roomseeker.eu' });

        trackEvent("rs", "CheckAvailByID", hotelIDs);


       $.ajax({
           type: "GET",
           url: "/services/RoomInfo.ashx?ids=" + hotelIDs + "&startDate=" + getAvailDate() + "&nights=" + $('#availNights').val(),
           contentType: "application/json; charset=utf-8",
           dataType: "json",
           success: function (response) {
               var data = response;
               BuildTables(data.hotels);
               $("#loading").empty();
               //$(this).scrollTop($('#availablity').position().top)
               //document.location.href = "#availablity";
           },

           failure: function (msg) {
               $('#result').empty().append(msg);
               $("#loading").empty();
           }
       });


   }

    function BuildTables(hotels)
    {
    var hotel = hotels[0];

    for (var j = 0; j < hotel.Rooms.length; j++) {
            var room = hotel.Rooms[j];
            BuildTable(room);
        }
    }

    function BuildTable(room) {
            var table = "<div class='pad'><table class='book save' >";

            var end = room.rate.length;

            if ( room.rate.length > 7)
                end = 7;

            table += BuildWeek("rates1",room.name, "",room,0, end);

            if ( room.rate.length > 7)
                table += BuildWeek("rate2","", "week2",room,7, room.rate.length);

            table += "</table></div>";
            $("#rates").append( table);
            $(".pad").hide();
            $(".pad").slideDown("slow", function () { RepositionFooter(); });
    }

    
    function GetDate(roomDate)
    {
        // 28/02/2010 to Mon 23 Jun
        var start =  $.datepicker.parseDate('dd/mm/yy', roomDate);
        return $.datepicker.formatDate('D d M', start);
    }

    function BuildWeek(id,roomDesc,className, room, start , end)
    {
    var week = "";
    week += "<tr id='" + id + "' class='" + className + "'>";

    if ( roomDesc != "")
        week +="<td class='rm_type' valign='top' rowspan='3'><div><strong>"+ roomDesc + "</strong><br/> sleeps " + room.sleeps + "</div></td>";

    for (var j = start; j < end; j++) {
        var selected = (room.rate[j].price == "Full") ? "normal" : "selected";
        week += "<td class='" + selected + "'><div>" + GetDate(room.rate[j].date)  + "</div><del>£" + room.rack_rate + "</del><b>" + room.rate[j].price + "</b></td>";
    }

    week +="<td class='whitespace'></td>";
    //week +="<td valign='top' class='last' rowspan='3'><span class='roomsave' style='display:none;'>You Save </span></td>";


    week += "</tr>";

    return week;
    }

    
/*** End of hotel logic */



