﻿/*
Filename : /TUI.Web.Includes/Js/booking.js
Description :
Contains common logic to the booking procedure.
*/
var CallBacks = new Array();
var temaStr = "";
if ($("body").hasClass("is-tema") || $("body").hasClass("brand-id-18") || $("body").hasClass("brand-id-19") || $("body").hasClass("brand-id-20") || $("body").hasClass("brand-id-23")) {
    temaStr = "-tema";
}
$(document).ready(
    function() {
        registerHelpTextPopupHandlers(document);

        $("div#draggable div.ui-handle a").click(function() { $("div#draggable").hide().removeClass("popup-666").removeAttr("style").find("div.ui-content:first").removeClass("no-padding").removeAttr("style"); if ($.browser.msie && $.browser.version < 7) { $("select").show(); } });
        $("a.print-icon, a.print").click(function(event) { killDefault(event); window.print(); });

        TUIWebSession = function() {
            this.ID = ($("input#TUIWebSessionID").length > 0) ? $("input#TUIWebSessionID").val() : "";
            this.UrlPart = "?" + oBaseAppSettings.SessionParameterName + "=" + this.ID + oBaseAppSettings.DEBUG;
            this.Reload = function() { this.ID = ($("input#TUIWebSessionID").length > 0) ? $("input#TUIWebSessionID").val() : ""; this.UrlPart = "?" + oBaseAppSettings.SessionParameterName + "=" + this.ID };
        }
        oTUIWebSession = new TUIWebSession();

        Logger = function() {
            this.Count = 1;
            this.Init = function() {
                $("form:first").append("<div id=\"logger\"></div>");
                $("div#logger").css({ position: "fixed", left: "50px", top: "50px", width: "200px", height: "400px", background: "#FFF", border: "1px solid #000", overflow: "scroll", fontSize: "10px" });
            }
            this.Write = function(logText) {
                if ($("div#logger").length == 0) { this.Init(); }
                $("div#logger").html(this.Count.toString() + ". " + logText + "<br/>" + $("div#logger").html());
                this.Count++;
            };
        }
        oLogger = new Logger();

        //List boxes
        Array.prototype.GetFunction = function(s) { for (i = 0; i < this.length; i++) { if (this[i].indexOf(s + "|") == 0) { return (this[i].replace(s + "|", "")); } } return (""); }
        Status = "ready"; ActiveListBox = null;
        jQuery.fn.extend({
            ListContainer: function() { return $(this).parents("div.list-box:first"); },
            ValueHolder: function() { return $(this).ListContainer().children("input:first"); },
            TextHolder: function() { return $(this).ListContainer().children("span"); },
            ListHolder: function() { return $(this).children("dl:first"); },
            ListItems: function(s) { return $(this).ListHolder().children("dd" + ((s != null) ? "." + s : "")); },
            ValueItems: function(s) { return $(this).ListHolder().children("dt" + ((s != null) ? "." + s : "")); },
            Open: function() { Status = "processing"; if (ActiveListBox != null) { ActiveListBox.Close("processing"); } $(this).addClass("active-box"); ActiveListBox = $(this); $(this).ListHolder().show(); setTimeout("Status=\"open\"", 300); },
            Close: function(s) { $(this).removeClass("active-box"); $(this).ListHolder().hide(); ActiveListBox = null; if (s != null) { Status = s; } else { Status = "ready"; } },
            ItemText: function() { return ($(this).find(".text").length > 0) ? $(this).find(".text").text() : $(this).text(); },
            SetSelected: function() { $(this).TextHolder().text($(this).ItemText()); $(this).ValueHolder().val(((($(this).prev("dt").attr("class") != null) && ($(this).prev("dt").attr("class") != "")) ? $(this).prev("dt").attr("class") + "|" : "") + $(this).prev("dt").text()); $(this).parent("dl").children("dd.selected").removeClass("selected"); $(this).addClass("selected"); },
            Call: function() { if (typeof CallBacks == "undefined") { return; } s = CallBacks.GetFunction($(this).ListContainer().attr("id")); if (s == "") { return; } eval(s + "(\"" + $(this).prev("dt").text() + "\")"); },
            SetHeight: function() { if ($(this).length > 12) { $(this).parent("dl").addClass("overflow"); if ($.browser.opera) { $(this).parent("dl").css("overflow", "scroll"); $(this).css("width", ($(this).parent("dl").width() - 24) + "px"); } } else { $(this).parent("dl").removeClass("overflow"); if ($.browser.opera) { $(this).parent("dl").css("overflow", "visible"); $(this).css("width", "auto"); } } },
            ClickItem: function() { if (($(this).hasClass("disabled")) || ($(this).hasClass("non-clickable"))) { Status = "processing"; setTimeout("Status=\"open\"", 100); return; } $(this).SetSelected(); $(this).Call(); },
            InitEvents: function() { $(this).mousedown(function() { return false; }); $(this).hover(function() { $(this).addClass("hover"); }, function() { $(this).removeClass("hover"); }); $(this).click($(this).ClickItem); $(this).SetHeight(); },
            Scroll: function() { if (($(this).ListItems("selected").length > 0) && ($(this).ListItems().index($(this).ListItems("selected:first").get(0)) > 11)) { $(this).ListHolder().scrollTo($(this).ListItems("selected")); } else { $(this).ListHolder().scrollTo(0); } },
            MoveLabelItem: function() { $(this).TextHolder().text($(this).text()); $(this).prev("dt").remove(); $(this).remove(); },
            SelectFirstItem: function() { $(this).children("dd:first").SetSelected(); },
            SetLoadStatus: function() { $(this).addClass("list-box-loading"); if ($(this).children("span").html() == "") { $(this).children("span").html("&#160;"); } return $(this); },
            RemoveLoadStatus: function() { $(this).removeClass("list-box-loading"); }
        });
        InitListBoxes = function(o) {
            o.find("div.list-box").each(function(i) {
                $(this).children("span").mousedown(function() { return false; }).click(function() { $(this).parent("div").trigger("click"); return false; });
                $(this).hover(function() { $(this).addClass("list-box-hover"); }, function() { $(this).removeClass("list-box-hover"); });
                $(this).click(function() { if (Status == "processing") { return; } else if (($(this).ListHolder().is(":visible")) && (Status == "open")) { $(this).Close(); return; } $(this).Open(); $(this).Scroll(); });
                //$(this).focus(function(){if(Status=="processing"){return;}else if(($(this).ListHolder().is(":visible"))&&(Status=="open")){$(this).Close();return;}$(this).Open();$(this).Scroll();});
                $(this).ListItems().InitEvents();
                if ($(this).ListItems("label").length > 0) { $(this).ListItems("label").MoveLabelItem(); if ($(this).ListItems("selected").length > 0) { $(this).ListItems("selected").SetSelected(); } } else if ($(this).ListItems("selected").length > 0) { $(this).ListItems("selected").SetSelected(); } else { $(this).ListItems().eq(0).SetSelected(); }
            });
        }
        $(document).click(function() { if (Status == "open" && ActiveListBox != null) { ActiveListBox.Close(); } });
        var nCurrPos = 0;
        $(document).keydown(function(event) {
            if ((Status == "open") && (typeof (ActiveListBox) != "undefined")) {
                arrList = ActiveListBox.find("dd");
                oSelected = arrList.filter(".selected:first");
                if (event.keyCode == 9 || event.keyCode == 13) { oSelected.trigger("click"); ActiveListBox.Close(); return (true); }
                else if (event.keyCode == 40) {
                    o = (oSelected.length > 0) ? oSelected : null;
                    if (o != null) { o.removeClass("selected"); o.nextAll("dd:first").addClass("selected"); }
                    else { arrList.eq(0).addClass("selected"); }
                    ActiveListBox.Scroll();
                    return (false);
                } else if (event.keyCode == 38) {
                    o = (oSelected.length > 0) ? oSelected : null;
                    if (o != null) { o.removeClass("selected"); o.prevAll("dd:first").addClass("selected"); }
                    else { arrList.filter(":last").addClass("selected"); }
                    ActiveListBox.Scroll();
                    return (false);
                } else {
                    s = "";
                    if (event.keyCode >= 65 && event.keyCode <= 90) { n = (event.keyCode - 65); s = oTUIStrings.sLetters.substring(n, (n + 1)); }
                    else if (event.keyCode >= 48 && event.keyCode <= 57) { s = (event.keyCode - 48).toString(); }
                    else if (event.keyCode >= 96 && event.keyCode <= 105) { s = (event.keyCode - 96).toString(); }
                    else {
                        switch (event.keyCode) {
                            case 192: s = oTUIStrings.arrCharacters[2]; break;
                            case 221: s = oTUIStrings.arrCharacters[0]; break;
                            case 222: s = oTUIStrings.arrCharacters[1]; break;
                        }
                    } if (s == "") { return (false); }
                    sFirstLetter = (oSelected.length > 0) ? oSelected.text().substring(0, 1) : "";
                    nCurrPos = (sFirstLetter.toLowerCase() == s.toLowerCase()) ? (nCurrPos + 1) : 0;
                    arrList.removeClass("selected");
                    o = arrList.filter(function(nPos) { return ($(this).text().substring(0, 1).toLowerCase() == s && nPos >= nCurrPos); }).eq(0);
                    nCurrPos = arrList.index(o);
                    o.addClass("selected");
                    ActiveListBox.Scroll();
                    return (false);
                }
            }
        });

        var $pageCombinations = $('div.page-combinations');
        
        $pageCombinations.find("div.hotel-description a.about, #combination-periods a.about").click
        (
            function(e) {
                var 
                    iframe = String.format("<img src=\""+oBaseAppSettings.IncludeSiteDirectory+"/Images/Layout/HotelItem/icon-load-66x66{0}.gif\" class=\"icon-load\" /><iframe scrolling='auto' frameborder='0' src='{1}HotelAbout.aspx{2}&period={3}&remote=true'></iframe>", temaStr, oBaseAjaxUrls.BookingSite, oTUIWebSession.UrlPart, this.periodIndex),
                    dialogControl = TUI.Web.UI.WebControls.Dialog.createNewGlobalDialog({ 'innerHtmlTop': this.hotelName, 'innerHtmlCenter': iframe, 'isDraggable': true, 'showOverlay': true }, 'dialog-hotel-description');

                dialogControl.show();
            }
        );

        $pageCombinations.find('div.hotel-description a.remove, #combination-periods a.remove').click
        (
            function(e) {
                var nCurrentPeriodIndex = $pageCombinations.find('div.hotel-description a.remove, #combination-periods a.remove').filter(":visible").length,
                    nPeriodIndex = Number(this.periodIndex);
                if ((nCurrentPeriodIndex - 1) <= nPeriodIndex) { document.location.href = String.format("{0}SearchResult.aspx{1}&period={2}", oBaseAjaxUrls.BookingSite, oTUIWebSession.UrlPart, nPeriodIndex); return; }
                var 
                    html = String.format("<p>{0}</p><p>{1}</p><p class=\"button-holder\"><a href=\"javascript:void(0)\" class=\"dialog-change-hotel-cancel\"><img src=\"{2}/Images/Buttons/{3}/cancel.gif\" /></a><a href=\"javascript:void(0)\" class=\"dialog-change-hotel-ok\"><img src=\"/{2}/Images/Buttons/{3}/change-hotel.gif\" /></a></p>", this.resQuestion, this.resWarning, oBaseAppSettings.IncludeSiteDirectory, oBaseAppSettings.BrandID),
                    dialogControl = TUI.Web.UI.WebControls.Dialog.createNewGlobalDialog({ 'innerHtmlTop': $(this).text(), 'innerHtmlCenter': html, 'showOverlay': true }, 'dialog-change-hotel');

                $(dialogControl.get_element()).find('a.dialog-change-hotel-ok').click(function(e) {
                    $(this).parents("div.dialog-center-inner:first").html(String.format("<img src=\""+oBaseAppSettings.IncludeSiteDirectory+"/Images/Layout/HotelItem/icon-load-66x66{0}.gif\" class=\"icon-load\" />", temaStr));
                    document.location.href = String.format("{0}SearchResult.aspx{1}&period={2}", oBaseAjaxUrls.BookingSite, oTUIWebSession.UrlPart, nPeriodIndex);
                });
                $(dialogControl.get_element()).find('a.dialog-change-hotel-cancel').click(function(e) {
                    dialogControl.hide();
                });

                dialogControl.show();
            }
        );

        $pageCombinations.find('a.price-spec-details').click
        (
            function(e) {
                var 
                    urlPriceSpecHandler = String.format("{0}PriceSpecCombi.aspx{1}", oBaseAjaxUrls.DynamicContent, oTUIWebSession.UrlPart),
                    dialogControl = TUI.Web.UI.WebControls.Dialog.createNewGlobalDialog({ 'innerHtmlTop': oTUIStrings.sPriceSpecificationTitle, 'dynamicServiceFullPath': urlPriceSpecHandler, 'showOverlay': true }, 'dialog-price-specification');

                dialogControl.show();
            }
        );

        $("div.secure-page a.price-spec-details").click
        (
            function() {
                if (this.isCombination == "true") {
                    s = oBaseAjaxUrls.DynamicContent + "PriceSpecCombi.aspx" + oTUIWebSession.UrlPart;
                }
                else {
                    s = oBaseAjaxUrls.DynamicContent + "PriceSpec.aspx" + oTUIWebSession.UrlPart;
                }
                //displayDialog(this, oTUIStrings.sPriceSpecificationTitle, s, 670);
                dialogControl = TUI.Web.UI.WebControls.Dialog.createNewGlobalDialog({ 'innerHtmlTop': oTUIStrings.sPriceSpecificationTitle, 'dynamicServiceFullPath': s, 'showOverlay': true }, 'dialog-price-specification');
                dialogControl.show();
            }
        );
    }
);
addDays=function(yyyy,mm,dd,n){mm=parseInt(mm,10)-1;d=new Date();d.setFullYear(yyyy,mm,dd);d.setDate(d.getDate()+n);return d;}
killDefault=function(e){e.returnValue=false;if(e.preventDefault)e.preventDefault();}

