
isIE6 = (navigator.appVersion.indexOf('MSIE 6.0') > 0) ? true : false;
isIE7 = (navigator.appVersion.indexOf('MSIE 7.0') > 0) ? true : false;

// replace headers with sIFR Dax text - called at foot of masterpage. Does not run in page edit mode
function initSIFR() {
	// make space for pageTools
	if($(".pageTools").length > 0 && $(".column1 h1.sifrSize0, .doubleColumn h1.sifrSize0").length > 0) {
		h1Width = 530-($(".pageTools").width()+20)
		$(".column1 h1.sifrSize0, .doubleColumn h1.sifrSize0").width(h1Width);
		$(".pageTools").css({"margin-bottom":"-35px","margin-top":"15px"});
	}
	// add richHTMLField class to field control text (this has to happen before sifr) - duplicate in variousCSS for users without flash
	$("div[id*='RichHtmlField']").addClass("richHTMLField");

	if($(".ms-WPAddButton").length>0) {
		//disable sIFR  in edit pages
		$("html").removeClass("sIFR-hasFlash");
	}
	fontPath = "/_layouts/CB2C/Styles/dax.swf";
	
	if(typeof sIFR == "function" && $(".ms-WPAddButton").length =='0'){
		// page titles (opaque)
		sIFR.replaceElement(".sifrSize0", named({sFlashSrc: fontPath, sColor: "#117193", sWmode: "opaque"}));

		// port names in destination pages ports carousel
		sIFR.replaceElement(".destCarouselHead h3.sifrSize3", named({ sFlashSrc: fontPath, sColor: "#ffffff", sBgColor: "#7AC8D5", sWmode: "opaque" }));
		sIFR.replaceElement(".destCarouselHead h3.sifrSize2", named({ sFlashSrc: fontPath, sColor: "#ffffff", sBgColor: "#7AC8D5", sWmode: "opaque" }));
		// cruise names in ship cruise cam page
		sIFR.replaceElement(".currentCruiseBox .sifrSize2", named({sFlashSrc: fontPath, sColor: "#ffffff", sBgColor:  "#7AC8D5" }));
		// highlightArea
		sIFR.replaceElement(".highlightArea h2.sifrSize1", named({sFlashSrc: fontPath, sColor: "#ffffff", sBgColor:  "#7AC8D5", sWmode: "opaque" }));
		// headers in dynamic highlight areas (e.g. how to book)
		sIFR.replaceElement(".highlightArea h3.sifrSize2", named({sFlashSrc: fontPath, sColor: "#117193", sBgColor:  "#F0F8F9" }));
		// headers in cruise profile tabs
		sIFR.replaceElement(".contentMainInner3 .column2 .sifrSize1, .contentMainInner3 .cruiseProfCol2 .sifrSize1", named({sFlashSrc: fontPath, sColor: "#ffffff", sBgColor:"#7bc9d6"}));
		// blue titles in cruise profile, cruise guide tab
		sIFR.replaceElement(".contentMainInner3 .column2 .wp26 .sifrSize2", named({sFlashSrc: fontPath, sColor: "#158bb2", sBgColor: "#f0f8f9"}));
		// regular page subtitles (opaque)
		sIFR.replaceElement(".column1 .sifrSize1", named({ sFlashSrc: fontPath, sColor: "#2492b7", sWmode: "opaque" }));
		// cruise profile subtitles
		sIFR.replaceElement(".contentMainInner3 .sifrSize1", named({ sFlashSrc: fontPath, sColor: "#2492b7", sWmode: "opaque" }));
		// cruise profile /prices tab highlight box
		sIFR.replaceElement(".whatsincludedSection .sifrSize2", named({ sFlashSrc: fontPath, sColor: "#2492b7", sBgColor: "#f0f8f9", sWmode: "opaque" }));
		// cruise profile /prices tab suite type
		sIFR.replaceElement(".pricingTab .sifrSize2", named({ sFlashSrc: fontPath, sColor: "#2492b7", sWmode: "opaque" }));
		// regular page smaller titles (opaque)
		sIFR.replaceElement(".column1 .sifrSize2", named({sFlashSrc: fontPath, sColor: "#0071a0", sWmode: "opaque"}));
		// homepage middle column subtitles
		sIFR.replaceElement(".column1a .sifrSize1", named({sFlashSrc: fontPath, sColor: "#2492b7", sWmode: "transparent"}));
		// homepage middle column smaller title
		sIFR.replaceElement(".column1a .sifrSize2", named({sFlashSrc: fontPath, sColor: "#0071a0", sWmode: "transparent"}));
		// need help titles (transparent)
		sIFR.replaceElement(".column2 .wp26 h2", named({sFlashSrc: fontPath, sColor: "#ffffff", sWmode: "transparent"}));
		sIFR.replaceElement(".column2 .wp26 .sifrSize2", named({sFlashSrc: fontPath, sColor: "#ffffff", sWmode: "transparent"}));
		// shps blog title (transparent)
		sIFR.replaceElement(".column2 .wpShipBlog .sifrSize1", named({sFlashSrc: fontPath, sColor: "#ffffff", sWmode: "transparent"}));
		// column 2 subtitles (opaque)
		sIFR.replaceElement(".column2 h2.sifr, .column2 a.sifrSize1, .column2 .wpBonusMessage h2", named({sFlashSrc: fontPath, sColor: "#ffffff", sBgColor: "#7dbdcd", sWmode: "opaque"}));
		// regular page small titles, cruise profile tab small titles
		sIFR.replaceElement(".column1 .sifrSize3, .contentMainInner3 .sifrSize3", named({sFlashSrc: fontPath, sColor: "#158bb2", sWmode: "opaque"}));
		// column 2 small titles (opaque)
		sIFR.replaceElement(".column2 h3.sifrSize3", named({sFlashSrc: fontPath, sColor: "#ffffff", sBgColor: "#7dbdcd", sWmode: "opaque"}));
		
		if(!jQuery.support.boxModel) $(".contentMainInner2").css("zoom","1");
	};
}

