

var defaultQueryString = 
    "source=lastminutehotel&datevarianceid=6&durationid=0&adults=2&pageindex=0" + 
    "&date=19.02.2012&orderby=price";
var query = null;
var searchQuery = null;
var searchResult = null;

$(document).ready(function(){
    //init calendar
    $('.datepickerContainer')
		.datePicker({inline:true,showYearNavigation:false})
		.bind(
			'dateSelected',
			DateHandler
		);

    //init history
    $.history.init(HistoryCallback);
});


//free text search
function FreeTextSearch()
{
    $(".noresults").hide();
    
    var freeText = $("#textBoxFreeTextSearch").attr("value");
    if (Trim(freeText) != null && Trim(freeText) != "")
    {
        var freeTextQuery = $.query.parse("");
        freeTextQuery.set("source", "freetextsearch");
        freeTextQuery.set("query", query.toString());
        freeTextQuery.set("freetext", freeText);
        /*$("#ajaxLoader").slideDown(500, function(){
            blockWithLoader();
            jQuery.get(
                "dataprovider.aspx?" + freeTextQuery.toString() + "&" + Math.random(), 
                {}, 
                FreeTextSearchCallBack);
        });*/
        blockWithLoader();
            jQuery.get(
                "dataprovider.aspx?" + freeTextQuery.toString() + "&" + Math.random(), 
                {}, 
                FreeTextSearchCallBack);
    }
    else
    {
        searchQuery = query.copy();
        searchQuery.remove("hotelname");
        searchQuery.set("handler", "freetext");
        SearchOffers();
    }
}

function FreeTextSearchCallBack(data, textStatus) 
{
    unBlockWithLoader();
    
    if (data != null && data != "")
    {
        FreeTextSearchHandler(data);
    }
    else
    {
        SearchCallBack(null, null);
    }
}


//history and gui
var lastHash;
function HistoryCallback(hash)
{
    //firefox fix to ignore second parasite request
    if ($.browser.mozilla && (hash == lastHash || hash == unescape(lastHash)))
    {
        return;
    }
    lastHash = hash;

    if (hash == null || hash == "")
    {
        //init query to the default search
        query = $.query.parse(defaultQueryString);
        UpdateGui();
        ShowOffers();
    }
    else
    {
        ShowSearch();
        if (searchResult == null)
        {
            searchQuery = $.query.parse(hash);
            SearchOffers(true);
        }
        else
        {
            searchResult = null;
        }
    }
}

function ShowSearch()
{
    if ($(".searchResultContainer").css("display") == "none")
    {
        $(".offersContainer").hide(200, function(){
            $(".searchResultContainer").show(200);
        });
    }
}

function ShowOffers()
{
    $(".searchResultContainer").hide(200, function(){
        $(".offersContainer").show(200);
    });
}


// search
function SearchOffers(history)
{
    $(".noresults").hide();
    
    if (searchQuery.get("handler") != "pagination")
    {
        searchQuery.remove("pageindex");
    }
    
    /*$("#ajaxLoader").slideDown(500, function(){
        blockWithLoader();
        jQuery.get(
            "dataprovider.aspx?" + searchQuery.toString() + "&" + Math.random(), 
            {}, 
            history == true ? SearchCallBackHistory : SearchCallBack);
    });*/
    blockWithLoader();
    jQuery.get(
        "dataprovider.aspx?" + searchQuery.toString() + "&" + Math.random(), 
        {}, 
        history == true ? SearchCallBackHistory : SearchCallBack);
}

function SearchCallBackHistory(data, textStatus)
{
    SearchCallBack(data, textStatus, true);
}

