
// NOTE: If needed, update the URLs below

var GuideBookUrl = "/webpart/Guidebook.aspx";
var imageGalleryOverlayUrl = "/webpart/Gallery.aspx";
var homePageUrl = "/Home.aspx"; // Redirect to this address when clicking the Crystal logo
var liveCamUrl = "/webpart/LiveCamOverlay.aspx";
var contactMeUrl = "/webpart/ContactMeOverlay.aspx";
var newsletterUrl = "/webpart/NewsletterSignupOverlay.aspx";
var galleryImageSet;
var galleryTitleText;
var galleryDeckText;

activateMenu = function(nav) {
}

// Function to make IE 6 run the navigation menu correctly
function initializeIe6fixForMenu(){
	if (jQuery.browser.msie) {
		if(parseInt(jQuery.browser.version) == 6) {
    		// Necessary scripts for IE6
		    $("#destinationsMenu").bind("mouseenter", function() {
	            $("#destinations").addClass("dest");
		        $("#destinationsMenu").addClass("z100");
		        $("#crystalExperienceMenu").addClass("crystalExperienceMenuHover");
		        $("#cruiseGuideBookMenu").addClass("cruiseGuideBookMenuHover");
		        if (this.lastChild.tagName == "UL") {
		            this.lastChild.style.display = "block";
		        }
		        $(this).css({ 'width': '122px' });
		    }).bind("mouseleave", function() {
		        $("#destinations").removeClass('dest');
		        $("#destinationsMenu").removeClass("z100");
		        $("#crystalExperienceMenu").removeClass("crystalExperienceMenuHover");
		        $("#cruiseGuideBookMenu").removeClass("cruiseGuideBookMenuHover");
		        if (this.lastChild.tagName == "UL") {
		            this.lastChild.style.display = "none";
		        }
		        $(this).css({ 'width': '122px' });
		    });

		    $("#crystalExperienceMenu").bind("mouseenter", function() {
		        $("#theCrystalExperience").addClass('exp');
		        $("#crystalExperienceMenu").addClass("z100");
		        if (this.lastChild.tagName == "UL") {
		            this.lastChild.style.display = "block";
		        }
		    }).bind("mouseleave", function() {
		        $("#theCrystalExperience").removeClass('exp');
		        $("#crystalExperienceMenu").removeClass("z100");
		        if (this.lastChild.tagName == "UL") {
		            this.lastChild.style.display = "none";
		        }
		    });

		    $("#cruiseGuideBookMenu").bind("mouseenter", function() {
		        $("#cruiseGuidebook").addClass('guideb');
		        $("#cruiseGuideBookMenu").addClass("z100");
		        if (this.lastChild.tagName == "UL") {
		            this.lastChild.style.display = "block";
		        }
		    }).bind("mouseleave", function() {
		        $("#cruiseGuidebook").removeClass('guideb');
		        $("#cruiseGuideBookMenu").removeClass("z100");
		        if (this.lastChild.tagName == "UL") {
		            this.lastChild.style.display = "none";
		        }
		    });
		}
	}
	// END drop down menu code
}




/**
* Styleswitch stylesheet switcher built on jQuery
* Under an Attribution, Share Alike License
* By Kelvin Luck ( http://www.kelvinluck.com/ )
**/
function switchStylestyle(styleName) {
    $("link[rel*=style][media!=print][title]").each(function(i) {
        this.disabled = true;
        if (this.getAttribute("title") == styleName) this.disabled = false;
    });
}

function switchPrintStylestyle(styleName) {
    $("link[rel*=style][media=print][title]").each(function(i) {
        this.disabled = true
        if (this.getAttribute("title") == styleName) this.disabled = false;
    });
}


// Funtion to load a new page into modal layer using jQuery's Ajax.
// Attributes:
// element - id of element to replace
// url - page to load
function loadPageIntoElement(element, url) {
    $.ajax({
      url: url,
      cache: false,
      success: function(page) {
          $("#" + element).html(page);
      }
    });
}

