/*FILE INFO *

Purpose: Creates global header, footer and navigation, Login/Logout functioanlities, Show Special Offers Sign-up screen, Show Inactivity Screen.
-------------------------
1) Create Top Menu items- (depends on quickmenu.js) Method :createTopNav().
2) Create Header- Adds the header to the DOM using jQuery .html() function.
3) Create Footer- Creates localized footer(using 'footer_localized.js' which is generated by CMS).
4) Get Book and WWW URLs (for prepending it to hyperlinks)
5) Hide/Show Sign-in box and load sign-in page in iframe
6) Hide/Show Special Offers lightbox and load the page in iframe
7) Centralizing Lightbox- Function center_special_offers_lightbox()
8) Show/Hide Inactivity Screen (based on session/cookie timeout) -Associated methods: show_inactivity_screen(),inactivity_screen_show_hide(),center_inactivity_lightbox(), prepareInactivity(),keepAlive(),setSessionCookie, clearSession(), resetSessionCookie(), deleteCokie()
9) Login/Logout Functionality. Associated methods: hasLoggedIn(), notYou(), signOut(), printSignInBanner(),printSignOutBanner()
10) Search Submit- doSubmitSearch() 
*/

//Define Console.log for browsers that does not support
if(typeof(console) === 'undefined') {
    var console = {}
    console.log = console.error = console.info = console.debug = console.warn = console.trace = console.dir = console.dirxml = console.group = console.groupEnd = console.time = console.timeEnd = console.assert = console.profile = function() {};
}


/*Get Book and WWW URLs */
var pageProtocol= window.location.protocol;
var host_name= window.location.hostname;
var host_name_split = host_name.split('.');
var sub_domain = host_name_split[0];
var domain =host_name_split[1];
var domain_extn=host_name_split[2];
var shared_path; //global and share folder reference in book and www respectively
var match_sub_domain_string=/dev1|stage7|dev|preprod|stage/i;
var sub_domain_substring= sub_domain.match(match_sub_domain_string);

	if(pageProtocol=="http:"){
		shared_path ="share";
			}
	if(pageProtocol==="https:"){
		shared_path ="global";
			}

	if(sub_domain_substring =="dev"){
		www_sub_domain= "devwww";
		book_sub_domain="devbook";
	}
	else if(sub_domain_substring =="stage7"){
			www_sub_domain= "stage7www";
			book_sub_domain="stage7book";
	}
	else if(sub_domain_substring =="dev1"){
		www_sub_domain= "dev1www";
		book_sub_domain="dev1book";
	}
	else if(sub_domain_substring =="stage"){
		www_sub_domain= "stagewww";
		book_sub_domain="stagebook";
	} else if(sub_domain_substring =="preprod") {		
		www_sub_domain= "preprodwww";
		book_sub_domain="preprodbook";
	} 	
	else{
		www_sub_domain= "www";
		book_sub_domain="book";
		}
		
$bookURL= 'https:' + '//'+ book_sub_domain +'.'+ domain +'.'+domain_extn;
$wwwURL = 'http:' + '//'+ www_sub_domain +'.'+ domain +'.'+domain_extn;

	if( (host_name ==="localhost")){
		$bookURL='http://localhost';
		$wwwURL='http://localhost';
	}	
	if (host_name=="www.princess.com" || host_name=="book.princess.com" || host_name=="search.atomz.com" ){
		$bookURL='https://book.princess.com';
		$wwwURL='http://www.princess.com';
	 }
	 