// nautical glossary - rotate terms
function initGlossary() {
	$(".wp02 dt:first").show();
	$(".wp02 dd:first").show();
	
	$(".wp02 .next").click(function() {
		if( $(".section.wp02 dd:last-child").is(":visible") ) {
			$(".section.wp02 dt:visible").hide().next().hide();
			$(".section.wp02 dt:first").show().next().show();
		} else {
			$(".section.wp02 dt:visible").hide().next().hide().next().show().next().show();
		}
		return false;
	});
}

// replace images with  rounded corner images (not in page edit mode)
function roundImages() {
	//add grid class to grid images
	$("ul.grid img").addClass("img_grid");
	$("ul.heroGrid img").addClass("img_hero").removeClass("img_grid");
	// add hero class to shore tour images
	$(".shoreTourImage img").addClass("img_hero");
	
	// only outside page edit mode
	if($(".ms-WPAddButton").length == 0){
	
		// replace images in content areas with just img
		$("div[id*='RichHtmlField'] img").each( function() {
			if($(this).hasClass('preRounded')) return;
			if ($(this).width() == 153) {$(this).addClass("img_grid");}
			if ($(this).width() == 190) {$(this).addClass("img_body");}
			if ($(this).width() == 250) { $(this).addClass("img_hero"); }
			if ($(this).width() == 255) { $(this).addClass("img_home"); }
			//remove alignment paragraph
			if($(this).parents("p").length == 1) {
				imgString = $(this).parents("p").html();
				$(this).parents("p").replaceWith(imgString);
			}
		});
	
		$("img.img_hero,img.img_body,img.img_grid,img.img_home").each( function(){
			isrc = $(this).attr("src");
			iclass = $(this).attr("class");
			ialt = $(this).attr("alt");
			$(this).replaceWith('<div class="'+iclass+'" style="background:url('+isrc+') no-repeat 0 0" title="'+ialt+'"><div></div></div>')
		});
	}
}
_spBodyOnLoadFunctionNames.push('roundImages');

// style a highlight area so that it can be included easily in dynamic content
function highlightArea() {
	// only outside of page edit mode 
	if($(".ms-WPAddButton").length == 0 && $(".pricingTab").length == 0){
		$("div.highlightArea div").addClass("hl-content");
		$("div.highlightArea").append("<span class='hl-top-lft'>&nbsp;</span><span class='hl-top-rgt'>&nbsp;</span><span class='hl-bot-lft'>&nbsp;</span><span class='hl-bot-rgt'>&nbsp;</span>");
		$("div.highlightArea h2").wrap("<div class='hl-header'>");
	}
}
_spBodyOnLoadFunctionNames.push('highlightArea');

// various CSS tweaks
function variousCSS() {
	// add richHTMLField class to field control text for users without flash (also in initSIFR)
	if(!$("html").hasClass('sIFR-hasFlash')){
		$("div[id*='RichHtmlField']").addClass("richHTMLField");
	}
	//remove dotted line from last col2 section
	$(".column2 .section:last").css("background-image","none");
	// remove empty first list in navigation
	$(".CB2C li li:first-child a").css({"border":"0"});
	//first child of gallery
	$(".gallery ul li:first-child").css("margin-left","0");
	// trim last departure port name until it's small enough.
	if($("#ccDepartPortName").width() > 120) {
		portName = $("#ccDepartPortName").text();
		$("#ccDepartPortName a").text(portName.substr(0,20) + "...")
	}
}
_spBodyOnLoadFunctionNames.push('variousCSS');