String.prototype.appendSessionID=function(){
    sURI=oBaseAppSettings.SessionParameterName+"="
    if((this.indexOf("?"+sURI)!=-1)||(this.indexOf("&"+sURI)!=-1)||(this.indexOf(" ")!=-1)){return(this);}
    sURI=(this.indexOf("?")==-1)?"?"+sURI:"&"+sURI;
    return((oTUIWebSession.ID!="")?this+sURI+oTUIWebSession.ID:this);
};

String.prototype.trim=function(){
    var objRegExp=/^(\s*)$/,strValue=this;
    if(objRegExp.test(strValue)){
        strValue=strValue.replace(objRegExp, '');
        if(strValue.length==0){return(strValue)}
    }
    objRegExp=/^(\s*)([\W\w]*)(\b\s*$)/;
    if(objRegExp.test(strValue)){strValue=strValue.replace(objRegExp,'$2');}
    return(strValue);
};

EventTracker=function(){
    this.Category="";
    this.Action="";
    this.Label="";
    this.SendEvent=function(){
        try{
            _gaq.push(['_trackEvent', this.Category, this.Action, this.Label]);
        }catch(err){}
    };
}
oEventTracker=new EventTracker();

var 
    globalCommonHelpPopupDialogElement,
    globalCommonHelpPopupDialogControl;
    
// TODO: The 'TUI.Web.UI.WebControls.Dialog.createNewGlobalDialog' function uses a better pattern than 'registerHelpTextPopupHandlers' and 'displayDialog' - consider major refactoring
function registerHelpTextPopupHandlers(container)
{
    $(container ? container : document).find('a.help-text-popup,img.help-text-popup').click
    (
        function (e)
        {
            e.stopPropagation();
            
            var
                $this = $(this),
                helpSection = $this.attr('rel').split("|")[0],
                helpPage = $this.attr('rel').split("|")[1],
                targetControlCssClass = $this.attr('class').replace("help-text-popup", "");
            
            if (globalCommonHelpPopupDialogControl != null)
            {
                if (globalCommonHelpPopupDialogControl.get_targetControl() == this)
                {
                    return; // A dialog is already attached to the help link - let it take care of hiding and showing or whatever
                }
                else
                {
                    Sys.Application.removeComponent(globalCommonHelpPopupDialogControl);
                    $(globalCommonHelpPopupDialogElement).remove();
                }
            }
            
            globalCommonHelpPopupDialogElement = $("<div id='help-text-dialog'></div>").appendTo($(this).parent()).get(0);
            globalCommonHelpPopupDialogControl = new TUI.Web.UI.WebControls.Dialog(globalCommonHelpPopupDialogElement);
            
            if (targetControlCssClass != null && targetControlCssClass != "")
            {
                $(globalCommonHelpPopupDialogElement).addClass(targetControlCssClass);
            }

            globalCommonHelpPopupDialogControl.beginUpdate();
            globalCommonHelpPopupDialogControl.set_innerHtmlTop(this.title);
            globalCommonHelpPopupDialogControl.set_dynamicServiceFullPath(oBaseAjaxUrls.DynamicContent + 'GetEPiHelpPage.aspx?helpSection=' + helpSection + '&helpPage=' + helpPage);
            globalCommonHelpPopupDialogControl.set_isDraggable(true);
            globalCommonHelpPopupDialogControl.set_targetControl(this);
            globalCommonHelpPopupDialogControl.set_dialogPosition(TUI.Web.UI.WebControls.DialogPosition.nearTargetInsideClient);
            globalCommonHelpPopupDialogControl.endUpdate();
            
            globalCommonHelpPopupDialogControl.show();
            
            Sys.Application.addComponent(globalCommonHelpPopupDialogControl);
            return(false);
        }
    );
    $("a.help-text-dialog").unbind("click").bind("click", function(e){
        e.stopPropagation();
        displayDialog(this, this.title, oBaseAjaxUrls.DynamicContent + "GetEPiHelpPage.aspx?helpSection="+this.rel.split("|")[0]+"&helpPage="+this.rel.split("|")[1]);
        return(false);
    });
}

// TODO: The 'TUI.Web.UI.WebControls.Dialog.createNewGlobalDialog' function uses a better pattern than 'registerHelpTextPopupHandlers' and 'displayDialog' - consider major refactoring
function displayDialog(oTriggeringElement, sTitle, sUrl, nWidth, sClass, sCallBack)
{
    if (globalCommonHelpPopupDialogControl != null) {
        if (globalCommonHelpPopupDialogControl.get_targetControl() == oTriggeringElement) {
            //return; // A dialog is already attached to the help link - let it take care of hiding and showing or whatever
        }
        else {
            //Sys.Application.removeComponent(globalCommonHelpPopupDialogControl);
            //$(globalCommonHelpPopupDialogElement).remove();
        }
        Sys.Application.removeComponent(globalCommonHelpPopupDialogControl);
        $(globalCommonHelpPopupDialogElement).remove();
    }else{
        //globalCommonHelpPopupDialogElement = $("<div id='help-text-dialog'></div>").appendTo("body").get(0);
        //globalCommonHelpPopupDialogControl = new TUI.Web.UI.WebControls.Dialog(globalCommonHelpPopupDialogElement);
        //Sys.Application.addComponent(globalCommonHelpPopupDialogControl);
    }
    globalCommonHelpPopupDialogElement = $("<div id='help-text-dialog'></div>").appendTo("body").get(0);
    globalCommonHelpPopupDialogControl = new TUI.Web.UI.WebControls.Dialog(globalCommonHelpPopupDialogElement);
    Sys.Application.addComponent(globalCommonHelpPopupDialogControl);
    globalCommonHelpPopupDialogControl.beginUpdate();
    globalCommonHelpPopupDialogControl.set_innerHtmlTop(sTitle);
    if(sUrl){globalCommonHelpPopupDialogControl.set_dynamicServiceFullPath(sUrl);}
    globalCommonHelpPopupDialogControl.set_isDraggable(true);
    globalCommonHelpPopupDialogControl.set_targetControl(oTriggeringElement);
    globalCommonHelpPopupDialogControl.set_dialogPosition(TUI.Web.UI.WebControls.DialogPosition.custom);
    if (sCallBack) { globalCommonHelpPopupDialogControl.set_callBackFunction(sCallBack); }
    globalCommonHelpPopupDialogControl.endUpdate();
    
    if(nWidth){
        $(globalCommonHelpPopupDialogElement).addClass((sClass)?sClass:"").css("width","auto").find("div.dialog-center-inner").css("width",nWidth.toString()+"px");
        $(globalCommonHelpPopupDialogElement).find("div.dialog-top-inner, div.dialog-bottom-inner").css("width",(nWidth-18).toString()+"px");
    }
    globalCommonHelpPopupDialogControl.show();
    
    return $(globalCommonHelpPopupDialogElement).css({left:($(oTriggeringElement).offset().left-400)+"px",top:($(oTriggeringElement).offset().top+20)+"px",background:"none"});
}

function displayDraggable(triggeringElement, width)
{
    var
        $triggeringElement = $(triggeringElement),
        $targetDraggable = $("div#draggable");
    width=(width)?width:500;
    //width=(width>500)?666:500;
    if(width>800){width=900;$targetDraggable.addClass("popup-900");}
    else if(width>500){width=666;$targetDraggable.addClass("popup-666");}
    else{$targetDraggable.removeClass("popup-666").removeClass("popup-900");}
    $targetDraggable.find("div.ui-content:first").html("<img class=\"icon-load\" src=\"" + oBaseAppSettings.IncludeSiteDirectory + "/Images/Layout/HotelItem/icon-load-66x66" + temaStr + ".gif\"/>");
    nPosLeft=($triggeringElement.offset().left-(width-300));if(nPosLeft<50){nPosLeft=50;}
    if($triggeringElement.parents("div#content-start:first").length>0){$targetDraggable.css({width:width,top:"465px",left:(($(document).width()/2)-250)+"px"});}
    else{$targetDraggable.css({width:width,top:($triggeringElement.offset().top-100)+"px",left:nPosLeft+"px"});}
    if($.browser.msie&&$.browser.version<7){$("select").hide();}
    if(!$targetDraggable.hasClass("ui-draggable")){
        if($.browser.msie&&$.browser.version<8){$targetDraggable.draggable({handle:'div.ui-handle',cursor:'move'}).show();}else{$targetDraggable.draggable({handle:'div.ui-handle',cursor:'move',opacity:0.5}).show();}
        $targetDraggable.find("div.ui-handle a").click(function(){$targetDraggable.hide().removeAttr("style").find("div.ui-content:first").removeClass("no-padding").removeAttr("style");});
    }else{$targetDraggable.show();}
    return $targetDraggable;
}

formatNumber=function(n){
    if(isNaN(n)){return("0");}
    s=n.toString();nStart = s.indexOf(" ");
	if(nStart<0){nStart=s.length;}nStart-=3;
	while(nStart>= 1){s=s.substring(0,nStart)+" "+s.substring(nStart,s.length);nStart-=3;}
	return((s.indexOf(oTUIStrings.sCurrencySign)!=-1)?s:s+oTUIStrings.sCurrencySign);
}

