

var defaultQueryString = 
    "source=flightoffer&destinationid=--2&datevarianceid=14&adults=2&pageindex=0" + 
    "&date=09.02.2012&orderby=airportrandom";
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);
});


//redirect to booking
function RedirectToBooking()
{
    window.location.href = "_FlightBooking.aspx?" + 
        "lmsadn=" + escape(query.get("adults")) + "&" +
        "lmschn=" + escape(query.get("children")) + "&" +
        "lmschag=" + escape(query.get("childrenages")) + "&" +
        "bkngflt=" + escape($("OfferId", booking).text()) + "&" +
        "lmbkbk=" + escape($("CacheId", booking).text());
}

//availability check
function AvailabilityCheck(offerId)
{
    $(".noresults").hide();
    
    var acQuery = $.query.parse("");
    acQuery.set("bkngflt", offerId);
    acQuery.set("lmsadn", query.get("adults"));
    acQuery.set("lmschn", query.get("children"));
    acQuery.set("lmschag", query.get("childrenages"));
    acQuery.set("bkngmode", "xml");
    $("#acolOffersContainer").fadeOut();
    $("#ajaxLoaderBooking").fadeIn();
    $.get("FlightAvailabilityCheck.aspx?" + acQuery.toString() + "&" + Math.random(), {}, 
        AvailabilityCheckCallback);
}

function AvailabilityCheckCallback(data, textStatus)
{
    $("#ajaxLoaderBooking").fadeOut();

    booking = data;

    if (data != null && $("Booking", data).size() > 0)
    {
        $("#bookingInfo").fadeOut(100);
        
        //render
        $("#bookingTotalPrice").html($("TotalPrice", data).text());
        $("#bookingDateFrom").html($("DateFrom", data).text());
        $("#bookingDateTo").html($("DateTo", data).text());
        $("#bookingDuration").html($("Duration", data).text() + " dagen");
        $("#bookingOriginAirport").html($("OriginAirport", data).text());
        $("#bookingOriginAirport2").html($("OriginAirport", data).text());
        $("#bookingDestinationAirport").html($("DestinationAirport", data).text());
        $("#bookingDestinationAirport2").html($("DestinationAirport", data).text());
        
        if ($("Flight1Departure", data).text() != "" && $("Flight1Arrival", data).text() != "")
        {
            $("#bookingFlight1Time").html($("Flight1Departure", data).text() + " - " +
                $("Flight1Arrival", data).text());
        }
        else
        {
            $("#bookingFlight1Time").hide();
        }
        
        if ($("Flight2Departure", data).text() != "" && $("Flight2Arrival", data).text() != "")
        {
            $("#bookingFlight2Time").html($("Flight2Departure", data).text() + " - " +
                $("Flight2Arrival", data).text());
        }
        else
        {
            $("#bookingFlight2Time").hide();
        }
        
        if ($("Flight1Airline", data).text() != "")
        {
            $("#bookingFlight1Airline").html($("Flight1Airline", data).text());
        }
        else
        {
            $("#bookingFlight1Airline").hide();
        }
        
        if ($("Flight2Airline", data).text() != "")
        {
            $("#bookingFlight2Airline").html($("Flight2Airline", data).text());
        }
        else
        {
            $("#bookingFlight2Airline").hide();
        }
        
        $("#bookingRoomsContainer").html("");
        var isFirstItem = true;
        $("Flight", data).each(function(){
            if (!isFirstItem)
            {
                $("#bookingRoomsContainer").append(
                    '<div style="border-bottom:solid 1px #939385;"><img src="i/x.gif" width="1" height="5" /></div>');
            }
            else
            {
                isFirstItem = false;
            }
            
            $("Traveler", this).each(function(){
                var identityLabel = "";
                switch ($("TravelerIdentity", this).text())
                {
                    case "H":
                    {
                        identityLabel = "<b>volwassene</b>";
                        break;
                    }
                    case "D":
                    {
                        identityLabel = "<b>volwassene</b>";
                        break;
                    }
                    case "K":
                    {
                        identityLabel = "<b>kind</b> (" + $("TravelerAge", this).text() + " jaar)";
                        break;
                    }
                    case "B":
                    {
                        identityLabel = "<b>baby</b>"; // (" + $("TravelerAge", this).text() + " jaar)";
                        break;
                    }                
                }
            
                $("#bookingRoomsContainer").append(
                    '<div style="float:left;padding-top:7px;width:130px;">' +
                    '    <b>1</b> ' + identityLabel + 
                    '</div>' +
                    '<div style="float:left;padding-top:7px;font-weight:bold;">' +
                    '    &euro; ' + $("TravelerPrice", this).text() +
                    '</div>' +
                    '<div style="clear:both;"></div>' +
                    '<div style=""><img src="i/x.gif" width="1" height="4" /></div>' +
                    '<div style="" class="hline"><img src="i/x.gif" width="1" height="1" /></div>');
            });
            
            $("#bookingRoomsContainer").append(
                '<div style="padding-top:3px;"><b>1 x vlucht</b></div>');
        });
        
        //taxes
        $("#bookingTaxesContainer").html("");
        isFirstItem = true;
        $("Tax", data).each(function(){
            if (!isFirstItem)
            {
                $("#bookingTaxesContainer").append(
                    '<div style=""><img src="i/x.gif" width="1" height="4" /></div><div style="" class="hline"><img src="i/x.gif" width="1" height="1" /></div>');
            }
            else
            {
                isFirstItem = false;
            }
            
            $("#bookingTaxesContainer").append(
                    '<div style="float:left;padding-top:3px;width:130px;">' +
                    $("Name", this).text() + 
                    '</div>' +
                    '<div style="float:left;padding-top:3px;font-weight:bold;">' +
                    '    &euro; ' + $("Price", this).text() +
                    '</div>' +
                    '<div style="clear:both;"></div>');
        });
        
        //show
        $("#bookingInfo").fadeIn(500);
        
        $("div.selectedOfferCell").removeClass("selectedOfferCell");
        $("div[@offerid='" + $("OfferId", data).text() + "']").addClass("selectedOfferCell");
    }
    else
    {
        $(".noresults").show().html("De door u gekozen datum is niet meer beschikbaar. Klik op een alternatieve datum.");
    }
}


