/* Copyright (c) 2008, Sail Caribbean Voyages. All rights reserved. Developed by markhealey.org */

common_class = function() {
	this.SiteURL = (s) ? s : "";
	this.assetURL = (a) ? a : "";
	this.page = (p) ? p : "";
	this.isIE6 = ($.browser.msie && $.browser.version == 6.0) ? 1 : 0;
	//global ajax
	$.ajaxSetup({
		cache: false,
		type: "GET",
		dataType: "html"
	});
}

/* CSS Browser Selector v0.2.7 Rafael Lima (http://rafael.adm.br) http://rafael.adm.br/css_browser_selector */ 
common_class.prototype.setUserAgentCSS = function() { var c_b_s = function() {var ua=navigator.userAgent.toLowerCase(),is=function(t){return ua.indexOf(t) != -1;},h=document.getElementsByTagName('body')[0],b=(!(/opera|webtv/i.test(ua))&&/msie (\d)/.test(ua))?('ie ie'+RegExp.$1):is('firefox/2')?'ff2':is('firefox/3')?'ff3':is('gecko/')?'gecko':is('opera/9')?'opera opera9':/opera (\d)/.test(ua)?'opera opera'+RegExp.$1:is('konqueror')?'konqueror':is('applewebkit/')?'webkit safari':is('mozilla/')?'gecko':'',os=(is('x11')||is('linux'))?' linux':is('mac')?' mac':is('win')?' win':'';var c=b+os+' js'; h.className += h.className?' '+c:c;}(); }

common_class.prototype.showLoading = function(container,loader) {
	var css = "loadingIndicator";
	if (loader=="wht") {
		var src = common.assetURL+"/i/loadingWht.gif";
	} else {
		var src = common.assetURL+"/i/loading.gif";
		if (this.page=="home") { src = common.assetURL+"/i/loading_home.gif"; css = "loadingIndicator home"; }
		if (this.page=="programs") { src = common.assetURL+"/i/loading-leftnav.gif"; }
	}
	var height = $("#"+container).height();
	var width = $("#"+container).width();
	var elPos = $("#"+container).offset();
	var topPosOfImg = (parseInt(height / 2 - 15)); //center loading gif
	var leftPos = (parseInt(width / 2 - 15)); //centered
	var indicator = $('<div></div>').attr({id:'loading_' +container, 'className':css}).css({top:elPos.top+'px',left:elPos.left+'px',height:height+'px',width:width+'px'}).appendTo("body");	
	var graphic = $('<img src="'+src+'" />').attr({id:'loadingIcon'}).css({position:"absolute",top:topPosOfImg+'px',left:leftPos+'px'}).appendTo(indicator);
}

//larger white box with loading icon
common_class.prototype.showLoadingBox = function(container,text) {
	var height = $("#"+container).height();
	var boxHeight = 175;
	var width = $("#"+container).width();
	var boxWidth = 446;
	var elPos = $("#"+container).offset();
	var topPos = elPos.top + (parseInt(height / 2 - boxHeight / 2)); //center loading gif
	var leftPos = elPos.left + (parseInt(width / 2 - boxWidth / 2)); //centered

	$('<div>&nbsp;</div>').attr({id:'loading_' +container, 'className':'loadingIndicator'}).css({top:elPos.top+'px',left:elPos.left+'px',height:height+'px',width:width+'px'}).appendTo("body");	
	
	var loadingFrame = $('<div></div>').attr({id:'loadingBox_' +container, 'className':'loadingBoxFrame'}).css({top:topPos+'px',left:leftPos+'px',height:boxHeight+'px',width:boxWidth+'px'}).appendTo("body");	
	var loadingBox = $('<div></div>').attr({id:'loadingBox', 'className':'loadingBox'}).css({marginTop:'2px',marginLeft:'2px',height:(boxHeight-5)+'px',width:(boxWidth-4)+'px'}).appendTo(loadingFrame);
	var loadingBoxText = $('<div>'+text+'<span class="pl10"><img align="absmiddle" src="../common/img/ajax-loader_lg.gif" /></span></div>').attr({id:'loadingBoxText', 'className':'loadingBoxText'}).appendTo(loadingBox);

	var topTextPos = parseInt(boxHeight / 2 - 16);
	var leftTextPos = parseInt(boxWidth / 2 - ($(loadingBoxText).width() / 2));

	$(loadingBoxText).css({top:topTextPos+'px',left:(leftTextPos - 16) +'px'});
}