//Calendar
var oDate=new Date();
TUICalendar = function() {
    jQuery.fn.extend({ Display: function(o) { var temaStr = (oFormHelper.Type == "TEMA") ? "-tema" : ""; oTUICalendar.WeekHolder.html("<img src=\""+oBaseAppSettings.IncludeSiteDirectory+"/Images/Layout/HotelItem/icon-load-66x66" + temaStr + ".gif\" />"); oTUICalendar.CalendarObject.css({ top: o.offset().top + 17, left: o.offset().left - 113 }); oTUICalendar.CalendarObject.show(); } });
    Number.prototype.toDatePartString = function() { return (this < 10) ? "0" + this.toString() : this.toString(); };
    this.Init = function() { this.CalendarObject = $("div#calendar"); this.WeekHolder = this.CalendarObject.find("div.content div.week-holder:first"); this.InfoTextHolder = this.CalendarObject.find("div.content span.info:first"); this.MonthList = this.CalendarObject.find("div.head div#month-list"); /*this.CalendarObject.draggable({handle:'div.head',cursor:'move'});*/this.CalendarObject.find("div.head a.close").click(function() { oTUICalendar.Close(); }); this.CalendarObject.find("div.head a.prev").click(function() { oTUICalendar.SelectPrevMonth(); }); this.CalendarObject.find("div.head a.next").click(function() { oTUICalendar.SelectNextMonth(); }); }
    this.InitWeekEvents = function() { this.WeekHolder.find("li a").click(function() { oTUICalendar.Day = parseInt($(this).text(), 10); oTUICalendar.SetInputDate(); if (typeof (SetReturnDate) == "function" && oTUICalendar.DateHolder != null && oTUICalendar.DateHolder.hasClass("departure-date")) { SetReturnDate(); } oTUICalendar.Close(); }); };
    this.CalendarObject = null;
    this.WeekHolder = null;
    this.InfoTextHolder = null;
    this.MonthList = null;
    this.MonthListIndex = 0;
    this.UpdateMonthListIndex = function() { this.MonthListIndex = this.MonthList.ListItems().index(this.MonthList.ListItems("selected").get(0)); };
    this.DateHolder = null;
    this.Year = oDate.getFullYear();
    this.Month = (oDate.getMonth() + 1);
    this.ActiveMonth = this.Month;
    this.FirstActiveMonth = null;
    this.Day = oDate.getDate();
    this.SetDate = function() { this.Year = this.DateHolder.children("span.year").text(); this.Month = parseInt(this.DateHolder.children("span.month").text(), 10); this.Day = parseInt(this.DateHolder.children("span.day").text(), 10); this.UpdateMonthListIndex(); };
    this.GetDateString = function() { return this.Year.toString() + "-" + this.Month.toDatePartString() + "-" + this.Day.toDatePartString(); };
    this.SetInputDate = function() { this.DateHolder.children("span.year").text(this.Year.toString()); this.DateHolder.children("span.month").text(this.Month.toDatePartString()); this.DateHolder.children("span.day").text(this.Day.toDatePartString()); };
    this.HotelIdUrlPart = function() { return ($("input#enokhotelid").length > 0) ? "&hotelid=" + $("input#enokhotelid").val() : ""; };
    this.LoadMonthList = function() { sDestCode = ((oFormHelper.GetResortCodeCRS() != "") ? oFormHelper.GetResortCodeCRS() : oFormHelper.GetDestinationCodeCRS()); s = oBaseAjaxUrls.DynamicContent + "Calendar.aspx?year=" + this.Year.toString() + "&month=" + this.Month.toString() + "&mode=months&depcode=" + oFormHelper.GetDepartureCodeCRS() + "&destcode=" + sDestCode + "&type=" + oFormHelper.Type + this.HotelIdUrlPart(); this.MonthList.ListHolder().load(s, function() { oTUICalendar.MonthList.RemoveLoadStatus(); oTUICalendar.MonthList.ListItems().InitEvents(); oSelectedMonth = oTUICalendar.MonthList.ListItems("selected:first"); oFirstActiveMonth = oTUICalendar.MonthList.ListItems().filter(function() { return (!$(this).hasClass("disabled")); }).eq(0); if (oFirstActiveMonth.length == 0) { oFirstActiveMonth = oTUICalendar.MonthList.ListItems().eq(0).addClass("selected"); } oTUICalendar.FirstActiveMonth = oFirstActiveMonth.prev("dt:first").text().split(",")[0]; if (oSelectedMonth.length == 0) { oFirstActiveMonth.SetSelected(); oFirstActiveMonth.Call(); } else { oSelectedMonth.SetSelected(); oSelectedMonth.Call(); }; registerHelpTextPopupHandlers($(this)); }); return this.MonthList; };
    this.SelectMonth = function(s) { a = s.split(","); this.Year = parseInt(a[1], 10); this.Month = parseInt(a[0], 10); /*this.SetInputDate();*/this.LoadWeeks(); this.UpdateMonthListIndex(); };
    this.SelectNextMonth = function() {
        oDD = this.MonthList.find("dd.selected:first").nextAll("dd:first");
        if (oDD.length == 0) { return; }
        oDD.SetSelected();
        a = oDD.prev("dt").text().split(",");
        this.Year = parseInt(a[1], 10); this.Month = parseInt(a[0], 10); this.LoadWeeks(); this.UpdateMonthListIndex();
    };
    this.SelectPrevMonth = function() {
        oDD = this.MonthList.find("dd.selected:first").prevAll("dd:first");
        if (oDD.length == 0) { return; }
        oDD.SetSelected();
        a = oDD.prev("dt").text().split(",");
        this.Year = parseInt(a[1], 10); this.Month = parseInt(a[0], 10); this.LoadWeeks(); this.UpdateMonthListIndex();
    };
    this.LoadWeeks = function() {
        sDestCode = ((oFormHelper.GetResortCodeCRS() != "") ? oFormHelper.GetResortCodeCRS() : oFormHelper.GetDestinationCodeCRS());
        this.WeekHolder.load(oBaseAjaxUrls.DynamicContent + "Calendar.aspx?year=" + this.Year.toString()
            + "&month=" + this.Month.toString()
            + "&day=" + this.Day.toString() + "&depcode=" + oFormHelper.GetDepartureCodeCRS()
            + "&destcode=" + sDestCode
            + "&selmonth=" + this.Month.toString()
            + "&selday=" + this.Day.toString()
            + "&type=" + oFormHelper.Type
            + ((this.DateHolder.hasClass("return-date")) ? "&depdate=" + oFormHelper.DepartureDate() : "")
            + "&icon=true" + this.HotelIdUrlPart(),
    	function() {
    	    oTUICalendar.InitWeekEvents();
    	    oTUICalendar.UpdateMonthListIndex();
    	    if (oTUICalendar.WeekHolder.find("a").length == 0) { oTUICalendar.SetStatusText(oTUIStrings.sCalendarMonthNoDepartures); } else {
    	        if (parseInt(oTUICalendar.FirstActiveMonth) == oTUICalendar.Month) { oTUICalendar.SetStatusText(oTUIStrings.sCalendarEarliestDepartureDate + ": " + oTUICalendar.WeekHolder.find("a:first").text() + "/" + oTUICalendar.Month.toString()); } else { oTUICalendar.SetStatusText(""); }
    	    }
    	});
    };
    this.Open = function(o) {
        CalendarStatus = "ready"; setTimeout("CalendarStatus=\"open\";", 100);
        this.DateHolder = o.prevAll("span.calendar-dates:first");
        this.SetDate();
        if ($.browser.msie && $.browser.version < 7) { this.AllSelectLists.hide(); }
        this.CalendarObject.Display(o);
        this.LoadMonthList().SetLoadStatus();
    };
    this.Close = function() { this.CalendarObject.hide(); if ($.browser.msie && $.browser.version < 7) { this.AllSelectLists.show(); } };
    this.SetStatusText = function(s) { if (s == "") { s = "&#160;"; } this.InfoTextHolder.html(s); };
    this.AllSelectLists = null;
}
var oTUICalendar = new TUICalendar();
//
CallBacks.push("charter-departure|departureClick");
CallBacks.push("charter-departure-ow|departureOWClick");
CallBacks.push("charter-destination|destinationClick");
CallBacks.push("charter-destination-ow|destinationOWClick");
CallBacks.push("charter-resort|resortClick");
CallBacks.push("no-of-rooms|addRoomAllocationContainer");
CallBacks.push("period|periodClick");
CallBacks.push("adults1|adultsClick1");
CallBacks.push("adults2|adultsClick2");
CallBacks.push("adults3|adultsClick3");
CallBacks.push("children1|childrenClick1");
CallBacks.push("children2|childrenClick2");
CallBacks.push("children3|childrenClick3");
var oFormHelper = null;
var setDestinationSelected = false;
var typeForCurrentPeriodCall = "CHARTER";
$(document).ready(
    function() {
        InitPage = function() {
            jQuery.fn.extend({ toggle2: function() { if ($(this).is(":visible")) { $(this).css("display", "none"); } else { $(this).css("display", "block"); } } });
            RoomHelper = function(o) {
                this.Container = o.children("div.no-of-rooms-holder:first");
                this.Template = this.Container.find("div.room-allocation:first");
                this.AllocationContainer = function(s) { return this.Container.find("div.room-allocation" + ((s != null) ? s : "")); };
            }
            oRoomHelper = new RoomHelper($("div.bp-content:first"));
            ListHelper = function() {
                this.PageContainer = $("div.page-container");
                this.StartPageContainer = $("div#search-form");
                this.BookingPanelContainer = this.StartPageContainer;
                this.CharterContainer = this.StartPageContainer.find("div#charter");
                this.CharterToggleChoices = this.StartPageContainer.find("span.toggle");
                this.DepartureContainer = this.BookingPanelContainer.find("div#charter-departure");
                this.DepartureList = this.DepartureContainer.children("dl:first");
                this.DepartureContainerOW = this.BookingPanelContainer.find("div#charter-departure-ow");
                this.DepartureListOW = this.DepartureContainerOW.children("dl:first");
                this.DestinationContainer = this.BookingPanelContainer.find("div#charter-destination");
                this.DestinationList = this.DestinationContainer.children("dl:first");
                this.DestinationContainerOW = this.BookingPanelContainer.find("div#charter-destination-ow");
                this.DestinationListOW = this.DestinationContainerOW.children("dl:first");
                this.ResortContainer = this.BookingPanelContainer.find("div#charter-resort");
                this.ResortList = this.ResortContainer.children("dl:first");
                this.PeriodContainer = this.BookingPanelContainer.find("div#period");
                this.PeriodList = this.PeriodContainer.children("dl:first");
                this.NumberOfRoomList = this.BookingPanelContainer.find("div#no-of-rooms");
                this.AdultsList = this.BookingPanelContainer.find("div#adults1,div#adults2,div#adults3");
                this.ChildrenList = this.BookingPanelContainer.find("div#children1,div#children2,div#children3");
                this.ChildrenAgesHolder = this.BookingPanelContainer.find("div.children-ages");
                this.DepartureDateHolder = this.BookingPanelContainer.find("span.departure-date");
                this.ReturnDateHolder = this.BookingPanelContainer.find("span.return-date");
                this.HotelCodeHolder = this.BookingPanelContainer.find("input#hotel-code");
                this.BookingCodeHolder = this.BookingPanelContainer.find("input#booking-code");
            }
            oListHelper = new ListHelper();
            Validator = function() {
                this.TotalPax = oRoomHelper.AllocationContainer(":eq(2)").find("span.pax-overflow-error");
                this.ValidateTotalPax = function() { n = 0; oListHelper.AdultsList.children("input").each(function() { n += parseInt($(this).val()); }); oListHelper.ChildrenList.children("input").each(function() { n += parseInt($(this).val()); }); if (n > 15) { this.TotalPax.css("display", "block"); return (false); } else { this.TotalPax.css("display", "none"); return (true); } };
                this.ChildrenAges = function(arr) { return (arr.parents("div.room-allocation").find("span.children-ages-error")); };
                this.ValidateChildrenAges = function() {
                    arrIncorrectInputs = oListHelper.ChildrenAgesHolder.filter(function() { return ($(this).is(":visible")); }).find("span:visible input").filter(function() { return ($(this).val().length == 0); });
                    oListHelper.ChildrenAgesHolder.find("span input").css("border", "1px solid #999");
                    arrIncorrectInputs.css("border", "1px solid #EF0000");
                    this.ChildrenAges(oListHelper.ChildrenAgesHolder).css("display", "none");
                    this.ChildrenAges(arrIncorrectInputs).css("display", (arrIncorrectInputs.length > 0) ? "block" : "none");
                    return (arrIncorrectInputs.length == 0);
                };
                this.Period = oListHelper.CharterContainer.find("span.period-error");
                this.ValidatePeriod = function() {
                    s = oListHelper.PeriodContainer.children("span").text();
                    b = oListHelper.PeriodList.children("dd").filter(function() { return ($(this).text() == s); }).hasClass("disabled");
                    if (b) { oListHelper.PeriodContainer.css("border", "1px solid #EF0000"); this.Period.css("display", "block"); }
                    else { this.ResetPeriod(); }
                    return (!b);
                };
                this.ResetPeriod = function() { oListHelper.PeriodContainer.css("border", "1px solid #999"); this.Period.css("display", "none"); };
                this.CharterDestination = oListHelper.CharterContainer.find("span.charter-destination-error");
                this.ResetCharterDestination = function() { oListHelper.DestinationContainer.css("border", "1px solid #999"); this.CharterDestination.css("display", "none"); };
                this.ValidateCharterDestination = function() {
                    s = $.trim(oFormHelper.GetDestinationCodeCRS());
                    b = (s.length == 0) ? false : (s.substring(s.length - 1) == "d");
                    if (!b) { oListHelper.DestinationContainer.css("border", "1px solid #EF0000"); this.CharterDestination.css("display", "block"); }
                    else { this.ResetCharterDestination(); }
                    return (b);
                };
                this.Validate = function() {
                    b1 = this.ValidateChildrenAges();
                    b2 = ((oFormHelper.Type == "TEMA") || (oFormHelper.Type == "FLEX_HTL") || (oFormHelper.Type == "CHARTER_FLT" && oFormHelper.OneWay == "1")) ? true : this.ValidatePeriod();
                    b3 = (oFormHelper.Type == "COMBINATION") ? this.ValidateCharterDestination() : true;
                    return (b1 && b2 && b3);
                };
            }
            oValidator = new Validator();
            InitListBoxes(oListHelper.CharterContainer);
            Array.prototype.trim = function() { s = ""; for (i = 0; i < this.length; i++) { s += (this[i] != "" && this[i] != ";") ? ((i > 0) ? "|" + this[i] : this[i]) : ""; } return s; }
            FormHelper = function() {
                if ($("input#isBookableOnline").val()) {
                    if (oListHelper.DepartureContainer.length === 0 || $("input#isBookableOnline").val().toLowerCase() != "true") {
                        $("#search-form h3").text(oTUIStrings.sEnokNotBookableOnlineHeader);
                        return;
                    }
                }
                else {
                    if (oListHelper.DepartureContainer.length === 0) {
                        $("#search-form h3").text(oTUIStrings.sEnokNotBookableOnlineHeader);
                        return;
                    }
                }
                this.Status = "Ready";
                this.TabIndex = "1";
                this.HotelIdUrlPart = function() { return ($("input#enokhotelid").length > 0) ? "&hotelid=" + $("input#enokhotelid").val() : ""; };
                this.Type = "CHARTER";
                this.SetType = function() {
                    switch (this.TabIndex) {
                        case "1":
                            if (oBaseAppSettings.IsTemaSite)
                                this.Type = "TEMA";
                            else if (oListHelper.BookingPanelContainer.find("span.choice:visible input:visible:checked").length != 0)
                                this.Type = oListHelper.BookingPanelContainer.find("span.choice:visible input:visible:checked").val();
                            else
                                this.Type = "CHARTER";
                            break;
                        case "2": this.Type = "CHARTER_FLT";
                            break;
                        case "3": this.Type = "FLEX_HTL";
                            break;
                    }
                };
                this.OneWay = ($("span.sub-choice input:checked").length == 0) ? "0" : $("span.sub-choice input:checked").val();
                this.SetOneWay = function(o) { this.OneWay = o.val(); this.SetDepartureCodes((o.val() == "1") ? oListHelper.DepartureContainerOW : oListHelper.DepartureContainer); this.SetDestinationCodes((o.val() == "1") ? oListHelper.DestinationContainerOW : oListHelper.DestinationContainer); };
                this.DepartureCodes = oListHelper.DepartureContainer.children("input:first").val().split("|");
                this.DestinationCodes = oListHelper.DestinationContainer.children("input:first").val().split("|");
                this.ResortCodes = oListHelper.ResortContainer.children("input:first").val().split("|");
                this.SetDepartureCodes = function(o) { this.DepartureCodes = o.children("input:first").val().split("|"); };
                this.SetDestinationCodes = function(o) { this.ResortCodes = [""]; this.DestinationCodes = o.children("input:first").val().split("|"); };
                this.SetResortCodes = function() { this.ResortCodes = oListHelper.ResortContainer.children("input:first").val().split("|"); };
                this.GetDepartureCodeOWCRS = function() { s = this.DepartureCodes[0].replace(/CRS-/gi, ""); return ((s == "0") ? "" : s); };
                this.GetDepartureCodeCRS = function() { if (this.OneWay.toString() == "1" && this.DepartureCodes[1].substring(0, 1) == "d") { return this.GetDepartureCodeOWCRS(); } s = this.DepartureCodes[1].substring(2); return ((s == "0") ? "" : s); };
                this.GetDestinationCodeCRS = function() { s = this.DestinationCodes[0].replace(/CRS-/gi, ""); return ((s == "0") ? "" : s); };
                this.GetResortCodeCRS = function() { s = this.ResortCodes[0].replace(/CRS-/gi, ""); return ((s == "0") ? "" : s); };
                this.Period = oListHelper.PeriodContainer.children("input:first").val();
                //this.GetPeriod=function(){if(typeof(oSearchParams.period)!="undefined"&&oSearchParams.period!=null&&oSearchParams.period!="") return oSearchParams.period;return this.Period;}
                this.DepartureDate = function() { return oListHelper.DepartureDateHolder.children("span.year").text() + "-" + oListHelper.DepartureDateHolder.children("span.month").text() + "-" + oListHelper.DepartureDateHolder.children("span.day").text(); };
                this.ReturnDate = function() { return oListHelper.ReturnDateHolder.children("span.year").text() + "-" + oListHelper.ReturnDateHolder.children("span.month").text() + "-" + oListHelper.ReturnDateHolder.children("span.day").text(); };
                this.Pax = [";", ";", ";"];
                this.SetPax = function() {
                    oListHelper.ChildrenAgesHolder.each(function(i) {
                        a = ["", ""]; if ($(this).parent("div.room-allocation").is(":visible")) { a[0] = oListHelper.AdultsList.eq(i).children("input:first").val(); }
                        if ($(this).is(":visible")) { $(this).find("span:visible input").each(function(j) { a[1] += (j > 0) ? "," + $(this).val() : $(this).val(); }); }
                        oFormHelper.Pax[i] = a.join(";");
                    });
                };
                this.GetLmsCode = function() { if (typeof (oSearchParams) != "undefined" && oSearchParams != null && typeof (oSearchParams.lmscode) != "undefined" && oSearchParams.lmscode != null) return oSearchParams.lmscode; return ""; }
                this.GetSource = function() { if (typeof (oSearchParams) != "undefined" && oSearchParams != null && typeof (oSearchParams.source) != "undefined" && oSearchParams.source != null) return oSearchParams.source; return ""; }
                this.GetHotelCodeCrs = function() { if (typeof (oSearchParams) != "undefined" && oSearchParams != null && typeof (oSearchParams.hotel) != "undefined" && oSearchParams.hotel != null) return oSearchParams.hotel; return ""; }
                this.GetHotelCode = function() { var hotelParams = ""; if (typeof (oSearchParams) != "undefined" && oSearchParams != null) { var webcode = oListHelper.HotelCodeHolder.val(); if (webcode != "") { hotelParams = webcode; } else if (typeof (oSearchParams.hotelcode) != "undefined" && oSearchParams.hotelcode != null) { hotelParams = oSearchParams.hotelcode; } } return hotelParams; }
                this.GetBookingCode = function() { return oListHelper.BookingCodeHolder.val(); };
                this.GetQuerystringParam = function(k, v, d) { return v != "" ? "&" + k + "=" + v : ""; }
            }
            oFormHelper = new FormHelper();
            if (oFormHelper.Status !== "Ready") { return; }
            if (oListHelper.StartPageContainer.hasClass("bp-tab2")) { oFormHelper.TabIndex = "2"; }
            else if (oListHelper.StartPageContainer.hasClass("bp-tab3")) { oFormHelper.TabIndex = "3"; }
            oFormHelper.SetType();
            $("a.search-button").click(function() { performSearch(); return; });
            jQuery.fn.extend({
                ResetPeriodList: function() {
                    if ($(this).children("dt").filter(function() { return ($(this).text() == oListHelper.PeriodContainer.children("input:hidden").val()); }).length == 0) {
                        $(this).children("dd.selected:first").trigger("click");
                    }
                }
            });
            LoadPanel = function() {
                s = oFormHelper.Type;
                if (s == "COMBINATION") { oListHelper.BookingPanelContainer.addClass("bp-combinations"); }
                else { oListHelper.BookingPanelContainer.removeClass("bp-combinations"); }
                oListHelper.ResortContainer.hide();
                oListHelper.DepartureContainer.SetLoadStatus(); oListHelper.DestinationContainer.SetLoadStatus();
                if (s == "FLEX_HTL") {
                    oListHelper.DestinationList.load(oBaseAjaxUrls.DynamicContent + "Destinations/GetDestinations.aspx?code=f_&type=" + s, function() {
                        oListHelper.DestinationContainer.RemoveLoadStatus();
                        oListHelper.DestinationContainer.ListItems().InitEvents();
                        oListHelper.DestinationContainer.ListItems().eq(0).ClickItem();
                    });
                }
                else {
                    oListHelper.DepartureList.load(oBaseAjaxUrls.DynamicContent + "Destinations/GetDestinations.aspx?code=b_&type=" + s + "&hotelcode=" + getEnokHotelId(), function() {
                        oListHelper.DepartureContainer.RemoveLoadStatus();
                        oListHelper.DepartureContainer.ListItems().InitEvents();
                        oListHelper.DepartureContainer.ListItems().eq(0).ClickItem();
                    });
                }
            }
            oListHelper.StartPageContainer.find("ul.tabs li").click(function() { s = $(this).attr("id"); oFormHelper.TabIndex = s.replace(/tab/gi, ""); $(this).parent("ul").attr("class", "tabs " + s); bIsInner = oListHelper.BookingPanelContainer.hasClass("inner-booking-panel"); oListHelper.BookingPanelContainer.attr("class", ((bIsInner) ? "inner-booking-panel" : "booking-panel") + " bp-" + s + ((s == "tab2") ? " bp-" + s + "-" + oFormHelper.OneWay : "")); oFormHelper.SetType(); LoadPanel(); if (!$(this).hasClass("selected")) { $(this).parent("ul").find("li").toggleClass("selected") } });
            oListHelper.StartPageContainer.find("a.calendar-icon").click(function() { oTUICalendar.Open($(this)); });
            oListHelper.StartPageContainer.find("span.calendar-dates").click(function() { oTUICalendar.Open($(this).nextAll("a.calendar-icon:first")); });
            oListHelper.StartPageContainer.find("a.toggle-choices").click(function() { $(this).children("span").toggle(); oListHelper.CharterToggleChoices.toggleClass("toggle"); if (($(this).children("span:visible").hasClass("show")) && (oFormHelper.Type == "TRAIN" || oFormHelper.Type == "CRUISE" || oFormHelper.Type == "CAR")) { oListHelper.StartPageContainer.find("span.choice:first input").attr("checked", "checked"); oListHelper.StartPageContainer.find("span.choice:first input").trigger("click"); } });
            oListHelper.StartPageContainer.find("span.choice input").click(function() { if ($(this).parent("span").hasClass("sub-choice")) { return; } oFormHelper.SetType(); LoadPanel(); });
            oListHelper.StartPageContainer.find("span.sub-choice input").click(function() {
                oFormHelper.SetOneWay($(this)); bIsInner = oListHelper.BookingPanelContainer.hasClass("inner-booking-panel"); oListHelper.BookingPanelContainer.attr("class", ((bIsInner) ? "inner-booking-panel" : "booking-panel") + " bp-tab2 bp-tab2-" + oFormHelper.OneWay);
                oListHelper.DestinationContainer.ListItems().eq(0).SetSelected(); oListHelper.ResortContainer.hide();
                if ((oListHelper.DepartureContainerOW.hasClass("list-box-loading")) && (oFormHelper.OneWay == "1")) {
                    oListHelper.DepartureListOW.load(oBaseAjaxUrls.DynamicContent + "Destinations/GetDestinations.aspx?code=o_&type=CHARTER", function() {
                        oListHelper.DepartureContainerOW.removeClass("list-box-loading");
                        oListHelper.DepartureContainerOW.ListItems().InitEvents();
                        oListHelper.DepartureContainerOW.ListItems().eq(0).ClickItem();
                    });
                } else if (oListHelper.DepartureContainer.ListItems().length == 0) {
                    LoadPanel();
                }
            });
            oListHelper.StartPageContainer.find("a.hotel-code-link, a.booking-code-link").click(function() { $(this).hide(); $(this).next("span").css("display", "block"); });
            oListHelper.StartPageContainer.find("input#hotel-code, input#booking-code").blur(function() { if ($(this).val() != "") { return; } $(this).parent("span").hide(); $(this).parent("span").prev("a").css("display", "block"); });
            //resetDestinations=function(){if(oFormHelper.DestinationCodes[0]!=""){if(oListHelper.DestinationContainer.ValueItems(oFormHelper.DestinationCodes[0]).length==0){oListHelper.DestinationList.children("dd:first").ClickItem();}}}
            resetDestinations = function() {
                if (oFormHelper.DestinationCodes[0] != "") {
                    if (oListHelper.DestinationContainer.ValueItems(oFormHelper.DestinationCodes[0]).length == 0) {
                        oListHelper.DestinationList.children("dd:first").ClickItem();
                    }
                    else {
                        oListHelper.DestinationList.find("dd").filter(function() { return ($(this).text() == oListHelper.DestinationContainer.children("span:first").text()); }).ClickItem();
                    }
                } else { oListHelper.DestinationContainer.ListItems().eq(0).SetSelected(); }
            }
            addRoomAllocationContainer = function(s) { oRoomHelper.AllocationContainer(":gt(" + (parseInt(s) - 1).toString() + ")").addClass("toggle"); oRoomHelper.AllocationContainer(":lt(" + s + "):gt(0)").removeClass("toggle"); }
            departureClick = function(s) {
                oFormHelper.SetDepartureCodes(oListHelper.DepartureContainer);
                oListHelper.DestinationContainer.SetLoadStatus();
                oListHelper.DestinationList.load(oBaseAjaxUrls.DynamicContent + "Destinations/GetDestinations.aspx?code=" + s + "&type=" + oFormHelper.Type, function() {
                    oListHelper.DestinationContainer.RemoveLoadStatus();
                    oListHelper.DestinationContainer.ListItems().InitEvents();
                    setTimeout("resetDestinations()", 100);
                });
            }
            departureOWClick = function(s) {
                oFormHelper.SetDepartureCodes(oListHelper.DepartureContainerOW);
                oListHelper.ResortContainer.hide();
                oListHelper.DestinationContainerOW.SetLoadStatus();
                oListHelper.DestinationListOW.load(oBaseAjaxUrls.DynamicContent + "Destinations/GetDestinations.aspx?code=" + s + "&type=CHARTER&oneway=1", function() {
                    oListHelper.DestinationContainerOW.RemoveLoadStatus();
                    oListHelper.DestinationContainerOW.ListItems().InitEvents();
                    if ((setDestinationSelected) && (typeof (oSearchParams) != "undefined") && (oFormHelper.Type == "CHARTER_FLT") && (oSearchParams.type == "ONEWAY")) {
                        oListHelper.DestinationListOW.children("dt").filter(function() { return ($(this).attr("class").indexOf(oSearchParams.destcode) > -1); }).filter(":last").next("dd").ClickItem();
                    } else {
                        oListHelper.DestinationContainerOW.ListItems().eq(0).SetSelected();
                    }
                });
            }
            destinationClick = function(s) {
                oValidator.ResetCharterDestination();
                oFormHelper.SetDestinationCodes(oListHelper.DestinationContainer);
                if (oFormHelper.Type != "FLEX_HTL") {
                    oListHelper.PeriodContainer.SetLoadStatus();
                    oListHelper.PeriodList.load(oBaseAjaxUrls.DynamicContent + "GetPeriods.aspx?type=" + oFormHelper.Type + "&depcode=" + oFormHelper.GetDepartureCodeCRS() + "&destcode=" + oFormHelper.GetDestinationCodeCRS() + ((typeForCurrentPeriodCall == oFormHelper.Type) ? "&period=" + oFormHelper.Period : "") + oFormHelper.HotelIdUrlPart(), function() {
                        oListHelper.PeriodContainer.RemoveLoadStatus();
                        oListHelper.PeriodContainer.ListItems().InitEvents();
                        if (oListHelper.PeriodContainer.ListItems(".selected:first").hasClass("disabled")) {
                            oListHelper.PeriodContainer.ListItems().filter(function() { return (!$(this).hasClass("disabled")); }).eq(0).ClickItem();
                        } else if (oListHelper.PeriodContainer.ListItems(".selected").length == 0) {
                            oListHelper.PeriodContainer.ListItems().eq(0).ClickItem();
                        } else {
                            oListHelper.PeriodContainer.ListItems(".selected:first").ClickItem();
                        }
                        oValidator.ValidatePeriod();
                        typeForCurrentPeriodCall = oFormHelper.Type;
                    });
                }
                if (s == "" || s == "0") { oListHelper.ResortContainer.hide(); oListHelper.PeriodList.children("dd").removeClass("disabled"); return; }
                oListHelper.ResortContainer.SetLoadStatus().show(); oListHelper.NumberOfRoomList.addClass("ie6-bug-fix");
                oListHelper.ResortList.load(oBaseAjaxUrls.DynamicContent + "Destinations/GetDestinations.aspx?code=" + s + "&type=" + oFormHelper.Type + "&depcode=" + oFormHelper.GetDepartureCodeCRS(), function() {
                    $(this).SelectFirstItem();
                    oListHelper.ResortContainer.RemoveLoadStatus();
                    oListHelper.ResortContainer.ListItems().InitEvents();
                });
            }
            destinationOWClick = function(s) {
                oFormHelper.SetDestinationCodes(oListHelper.DestinationContainerOW);
                if (s == "" || s == "0" || (oFormHelper.DepartureCodes[0].replace(/CRS-/gi, "") != "")) { oListHelper.ResortContainer.hide(); return; }
                oListHelper.ResortContainer.SetLoadStatus().show();
                oListHelper.ResortList.load(oBaseAjaxUrls.DynamicContent + "Destinations/GetDestinations.aspx?code=" + s + "&type=CHARTER", function() {
                    $(this).SelectFirstItem();
                    oListHelper.ResortContainer.RemoveLoadStatus();
                    oListHelper.ResortContainer.ListItems().InitEvents();
                });
            }
            resortClick = function(s) {
                if (s == "0") { if (oListHelper.DestinationContainerOW.is(":visible")) { oFormHelper.SetDestinationCodes(oListHelper.DestinationContainerOW); } else { oFormHelper.SetDestinationCodes(oListHelper.DestinationContainer); } }
                else { oFormHelper.SetResortCodes(); }
                if (s.substring(0, 2) == "d_") {
                    oListHelper.PeriodContainer.SetLoadStatus();
                    sDestCode = ((oFormHelper.GetResortCodeCRS() != "") ? oFormHelper.GetResortCodeCRS() : oFormHelper.GetDestinationCodeCRS());
                    if (oFormHelper.Type != "FLEX_HTL") {
                        oListHelper.PeriodList.load(oBaseAjaxUrls.DynamicContent + "GetPeriods.aspx?type=" + oFormHelper.Type + "&depcode=" + oFormHelper.GetDepartureCodeCRS() + "&destcode=" + sDestCode + ((typeForCurrentPeriodCall == oFormHelper.Type) ? "&period=" + oFormHelper.Period : "") + oFormHelper.HotelIdUrlPart(), function() {
                            oListHelper.PeriodContainer.RemoveLoadStatus();
                            oListHelper.PeriodContainer.ListItems().InitEvents();
                            if (oListHelper.PeriodContainer.ListItems(".selected:first").hasClass("disabled")) {
                                oListHelper.PeriodContainer.ListItems().filter(function() { return (!$(this).hasClass("disabled")); }).eq(0).ClickItem();
                            } else if (oListHelper.PeriodContainer.ListItems(".selected").length == 0) {
                                oListHelper.PeriodContainer.ListItems().eq(0).ClickItem();
                            } else {
                                oListHelper.PeriodContainer.ListItems(".selected:first").ClickItem();
                            }
                            oValidator.ValidatePeriod();
                            typeForCurrentPeriodCall = oFormHelper.Type;
                        });
                    }
                }
            }
            periodClick = function(s) { oFormHelper.Period = s; oValidator.ResetPeriod(); }
            adultsClick1 = function(s) { oListHelper.ChildrenList.eq(0).ListItems().removeClass("disabled"); oListHelper.ChildrenList.eq(0).ListItems().filter(function() { return (parseInt($(this).text()) > (oBaseAppSettings.MaxPax - parseInt(s))); }).addClass("disabled"); oValidator.ValidateTotalPax(); }
            adultsClick2 = function(s) { oListHelper.ChildrenList.eq(1).ListItems().removeClass("disabled"); oListHelper.ChildrenList.eq(1).ListItems().filter(function() { return (parseInt($(this).text()) > (oBaseAppSettings.MaxPax - parseInt(s))); }).addClass("disabled"); oValidator.ValidateTotalPax(); }
            adultsClick3 = function(s) { oListHelper.ChildrenList.eq(2).ListItems().removeClass("disabled"); oListHelper.ChildrenList.eq(2).ListItems().filter(function() { return (parseInt($(this).text()) > (oBaseAppSettings.MaxPax - parseInt(s))); }).addClass("disabled"); oValidator.ValidateTotalPax(); }
            childrenClick1 = function(s) { oListHelper.ChildrenAgesHolder.eq(0).attr("class", "children-ages number-" + s); oValidator.ValidateTotalPax(); if (s == "0") { oValidator.ValidateChildrenAges(); } }
            childrenClick2 = function(s) { oListHelper.ChildrenAgesHolder.eq(1).attr("class", "children-ages number-" + s); oValidator.ValidateTotalPax(); if (s == "0") { oValidator.ValidateChildrenAges(); } }
            childrenClick3 = function(s) { oListHelper.ChildrenAgesHolder.eq(2).attr("class", "children-ages number-" + s); oValidator.ValidateTotalPax(); if (s == "0") { oValidator.ValidateChildrenAges(); } }
            handleKeyDown = function(o, n) {
                if ((n == 9) || (n == 37) || (n == 39) || (n == 8) || (n == 46)) { return true; }
                else { return ((n >= 48 && n <= 57) || (n >= 96 && n <= 105)); }
            }
            handleKeyUp = function(o) {
                if (o.val() > 17) { o.val(o.val().substring(0, (o.val().length - 1))) }
            }
            $("span.child input").keydown(function(event) { return handleKeyDown($(this), event.keyCode); });
            $("span.child input").keyup(function() { return handleKeyUp($(this)); });
            if (typeof overRide != "undefined") { overRide(); }
        }
        LoadBookingPanel = function() {
            sUrlParams = "";
            if (typeof (oSearchParams) == "undefined" && $.cookie("tui.searchparams") != null) { oSearchParams = JSON.parse($.cookie("tui.searchparams")); }
            else if ((typeof (oSearchParams) != "undefined") && (oSearchParams.source != "") && (oSearchParams.source != "lms")) { oSearchParams.type = "CHARTER"; }
            if ((typeof (oSearchParams) != "undefined") && ($("div.enok-hotel-level").length == 0)) {
                sInnerBookingPanelClass = ($("body:first").hasClass("searchresult")) ? "booking-panel inner-booking-panel" : "inner-booking-panel";
                if (oSearchParams.type == "COMBINATION" || oSearchParams.type == "TRAIN" || oSearchParams.type == "CRUISE" || oSearchParams.type == "CAR") { if (oSearchParams.type == "COMBINATION") { $("div#search-form").addClass("bp-combinations"); } $("div#search-form span.choice input").filter(function() { return ($(this).val() == oSearchParams.type); }).attr("checked", "checked"); }
                else if (oSearchParams.type == "CHARTER_FLT") {
                    sBPClass = ($("div#search-form").hasClass("inner-booking-panel")) ? sInnerBookingPanelClass : "booking-panel";
                    $("div#search-form").attr("class", sBPClass + " bp-tab2 bp-tab2-0").children("ul.tabs:first").attr("class", "tabs tab2");
                }
                else if (oSearchParams.type == "ONEWAY") {
                    sBPClass = ($("div#search-form").hasClass("inner-booking-panel")) ? sInnerBookingPanelClass : "booking-panel";
                    $("input#tab2_4").attr("checked", "checked");
                    $("div#search-form").attr("class", sBPClass + " bp-tab2 bp-tab2-1").children("ul.tabs:first").attr("class", "tabs tab2");
                }
                else if (oSearchParams.type == "FLEX_HTL") {
                    sBPClass = ($("div#search-form").hasClass("inner-booking-panel")) ? sInnerBookingPanelClass : "booking-panel";
                    $("div#search-form").attr("class", sBPClass + " bp-tab3").children("ul.tabs:first").attr("class", "tabs tab3");
                }
                sUrlParams = oSearchParams.urlparams;
                typeForCurrentPeriodCall = oSearchParams.type;
            }
            else if ((typeof (oSearchParams) != "undefined") && ($("div.enok-hotel-level").length > 0)) { sUrlParams = oSearchParams.urlparams; }
            var bookableString = "";
            if ($("input#isBookableOnline").val()) {
                bookableString = "&bookableonline=" + $("input#isBookableOnline").val().toLowerCase();
            }
            $("div#charter").load(oBaseAjaxUrls.DynamicContent + "BookingPanel/BookingPanel.aspx?bid=" + oBaseAppSettings.BrandID + sUrlParams + "&hotelcode=" + getEnokHotelId() + bookableString, function() {

                // TODO: Timing issue: DreamVacation already loaded and displayed on top of the booking panel at this point. Booking panel elements "shine through" and causes white stripes to be displayed in the campaign Flash video. This code prevents this, but maybe there's a better solution.
                var hasQuery = (getQueryStringParameter("showCampaignPage") != "") ? true : false;
                var hasPageQuery = (getQueryStringParameter("page") != "") ? true : false;
                if (typeof Sys !== 'undefined' && typeof Tui !== 'undefined' && ($.cookie("CampaignHasBeenShown") == null || hasQuery))
                //if (typeof Sys !== 'undefined' && typeof Tui !== 'undefined')
                {
                    Tui.Web.DreamVacation.hideProblematicBookingPanelElements();
                }
                else if (hasPageQuery) {
                    if ($.browser.mozilla) {
                        $('.bp-content:first').find('.list-box span, .list-box-large span').hide();
                    }
                }

                $(this).removeClass("bp-content-loading"); InitPage();
                registerHelpTextPopupHandlers($(this));
                if (typeof (oSearchParams) != "undefined") {
                    if ((oFormHelper.Type == "CHARTER_FLT") && (oSearchParams.type == "ONEWAY") && (oSearchParams.destcode != "")) {
                        setDestinationSelected = true;
                        oListHelper.DepartureListOW.children("dd.selected").ClickItem();
                    }
                    else if (((oFormHelper.Type == "CHARTER_FLT") || (oSearchParams.source == "lms" || oSearchParams.source == "dynamictable")) && (oSearchParams.destcode != "")) {
                        oListHelper.DestinationList.children("dt").filter(function() { return ($(this).attr("class").indexOf(oSearchParams.destcode) > -1); }).filter(":last").next("dd").ClickItem();
                    }
                    if (($("div#search-form a.toggle-choices:visible").length > 0) && (oSearchParams.type == "TRAIN" || oSearchParams.type == "CRUISE" || oSearchParams.type == "CAR")) { $("div#search-form a.toggle-choices:visible").trigger("click"); }
                }
            });
        }
        SetReturnDate = function() {
            o = oTUICalendar.DateHolder;
            if (o.parents("div.column:first").find("span.return-date").length == 0) { return; }
            d = addDays(o.children("span.year").text(), o.children("span.month").text(), o.children("span.day").text(), 3);
            oTUICalendar.DateHolder = o.parents("div.column:first").find("span.return-date");
            oTUICalendar.Year = d.getFullYear();
            oTUICalendar.Month = d.getMonth() + 1;
            oTUICalendar.Day = d.getDate();
            oTUICalendar.SetInputDate();
        }
        if (!$("div#search-form").hasClass("inner-booking-panel")) { LoadBookingPanel(); }
        $("a.display-bp").click(function() { $("div#search-form").toggle(); if ($("div#search-form").is(":visible")) { LoadBookingPanel(); } });
        $("a.search-all").click(function() {
            s = $(this).attr("lang");
            if ((s == "") && (typeof (oSearchParams) == "undefined" && $.cookie("tui.searchparams") != null)) {
                oSearchParams = JSON.parse($.cookie("tui.searchparams"));
                var searchtype = (oSearchParams.type == "COMBINATION") ? "CHARTER" : oSearchParams.type;
                var returndateparam = ((oSearchParams.type == "FLEX_HTL") ? "&returndate=" + oSearchParams.returndate[0] + "-" + oSearchParams.returndate[1] + "-" + oSearchParams.returndate[2] : "");
                var combiparam = (oSearchParams.type == "COMBINATION") ? "&combi=true" : "";
                s = oBaseAjaxUrls.BookingSite + "SearchProduct.aspx?depcode=" + oSearchParams.depcode + "&destcode=" + ((oSearchParams.resortcode != "") ? oSearchParams.resortcode : oSearchParams.destcode) + "&period=" + oSearchParams.period + "&type=" + searchtype + "&depdate=" + oSearchParams.depdate[0] + "-" + oSearchParams.depdate[1] + "-" + oSearchParams.depdate[2] + returndateparam + "&PaxInRooms=" + oSearchParams.paxinrooms + "&alt=true" + combiparam;
            }
            else if (s == "") { document.location.href = oBaseAjaxUrls.BookingSite + "SearchForm" + (oBaseAppSettings.IsTemaSite ? "Tema" : "") + ".aspx"; return; }
            if ($("div.page-container").find("div#searching img").length == 0) {
                var imgtag = "<img src=\"" + oBaseAppSettings.IncludeSiteDirectory + "/Images/Layout/BookingPanel/searching" + (oBaseAppSettings.IsTemaSite ? "-tema" : "") + ".jpg\" alt=\"\" />"
                $("div.page-container").find("div#searching").append(imgtag);
            }
            $("div.page-container").addClass("searching");
            $.get(s, function(data) {
                sStatus = $(data).find("Status").text();
                if (sStatus == "OK") {
                    s = $(data).find("Url").text(); /*sHits = $(data).find("SearchHits").text();*/
                    $.cookie("tui.searchresult", null, { path: "/" });
                    document.location.href = s;
                } else {
                    $("input#searchurl").val(s);
                    var code = $(data).find("Code").text();
                    var producttype = $(data).find("ProductType").text();
                    $("input#errorcode").val(code);
                    $("input#producttype").val(producttype);
                    document.forms["errorform"].submit();
                }
            });
        });
        //Calendar
        CalendarStatus = "ready";
        oTUICalendar.Init();
        CallBacks.push("month-list|oTUICalendar.SelectMonth");
        InitListBoxes(oTUICalendar.CalendarObject);
        $(document).click(function() { if (CalendarStatus == "open") { oTUICalendar.Close(); } });
        $("div#calendar").click(function() { CalendarStatus = "ready"; setTimeout("CalendarStatus=\"open\";", 100); });
        if ($.browser.msie && $.browser.version < 7) { oTUICalendar.AllSelectLists = $("select"); }
        //
    }
);