function SearchCallBack(data, textStatus, history) 
{
    unBlockWithLoader();

    //$("#ajaxLoader").slideUp();

    if ($(data).find("LastMinute").size() > 0)
    {
        searchResult = data;
        query = searchQuery;
        UpdateGui();
        UpdateSearchResult();
        if (!(history == true)) //click
        {
            $.history.load(searchQuery.toString());
        }
        else
        {
            searchResult = null;
        }
    }
    else if (searchQuery.get("handler") == "hotelcategory" && searchQuery.get("hotelcategoryid") != "" &&
        searchQuery.get("hotelcategoryid") != "4")
    {
        switch (searchQuery.get("hotelcategoryid"))
        {
            case "-3":{searchQuery.set("hotelcategoryid", "1"); break;}    
            case "1":{searchQuery.set("hotelcategoryid", "2"); break;}    
            case "2":{searchQuery.set("hotelcategoryid", "3"); break;}    
            case "3":{searchQuery.set("hotelcategoryid", "4"); break;}
        }
        SearchOffers();
    }
    else
    {
        UpdateGui();
        $(".noresults").show();
        
        //if search result empty - search default query
        if (query == null)
        {
            query = $.query.parse(defaultQueryString);
            ShowSearch();
            searchQuery = query.copy();
            SearchOffers(true);
        }
    }
}
 
 
// render search result      
function UpdateSearchResult() {
    var data = searchResult;
    
    var tmpl = 
        '<div class="searchItem" style="display:none;border:solid 1px #C8C8C0;margin-top:10px;padding:4px;padding-bottom:0px;background-image:url(i/search/bg_search_item.gif);background-repeat:repeat-x;">' +
        '   <div style="float:left;width:152px;height:112px;border:solid 1px #C8C8C0;padding:3px;"><img class="searchItemHotelImage" src="i/x.gif" style="width:152px;height:112px;" /></div>' +
        '   <div style="float:left;width:480px;">' +
        '       <div style="float:left;width:293px;padding-left:7px;padding-top:7px;"><a href="#" class="searchItemOffersLink searchItemHotelName"></a> <img src="" class="searchItemStarsImage" /></div>' +
        '       <div style="float:left;width:175px;padding-top:5px;text-align:right;">' +
        '           <span style="font-size:14px;padding-right:5px;">vanaf &euro;</span><span style="padding-right:5px;"><a href="#" class="searchItemOffersLink searchItemPrice"></a></span>' + 
        '           <a href="#" class="searchItemOffersLink"><img src="i/search/btn_arrow.gif" style="border:0px;vertical-align:bottom;" /></a>' +
        '       </div>' +
        '       <div style="clear:both;"></div>' +
        '       <div style="padding-left:7px;padding-top:3px;">' +
        '           <span class="searchItemLocation"></span>' +
        '       </div>' +
        '       <div style="padding-left:7px;padding-top:3px;">' +
        '           <span class="searchItemHotelText"></span>' +
        '       </div>' +
        '       <div style="padding-left:7px;padding-top:3px;">' +
        '           <span class="searchItemOfferText"></span>' +
        '       </div>' +
        '       <div style="padding-left:7px;padding-top:14px;position:relative;">' +
        '           <div style="float:left;"><a href="#"><img src="i/search/btn_hotel.gif" style="border:0px;" /></a><a href="#" class="searchItemHotelLink"></a></div>' +
        '           <div class="searchItemHotelRatingContainer" style="float: right; background-image: url(i/zoover_bg2.gif); position: absolute; top: -4px; right: 6px; padding-top: 6px; padding-left: 26px; width: 29px; height: 31px;"><span class="searchItemHotelRating" style="color: rgb(65, 125, 188); font-size: 16px; font-weight: bold;"></span></div>' +
        '       </div>' +
        '   </div>' +
        '   <div style="clear:both;height:4px;"><img src="i/x.gif" style="width:1px;height:4px;" /></div>' +
        '</div>';
 
    $(".searchItem", "#searchResult").hide(1000);
    $("#searchResult").html("");
    $(data).find("LastMinute").each(function(){
        resultsHTML = $(tmpl);
        
        var hotelName = $('HotelName', this).text();
	var hotelRating = $("HotelRating", this).text();
        
        $('.searchItemLocation', resultsHTML).html($("HotelLocation", this).text());
        $('.searchItemHotelText', resultsHTML).html($("HotelTeaser", this).text());
        $('.searchItemPrice', resultsHTML).html($('MinPrice', this).text() + ',-');
        $('.searchItemHotelName', resultsHTML).html(hotelName);
	$('.searchItemHotelRating', resultsHTML).html(hotelRating);
        if (hotelRating == null || hotelRating == "")
        {
	    $('.searchItemHotelRating', resultsHTML).html("n/a");
            //$('.searchItemHotelRatingContainer', resultsHTML).css("display", "none");
        }
        $('.searchItemHotelLink', resultsHTML).html("Lees meer over " + hotelName);
        $('.searchItemOfferText', resultsHTML).html(
            $('DurationDays', this).text() + " " + 
            ($('DurationDays', this).text() == "1" ? "Dag" : "Dagen") + 
            " " + $('MealPlanLabel', this).text());
        $('.searchItemHotelImage', resultsHTML).attr("src", 
            "/vakantie/HotelPics/" + 
            $('FirstPicture', this).text());

        if ($("HotelClass", this).text() != "")
        {        
            $(".searchItemStarsImage", resultsHTML).attr("src",
                "i/search/stars" + $("HotelClass", this).text().replace(",", "") + ".gif");
        }
        else
        {
            $(".searchItemStarsImage", resultsHTML).attr("src", "i/x.gif");
        }
        
        var q = query.copy().set("hotelid", $('HotelId', this).text());
        q.set("source", "lastminuteoffer");
        q.set("orderby", "table");
        q.set("pageindex", "0");
        $('a.searchItemOffersLink', resultsHTML).attr("href", 
            $("SEOLink", this).text() + "?" + 
            /*"_HotelDetails.aspx?" + */
            "rechot=" + escape($('HotelId', this).text()) + "&" +
            "offerid=" + escape($('PK', this).text()) + "&" +
            "minprice=" + escape($('MinPrice', this).text()) + "#" + q.toString());
        $('a.searchItemHotelLink', resultsHTML).attr("href", 
            $('a.searchItemOffersLink', resultsHTML).attr("href"));
           
        $("#searchResult").append(resultsHTML);
        $(resultsHTML).fadeIn(1000);
    })
    
    //pagination
    var pagesCount = new Number($(data).find("PagesCount").text());
    var pageIndex = new Number($(data).find("PageIndex").text());
    var paginationContent = '<div style="position:absolute;left:7px;top:7px;font-size:14px;color:White;">' + 
        'Pagina <b>' + (pageIndex + 1) + '</b> Vanaf ' + pagesCount + '</div>';
        
    var paginationStartPage = 0;
    var paginationEndPage;
    var paginationDisplayPagesCount = 5;
    while ((paginationStartPage + paginationDisplayPagesCount) <= pageIndex)
    {
        paginationStartPage += paginationDisplayPagesCount;
    }
    paginationEndPage = paginationStartPage + paginationDisplayPagesCount;
    
    paginationContent += '<table align="center" style="margin:auto;position:relative;top:-5px;height:28px;" cellpadding="0" cellspacing="0"><tr>';
    
    //prev page link
    paginationContent += '<td style="padding-right:10px;">';
    if (pageIndex <= 0)
    {
        paginationContent += '<span class="paginationPreviousLinkDisabled">&lt; Terug</span>';
    }
    else
    {
        paginationContent += '<a href="#" class="paginationPreviousLink" onclick="var q = $.query.hash();q.set(\'handler\', \'pagination\');q.set(\'pageindex\', \'' + (pageIndex - 1) + '\');$.history.load(q.toString());return false;">&lt; Terug</a>';
    }
    paginationContent += '</td>';
    
    //pages
    paginationContent += '<td><div style="width:2px;height:30px;background-color:White;"></div></td>';
    for(var i = paginationStartPage; i < paginationEndPage && i < pagesCount; i++)
    {
        paginationContent += '<td>';
        if (i == pageIndex)
        {
            paginationContent += '<div style="border-left:solid 3px white;border-right:solid 3px white;"><div style="width:24px;height:20px;border:solid 3px #0C5DAE;background-color:White;padding-top:4px;text-align:center;" class="paginationCurrentPage">' + (i + 1) + '</div></div>';
        }
        else
        {
            paginationContent += '<div style="border:solid 3px white;border-top:solid 1px white;border-bottom:solid 1px white;"><div style="width:24px;height:22px;border:solid 1px #41B4EE;background-color:White;padding-top:4px;text-align:center;">' +
                '<a href="#" class="paginationPage" onclick="var q = query.copy();q.set(\'handler\', \'pagination\');q.set(\'pageindex\', \'' + i + '\');$.history.load(q.toString());return false;">' + (i + 1) + '</a>' +
                '</div></div>';
        }
        paginationContent += '</td>';
    }
    paginationContent += '<td><div style="width:2px;height:30px;background-color:White;"></div></td>';
    
    //next page link
    paginationContent += '<td style="padding-left:10px;">';
    if (pageIndex >= (pagesCount - 1))
    {
        paginationContent += '<span class="paginationNextLinkDisabled">Verder &gt;</span>';
    }
    else
    {
        paginationContent += '<a href="#" class="paginationNextLink" onclick="var q = query.copy();q.set(\'handler\', \'pagination\');q.set(\'pageindex\', \'' + (pageIndex + 1) + '\');$.history.load(q.toString());return false;">Verder &gt;</a>';
    }
    paginationContent += '</td>';
    
    paginationContent += '</tr></table>';
    
    $("#searchPagination").html(paginationContent);
}

