/* DETECTS: text-shadow, border-radius, box-shadow, css transitions */
window.Modernizr=function(e,g,h){function l(c,a){var b=c.charAt(0).toUpperCase()+c.substr(1),i;a:{b=(c+" "+t.join(b+" ")+b).split(" ");for(var p in b)if(q[b[p]]!==h&&(!a||a(b[p],m))){i=true;break a}}return!!i}var d={},j=g.documentElement;g.head||g.getElementsByTagName("head");var m=g.createElement("modernizr"),q=m.style;g.createElement("input");" -webkit- -moz- -o- -ms- -khtml- ".split(" ");var t="Webkit Moz O ms Khtml".split(" ");e={};var r=[],k;(function(){var c={select:"input",change:"input",submit:"form",
reset:"form",error:"img",load:"img",abort:"img"};return function(a,b){b=b||g.createElement(c[a]||"div");a="on"+a;var i=a in b;if(!i){b.setAttribute||(b=g.createElement("div"));if(b.setAttribute&&b.removeAttribute){b.setAttribute(a,"");i=typeof b[a]==="function";typeof b[a]===h||(b[a]=h);b.removeAttribute(a)}}return i}})();var n={}.hasOwnProperty,s;s=typeof n!==h&&typeof n.call!==h?function(c,a){return n.call(c,a)}:function(c,a){return a in c&&typeof c.constructor.prototype[a]===h};e.borderradius=
function(){return l("borderRadius","",function(c){return(""+c).indexOf("orderRadius")!==-1})};e.boxshadow=function(){return l("boxShadow")};e.textshadow=function(){return g.createElement("div").style.textShadow===""};e.csstransitions=function(){return l("transitionProperty")};for(var o in e)if(s(e,o)){k=o.toLowerCase();d[k]=e[o]();r.push((d[k]?"":"no-")+k)}d.crosswindowmessaging=d.postmessage;d.historymanagement=d.history;d.addTest=function(c,a){c=c.toLowerCase();if(!d[c]){a=!!a();j.className+=" "+
(a?"":"no-")+c;d[c]=a;return d}};q.cssText="";m=f=null;d._enableHTML5=true;d._version="1.6";j.className=j.className.replace(/\bno-js\b/,"")+" js";j.className+=" "+r.join(" ");return d}(this,this.document);;
(function($) {
  
  var defaults = {
    'swipeTolerance': 40
  };
  
  var touchStatus = function(target, touch) {
    this.target    = $(target);
    this.touch     = touch;
    this.startX    = this.currentX = touch.screenX;
    this.startY    = this.currentY = touch.screenY;
    this.eventType = null;
  }
  touchStatus.options = {};
  touchStatus.latestTap = null;

  touchStatus.prototype.move = function(touch) {
    this.currentX = touch.screenX;
    this.currentY = touch.screenY;
  }

  touchStatus.prototype.process = function() {
    var offsetX = this.currentX - this.startX;
    var offsetY = this.currentY - this.startY;
    if(offsetX == 0 && offsetY == 0) {
      this.checkForDoubleTap();
    } else if(Math.abs(offsetY) > touchStatus.options.swipeTolerance && Math.abs(offsetY) > Math.abs(offsetX)) {
      this.eventType = offsetY > 0 ? 'swipedown' : 'swipeup';
      this.target.trigger('swipe', [this])
    } else if(Math.abs(offsetX) > touchStatus.options.swipeTolerance) {
      this.eventType = offsetX > 0 ? 'swiperight' : 'swipeleft';
      this.target.trigger('swipe', [this])
    }
    if(this.eventType) this.target.trigger(this.eventType, [this])
    this.target.trigger('touch',        [this])
  }

  touchStatus.prototype.checkForDoubleTap = function() {
    if(touchStatus.latestTap) {
      if((new Date() - touchStatus.latestTap) < 400) 
        this.eventType = 'doubletap'
    }
    if(!this.eventType) this.eventType = 'tap'
    touchStatus.latestTap = new Date()
  }

  var swipeEvents = function(elements, options) {
    touchStatus.options = $.extend(defaults, options);
    elements.bind('touchstart',  this.touchStart);
    elements.bind('touchmove',   this.touchMove);
    elements.bind('touchcancel', this.touchCancel);
    elements.bind('touchend',    this.touchEnd);
  }

  swipeEvents.prototype.touchStart = function(evt) {
    var target = this;
    swipeEvents.eachTouch(evt, function(touch) {
      swipeEvents.touches[touch.identifier] = new touchStatus(target, touch);
    })
  }

  swipeEvents.prototype.touchMove = function(evt) {
    swipeEvents.eachTouch(evt, function(touch) {
      var loc = swipeEvents.touches[touch.identifier]
      if(loc) loc.move(touch)
    })
  }

  swipeEvents.prototype.touchCancel = function(evt) {
    swipeEvents.eachTouch(evt, function(touch) {
      swipeEvents.purge(touch, true)
    })
  }

  swipeEvents.prototype.touchEnd = function(evt) {
    swipeEvents.eachTouch(evt, function(touch) {
      swipeEvents.purge(touch)
    })
  }

  swipeEvents.touches = {}
  swipeEvents.purge = function(touch, cancelled) {
    if(!cancelled) {
      var loc = swipeEvents.touches[touch.identifier]
      if(loc) loc.process()
    }
    delete swipeEvents.touches[touch.identifier]
  }

  swipeEvents.eachTouch = function(evt, callback) {
    var evt = evt.originalEvent;
    var num = evt.changedTouches.length;
    for(var i = 0; i < num; i++) {
      callback(evt.changedTouches[i])
    }
  }

  // adds custom events:
  //   touch      // all events
  //   swipe      // only swipe* events
  //   swipeleft
  //   swiperight
  //   swipeup
  //   swipedown
  //   tap
  //   doubletap
  $.fn.addSwipeEvents = function(options, callback) { 
    if (!callback && jQuery.isFunction(options)) {
      callback = options;
      options = null;
    }
    new swipeEvents(this, options);
    if(callback) this.bind('touch', callback);
    return this;
  }
})(jQuery);;
(function ($, Carnival) {

    if (!Carnival) Carnival = {};

    if (!Carnival.Header2013) Carnival.Header2013 = {};

    var nav = {};

	nav.$el = $("#ccl-refresh-header");
	nav.$searchForm = $('.search-wrapper form');
	nav.$searchFormInput = $('#ccl_header_site-search');

	nav.searchURL = applyUriSanitazion($("#hSearchUrl").val());

    nav.animationTime = 300;

    nav.closeTime = 500;

    nav.currentFlyoutTimer;

    nav.transitions = Modernizr.csstransitions;

    nav.placeholder = (function () { var i = document.createElement('input'); return 'placeholder' in i; })();

    nav.touch = Modernizr.touch;

    nav.shadow = Modernizr.boxshadow;

    nav.init = function () {

        // header alert
        nav.headerAlert();

        // subscribe and save slide-down section
        nav.initSubscribe();

        // locale, compass tooltip
        nav.navTooltips();

        // flyouts
        nav.initFlyouts();

        // forgot username/pw lightboxes
        //nav.initForgot();

        // icon hover states
        nav.iconHover();

        // no-click links
        nav.initNoClick();

        // placeholder support
        nav.supportPlaceholder();

        // search form
        nav.initSearch();

        // tagging
        nav.initTagging();

        //set the mybooking links
        //nav.handleMyBookingLink();

        //set the Manage Flyout links
        //nav.manageFlyoutInit();
        if (Carnival.Header2013 && Carnival.Header2013.CCLHeader2013Personalizer && Carnival.Header2013.CCLHeader2013Personalizer.personlizeMangeTab) {
            Carnival.Header2013.CCLHeader2013Personalizer.personlizeMangeTab();
        }
        //set active tab
        nav.hightLightActiveTab();

        //set the header advisories
        /* moved to footer
        Carnival.headerAdvisories.dynamicallyLoadAdvisoryContent('{}', nav.$el, '.message-bar', '.inner', '.message-bar-close');

        //////////////////////// D O M A I N   N O T I F I C A T I O N /////////////////
        if (Carnival.domainNotifCookie && Carnival.domainNotifCookie.getDomainNotifCookie() == null ||
            Carnival.domainNotifCookie.getDomainNotifCookie() == 'set') {
            Carnival.domainNotifCookie.dynamicallyLoadDomainNotification(nav.$el, '.notif-bar', ".notif-bar-close", '.inner');
        }
        */
        ////////////////////////////////////////////////////////////////////////////////
    };
    
    nav.initForgot = function () {
        //nav.$el.find(".forgot").colorbox({
        //    iframe: true,
        //    opacity: 1,
        //    width: 510,
        //    height: 600,
        //    transition: "none"
        //});
    };

    nav.initSubscribe = function (command) {
        var $subscribe = nav.$el.find(".header-subscribe"),
             $triggers = nav.$el.find("#subscribeLink"),
             $closebutton = $subscribe.find(".close");

        $closebutton.attr("id", "btn-close-header-subscribe");

        if (command == "close") {
            $subscribe.slideUp("fast");
            return false;
        }

        var scapeFunction = function () {
            $subscribe.slideUp("fast");
            $triggers.focus();
        }

        var closeFunction = function () {
            $subscribe.slideUp("fast");
            $triggers.attr("aria-expanded", "false");
			$triggers.focus();
        }

        $triggers.focus(function () {
            var $tooltiptriggers = nav.$el.find(".nav-tooltip-trigger");

            $tooltiptriggers.each(function () {
                $(this).data("mouseleave")(true);
            });
        });

        $triggers.click(function () {
            //if (nav.touch) {
            //    nav.closeAll();
            //}

            $triggers.attr("aria-expanded", $triggers.attr("aria-expanded") == "true" ? "false" : "true");
            nav.closeAll();
            nav.navTooltips("close");
            $subscribe.slideToggle("fast");
            setFocusModal("EmailSubscribeContainer", scapeFunction, closeFunction, null, "btn-close-header-subscribe", true);
            return false;
        });

        $closebutton.click(function () {
            closeFunction();
            return false;
        });
    };

    nav.initTagging = function () {

        if (!(window.s_gi && window.s_account)) return false;

        var $localLinks = nav.$el.find("#ccl_header_locale_options a"),
			$popularLinks = nav.$el.find(".popular-box a"),
			$searchBtn = nav.$el.find("#ccl_header_site-search-submit");

        // locale links
        $localLinks.click(function () {
            var s = s_gi(s_account);
            s.linkTrackVars = "s.prop8";
            s.prop8 = $(this).text().trim();
            s.tl(this, 'o', s.pageName + ': Country Selector');
        });

        // popular search terms
        $popularLinks.click(function () {
            var s = s_gi(s_account);
            s.linkTrackVars = "s.prop15";
            s.prop15 = $(this).text();
            s.tl(this, 'o', s.pageName + ': Popular Searches');
        });

        $searchBtn.click(function () {
            var $search = $("#ccl_header_site-search"),
				val = $.trim($search.val()),
				s = null;

            if (val.length && val.toLowerCase() != $search.attr("placeholder").toLowerCase()) {
                s = s_gi(s_account);
                s.linkTrackVars = "s.prop15";
                s.prop15 = val;
                s.tl(this, 'o', s.pageName + ': Search');
            }
        });
    };

    nav.supportPlaceholder = function () {

        if (nav.placeholder) return false;

        var $inputs = nav.$el.find("[placeholder]");

        $inputs.focus(function () {
            var o = $(this),
				ph = o.attr("placeholder");

            if (o.val() == ph) o.val("").removeClass("placeholder");
        }).blur(function () {
            var o = $(this),
				ph = o.attr("placeholder");

            if (o.val() === "") o.val(ph).addClass("placeholder");
        }).trigger("focus").trigger("blur");
	};

	nav.addSearch = function () {

		var ffEnabled = !(Carnival.SiteSearch && Carnival.SiteSearch.DisableAddSearch && Carnival.SiteSearch.DisableAddSearch === true);

		return {
			Enabled: function () {
				return (
					nav.$searchForm &&
					nav.$searchForm.length > 0 &&
					nav.$searchFormInput &&
					nav.$searchFormInput.length > 0 &&
					ffEnabled);
			}
		};
	

	};

    nav.initSearch = function () {
        var $search = $("#ccl_header_site-search"),
			$submit = $("#ccl_header_site-search-submit"),
            $glassSearch = $("#glass_search");

        var anchors = nav.$el.find(".popular-box li > a");

        $("#ccl_header_site-search").attr('aria-label', 'Type what you are looking for on carnival.com');

		var addSearch = nav.addSearch();
		if (addSearch.Enabled()) {

			nav.$searchForm.attr("method", "get");
			nav.$searchForm.attr("action", "search");
			nav.$searchFormInput.attr("name", "addsearch");

		}

        $search.bind("keydown", function (event) {
            if (event.keyCode == 13) {
                $submit.click();
                event.stopPropagation();
                event.preventDefault();
            }
            if (event.keyCode == 27) {
                var focus = nav.$el.find(".initialized");
                nav.closeAll();
                focus.focus();
            }
        });

        anchors.each(function () {
            $(this).on("blur",
                function () {
                    if (nav.$el.find(".popular-box:focus-within").length === 0) {
                        nav.closeAll();
                    }
                });
        });


        $submit.bind("keydown", function (event) {
            if (event.keyCode == 27) {
                var focus = nav.$el.find(".initialized");
                nav.closeAll();
                focus.focus();
            }
        });

        $submit.click(function () {
			var val = cleanUrl($.trim($search.val()));
			
			if (!addSearch.Enabled()) { 

				if (val.toLowerCase() != $search.attr("placeholder").toLowerCase()) {
					$(document).trigger("internal-site-search-trigger");
					location.href = nav.searchURL + encodeURIComponent(val);
				}
				// For IE
				else {
					location.href = nav.searchURL;
				}
			}

        });

        function cleanUrl(d) {

            if (!d) {
                d = "";
            }
            d = d.replace('>', '');
            d = d.replace('<', '');
            //d = d.replace(/[^a-zA-Z0-9]/g, '');

            return d;
        }

        $glassSearch.attr('href', nav.searchURL);
    };

    nav.iconHover = function () {
        var $links = nav.$el.find(".flyout > ul > li > a");

        //preload all hover states
        $links.each(function (i, lnk) {
            var $img = $(lnk).find(".img img"),
                hover = $img.data("hover");

          if (hover) {
            _preload(hover);
          }
        });

        function _preload(url) {
            var img = new Image();
            img.src = url;
        }

        //if (!nav.touch) {
        $links.data("mouseenter", function (_this) {
            var $img = $(_this).find(".img img"),
                def = $img.data("default"),
                hover = $img.data("hover");

            $(_this).addClass("hover");

            if (def && hover) {
                $img.attr("src", hover);
            }
        }).bind("mouseenter", function () { $(this).data("mouseenter")(this); });

        $links.data("mouseleave", function (_this) {
            var $img = $(_this).find(".img img"),
                def = $img.data("default"),
                hover = $img.data("hover");

            $(_this).removeClass("hover");

            if (def && hover) {
                $img.attr("src", def);
            }
        }).bind("mouseleave", function () { $(this).data("mouseleave")(this); });
        //}

        if (nav.touch) {
            $links.unbind("mouseenter mouseleave").bind("click", function () {
                var lnk = $(this);

                if (lnk.hasClass("hover")) {
                    lnk.data("mouseleave")(lnk);
                } else {
                    lnk.data("mouseenter")(lnk);
                }
            });
        }

    };

    nav.clearCloseTimout = function (toName) {
        if (nav[toName]) { clearTimeout(nav[toName]); nav[toName] = null; }
    };

    nav.exposeFlyouts = function ($flyout) {
        var $wrap = nav.$el.find(".header-flyouts");

        nav.closeAll($flyout);

        if (nav.transitions) {

            if (!$wrap.hasClass("exposed")) {
                $flyout.addClass("active");
                $wrap.addClass("exposed");
                $wrap.show();
                clearTimeout(nav.currentFlyoutTimer);
                nav.currentFlyoutTimer = setTimeout(function () {
                    $flyout.addClass("active showUL");
                }, nav.animationTime);
            } else {
                $flyout.addClass("active");
                clearTimeout(nav.currentFlyoutTimer);
                nav.currentFlyoutTimer = setTimeout(function () {
                    $flyout.addClass("showUL");
                }, 100);
            }

        } else {

            if (!$wrap.hasClass("exposed")) {
                $flyout.addClass("active showUL");
                $wrap.addClass("exposed");
                $wrap.show();
            } else {
                $flyout.addClass("active showUL");
            }

        }
    };

    nav.closeAll = function ($exclude) {
        var $wrap = nav.$el.find(".header-flyouts"),
			$flyouts = $wrap.find(".flyout"),
			$inputs = $wrap.find("input:visible");

        //$inputs.blur();

        if ($exclude) {
            $flyouts = $flyouts.not($exclude);
            $flyouts.removeClass("showUL active");
        } else {
            $wrap.removeClass("exposed");
            $wrap.hide();
            nav.$el.find(".canHover.hover").removeClass("hover");
            if (nav.transitions) {
                setTimeout(function () {
                    $flyouts.removeClass("showUL active");
                }, nav.animationTime);
            } else {
                $flyouts.removeClass("showUL active");
            }
        }

        
    };

    nav.headerAlert = function () {
        nav.$el.find(".header-alert-close").click(function () {
            $(this).parents('.header-alert').slideUp('fast');
            return false;
        });
    };

    nav.navTooltips = function (command) {
        var $triggers = nav.$el.find(".nav-tooltip-trigger"),
			$white = nav.$el.find(".header-branding"),
			tooltipTimeout = null;

        if (command == "close") {
            $triggers.each(function () {
                $(this).data("mouseleave")(true);
            });

            return false;
        }

        var $tooltipsitems = nav.$el.find(".nav-tooltip");
        $tooltipsitems.find("a").bind("keydown", function (event) {
            if (event.keyCode == 27) {
                var nextfocus = nav.$el.find(".hover");
                nextfocus = nextfocus.find(".nav-tooltip-trigger");
                nextfocus.data("mouseleave")(true);
                nextfocus.focus();
                return false;
            }
            if (event.shiftKey && event.keyCode == 9) {
                $(this).addClass("preventClose");
            }
        });

        $tooltipsitems.find("a").bind("blur", function (event) {
            if ($(this).attr("class")) {
                if ($(this).attr("class").indexOf("preventClose") > -1) {
                    $(this).removeClass("preventClose");
                }
            }
            else {
                var elemento = $(this).parent();
                while (!elemento.attr("data-id")) {
                    elemento = elemento.parent();
                }
                var parentCurrentlyFocus = elemento.attr("id");

                $nextTabbable = $(this).next(":tabbable").length
                    ? $(this).next(":tabbable")
                    : $(this).parent().next().find(":tabbable");

                if ($nextTabbable.length > 0) {
                    while (!$nextTabbable.attr("data-id")) {
                        $nextTabbable = $nextTabbable.parent();
                    }
                    var parentNextFocus = $nextTabbable.attr("id");
                    if (parentCurrentlyFocus != parentNextFocus) {
                        var nextfocus = nav.$el.find(".hover");
                        nextfocus = nextfocus.find(".nav-tooltip-trigger");
                        nextfocus.data("mouseleave")(true);
                    }
                } else {
                    var nextfocus = nav.$el.find(".hover");
                    nextfocus = nextfocus.find(".nav-tooltip-trigger");
                    nextfocus.data("mouseleave")(true);
                }
            }
        });

        $triggers.bind("focus", function () {
            $triggers.each(function () {
                $(this).data("mouseleave")(true);
            });
        });

        $triggers.each(function () {
            var $localeLink = $(this),
				id = $localeLink.data("id"),
				$localeTooltip = nav.$el.find(".nav-tooltip[data-id='" + id + "']"),
				myTimeout = null;

            $localeLink.add($localeTooltip).data("mouseenter", function () {
                if (myTimeout) { clearTimeout(myTimeout); }
                if (tooltipTimeout) { clearTimeout(tooltipTimeout); }

                $localeLink.attr("aria-expanded", "true");

                $localeLink.parent().addClass("hover");
                $white.addClass("increaseZ");
                $triggers.not($localeLink).each(function () {
                    $(this).parent().removeClass("hover");
                });
            }); //.bind("mouseenter", function(){$(this).data("mouseenter")();});

            $localeLink.add($localeTooltip).data("clearTimeouts", function () {
                if (myTimeout) { clearTimeout(myTimeout); }
                if (tooltipTimeout) { clearTimeout(tooltipTimeout); }
            }).bind("mouseenter", function () { $(this).data("clearTimeouts")(); });

            $localeLink.add($localeTooltip).data("mouseleave", function (immediate) {
                if (immediate === true) {
                    $localeLink.parent().removeClass("hover");
                    $white.removeClass("increaseZ");
                    $localeLink.attr("aria-expanded", "false");
                } else {
                    myTimeout = setTimeout(function () {
                        $localeLink.parent().removeClass("hover");
                        $localeLink.attr("aria-expanded", "false");
                    }, nav.closeTime);

                    tooltipTimeout = setTimeout(function () {
                        $white.removeClass("increaseZ");
                        $localeLink.attr("aria-expanded", "false");
                    }, nav.closeTime);
                }
            }).bind("mouseleave", function () { $(this).data("mouseleave")(); });



            // bind touch events
            //if(nav.touch){
            // for locale tooltip
            //$localeLink.unbind("mouseenter mouseleave")
            $localeLink.bind("click", function () {
                var $link = $localeLink,
                    $par = $link.parent();

                if ($par.hasClass("hover")) {
                    $link.data("mouseleave")(true);
                } else {
                    nav.initSubscribe("close");
                    nav.closeAll();
                    $link.data("mouseenter")();
                }

                return false;
            });
            //}

        });

    };

    nav.initNoClick = function () {
        var $noClick = nav.$el.find("a[data-link-disabled='true']");

        $noClick.bind("click", function () { return false; });
    };

    nav.initFlyouts = function () {
        $(".header-flyouts").each(function (index) {
            $(this).hide();
        });

        var $clickable = $("a[data-ccl-flyout-click='true']").addClass("canHover"),
			$flyoutLinks = nav.$el.find("a[data-ccl-flyout]").not("[data-flyout-disabled='true']").not($clickable).addClass("canHover"),
            $flyouts = nav.$el.find(".flyout");

        $flyoutLinks.bind("focus", function () {
            if (!$(this).hasClass('hover')) {
                nav.closeAll();
            }
        });

        // add child class to flyouts
        $flyouts.each(function () {
            var o = $(this).find(">ul"),
				childCount = o.find(">li").length;

            o.addClass("children-" + childCount);
        });

        $flyouts.find("a").bind("keydown", function (event) {
            if (event.keyCode == 27) {
                var focus = nav.$el.find(".initialized");
                nav.closeAll();
                focus.focus();
            }
        });

        $flyouts.find("input, .flyout-btn").on("focus", function () {
            var flyout = $(this).closest(".flyout");

            flyout.trigger("mouseenter");
        });

        if (nav.transitions) {
            $flyoutLinks.each(function () {
                var $span = $(this).find("span").addClass("org"),
					$top = $('<span class="top">' + $span.html() + '</span>'),
					$btm = $('<span class="btm">' + $span.html() + '</span>');

                $(this).append($top, $btm);
            });
        }

        if (!nav.shadow) {
            $flyoutLinks.each(function () {
                $(this).append('<span class="arr"></span>');
            });
        }

        // hover over a link
        $flyoutLinks.add($clickable).data("mouseenter", function (_this) {

            nav.initSubscribe("close");
            var $link = $(_this),
				flyoutID = $link.data("cclFlyout"),
				$flyout = $link.data("flyout"),
                inputs;

            if ($link.hasClass("canHover")) {
                $flyoutLinks.add($clickable).not($link).removeClass("hover");
                $link.addClass("hover initialized");
            }

            if (!$flyout) {
                $flyout = nav.$el.find(".flyout[data-ccl-flyout='" + flyoutID + "']");
                $link.data("flyout", $flyout);
            }

            inputs = $flyout.find("input, .flyout-btn");

            inputs.each(function (i, elm) {
                if ($(elm).attr('id') != "ccl_header_site-search") {
                    $(elm).attr("tabindex", i + 1);
                }
            });

            nav.exposeFlyouts($flyout);
            nav.clearCloseTimout("closeTimeout");

        }).bind("mouseenter", function () { nav.navTooltips("close"); $(this).data("mouseenter")(this); });

        // hover out of a link
        $flyoutLinks.add($flyouts).add($clickable).data("mouseleave", function (immediate, ctx) {
            var $el = $(ctx),
                $focused = $el.find("input:focus"),
                flyout = $el.hasClass("flyout") ? $el : $el.data("flyout"),
                inputs = flyout.find("input, .flyout-btn"),
                butons = flyout.find("button");


            if (immediate === true) {
                nav.closeAll();
                inputs.each(function (i, elm) {
                    $(elm).removeAttr("tabindex");
                });
            } else {
                nav.closeTimeout = setTimeout(function () {
                    nav.closeAll();
                    inputs.each(function (i, elm) {
                        $(elm).removeAttr("tabindex");
                    });
                }, nav.closeTime);
            }
        }).bind("mouseleave", function () { $(this).data("mouseleave")(false, this); });

        // click to activate flyout
        $clickable.unbind("mouseenter mouseleave").bind("click", function () {
            var $link = $(this);

            if ($link.hasClass("hover")) {
                $link.data("mouseleave")(true);
            } else {
                if (nav.touch) {
                    nav.navTooltips("close");
                    nav.initSubscribe("close");
                }
                $link.data("mouseenter")(this);
            }

            return false;
        });

        // hover over a flyout
        $flyouts.data("mouseenter", function () {
            nav.clearCloseTimout("closeTimeout");
        }).bind("mouseenter", function () { $(this).data("mouseenter")(); });


        // bind touch events
        if (nav.touch) {

            // for flyout links
            $flyoutLinks.unbind("mouseenter mouseleave").bind("click", function () {
                return flyoutLinkTouched(this);
            });

        }
    };

    function flyoutLinkTouched(e) {
        var $link = $(e);
        if ($link.hasClass("hover")) {
            $link.data("mouseleave")(true);
        } else {
            nav.navTooltips("close");
            nav.initSubscribe("close");
            $link.data("mouseenter")(e);
        }

        return false;
    }

    nav.hightLightActiveTab = function () {
        var $flyoutLinks = nav.$el.find("a[data-highlightPattern]");
        $flyoutLinks.removeClass('active');
        $flyoutLinks.each(function () {
            var $o = $(this);
            var href = window.document.location.pathname.toLowerCase(); //exclude querystring and hash
            if ($o.attr('data-highlightPattern') && $o.attr('data-highlightPattern').length > 0) {
                var pattern = new RegExp('\\b' + $o.attr('data-highlightPattern').toLowerCase() + '\\b');
                if (pattern.test(href)) {
                    $o.addClass('active');
                    return;
                }
            }
        });
    };

    Carnival.Header2013 = $.extend(nav, Carnival.Header2013);
    window.Carnival = Carnival;


    $(function () {
        if (Carnival.Header2013.$el.length) {
            Carnival.Header2013.init();

            $(".nav-tooltip-trigger").focus(function () {
                nav.closeAll();
            });

            $(".log a").focus(function () {
                nav.closeAll();
            });
        }
	});

	function applyUriSanitazion(uri) {
		return sanitizeUri(uri);
	}

	function sanitizeUri(value) {

		var URI_INVALID_CHARS = /[^-A-Za-z0-9+&@#/%?=~_|!:,.;\(\)\*']/gi;

		var isUriEncoded = function(value) {
			value = value || "";
			try {
				return value !== decodeURI(value);
			} catch (error) {
				return false;
			}
		};

		var trimInvalidChars = function(invalidChars, value) {
			return value.replace(invalidChars, "");
		};

		if (!value)
			return "";

		if (isUriEncoded(value)) {
			value = decodeURI(value);
			value = trimInvalidChars(URI_INVALID_CHARS, value);
			return encodeURI(value);
		}
		return trimInvalidChars(URI_INVALID_CHARS, value);
	}

})(jQuery, window.Carnival);;
/**
 * jQuery DoubleTap
 * Custom touch-screen events
 * for iPads, iPhones, and iPod touches
 * https://github.com/technoweenie/jquery.doubletap
 *
 * Copyright (c) 2010-* rick olson
 */
(function(c){var d={swipeTolerance:40};var a=function(e,f){this.target=c(e);this.touch=f;this.startX=this.currentX=f.screenX;this.startY=this.currentY=f.screenY;this.eventType=null};a.options={};a.latestTap=null;a.prototype.move=function(e){this.currentX=e.screenX;this.currentY=e.screenY};a.prototype.process=function(){var e=this.currentX-this.startX;var f=this.currentY-this.startY;if(e==0&&f==0){this.checkForDoubleTap()}else{if(Math.abs(f)>a.options.swipeTolerance&&Math.abs(f)>Math.abs(e)){this.eventType=f>0?"swipedown":"swipeup";this.target.trigger("swipe",[this])}else{if(Math.abs(e)>a.options.swipeTolerance){this.eventType=e>0?"swiperight":"swipeleft";this.target.trigger("swipe",[this])}}}if(this.eventType){this.target.trigger(this.eventType,[this])}this.target.trigger("touch",[this])};a.prototype.checkForDoubleTap=function(){if(a.latestTap){if((new Date()-a.latestTap)<400){this.eventType="doubletap"}}if(!this.eventType){this.eventType="tap"}a.latestTap=new Date()};var b=function(f,e){a.options=c.extend(d,e);f.bind("touchstart",this.touchStart);f.bind("touchmove",this.touchMove);f.bind("touchcancel",this.touchCancel);f.bind("touchend",this.touchEnd)};b.prototype.touchStart=function(e){var f=this;b.eachTouch(e,function(g){b.touches[g.identifier]=new a(f,g)})};b.prototype.touchMove=function(e){b.eachTouch(e,function(g){var f=b.touches[g.identifier];if(f){f.move(g)}})};b.prototype.touchCancel=function(e){b.eachTouch(e,function(f){b.purge(f,true)})};b.prototype.touchEnd=function(e){b.eachTouch(e,function(f){b.purge(f)})};b.touches={};b.purge=function(g,e){if(!e){var f=b.touches[g.identifier];if(f){f.process()}}delete b.touches[g.identifier]};b.eachTouch=function(e,h){var e=e.originalEvent;var f=e.changedTouches.length;for(var g=0;g<f;g++){h(e.changedTouches[g])}};c.fn.addSwipeEvents=function(e,f){if(!f&&jQuery.isFunction(e)){f=e;e=null}new b(this,e);if(f){this.bind("touch",f)}return this}})(jQuery);

var header_helper = {
	detectIE: function() {
		var ua = window.navigator.userAgent;

		// Test values; Uncomment to check result �

		// IE 10
		// ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';

		// IE 11
		// ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';

		// Edge 12 (Spartan)
		// ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';

		// Edge 13
		// ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586';

		var msie = ua.indexOf('MSIE ');
		if (msie > 0) {
			// IE 10 or older => return version number
			return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
		}

		var trident = ua.indexOf('Trident/');
		if (trident > 0) {
			// IE 11 => return version number
			var rv = ua.indexOf('rv:');
			return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
		}

		var edge = ua.indexOf('Edge/');
		if (edge > 0) {
			// Edge (IE 12+) => return version number
			return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
		}

		// other browser
		return false;
	}
};

var ccl_header2013 = {

    flyoutClosing: false,

    showFlyout: function (elem) {

        var header = $("#ccl_header"),
			ul = header.find(".navigation"),
			li = elem.parent(),
			lis = header.find(".navigation li").not(li),
			id = elem[0].id,
			wrapper = header.find(".flyout-wrapper"),
			flyout = wrapper.find(".flyout." + id),
			flyouts = wrapper.find(".flyout").not(flyout),
			hpContent = $("#ccl_homepage .homepage-content");

        lis.removeClass("active");
        flyouts.hide();

        li.addClass("active");
        flyout.show();


        ccl_header2013.unPIE(ul);

        if (!wrapper.hasClass("expanded")) {

            if (hpContent.length) {

                hpContent.find(".banner-rotator .slideshow").cycle("pause");
                hpContent.delay(80).animate({ "margin-top": "0" }, 60, function () { });

                wrapper.stop(false, true).slideDown("fast", "linear", function () {
                    wrapper.addClass("expanded").css("height", wrapper.height() + "px");
                    ccl_header2013.PIE(ul);
                    ccl_header2013.equalizeSectionHeights(flyout);
                    hpContent.find(".banner-rotator .slideshow").cycle("resume");
                });


            } else {

                wrapper.stop(false, true).slideDown("fast", "linear", function () {
                    wrapper.addClass("expanded").css("height", wrapper.height() + "px");
                    ccl_header2013.PIE(ul);
                    ccl_header2013.equalizeSectionHeights(flyout);
                });

            }

        } else {
            var newHeight = 0;
            flyout.each(function () {
                var h = $(this).height();
                newHeight += (h + 90);
            });
            ccl_header2013.unPIE(ul);
            ccl_header2013.PIE(ul);
            ccl_header2013.equalizeSectionHeights(flyout);
            wrapper.animate({ height: newHeight + "px" }, 150, "linear");
        }

    },

    hideFlyouts: function () {

        var header = $("#ccl_header"),
			ul = header.find(".navigation"),
			lis = ul.find("li"),
			wrapper = header.find(".flyout-wrapper"),
			flyouts = wrapper.find(".flyout"),
			hpContent = $("#ccl_homepage .homepage-content");

        ccl_header2013.unPIE(ul);

        if (wrapper.hasClass("expanded") && !ccl_header2013.flyoutClosing) {
            lis.removeClass("active");
            ccl_header2013.flyoutClosing = true;


            if (hpContent.length) {
                hpContent.find(".banner-rotator .slideshow").cycle("pause");
                hpContent.animate({ "margin-top": "-62px" }, 50, "linear");
            }

            wrapper.stop(false, true).slideUp("fast", "linear", function () {
                flyouts.hide();
                wrapper.removeClass("expanded").removeAttr("style");
                ccl_header2013.flyoutClosing = false;

                ccl_header2013.PIE(ul);
                ccl_header2013.adjustHeight(25);
                if (hpContent.length) {
                    hpContent.find(".banner-rotator .slideshow").cycle("resume");
                }
            });
        } else {
            lis.removeClass("active");
            flyouts.hide();
            wrapper.stop().removeClass("expanded").hide().removeAttr("style");
            ccl_header2013.flyoutClosing = false;
            if (hpContent.length) {
                hpContent.stop(true, false).css("margin-top", "-62px");
            }
            ccl_header2013.PIE(ul);
            ccl_header2013.adjustHeight(25);
        }
    },

    initPIE: function () {
        if (window.PIE) {
            $("#ccl_header .header-top, #ccl_header ul.navigation, #ccl_header ul.navigation li.first-child, #ccl_header .site-search, #ccl_homepage #ccl_header .trans-wrap").each(function () {
                PIE.attach(this);
            });
        }
    },

    PIE: function (elem) {
        if (window.PIE) {
            PIE.attach(elem[0]);
        }
    },

    unPIE: function (elem) {
        if (window.PIE) {
            PIE.detach(elem[0]);
        }
    },

    originalHeight: 0,

	adjustHeight: function (pad) {

		var ie = header_helper.detectIE();

        if (ie && ie < 8) {
            var height = $(document).height(),
				 btm = $("#ccl_header .top-section");

            if (height > (ccl_header2013.originalHeight + pad)) {
                btm.css("margin-bottom", "1px");
                setTimeout(function () {
                    btm.css("margin-bottom", "0");
                }, 50);
            }
        }
    },

    supportPH: function () {
        var phSupport = ("placeholder" in document.createElement("input"));

        $("#ccl_header *[placeholder][type!=password]").each(function () {
            var o = $(this),
			ph = o.attr("placeholder");

            o.val(ph).focus(function () {
                if (o.val() == ph) { o.val(""); }
            }).blur(function () {
                if (o.val() == "") { o.val(ph); }
            }).removeAttr("placeholder");
        });


        $("#ccl_header input[type=password]").each(function () {
            if ($(this).parent().is(".pw-wrap")) {
                var o = $(this),
					 ph = o.attr("placeholder"),
					 id = o.attr("id"),
					 lbl = $('<label for="' + id + '">' + ph + '</label>');

                if (o.hasClass("error")) {
                    o.parent().addClass("error");
                }

                if (phSupport) {
                    o.removeAttr("placeholder");
                }

                o.before(lbl).focus(function () {
                    lbl.hide();
                }).blur(function () {
                    if (o.val() == "") { lbl.show(); }
                });

                o.val() == "" ? lbl.show() : lbl.hide();
            }
        });
    },

    equalizeSectionHeights: function (flyout) {

        flyout.each(function () {
            var fo = $(this);

            if (!fo.hasClass("equalized")) {
                var sects = fo.find(".section"),
					maxHeight = 0;

                sects.each(function () {
                    if ($(this).height() > maxHeight) { maxHeight = $(this).height(); }
                });

                sects.css("height", maxHeight + "px");
                fo.addClass("equalized");
            }

        });

    },

    handleLoggedStates: function () {
        //look for logged in cookie
        if (false) {
            $("#ccl_header").addClass("logged-in");
        }
    },

    getCookieDomain: function () {
        var domain = document.domain;
        if (domain == "localhost") return "";
        if (domain.indexOf(".com") > 0) {
            if (domain.indexOf(".") < domain.indexOf(".com")) domain = domain.substr(domain.indexOf(".") + 1);
            return domain;
        }
        else
            return "";
    },

    setReturnerCookie: function () {
        if (typeof returnerCookieExpirationDays === 'undefined')
            return;

        var retPersistent = $.cookie("CCL_IsReturner");
        var retSession = $.cookie("CCL_ExistingSession");
        var cookieDomain = ccl_header2013.getCookieDomain();

        if (retPersistent == undefined || retPersistent == 'false') {
            retPersistent = (retSession == undefined && retPersistent == 'false');
        }

        if (!retSession) {
            $.cookie("CCL_ExistingSession", 'true', { secure: true, path: '/', domain: cookieDomain });
        }

        $.cookie("CCL_IsReturner", retPersistent, { secure: true, path: '/', expires: returnerCookieExpirationDays, domain: cookieDomain });
    },

    dropEmailCookie : function() {
        var queryString = window.location.search.slice(1),
            emailCookie = $.cookie("mk_email_seg"),
            authenticated = (JSON.parse(decodeURIComponent($.cookie("cclSession") || "{}")).IsAuthenticated || $.cookie("MSCSAuth")),
            cookieDomain = ccl_header2013.getCookieDomain();

        if (!authenticated) {
            if (queryString.indexOf("offid=EmH_Booked_Guest_EM") !== -1) {
                if (emailCookie == null || emailCookie != "BK") {
                    $.cookie("mk_email_seg", 'BK', { path: '/', domain: cookieDomain, expires: 20 * 365 });
                }
            }            
            if (queryString.indexOf("cid=Em_PG") !== -1) {
                if (emailCookie == null || emailCookie != "PG") {
                    $.cookie("mk_email_seg", 'PG', { path: '/', domain: cookieDomain, expires: 20 * 365 });
                }
            }
        }
	},

	

};

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    var cookieStr = name + "=" + value + expires + "; path=/";
    document.cookie = cookieStr;
    return cookieStr;
}