getCountryName=function(){
    if($("div.enok-hotel-level").length>0 && $("div.breadcrumbs a").length>0){
        return $("div.breadcrumbs a:eq(0)").text();
    }else if(oListHelper.DestinationContainer.children("input:hidden").val()=="" || oListHelper.DestinationContainer.children("input:hidden").val()=="0"){
        return "-";
    }else if(oListHelper.DestinationContainer.children("input:hidden").val().split("|")[1].substring(0,1) == "c"){
        return oListHelper.DestinationContainer.children("span").text();
    }else{
        return oListHelper.DestinationContainer.find("dd.selected").prevAll("dd.parent:first").text();
    }
}
getDestinationName=function(){
    if($("div.enok-hotel-level").length>0 && $("div.breadcrumbs a").length>1){
        return $("div.breadcrumbs a:eq(1)").text();
    }else if(oListHelper.DestinationContainer.children("input:hidden").val()=="" || oListHelper.DestinationContainer.children("input:hidden").val()=="0"){
        return "-";
    }else if(oListHelper.DestinationContainer.children("input:hidden").val().split("|")[1].substring(0,1) == "c"){
        if(oListHelper.ResortContainer.children("input:hidden").val()=="" || oListHelper.ResortContainer.children("input:hidden").val()=="0"){
            return "-";
        }else if(oListHelper.ResortContainer.children("input:hidden").val().split("|")[1].substring(0,1) == "d"){
            return oListHelper.ResortContainer.children("span").text();
        }else{
            return oListHelper.ResortContainer.find("dd.selected").prevAll("dd.parent:first").text();
        }
    }else if(oListHelper.DestinationContainer.children("input:hidden").val().split("|")[1].substring(0,1) == "d"){
        return oListHelper.DestinationContainer.children("span").text();
    }else{
        return oListHelper.ResortContainer.find("dd.selected").prevAll("dd.parent:first").text();
    }
}
getResortName=function(){
    if($("div.enok-hotel-level").length>0 && $("div.breadcrumbs a").length>2){
        return $("div.breadcrumbs a:eq(2)").text();
    }else if(oListHelper.ResortContainer.filter(":visible").length>0 && oListHelper.ResortContainer.children("input:hidden").val()!="" && oListHelper.ResortContainer.children("input:hidden").val()!="0" && oListHelper.ResortContainer.children("input:hidden").val().split("|")[1].substring(0,1) == "r"){
        return oListHelper.ResortContainer.children("span").text();
    }else{
        return "-";
    }
}
getHotelName=function(){
    if($("div.enok-hotel-level div#main-header h1").length>0){
        return $("div.enok-hotel-level div#main-header h1").text();
    }else{
        return "-";
    }
}
getEnokHotelId=function(){
    if($("input#enokhotelid").length>0){
        return $("input#enokhotelid").val();
    }else if(typeof(oListHelper)=="object" && oListHelper.HotelCodeHolder.filter(":visible").length>0){
        return oListHelper.HotelCodeHolder.val();
    }else{
        return "-";
    }
}
getPaxPerRoom=function(roomIndex){
    allPax=(oFormHelper.Pax.trim() + "|;|;").split("|");
    if(allPax[roomIndex]==";"){
        return "-";
    }else{
        adults=allPax[roomIndex].split(";")[0];
        children = (allPax[roomIndex].split(";").length < 2 || allPax[roomIndex].split(";")[1] == "") ? "0+0+0" : getChildrenPerRoom(allPax[roomIndex].split(";")[1].split(","));
        return String.format("{0}+{1}", adults, children);
    }
}
getChildrenPerRoom = function(childAges) {
    var teens = 0,
        children = 0,
        infants = 0;
    for (i = 0; i < childAges.length; i++) {
        if (childAges[i] < 2) {
            infants++;
        }
        else if (childAges[i] < 12) {
            children++;
        }
        else {
            teens++;
        }
    }
    return String.format("{0}+{1}+{2}", teens, children, infants);
}
getPanelLocation=function(){
    if($("div#content-start").length>0){
        return "front page";
    }else if($("div.enok-hotel-level").length>0){
        return "hotel page";
    }else if($("div#page-content.message-page-container").length>0){
        return "general message page";
    }else if($("div.serp-holder").length>0){
        return "search result page";
    }else{
        return "booking tab";
    }
}
journeyDurationInDays=function(){
    if(oListHelper.ReturnDateHolder.filter(":visible").length>0){
        var date1 = new Date();
        date1.setFullYear(Number(oListHelper.ReturnDateHolder.children("span.year").text()), Number(oListHelper.ReturnDateHolder.children("span.month").text())-1, Number(oListHelper.ReturnDateHolder.children("span.day").text()));
        var date2 = new Date();
        date2.setFullYear(Number(oListHelper.DepartureDateHolder.children("span.year").text()), Number(oListHelper.DepartureDateHolder.children("span.month").text())-1, Number(oListHelper.DepartureDateHolder.children("span.day").text()));
        return Math.floor((date1.getTime() - date2.getTime()) / 86400000)+1;
    }else{
        return oFormHelper.Period;
    }
}
prepareEventTracking = function(bookingType) {
    var eventLabel = "";
    eventLabel = String.format("{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}|{8}|{9}|{10}|{11}|{12}|{13}",
        (bookingType == "FLEX_HTL") ? "HOTELONLY" : bookingType,
        oListHelper.DepartureContainer.children("span").text(),
        getCountryName(),
        getDestinationName(),
        getResortName(),
        getHotelName(),
        oListHelper.DepartureDateHolder.text(),
        journeyDurationInDays(),
        (oListHelper.NumberOfRoomList.filter(":visible").length > 0) ? oListHelper.NumberOfRoomList.children("input:hidden").val() : "-",
        getPaxPerRoom(0),
        getPaxPerRoom(1),
        getPaxPerRoom(2),
        getEnokHotelId(),
        (oListHelper.BookingCodeHolder.filter(":visible").length > 0) ? oListHelper.BookingCodeHolder.val() : "-"
    );
    oEventTracker.Category = "booking search";
    oEventTracker.Action = getPanelLocation();
    oEventTracker.Label = eventLabel;
}

