addEvent(window, "load", showImageBrowsingBar, false);
addEvent(window, "load", addGroupHeaderEvents, false);
addEvent(window, "load", addSelectSeasonEvents, false);
addEvent(window, "load", addEnokViewerEvents, false);

$(document).ready(function() {
    $("#open-tema-map, #tema-small-map").click(function() {        
        var ctrlId = $(".media-tabs").attr("id");
        var 
            ctrl = $find(ctrlId),
            numOfTabs = ctrl.get_tabs().length;

        if (numOfTabs>3){ctrl.set_activeTab(ctrl.get_tabs()[3]);}
        else if(numOfTabs>2){ctrl.set_activeTab(ctrl.get_tabs()[2]);}
        else{ctrl.set_activeTab(ctrl.get_tabs()[1]);}
    });
    $("#show-all-trips").click(function() {

        if ($("#over-five-trips").is(":visible")) {
            $("#over-five-trips").slideUp("slow");
            $(this).text(strShowAllTrips).removeClass("selected");        
        }
        else {
            $("#over-five-trips").slideDown("slow");
            $(this).text(strHideAllTrips).addClass("selected");
        }
    });
});


$("div.hotel-price-example a").click(function(){
    $("div#draggable div.ui-handle h3").text("Prisexempel");
    oPriceEx=displayDraggable($(this));
    //oPriceEx.find("div.ui-content").html("");
});

function setTemaTopStyle(imgName) {
    $("#media-viewer .ajax__tab_header").css("background", String.format("transparent url(/Includes/Images/BlueSites/Tema/Layout/{0}) no-repeat scroll center 22px", imgName));
}

function setTabStyle(sender, e) {
     var tabCssClass = sender.get_activeTab().get_cssClass();
     if (tabCssClass === "video-viewer-tab") {        
        $(".ajax__tab_body_bottom").hide();
        if (isTemaSite) {
            $("#media-viewer div.ajax__tab_panel").css("background", "none");
            setTemaTopStyle("box-659x500-top-bg.png");            
        } 
    }
    else if (tabCssClass == "pictures-viewer-tab") {
        if ($('div.image-viewer-small').get(0) !== null) {
            $('div.image-viewer-small').get(0).control.start(1);
        }
        if (isTemaSite) {
            $("#media-viewer div.ajax__tab_panel").css("background", "transparent url(/Includes/Images/BlueSites/Tema/MediaViewer/box-655-filler-bg.png) repeat-y scroll left top");
            setTemaTopStyle("box-655x500-top-bg.png");            
        }
        $(".ajax__tab_body_bottom").show();        
    }
    else {
        $(".ajax__tab_body_bottom").show();
        if (isTemaSite) {            
            $("#media-viewer div.ajax__tab_panel").css("background", "transparent url(/Includes/Images/BlueSites/Tema/MediaViewer/box-655-filler-bg.png) repeat-y scroll left top");
            setTemaTopStyle("box-655x500-top-bg.png");            
        }      
    }
}


function addOpenMoreFactsBlock(){
    $("a.more-facts-JS").click(function() {
        if ($(this).attr("id") == "more-facts-id-dest") {
            $(this).text(($(this).text() == strShowDayProgram) ? strHideDayProgram : strShowDayProgram);
        }
        else {
            $(this).text(($(this).text() == strShowMoreFact) ? strHideMoreFact : strShowMoreFact);
        }

        if ($(this).attr("class") == "more-facts-JS") {
            $(this).removeClass("more-facts-JS").addClass("more-facts-JS-hide").toggleClass("selected");
            $("dl#more-facts-dl").fadeIn("slow");
        }
        else {
            $(this).removeClass("more-facts-JS-hide").addClass("more-facts-JS").toggleClass("selected");
            $("dl#more-facts-dl").fadeOut("slow");
        }
        return false;
    });
}
function addOpenLargeMap(){
    $("a#open-large-map, img#small-map").click(function() {
        $("div.open-large-map").fadeOut("slow");
        $("div#map-small").fadeOut("slow");
        $("div#large-map-container").fadeIn("slow");
        $("img#flag-img").css("margin-bottom", "10px");
        return false;
    });
    $("a#close-large-map, img.large-map-decrease").click(function() {
        $("div.open-large-map").fadeIn("slow");
        $("div#map-small").fadeIn("slow");
        $("div#large-map-container").fadeOut("slow");
        $("img#flag-img").css("margin-bottom", "0px");
        return false;
    });
}
function addExpandMoreHotelInfo(){
	$("a.info-link").click(function(){
		var oInfoDiv = document.getElementById("detailed-hotel-info-container");	
		var link = document.getElementById("detailed-hotel-info-link");	
		link.className = (link.className == "info-link") ? "info-link-selected" : "info-link";
		oInfoDiv.className = (oInfoDiv.className == "display-none") ? "display-block" : "display-none";			
	return;
	});
}