//wizard
function UpdateGui()
{
    if (query != null)
    {
        //wizard
        
        //free text
        if (query.get("hotelname") != "" && !$("#textBoxFreeTextSearch").attr("value"))
        {
            $("#textBoxFreeTextSearch").attr("value", query.get("hotelname"));
        }
        
        //date
        $('.datepickerContainer').dpSetSelected(ToCalendarDate(query.get("date")));
        
        //datevariance
        $("#dropDownListDateVariance").find("option[@value='" + query.get("datevarianceid") + "']").attr("selected", "selected");
        
        //duration
        $("#dropDownListDuration").find("option[@value='" + query.get("durationid") + "']").attr("selected", "selected");
        
        //adults
        $("#textBoxAdults").attr("value", query.get("adults"));
        
        //children
        $("#textBoxChildren").attr("value", query.get("children"));
        
        //room type
        $("#roomTypeSingle").removeClass("wizard_list_item_room_type_selected");
        $("#roomTypeSingle").addClass("wizard_list_item_room_type");
        $("#roomTypeDouble").removeClass("wizard_list_item_room_type_selected");
        $("#roomTypeDouble").addClass("wizard_list_item_room_type");
        $("#roomTypeFamily").removeClass("wizard_list_item_room_type_selected");
        $("#roomTypeFamily").addClass("wizard_list_item_room_type");
        var roomsMapping = query.get("roomsmapping");
        if (roomsMapping != null && roomsMapping != "")
        {
            if (roomsMapping.indexOf("EZ") >= 0)
            {
                $("#roomTypeSingle").removeClass("wizard_list_item_room_type");
                $("#roomTypeSingle").addClass("wizard_list_item_room_type_selected");
            }
            if (roomsMapping.indexOf("DZ") >= 0)
            {
                $("#roomTypeDouble").removeClass("wizard_list_item_room_type");
                $("#roomTypeDouble").addClass("wizard_list_item_room_type_selected");
            }
            if (roomsMapping.indexOf("FZ") >= 0)
            {
                $("#roomTypeFamily").removeClass("wizard_list_item_room_type");
                $("#roomTypeFamily").addClass("wizard_list_item_room_type_selected");
            }
        }
        
        //dynamic occupancy
        if ($("*[@occupancyid='" + query.get("occupancyid") + "'].wizard_list_item_occupancy").size() == 0 &&
            $("*[@occupancyid='" + query.get("occupancyid") + "'].wizard_list_item_occupancy_selected").size() == 0 &&
            query.get("occupancyid") != "")
        {
            $("#dynamicOccupancy").attr("occupancyid", query.get("occupancyid"));
            $("#dynamicOccupancy").html(
                $("*[@occupancyid='" + query.get("occupancyid") + "'].wizard_popup_list_item_occupancy").attr("shorttitle"));
            $("#dynamicOccupancy").show();
        }
        else if ($("#dynamicOccupancy").attr("occupancyid") != query.get("occupancyid"))
        {
            $("#dynamicOccupancy").hide();
            $("#dynamicOccupancy").attr("occupancyid", "");
            $("#dynamicOccupancy").html("");
        }
        
        //occupancy
        $(".wizard_list_item_occupancy_selected").addClass("wizard_list_item_occupancy");
        $(".wizard_list_item_occupancy").removeClass("wizard_list_item_occupancy_selected");
        $("*[@occupancyid='" + query.get("occupancyid") + "'].wizard_list_item_occupancy").addClass(
            "wizard_list_item_occupancy_selected");
        
        //dynamic destination
        if ($("*[@destinationid='" + query.get("destinationid") + "'].wizard_list_item_destination").size() == 0 &&
            $("*[@destinationid='" + query.get("destinationid") + "'].wizard_list_item_destination_selected").size() == 0 &&
            query.get("destinationid") != "--2")
        {
            $("#dynamicDestination").attr("destinationid", query.get("destinationid"));
            $("#dynamicDestination").html(
                $("*[@destinationid='" + query.get("destinationid") + "'].wizard_popup_list_item_destination").html());
            $("#dynamicDestination").show();
        }
        else if ($("#dynamicDestination").attr("destinationid") != query.get("destinationid"))
        {
            $("#dynamicDestination").hide();
            $("#dynamicDestination").attr("destinationid", "");
            $("#dynamicDestination").html("");
        }
        
        //destination
        $(".wizard_list_item_destination_selected").addClass("wizard_list_item_destination");
        $(".wizard_list_item_destination").removeClass("wizard_list_item_destination_selected");
        $("*[@destinationid='" + query.get("destinationid") + "'].wizard_list_item_destination").addClass(
            "wizard_list_item_destination_selected");
            
        //hotel category
        $(".wizard_list_item_hotel_category_selected").addClass("wizard_list_item_hotel_category");
        $(".wizard_list_item_hotel_category").removeClass("wizard_list_item_hotel_category_selected");
        $("*[@hotelcategoryid='" + query.get("hotelcategoryid") + "'].wizard_list_item_hotel_category").addClass(
            "wizard_list_item_hotel_category_selected");
            
        //price interval
        $(".wizard_list_item_price_interval_selected").addClass("wizard_list_item_price_interval");
        $(".wizard_list_item_price_interval").removeClass("wizard_list_item_price_interval_selected");
        $("*[@priceintervalid='" + query.get("priceintervalid") + "'].wizard_list_item_price_interval").addClass(
            "wizard_list_item_price_interval_selected");
            
        //meal plan
        $(".wizard_list_item_meal_plan_selected").addClass("wizard_list_item_meal_plan");
        $(".wizard_list_item_meal_plan").removeClass("wizard_list_item_meal_plan_selected");
        $("*[@mealplanid='" + query.get("mealplanid") + "'].wizard_list_item_meal_plan").addClass(
            "wizard_list_item_meal_plan_selected");
            
        //order by   
        if (query.get("orderby") == "price" || query.get("orderby") == null || query.get("orderby") == "")
        {
            $("#orderByPrice").attr("checked", true);
            $("#orderByPriceLabel").removeClass("sort_label");
            $("#orderByPriceLabel").addClass("sort_label_active");
        }
        else
        {
            $("#orderByPriceLabel").removeClass("sort_label_active");
            $("#orderByPriceLabel").addClass("sort_label");
        }
        
        if (query.get("orderby") == "hotelname")
        {
            $("#orderByName").attr("checked", true);
            $("#orderByNameLabel").removeClass("sort_label");
            $("#orderByNameLabel").addClass("sort_label_active");
        }
        else
        {
            $("#orderByNameLabel").removeClass("sort_label_active");
            $("#orderByNameLabel").addClass("sort_label");
        }
        
        if (query.get("orderby") == "location")
        {
            $("#orderByLocation").attr("checked", true);
            $("#orderByLocationLabel").removeClass("sort_label");
            $("#orderByLocationLabel").addClass("sort_label_active");
        }
        else
        {
            $("#orderByLocationLabel").removeClass("sort_label_active");
            $("#orderByLocationLabel").addClass("sort_label");
        }
        
        if (query.get("orderby") == "hotelcategory")
        {
            $("#orderByCategory").attr("checked", true);
            $("#orderByCategoryLabel").removeClass("sort_label");
            $("#orderByCategoryLabel").addClass("sort_label_active");
        }
        else
        {
            $("#orderByCategoryLabel").removeClass("sort_label_active");
            $("#orderByCategoryLabel").addClass("sort_label");
        }
    }
}