var navigation_content ='<div id="navigation"> <ul id="qm0" class="qmmc"> <li> <a href="'+ $wwwURL +'/index.html" title="Go to Home Page" onclick="javascript:pageTracker._trackPageview(\'/topnav/home\');"><img  class="qm-is qm-ih qm-ia" src="/images/'+ shared_path+'/menu/Nav_Home.gif" width="48" height="27"  alt="Home" id="home"/></a></li>\
	  <li> <a  href="'+ $wwwURL +'/learn/index.jsp" title="Go to Learn About Our Cruises Page" onclick="javascript:pageTracker._trackPageview(\'/topnav/learn\');"><img  class="qm-is qm-ia qm-ih" src="/images/'+ shared_path+'/menu/Nav_Learn.gif" width="153" height="27" alt="Learn About Our Cruises" id="learn" /></a>\
        <ul class="laoc">\
         <li><a href="' + $wwwURL + '/why_princess/" title="Why Princess" onclick="javascript:pageTracker._trackPageview(\'/topnav/learn/whyPrincess\');">Why Princess</a> </li>\
         <li><a href="' + $wwwURL + '/learn/destinations/" title="Destinations" onclick="javascript:pageTracker._trackPageview(\'/topnav/learn/destinations\');">Destinations</a></li>\
          <li> <a href="' +$wwwURL + '/learn/cruisetours/" title="Cruisetours" onclick="javascript:pageTracker._trackPageview(\'/topnav/learn/cruisetours\');">Cruisetours</a></li>\
        <li><a href="' + $wwwURL + '/learn/excursions/index.jsp" title="Ports and Excursions" onclick="javascript:pageTracker._trackPageview(\'/topnav/learn/shoreexcursions\');">Ports & Excursions</a></li>\
          <li><a href="' + $wwwURL + '/learn/ships/" title="Ships" onclick="javascript:pageTracker._trackPageview(\'/topnav/learn/ships\');">Ships</a> </li>\
           <li><a href="' + $wwwURL + '/learn/onboard/" title="Onboard Experience" onclick="javascript:pageTracker._trackPageview(\'/topnav/learn/onboardexperience\');">Onboard Experience</a></li>\
         <li><a href="' + $wwwURL + '/learn/faq_answer/index.jsp" title="FAQ: Cruise Answer Place" onclick="javascript:pageTracker._trackPageview(\'/topnav/prepare/cruiseanswerplace\');">FAQ: Cruise Answer Place</a></li>\
        </ul>\
      </li>\
       <li> <a href="' + $wwwURL + '/find/index.jsp" title="Go to Find and Compare Cruises Page" onclick="javascript:pageTracker._trackPageview(\'/topnav/find\');"> <img  class="qm-is qm-ia qm-ih" src="/images/'+ shared_path+'/menu/Nav_Find.gif" width="160" height="27" alt="Find and Compare Cruises" id="find"/></a>\
        <ul class="fac">\
         <li><a href="' +  $wwwURL + '/find/index.jsp?resType=C" title="Find and Compare Cruises Page" onclick="javascript:pageTracker._trackPageview(\'/topnav/find/searchcruises\');">Search Cruises</a></li>\
          <li><a href="' +  $wwwURL + '/find/index.jsp?resType=T" title="Find and Compare Cruises Tour Page" onclick="javascript:pageTracker._trackPageview(\'/topnav/find/searchcruisetours\');">Search Cruisetours</a></li> </ul></li>\
		  <li> <a href="' +$wwwURL + '/book/index.jsp" title="Go to How To Book Page" onclick="javascript:pageTracker._trackPageview(\'/topnav/howtobook\');"><img class="qm-is qm-ia qm-ih" src="/images/'+ shared_path+'/menu/Nav_Book.gif" width="91" height="27"  alt="How To Book" id="howto"/></a>\
          <ul><li><a href="' + $wwwURL + '/book/agent/index.jsp" title="Travel Agent Locator" onclick="javascript:pageTracker._trackPageview(\'/topnav/howtobook/talocator\');">Travel Agent Locator</a> </li>\
		   <li><a href="' + $bookURL + '/captaincircle/jsp/planner.jsp" title="Cruise Vacation Planner" onclick="javascript:pageTracker._trackPageview(\'/topnav/howtobook/cruisevacationplanner\');">Cruise Vacation Planner</a> </li>\
		   <li><a href="' + $wwwURL + '/find/bookonline.jsp" title="Book Online" onclick="javascript:pageTracker._trackPageview(\'/topnav/howtobook/bookonline\');">Book Online</a> </li>\
        </ul>\
      </li>\
      <li><a href="' + $wwwURL + '/prepare/index.jsp" title="Go to Prepare For Your Cruise Page" onclick="javascript:pageTracker._trackPageview(\'/topnav/prepare\');"><img  class="qm-is qm-ih qm-ia" src="/images/'+ shared_path+'/menu/Nav_Prepare.gif" width="150" height="27" alt="Prepare For Your Cruise" id="prepare"/></a>\
        <ul class="pfc">\
         <li> <a href="' +$bookURL + '/cruisepersonalizer/login.page?company=PC" title="Cruise Personalizer" onclick="javascript:pageTracker._trackPageview(\'/topnav/prepare/cruisepersonalizer\');">Cruise Personalizer</a> </li>\
          <li><a href="' + $wwwURL + '/learn/faq_answer/index.jsp" title="FAQ: Cruise Answer Place" onclick="javascript:pageTracker._trackPageview(\'/topnav/prepare/cruiseanswerplace\');">FAQ: Cruise Answer Place</a></li>\
          <li><a href="' + $wwwURL + '/learn/faq_answer/pre_cruise/prepare.jsp#Princess_Vacation_Protection" title="Vacation Protection" onclick="javascript:pageTracker._trackPageview(\'/topnav/prepare/vacationprotection\');">Vacation Protection</a></li>\
		  <li><a href="' + $wwwURL + '/learn/excursions/departure_ports/" title="Departure Ports" onclick="javascript:pageTracker._trackPageview(\'/topnav/prepare/embarkationports\');">Departure Ports</a></li>\
        </ul>\
      </li>\
     <li> <a href="' + $wwwURL + '/customer_care/" title="Go to Customer Care Page" onclick="javascript:pageTracker._trackPageview(\'/topnav/customercare\');"><img  class="qm-is qm-ih qm-ia" src="/images/'+ shared_path+'/menu/Nav_Customer.gif" width="100" height="27" alt="Customer Care" id="customercare"/></a>\
        <ul class="cc">\
           <li> <a href="' + $bookURL + '/captaincircle/myPrincess.page" title="My Princess" onclick="javascript:pageTracker._trackPageview(\'/topnav/customercare/myprincess\');">My Princess</a></li>\
         <li> <a href="' + $bookURL + '/captaincircle/jsp/captainCircleHome.jsp" title="Princess Captain\'s Circle" onclick="javascript:pageTracker._trackPageview(\'/topnav/customercare/captainscircle\');">Princess Captain\'s Circle</a></li>\
         <li> <a href="' + $wwwURL + '/customer_care/contact/index.jsp" title="Contact Us" onclick="javascript:pageTracker._trackPageview(\'/topnav/customercare/contactus\');">Contact Us</a> </li>\
        </ul>\
      </li>\
    </ul></div>';
	