performSearch = function() {
    if (!oValidator.Validate()) { return; }
    $("div#light-box,div#light-box-content").hide();
    oFormHelper.SetPax();
    var imgtag = "<img src=\""+oBaseAppSettings.IncludeSiteDirectory+"/Images/Layout/BookingPanel/searching" + (oBaseAppSettings.IsTemaSite ? "-tema" : "") + ".jpg\" alt=\"\" />"
    if (oListHelper.PageContainer.find("div#searching img").length == 0) { oListHelper.PageContainer.find("div#searching").append(imgtag); }
    oListHelper.PageContainer.addClass("searching");

    $.cookie("tui.searchparams", null, { path: "/" });
    if (typeof (oSearchParams) == "undefined" || oSearchParams == null) oSearchParams = new Object();
    oSearchParams.type = (((oFormHelper.Type == "CHARTER_FLT") && (oFormHelper.OneWay == "1")) ? "ONEWAY" : oFormHelper.Type);
    oSearchParams.depcode = oFormHelper.GetDepartureCodeCRS();
    oSearchParams.destcode = oFormHelper.GetDestinationCodeCRS();
    oSearchParams.resortcode = oFormHelper.GetResortCodeCRS();
    oSearchParams.period = oFormHelper.Period;
    oSearchParams.paxinrooms = oFormHelper.Pax.trim();
    oSearchParams.depdate = [oListHelper.DepartureDateHolder.children("span.year").text(), oListHelper.DepartureDateHolder.children("span.month").text(), oListHelper.DepartureDateHolder.children("span.day").text()];
    oSearchParams.returndate = [oListHelper.ReturnDateHolder.children("span.year").text(), oListHelper.ReturnDateHolder.children("span.month").text(), oListHelper.ReturnDateHolder.children("span.day").text()];
    //oSearchParams.urlparams="&bookingtype="+oSearchParams.type+"&depcode="+oFormHelper.DepartureCodes[1]+"&destcode="+oFormHelper.DestinationCodes[1]+"&destcodecrs="+((oSearchParams.resortcode!="")?oSearchParams.resortcode:oSearchParams.destcode)+"&resortcode="+((typeof(oFormHelper.ResortCodes[1])!="undefined")?oFormHelper.ResortCodes[1]:"")+"&depyear="+oSearchParams.depdate[0]+"&depmonth="+oSearchParams.depdate[1]+"&depday="+oSearchParams.depdate[2]+"&period="+oSearchParams.period+"&pax="+oSearchParams.paxinrooms;
    oSearchParams.urlparams = "&bookingtype=" + oSearchParams.type + "&depcode=" + oSearchParams.depcode.replace(/-d/gi, "").replace(/-/gi, "") + "&destcode=" + ((typeof (oFormHelper.DestinationCodes[1]) != "undefined") ? oFormHelper.DestinationCodes[1] : "") + "&destcodecrs=" + oSearchParams.destcode + "&resortcode=" + ((typeof (oFormHelper.ResortCodes[1]) != "undefined") ? oFormHelper.ResortCodes[1] : "") + "&depyear=" + oSearchParams.depdate[0] + "&depmonth=" + oSearchParams.depdate[1] + "&depday=" + oSearchParams.depdate[2] + "&period=" + oSearchParams.period + "&pax=" + oSearchParams.paxinrooms;

    var trackSearchEvent = true;
    try {
        prepareEventTracking(oSearchParams.type);
    }
    catch (err) { trackSearchEvent = false; }

    var returndateparam = ((oFormHelper.Type == "FLEX_HTL") ? oFormHelper.GetQuerystringParam("returndate", oFormHelper.ReturnDate()) : "");
    var hotelcodeparam = oFormHelper.GetQuerystringParam("hotelcode", oFormHelper.GetHotelCode());
    var sourceparam = oFormHelper.GetQuerystringParam("source", oFormHelper.GetSource());
    var hotelcodecrsparam = oFormHelper.GetQuerystringParam("hotel", oFormHelper.GetHotelCodeCrs());
    var lmscodeparam = oFormHelper.GetQuerystringParam("lmscode", oFormHelper.GetLmsCode());
    var bookingcodeparam = oFormHelper.GetQuerystringParam("BookingCode", oFormHelper.GetBookingCode());
    var searchtype = (oSearchParams.type == "COMBINATION") ? "CHARTER" : oSearchParams.type;
    var combiparam = (oSearchParams.type == "COMBINATION") ? oFormHelper.GetQuerystringParam("combi", "true") : "";
    var rndparam = oFormHelper.GetQuerystringParam("rnd", Math.ceil(10000 * Math.random()));
    oSearchParams.hotelcode = null;
    oSearchParams.hotel = null;
    oSearchParams.source = null;
    oSearchParams.lmscode = null;
    var hotelUrlPart = ($("input#enokhotelid").length > 0 && $("input#enokhotelid").val() != "" && hotelcodeparam == "") ? "&hotelcode=" + $("input#enokhotelid").val() : "";
    $.cookie("tui.searchparams", JSON.serialize(oSearchParams), { path: "/" });
    s = oBaseAjaxUrls.BookingSite + "SearchProduct.aspx?depcode=" + oSearchParams.depcode + "&destcode=" + ((oSearchParams.resortcode != "") ? oSearchParams.resortcode : oSearchParams.destcode) + "&period=" + oSearchParams.period + "&type=" + searchtype + "&depdate=" + oFormHelper.DepartureDate() + returndateparam + "&PaxInRooms=" + oSearchParams.paxinrooms + bookingcodeparam + hotelcodeparam + sourceparam + hotelcodecrsparam + lmscodeparam + hotelUrlPart + combiparam + rndparam;
    $.get(s, function(data) {
        sStatus = $(data).find("Status").text();
        if (sStatus == "OK") {
            s = $(data).find("Url").text(); /*sHits = $(data).find("SearchHits").text();*/
            $.cookie("tui.searchresult", null, { path: "/" });
            if (trackSearchEvent) {
                oEventTracker.Label = (oEventTracker.Label + "|" + "SUCCESS");
                oEventTracker.SendEvent();
            }
            document.location.href = s;
        } else {
            $("input#searchurl").val(s);
            var code = $(data).find("Code").text();
            var producttype = $(data).find("ProductType").text();
            $("input#errorcode").val(code);
            $("input#producttype").val(producttype);
            if (trackSearchEvent) {
                oEventTracker.Label = String.format((oEventTracker.Label + "|" + "FAILURE (CODE:{0})"), code)
                oEventTracker.SendEvent();
            }
            document.forms["errorform"].submit();
        }
    });
}


  function getQueryStringParameter(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];
        }
    }