function UpdateChildrenPopupGui(element) //element = textbox
{
    var children;
    var childrenages;
    if (element === undefined)
    {
        children = query.get("children");
        childrenages = query.get("childrenages");
    }
    else
    {
        children = element.value;
        childrenages = "";
        for (var i = 0; i < children; i++)
        {
            if (childrenages != "")
            {
                childrenages += ",";
            }
            childrenages += "3";
        }
    }
       
    //update popup controls
    $("input[@name='childrenCount']").each(function(){
        if ($(this).attr("value") == children)
        {
            $(this).attr("checked", true);
        }
        else
        {
            $(this).attr("checked", false);
        }
    });
    
    for (var i = 0; i < 6; i++)
    {
        $("#dropDownListChildrenAge" + i).get(0).selectedIndex = 3;
    }
    
    for (var i = 0; i < children; i++)
    {
        $("#dropDownListChildrenAge" + i).get(0).selectedIndex = childrenages.split(',')[i]; // - 1;
    }
    
    UpdateChildrenAgeListsGui();
}

function UpdateChildrenAgeListsGui()
{
    var childrenCount = 0;
    $("input[@name='childrenCount']").each(function(){
        if ($(this).attr("checked"))
        {
            childrenCount = $(this).attr("value");
        }
    });
    
    for (var i = 0; i < 6; i++)
    {
        $("#dropDownListChildrenAge" + i).hide();
    }
    
    for (var i = 0; i < childrenCount; i++)
    {
        $("#dropDownListChildrenAge" + i).show();
    }
}