common_class.prototype.hideLoading = function(container,delay) {
	if (delay) {
		window.setTimeout("common.hideLoadingTime('"+container+"')",delay);
	} else {
		$("#loading_"+container).remove();
	}		
}

common_class.prototype.hideLoadingTime = function(container,delay) {
	$("#loading_"+container).remove();
	$("#loadingBox_"+container).remove();	
}

common_class.prototype.toggleTabs = function(el) {
	var tab = $(el).parent().get(0);
	if (tab.id == "ourPrograms") {
		$("#pane_programs").show();
		$("#pane_news").hide();
		$("#ourNews").removeClass("on");
		$("#ourPrograms").addClass("on");
	} else {
		$("#pane_programs").hide();
		$("#ourPrograms").removeClass("on");
		$("#ourNews").addClass("on");
		$("#pane_news").show();
		if(!$("#latestNews:has(ul)")) {
			common.showLoading('pane_news');
			$.ajax({
				url: "default-fetchnews.asp",
				data: "",
				success: function(results){
					$("#latestNews").html(results);
					common.hideLoading('pane_news');	
				}
			});
		}
	}
}

common_class.prototype.preloadLatestNews = function() {
	$.ajax({
		url: "default-fetchnews.asp",
		data: "",
		success: function(results){
			$("#latestNews").html(results);
		}
	});
}

common_class.prototype.toggleFAQ = function(el) {
	if (this.open == el) { return; }
	var answers = $("div.faqanswer").each(function() {
		$(this).hide();
	});
	var questions = $("ul.faq a").each(function() {
		$(this).removeClass("reading");
	});
	$(el).siblings("div.faqanswer").slideDown('fast').andSelf().addClass("reading");
	this.open = el;
	//iterate count
	var viewCount = $(el).attr("viewCount");
	var faqID = $(el).attr("faqId");
	$.ajax({
		cache: true,
		url: "/common/countFaq.asp",
		data: { viewCount:viewCount, faqID:faqID },
		success: function(html){ }
	});
}

function loadVideoPlayer() {
	$(document).ready(function() {
		// flashvars, params, attributes
		swfobject.embedSWF(common.assetURL + "/media/video/standalone.swf", "video", "622", "416", "9.0.0", common.assetURL+"/i/swf/expressInstall.swf","",{wmode:"transparent",bgcolor:"#ffffff",menu:false});
	});
}

//function check_useraccount(){var _25=$F("userEmail");var _26="account_exists";try{if(_25.value!=""){$(_26).style.display="";var url="check-account.asp";var _28="username="+_25.value;var _29=new Ajax.Updater(_26,url,{method:"get",parameters:_28,evalScripts:true});}if(_25.value==""){$(_26).style.display="none";}}catch(e){alert(global_ajax_error);}}

common_class.prototype.check_useraccount = function() {
	var u = $("#userEmail").val();
	var $msg = $("#account_exists");
	if (u && u.length > 0){ 
		$.ajax({
			cache: true,
			url: "check-account.asp",
			data: {username:u},
			success: function(html){
				if (html) {
					$msg.show().css({"margin":"4px 0 4px 0"}).html(html);	
				} else {
					$msg.hide();
				}
			}
		});
	}
}

common_class.prototype.getFileSize = function(fileIn) {
	$.ajax({
		cache: true,
		url: "/common/filesize.asp",
		data: {fileIn:fileIn},
		success: function(html){
			$("span#programPageFileSize").html(html);	
		}
	});
}

common_class.prototype.loadRailPhotos = function(args) {
	common.showLoading("photoRail");
	$.ajax({
		cache: true,
		url: "/media/photoRailBuffer.asp",
		data: {railCat:args.cat, railSection:args.section, railMapping:args.map},
		success: function(html){
			$("#photoRail").html(html);
			common.hideLoading('photoRail');	
		}
	});
}

