/*------------------------------------------------------------

 Royal Caribbean - Javascript Functions

 Copyright (c) Building Blocks (UK) Ltd

 Author: Paul Welsh
 Email: p.welsh@building-blocks.com

 Notes:

 - Uses Modernizr to detect feature support
   http://www.modernizr.com

------------------------------------------------------------*/


/* Global Variables
------------------------------------------------------------*/

var mapIconImage = '/_images/css/map-pin-image.png';
var mapIconShadow = '/_images/css/map-pin-shadow.png';
var videoSkin = '/_scripts/jwplayer_royalcaribbean/royalcaribbean.zip';
var videoPlayer = '/_scripts/player.swf';
var currentVideo;

var lang_SeeOtherShips = "See other ships";
var lang_AboutRoyalCaribbean = "About Royal Caribbean";
var lang_Previous = "Previous";
var lang_Next = "Next";

// Use these IE variables as little as possible!
var ltIE7 = $.browser.msie && parseFloat($.browser.version) < 7;
var ltIE8 = $.browser.msie && parseFloat($.browser.version) < 8;

var flashInstalled = false;
try {
    var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
    if(fo){
        flashInstalled = true;
    }
}catch(e){
    if(navigator.mimeTypes ["application/x-shockwave-flash"] != undefined){
        flashInstalled = true;
    }
}

/* Functions
------------------------------------------------------------*/

function IsAttributeSupported(tagName, attrName) {
    var val = false;
    // Create element
    var input = document.createElement(tagName);
    // Check if attribute (attrName)
    // attribute exists
    if (attrName in input) {
        val = true;
    }
    // Delete "input" variable to
    // clear up its resources
    delete input;
    // Return detected value
    return val;
}

// Adds 'Placeholder' polyfill to all items with the attribute
function _placeholderInputs(){

	if(!IsAttributeSupported("input", "placeholder")){
		$('[placeholder]').focus(function(){
			var input = $(this);
			if (input.val() == input.attr('placeholder')){
				input.val('');
				input.removeClass('placeholder');
			}
		}).blur(function() {
			var input = $(this);
			if (input.val() == '' || input.val() == input.attr('placeholder')){
				input.addClass('placeholder');
				input.val(input.attr('placeholder'));
			}
		}).blur().parents('form').submit(function() {
			$(this).find('[placeholder]').each(function(){
				var input = $(this);
				if (input.val() == input.attr('placeholder')){
					input.val('');
				}
			})
		});
	}

}

// Homepage Hero Carousel
function _heroCarousel(){

	function carouselLoad(carousel,carouselNav,currentItem,options){
		carouselNav.addClass('in-view').show();
		$('#hero-carousel').find('article .contents').addClass('ir');
		currentItem.find('.contents').removeClass('ir');
	}
	
	function carouselStart(carousel,carouselNav,currentItem,options,direction){
		$('#hero-carousel').find('article .contents').addClass('ir');
		if(direction == "previous"){
			currentItem.prev().find('.contents').removeClass('ir');
		}else{
			currentItem.next().find('.contents').removeClass('ir');
		}
	}
	
	function carouselEnd(carousel,carouselNav,currentItem,options,direction){
		if(direction == "previous"){
			currentItem.next().find('.contents').addClass('ir');
		}else{
			currentItem.prev().find('.contents').addClass('ir');
		}
	}

	$('#hero-carousel').heroCarousel({
		onLoad: carouselLoad,
		onStart: carouselStart,
		//onEnd: carouselEnd,
		timeout: 4000,
		easing: 'easeOutExpo',
		css3pieFix: true
	});

}

// Adds minimum heights to elements that need to match
function _equalHeights(){

	$('.promos').each(function(i, item){
		var currPromos = $(item);
		if(!currPromos.hasClass('alt')){
			/*
			setTimeout(function(){
				currPromos.find('.promo .contents:not(.cruise-finder)').equalHeights(100,0,10);
				setTimeout(function(){
					currPromos.find('.promo').equalHeights(0,0,10);
				},100);
			},100);
			currPromos.find('.promo').equalHeights(0,0,10);
			*/
		}
	});
	$('.site-links nav').equalHeights(0,0,5);
	$('.extra-content .block').equalHeights(0,0,5);

}