$(function () {

    ccl_header2013.handleLoggedStates();

    var header = $("#ccl_header"),
		 wrapper = header.find(".flyout-wrapper");

    //////////////////////////////////////////////////////
    // show/hide login flyout
    //////////////////////////////////////////////////////		 
    //header.find("#ccl_header_expand-login-link").click(function () {
    //    var o = $(this),
	//		 par = o.parent(),
	//		 top = header.find(".top-section"),
	//		 flyout = header.find(".login-flyout");

    //    if (!par.hasClass("active")) {
    //        par.addClass("active");
    //        top.addClass("flyout-expanded");
    //        flyout.slideDown("fast");
    //    } else {
    //        flyout.slideUp("fast", function () {
    //            par.removeClass("active");
    //            top.removeClass("flyout-expanded");
    //        });
    //    }

    //    return false;
    //});

    //////////////////////////////////////////////////////
    // show flyouts
    //////////////////////////////////////////////////////

    // open on click logic
    header.find("a.flyout").bind("click", function () {

        if ($(this).parent().hasClass("active")) {
            ccl_header2013.hideFlyouts();
        } else {
            ccl_header2013.showFlyout($(this));
        }
        return false;

    });

    /* .bind("mouseenter",function(){
		if(wrapper.hasClass("expanded")){
			ccl_header2013.showFlyout($(this));
		}
	}); */

    // open on hover logic
    /* 	header.find("a.flyout").bind("mouseenter",function(){
    
            ccl_header2013.showFlyout($(this));
            
        }).addSwipeEvents().bind("tap",function(evt,touch){
                
            $(this).unbind("click").bind("click",function(){
                return false;
            });
            
            if(!$(this).parent().hasClass("active")){
                ccl_header2013.showFlyout($(this));
            } else {
                ccl_header2013.hideFlyouts();
            }
                
        });	 */


    //////////////////////////////////////////////////////
    // hide flyouts
    //////////////////////////////////////////////////////	

    /* 	header.find(".bottom-section").bind("mouseleave",function(){
            
            ccl_header2013.hideFlyouts();
            
        }); */

    header.find(".flyout-close").click(function () {
        ccl_header2013.hideFlyouts();
        return false;
    });

    header.find(".navigation li a").not(".flyout").bind("mouseenter", function () {
        ccl_header2013.hideFlyouts();
    });

    //////////////////////////////////////////////////////
    // "hide" message bar
    //////////////////////////////////////////////////////	
    header.find(".message-bar-close").click(function () {

        header.find(".message-bar").slideUp("fast");
        return false;

    });

    //////////////////////////////////////////////////////
    // support Placeholder
    //////////////////////////////////////////////////////		
    ccl_header2013.supportPH();

    //////////////////////////////////////////////////////
    // init PIE
    //////////////////////////////////////////////////////		
    ccl_header2013.initPIE();

    //////////////////////////////////////////////////////
    // get original document height
    //////////////////////////////////////////////////////		
    $(window).on('load', function () { ccl_header2013.originalHeight = $(document).height(); });

    //ccl_header2013.applyFauxPlaceholder();
    setTimeout(function () { ccl_header2013.setReturnerCookie(); }, 1000);

    ccl_header2013.dropEmailCookie();

    $("#tooltip-clickme").attr("aria-label", "See more details about available discounts").attr("role", "button");
    $('.ca-popover-help-content-container').attr("role", "alert").attr("aria-live", "polite");
    $("#tooltip-clickme").css('margin-left', "2px").css('padding-left', "0");

    $("#tooltip-clickme").keyup(function (e) {
        if(e.keyCode == 27) {
            $(".ca-popover-help-content-container").hide();
        }
    });

    $('#help-icon-mobile').click(function () {
        $('#ccl-srAriaLive').text($('.popover.fade').text());
    });

});;
(function($, Carnival){

	if(!Carnival) Carnival = {};

	if(!Carnival.Footer) Carnival.Footer = {};

	var foot = {};
	
	foot.$el = $("#ccl-refresh-footer", "#cclr-global-footer-root");
	
	foot.init = function(){

        foot.initFooterADA();

		// header alert
		foot.lazyLoadFBLike();
		
    };

    foot.initFooterADA = function () {
        //Aria-Label for FooterLink Items
        $('div.link-lists ul li').each(function () {
            var iconExt = $(this).find('.icon-link-ext');
            if (iconExt.length) {
                var complement = "indicates external site which may or may not meet accessibility guidelines";
                $(this).find('a').attr('aria-label', $(this).find('a').text() + complement);
            }
        });
    };

	foot.lazyLoadFBLike = function(){
		var $frame = foot.$el.find("#lazy_like");

		$(window).bind("scroll.lazyLoadFBLike", function(){
			if(foot.checkVisibility(foot.$el)){
				$(window).unbind("scroll.lazyLoadFBLike");
				$frame.attr("src", $frame.data("src"));
			}
		}).trigger("scroll.lazyLoadFBLike");
	};

	foot.checkVisibility = function($elm){
		var top = $elm.offset().top,
			winH = $(window).height(),
			scrolled = $(window).scrollTop(),
			visible = false;

		if((scrolled+winH) >= top){
			visible = true;
		}

		//console.log(visible);
		return visible;
	};

	Carnival.Footer = $.extend(foot, Carnival.Footer);

	window.Carnival = Carnival;
	
	
	$(function(){
		if(Carnival.Footer.$el.length){
			Carnival.Footer.init();
		}
	});	

})(jQuery, window.Carnival);;
/**
 * Activate the visible focus only when TAB key is pressed
 */