var inactivity_layout='<div id="inactivity-screen"><div class="lite-popup"><div id="white-overlay"></div></div></div>';
var inactivity_content='<div id="inactivity-warning">\
			<h3>Alert:</h3>\
			<p class="error">Due to inactivity, your browsing session is about to expire. To maintain the security of your personal information, you will automatically be signed out momentarily.<p>\
			<a class="global-button" href="javascript:keepAlive();" id="continue-session">Continue Session</a> &nbsp; <a href="javascript:clearSession(\'Y\');" id="signout">Sign Out Now &raquo;</a>\
		  </div>'

	

function createTopNav(){	
	//Temporary code until p13 code is ready
	if (jQuery("#princess-footer").length > 0){
		targetDivforFooter =jQuery('#princess-footer');
	}
	else{
		targetDivforFooter =jQuery('#footer');
	}
	jQuery(targetDivforFooter).after(navigation_content);
	jQuery('#navigation').hide();
}

	
jQuery(document).ready( function (){
	/*To track the links for google Analytics */

	setInterval(poll,500);
	getLocale();

	var pagename="";
	if (jQuery("#princess-header").attr('data-pagename') !== undefined) {
		pagename= jQuery("#princess-header").attr('data-pagename');
	}
	
	var header_content ='<div id="header">\
		<div id="princess-logo">\
		  <a href="'+ $wwwURL +'/index.html" title="Go to Princess Home" onclick="javascript:pageTracker._trackPageview(\''+pagename+'/topnav/princesslogo\');">\
		  <img src="/images/'+ shared_path+'/princess_logo.gif" alt="Princess Cruises Logo" /></a></div>\
		  <div id="page-header-links"><a href="' + $bookURL + '/captaincircle/specialOfferRegistration.page" id="special-offers-link" style="display:none" onclick="javascript:pageTracker._trackPageview(\''+pagename+'/topnav/specialoffers\');">\
		  <img src="/images/'+ shared_path+'/special_offers_sign_up.gif" width="168" height="19" alt="Sign Up for Special Offers" /></a> \
		  <span class="separator" id="special-offers-separator">&nbsp;</span> \
		  <span id="signin-signout">\
		  </span>\
		  <span class="separator">&nbsp;</span> <img src="/images/'+ shared_path+'/myprincess_icon.gif" width="20" height="17" alt="" /> \
		  <a href="'+ $bookURL + '/captaincircle/myPrincess.page" class="linksblue" title="Sign in to My Princess" onclick="javascript:pageTracker._trackPageview(\''+pagename+'/topnav/myprincess\');"> My Princess</a>\
		<div id="sign-in-box">\
			<div id="loading-symbol"><img src="/images/'+ shared_path+'/ajax_loader.gif" width="32" height="32" alt=""></div>\
			<h3>Secure Sign In:</h3>\
			<iframe id="iframe-page" src="" width="280" frameBorder="0"></iframe>\
			<div id="register-block"><a href="'+ $bookURL + '/captaincircle/jsp/registrationStepOne.jsp" onclick="javascript:pageTracker._trackPageview(\''+pagename+'/topnav/register\');">Register</a></div>\
			<div class="close-box"><a href="javascript:void(0);"><img src="/images/'+ shared_path+'/close_small_btn.gif" width="13" height="13" alt="Close"></a></div>\
		  </div> </div> \
  		  <form id="form2" onsubmit="return doSubmitSearch();" method="get" action="http://search.atomz.com/search/" name="NEWSEARCH_FORM"> \
		  <div id="toll-free-and-search-placeholder">\
		  	<span id="toll-free-number-placeholder"> </span>\
		  <span id="search-panel"> <label for="search1">Search:</label>\
		  <input id="search1" type="text"  name="sp-q" title="Enter your search phrase here"  value=""/>\
		  <input type="hidden" name="sp_t" value="search" />\
		  <input type="hidden" name="sp-a" value="sp10001540" />\
		  <input type="hidden" name="sp-f" value="iso-8859-1" />\
		  <a href="#" title="Search Princess.com"  onclick="doSubmitSearch();javascript:pageTracker._trackPageview(\''+pagename+'/topnav/search\');"><img src="/images/global/go.gif" alt="GO" /></a> </span> </div></form></div>\
		  <div class="clear"></div>';	

	/* Add header */
	jQuery("#princess-header").html(header_content);
	jQuery('#navigation').fadeIn();
	
		  	
		/*Delete the cookies if sniffed country is not same as the persistent country  */	
          jQuery.ajax({
              type: "GET",
              url: getBookUrl(getUrl())+'captaincircle/deletePersistentCookies.do',
              dataType:"jsonp",
              global:false,
              success:function(result){
                 if(result.status=="deletedcookie")   
                	directToNewURL();
              },
              error: function(e) {
                 console.log("ERROR IN captaincircle/deletePersistentCookies.do " + e.responseText);
              }
		  });		

	if(hasLoggedIn()|| hasKeptSignedIn()) {
	printGreeting();
	
	}
	 printSignInBanner();
	 
	 function printSignInBanner() {
	if(hasLoggedIn()) {
		jQuery("#signin-signout").append('<a title="Sign Out" class="linksorange" href="javascript:signOut()"  onclick="javascript:pageTracker._trackPageview(\''+pagename+'/topnav/signout\');">Sign Out</a>');
	} else {
		jQuery("#signin-signout").append('<img src="/images/'+ shared_path+'/lock_icon.gif" width="11" height="17" alt="" /> \
		<a href="'+ $bookURL +'/captaincircle/renderQLForm.page" title=" Sign in or Register" id="sign-in-register-link" onclick="javascript:pageTracker._trackPageview(\''+pagename+'/topnav/signinregister\');"> Sign In / Register</a> '); 
	}
}
	
	 /* Add footer from footer_localized.js (generated by CMS -p13 script) */ 
	 jQuery.getScript('/js/'+shared_path+'/footer_localized.js',function(){
		 jQuery('.new-window-link').click(function(){
			window.open(this.href,'','width=700,height=700');
				return false;
			});
		});

	/* Sign-in box open/close and load Sign in page iframe */  
	jQuery('#sign-in-register-link').click(function(){
		jQuery('#iframe-page').attr('src', $bookURL + '/captaincircle/renderQLForm.page');
			 var elemOffsetPosition= $(this).offset();
			jQuery('#sign-in-box').fadeIn('fast'); 
			jQuery('#sign-in-box').offset({'left':elemOffsetPosition.left-100, 'top':elemOffsetPosition.top+22}); 
			return false;
		});
			  
	jQuery('.close-box').click(function(){
		jQuery('#sign-in-box').fadeOut('fast', function(){
			return false;
		});
	});
		
	/* Special Offers popup */  
	jQuery('#special-offers-link').click(function(){
	    jQuery('#special-offers-signup').html('<div class="main-lightbox">&nbsp; </div>\
		<div id="special-offers-lightbox">\
		<iframe src="'+this.href+'" height="442" width="415" frameBorder="0"> </iframe>\
		<a href="javascript:void(0)" id="special-offers-close-btn"><img width="45" height="12" alt="Close" src="/images/'+ shared_path+'/special_popup_close_btn.gif"></a></div>\
		')
		jQuery('#special-offers-signup').show();
		center_special_offers_lightbox();
		jQuery('#special-offers-close-btn').click(function(){
			jQuery('#special-offers-signup').hide();
		})
		return false;
	});
		  //IE6 Hack for first child styling
		if(jQuery.browser.msie && jQuery.browser.version < 7){
			jQuery('#footer dt:first-child').css('padding-top','2px');
		}
});