$(document).ready(
    function() {
        $("input#TUIWebSessionID").remove();
        $("div#content-inner").append($("div#searching"));
        EnokHelper = function() {
            this.MealsList = null;
            this.FlightClassesList = null;
            this.PackageForm = document.forms["package"];
            this.InitialPrice = null;
            this.BoardType = $("input#boardType");
            this.FlightClass = $("input#flightClass");
            this.PriceHolders = null;
            arrBreadCrumbs = $("div.breadcrumbs").text().split("|");
            this.HotelName = (jQuery.trim(arrBreadCrumbs[arrBreadCrumbs.length - 1]));
            this.AllSelectLists = $("select");
        }
        oEnokHelper = new EnokHelper();
        overRide = function() {
            $("div#search-form a.search-button").unbind("click");
            $("div#search-form a.search-button").click(function() {
                if (!oValidator.Validate()) { return; }
                var imgtag = "<img src=\"" + oBaseAppSettings.IncludeSiteDirectory + "/Images/Layout/Tabs/icon-load-66x66" + (oFormHelper.Type == "TEMA" ? "-tema" : "-white") + ".gif\" alt=\"\" class=\"icon-load\" />"
                o = $("div#main-and-right"); if (o.children("div#matrix").length == 0) { o.prepend("<div id=\"matrix\" class=\"loading\">" + imgtag + "</div>"); } else { o.children("div#matrix").addClass("loading").html(imgtag); }
                oFormHelper.SetPax();
                var numberRooms = $.grep(oFormHelper.Pax, function(n, i) { return n != "" && n != ";" }).length;
                if ((oFormHelper.Type == "CHARTER" || oFormHelper.Type == "TEMA") && numberRooms == 1)
                    performMatrixSearch();
                else {
                    oListHelper.PageContainer = $("div#content-inner");
                    performSearch();
                }
            });
            if ((typeof (oSearchParams) == "object") && (typeof (oSearchParams.source) != "undefined") && (oSearchParams.source != null) && (oSearchParams.source != "")) {
                if (oListHelper.PeriodList.children("dd.selected").hasClass("disabled")) {
                    oListHelper.PeriodList.children("dd").filter(function() { return (!$(this).hasClass("disabled")); }).eq(0).ClickItem();
                }
                oBtn = $("div#search-form a.search-button"); setTimeout("oBtn.trigger('click');", 500);
            }
        }
        $("span.choice input").click(function() {
            switch ($(this).val()) {
                case "CHARTER":
                case "FLEX_PKG": $("div#search-form").attr("class", "bp-tab1");
                    break;
                case "FLEX_HTL": $("div#search-form").attr("class", "bp-tab3");
                    break;
            }
        });
        $("div#draggable div.ui-handle a").click(function() { $("div#draggable span.pax-info").remove(); $("div#draggable h3.price").remove(); $("div#draggable,div#light-box").removeClass("hotel-package-win").hide(); if ($.browser.msie && $.browser.version < 7) { oEnokHelper.AllSelectLists.show(); } });
        addMatrixEvents = function(oThis) {
            oThis.find("th.date a.time").click(function() {
                s = $(this).attr("lang");
                $("div#draggable div.ui-handle h3").text(oTUIStrings.sFlightInfoTitle);
                displayDraggable(this, 666).removeClass("hotel-package-win").find("div.ui-content").load(s + " div.flight-info-content");
            });
            oThis.find("a.prev-flights").click(function(event) {
                s = oBaseAjaxUrls.SearchResult + "SearchResult/Matrix/SearchResult.aspx" + oTUIWebSession.UrlPart + "&dir=before&info=" + $(this).attr("rel") + "&type=" + oFormHelper.Type;
                o = $(this).parents("div.content:first");
                o.find("span.load-flights:first").css("display", "block");
                o.find("div.flights-holder:first").hide().load(s + " div.flights-holder > *", function() {
                    o.find("span.load-flights:first").hide();
                    $(this).show();
                    addMatrixEvents($(this));
                });
            });
            oThis.find("a.next-flights").click(function(event) {
                s = oBaseAjaxUrls.SearchResult + "SearchResult/Matrix/SearchResult.aspx" + oTUIWebSession.UrlPart + "&dir=after&info=" + $(this).attr("rel") + "&type=" + oFormHelper.Type;
                o = $(this).parents("div.content:first");
                o.find("span.load-flights:first").css("display", "block");
                o.find("div.flights-holder:first").hide().load(s + " div.flights-holder > *", function() {
                    o.find("span.load-flights:first").hide();
                    $(this).show();
                    addMatrixEvents($(this));
                });
            });
            oThis.find("td a").click(function() {
                s = oBaseAjaxUrls.DynamicContent + "PriceSpec.aspx" + oTUIWebSession.UrlPart + "&matrix=true&selectedPkgCodes=" + $(this).prev("input").val().substring($(this).prev("input").val().indexOf("|") + 1);
                $("div#draggable div.ui-handle h3").text(oTUIStrings.sPriceSpecificationTitle);
                displayDraggable(this, 670).removeClass("hotel-package-win").find("div.ui-content").load(s, function() { });
            });
            oThis.find("a.next-button").click(function() {
                o = $("div#matrix").find("table:visible input:checked");
                if (o.length == 0) { return; } s = $("div#matrix").find("table:visible input:checked").val();
                $("div#light-box").css("height", $(document).height() + 200 + "px").show();
                displayDraggable($(this), 670);
                $("div#draggable").addClass("hotel-package-win").css({ top: (o.offset().top) + "px", left: ($("div#matrix").find("table:first").offset().left) + "px" });
                $("div#draggable div.ui-handle h3.price").remove();
                $("div#draggable div.ui-handle span.pax-info").remove();
                window.scrollTo(0, (o.offset().top - 50));
                if ($.browser.msie && $.browser.version < 7) { oEnokHelper.AllSelectLists.hide(); }
                $("div#draggable div.ui-content").load(oBaseAjaxUrls.SearchResult + "SearchResult/Matrix/HotelPackage.aspx" + oTUIWebSession.UrlPart + "&code=" + s, function() {
                    $("div#draggable div.ui-handle h3").html("").append($(this).find("span.pax-info"));
                    $("div#draggable div.ui-handle").append($(this).find("h3.price"));
                    InitListBoxes($(this));
                    oEnokHelper.InitialPrice = $(this).find("input#initial-price");
                    oEnokHelper.MealsList = $(this).find("div#meals");
                    oEnokHelper.FlightClassesList = $(this).find("td.flight-classes ul li");
                    oEnokHelper.FlightClassesList.children("input").click(function() {
                        flightClassesClick($(this).val());
                    });
                    oEnokHelper.PriceHolders = $(document).find("div.hotel-package-win h3.price");
                    $(this).find("a.close-package").click(function() { $("div#draggable,div#light-box").removeClass("hotel-package-win").hide(); if ($.browser.msie && $.browser.version < 7) { oEnokHelper.AllSelectLists.show(); } });
                    $(this).find("a.select-button").click(function() {
                        oEnokHelper.BoardType.val(oEnokHelper.MealsList.children("input:hidden").val().split("|")[0]);
                        if (oEnokHelper.FlightClassesList.length > 0) { oEnokHelper.FlightClass.val(oEnokHelper.FlightClassesList.children("input:checked").val().split("|")[0]); }
                        _action = $(oEnokHelper.PackageForm).attr("action");
                        $(oEnokHelper.PackageForm).attr("action", _action.appendSessionID());
                        setTimeout("oEnokHelper.PackageForm.submit();", 100);
                    });
                    $(this).find("a.more-flight-info").click(function() {
                        s = oBaseAjaxUrls.DynamicContent + "GetFlightInfo.aspx" + oTUIWebSession.UrlPart;
                        $(this).parents("div.ui-content:first").find("div.flight-info-container").show().load(s + " div.flight-info-content > *", function() { $(this).find("div.box-control").removeAttr("class"); $(this).prepend("<a href=\"javascript:void(0)\" class=\"close-flight-info\">x</a>"); $(this).removeClass("flight-info-loading"); $(this).find("a.close-flight-info").click(function() { $(this).parents("div.flight-info-container").html("").hide().addClass("flight-info-loading"); }); });
                    });
                    if ($(this).find("td.flight-classes").html() == "") { $(this).find("tr.head td:last").html(""); }
                });
            });
        }
        $("a.show-season-link").click(function() {
            var seasonId = $(this).attr("id").substr($(this).attr("id").lastIndexOf("-") + 1);
            $(this).parents("div#other-seasons").find("ul#list-season-" + seasonId).toggle();
            $(this).toggleClass("expanded");
        });

        //this is just to make sure no season links appear when there are no citys/destinations to show. this should never happen though. 
        $("div#other-seasons ul").each(function(index) {
            if ($(this).children("li").length == 0) {
                var seasonId = $(this).attr("id").substr($(this).attr("id").lastIndexOf("-") + 1);
                $(this).parents("div#other-seasons").find("a#show-season-" + seasonId).hide();
            }
        });
        mealsClick = function(s) {
            n1 = s.split("|")[2];
            n2 = (oEnokHelper.FlightClassesList.length > 0) ? oEnokHelper.FlightClassesList.children("input:checked").val().split("|")[2] : parseInt(oEnokHelper.InitialPrice.val());
            oEnokHelper.PriceHolders.text(formatNumber((parseInt(n1) + parseInt(n2))).toString() + oTUIStrings.sCurrencySign);
        }
        flightClassesClick = function(s) {
            n1 = s.split("|")[2];
            n2 = (oEnokHelper.MealsList.length > 0) ? oEnokHelper.MealsList.children("input:hidden").val().split("|")[2] : 0;
            oEnokHelper.PriceHolders.text(formatNumber((parseInt(n1) + parseInt(n2))).toString() + oTUIStrings.sCurrencySign);
        }
        $("span.editable-false input:radio").attr("disabled", "disabled");
        CallBacks.push("meals|mealsClick");
    }
);