//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();
        ShowSearch();
        searchQuery = query.copy();
        SearchOffers(true);
    }
    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("Flight").size() > 0)
    {
        searchResult = data;
        query = searchQuery;
        UpdateGui();
        UpdateSearchResult();
        if (!(history == true)) //click
        {
            $.history.load(searchQuery.toString());
        }
        else
        {
            searchResult = null;
        }
    }
    else
    {
        UpdateGui();
        $(".noresults").show().html("Uw zoekopdracht heeft geen resultaten opgeleverd. U kunt een vernieuwde zoekopdracht proberen.");
        
        //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;">' +
        '       <div style="float:left;width:453px;padding-left:7px;padding-top:7px;" class="searchItemFlightName"><span class="searchItemOriginAirportName"></span>&nbsp;<img src="i/flight/round_flight.gif" style="vertical-align:bottom;" />&nbsp;<span class="searchItemDestAirportName"></span></div>' +
        '       <div style="float:left;width:175px;padding-top:5px;text-align:right;">' +
        '           <span style="font-size:14px;padding-right:5px;">&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:5px;">' +
        '           <div style="float:left;width:80px;">Heenvlucht:</div><div style="float:left;font-weight:bold;" class="searchItemDestFlightDate">01.01.2008</div><div style="float:left;">&nbsp;</div><div style="float:left;color:#0C5DAE;" class="searchItemDestFlightDepartureTime">10:00</div><div style="float:left;">&nbsp;-&nbsp;</div><div style="float:left;" class="searchItemOriginAirportName"></div><div style="float:left;">&nbsp;/&nbsp;</div><div style="float:left;color:#0C5DAE;" class="searchItemDestFlightArrivalTime">10:00</div><div style="float:left;">&nbsp;-&nbsp;</div><div style="float:left;" class="searchItemDestAirportName"></div><div style="clear:both;"></div>' +
        '       </div>' +
        '       <div style="padding-left:7px;padding-top:3px;padding-bottom:3px;">' +
        '           <div style="float:left;width:80px;">Terugvlucht:</div><div style="float:left;font-weight:bold;" class="searchItemReturnFlightDate">01.01.2008</div><div style="float:left;">&nbsp;</div><div style="float:left;color:#0C5DAE;" class="searchItemReturnFlightDepartureTime">10:00</div><div style="float:left;">&nbsp;-&nbsp;</div><div style="float:left;" class="searchItemDestAirportName"></div><div style="float:left;">&nbsp;/&nbsp;</div><div style="float:left;color:#0C5DAE;" class="searchItemReturnFlightArrivalTime">10:00</div><div style="float:left;">&nbsp;-&nbsp;</div><div style="float:left;" class="searchItemOriginAirportName"></div><div style="clear:both;"></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("Flight").each(function(){
        resultsHTML = $(tmpl);
        
        var hotelName = $('HotelName', this).text();
        
        $('.searchItemPrice', resultsHTML).html($('Price', this).text() + ',-');
        $('.searchItemOriginAirportName', resultsHTML).html($('OriginAirportName', this).text());
        $('.searchItemDestAirportName', resultsHTML).html($('DestAirportName', this).text());
        
        $('.searchItemDestFlightDate', resultsHTML).html(
            FromTimeTics(new Number($('DateFromJS', this).text())));           
        $('.searchItemReturnFlightDate', resultsHTML).html(
            FromTimeTics(new Number($('DateToJS', this).text())));            
        
        $('.searchItemDestFlightDepartureTime', resultsHTML).html(
            FormatTime($('DestinationFlightDepartureTime', this).text()));
        $('.searchItemDestFlightArrivalTime', resultsHTML).html(
            FormatTime($('DestinationFlightArrivalTime', this).text()));
        $('.searchItemReturnFlightDepartureTime', resultsHTML).html(
            FormatTime($('ReturnFlightDepartureTime', this).text()));
        $('.searchItemReturnFlightArrivalTime', resultsHTML).html(
            FormatTime($('ReturnFlightArrivalTime', this).text()));
            
        $('a.searchItemOffersLink', resultsHTML).click(function(){
            AvailabilityCheck($(this).attr("offerid"));
            return false;
        });
        $('a.searchItemOffersLink', resultsHTML).attr("offerid", $("PK", this).text());
            
        $("#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="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
        
        //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"));
        
        //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");
        
        //dynamic airport
        if ($("*[@airportid='" + query.get("airportid") + "'].wizard_list_item_airport").size() == 0 &&
            $("*[@airportid='" + query.get("airportid") + "'].wizard_list_item_airport_selected").size() == 0 &&
            query.get("airportid") != "")
        {
            $("#dynamicAirport").attr("airportid", query.get("airportid"));
            $("#dynamicAirport").html(
                $("*[@airportid='" + query.get("airportid") + "'].wizard_popup_list_item_airport").html());
            $("#dynamicAirport").show();
        }
        else if ($("#dynamicAirport").attr("airportid") != query.get("airportid"))
        {
            $("#dynamicAirport").hide();
            $("#dynamicAirport").attr("airportid", "");
            $("#dynamicAirport").html("");
        }
        
        //airport
        $(".wizard_list_item_airport_selected").addClass("wizard_list_item_airport");
        $(".wizard_list_item_airport").removeClass("wizard_list_item_airport_selected");
        $("*[@airportid='" + query.get("airportid") + "'].wizard_list_item_airport").addClass(
            "wizard_list_item_airport_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") == "airport")
        {
            $("#orderByAirport").attr("checked", true);
            $("#orderByAirportLabel").removeClass("sort_label");
            $("#orderByAirportLabel").addClass("sort_label_active");
        }
        else
        {
            $("#orderByAirportLabel").removeClass("sort_label_active");
            $("#orderByAirportLabel").addClass("sort_label");
        }
        
        if (query.get("orderby") == "date")
        {
            $("#orderByDate").attr("checked", true);
            $("#orderByDateLabel").removeClass("sort_label");
            $("#orderByDateLabel").addClass("sort_label_active");
        }
        else
        {
            $("#orderByDateLabel").removeClass("sort_label_active");
            $("#orderByDateLabel").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 UpdateDestinationPopupGui()
{
    $(".wizard_popup_list_item_destination").show();
    $("*[@destinationid='" + query.get("destinationid") + "'].wizard_popup_list_item_destination").hide();
}

function UpdateAirportsPopupGui()
{
    $(".wizard_popup_list_item_airport").show();
    $("*[@airportid='" + query.get("airportid") + "'].wizard_popup_list_item_airport").hide();
}

function ClosePopups()
{
    $("#childrenPopup").hide();
    $("#roomsPopup").hide();
    $("#destinationsPopup").hide();
    $("#airportsPopup").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);
    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")
        
        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")
        
        SearchOffers();
    }
}

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 AirportHandler(element) //element = div
{
    searchQuery = query.copy();
    searchQuery.set("handler", "airport");
 
    if ($(element).hasClass("wizard_list_item_airport_selected"))
    {
        searchQuery.remove("airportid");
    }
    else
    {
        searchQuery.set("airportid", $(element).attr("airportid"));
    }
    
    SearchOffers();
}

function AirportPopupHandler(element) //element = div
{
    ClosePopups();
    AirportHandler(element);
}

function OrderByHandler(code)
{
    searchQuery = query.copy();
    searchQuery.set("handler", "orderby");
    searchQuery.set("orderby", code);
    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 FormatTime(rawTime)
{
    if (rawTime != null && rawTime.length > 3)
    {
        return rawTime.substr(0, 2) + ":" + rawTime.substr(2, 2);
    }
    else
    {
        return "";
    }
}

function FromTimeTics(tics)
{
    var date = new Date(tics);
    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;
}