var 
    $weatherDisplayer,
    $weatherLayer,
    $weatherDialogElement,
    weatherDialogControl;

function addWeatherForecastEvents() {
    $weatherDisplayer = $('#weather-displayer');
    $weatherLayer = $('#weather-layer');
    $weatherDialogElement = $('#weather-dialog');

    if ($weatherDisplayer.length == 1 && $weatherLayer.length == 1 && $weatherDialogElement.length == 1)
    {
        weatherDialogControl = new TUI.Web.UI.WebControls.Dialog($weatherDialogElement.get(0));
        $weatherLayer.appendTo($weatherDialogElement.find('div.dialog-center-inner')).show();

        weatherDialogControl.beginUpdate();
        weatherDialogControl.set_innerHtmlTop(strFiveDayForecast);
        weatherDialogControl.set_targetControl($weatherDisplayer.get(0));
        weatherDialogControl.set_isDraggable(true);
        weatherDialogControl.endUpdate();

        Sys.Application.addComponent(weatherDialogControl);
    }
}


function addEnableSubmitButtonEvents(){
	var arrEnableElements = getElementsByClassName(document, "select", "enable-submit-button");	
	for(var i=0; i<arrEnableElements.length; i++){
		arrEnableElements[i].onchange = function (){
			var strClassName = this.className.replace(/.*enable-(\w+)(\b.*|$)/i, "$1");
			var strValue = this.options[this.options.selectedIndex].value;
			if(strValue.length > 0){
				var strIdOfElementToEnable = strClassName.replace(/.*enable-([\w\d\-]+)(\b.*|$)/i, "$1");
				oButtonToEnable = document.getElementById(strIdOfElementToEnable);
				oButtonToEnable.disabled = false;
				var strButtonSource = oButtonToEnable.getAttribute("src");
				if(strButtonSource){
					oButtonToEnable.setAttribute("src", strButtonSource.replace(/-disabled/i, ""));
				}
			}
		};
	}
}
/*Flytta detta till Tema*/
var arrImages;
var intImageIndex = 0;
var oSlideShowTimer = null;
function prevImg(){
	if(intImageIndex > 0){
		intImageIndex--;
		setImageSrc();
	}
}
function nextImg(){
	if (arrImages) {
		if(intImageIndex < (arrImages.length - 1)){
			intImageIndex++;
		}else{
			intImageIndex = 0;
		}
		setImageSrc();
	}
}
// --- Admin?
function setImageSrc(){
	if(document.getElementById){	
		var oImage = document.getElementById("destination-image");	
		if(oImage !== null){		
			oImage.setAttribute("src", arrImages[intImageIndex]);
			var oCounter = document.getElementById("image-number").innerHTML = (intImageIndex + 1) + "/" + arrImages.length;
		}
	}
}
function startSlideShow(){
	
	if(document.getElementById){	
		intImageIndex = 0;
		setImageSrc();
		oSlideShowTimer = setTimeout("slideshow()", 2000);
		document.getElementById("show-slideshow").className = "display-none";
		document.getElementById("stop-slideshow").className = "display-inline";
	}	
}
function stopSlideShow(){
	if(oSlideShowTimer && document.getElementById){
		setImageSrc();
		clearTimeout(oSlideShowTimer);
		oSlideShowTimer = null;
		document.getElementById("show-slideshow").className = "display-inline";
		document.getElementById("stop-slideshow").className = "display-none";
	}
}
function toggleSlideShow(){
	if(document.getElementById){
		if (oSlideShowTimer) {
			setImageSrc();
			clearTimeout(oSlideShowTimer);
			oSlideShowTimer = null;
			document.getElementById("show-slideshow").className = "display-inline";
			document.getElementById("stop-slideshow").className = "display-none";
		}
		else {
			intImageIndex = 0;
			setImageSrc();
			oSlideShowTimer = setTimeout("slideshow()", 2000);
			document.getElementById("show-slideshow").className = "display-none";
			document.getElementById("stop-slideshow").className = "display-inline";
		}
	}
}
function slideshow(){
	if(intImageIndex < (arrImages.length - 1)){
		nextImg();
		oSlideShowTimer = setTimeout("slideshow()", 2000);
	}
	else{
		intImageIndex = 0;
		stopSlideShow();		
	}	
}
document.onkeydown = function (oEvent){
	var oEvent = (typeof oEvent != "undefined")? oEvent : event;
	if(!oEvent.altKey){
		var intKeyCode = oEvent.keyCode;
		var showSlideHide = document.getElementById("no-slide-show");
		if(!showSlideHide){
			if(intKeyCode==37){prevImg();}
			else if(intKeyCode==39){nextImg();}
		}
	}	
}
/*** showImageBrowsingBar - Enters a timeout to show the image browsing bar
 * Note:	If the image-browsing is not loaded before the delay period 
 *			the time-out is increased by 50% and then a new time-out is issued.
 * @param delay			delay in milliseconds before trying to show the image browsing bar.
 *						(optional, default = 400)
 * @param repetitions	number of times to try
 *						(optional, default = 0 and hence no recursion)
 */