(function ($) {
    $(document).ready(function () {
        $(window).keydown(function (e) {
            var pressedKey = (e.keyCode ? e.keyCode : e.which);
            if (pressedKey == 9) {
                $('body').addClass('ccl-ada-focus');
            }
        });
    });
})(jQuery);

/**
 * Skip to Main Content Link Focusing Behavior
 */
(function ($) {
    $(document).ready(function () {
        // We define the possible main container IDs present in the DOM
        var mainContainerIDList = ['#ccl-mainContainer', '#main', '.mainContainer'];
        $.each(mainContainerIDList, function (index, value) {
            // We need to detect if the selected main container ID exists in the DOM
            if ($(value).length) {
                if (value.indexOf('.') > -1) {
                    value = $(value).attr('id').toString();
                }
                value = value.replace('#', '');

                // If it exists, we visually show the 'Skip to Main Content' link
                $('.ccl-stickSkipBar').css('display', 'block');
                $('.ccl-skipToMainContentLink').attr('href', '#' + value);

                //Normal cursor when skip to main is not visible
                $('.ccl-skipToMainContentLink').css('cursor', 'default');

                //$('.ccl-skipToMainContentLink').attr('href', value);
                $('.ccl-skipToMainContentLink').removeAttr('tabindex');
                // We define when the 'Skip to Main Content' link has to be visually shown the
                // current page header
                $('.ccl-skipToMainContentLink').blur(function () {
                    $('.ccl-stickSkipBar').removeClass('showSkip');
                    $(this).css('cursor', 'default');
                }).focus(function () {
                    $('.ccl-stickSkipBar').addClass('showSkip');
                    $(this).css('cursor', '');
                });
                // We help the ScreenReader to focus the selected main container element in order
                // to give him the possibility to read all of the main container's content
                $('.ccl-skipToMainContentLink').keydown(function (e) {
                    var pressedKey = (e.keyCode ? e.keyCode : e.which);
                    if (pressedKey == 13) {
                        $('#' + value).focus();
                    }
                });
                // We need to break the loop. If we don't break it, we won't never be able to see
                // the 'Skip to main Content' link in the current page header
                //}
                $('.ccl-stickSkipBar').removeClass('showSkip');
                return false;
            } else {
                if (index == (mainContainerIDList.length - 1)) {
                    // If it doesn't exists, we visually hide the 'Skip to Main Content' link
                    $('.ccl-stickSkipBar').remove();
                }
            }
        });
    });
})(jQuery);