// JW Player HTML5/Flash videos (replaces all <video> tags
var players = [];
function _videoPlayers(autoplay){

	var play = false;
	if(autoplay){
		play = true
	}
	var vidWidth = 640;
	var vidHeight = 360;
	
	$('video').each(function(i,item){
		
		var vid = $(item);
        var vidId = vid.attr('id').replace(/(-|:)/g, "");
		vid.attr('id', vidId);

		if(!$('#video-container-'+vidId).length > 0){
	    	var closeOverlay = false;
	    	if( vid.attr('data-videoclose') == "Yes"){
	    		closeOverlay = true;
	    	}
	    	// height and width set??
			if(vid.attr('width') && vid.attr('height')){
				vidWidth = vid.attr('width');
				vidHeight = vid.attr('height');
			} else if(vid.parents(".hero").length > 0){
				vidWidth = 830;
				vidHeight = 470;
            }
	    	// video source
	    	var vidSources = vid.find('source');
	    	var vidSource = "";
	    	vidSources.each(function(i, item){
	    		var currSource = $(this);
				var sourceType = "";
				if(currSource.attr('type') != null){
					sourceType = currSource.attr('type').toString();
				}
	    		if( sourceType != "" ){
					sourceType = sourceType.split(';');
	    			sourceType = sourceType[0].split('/');
	    			if(sourceType[1].toString() == 'mp4'){
	    				vidSource = currSource.attr('src');
	    			}
	    		}else if(i == 0){
	    			vidSource = currSource.attr('src');
	    		}
	    	});
	    	var vidImage = vid.attr('poster');
	    	vid.wrap('<div id="video-container-'+vidId+'"></div>');
	    	_buildVideoPlayer(vidId,vidSource,vidWidth,vidHeight,vidImage,play,closeOverlay);
		}
	
	});
	
	$('.youtube-video').each(function(i,item){
		
		var vid = $(item);
        var vidId = vid.attr('id').replace(/(-|:)/g, "");
		vid.attr('id', vidId);

		if(!$('#video-container-'+vidId).length > 0){
			var play = false;
			if(autoplay){
				play = true
			}
	    	var closeOverlay = false;
	    	if( vid.attr('data-videoclose') == "Yes"){
	    		closeOverlay = true;
	    	}
	    	// hight and width set??
			if(vid.find('img') && vid.find('img').attr('height')){
				vidWidth = vid.find('img').attr('width');
				vidHeight = vid.find('img').attr('height');
			}
	    	// video source
	    	var vidSource = vid.find('a').attr('href');
	    	var vidImage = vid.find('img').attr('src');
	    	vid.wrap('<div id="video-container-'+vidId+'"></div>');
	    	_buildVideoPlayer(vidId,vidSource,vidWidth,vidHeight,vidImage,play,closeOverlay);
		}
	
	});

}

function _buildVideoPlayer(vidId,vidSource,vidWidth,vidHeight,vidImage,play,closeOverlay){
	jwplayer(vidId).setup({
		'file': vidSource,
		'image': vidImage,
		'width': vidWidth,
		'height': vidHeight,
		'stretching': 'fill',
		'className': 'video',
		'controlbar': 'over',
		'skin': videoSkin,
		'controlbar.idlehide': true,
		'autostart': play,
     	'players': [
        	{type: 'flash', src: videoPlayer}
    	],
    	'events': {
    		'onPlay': function(obj){
				players.push(vidId)
    		},
   			'onComplete': function(obj){
   				if(closeOverlay){
   					$.fancybox.close();
   				}
   			}
    	}
  	});
}

function _stopAllVideos(){
	for (var player in players){
		players[player].sendEvent("STOP");
	}
}

function _imageGalleries(){
	$('.image-gallery').each(function(i,item){
		var gal = $(item);
		gal.find('.image-gallery-items').cycle({
			'pause': true,
			'pauseOnPagerHover': true,
			'timeout': 0,
			'cleartype': true,
			'cleartypeNoBg': true,
			'pager': gal.find('.image-gallery-carousel ul'),
			'pagerAnchorBuilder': function(idx, slide){
	        	return gal.find('.image-gallery-carousel li:eq(' + idx + ') a');
	    	},
	    	'before': function(curr, next, opts, fwd){
				var nextHeight = $(next).outerHeight();
				$(curr).parent().animate({
					'height': nextHeight
				},200);
			}
		});
		
		gal.find('.image-gallery-carousel ul').wrap('<div class="mask"></div>');
		gal.find('.image-gallery-carousel').prepend('<ul class="image-gallery-nav"><li><a href="#" class="prev">'+lang_Previous+'</a></li><li><a href="#" class="next">'+lang_Next+'</a></li></ul>');
				
		var galCarouselWidth = 0;
		gal.find('.image-gallery-carousel .mask li').each(function(){
			galCarouselWidth = galCarouselWidth + $(this).outerWidth();
		});
		$('.image-gallery-carousel .mask ul').width(galCarouselWidth+100);
	
		var galChildCount = gal.find('.image-gallery-carousel .mask li').size(),
		increment = gal.find('.image-gallery-carousel .mask li:first-child').outerWidth(),
		count = 0;
		
		gal.find('.image-gallery-nav .next').click(function(e){
			e.preventDefault();
			if( count < parseInt(galChildCount -7)){
				$('.image-gallery-carousel .mask ul').animate({
					'left': '-='+ parseInt(increment)
				},200);
				count++
			}
			// remove dotted border in IE
			if(ltIE8){
				$(this).attr('hideFocus','true');
			}
		});
	
		gal.find('.image-gallery-nav .prev').click(function(e){
			e.preventDefault();
			if( count > 0 ){
				$('.image-gallery-carousel .mask ul').animate({
					'left': '+='+ parseInt(increment)
				},200);
				count--
			}
			// remove dotted border in IE
			if(ltIE8){
				$(this).attr('hideFocus','true');
			}
		});
	});
}