function center_special_offers_lightbox(){
	var topPosition=jQuery(window).scrollTop();
	jQuery('#special-offers-lightbox').css('top',topPosition+150);
	jQuery('#special-offers-lightbox').css("left", (jQuery(window).width() - jQuery('#special-offers-lightbox').outerWidth())/2 + 'px');
	if(jQuery.browser.msie){
		var overlayDiv =jQuery('.main-lightbox');
		overlayDiv.css("height", jQuery(document).height()) ;
		if(jQuery.browser.version < 7){
			overlayDiv.css("position",'absolute');
			}
		} 
	jQuery(window).resize(function() {
		var div= jQuery('#special-offers-lightbox');
		div.css("left", (jQuery(window).width() - div.outerWidth())/2  + 'px');
	});
}
 //Inactivity Screen Show/Hide */
function inactivity_screen_show_hide(){
	center_inactivity_lightbox();
	//To Adjust the position of lighbox (Center of the page)
	var div= jQuery('#inactivity-warning');
	div.css("left", (jQuery(window).width() - div.width())/2  + 'px');
	//Fix the issue of lightbox overlay not covering the whole height in IE6 
	if(jQuery.browser.msie && jQuery.browser.version < 7){
		var overlayHeight =jQuery('#white-overlay');
		overlayHeight.css("height", jQuery(document).height() ) ;
	}
	if(jQuery.browser.msie && jQuery.browser.version < 7) {
		if(jQuery('#inactivity-warning').css('display')=="block"){
			jQuery('#container select').css('visibility', 'hidden');
			}
		else { 
			jQuery('#container select').css('visibility', 'visible');
		  }
	  }
//To hide the lightbox on clicking close button
jQuery('#inactivity-warning .close-box, #continue-session').click(function() {
	jQuery('#inactivity-screen').remove();
	// IE6 select overlapping over popup div issue
	if(jQuery.browser.msie && jQuery.browser.version < 7){
		jQuery('#container select').css('visibility', 'visible');
	}
});
}
//To Adjust the position of lighbox when window is resized
function center_inactivity_lightbox(){
	var topPosition=jQuery(window).scrollTop();
	jQuery('#inactivity-warning').css('top',topPosition+100);
	jQuery(window).resize(function() {
		var div= jQuery('#inactivity-warning');
		div.css("left", (jQuery(window).width() - div.width())/2  + 'px');
	});
}	

