﻿/*
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);
}