// Overlay Popups (Fancybox)
function _overlayLinks(){

    $('.fb').each(function(){
        var fbObject = $(this);
        var fbHeight = 550;
        var fbWidth = 650;
        // does the link have dynamic height/width set
        if (fbObject.attr('data-fbs')) {
            var fbSize = fbObject.attr('data-fbs').split('x');
            if (fbSize.length > 0) {
                fbWidth = parseInt(fbSize[0]);
                fbHeight = parseInt(fbSize[1]);
            }
        }
        //is it an ajax link?
        if (fbObject.hasClass('ajax')) {
            //ajax fancybox
            fbObject.fancybox({
                'ajax': {
                    //filter ajax content
                    dataType: 'html',
                    dataFilter: function(data){
                    	// is the request page using our 'overlay' template?
                        if($(data).find('#overlay-content')){
                        	data = $(data).find('#overlay').html();
                        }
                        return data;
                    },
                    cache: false
                },
                'showNavArrows': false,
                'overlayColor': '#003976',
	            'overlayOpacity': 0.8,
                'padding': 5,
                'centerOnScroll': true,
                'autoDimensions': true,
                'autoScale': false,
                'titleShow': false,
                'onComplete': function(){
					$('.overlay-contents .block').equalHeights(0,0,5);
					if($('#fancybox-content').find('video,.youtube-video').length > 0){
						_videoPlayers(true);
					}
					if($('#fancybox-content').find('.image-gallery').length > 0){
						_imageGalleries();
					}
					if($('#fancybox-content').find('input[type=date],input.date').length > 0){
						_datePickerInputs();
                	}
                }	
            });
        }else{
	 		fbObject.fancybox({
	            'overlayColor': '#003976',
	            'overlayOpacity': 0.8,
	            'height': fbHeight,
	            'width': fbWidth,
	            'padding': 5,
	            'centerOnScroll': true,
	            'autoDimensions': false,
	            'autoScale': false,
	            'titleShow': false
	        });
        }
    });
    
    // Onload fancybox (only open once)
    var onloadLink = $('#onload-fancybox');
   	onloadLink.hide();
    $(window).load(function(){
    	var onloadLinkID = onloadLink.attr('data-fbid');
    	
    	// use local storage
    	if (Modernizr.localstorage) {
	    	if(!localStorage.getItem('onloadLinkID_'+onloadLinkID)){
	    		onloadLink.find('a').click();
	    		if(onloadLinkID){
	    			localStorage.setItem('onloadLinkID_'+onloadLinkID, true);
	    		}
	    	}
	    //... or fallback to cookie
	   	}else{
	   		if(!$.cookie('onloadLinkID_'+onloadLinkID)) {
	   			onloadLink.find('a').click();
	   			if(onloadLinkID){
	    			$.cookie('onloadLinkID_'+onloadLinkID, true);
	    		}
	   		}
	   	}
	   	
    });
}

// Webkit background 1px center fix
function _reCenterViewport(){

    var html = $('html');
    html.css('margin-left', '0');
    if ($(document).width()%2 > 0) {
    	html.css('margin-left', '-1px');
    }

}