function UpdateRoomsPopupGui()
{
    var roomsCount = query.get("roomsnumber");
    var roomsMapping = query.get("roomsmapping");
    
    //update popup controls
    $("input[@name='roomsCount']").each(function(){
        if ($(this).attr("value") == roomsCount)
        {
            $(this).attr("checked", true);
        }
        else
        {
            $(this).attr("checked", false);
        }
    });
    
    for (var i = 0; i < 3; i++)
    {
        $("#dropDownListRoomAdults" + i).get(0).selectedIndex = 0;
        $("#dropDownListRoomChildren" + i).get(0).selectedIndex = 0;
        $("#dropDownListRoomInfants" + i).get(0).selectedIndex = 0;
        $("#dropDownListRoomType" + i).get(0).selectedIndex = 0;
    }
    
    var rooms = query.get("roomsmapping").split(',');
    for (var i = 0; i < roomsCount && i < rooms.length; i++)
    {
        var roomData = rooms[i].split(' ');
        $("#dropDownListRoomAdults" + i).get(0).selectedIndex = roomData[0];
        $("#dropDownListRoomChildren" + i).get(0).selectedIndex = roomData[1];
        $("#dropDownListRoomInfants" + i).get(0).selectedIndex =  roomData[2];
        switch(roomData[3])
        {
            case "EZ": 
            {
                $("#dropDownListRoomType" + i).get(0).selectedIndex = 0;
                break;
            }
            case "DZ": 
            {
                $("#dropDownListRoomType" + i).get(0).selectedIndex = 1;
                break;
            }
            case "FZ": 
            {
                $("#dropDownListRoomType" + i).get(0).selectedIndex = 2;
                break;
            }
        }
    }

    UpdateRoomsMappingListsGui();
}