// realign grid if h3.sifr title text runs onto more than one line.
function realignGrid(){
	$(".grid > li").addClass('g');
	$(".grid li:has('h3.sifr')").each( function(i) {
		if(parseInt($(this).children("h3.sifr").height()) > 17) {
			newHeight = $(this).children("h3.sifr").height() + "px";
			// apply heights to 2 other headings in the same row depending on current position in the row
			if((i+1)%3 == 1) {	rowExpression = "li.g:eq("+(i+1)+"), li.g:eq("+(i+2)+")";	}
			if((i+1)%3 == 2) {	rowExpression = "li.g:eq("+(i-1)+"), li.g:eq("+(i+1)+")";	}
			if((i+1)%3 == 3) {	rowExpression = "li.g:eq("+(i-2)+"), li.g:eq("+(i-1)+")";	}

			$(this).parent().children(rowExpression).find("object,embed").css("height",newHeight);
		}
	});
	
	// force  LI P heights to be the same size in each row
	rowHeights = new Array();
	$(".grid").each( function(){
		//hero grids only have 2 columns
		columns = $(this).hasClass("heroGrid") ? 2 : 3;
		// get number of list items
		numOfItems = $(this).find("li.g").length;
		// make an array of all LI heights
		for(i=0; i<numOfItems; i++){
			rowHeights[i] = $(this).find("li.g:eq("+i+") p").height();
		}
		function sortNumber(a,b){
			return a - b;
		}
		
		// loop through all LIs
		for(j=0; j<numOfItems; j++){
			// for each LI in first col,
			if(j%columns == 0) {
				// make array of all heights in this row, sort descending, take first item
				tallestP = rowHeights.slice(j,j+columns).sort(sortNumber).reverse()[0];
				// have to use diff start expression for j=0, because can't use li:gt(-1)
				startFinishExpression = (j==0) ? "li.g:lt("+(j+columns)+") p" : "li.g:gt("+(j-1)+"):lt("+(j+columns)+") p";
				// set heights for all row paragraphs
				$(this).find(startFinishExpression).height(tallestP);
			}
		}
	});
}
_spBodyOnLoadFunctionNames.push('realignGrid');

// operate destination port dropdowns
function OpenPort(ref) {
	
	$(".portDropDown").blur( function() {
		$(this).hide();
	});
	
	if ($('#' + ref).css('display') == 'none') {
		$("div[id^='Drop']").css("display", "none");
		$('#' + ref).show().css('outline','none');
	}
	else {
		$("div[id^='Drop']").hide();
		
	}
}
//_spBodyOnLoadFunctionNames.push('OpenPort');

// Overrides to OOB SharePoint Script to hide presence
function ProcessDefaultOnLoad(onLoadFunctionNames) {
    ProcessPNGImages();
    UpdateAccessibilityUI();
    //ProcessImn(); //Hide Presence
    for (var i = 0; i < onLoadFunctionNames.length; i++) {
        var expr = "if(typeof(" + onLoadFunctionNames[i] + ")=='function'){" + onLoadFunctionNames[i] + "();}";
        eval(expr);
    }
    if (typeof (_spUseDefaultFocus) != "undefined")
        DefaultFocus();
}

// clear default text in input boxes on click (compares with title text)
function toggleDefaultText() {
	if($(".ms-WPAddButton").length == 0){
		$("input[type='text'], textarea").focus( function(){
			if($(this).attr("title") == $(this).attr("value")) {
				$(this).attr("value","");
			}
		});
		$("input[type='text'], textarea").blur( function(){
			if(jQuery.trim($(this).attr("value")) == "") {
				$(this).attr("value",$(this).attr("title"));
			}
		});
	}
}
_spBodyOnLoadFunctionNames.push('toggleDefaultText');

// set cookie function
function setCookie(c_name, value, expiredays) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+"; path=/"+
	    ((expiredays==null) ? "" : "; expires="+exdate.toGMTString());
}

// read cookies
function getCookie(c_name)
{
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}
// generic ajax updates
function initAjaxUpdates(sender, args) {
    initSIFR();
    roundImages();
    realignGrid();
    tb_init('a.thickbox');
	if (isIE6) { ie6pngFix(true) };
	
	// enumerates updatepanels who registered updates
	var dataItems = args.get_dataItems();
	if (dataItems != null) {
	    for (var prop in dataItems) {
	        eval(dataItems[prop]);
	    }
	}
}