/* Load Inactivity Screen Content */
function show_inactivity_screen(){		
	jQuery('body').prepend(inactivity_layout);
	jQuery('#inactivity-screen .lite-popup').append(inactivity_content);
	inactivity_screen_show_hide();
}

/* Search Functionality */
function doSubmitSearch() {
   if((document.NEWSEARCH_FORM["sp-q"].value !='SEARCH')&&(document.NEWSEARCH_FORM["sp-q"].value !='')){ 
   	document.NEWSEARCH_FORM.submit();
   }
   else{
   	alert("Please enter at least one keyword to be searched.");
   	 document.NEWSEARCH_FORM["sp-q"].focus();
   	 return false;
   }
}

var timerId;
var timeoutId;
var loc;
	
function getLocale() {
  jQuery.ajax({
      type: "GET",
      url: getBookUrl(getUrl())+"captaincircle/getLocale.do?"+(new Date()).getTime(),
      dataType:"jsonp",
      global:false,
      success:function(result){
        loc=result.status;
      },
      error: function(e) {
       	loc="IN";
       	console.log("ERROR IN captaincircle/getLocale.do " + e.responseText);
      },
      complete: function(d) {
		showPrincessTollFreeNumber();
		setUpSpecialOffers();
      }
	  
  });
}
resetSessionCookie();
checkInactivity();

