pageEditMode = false;
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);
	}
	// 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($("table.ms-WPAddButton").length>0) {
		//disable sIFR  in edit pages
		$("html").removeClass("sIFR-hasFlash");
	}
	fontPath = "/_layouts/CB2C/Styles/dax.swf";
	
	if(typeof sIFR == "function" && $("table.ms-WPAddButton").length =='0'){
			
		// port names in destination pages ports carousel
		sIFR.replaceElement(".facebookPage h1.sifrSize0", named({ sFlashSrc: fontPath, sColor: "#ffffff", sWmode: "transparent" }));
		
		// 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"}));
		
		//cruise profile header
		sIFR.replaceElement(".column1 #cpTab1 h1.sifrSize1", named({sFlashSrc: fontPath, sColor: "#117193", sWmode: "opaque" }));
		
		// blue titles in cruise profile, cruise guide tab
		sIFR.replaceElement(".contentMainInner3 .column2 .wp26 .sifrSize2", named({sFlashSrc: fontPath, sColor: "#158bb2", sBgColor: "#f0f8f9"}));

		// cruise profile subtitles
		sIFR.replaceElement(".contentMainInner3 .sifrSize1", named({ sFlashSrc: fontPath, sColor: "#ok2492b7", 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 titles
		sIFR.replaceElement(".column1a .sifrSize2, .homeColumn1 .sifrSize3", named({sFlashSrc: fontPath, sColor: "#2492b7", sWmode: "transparent"}));
		sIFR.replaceElement(".column1a .sifrSize2, .homeColumn1 .sifrSize2", named({sFlashSrc: fontPath, sColor: "#2492b7", sWmode: "opaque"}));
		sIFR.replaceElement(".homeColumn1 .sifrSize1, .rightSection3 .sifrSize1", named({sFlashSrc: fontPath, sColor: "#2492b7", sWmode: "transparent"}));
		sIFR.replaceElement(".homeColumn1 .sifrSize0", named({sFlashSrc: fontPath, sColor: "#2492b7", sBgColor: "#c8ecff", sWmode: "opaque"}));
		sIFR.replaceElement(".homeColumn2 .rightSection2 .sifrSize1", named({sFlashSrc: fontPath, sColor: "#ec008c", sWmode: "transparent" }));
		
		// homepage call for free web part
		sIFR.replaceElement(".homeColumn2 .cff_head h2.sifrSize1", named({sFlashSrc: fontPath, sColor: "#1291b9", sBgColor:  "#c6ebff", sWmode: "opaque" }));		

		// 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"}));
		// regular page subtitles (opaque)
		sIFR.replaceElement(".column1 .sifrSize1", named({ sFlashSrc: fontPath, sColor: "#2492b7", sWmode: "opaque" }));
		// page titles (opaque)
		sIFR.replaceElement(".sifrSize0", named({sFlashSrc: fontPath, sColor: "#117193", 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() {
	pageEditMode = ($("table.ms-WPAddButton").length>0) ? true : false;
	//add grid class to grid images
	$("ul.grid img").addClass("img_grid");
	$("ul.heroGrid img").addClass("img_hero").removeClass("img_grid");
	$(".img_home_holder img").addClass("img_home");
	// add hero class to shore tour images
	$(".shoreTourImage img").addClass("img_hero");
	
	// only outside page edit mode
	if(!pageEditMode){
	
		// 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"); }

			//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($("table.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 lines from various places.
	$(".column2 .section:last, .homeColumn1 li:first-child, .homeColumn2 li:first-child").css("background-image","none");
	$(".home3Cols li").mouseover(function () { $(this).css('background-color','#dcf3ff'); }).mouseout(function () { $(this).css('background-color','#fff'); } )
	// remove empty first list in navigation
	$(".CB2C li li:first-child a").css({"border":"0"});
	//first child of gallery
	$(".gallery ul li:first-child, .destPickerNav 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($("table.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, .mandatory ~ .chkbox").each(function() {
		
		if($(this).hasClass('chkbox') && $(this).find('input:checked').length == 0) {
			badCounter ++;
			// add warning message and highlight label
			$(this).after('<span class="formHelp">You must check this box to continue</span>').siblings(".mandatory").addClass("formWarning");
			// on focus remove warnings.
			$(this).focus( function (){
				$(this).siblings("label").removeClass("formWarning").siblings("span.formHelp").remove();
			});
		} else {
		
			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();
				});
			}
		}
	});

	$("#" + formName).find(".mandatory ~ select").each(function() {
	if (this.selectedIndex == 0 && this.value=='') {
	        badCounter++;
	        // add warning message and highlight label
	        $(this).siblings(".mandatory").addClass("formWarning");
	        // on focus remove warnings.
	        $(this).focus(function() {
	            $(this).siblings("label").removeClass("formWarning");
	        });
	    }
	});
	
	// 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
			var emailPattern = /^[a-zA-Z0-9\.\''_-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;   
			if(!emailPattern.test(emailInput))
			{
				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 ($("#brochuresValidate input:checkbox:checked").length == 0) {
        $(".formWarning").remove();
        $(".buttonContainerSection").before('<div class="formWarning">You haven\'t selected any brochures!</div>');
		$("#brochuresValidate 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 getHeading(ref) {
    var head = $(ref).siblings("h1,h2,h3");
    if (head.length > 0) {
        if (head[0].innerText == undefined)
            return head[0].children("span").innerText;
        else
            return head[0].innerText;
    }
    else
        return getHeading($(ref).parent());
}
// Google related
function AutoPageTracker() {
    $('.richHTMLField a').click(function() {
        var head = getHeading(this);
        if (head==undefined) head = $(this).text();
        recordEvent(location.pathname, $(this).attr('href'), head);
    });
}

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);
}
function recordEvent(category, action, label) {
    if (pageTracker != null) pageTracker._trackEvent(category, action, label);
}
function BookLink(ref, cruiseCode) {
    var url = ref.href;
    if (pageTracker != null)
        url = pageTracker._getLinkerUrl(ref.href);
    var utmz = $.cookie('__utmz');
    if (utmz != null && utmz.indexOf("utmcsr")>0) {
        var camp = utmz.substring(utmz.indexOf("utmcsr"));
        var parts = camp.split("|");
        for (var p = 0; p < parts.length; p++) {
            var item = parts[p].split("=");
            if (item[0] = "utmcsr") url += "&utm_source=" + item[1];
            if (item[0] = "utmccn") url += "&utm_campaign=" + item[1];
            if (item[0] = "utmcmd") url += "&utm_medium=" + item[1];
        }
    }
    return !window.open(url, "Book" + cruiseCode + "", "width=750,height=550,scrollbars=1");
}
_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);
}
function closeModalLarge() {
    $("#basicModalContent").hide();
    $("#TB_iframeContent").width(400).height(260);
    $("#TB_window").animate({ width: "400px", height: "260px", marginLeft: "-135px", marginTop: "-30px" });
    $("#basicModalContent").fadeIn('slow');
    t = setTimeout("self.parent.tb_remove()", 3000);
}

function afeatureSlides_initCallback(carousel) {
    // track right/left clicks 
    $('.jcarousel-next, .jcarousel-prev').bind('click', function() {
        var whichClicked = ($(this).hasClass('jcarousel-next')) ? 'Next' : 'Prev';
        recordEvent('Afeature ' + aFeatGACat, 'Arrows', whichClicked)
    });

    // scroll carousel when users click on dots, track clicks
    $('.jcarousel-control a').bind('click', function() {
        var buttonIndex = $(this).text();
        carousel.scroll($.jcarousel.intval(buttonIndex));
        $(this).blur();
        recordEvent('Afeature ' + aFeatGACat, 'Nav Circles', 'Slide ' + buttonIndex);
        return false;
    });

    $('.jcarousel-item .afeaturebutton').bind('click', function() {
        recordEvent('Afeature ' + aFeatGACat, 'Button', $(this).attr('copy'));
    });

};

// update dots when slides move
function afeatureSlides_visibleInCallback(carousel, listObject, listIndex) {
    currentSlide = $(listObject).find('h2').attr('jcarouselIndex');
    $('.jcarousel-control a').removeClass('selected');
    $('.jcarousel-control a:eq(' + currentSlide + ')').addClass('selected');
}

// set up carousel
function loadCarousel() {
    if (!pageEditMode) {
        // disable next/prev buttons, circularity in IE6		
        if (isIE6) {
            $("#afeatureSlides").jcarousel({ wrap: null, buttonNextHTML: null, buttonPrevHTML: null, scroll: 1, initCallback: afeatureSlides_initCallback, itemVisibleInCallback: { onBeforeAnimation: afeatureSlides_visibleInCallback} }).css('visibility', 'visible');
        } else {
            $("#afeatureSlides").jcarousel({ scroll: 1, initCallback: afeatureSlides_initCallback, itemVisibleInCallback: { onBeforeAnimation: afeatureSlides_visibleInCallback} }).css('visibility', 'visible');
        }

        // apply sifr to titles
        boldFontPath = "/_layouts/CB2C/Styles/dax-bold.swf";
        exBoldFontPath = "/_layouts/CB2C/Styles/dax-extrabold.swf";
        sIFR.replaceElement(".afeatureSubtitle", named({ sFlashSrc: boldFontPath, sColor: "#ffffff", sWmode: "transparent" }));
        sIFR.replaceElement(".afeatureTitle", named({ sFlashSrc: exBoldFontPath, sColor: "#ffffff", sWmode: "transparent" }));

        //run pngFix
        if (isIE6) { $(".afeaturebutton").show().pngFix(); }
    }
}

/* call for free */
function InitCallForFree() {
    $('#cff_submit').click(function() {

        var badCounter = validateCallForm();

        if (badCounter == 0) {

            var data = { 'phone': '', 'area': '', 'email': '', 'firstname': '', 'lastname': '', 'cruisecode': '', 'itineraryname': '', 'region': '', 'cruisedbefore': '', 'urn': '', 'contacttime': '', 'optin': 'yes' };
            data.email = GetFieldValue('#cff_email');
            data.firstname = GetFieldValue('#cff_firstname');
            data.lastname = GetFieldValue('#cff_lastname');
            data.cruisecode = GetFieldValue('#cff_cruisecode');
            data.cruisedbefore = GetFieldValue('#cff_cruisedbefore');
            data.itineraryname = GetFieldValue('#cff_itineraryname');
            data.region = GetFieldValue('#cff_region');
            data.optin = GetFieldValue('#cff_optin');
            data.urn = GetFieldValue('#cff_urn');
            data.phone = GetFieldValue('#cff_area') + ' ' + GetFieldValue('#cff_phone');

            $.ajax({
                type: 'POST',
                url: '/_layouts/cb2c/ajax/CallForFreeHandler.ashx',
                data: data,
                success: HandleSubmit,
                dataType: 'json'
            });
            return false;
        } else {
            return false;
        }

    });

    $('#cff_cruisedbefore').click(function() {
        var y = $('select#cff_cruisedbefore option:selected').val();
        if (y == 'Yes') { $('#cff_urnfield').show(); } else { $('#cff_urnfield').hide(); }
    });

    // Opens and closes the 'tell us more' section.
    $('.toggle_container').hide();
    $('h2.expand_heading').toggle(function() {
        $(this).next('.toggle_container').slideToggle('slow');
        $('h2.expand_heading').addClass('active');
        $('.homeColumn2 #cff_entry .expand_wrapper').css('border-bottom', '1px dotted #FFF');
    }, function() {
        $(this).next('.toggle_container').slideToggle('slow', function() {
            $('h2.expand_heading').removeClass('active');
            $('.homeColumn2 #cff_entry .expand_wrapper').css('border-bottom', '1px dotted #37c3e9');
        })
    });

    $("#cff_cruisecode").autocomplete({
        minLength: 1,
        source: function(request, response) {
            $.ajax({
                url: "/_layouts/CB2C/Ajax/CruiseCodeOrTitleSearchHandler.ashx",
                dataType: "json",
                data: request,
                success: function(data) { if (data != null) response(data); }
            });
        },
        focus: function(event, ui) {
            $("#cff_cruisecode").val(ui.item.CruiseCode);
            $("#cff_itineraryname").val(ui.item.Title);
            return false;
        }
    })
    .keypress(function(e) {
        if (e.which == 13) { return false; }
    })
    .data("autocomplete")._renderItem = function(ul, item) {
        var key = $("#cff_cruisecode").val();
        var keyHigh = "<span class='highlite'>$1</span>";
        var keyReg = new RegExp("(" + (key + '').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, "\\$1") + ")", 'i');
        var text = "<a>" + item.Title.replace(keyReg, keyHigh) + ", " + item.CruiseCode.replace(keyReg, keyHigh) + "<br/>Departs " + item.Date + "</a>";

        return $("<li></li>")
	        .data("item.autocomplete", item)
	        .append(text)
	        .appendTo(ul);
    };
}

function validateCallForm() {
    var badCounter = 0;

    // first name 
    if (($('#cff_firstname').val() == "") || ($('#cff_firstname').val() == $('#cff_firstname').attr('title'))) {
        badCounter++;
        $('#error-firstname').show();
        // on focus remove warnings	
        $('#cff_firstname').focus(function() {
            $('#error-firstname').hide();
        });
    } else {
        $('#error-firstname').hide();
    }

    // last name 	
    if (($('#cff_lastname').val() == "") || ($('#cff_lastname').val() == $('#cff_lastname').attr('title'))) {
        badCounter++;
        $('#error-lastname').show();
        // on focus remove warnings	
        $('#cff_lastname').focus(function() {
            $('#error-lastname').hide();
        });
    } else {
        $('#error-lastname').hide();
    }

    // phone number	
    if (($('#cff_phone').val() == "") || ($('#cff_phone').val() == $('#cff_phone').attr('title'))) {
        badCounter++;
        $('#error-phone').show();
        // on focus remove warnings	
        $('#cff_phone').focus(function() {
            $('#error-phone').hide();
        });

    } else {
        $('#error-phone').hide();
    }

    // email	
    var emailInput = $('#cff_email').val();
    if (((emailInput != "") && ($('#cff_email').val() != $('#cff_email').attr('title')) || ($("#cff_optin").attr("checked") == true))) {
        // check for single @ and at least one dot in the domain
        var emailPattern = /^[a-zA-Z0-9\.\''_-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
        if (!emailPattern.test(emailInput)) {
            badCounter++;
            $('#error-email').show();

            // on focus remove warnings
            $('#cff_email').focus(function() {
                $('#error-email').hide();
            });
        }
    } else {
        $('#error-email').hide();
    }

    return badCounter;
}

function GetFieldValue(fieldref) {
    var field = $(fieldref);
    if (field.attr('title') == field.val()) return "";
    return field.val();
}

function HandleSubmit(result) {
    $('#cff_thanks').show();
    $('#cff_entry').hide();
    if (result != 'success') {
        $('#cff_error').text('Something went wrong, please try again later.');
    }
}


/**
* Date.parse with progressive enhancement for ISO 8601 <https://github.com/csnover/js-iso8601>
* © 2011 Colin Snover <http://zetafleet.com>
* Released under MIT license.
*/
(function(Date, undefined) {
    var origParse = Date.parse, numericKeys = [1, 4, 5, 6, 7, 10, 11];
    Date.parse = function(date) {
        var timestamp, struct, minutesOffset = 0;

        // ES5 §15.9.4.2 states that the string should attempt to be parsed as a Date Time String Format string
        // before falling back to any implementation-specific date parsing, so that’s what we do, even if native
        // implementations could be faster
        //              1 YYYY                2 MM       3 DD           4 HH    5 mm       6 ss        7 msec        8 Z 9 ±    10 tzHH    11 tzmm
        if ((struct = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/.exec(date))) {
            // avoid NaN timestamps caused by undefined values being passed to Date.UTC
            for (var i = 0, k; (k = numericKeys[i]); ++i) {
                struct[k] = +struct[k] || 0;
            }

            // allow undefined days and months
            struct[2] = (+struct[2] || 1) - 1;
            struct[3] = +struct[3] || 1;

            if (struct[8] !== 'Z' && struct[9] !== undefined) {
                minutesOffset = struct[10] * 60 + struct[11];

                if (struct[9] === '+') {
                    minutesOffset = 0 - minutesOffset;
                }
            }

            timestamp = Date.UTC(struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7]);
        }
        else {
            timestamp = origParse ? origParse(date) : NaN;
        }

        return timestamp;
    };
} (Date));