common_class.prototype.loadProgramDatesAndCosts = function(p) {
	common.showLoading("datesandcosts","wht");
	$.ajax({
		cache: true,
		url: "/programs/datesAndCostsBuffer.asp",
		data: {programID:p},
		success: function(html){
			$("#datesandcosts").html(html);
			common.hideLoading('datesandcosts');	
		}
	});
}

common_class.prototype.goToTripUpdateList = function(el) {
	var program = Number($(el).val());
	var tuURL = $("#tuURL").val();
	var url = tuURL + program + "/";
	window.location.href = url;
}

common_class.prototype.scubaTraining = function(el,p) {
	common.showLoading("trainingContent","wht");
	$.ajax({
		cache: true,
		type: "GET",
		url: "/common/buffer_content.asp",
		data: {p:p},
		success: function(html){
			$("#trainingContent").html(html);
			common.hideLoading('trainingContent');	
		}
	});
}

//tuRemember
//

common_class.prototype._checkIfUserCanChangePrograms = function(el) {
	var ck = $("#tuRemember");
	var year = $(el).attr("tuyear");
	if ($(ck).is(":checked")) { 
		alert('You cannot select a different program because you have checked \'Save for me\' below.\n\nTo choose a different program, uncheck \'Save for me\' first.');
		return false;
	} else {
		window.location.href = "/community/tripupdates/" +year+ "/";
	}
}

common_class.prototype.rememberTripUpdateSelection = function(el) {
	var cookieVal = $(el).val();
		cookieVal = cookieVal.replace("-","/");
	var IsAlreadySet = readCookie('rememberTripUpdate');
	
	//if Cookie value = sailing id, user wants to erase cookie
	if(IsAlreadySet == cookieVal) {
		//delete cookie
		eraseCookie( 'rememberTripUpdate' );
	
	} else if (IsAlreadySet != null) {
		//if cookie is set, but <> sailing id, then erase cookie and reset it
		//erase any old cookies
		eraseCookie( 'rememberTripUpdate' );
		//set cookie (name,sailing id,#of days til expire)
		createCookie( 'rememberTripUpdate', cookieVal, '90' );
		
	} else {
		//erase the bugger
		//set cookie
		createCookie( 'rememberTripUpdate', cookieVal, '90' );
	}
}

//For program comparison page
common_class.prototype.comparePrograms = function() {
	// never allow less than 2 checkboxes be checked
	var theChecks = $("form#comparison :checkbox");
	
	var tempVals = [];
	var checkCounter = 0;
	
	$(theChecks).each(function(){
		if ($(this).is(":checked")) {
			checkCounter++;
			tempVals.push(Number( $(this).val() ))
		}
	});
	
	if (checkCounter < 2) {
		alert("Please select at least two programs to compare.");
		return (false);
	} else {
		window.location.href = './compare/' + tempVals + "/";
	}
}

common_class.prototype.initComparisonEvents = function(){
	var self = this;
	
	$("a.hoverIcon").bind("mouseover",function(){
		var id = $(this).attr("sailingid");
		self.showHelp(this,{
			title:hover[id].t,
			body:hover[id].b,
			offsetTop:3,
			offsetLeft:0
		});
	});
	
	$("a.hoverIcon").bind("mouseout",function(){
		self.hideHelp(this);
	});
	
	self.rowCount = $("div.optCourseRow").length;
	
	$("a.remove").bind("click",function(){
		if (self.rowCount > 2) {
			$(this).parents("div.optCourseRow").hide('fast');
			self.rowCount--;
		}
	});
	
	$("div.optCourseRow").hover(
		function(){
			if (self.rowCount > 2) {
				$(this).find("div.removalLink").css("visibility","visible");
			}
		},
		function(){
			if (self.rowCount > 2) {
				$(this).find("div.removalLink").css("visibility","hidden");
			}
		}
	);
	
}