function showPrincessTollFreeNumber(){
	console.log("Location: "+loc);
	if(loc=="UK"){
		//jQuery('#toll-free-number, #toll-free-number-footer').text('0845 075 0031');
		jQuery('#toll-free-number-placeholder').html('<span class="highlight-color">Need Help?</span> \
            <span id="toll-free-number">0845 075 0031</span>\
            <span class="separator">&nbsp;</span>');
		jQuery('#toll-free-placeholder').html('<span class="highlight-color">Need Help?</span> <span id="toll-free-number-footer">0845 075 0031</span>');
	}	
	else if( loc=="AU" || loc=="NZ"){
		//Numbers to be added soon
		jQuery('#toll-free-number-placeholder').html('<span class="highlight-color">Need Help?</span> <span id="toll-free-number"> Australia: 1300 551 853 | New Zealand:  0800 780 717</span>\
            <span class="separator">&nbsp;</span>');
		jQuery('#toll-free-placeholder').html('<span class="highlight-color">Need Help?</span> <span id="toll-free-number-footer"> Australia: 1300 551 853 | New Zealand:  0800 780 717</span>');
		}
	else if(loc=="IN"){
			jQuery('#toll-free-number-placeholder, #toll-free-placeholder').html('');
		}
	else if(loc=="US"){
		jQuery('#toll-free-number-placeholder').html('<span class="highlight-color">Ready to Book?</span> \
            <span class="toll-free-number">1-866-335-6379</span><br>\
			<span class="highlight-color">Learn More: </span> \
            <span class="toll-free-number">1-800-774-6237</span>\
			');
			jQuery('#search-panel').css({'position':'relative','top':'-8px','right':'5px'});
			jQuery('#toll-free-number-placeholder').css({'padding-right':'20px','text-align':'right','display':'inline-block','line-height':'17px'});
			if (jQuery("#toll-free-number-placeholder").length > 0){
				jQuery('#navigation, #no-navigation').css({'top':'104px'});
			}
			jQuery('#toll-free-and-search-placeholder').css({'top':'62px'});
			jQuery('#header').css({'height':'95px'});
			jQuery('#toll-free-placeholder').css({'text-align':'right','display':'inline-block','line-height':'17px'});
		jQuery('#toll-free-placeholder').html('<span class="highlight-color">Ready to Book?</span> <span class="toll-free-number-footer">1-866-335-6379</span><br>\
		<span class="highlight-color">Learn More: </span> <span class="toll-free-number-footer">1-800-774-6237</span>');	}
		
	else{
		jQuery('#toll-free-number-placeholder, #toll-free-placeholder').html('');
		}		
}