/**
 * Force ScreenReader to read the validation error messages in forms.
 * selector: css selector to create a jquery and obtaing its text value ( .text()).
 */
function forceSRToReadValidErrMessages(selector) {
    selector = selector || '.validation-summary-errors li';
    var listedErrorMessage = $(selector);
    if (listedErrorMessage.length) {
        forceSRToReadAriaLive(listedErrorMessage.text());
    }
}
/**
 * Force ScreenReader to read the validation error messages in forms.
 * textAriaLiveHtml: string that SR has to read.
 */
function forceSRToReadText(textAriaLiveHtml) {
    if (textAriaLiveHtml.length) {
        forceSRToReadAriaLive(textAriaLiveHtml);
    }
}
/**
 * found the arialive dom element and changes its text.
 * textAriaLiveHtml: string that SR has to read.
 */
function forceSRToReadAriaLive(textAriaLiveHtml) {
    var $ariaLive = $('#ccl-srAriaLive');
    if ($ariaLive.length <= 0) {
        var el = window.parent.document.body.querySelector('#ccl-srAriaLive');
        $ariaLive = $(el);
    }
    $ariaLive.text(textAriaLiveHtml);
}

/**
 * Closing iframes called like a modal window
 * 
 * idDiv: Id for the DIV that contains information of the modal
 * closeButton: Its our simulated button to perform the close action via keyboard
 * overlayF: ID for the Div that contains the overlay. Located in the father. The one who summons the iframe
 * idContainerF: Container generated dinamically, to summon the iframe.  Located in the father.
 * forcedIdFirst: Optional param, used only if the element returned by the query "focusableElementsString" is not the first (is hidden by the parent)
 * forcedIdLast: Optional param, used only if the element returned by the query "focusableElementsString" is not the last (is hidden by the parent)
 * hideOverlay: boolean indicate if the overlay has to be removed or hiden (default remove autogenerated overlays)
 * openModalElement: JQuery selector to identify the element to send the focus when the modal is closed
 * closeFunction: Function, if this param is recieved the close button will call this function instead of the default behavior
 */