formatNumber=function(n){
    if(isNaN(n)){return("0");}
    s=n.toString();nStart = s.indexOf(" ");
	if(nStart<0){nStart=s.length;}nStart-=3;
	while(nStart>= 1){s=s.substring(0,nStart)+" "+s.substring(nStart,s.length);nStart-=3;}
	return s;
}

performMatrixSearch=function() {
    var trackSearchEvent=true;
    try{
        prepareEventTracking(oFormHelper.Type);
    }
    catch(err){trackSearchEvent=false;}

    s = oBaseAjaxUrls.SearchResult + "SearchResult/Matrix/SearchResult.aspx?depcode=" + oFormHelper.GetDepartureCodeCRS() + "&period=" + oFormHelper.Period + "&type=" + oFormHelper.Type + "&depdate=" + oFormHelper.DepartureDate() + "&PaxInRooms=" + oFormHelper.Pax.trim() + "&hotelid=" + $("input#enokhotelid").val() + "&lmsCode=" + oFormHelper.GetLmsCode() + "&BookingCode=" + oFormHelper.GetBookingCode();
    o.children("div#matrix").css("display","block").load(s+" div.matrix",function(){
        if(trackSearchEvent){
            oEventTracker.Label=(oEventTracker.Label + "|" + (($(this).find("table.flights-matrix").length>0)?"SUCCESS":"FAILURE"));
            oEventTracker.SendEvent();
        }
        registerHelpTextPopupHandlers($(this));
        $(this).removeClass("loading");
        oTUIWebSession.Reload();
        $(this).find("h3#hotel-name").text(oEnokHelper.HotelName);
        $(this).find("a.close").click(function(){$("div#matrix").hide();});
        addMatrixEvents($(this));
    });
}

if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();