function showImageBrowsingBar(delay, repetitions){
    if (isNaN(delay)) {
        delay = 400;
    }
    
    if (isNaN(repetitions)) {
        repetitions = 0;
    }
		
	setTimeout("ImageBrowsingBar(" + delay + ", " + repetitions + ")", delay);
}
/*** ImageBrowsingBar - Shows the image browsing bar
 * Note:	If the image-browsing is not loaded before the delay period 
 *			the time-out is increased by 50% and then a new time-out is issued.
 * @param delay			delay in milliseconds before trying to show the image browsing bar if repetitions > 0
 *						(optional, default = 400)
 * @param repetitions	number of times to try
 *						(optional, default = 1 and hence no recursion)
 */
function ImageBrowsingBar(delay, repetitions){
    if (isNaN(delay)) {
        delay = 400;
    }

    if (isNaN(repetitions)) {
        repetitions = 0;
    }
		
	if(document.getElementById && document.getElementById("image-browsing")){
		imageList = document.getElementById("image-list");

		$('#media-player a.show-image-viewer').click
		(
            function()
            {
		        var imageViewerComponent = $('div.image-viewer').get(0).control;
		        imageViewerComponent.show(intImageIndex + 1); // Image position is not 0-based inside ImageViewer
		    }
		);
        
		if (imageList) {
			arrImages = imageList.value.split(",");
		}
		document.getElementById("image-browsing-previous").onclick = prevImg;
		document.getElementById("image-browsing-next").onclick = nextImg;
		document.getElementById("show-slideshow").onclick = function (oEvent)
		{
			var oEvent = (typeof oEvent != "undefined")? oEvent : event;
			oEvent.returnValue = false;
			if(oEvent.preventDefault){
				oEvent.preventDefault();
			}
			startSlideShow();
		};
		document.getElementById("stop-slideshow").onclick = function (oEvent){
			var oEvent = (typeof oEvent != "undefined")? oEvent : event;
			oEvent.returnValue = false;
			if(oEvent.preventDefault){
				oEvent.preventDefault();
			}
			stopSlideShow();
		};		
		document.getElementById("image-browsing").className = "display-block";
		
		// Reset a slideshow that might be left running in the background from another hotelinfo-popup
		intImageIndex = 0;
		stopSlideShow();
	}
	else if (repetitions > 0)	{
		showImageBrowsingBar(delay*1.5, repetitions-1);
	}
}
var strAnchorId;
function setFocusToAnchor(strContainer){
	var oContainerElement = document.getElementById(strContainer);
	if(oContainerElement){
		var oAnchor = document.getElementById(strAnchorId);
		if(oAnchor){
			oContainerElement.scrollTop = oAnchor.offsetTop - (oAnchor.offsetHeight * ((document.all)? 1 : 2));
		}
		else{	
			setTimeout("setFocusToAnchor()", 500);
		}
	}
}
var arrAddOnsGroupHeaderLinks;
function addGroupHeaderEvents(){
	var oGroupHeaderContainer = document.getElementById("hotel-info");
	if (!oGroupHeaderContainer) {
	    oGroupHeaderContainer = document.getElementById("hotel-comparison");
	}
	
	if(oGroupHeaderContainer){
		arrAddOnsGroupHeaderLinks = getElementsByClassName(oGroupHeaderContainer, "a", "group-header-link");
		for(var i=0; i<arrAddOnsGroupHeaderLinks.length; i++){
			arrAddOnsGroupHeaderLinks[i].onclick = function (oEvent){
				var oEvent = (typeof oEvent != "undefined")? oEvent : event;
				oEvent.returnValue = false;
				if(oEvent.preventDefault){
					oEvent.preventDefault();
				}
				expandCollapseRows(this);				
			}
		}
		var oShowAllRows = document.getElementById("show-all-rows");
		if(oShowAllRows){
			oShowAllRows.onclick = function(){
				expandCollapseAllRows(true);
			};			
		}
		var oHideAllRows = document.getElementById("hide-all-rows");
		if(oHideAllRows){
			oHideAllRows.onclick = function(){
				expandCollapseAllRows(false);
			};
		}
	}	
}
function expandCollapseAllRows(bExpand){
	if(typeof arrAddOnsGroupHeaderLinks != "undefined"){
		for(var i=0; i<arrAddOnsGroupHeaderLinks.length; i++){
			expandCollapseRows(arrAddOnsGroupHeaderLinks[i], bExpand);
		}
	}
}
function expandCollapseRows(oElm, bExpand){
	
	var oTableRow = oElm.parentNode.parentNode;
	var bExpand = (typeof bExpand != "undefined")? bExpand : (oTableRow.className.search(/expanded-group/) == -1)? true : false;	
	var strRowClassName = "display-table-row";
	if(bExpand){
		oTableRow.className = oTableRow.className.replace(/\sexpanded-group/i, "") + " expanded-group";
	}
	else{
		oTableRow.className = oTableRow.className.replace(/\sexpanded-group/i, "");
		strRowClassName = "display-none";
	}	
	var strNewClassName;
	while(oTableRow.nextSibling){		
		oTableRow = oTableRow.nextSibling;
		if(oTableRow.nodeName.search(/tr/i) != -1 && oTableRow.className.search(/group-header/) == -1){
			strNewClassName = oTableRow.className.replace(/\s?display-(table-row|none)/gi, "");
			oTableRow.className = strNewClassName + " " + strRowClassName;
		}
		else if(oTableRow.nodeType == 3){
			continue;
		}
		else{
			break;
		}
	}
}
function redirectResortSeason(value){
	window.location = value;
}