function setFocusModalIFrame(idDiv, closeButton, overlayF, idContainerF, forcedIdFirst, forcedIdLast, hideOverlay, openModalElement, closeFunction) {
    var modal = document.getElementById(idDiv);
    var focusableElements;
    var firstTabStop;
    var lastTabStop;
    var openElement;

    // Variables related to popup with iFrame and focus
    var focusableElementsString = "a[href]:not([style*=\"display:none\"]), area[href]:not([style*=\"display:none\"]), \
    input:not([disabled]):not([style*=\"display:none\"]):not([type*=hidden]), select:not([disabled]):not([style*=\"display:none\"]), \
    textarea:not([disabled]):not([style*=\"display:none\"]), button:not([disabled]):not([style*=\"display:none\"]), \
    iframe:not([style*=\"display:none\"]), object:not([style*=\"display:none\"]), embed:not([style*=\"display:none\"]), \
    *[tabindex]:not([style*=\"display:none\"]), *[contenteditable]:not([style*=\"display:none\"])";

    // Listen trap key
    modal.addEventListener('keydown', trapTabKey);

    focusableElements = modal.querySelectorAll(focusableElementsString);
    focusableElements = Array.prototype.slice.call(focusableElements);

    firstTabStop = document.getElementById(forcedIdFirst) || focusableElements[0];
    lastTabStop = document.getElementById(forcedIdLast) || focusableElements[focusableElements.length - 1];

    // Focus first child
    firstTabStop.focus();

    $(closeButton).focus(function () {
        $(parent.document).find('.close').css('outline', '3px solid #00b5cb');
        $(parent.document).find('.close').css('outline-offset', '0');
        $(parent.document).find('.close').css('box-shadow', 'inset 0 0 2px #fff!important');
    });

    $(closeButton).focusout(function () {
        $(parent.document).find('.close').css('outline', '');
        $(parent.document).find('.close').css('outline-offset', '');
        $(parent.document).find('.close').css('box-shadow', '');
    });

    $(closeButton).click(function () {
        if (closeFunction != undefined) {
            closeFunction();
            resetFocusToOpenedElement();
        }
        else {
            $(parent.document).find(overlayF).remove();
            resetFocusToOpenedElement();
            $(parent.document).find(idContainerF).remove();
            return false;
        }
    });

    function resetFocusToOpenedElement() {
        var el = window.parent.document.body.querySelector(openModalElement || '.modalOpenElement');
        openElement = $(el);
        if (openElement.length) {
            openElement.focus();
        }
    };

    function trapTabKey(e) {
        var pressedKey = (e.keyCode ? e.keyCode : e.which);
        // Check for TAB key press
        if (pressedKey === 9) {
            // SHIFT + TAB key
            if (e.shiftKey) {
                if (document.activeElement == firstTabStop) {
                    e.preventDefault ? e.preventDefault() : e.returnValue = false;
                    lastTabStop.focus();
                }
            // TAB key
            } else {
                if (document.activeElement == lastTabStop) {
                    e.preventDefault ? e.preventDefault() : e.returnValue = false;
                    firstTabStop.focus();
                }
            }
        }
        // ESCAPE key
        if (pressedKey === 27) {
            resetFocusToOpenedElement();
            if (typeof closeButton !== 'undefined') {
                $(document).find(closeButton).click();
            } else {
                if (hideOverlay == undefined || hideOverlay == false) {
                    $(parent.document).find(overlayF).remove();
                    $(parent.document).find(idContainerF).remove();
                }
                else {
                    $(parent.document).find(overlayF).hide();
                    $(parent.document).find(idContainerF).hide();
                }
            }
        }
    }
    return 'done';
}