function initPriceTab() {
	togglePriceCategories();
}
function initShipTab(customScript) {
    if (customScript!=null) eval(customScript);
	imageGallery();
}
function initCruiseGuideTab() {
	toggleDefaultText();
}

// Read querystring param
function getParameterByName(name) { name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]"); var regexS = "[\\?&]" + name + "=([^&#]*)"; var regex = new RegExp(regexS); var results = regex.exec(window.location.href); if (results == null) return ""; else return results[1]; }

// enable T&C cookie for media library 
function acceptMediaTerms() {
    $(".iagree").click(function() {
        setCookie("caumediaterms", "accepted");
        document.location.href = unescape(getParameterByName("ref"));
    });
}
_spBodyOnLoadFunctionNames.push('acceptMediaTerms');

// enable shortlistbutton
function UpdateShortListButton() {
    var hasShortList = false;
    if (Number(getCookie("hasSL")) > 0) hasShortList = true;
    if (getCookie("CAUSL") != '') hasShortList = true;
    $('#ShortListButton').css("visibility", hasShortList ? "visible":"hidden");
    setTimeout(UpdateShortListButton, 1000);
}
_spBodyOnLoadFunctionNames.push('UpdateShortListButton');

// validate forms 
// nb this function is also in global-modal.js
function validateForm(formName) {
	badCounter = 0;
	//clear current error warnings
	$("#"+formName+" label").removeClass("formWarning").siblings("span.formHelp").remove();
	
	// for each mandatory input that's empty
	$("#" + formName).find(".mandatory ~ input, .mandatory ~ textarea").each(function() {
		
		if( ($(this).attr('value') == "") || ($(this).attr('value') == $(this).attr('title')) ) {
			badCounter ++;
			// add warning message and highlight label
			$(this).after('<span class="formHelp">Please enter text</span>').siblings(".mandatory").addClass("formWarning");
			// on focus remove warnings.
			$(this).focus( function (){
				$(this).siblings("label").removeClass("formWarning").siblings("span.formHelp").remove();
			});
		}
	});
	
	// for each input that's not a proper email address
	$("#"+formName).find(".email ~ input").each(function() {
		emailInput = $(this).attr("value");
		if( (emailInput != "") && (emailInput != $(this).attr('title')) ) {
			// check for single @ and at least one dot in the domain
			if(
				emailInput.split('@').length == 2 
				&& emailInput.split('@')[0] != ""
				&& emailInput.split('@')[1].split('.').length > 1 
				&& emailInput.split('@')[1].split('.')[0] != ""
				&& emailInput.split('@')[1].split('.')[1] != ""
			){
				return
			} else {
				badCounter ++;
				// add warning message and highlight label
				$(this).after('<span class="formHelp">Enter an email address</span>').siblings(".email").addClass("formWarning");
				// on focus remove warnings.
				$(this).focus( function (){
					$(this).siblings("label").removeClass("formWarning").siblings("span.formHelp").remove();
				});
			}
		}
	});
	
	return ( badCounter > 0) ? false : true;
}

// check that user has selected a brochure 
function validateBrochures(formName) {
	if($("#brochuresList input:checkbox:checked").length == 0) {
		$("#brochuresList").after('<div class="formWarning">You haven\'t selected any brochures!</div>');
		$("#brochuresList input:checkbox").focus( function(){
			$(".wp15 .formWarning").remove();
		});
		return false;
	} else {
		return true;
	}
}

// load waves
function loadWaves() {
	var params = {
		wmode: 'transparent',
		scale: 'noborder',
		salign: '',
		quality: 'best',
		menu: 'false',
		allowscriptaccess: 'always',
		allowFullscreen: 'false'
	};
	var flashvars = {};
	var attributes = {};
	swfobject.embedSWF("/_layouts/CB2C/Styles/Images/waves_left_loader.swf", "flashLeftBox", "357", "350", "9.0.0", "/SiteCollectionImages/Flash/expressInstall.swf", flashvars, params, attributes);
	swfobject.embedSWF("/_layouts/CB2C/Styles/Images/waves_right_loader.swf", "flashRightBox", "357", "350", "9.0.0", "/SiteCollectionImages/Flash/expressInstall.swf", flashvars, params, attributes);
	if (isIE6 || isIE7) $("#flashLeftBox").css("margin-left", "-500px");
}
window.onresize = function() {
	// fix left waves alignment in IE6&7
	if(isIE6 || isIE7) $("#flashLeftBox").css("margin-left","-500px");
}
_spBodyOnLoadFunctionNames.push('loadWaves');

// show prices boxes in cruise profile page
function togglePriceCategories(){
	$(".tableToggle").click( function(){
		if($(this).parents('.pricingTabHeadSection').siblings("table.cruisePrices").is(":visible")) {
			$(this).parent().find("a.tableToggle").each( function() {
				$(this).text($(this).text().replace('Hide','Show'))
			});
			$(this).parents('.pricingTabHeadSection').find(".tableToggle").css("background-position","0 0")
		} else {
			$(this).parent().find("a.tableToggle").each( function() {
				$(this).text($(this).text().replace('Show','Hide'))
			});
			$(this).parents('.pricingTabHeadSection').find(".tableToggle").css("background-position","0 bottom")
		}
				
		$(this).parents('.pricingTabHeadSection').siblings("table.cruisePrices").toggle();
		return false;
	});
}

// open lightbox from media image library
function mediaImageLibraryLightbox(){
	$(".mediaLibrary a").lightBox();
}

function carousselClick(thumb)
{
    // take thumbnail image and use to switch main pic's src and href.
    $(thumb).parents(".gallery").find("#mainPic img").attr({
		"src": $(thumb).attr("href"),
		"alt": $(thumb).find("img").attr("alt")
	});
    $(thumb).parents(".gallery").find("#mainPic a").attr({
		"href": $(thumb).find("img").attr("src").replace(/\/_w/, '').replace(/_jpg.jpg/, '.jpg'),
		"title": $(thumb).find("img").attr("alt")
	});
    return false;
}

// image gallery, adds onto jcarousel (qv)
function imageGallery(){
	$("#mainPic a").lightBox();
	$("#carousel a").lightBox();
	if(isIE6) $(document).pngFix();
}

// hides and reveals New Details of Past Passenger
function newDetailsPastPassenger(){
	$(".deleteDetails input").click(function(){
		$("#newDetails").css("display","none");
		$("#newDetails").find(".mandatory").removeClass("mandatory").addClass("notmandatory");
	});
	$(".updateDetails input").click(function(){	
		$("#newDetails").find(".notmandatory").removeClass("notmandatory").addClass("mandatory");
		$("#newDetails").css("display","block");
	});
}

//Resume-fulltour scripts
var playHeadPosition;
function storePlayHeadPosition(t) {
    setCookie("fullTourResume", t);
}
function readPlayHeadPosition() {
    playHeadPosition = getCookie("fullTourResume");
    document["fullTourBarSWF"].readPlayHeadPosition(playHeadPosition);
}
function removeBar() {
    setCookie("fullTourResume", "");
    $("#resumeBar").css("display", "none");
}
function showFullTour() {
    if (getCookie("fullTourResume") != "") {
        var flashvars = { movieURL: "/SiteCollectionImages/Flash/FullTour/FullTourVideoPlayer.swf" };
        var params = {
            wmode: 'transparent',
            bgcolor: '#FFFFFF',
            scale: 'noborder',
            salign: '',
            quality: 'best',
            menu: 'false',
            allowscriptaccess: 'always',
            swliveconnect: 'true',
            allowFullScreen: 'true'
        };
        var attributes = { id: "fullTourBarSWF" };
        swfobject.embedSWF("/SiteCollectionImages/Flash/FullTour/fullTourBar.swf", "fullTourBar", "148", "22", "9.0.0", "expressInstall.swf", flashvars, params, attributes);

        $("#resumeBar").css("display", "block");
    }
    setTimeout(showFullTour, 1000);
}
_spBodyOnLoadFunctionNames.push('showFullTour');

function shareWithFriend() {
    $('.sendFriend').click();
}

function switchSite(host,path,override) {
    var searchUrl = $('#ActiveSearchUrl');
    if (searchUrl.length > 0) { path = searchUrl.val()+override; }
    window.location.href = host+path;
    return false;
}

function initPageTrackers() {
    $('.trackGA').each(function(index) {
        $(this).bind(
        "click",
        function() {
            var href = $(this).attr('href');
            href = href.substring(href.indexOf('//') + 2).replace(/\/$/, "");
            recordPageView('/external/' + href);
        });
    });
}
function recordPageView(id) {
    if (pageTracker != null) pageTracker._trackPageview(id);
}
_spBodyOnLoadFunctionNames.push('initPageTrackers');

function closeModal(){
	$("#basicModalContent").hide();
	$("#TB_iframeContent").width(270).height(60);
	$("#TB_window").animate({width:"270px",height:"60px",marginLeft: "-135px", marginTop: "-30px"});
	$("#basicModalContent").fadeIn('slow');
	t = setTimeout("self.parent.tb_remove()",3000);
}