function UpdateRoomsMappingListsGui()
{
    var roomsCount = 0;
    $("input[@name='roomsCount']").each(function(){
        if ($(this).attr("checked"))
        {
            roomsCount = $(this).attr("value");
        }
    });
    
    for (var i = 0; i < 6; i++)
    {
        $("#dropDownListRoomAdults" + i).hide();
        $("#dropDownListRoomChildren" + i).hide();
        $("#dropDownListRoomInfants" + i).hide();
        $("#dropDownListRoomType" + i).hide();
    }
    
    for (var i = 0; i < roomsCount; i++)
    {
        $("#dropDownListRoomAdults" + i).show();
        $("#dropDownListRoomChildren" + i).show();
        $("#dropDownListRoomInfants" + i).show();
        $("#dropDownListRoomType" + i).show();
    }
}

function UpdateOccupanciesPopupGui()
{
    $(".wizard_popup_list_item_occupancy").show();
    $("*[@occupancyid='" + query.get("occupancyid") + "'].wizard_popup_list_item_occupancy").hide();
}

function UpdateDestinationsPopupGui()
{
    $(".wizard_popup_list_item_destination").show();
    $("*[@destinationid='" + query.get("destinationid") + "'].wizard_popup_list_item_destination").hide();
}

function ClosePopups()
{
    $("#childrenPopup").hide();
    $("#roomsPopup").hide();
    $("#occupanciesPopup").hide();
    $("#destinationsPopup").hide();
}

//wizard handlers
function DateHandler(e, selectedDate, $td)
{
    if (query.get("date") != FromCalendarDate(selectedDate))
    {
        searchQuery = query.copy();
        searchQuery.set("handler", "date");
        searchQuery.set("date", FromCalendarDate(selectedDate));
        SearchOffers();
    }
}

function DateVarianceHandler(element) //element = select
{
    searchQuery = query.copy();
    searchQuery.set("handler", "datevariance");
    searchQuery.set("datevarianceid", element.options[element.selectedIndex].value);
    SearchOffers();
}

function DurationHandler(element) //element = select
{
    searchQuery = query.copy();
    searchQuery.set("handler", "duration");
    searchQuery.set("durationid", element.options[element.selectedIndex].value);
    searchQuery.remove("duration");
    SearchOffers();
}

function AdultsHandler(element) //element = textbox
{
    if (query.get("adults") != element.value)
    {
        searchQuery = query.copy();
        searchQuery.set("handler", "adults");
        searchQuery.set("adults", element.value);
        
        searchQuery.remove("roomsnumber")
        searchQuery.remove("roomsmapping")
        searchQuery.remove("occupancyid")
        
        SearchOffers();
    }
}

function ChildrenPopupHandler()
{
    //process children popup
    searchQuery = query.copy();
    searchQuery.set("handler", "childrenpopup");
    
    var childrenCount = 0;
    $("input[@name='childrenCount']").each(function(){
        if ($(this).attr("checked"))
        {
            childrenCount = $(this).attr("value");
        }
    });
    
    var performSearch = false;
    if (childrenCount == 0)
    {
        if (query.get("children") != null && query.get("children") != "")
        {
            performSearch = true;
            searchQuery.remove("children");
            searchQuery.remove("childrenages");
        }
    }
    else
    {
        if (query.get("children") != childrenCount)
        {
            performSearch = true;
        }
        searchQuery.set("children", childrenCount);
        
        var childrenAges = "";
        for(var i = 0; i < childrenCount; i++)
        {
            if (childrenAges != "")
            {
                childrenAges += ",";
            }
            childrenAges += 
                $("#dropDownListChildrenAge" + i).get(0).options[$("#dropDownListChildrenAge" + i).get(0).selectedIndex].value;
        }
        if (query.get("childrenages") != childrenAges)
        {
            performSearch = true;
        }
        searchQuery.set("childrenages", childrenAges);
    }
    
    if (performSearch)
    {
        searchQuery.remove("roomsnumber")
        searchQuery.remove("roomsmapping")
        searchQuery.remove("occupancyid")
        
        SearchOffers();
    }
}