function urlencode(str) {
    return escape(str).replace(/\+/g, '%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/@/g, '%40');
}

/* MAIN SEARCH */
function mainSiteSearch(term) {
    document.location = "Search.aspx?s=" + urlencode(term);
    return false;
}

function mainSiteSearchPage(currentPage, searchFilter) {
    $.ajax({
        type: "get",
        data: "cp=" + currentPage + "&sf=" + searchFilter,
        url: 'webpart/SearchResultsPart.aspx',
        success: function(response) {
            $("#leftColumn").html(response)
        }
    });
    return false;
}


/* GUIDEBOOK SEARCH */
// On search submit, load search result into overlay
function guideBookSearch(){
	$.ajax({
		type: "get",
		data: "s=" + urlencode($("#searchTerm").attr("value")),
		url: $("#searchForm").attr("action"),
		success: function(response){
		    $("#guidebookModalWindow").html(response)
		}
	});
	return false;
}

function guideBookSearchPage(currentPage) {
    $.ajax({
        type: "get",
        data: "cp=" + currentPage,
        url: 'webpart/GuidebookSearchResultsPart.aspx',
        success: function(response) {
        $("#scrollableArticleContainer").html(response)
        }
    });
    return false;
}

// Initiate Cruise Guidebook overlay handling
$(document).ready(function() {
	if(($("#nav").length>0)&&($("#guidebookModalWindow").length==0)){
		$("body").append("<div id='guidebookModalWindow'></div>");
	}
	
	//try{$('#guidebookModalWindow').jqm({modal:'yes',ajax: GuideBookUrl});}catch(e){}

	//$('#cruiseGuidebook').click(function() {
	//	$('#guidebookModalWindow').jqmShow();
	//});
});

function openGuideBook(setGuideBookUrl){
    try {
        $('#guidebookModalWindow').jqm({ modal: 'yes', ajax: setGuideBookUrl });
    } catch (e) { }
    switchPrintStylestyle('guidebookPrint');
	$('#guidebookModalWindow').jqmShow();
}

function closeGuideBook() {
    $("head #guidebookPrint").remove();
    switchPrintStylestyle('off');
    $("#guidebookModalWindow").jqmHide();
}

function openGuideBookPrint(guideBookID) {
    window.open("/PrintGuidebookContent.aspx?ID=" + guideBookID, "gbpwindow", "menubar=1,resizable=1,scrollbars=1,width=700,height=600"); 
}

function openShareFriend(linkUrl) {
    try { $('#genUseModalWindow').jqm({ modal: 'yes', ajax: '/webpart/ModalOverlay_ShareFriend.aspx?link=' + linkUrl }); } catch (e) { };
    $('#genUseModalWindow').jqmShow();
}

function openGenUsePrint(printURL) {
    window.open(printURL, "gupwindow", "menubar=1,resizable=1,scrollbars=1,width=700,height=600");
}


// Register live cam overlay
$(document).ready(function() {
    if ($("#liveCamOverlay").length == 0) {
        $("body").append("<div id='liveCamOverlay'></div>");
    }
});

function openLiveView(camid) {
    try { $('#liveCamOverlay').jqm({ modal: 'yes', ajax: liveCamUrl + '?LV=' + camid }); } catch (e) { }
    $('#liveCamOverlay').jqmShow();
    try { $.scrollTo("#liveCamOverlay", 800); } catch (e) { }
}

// Register Multi-Use overlay
$(document).ready(function() {
    if ($("#genUseModalWindow").length == 0) {
        $("body").append("<div id='genUseModalWindow'></div>");
    }
});

// Register photo gallery
$(document).ready(function() {
    if ($("#galleryOverlay").length == 0) {
        $("body").append("<div id='galleryOverlay'></div>");
    }
});

// Register newsletter signup overlay
$(document).ready(function() {
    if ($("#newsletterSignupOverlay").length == 0) {
        $("body").append("<div id='newsletterSignupOverlay'></div>");
    }
});

function openNewsletterSignup(email) {
    try {
        if (email == undefined) {
            email = '';
        }
        $('#newsletterSignupOverlay').jqm({ modal: 'yes', ajax: newsletterUrl + "?em=" + email });
    } catch (e) { }
    $('#newsletterSignupOverlay').jqmShow();
}

// Register contactMe overlay
$(document).ready(function() {
    if ($("#requestAContactOverlay").length == 0) {
        $("body").append("<div id='requestAContactOverlay'></div>");
    }
});

function openContactMe(cruiseid, origcode) {
    try { $('#requestAContactOverlay').jqm({ modal: 'yes', ajax: contactMeUrl + "?CID=" + cruiseid + "&IOC=" + origcode }); } catch (e) { }
    $('#requestAContactOverlay').jqmShow();
}

function closeContactMe() {
    $("#requestAContactOverlay").jqmHide();
}

function closeGallery(){
	$("#galleryOverlay").jqmHide();
}

function closeLiveView() {
    $("#liveCamOverlay").jqmHide();
}

function preinitImageGallery(slideshowCode, pageCode) {
    if (pageCode == undefined) {
        pageCode = '';
    }
    $('#galleryOverlay').jqm ({modal:'yes',ajax: imageGalleryOverlayUrl+'?CODE=' + slideshowCode + '&PAGE=' + pageCode});
    $("#galleryOverlay").jqmShow();
}

function initImageGallery(title,galleryArray,deckTxt){
	galleryImageSet = galleryArray;
	galleryTitleText = title.toUpperCase();
	galleryDeckText = deckTxt;
}

// Class to hold data for each image: urls and image texts
function galleryImage(bigImageUrl,thumbnailImageUrl,caption,bodyText,deck){
	this.big = bigImageUrl;
	this.thumbnail = thumbnailImageUrl;
	this.caption = caption;
	this.body = bodyText;
	this.deckText = deck;
}

// Show previous image in gallery (wrapping)
function galleryPrevious(){
	if (currentGalleryImage==0){
		currentGalleryImage=galleryImageSet.length-1;
	}else{
		currentGalleryImage--;
	}
	skipToImage(currentGalleryImage);
	setThumbnailMarker(currentGalleryImage);
}

// Show next image in gallery (wrapping)
function galleryNext(){
	if (currentGalleryImage==galleryImageSet.length-1){
		currentGalleryImage=0;
	}else{
		currentGalleryImage++;
	}
	setThumbnailMarker(currentGalleryImage);
	skipToImage(currentGalleryImage)
}

// Show gallery image
function skipToImage(index){
	currentGalleryImage = index;
	setThumbnailMarker(index);
	$(".imageHolder").addClass("noDisplay");
	$("#imageHolder"+currentGalleryImage).removeClass("noDisplay");
	$("#galleryCaption").text(galleryImageSet[index].caption);
	$("#galleryBodyText").text(galleryImageSet[index].body);
}

// Open and display the gallery overlay.
// All images will be loading in the background to the cache to boost performance
// Param = imageSet array with galleryImage().
function openGallery(){
	var imageSet=galleryImageSet;
	$("#galleryTitle").text(galleryTitleText);
	if(imageSet.length>9){
		imageSet.length=9;
	}
	if(imageSet.length==1){
		$("#galleryPagination").hide();
	}
	for(var i=0;i<imageSet.length;i++){
		$("#galleryThumbs").append("<img src="+ imageSet[i].thumbnail +" id=thumbnailHolder"+i+" class='galleryThumbnail'"+i+"/>");
	}
	for(var i=0;i<imageSet.length;i++){
		$("#galleryImageContainer").append("<img src="+ imageSet[i].big +" id=imageHolder"+i+" class='noDisplay imageHolder'/>");
	}
	$("#imageHolder0").removeClass("noDisplay");
	setThumbnailMarker(0);
	$(".galleryThumbnail").bind("click",function(){
		var clickedImageIndex = $(this).attr("id").charAt(15);
		skipToImage(clickedImageIndex);
	});
	$("#galleryCaption").text(imageSet[0].caption);
	$("#galleryBodyText").text(imageSet[0].body);
	$("#galleryDeck").text(galleryDeckText);
	sifrGallery();
}

// Move thumbnail highlight marker to selected image
function setThumbnailMarker(thumbnailNumber){
	$(".galleryThumbnail").removeClass("galleryThumbnailSelected");
	$("#thumbnailHolder"+thumbnailNumber).addClass("galleryThumbnailSelected");
}

// Add rollover color change on all pages with voyage module (needed for IE6)
function setVoyageOverlayRollover() {
	$(".voyageModule").bind("mouseenter",function(){
		$(this).addClass("voyageModuleHover");
		$(this).find("a").addClass("voyageModuleLinkHover");
	}).bind("mouseleave",function(){
		$(this).removeClass("voyageModuleHover");
		$(this).find("a").removeClass("voyageModuleLinkHover");
	}).bind("click",function(){
		document.location=$(this).find("a").attr("href");
	});	
}

// Add rollover color change on all pages with offer module (needed for IE6)
function setOfferOverlayRollover() {
	$(".offerModule").bind("mouseenter",function(){
		$(this).addClass("offerModuleHover");
		$(this).find("a").addClass("offerModuleLinkHover");
	}).bind("mouseleave",function(){
		$(this).removeClass("offerModuleHover");
		$(this).find("a").removeClass("offerModuleLinkHover");
	}).bind("click",function(){
		document.location=$(this).find("a").attr("href");
	});	
}

$(document).ready(function() {
setVoyageOverlayRollover(); 
setOfferOverlayRollover(); 
});

// BEGIN: Tool Tip Engine
var arrowSide;
var toolTipMother;
var proceedFadeOut;
var lastObjectHovered;
var triggerDelay = 300;

// Fading smoothness depends on browser, tooltip size and gfx card
var fadeInSpeed = 200;
var fadeOutSpeed = 300;


function fadeOutVoyageOverlay() {
    $("#theToolTip").fadeOut();
    $("#toolTipArrow").fadeOut(fadeOutSpeed);
}

function initVoyageOverlay() {
	
	// Add overlay tooltip containers if page has voyage modules tooltips defined.
	if ($(".hiddenOverlayContainer").length>0){
		$("body").append("<div id='toolTipArrow'>&nbsp;</div>")
			.append("<div id='theToolTip'></div>");
	}
	else{return}

	$(window).bind('resize', function() {
		position(toolTipMother,"#theToolTip");
	}).bind('scroll', function() {
		position(toolTipMother,"#theToolTip");
	});

	// Hover/Mouse over function (using hover to cover also child elements)
	$(".voyageModule, .associations, .activityIcon, .activityLabel, .activityInfo, .shoreExInfo").hover(function(e) {
		//setTimeout(fadeOut,100);
		setTimeout(displayTooltip,100+triggerDelay)
		var mother=$(this);
		toolTipMother=mother;
		
		function displayTooltip(){
			if(mother!=toolTipMother){return}
			var toolTipContent = $(mother).find(".hiddenOverlayContainer").html();
			if (toolTipContent==null){return}
			$("#theToolTip").html(toolTipContent);
			if (position(toolTipMother,"#theToolTip")=="position failed"){return}
			$("#theToolTip").fadeIn(fadeInSpeed);
			$("#toolTipArrow").fadeIn(fadeInSpeed);
		}
		function fadeOut(){
			if (proceedFadeOut){
				$("#theToolTip").fadeOut(fadeOutSpeed);
				$("#toolTipArrow").fadeOut(fadeOutSpeed);
			}
			proceedFadeOut=true;
		}
	
	// Hover out function
	},function(){
		toolTipMother=null;
		proceedFadeOut=true;
		setTimeout(fadeOut,350);
		function fadeOut(){
			if(proceedFadeOut){
				$("#theToolTip").fadeOut(fadeOutSpeed);
				$("#toolTipArrow").fadeOut(fadeOutSpeed);
			}		
		}
	})

	// Hover over function
	$("#theToolTip").hover(function(){
		proceedFadeOut=false;
		$(this).fadeIn(200);
		$("#toolTipArrow").fadeIn(fadeInSpeed);

	// Hover out function
	},function(){
		$(this).fadeOut();
		$("#toolTipArrow").fadeOut(fadeOutSpeed);
	})
}

$(document).ready(function() {
initVoyageOverlay();
});

// Calculate Voyage Module Tooltip position
function position(mother,toolTip){
	if(mother==null){return}
	var toolTipX,toolTipY;
	var offsetX = 0;
	var offsetY = 5;
	var sTop = $(document).scrollTop();
	var sLeft = $(document).scrollLeft();
	var winWidth = $(window).width();
	var winHeight = $(window).height();
	var motherTop = $(mother).offset().top;
	var motherLeft = $(mother).offset().left;
	var arrowWidth = 23;
	var arrowHeight = $("#toolTipArrow").height();
	var motherWidth = $(mother).width();
	var motherHeight = $(mother).height();
	var toolTipWidth = $(toolTip).width();
	var toolTipHeight = $(toolTip).height();
	var spaceAvailableAbove = motherTop+(motherHeight/2)-sTop;
	var spaceAvailableToTheLeft = motherLeft-sLeft-offsetX;
	var spaceAvailableToTheRight = winWidth-motherLeft-motherWidth-offsetX+sLeft;
	var spaceAvailableUnderneath = winHeight-(motherHeight/2)-motherTop+sTop;

		// Determine horizontal position
	if (spaceAvailableToTheRight<toolTipWidth){
		
		if(spaceAvailableToTheLeft<spaceAvailableToTheRight){
			// Display to the right
			toolTipX = motherWidth+motherLeft+offsetX+arrowWidth;
		}
		else{
			//Display to the left
			toolTipX = motherLeft-offsetX-toolTipWidth-arrowWidth;
			arrowSide = "left";
		}
	}else{
		// Display to the right
		toolTipX = motherWidth+motherLeft+offsetX+arrowWidth;
		arrowSide = "right";
		
	}
	// Determine vertical position
	if((winHeight)<toolTipHeight){
		toolTipY = sTop - offsetY;	
	}
	else if(spaceAvailableUnderneath<-20){
		return "position failed";	
	}
	else if(spaceAvailableUnderneath<(toolTipHeight/2)){
		toolTipY = winHeight+sTop-toolTipHeight - offsetY;
	}
	else if(spaceAvailableAbove<0){
		return "position failed";	
	}
	else if(spaceAvailableAbove<(toolTipHeight/2)){
		toolTipY = sTop + offsetY;	
	}
	else{
		toolTipY = motherTop+(motherHeight/2)-(toolTipHeight/2);	
	}

	$(toolTip).css({
		top: toolTipY,
		left: toolTipX
	});
	displayArrow(mother);

	function displayArrow(mother) {
	    var toolTipWidth = $(toolTip).width();
	    var toolTipHeight = $(toolTip).height();
	    var arrowX = toolTipX - arrowWidth + 1;
	    var arrowY = toolTipY + (toolTipHeight / 2) - arrowHeight / 2;
	    var toolTipArrow = $("#toolTipArrow");
	    var activityClass = (mother.parents('.shoreExcursion').length > 0) ? true : false;

	    if (arrowSide == "left") {
	        toolTipArrow.removeClass("activityTipLeft").removeClass("activityTipRight");
	        (activityClass) ? toolTipArrow.addClass("activityTipRight").removeClass("activityTipLeft") : null;
	        toolTipArrow.addClass("vmOverlayArrowRight").removeClass("vmOverlayArrowLeft");
	        arrowX = toolTipX + toolTipWidth - 2;
	    } else {
	        toolTipArrow.removeClass("activityTipLeft").removeClass("activityTipRight");
	        (activityClass) ? toolTipArrow.removeClass("activityTipRight").addClass("activityTipLeft") : null;
	        toolTipArrow.removeClass("vmOverlayArrowRight").addClass("vmOverlayArrowLeft");
	        arrowX = toolTipX - arrowWidth + 1;
	    }
	    if (arrowY > motherTop + motherHeight / 2 - arrowHeight / 2) {
	        arrowY = motherTop + motherHeight / 2 - arrowHeight / 2;
	    }
	    if (arrowY < motherTop + motherHeight / 2 - arrowHeight / 2) {
	        arrowY = motherTop + motherHeight / 2 - arrowHeight / 2;
	    }
	    if ((motherTop - sTop + motherHeight / 2 - arrowHeight / 2) < 0) {
	        arrowY = toolTipY;
	    }
	    // mother object is beneath the fold
	    if ((motherTop - winHeight - sTop) > 0) {
	        arrowY = winHeight + sTop - arrowHeight - 3;
	    }
	    // mother object is close to beneath the fold
	    if ((motherTop - winHeight - sTop + arrowHeight / 2 + motherHeight / 2) > 0) {
	        arrowY = winHeight + sTop - arrowHeight - 5;
	    }
	    toolTipArrow.css({ top: arrowY, left: arrowX });
	}
}
// END: Tool Tip Engine

function google_translate_func(selector, lang) {
    $.translate(function() {
        $(selector).translate('en', lang, {
            not: '.option, #demo, #source, pre, .jq-translate-ui, .notranslate, .cufon-canvas',
            fromOriginal: true
        });
    });
}

/* @author Klaus Hartl/klaus.hartl@stilbuero.de */
function cookie(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