common_class.prototype.showHelp = function(el, obj) {
       
    $('<div id="bubble"><div class="body"><div class="title">'+unescape(obj.title)+'</div><div>'+unescape(obj.body)+'</div></div><div class="footer">&nbsp;</div></div>').appendTo("body");  
    
    var height = $("#bubble").height();

    var t = parseInt($(el).offset().top - height - parseInt(obj.offsetTop)) + 'px';
    var l = parseInt($(el).offset().left + parseInt(obj.offsetLeft)) + 'px';
    
    if (obj && obj.overrideWidth > 0) {
    	$("#bubble").css({top:t,left:l,width:obj.overrideWidth});
    	$("#bubble .footer").css({width:parseInt(obj.overrideWidth)});
    } else {
    	$("#bubble").css({top:t,left:l});
    }
}

common_class.prototype.hideHelp = function(el) {
    $("#bubble").remove();
}

common_class.prototype._helpJQueryIDs = function(elementID) {
	//help funky characters in jQuery ----> http://docs.jquery.com/Frequently_Asked_Questions#How_do_I_select_an_element_that_has_weird_characters_in_its_ID.3F
	if(elementID) {
		elementID = elementID.replace("&","\\&");
		elementID = elementID.replace("/","\\/");
	}
	return elementID;
}

legacy_class = function() { }

legacy_class.prototype.jumpFormSubmit = function(form) {
	form.submit();
}

legacy_class.prototype.goAway = function(url) {
	var goAway = window.open(url, "_out", "width=600,height=500,top=10,left=10,menubar=yes,toolbar=yes,location=yes,scrollbars=yes,resizable=yes,status=yes");
}

//we're ready...
$(document).ready(function() {
    common = new common_class();
    //common.setUserAgentCSS();
    legacy = new legacy_class();
    
    /* EVENTS **/
  	if (common.page=="home") { 
  		//swfobject.embedSWF(common.assetURL + "/i/swf/home.swf", "homeSlideShow", "570", "287", "9.0.0", common.assetURL+"/i/swf/expressInstall.swf","",{wmode:"transparent",menu:false});
  		
  		$("#ourPrograms").find("a").bind("click",function(){
  			common.toggleTabs(this);
  		});
  		$("#ourNews").find("a").bind("click",function(){
  			common.toggleTabs(this);
  		});
  		$(".moreAbout").find("a").bind("click",function(){
  			$("#moreAboutSailCaribbean").slideToggle('fast');
  		});
  		
  		common.preloadLatestNews();
  		
  		newsTab = new Image(109,25); 
		newsTab.src="/i/homeNavBgNewsOn.png"; 
  		
  		//main nav needs a kick in IE6
  		if (common.isIE6) {
  			$("div#mainmenu ul li").hover(
				function () { $(this).addClass("hover"); }, 
				function () { $(this).removeClass("hover");	}
			);
  		}
  	}
  	/*inside pages */
  	if (common.page=="contact") {
	  	$("ul.faq a").bind("click",function(){
			common.toggleFAQ(this);
		});
	}
	
	if (common.page=="community") {
	  	$("select#tuSelector").bind("change",function(){
			common.goToTripUpdateList(this);
		});
		$("select#sailing").bind("change",function(){
			common.goToTripUpdateList(this);
		});
		$("a#tuPickDifferent").bind("click",function(){
			common._checkIfUserCanChangePrograms(this);
		});
		$("input#tuRemember").bind("click",function(){
			common.rememberTripUpdateSelection(this);
		});

	}
	
	//remove title attributes from showing on main menu
	$("#mainmenu").find("a").attr("title","");
  	
});

function utilityShareThis() {
	//SHARETHIS.addEntry({ title:'Sail Caribbean' });
	$("span.stbuttontext").html("Share this page");
	//$(".stico_default").css("background":"none");
}

//helper
function log(m) {
	if (console && console.log) {
		console.log(m);
	}
}

/*legacy wrappers */
function eEmail() {
	//hide emails
	/* http://www.dynamicdrive.com/emailriddler/ */
	var emailarray7773= new Array(105,110,102,111,64,115,97,105,108,99,97,114,105,98,98,101,97,110,46,99,111,109)
	var postemail7773=''
	for (i=0;i<emailarray7773.length;i++)
	postemail7773+=String.fromCharCode(emailarray7773[i])
	document.write('<a class="email" href="mailto:'+postemail7773+'">'+postemail7773+'</a>')	
}