function RoomsPopupHandler()
{
    searchQuery = query.copy();
    searchQuery.set("handler", "roomspopup");
    
    var roomsCount = 0;
    $("input[@name='roomsCount']").each(function(){
        if ($(this).attr("checked"))
        {
            roomsCount = $(this).attr("value");
        }
    });
    
    if (roomsCount > 0)
    {
        //calculate adults and children selected
        var adultsCount = 0;
        var childrenCount = 0;
        var infantsCount = 0;
        
        for (var i = 0; i < roomsCount; i++)
        {
            adultsCount += new Number($("#dropDownListRoomAdults" + i).attr("value"));
            childrenCount += new Number($("#dropDownListRoomChildren" + i).attr("value"));
            infantsCount += new Number($("#dropDownListRoomInfants" + i).attr("value"));
        }
        
        //validate to match configured adults and children
        if (adultsCount != query.get("adults") ||
            childrenCount != GetConfiguredChildren() || infantsCount != GetConfiguredInfants())
        {
            alert("Die Gesamtzalh der Erwachsenen und Kinder muss wie konfiguriert sein!");
            $("#roomsPopup").show();
            return;
        }
            
        //alernative to validation and return: set adults and children automatically - disabled now
        searchQuery.set("adults", adultsCount);
        
        if (childrenCount != GetConfiguredChildren() || infantsCount != GetConfiguredInfants())
        {
            var childrenAges = "";
            for(var i = 0; i < childrenCount; i++)
            {
                if (childrenAges != "")
                {
                    childrenAges += ",";
                }
                childrenAges += "3";
            }
            for(var i = 0; i < infantsCount; i++)
            {
                if (childrenAges != "")
                {
                    childrenAges += ",";
                }
                childrenAges += "1";
            }
            searchQuery.set("children", childrenCount + infantsCount);
            searchQuery.set("childrenages", childrenAges);
        }
            
        //process popup
        searchQuery.set("roomsnumber", roomsCount);
        
        var roomsMapping = "";
        for(var i = 0; i < roomsCount; i++)
        {
            if (roomsMapping != "")
            {
                roomsMapping += ",";
            }
            roomsMapping += 
                $("#dropDownListRoomAdults" + i).attr("value") + " " +
                $("#dropDownListRoomChildren" + i).attr("value") + " " +
                $("#dropDownListRoomInfants" + i).attr("value") + " " +
                $("#dropDownListRoomType" + i).attr("value");
        }
        searchQuery.set("roomsmapping", roomsMapping);
        
        if (query.get("roomsnumber") != searchQuery.get("roomsnumber") || 
            query.get("roomsmapping") != searchQuery.get("roomsmapping"))
        {    
            SearchOffers();
        }
    }
}

function RoomTypeHandler(element) //element = div
{
    searchQuery = query.copy();
    searchQuery.set("handler", "roomtype");
 
    if ($(element).hasClass("wizard_list_item_room_type_selected")) //&& $(".wizard_list_item_room_type_selected").size() == 1)
    {
        searchQuery.remove("roomsnumber");
        searchQuery.remove("roomsmapping");
        
        SearchOffers();
    }
    else if ($(element).hasClass("wizard_list_item_room_type") && $(".wizard_list_item_room_type_selected").size() <= 1)
    {   
        var adults = searchQuery.get("adults");
        var children = searchQuery.get("children");
        if (children == null || children == "")
        {
            children = "0";
        }
        
        searchQuery.set("roomsnumber", "1");
        switch(element.id)
        {
            case "roomTypeSingle":
            {
                if (adults == 1)
                {
                    searchQuery.set("roomsmapping", "1 " + GetConfiguredChildren() + " " + GetConfiguredInfants() + " EZ,0 0 0 NA,0 0 0 NA");
                }
                else if (adults == 2)
                {
                    searchQuery.set("roomsnumber", "2");
                    searchQuery.set("roomsmapping", "1 " + GetConfiguredChildren() + " " + GetConfiguredInfants() + " EZ,1 0 0 EZ,0 0 0 NA");
                }
                else if (adults == 3)
                {
                    searchQuery.set("roomsnumber", "3");
                    searchQuery.set("roomsmapping", "1 " + GetConfiguredChildren() + " " + GetConfiguredInfants() + " EZ,1 0 0 EZ,1 0 0 EZ");
                }
                else
                {
                    searchQuery.set("roomsmapping", adults + " " + GetConfiguredChildren() + " " + GetConfiguredInfants() + " EZ,0 0 0 NA,0 0 0 NA");
                }
                break;
            }
            case "roomTypeDouble":
            {
                searchQuery.set("roomsmapping", adults + " " + GetConfiguredChildren() + " " + GetConfiguredInfants() + " DZ,0 0 0 NA,0 0 0 NA");
                break;
            }
            case "roomTypeFamily":
            {
                searchQuery.set("roomsmapping", adults + " " + GetConfiguredChildren() + " " + GetConfiguredInfants() + " FZ,0 0 0 NA,0 0 0 NA");
                break;
            }
        }
        
        SearchOffers();
    }
    else
    {
        UpdateRoomsPopupGui();
        $('#roomsPopup').fadeIn(300);
    }
}

function OccupancyHandler(element) //element = div
{
    searchQuery = query.copy();
    searchQuery.set("handler", "occupancy");
 
    if ($(element).hasClass("wizard_list_item_occupancy_selected"))
    {
        searchQuery.remove("occupancyid");
        searchQuery.remove("roomsnumber");
        searchQuery.remove("roomsmapping");
        searchQuery.set("adults", "2");
        searchQuery.remove("children");
        searchQuery.remove("childrenages");
    }
    else
    {
        searchQuery.set("occupancyid", $(element).attr("occupancyid"));
        searchQuery.set("roomsnumber", ExtractOccupancyRoomsNumber($(element).attr("occupancyid")));
        searchQuery.set("roomsmapping", ExtractOccupancyRoomsMapping($(element).attr("occupancyid")));
        searchQuery.set("adults", ExtractOccupancyAdults($(element).attr("occupancyid")));
        searchQuery.set("children", ExtractOccupancyChildren($(element).attr("occupancyid")));
        searchQuery.set("childrenages", ExtractOccupancyChildrenAges($(element).attr("occupancyid")));
    }
    
    SearchOffers();
}