/*PANORAMA START-*/

$(document).ready
(
    function() {

        var $totalImagesCount = 0;

        loadCarousel = function() {

        var $totalImagesCount = $("div.carousel div.images ul:first li").length;

            var $visibleImagesCount = 5;

            if ($totalImagesCount < 6) {
                $("div.scroll").hide();
                $visibleImagesCount = $totalImagesCount;
            }

            $("div.carousel .images").jCarouselLite({
                btnNext: "div.carousel .next",
                btnPrev: "div.carousel .prev",
                visible: $visibleImagesCount,
                vertical: true,
                mouseWheel: true,
                speed: 500,
                circular: false,
                afterEnd: function(elements) {
                    var $filePath = $(elements).filter('li:eq(0)').children().attr('src').replace('thumbs/', '');
                    rewriteApplet($filePath);
                }
            });

            $("div.carousel img").click(function() {
                var $filePath = $(this).attr('src').replace('thumbs/', '');
                rewriteApplet($filePath);
            });

            $("span.panorama-viewer-tab").die("click", loadCarousel);
        }

        $("span.panorama-viewer-tab").live("click", loadCarousel);


        rewriteApplet = function(file) {

            var $barColor = "CCE6FF";
            if (isTemaSite) {
                $barColor = "881f36";
            }

            var $appletCode = '<applet archive="/TuiPlugins/Media/qtptviewer.jar" code="ptviewer.class" width="565" height="343">' +
                '	<param name="file" value="' + file + '" />' +
                '	<param name="panmin" value="-180" />' +
                '	<param name="panmax" value="180" />' +
                '	<param name="pan" value="0" />' +
                '	<param name="tiltmin" value="-60" />' +
                '	<param name="tiltmax" value="80" />' +
                '	<param name="tilt" value="0" />' +
                '	<param name="fovmin" value="42" />' +
                '	<param name="fovmax" value="119" />' +
                '	<param name="fov" value="95" />' +
                '	<param name="wait" value="/TuiPlugins/Media/' + brandId + '/loading.gif" />' +
                '	<param name="bar_x" value="162" />' +
                '	<param name="bar_y" value="228" />' +
                '	<param name="bar_width" value="240" />' +
                '	<param name="bar_height" value="16" />' +
                '	<param name="barcolor" value="' + $barColor + '" />' +
                '	<param name="view_x" value="0" />' +
                '	<param name="view_y" value="0" />' +
                '	<param name="view_width" value="565" />' +
                '	<param name="view_height" value="343" />' +
                '	<param name="quality" value="1" />' +
                '	<param name="frame" value="/Includes/Images/BlueSites/' + addPrefixIfTema('Tema/') + 'MediaViewer/PanoramaViewer/control-bar.gif" />' +
                '	<param name="bgcolor" value="FFFFFF" />' +
                '	<param name="auto" value="0.3" />' +
                '   <param name="shotspot0" value=" x382 y313 a405 b340 u\'ptviewer:startAutoPan(1.0,0,1.0)\' " />' +
                '   <param name="shotspot1" value=" x348 y313 a375 b340 u\'ptviewer:startAutoPan(-1.0,0,1.0)\' " />' +
                '   <param name="shotspot2" value=" x287 y313 a317 b340 u\'ptviewer:startAutoPan(0,-1.0,1.0)\' " />' +
                '   <param name="shotspot3" value=" x257 y313 a282 b340 u\'ptviewer:startAutoPan(0,1.0,1.0)\' " />' +
                '   <param name="shotspot4" value=" x163 y313 a190 b340 u\'ptviewer:startAutoPan(0,0,0.99)\' " />' +
                '   <param name="shotspot5" value=" x195 y313 a225 b340 u\'ptviewer:startAutoPan(0,0,1.01)\' " />' +
                '	<param name="shotspot6" value=" x0 y0 a0 b0 u\'#\' t\'\' " />' +
                '</applet>';
            document.getElementById('panorama-container').innerHTML = $appletCode;

        };

        addPrefixIfTema = function(retVal) {
            return (isTemaSite) ? retVal : '';
        }

    }
);