function checkInactivity() {
	var sccn = getCookie("sccn");
	if(getCookie("sccn")!=null && getCookie("sccn") != "" && getCookie("cc")!=null&& getCookie("cc") != "") {
		timerId = setTimeout("prepareInactivity()",1740000);
		//timerId = setTimeout("prepareInactivity()",10000);
	}
}

function prepareInactivity() {
	show_inactivity_screen();
	clearTimeout(timerId);
	timeoutId = setTimeout("clearSession_forInactivity()",60000);
	//timeoutId = setTimeout("clearSession_forInactivity()",10000);
    return false;
}


function keepAlive() {
	clearTimeout(timeoutId);
	setTimeout("prepareInactivity()",1740000);
	//setTimeout("prepareInactivity()",10000);
	resetSessionCookie();
	directToNewURL();
}


function clearSession_forInactivity() {
 clearSession("N");
}

//Function returns the value of the QueryString
function getQueryVariable(variable) {
   var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
            return pair[1];
        }
    }
    return null;
}

/*Function to append a random string to the current url to avoid caching
  Ex: ?random=8796654.66
  If querystring conatains 'random' replaces with a new random number
  If querystring does not conatain 'random' append ?random= or &random=
  If the current URL have # append 'random' before that.
*/
function directToNewURL() {
	var str = document.location.href;
	var random = "";
	var randomString = getQueryVariable("random");
	if(null !=randomString && randomString.length > 0) {
	   str = str.replace(randomString, (Math.random() * Date.parse(new Date())));
	   document.location.href = str;
	} else {
		if(str.indexOf("?")!=-1) random = '&random=';
		else random = '?random=';
		random = random + (Math.random() * Date.parse(new Date()));
		if(document.location.href.indexOf("#")!=-1)
		{
			var indexofHash = str.indexOf("#");
			if(document.location.href.indexOf("#") == document.location.href.length-1 ){
			var docLoc = document.location.href;
			var ran = random;
			document.location.href = document.location.href.replace('#','')+random;
			return;
			}
			var beforehash = str.substring(0,indexofHash);
			var afterhash = str.substring(indexofHash, str.length);
	    	document.location.href = beforehash+ random+afterhash;
	   	} else {
	   		document.location.href = document.location.href+random
	   	}
   	}
}

function clearSession(fromInactivity) {
	clearTimeout(timeoutId);
	deleteCokie("sccn","/",".princess.com");
	jQuery.ajax({ 
	type: "GET",
	url: getBookUrl(getUrl())+'captaincircle/logoutFromCC.do?ina='+fromInactivity ,
	dataType:"jsonp",  
	global:false,
	success:function(result){
		if(document.location.href.indexOf(".com/cruisepersonalizer")!=-1) {
			document.location.href = $bookURL+"/cruisepersonalizer/logout.page";
		} else if( document.location.href.indexOf(".com/reserve")!=-1 ){
          		var confirmation=confirm("Are you sure you want to sign out of princess.com?"+ "\nYour booking will not be saved.");
          		if (confirmation!=true){
            			return;
          		}
            navForm.action=$bookURL+"/reserve/logout.page";
            navForm.submit();
		}else {
			directToNewURL();
		}
	},
	error: function(e) { 
	    console.log("ERROR IN captaincircle/logoutFromCC.do " + e.responseText);
	}	 
   }); 
}