// Replace 'date' type inputs with jQuery datePicker
function _datePickerInputs(){

 	$('input[type=date],input.date,input.dateISO').each(function(i, item){
 		var dateInput = $(item),
 		attrs = this.attributes,
 		itemAttributes = '';

		for(var a=0; a<attrs.length; a++) {
			var attrName = attrs[a].nodeName;
			var attrVal = attrs[a].nodeValue;
			if(attrName != 'type'){
				itemAttributes = itemAttributes + attrName + '="' +attrVal+ '" ';
			}
		}

		var months = 3,
		maxMonths = months,
		minDateMonth = 0,
		maxDateMonth = 0,
		fixedMultiMonth = false;

		// are min and max attributes set?
 		if(dateInput.attr('max')){
 			if(dateInput.attr('min')){
 				var minDate = new Date(dateInput.attr('min').replace(/-/gi,'/'));
 			}else{
 				var minDate = new Date();
 			}
 			var maxDate = new Date(dateInput.attr('max').replace(/-/gi,'/'));
 			// how many calendars to show?
 			showMonths(minDate, maxDate);
 		}

 		function showMonths(minDate, maxDate){
			minDateMonth = minDate.getMonth();
	    	maxDateMonth = maxDate.getMonth();

			var diffMonths = Math.abs(minDateMonth - maxDateMonth);
			// are their less month than our maxMonths?
			if(diffMonths < maxMonths){
				months = diffMonths+1;
				fixedMultiMonth = true;
			}
		}

 		// replicate input as 'type=text', add its attributes and remove original input
 		dateInput.after('<span class="date-picker-input"><input type="text" data-type="date-picker-'+i+'" '+itemAttributes+' /></span>').remove();
 		var newInput = $('input[data-type="date-picker-'+i+'"]');

 		// Match date format ISO 8601 (yyyy-mm-dd)
		Date.format = 'yyyy-mm-dd';

		// set up datePicker with inputs settings
 		newInput.removeAttr('disabled').datePickerMultiMonth({
 			clickInput: true,
 			numMonths: months,
			startDate: dateInput.attr('min'),
			endDate: dateInput.attr('max')
 		}).bind('dateSelected',function(event, date){
 			// fixed multi picker, set to the minDate
 			if(fixedMultiMonth){
 				newInput.dpSetDisplayedMonth(minDateMonth);
 			// is the selected date inside the last month of the maxDate?
 			}else if(maxDateMonth === date.getMonth()){
 				newInput.dpSetDisplayedMonth(Math.round(maxDateMonth - (months-1)));
 			}
 		}).bind('dpDisplayed',function(e){
	 		// position picker to the right if its closer
	 		var inputOffset = Math.round(newInput.offset().left);
	 		var halfWindow = Math.round($(window).width() / 2);
	 		if(inputOffset > halfWindow){
	 			newInput.dpSetPosition($.dpConst.POS_TOP, $.dpConst.POS_RIGHT_MULTI);
	 		}
 		});

 	});

}

// Multiple 'toggle' functions
function _toggleContent(){

	// Toggle 'cruise finder' search options
	$('.promo .more-options-handle').live('click',function(e){
		e.preventDefault();
		var handle = $(this),
		more = $(this).attr('data-more'),
		less = $(this).attr('data-less');
		if(ltIE8){
			handle.attr('hideFocus','true');
		}
		handle.parent().find('.more-options').slideToggle(function (){
			if($(this).is(':visible')){
				handle.text(less).addClass('less');
			}else{
				handle.text(more).removeClass('less');
			}
        });
	});

	// Toggle 'SEO' content
	$('.extra-content .contents').before('<a href="#" class="extra-content-handle"><span>'+lang_AboutRoyalCaribbean+'</span></a>').wrap('<div class="toggle-contents"></div>');
	$('.extra-content-handle').click(function(e){
		e.preventDefault();
		var handle = $(this);
		handle.toggleClass('less');
		if(ltIE8){
			handle.attr('hideFocus','true');
		}
		$('.extra-content .toggle-contents').slideToggle();
	});

}

// Split sub nav into columns
function _splitSubNav(){
	
	$('.sub-nav').each(function(i,item){
		var currSubNav = $(item);
		if(currSubNav.find('.sub-nav-col').length > 3){
			currSubNav.addClass('wide');
		}
		currSubNav.find('.sub-nav-col').equalHeights(0,0,5);
	});
	


}

// Split link list into columns
function _splitLinkList(){

	$('.links-list ul, .links-list ol, .highlighted-links.split ul').listColumns({
		columns: 2,
		columnClass: 'links-list-col'
	});
	$('.links-list ul, .links-list ol').equalHeights(0,0,5);
	$('.links-list').each(function(i,item){
		$(item).find('.links-list-col:first').addClass('first');
	});

}