/*PANORAMA END*/

function addOpenCityIntroText(){
	$("a#texts-text-link").click(function(){
		if($(this).attr("class") == "selected"){
			$(this).removeClass("selected").text(strReadMoreCity);						
			$("div#texts-text-container").fadeOut("slow");			
			$("p#texts-text-ingress").removeClass("display-none").addClass("display-block");
		} else {
			$(this).addClass("selected").text(strReadLessCity);
			$("p#texts-text-ingress").removeClass("display-block").addClass("display-none");
			$("div#texts-text-container").fadeIn("slow");			
		}		
		return false;
	 });	
}
function addSelectSeasonEvents() {
	var oSelectSeason = document.getElementById('select-season');
	if (oSelectSeason) {
		var arrAllInputRadios = oSelectSeason.getElementsByTagName('input');
		for (var i=0; i < arrAllInputRadios.length; i++) {
		    arrAllInputRadios[i].onmousedown = function(oEvent) {
		        var oSelect = oSelectSeason.getElementsByTagName('select')[0];
		        if (oSelect) {
		            oSelect.selectedIndex = 0;
		        }
		        return true;
		    };		
		}
	}
}
function addEnokViewerEvents() {
    $("div.enok-hotel-level div.enok-booking-container dd.editable-false input:radio").attr("disabled", "true");
    $("input.city-level-book").click(
		function() {
		    _hotelid = $(this).attr("name").replace(/btnBookHotel-/gi, '');
		    $("ul.links li input[name='selected-booking-type-" + _hotelid + "']").each(
				function() {
				    if (this.checked) {
				        $("input#selected-booking-type").val($(this).val());
				        return false;
				    }
				}
			);
		    return true;
		}
	);
}
function showHotelInfoMap() {
	if ($("div.symbol-container").css("display") == "none") {
		$("div.symbol-container").fadeIn("slow");
		$("div#map-container").fadeIn("slow");
	} else {
		$("div.symbol-container").fadeOut("slow");
		$("div#map-container").fadeOut("slow");
	}
}

function showEnvironmentalDialog() {

    var environmentDialog = $find('environment-dialog');
    
    if (environmentDialog === null)
    {
        environmentDialog = $create(
            TUI.Web.UI.WebControls.Dialog, 
            { 
                'innerHtmlCenter' : $('#environment-dialog-content').html(),
                'showOverlay' : true,
                'dialogPosition' : TUI.Web.UI.WebControls.DialogPosition.custom
            },
            null, 
            null, 
            $get('environment-dialog')
        );
    }

    environmentDialog.show();
    window.scrollTo(0, 0);
}