/**
 * Closing div called like a modal window
 * 
 * idDiv: Id for the DIV that contains information of the modal
 * scapeFunction: function to execute when pressed esc (the focus should return to the element who shot the modal)
 * closeFunction: function to execute when close modal (the focus should go to the next focusable element)
 * forcedIdFirst: Optional param, used only if the element returned by the query "focusableElementsString" is not the first (is hidden by the parent)
 * forcedIdLast: Optional param, used only if the element returned by the query "focusableElementsString" is not the last (is hidden by the parent)
 * preventTrabTap: flag to indicate whether the tabulation should be circular or not (undefined or false is circular)
 */
function setFocusModal(idDiv, scapeFunction, closeFunction, forcedIdFirst, forcedIdLast, preventTrabTap) {
    var modal = document.getElementById(idDiv);
    var focusableElements;
    var firstTabStop;
    var lastTabStop;

    // Variables related to popup with iFrame and focus
    var focusableElementsString = "a[href]:not([style*=\"display:none\"]), area[href]:not([style*=\"display:none\"]), \
    input:not([disabled]):not([style*=\"display:none\"]):not([type*=hidden]), select:not([disabled]):not([style*=\"display:none\"]), \
    textarea:not([disabled]):not([style*=\"display:none\"]), button:not([disabled]):not([style*=\"display:none\"]), \
    iframe:not([style*=\"display:none\"]), object:not([style*=\"display:none\"]), embed:not([style*=\"display:none\"]), \
    *[tabindex]:not([style*=\"display:none\"]), *[contenteditable]:not([style*=\"display:none\"])";

    // Listen trap key
    modal.addEventListener('keydown', trapTabKey);

    focusableElements = modal.querySelectorAll(focusableElementsString);
    focusableElements = Array.prototype.slice.call(focusableElements);

    firstTabStop = document.getElementById(forcedIdFirst) || focusableElements[0];
    lastTabStop = document.getElementById(forcedIdLast) || focusableElements[focusableElements.length - 1];

    // Focus first child
    setTimeout(function () {
        firstTabStop.focus();
    }, 100);


    function trapTabKey(e) {
        var pressedKey = (e.keyCode ? e.keyCode : e.which);
        // Check for TAB key press
        if (pressedKey === 9) {
            // SHIFT + TAB key
            if (e.shiftKey) {
                if (document.activeElement == firstTabStop) {
                    e.preventDefault();
                    if (preventTrabTap == undefined || !preventTrabTap) {
                        lastTabStop.focus();
                    }
                    else {
                        scapeFunction();
                    }
                }
            // TAB key
            } else {
                if (document.activeElement == lastTabStop) {
                    e.preventDefault();
                    if (preventTrabTap == undefined || !preventTrabTap) {
                        e.preventDefault();
                        firstTabStop.focus();
                    }
                    else {
                        closeFunction();
                    }
                }
            }
        }
        // ESCAPE key
        if (pressedKey === 27) {
            scapeFunction();
        }
    }
}

/**
 * This function is an handler event. When a specific key is pressed, a click event is simulated.
 * 
 * jQueryElementParent: JQuery element containing the elements
 * codeKey: Code key
 * Example usage:
 * <div id="modalDiv"><a class="closebutton keypresstoclick">x</a></div>
 * var specificHandler = new AddhandlerKeypressClick($("#modalDiv"), 32)   //Enable event click on link with space key
 */
function AddhandlerKeypressClick(jQueryElementParent, codeKey) {
    try {
        jQueryElementParent.on("keydown", ".keypresstoclick", function (e) {
            var pressedKey = (e.keyCode ? e.keyCode : e.which);
            if (pressedKey === codeKey) {
                $(this).trigger("click");
            }
        });
    } catch (err) {
        console.log(err.message);
    }
};