function goAway(url) { legacy.goAway(url); }

function jump(f) { legacy.jumpFormSubmit(f); }

//Popup windows
function watchVideo(thepage,thewidth,theheight){
	var myWin = window.open(thepage, "video", "width="+thewidth+",height="+theheight+",scrollbars=no")
}

function popPrintConf(RndAppId){
	var thepage = "confirmation_print.asp?RndAppId="+RndAppId
	var myWin = window.open(thepage, "app_print", "width=525,height=550,scrollbars=yes")
}

function popMiscPage(mp){
	var thepage = "/miscpage_pop.asp?mp="+mp
	var myWin = window.open(thepage, "mp_pop", "width=475,height=500,scrollbars=yes")
}

function openWin(thepage){
	//var thepage = page
	var myWin = window.open(thepage, "openWin", "width=455,height=500,top=10,left=10,toolbar=no,scrollbars=yes,resizable=yes,status=yes")
}

function openPhoto(thepage){
	var myWin = window.open(thepage, "openPhoto", "width=500,height=500,scrollbars=yes,resizable=yes")
}

function goExternal(thepage){
	var externalSite = window.open(thepage, "externalSite", "width=600,height=500,top=10,left=10")
}

//Confirms users choice
function confirmSubmit(msg) {
	var agree=confirm(msg);
	if (agree)
		return true ;
	else
		return false ;
}	

//generic confirm
function c(msg,url) {
	if (confirm(msg)) location=url
}

//For cookies
function createCookie(name,value,days) {
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}




/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 9/11/2008
 * @author Ariel Flesler
 * @version 1.4
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(h){var m=h.scrollTo=function(b,c,g){h(window).scrollTo(b,c,g)};m.defaults={axis:'y',duration:1};m.window=function(b){return h(window).scrollable()};h.fn.scrollable=function(){return this.map(function(){var b=this.parentWindow||this.defaultView,c=this.nodeName=='#document'?b.frameElement||b:this,g=c.contentDocument||(c.contentWindow||c).document,i=c.setInterval;return c.nodeName=='IFRAME'||i&&h.browser.safari?g.body:i?g.documentElement:this})};h.fn.scrollTo=function(r,j,a){if(typeof j=='object'){a=j;j=0}if(typeof a=='function')a={onAfter:a};a=h.extend({},m.defaults,a);j=j||a.speed||a.duration;a.queue=a.queue&&a.axis.length>1;if(a.queue)j/=2;a.offset=n(a.offset);a.over=n(a.over);return this.scrollable().each(function(){var k=this,o=h(k),d=r,l,e={},p=o.is('html,body');switch(typeof d){case'number':case'string':if(/^([+-]=)?\d+(px)?$/.test(d)){d=n(d);break}d=h(d,this);case'object':if(d.is||d.style)l=(d=h(d)).offset()}h.each(a.axis.split(''),function(b,c){var g=c=='x'?'Left':'Top',i=g.toLowerCase(),f='scroll'+g,s=k[f],t=c=='x'?'Width':'Height',v=t.toLowerCase();if(l){e[f]=l[i]+(p?0:s-o.offset()[i]);if(a.margin){e[f]-=parseInt(d.css('margin'+g))||0;e[f]-=parseInt(d.css('border'+g+'Width'))||0}e[f]+=a.offset[i]||0;if(a.over[i])e[f]+=d[v]()*a.over[i]}else e[f]=d[i];if(/^\d+$/.test(e[f]))e[f]=e[f]<=0?0:Math.min(e[f],u(t));if(!b&&a.queue){if(s!=e[f])q(a.onAfterFirst);delete e[f]}});q(a.onAfter);function q(b){o.animate(e,j,a.easing,b&&function(){b.call(this,r,a)})};function u(b){var c='scroll'+b,g=k.ownerDocument;return p?Math.max(g.documentElement[c],g.body[c]):k[c]}}).end()};function n(b){return typeof b=='object'?b:{top:b,left:b}}})(jQuery);