function resetSessionCookie() {
	sccn = getCookie("sccn");
	if(getCookie("sccn")!=null && getCookie("sccn") != ""&& getCookie("cc")!=null&& getCookie("cc") != "") {
		deleteCokie("sccn","/",".princess.com");
		setSessionCookie("sccn",sccn);
	}
}

function deleteCokie(sName, path, domain) {
	var expDate = new Date();
	//set the date value to the past
	expDate.setTime(expDate.getTime()-100000);

	if ( getCookie( sName ) !=null && getCookie("sName") != "") {
		document.cookie = sName  + "=test" +
		( ( path ) ? ";path=" + path : "") +
		( ( domain ) ? ";domain=" + domain : "" ) +";expires="+expDate.toGMTString()+ "; ";
	}
	//document.cookie = sName + "=; expires=Thu, 01-Jan-70 00:00:01 GMT";

}

function setSessionCookie(sName, sValue) {
	var dt = new Date();
	dt.setTime( dt.getTime() + 30*60*1000 );

	if(getCookie(sName)==null) {
		if(isValidUsrURL(path)) {
			document.cookie = sName + "=" + escape(sValue) + "; " +
				"path=/;" + 'expires=' + dt.toGMTString()+ "; ";
		} else {
			domainname='.princess.com';
			document.cookie = sName + "=" + escape(sValue) + "; " +
				"path=/; domain=" + domainname + ";"+ 'expires=' + dt.toGMTString()+ "; ";
		}
	}
}

function poll() {
    if(window.location.hash != "#si") {
        return;
    }
	jQuery('#sign-in-box').fadeOut('fast');
    window.location.hash = "";
	window.location.reload();
}


//Function to set up Special offers link
function setUpSpecialOffers() {
    hasSignedUpForSpclOffers = getCookie("SIGNED_UP_SPCL_OFFERS");
	jQuery('#special-offers-link, #special-offers-separator').hide();
    if(!(hasLoggedIn()) && !hasSignedUpForSpclOffers) {
      if(loc=="US" || loc=="AU" || loc=="NZ")
	    jQuery('#special-offers-link , #special-offers-separator').show();
    }
	if(loc=="UK" || loc=="IN"){
		jQuery('#special-offers-signup').remove();
		jQuery('#special-offers-link, #special-offers-separator').show(function(){
			jQuery('#special-offers-link').click(function(){
			window.location.href=$bookURL + "/captaincircle/jsp/registrationStepOne.jsp"
			});	
		});
	}
}
jQuery.isBlank = function(object) {
        return (
            (jQuery.isPlainObject(object) && jQuery.isEmptyObject(object)) ||
            (jQuery.isArray(object) && object.length == 0) ||
            (typeof(object) == "string" && jQuery.trim(object) === "") ||
            (!object)
        );
    };
	
function hasLoggedIn() {
	var sloginId = getCookie("sccn");
	var loginId = getCookie("cc");
	return !isBlank(sloginId)&&!isBlank(loginId);
}

function hasKeptSignedIn() {
	var ploginId = getCookie("pccn");
	return (!isBlank(ploginId));
}

function notYou(){
	jQuery("#signin-btn").removeAttr("disabled");
	clearSession("Y");
}

function signOut(){
	jQuery("#signin-btn").removeAttr("disabled");
	 clearSession("N");
}


function printGreeting(){
	$user = "";
	if(hasLoggedIn()) {
		$user =getCookie("NAME_ON_TOP_BANNER");
	} else if(hasKeptSignedIn()) {
		$user =getCookie("pnotp");
	}
	jQuery("#signin-signout").html('Welcome back ' + $user +' (<a title="Not You" class="linksorange" href="javascript:notYou();">Not You?</a>) ');
} 