// Google Map and Port Markers
function _googleMap(){

	$('.google-canvas').each(function(i,item){

		var canvas = $(item);
		// Give map an ID
		canvas.attr('id', 'map'+i);

		var places = canvas.find('li'),
		geocoder = new google.maps.Geocoder();

		/* Map */
		var lat = 0, lng = 0, zoom = 5, useDefaultCenter = true, useDefaultZoom = true;
		if(canvas.attr('data-lng-lat') != undefined && canvas.attr('data-lng-lat') != ""){
			lat = canvas.attr('data-lng-lat').split(",")[1];
			lng = canvas.attr('data-lng-lat').split(",")[0];
			useDefaultCenter = false;
		}
		if(canvas.attr('data-zoom') != undefined && canvas.attr('data-zoom') != ""){
			zoom = canvas.attr('data-zoom');
			useDefaultZoom = false;
		}
		var latlngbounds = new google.maps.LatLngBounds();
		
		var latlng = new google.maps.LatLng(lat,lng),
		mapOptions = {
		    zoom: parseInt(zoom),
		    center: latlng,
	        mapTypeId: google.maps.MapTypeId.HYBRID,
	        scrollwheel: false
		},
		googleMap = new google.maps.Map(document.getElementById( canvas.attr('id') ), mapOptions);

		/* Markers */
		var image = new google.maps.MarkerImage(
			mapIconImage,
			new google.maps.Size(38,60),
			new google.maps.Point(0,0),
			new google.maps.Point(19,60)
		),
		shadow = new google.maps.MarkerImage(
	  		mapIconShadow,
	  		new google.maps.Size(72,60),
	  		new google.maps.Point(0,0),
	  		new google.maps.Point(19,60)
		),
		shape = {
			coord:[22,0,26,1,28,2,30,3,31,4,32,5,33,6,34,7,35,8,35,9,36,10,36,11,36,12,37,13,37,14,37,15,37,16,37,17,37,18,37,19,37,20,37,21,37,22,37,23,37,24,37,25,36,26,36,27,36,28,35,29,35,30,34,31,33,32,32,33,32,34,30,35,29,36,29,37,28,38,28,39,27,40,27,41,26,42,26,43,25,44,25,45,25,46,24,47,24,48,24,49,24,50,23,51,23,52,23,53,23,54,23,55,23,56,23,57,22,58,20,59,18,59,16,58,15,57,15,56,14,55,14,54,14,53,14,52,14,51,13,50,13,49,13,48,13,47,12,46,12,45,12,44,11,43,11,42,11,41,10,40,10,39,9,38,8,37,7,36,6,35,5,34,4,33,3,32,3,31,2,30,2,29,1,28,1,27,0,26,0,25,0,24,0,23,0,22,0,21,0,20,0,19,0,18,0,17,0,16,0,15,0,14,0,13,0,12,1,11,1,10,2,9,2,8,3,7,3,6,4,5,5,4,7,3,8,2,10,1,15,0,22,0],
			type: 'poly'
		},
		infowindow = new google.maps.InfoWindow({
        	content: "",
        	maxWidth: 300
    	});
		function setMarker(placeLatLng, placeTitle, placeInfo){
		   	var marker = new google.maps.Marker({
		        position: placeLatLng,
		        map: googleMap,
		        icon: image,
		        shadow: shadow,
		        shape: shape,
		        title: placeTitle
			});
			// Info window content and click
			if(placeInfo){
				google.maps.event.addListener(marker, 'click', function() {
					infowindow.setContent(placeInfo);
                	infowindow.open(googleMap, this);
    			});
			}
		}
		// Each place in UL list
	    places.each(function(i) {
			var place = $(this),
			placeTitle = place.find('.place-title').text(),
			placeInfo = place.html(),
			placeLat,
			placeLng;
			
			if(place.attr('data-lng-lat') != undefined && place.attr('data-lng-lat') != ""){
				placeLat = place.attr('data-lng-lat').split(",")[1];
				placeLng = place.attr('data-lng-lat').split(",")[0];
			}
			
			// Does LI have lng and lat?
			if(placeLat && placeLng){
				var placeLatLng = new google.maps.LatLng(placeLat,placeLng);
				setMarker(placeLatLng, placeTitle, placeInfo);
				latlngbounds.extend( placeLatLng );
			// Otherwise geocode title
			}else{
				geocoder.geocode({'address':placeTitle}, function(results, status){
					if (status == google.maps.GeocoderStatus.OK){
						var placeLatLng = results[0].geometry.location;
						setMarker(placeLatLng, placeTitle, placeInfo);
						latlngbounds.extend( placeLatLng );
						setBounds(googleMap, latlngbounds, useDefaultCenter, useDefaultZoom);
        			}
        		});
        	}
		});
		setBounds(googleMap, latlngbounds, useDefaultCenter, useDefaultZoom);
		
		function setBounds(map, bounds, setCenter, setZoom){
			if(setCenter){
				map.setCenter( bounds.getCenter( ) );
			}
			if(setZoom && (places.length > 1)){
				map.fitBounds(bounds);
			}
		}

	});
}