function OccupancyPopupHandler(element) //element = div
{
    ClosePopups();
    OccupancyHandler(element);
}

function DestinationHandler(element) //element = div
{
    searchQuery = query.copy();
    searchQuery.set("handler", "destination");
 
    if ($(element).hasClass("wizard_list_item_destination_selected"))
    {
        searchQuery.set("destinationid", "--2");
    }
    else
    {
        searchQuery.set("destinationid", $(element).attr("destinationid"));
    }
    
    SearchOffers();
}

function DestinationPopupHandler(element) //element = div
{
    ClosePopups();
    DestinationHandler(element);
}

function HotelCategoryHandler(element) //element = div
{
    searchQuery = query.copy();
    searchQuery.set("handler", "hotelcategory");
 
    if ($(element).hasClass("wizard_list_item_hotel_category_selected"))
    {
        searchQuery.remove("hotelcategoryid");
    }
    else
    {
        searchQuery.set("hotelcategoryid", $(element).attr("hotelcategoryid"));
    }
    
    SearchOffers();
}

function PriceIntervalHandler(element) //element = div
{
    searchQuery = query.copy();
    searchQuery.set("handler", "priceinterval");
 
    if ($(element).hasClass("wizard_list_item_price_interval_selected"))
    {
        searchQuery.remove("priceintervalid");
    }
    else
    {
        searchQuery.set("priceintervalid", $(element).attr("priceintervalid"));
    }
    
    SearchOffers();
}

function MealPlanHandler(element) //element = div
{
    searchQuery = query.copy();
    searchQuery.set("handler", "mealplan");
 
    if ($(element).hasClass("wizard_list_item_meal_plan_selected"))
    {
        searchQuery.remove("mealplanid");
    }
    else
    {
        searchQuery.set("mealplanid", $(element).attr("mealplanid"));
    }
    
    SearchOffers();
}

function OrderByHandler(code)
{
    searchQuery = query.copy();
    searchQuery.set("handler", "orderby");
    searchQuery.set("orderby", code);
    SearchOffers();
}

function FreeTextSearchHandler(newQueryString)
{
    searchQuery = $.query.parse(newQueryString);
    searchQuery.set("handler", "freetext");
    SearchOffers();
}

// utilities
function ToCalendarDate(date)
{
    return date.replace(".", "/").replace(".", "/");
}

function FromCalendarDate(dateString)
{
    var date = new Date(Date.parse(dateString));
    var month = (date.getMonth() + 1);
    var s = (date.getDate() <= 9 ? "0" + date.getDate() : date.getDate()) + "/";
    s += (month <= 9 ? "0" + month : month) + "/";
    s += date.getYear() < 2000 ? 1900 + date.getYear() : date.getYear();
    return s;
}

function GetConfiguredChildren()
{
    return new Number(query.get("children")) - GetConfiguredInfants();
}

function GetConfiguredInfants()
{
    //get infants configured in children popup
    var configuredInfants = 0;
    var ages = query.get("childrenages").split(',');
    for (var i = 0; i < ages.length; i++)
    {
        if (ages[i] == "1")
        {
            configuredInfants++;
        }
    }
    return configuredInfants;
}

function Trim(str)
{
    if(!str || typeof str != 'string')
        return null;

    return str.replace(/^[\s]+/,'').replace(/[\s]+$/,'').replace(/[\s]{2,}/,' ');
}

function ExtractOccupancyRoomsNumber(occupancy)
{
    if (occupancy.indexOf("0 0 0 NA,0 0 0 NA") >= 0)
    {
        return 1;
    }
    else if (occupancy.indexOf("0 0 0 NA") >= 0)
    {
        return 2;
    }
    else
    {
        return 3;
    }
}

function ExtractOccupancyRoomsMapping(occupancy)
{
    return occupancy;
}

function ExtractOccupancyAdults(occupancy)
{
    return new Number(occupancy.substr(0, 1)) + new Number(occupancy.substr(9, 1)) + 
        new Number(occupancy.substr(18, 1));
}

function ExtractOccupancyChildren(occupancy)
{
    return new Number(occupancy.substr(2, 1)) + new Number(occupancy.substr(11, 1)) + 
        new Number(occupancy.substr(20, 1));
}

function ExtractOccupancyChildrenAges(occupancy)
{
    var childrenAges = "";
    var children = ExtractOccupancyChildren(occupancy);
    var firstIteration = true;
    for(var i = 0; i < children; i++)
    {
        if (!firstIteration)
        {
            childrenAges += ",";
        }
        childrenAges += "3";
        firstIteration = false;
    }
    return childrenAges;
}