function _formValidation(){
	
	if($('#aspnetForm').length > 0){
	
		$.validator.addMethod('ValidDate', function (value, element) {
	        var day = NaN;
	        var month = NaN;
	        var year = NaN;
	
	        if ($(element).hasClass('fullday')) {
	            day = value;
	            month = parseInt($(element).parent().find('.fullmonth').val());
	            year = parseInt($(element).parent().find('.fullyear').val());
	        } else if ($(element).hasClass('fullmonth')) {
	            day = parseInt($(element).parent().find('.fullday').val());
	            month = value;
	            year = parseInt($(element).parent().find('.fullyear').val());
	        } else if ($(element).hasClass('fullyear')) {
	            day = parseInt($(element).parent().find('.fullday').val());
	            month = parseInt($(element).parent().find('.fullmonth').val());
	            year = value;
	        }
	
	        var valid = false;
	        if (!isNaN(day) && !isNaN(month) && !isNaN(year)) {
	            var d = new Date(year, month - 1, day);
	            if (Object.prototype.toString.call(d) === '[object Date]') {
	                if (!isNaN(d.getTime()) && d.getDate() == day && d.getMonth() == (month - 1)) {
	                    valid = true;
	                }
	            }
	        }
	
	        return valid;
	    });
		
		jQuery.validator.addMethod("LastName", function(value, element) {
			return this.optional(element) || /^[a-z-']+$/i.test(value);
		}, "Last name can only contain alphanumeric , ' and - charecters");

		jQuery.validator.addMethod("FirstName", function(value, element) {
			return this.optional(element) || /^[a-z-']+$/i.test(value);
		}, "First name can only contain alphanumeric , ' and - charecters");

		jQuery.validator.addMethod("UKPostcode", function(value, element) {	
			return this.optional(element) || /[A-Z]{1,2}[0-9R][0-9A-Z]?\s*[0-9][ABD-HJLNP-UW-Z]{2}/i.test(value);
		}, "Must be a valid Postcode");
		
		jQuery.validator.addMethod("emailallowwhitespace", function(value, element) {
			return (this.optional(element) || jQuery.validator.methods.email.call(this, jQuery.trim(value), element));
		}, "Required to be a valid email address.");
		
		$.validator.addMethod('ValidTelephone', function (value, element) {
			
			var valid = false;
			var country = NaN;
			var areaCode = NaN;
			var number = NaN;	
			
			if ($(element).hasClass('telephone-country')) {
				country = value;
	            areaCode = parseInt($(element).parent().find('.telephone-area-code').val());
	            number = parseInt($(element).parent().find('.telephone-number').val());
			}else if ($(element).hasClass('telephone-area-code')) {
				country = parseInt($(element).parent().find('.telephone-country').val());
	            areaCode = value;
	            number = parseInt($(element).parent().find('.telephone-number').val());		
			}else if ($(element).hasClass('telephone-number')) {
				country = parseInt($(element).parent().find('.telephone-country').val());
	            areaCode = parseInt($(element).parent().find('.telephone-area-code').val());
	            number = value;			
			}
			
			if (!isNaN(country) && !isNaN(areaCode) && !isNaN(number)) {
				valid = true;
			}
			
			return valid;
		});
	
		$('#aspnetForm').validate({
			errorElement: 'span',
			errorClass: 'inline-validation',
		    errorPlacement: function(error, element) {
		    	error.appendTo($(element).parents('.form-item'));
		    	if($(element).attr('type') == 'checkbox'){
					error.appendTo($(element).parents('.cb'));
				}else{
					error.appendTo($(element).parents('.form-item'));
				}
		    },
			highlight: function(element) {
				$(element).parents('.form-item').addClass('error');
			},
			unhighlight: function(element) {
				$(element).parents('.form-item').removeClass('error');
			}
		});
		$.each($.validator.messages, function(i) {
			$.validator.messages[i] = "";
		});
	
		$('.form input').keypress(function(e){
			if ((e.which == 13) || (e.keyCode == 13)) {
				e.preventDefault();
				$(this).parents('.form').find('input[type=submit]').click();
			}
		});
		
		var telCountry = $('.telephone-country');
		var telAreaCode = $('.telephone-area-code');
		var telNumber = $('.telephone-number');
		if(telCountry.length > 0){
			telCountry.rules('add', 'ValidTelephone');
		}
		if(telAreaCode.length > 0){
			telAreaCode.rules('add', 'ValidTelephone');
		}
		if(telNumber.length > 0){
			telNumber.rules('add', 'ValidTelephone');
		}
	}

}

function _prizeDraw() {
    // remove blank target
    $('#aspnetForm').attr('target', '');
    // remove validation from side controls
    $('.promos .promo .button input').addClass('cancel');

    var customQuestions = $('.prize-draw fieldset.custom-questions');

    if (customQuestions.length > 0) {
        var hiddenFields = $('.prize-draw fieldset:not(.custom-questions), .prize-draw .form-item.submit')
        hiddenFields.hide();

		customQuestions.find('.form-item input[type="radio"]').click(function() {
            $(this).parents('.form-item').find('.error-message').hide();
		});

        var button = customQuestions.find('input[type="button"]');
        button.parent().show();
        button.click(function (e) {
            e.preventDefault();

            var valid = true;
            customQuestions.find('.form-item').each(function () {
                if ($(this).find('input[type="radio"]:checked').length == 0) {
                    valid = false;
                    $(this).find('.error-message').show();
                }
            });

            if (valid) {
                customQuestions.find('.form-item').removeClass('error');
                customQuestions.hide();
                hiddenFields.show();
            }
        });

        var backbutton = hiddenFields.find('input[type="button"]');
        backbutton.parent().show();
        backbutton.click(function (e) {
            e.preventDefault();

            customQuestions.show();
            hiddenFields.hide();
        });
    }
}

function _infroGridText(){

	$('.info-grid-banner .image-blocks li a').click(function(e){
		e.preventDefault();
		var link = $(this);
		if(!link.hasClass('selected')){
			var contents = link.next('.contents').html();
			var container = link.closest('.info-grid-banner').children('.contents');
			if(contents){
				$('.info-grid-banner .image-blocks li a').removeClass('selected');
				link.addClass('selected');
				container.fadeOut(500,function(){
					container.html(contents).fadeIn();
				});
			}
		}
	});
	$('.info-grid-banner .image-blocks a:first').click();
}

function _rollUpCarousel(){

	var carouselWidth = 0;
	$('.roll-up nav').each(function(e){
		carouselWidth = carouselWidth + $(this).width();
	});
	$('.roll-up-carousel').width(carouselWidth+1000).before('<ul class="roll-up-carousel-nav"><li><a href="#" class="prev">'+lang_Previous+'</a></li><li><a href="#" class="next">'+lang_Next+'</a></li></ul>').wrap('<div class="mask"></div>');

	var childCount = $('.roll-up-carousel li').size(),
	current = 9,
	selectedChild = $('.roll-up-carousel li:eq('+ parseInt(current) +')');
	increment = selectedChild.outerWidth();

	selectedChild.addClass('current');

 	var count = parseInt(current),
 	newLeft = 0;
	$('.roll-up-carousel-nav .next').click(function(e){
		e.preventDefault();
		if( count < parseInt(childCount - 1) ){
			if(selectedChild.is(':last-child')){
				newLeft -= parseInt(increment + 6);
			}else{
				newLeft -= parseInt(increment);
			}
			$('.roll-up-carousel').animate({
				'left': newLeft
			},200);

			count++

			$('.roll-up-carousel li').removeClass('current');
			selectedChild = $('.roll-up-carousel li').eq(count);
			selectedChild.addClass('current');
		}
		// remove dotted border in IE
		if(ltIE8){
			$(this).attr('hideFocus','true');
		}
	});

	$('.roll-up-carousel-nav .prev').click(function(e){
		e.preventDefault();
		if( count > current ){
			if(selectedChild.is(':first-child')){
				newLeft += parseInt(increment + 6);
			}else{
				newLeft += parseInt(increment);
			}
			$('.roll-up-carousel').animate({
				'left': newLeft
			},200);

			count--

			$('.roll-up-carousel li').removeClass('current');
			selectedChild = $('.roll-up-carousel li').eq(count);
			selectedChild.addClass('current');
		}
		// remove dotted border in IE
		if(ltIE8){
			$(this).attr('hideFocus','true');
		}
	});

	var speed = 400;

	$('.roll-up .contents').before('<a href="#" class="roll-up-handle"><span>'+lang_SeeOtherShips+'</span></a>').wrap('<div class="toggle-contents"></div>');
	$('.roll-up-handle').click(function(e){
		e.preventDefault();
		var handle = $(this);
		if(handle.hasClass('less')){
			$('.roll-up .toggle-contents').slideUp(speed);
			handle.removeClass('less');
		}else{
			$('.roll-up .toggle-contents').slideDown(speed);
			handle.addClass('less');
		}
		// remove dotted border in IE
		if(ltIE8){
			handle.attr('hideFocus','true');
		}
	});

}

function _experiencesFeature(){

	var experienceContainer = $('.experience-container');

	if(experienceContainer.length > 0){

		experienceContainer.wrapInner('<div class="mover"></div>');
		
		if(experienceContainer.hasClass('animate')){

			var posTop = $('#experience-start').position().top,
			posLeft = $('#experience-start').position().left,
			backPosTop = $('.experience-container .mover').position().top,
			backPosLeft = $('.experience-container .mover').position().left;
	
			$('.experience-container .hero-item').each(function(){
				if($(this).attr('id') != 'experience-start'){
					$(this).find('.contents').before('<span class="button alt experience-back-link"><a href="#">Back</a></span>');
				}
			});
	
			$('#experience-start a').click(function(e){
				e.preventDefault();
	
				var link = $(this),
				scrollTo = $(link.attr('href')),
				newPosLeft = Math.round( posLeft - scrollTo.position().left),
				newPosTop = Math.round(  posTop - scrollTo.position().top);
	
				$('.experience-container .mover').animate({
					'left': newPosLeft,
					'top': newPosTop
				}, 1200, 'easeOutExpo');
				
				link.parents('li').addClass('selected');
	
			});
	
			$('.experience-back-link a').click(function(e){
				e.preventDefault();
				$('.experience-container .mover').animate({
					'left': backPosLeft,
					'top': backPosTop
				}, 1200, 'easeOutExpo',function(){
					$('#experience-start li').removeClass('selected')
				});
				_stopAllVideos();
			});
		
		}

	}

}

function _faqs(){
	$('.faq-content dt a').click(function(e){
		e.preventDefault();
		$(this).parent('dt').next('dd').slideToggle();
	});
}

function _cycleQuotes(){
	$('#experience-quote .quotes').cycle();
}

function _heroHeight(){

	if( $('.hero').length > 0 && $('.hero-item').css('height') != 210 && $('#hero-carousel').length == 0 ){
		var heroImg = new Image();
		heroImg.src = $('.hero').css('background-image').replace(/"/g,"").replace(/url\(|\)$/ig, "");
		$(heroImg).load(function(){
			$('.hero').height(heroImg.height);
		});
		$(window).load(function(){
			$('.hero').height(heroImg.height);
		});
	}

}

function _fixCallImage(){
	var callImage = $('header[role="banner"] .phone-number');
	var stopScroll = 60;
	var minWinHight = 200;
	$(window).scroll(function(){
		var win = $(this);
		if((win.scrollTop() > stopScroll) && (win.height() > minWinHight)){
			callImage.addClass('fixed');
		}else{
			callImage.removeClass('fixed');
		}
	}).resize(function(){
		var win = $(this);
	    if(win.height() < minWinHight){
	    	callImage.removeClass('fixed');
	    }else if((win.scrollTop() > stopScroll) && (win.height() > minWinHight)){
			callImage.addClass('fixed');
	    }
	});
}

/* Init Functions
------------------------------------------------------------*/
$(function(){

	_equalHeights();
	_placeholderInputs();
	_videoPlayers();
	_overlayLinks();
	_datePickerInputs();
	_toggleContent();
	_heroCarousel();
	_splitSubNav();
	_splitLinkList();
	_infroGridText();
	_rollUpCarousel();
	_imageGalleries();
	_experiencesFeature();
	_faqs();
	_cycleQuotes();
	// disabled PW 2011-09-21
	//_fixCallImage();
	_heroHeight();

	if(window.google){
		_googleMap();
	}
	
	if($.browser.webkit){
		_reCenterViewport();
		$(window).resize(function(){
			_reCenterViewport();
		});
	}

	if($('.form')){
        _prizeDraw();
		_formValidation();
	}
	
	// Remove borders (TODO: try do this server side)
	$('.main-content .content-block.one:first').addClass('nb');
	var cb = $('#content-blocks .content-block').eq(0);
	if(cb.hasClass('one')){
		cb.addClass('nb');
	}else if(cb.hasClass('two')){
		cb.addClass('nb');
		cb.next('.two').addClass('nb');
	}
    
	if( $('.hero').length < 1){
		$('#main').addClass('no-hero');
	}
	
	if( $('.breadcrumb li').length < 1){
		$('.breadcrumb').remove();
	}

    if(flashInstalled){
        $('html').addClass('flash');
    }else{
        $('html').addClass('no-flash');
    }
	
	// IE Text-Shadow
	if(!Modernizr.textShadow && $.browser.msie){
		$('.hero-item h1, .hero-item p').each(function(){
			var text = $(this).text();
			if(!$(this).parents('.experience-container').length > 1){
				$(this).append('<span class="ie-shadow">'+text+'</span>');
			}
 		});
	}
});

