/*******************************************************
MAIN GLOBAL FUNCTIONS
*********************************************************/

/*-- flickering in IE6 --*/

try {
  document.execCommand('BackgroundImageCache', false, true);
} catch(e) {}

/*--/ end flickering in IE6 --*/

/**********************************************************************************   
AUTO-TEXT
- A function to clear all input field values when users click inside 
*********************************************************************************/
/* begin auto-text */
function autoText(m,n)
{
	var a = document.getElementById(m)
	
	if (a.value == n)
	{
		/* a.style.color='#999'; */
		a.style.color='#111';
		
		a.onclick = function()
		{
			if (a.value == n)
			{
				a.value = '';
				/* a.style.color='#717165'; */
				a.style.color='#111';
			}
		}
		a.onfocus = function()
		{
			if (a.value == n)
			{
				a.value = '';
				/* a.style.color='#717165'; */
				a.style.color='#111';
			}
		}
		a.onblur = function()
		{
			if (a.value == '')
			{
				a.value = n;
				/* a.style.color='#999'; */
				a.style.color='#111';
			}
		}
	}
	
	if (a.value != n)
	{
		a.onblur = function()
		{
			if (a.value == '')
			{
				a.value = n;
				/* a.style.color='#999'; */
				a.style.color='#111';
			}
		}
	}
}
/* end auto-text */


/**********************************************************************************   
NEWS TICKER STYLES ON GLOBAL HEADER

NewsSlideFade - Made by Thomas Brattli *
*   Script date: 09/04/2001 (keep this date to check versions) 
*********************************************************************************/

function lib_bwcheck(){ //Browsercheck (needed)
	this.ver=navigator.appVersion
	this.agent=navigator.userAgent
	this.dom=document.getElementById?1:0
	this.opera5=(navigator.userAgent.indexOf("Opera")>-1 && document.getElementById)?1:0
	this.ie5=(this.ver.indexOf("MSIE 5")>-1 && this.dom && !this.opera5)?1:0; 
	this.ie6=(this.ver.indexOf("MSIE 6")>-1 && this.dom && !this.opera5)?1:0;
	this.ie4=(document.all && !this.dom && !this.opera5)?1:0;
	this.ie=this.ie4||this.ie5||this.ie6
	this.mac=this.agent.indexOf("Mac")>-1
	this.ns6=(this.dom && parseInt(this.ver) >= 5) ?1:0; 
	this.ns4=(document.layers && !this.dom)?1:0;
	this.bw=(this.ie6 || this.ie5 || this.ie4 || this.ns4 || this.ns6 || this.opera5)
	return this
}
var bw=lib_bwcheck()

/***************************************************************************
Use the style tag to change the placement and width of the layers.
If you are trying to place this into a table cell or something make the
position of the divNewsCont layer relative...Remeber that that might crash
Netscape 4 though, Good luck!
********************************************************************************/

/****
Variables to set 
****/

//How do you want the script to work? 
//0 = Fade in - Fade out
//1 = Slide in - Fade out
//2 = Random 
nWorks = 0

//If you use the slide set these variables:
nSlidespeed = 5 //in px
nNewsheight = 80 //This is how long down it should start the slide.

nBetweendelay = 5000 //The delay before fading out.
nFont = 'arial,helvetica,sans-serif' //The font for the news.
nFontsize = 11 //Font size in pixel.
nFadespeed = 100 //The speed to fade in, in milliseconds.

//Set the colors, first color is same as background, last color is the color it stops at:
//You can have as many colors you want
nColor=new Array('#196ec1','#2f7dc9','#468dd1','#609dd9','#7db0e1','#9ac2e9','b8d5f1','d6e7f8','f3f8fd','#ffffff')



function include_dom(script_filename)
{ 
	var html_doc = document.getElementsByTagName('head').item(0); 
	var js = document.createElement('script'); 
	js.setAttribute('language', 'javascript'); 
	js.setAttribute('type', 'text/javascript'); 
	js.setAttribute('src', script_filename); 
	html_doc.appendChild(js); 
	return false; 
} 

/********************************************************************************
Object code...Object constructors and functions...
********************************************************************************/
function makeNewsObj(obj,nest,font,size,color,news,fadespeed,betweendelay,slidespeed,works,newsheight){
    nest=(!nest) ? "":'document.'+nest+'.'
   	this.css=bw.dom? document.getElementById(obj).style:bw.ie4?document.all[obj].style:bw.ns4?eval(nest+"document.layers." +obj):0;	
   	this.writeref=bw.dom? document.getElementById(obj):bw.ie4?document.all[obj]:bw.ns4?eval(nest+"document.layers." +obj+".document"):0;
	if(font){this.color=new Array(); this.color=eval(color); this.news=new Array(); this.news=eval(news)
		this.font=font; this.size=size; this.speed=fadespeed; this.delay=betweendelay; this.newsheight=newsheight;
		this.fadeIn=b_fadeIn;this.fadeOut=b_fadeOut; this.newsWrite=b_newsWrite; this.y=1
		this.slideIn=b_slideIn; this.moveIt=b_moveIt; this.slideSpeed=slidespeed; this.works=works
		if(bw.dom || bw.ie4){this.css.fontFamily=this.font; this.css.fontSize=this.size; this.css.color=this.color[0]}
	}
	this.obj = obj + "Object"; 	eval(this.obj + "=this"); return this
}

// A unit of measure that will be added when setting the position of a layer.
var px = bw.ns4||window.opera?"":"px";

function b_moveIt(x,y){this.x=x; this.y=y; this.css.left=this.x+px; this.css.top=this.y+px;}

/*
function b_newsWrite(num,i){
	if (bw.ns4){
		this.writeref.write("<a href=\""+this.news[num]['link']+"\" target=\"myTarget\" style=\"text-decoration:none; font-size:"+this.size+"px\">"
			+"<font face=\""+this.font+"\" color=\""+this.color[i]+"\">"+this.news[num]['text']+"</font></a>")
		this.writeref.close()
	}else this.writeref.innerHTML = '<a id="'+this.obj+'link' +'" target="myTarget"  style="text-decoration:none; font-size:'+this.size+'px; color:'+this.color[i]+'" href="'+this.news[num]['link']+'">'+this.news[num]['text']+'</a>'
}
*/
function b_newsWrite(num,i){
	if (bw.ns4){
		this.writeref.write("<a href=\""+this.news[num]['link']+"\" style=\"text-decoration:none; font-size:"+this.size+"px\">"
			+"<font face=\""+this.font+"\" color=\""+this.color[i]+"\">"+this.news[num]['text']+"</font></a>")
		this.writeref.close()
	}else this.writeref.innerHTML = '<a id="'+this.obj+'link' +'"  style="text-decoration:none; font-size:'+this.size+'px; color:'+this.color[i]+'" href="'+this.news[num]['link']+'">'+this.news[num]['text']+'</a>'
}
//Slide in
function b_slideIn(num,i){
	if (this.y>0){
		if (i==0){this.moveIt(0,this.newsheight); this.newsWrite(num,this.color.length-1)}
		this.moveIt(this.x,this.y-this.slideSpeed)
		i ++
		setTimeout(this.obj+".slideIn("+num+","+i+");",50)
	}else setTimeout(this.obj+".fadeOut("+num+","+(this.color.length-1)+")",this.delay)
}
//The fade functions
function b_fadeIn(num,i){
	if (i<this.color.length){
		if (i==0 || bw.ns4) this.newsWrite(num,i)
		else{
			obj = bw.ie4?eval(this.obj+"link"):document.getElementById(this.obj+"link")
			obj.style.color = this.color[i]
		}
		i ++
		setTimeout(this.obj+".fadeIn("+num+","+i+")",this.speed)
	}else setTimeout(this.obj+".fadeOut("+num+","+(this.color.length-1)+")",this.delay)
}

function b_fadeOut(num,i){
	if (i>=0){
		if (i==0 || bw.ns4) this.newsWrite(num,i)	
		else{
			obj = bw.ie4?eval(this.obj+"link"):document.getElementById(this.obj+"link")
			obj.style.color = this.color[i]
		}
		i --
		setTimeout(this.obj+".fadeOut("+num+","+i+")",this.speed)
	}else{
		num ++
		if(num==this.news.length) num=0
		works = !this.works?0:this.works==1?1:Math.round(Math.random())
		if(works==0) setTimeout(this.obj+".fadeIn("+num+",0)",500)
		else if (works==1){this.y=1; setTimeout(this.obj+".slideIn("+num+",0)",500)
		}
	}
}
/********************************************************************************************
The init function. Calls the object constructor and set some properties and starts the fade
*********************************************************************************************/
function fadeInit(){
	oNews = new makeNewsObj('news_ticker','news_ticker_content',nFont,nFontsize,"nColor","nNews",nFadespeed,nBetweendelay,nSlidespeed,nWorks,nNewsheight)
	oNewsCont = new makeNewsObj('news_ticker_content')
	works = !oNews.works?0:oNews.works==1?1:Math.round(Math.random())
	if (works==0) oNews.fadeIn(0,0)
	else if (works==1) oNews.slideIn(0,0)
	oNewsCont.css.visibility = "visible"
}
/* ////////////////////////////////////////////////////// */




function addLoadEvent(func)
		{
		  var oldonload = window.onload;
		  if (typeof window.onload != 'function') {
			 window.onload = func;
		  } else {
			 window.onload = function() {
				if (oldonload) {
				  oldonload();
				}
				func();
			 }
		  }
		}

/* 2008.02.08 JBeam
Moved the call inline immediately after the div is rendered, so that 
the fade in/out starts immediately, instead of waiting for window.onload.

addLoadEvent(fadeInit);
*/
// addLoadEvent(externalLinks);
addLoadEvent
	(
		function()
		{
		  /* more code to run on page load */
		  
		}
	);
	

/*******************************************************
REGISTRATION/SIGNED IN SCRIPT
*********************************************************/

/* button roll-overs */
/*
function btReg_btnInteraction()
{
	if (!document.getElementsByTagName)
		return;
	
	var buttons = document.getElementsByTagName('input');
	
	for (var i=0; i<buttons.length; i++)
	{
		var button = buttons[i];
		if (button.getAttribute('type') == 'submit' && button.getAttribute('class') == 'button submit')
			button.onmouseover = 'this.className="button submit volvo"';
			button.onmouseout = 'this.className="button submit"';
	}
}
*/


function ReadCookie(name) {
  var BT_REGISTRATION_COOKIE = name+ "=";
  var cookies = document.cookie.split(';');
  for(var i=0;i < cookies.length;i++) {
       var cookie = cookies[i];
       while (cookie.charAt(0)==' ')	cookie = cookie.substring(1,cookie.length);
       if (cookie.indexOf(BT_REGISTRATION_COOKIE) == 0) 		
	return cookie.substring(BT_REGISTRATION_COOKIE.length,cookie.length);		
  }
  return null;
}


function getUserName(cookiename){
   username = ReadCookie('BTAccess');
   document.signin.usercookie.value = username;
}


function btReg_GlobalLinks()
{
	if (document.signin.usercookie.value == "null" || document.signin.usercookie.value == "")
	{
		document.write('<a href="http://www.budgettravel.com/bt-reg/PrepareLogin.do" target="_top">log in</a>');
		document.write('&nbsp;&nbsp;|&nbsp;&nbsp;');
		document.write('<a href="http://www.budgettravel.com/bt-reg/PrepareNewReg.do" target="_top">register</a>');
	}
	else
	{
		document.write('You are logged in as ' + document.signin.usercookie.value);
		// document.write('&nbsp;&nbsp;&nbsp;&nbsp;');
		// document.write('<a href="/bt-reg/PrepareManageAccount.do">change preferences</a>');
		document.write('&nbsp;&nbsp;|&nbsp;&nbsp;');
		document.write('<a href="http://www.budgettravel.com/bt-reg/ProcessLogout.do" target="_top">log out</a>');
	}
}


function getWellformedUrl(url,tokens){
	if(url.indexOf("?") == -1){
		return url+"?"+tokens;
	}else{
		return url+"&"+tokens;
	}
}


function callResponse(srResponse)
{
	//alert("Inside callResponse srResponse.isLoggedIn"+srResponse.isLoggedIn);
	isUserValid=srResponse.isLoggedIn;
	//alert("callResponse.isUserValid"+isUserValid);
	aObj.removeScriptTag();
}

function checkKALogin()
{
 	var username = ReadCookie('BTLogin');
 	var ssoTokens = ReadCookie('BTSSOTokens');
 	
 	if (username != null && username != "" && ssoTokens != null && ssoTokens != "" ){
		var logCheckUrl = 'http://mybt.budgettravel.com/kickapps/service/isUserLoggedIn.kickAction?as=21864&callback=callResponse';
		aObj = new JSONscriptRequest(logCheckUrl);
		aObj.buildScriptTag();
		aObj.addScriptTag();
	}
}

var isUserValid = 'false';

function submitForm(url,source){ 
 var username = ReadCookie('BTLogin');
 var ssoTokens = ReadCookie('BTSSOTokens');
 
  //Added for VIEW/EDIT Profile link
 if(url.match("addKAUserId=true") != null){
  	ssoTokens = ReadCookie('BTSSOUidToken');
 }
 
 
 if (source == "sso-nologin"){ /* KA SSO URLs that does not require login */
 	if (ssoTokens != null && ssoTokens != ""){
 		destinationUrl=getWellformedUrl(url,ssoTokens);
 		window.location=destinationUrl;
 	}else{
 		window.location=url;
 	}
 
 }else{
 	if(source == "sso"){ /* KA SSO URLs require login */
 		if (username == null || username == "" || ssoTokens == null || ssoTokens == "" || (window['isUserValid'] != undefined && isUserValid == 'false') ){
			url = "http://www.budgettravel.com/bt-reg/PrepareLogin.do?redirectUrl="+getWellformedUrl(url,"source="+source);
		  	window.location=url; 	
 		}else{
 			destinationUrl=getWellformedUrl(url,ssoTokens);
 		}
 	}else{ /* all other sources */
 		destinationUrl = getWellformedUrl(url,"source="+source);
 	}
 	window.location=destinationUrl;	
 }
} 


/*******************************************************
'THIS JUST IN' DROP-DOWN SCRIPTS
*********************************************************/

function writeBlogArticles () {

	blogCount = module[0].content.length;
	blogCount1 = moduleTalking[0].content.length;

	if (blogCount >= 4) {
		blogCount = 4;
	}
	if (blogCount1 >= 4) {
		blogCount1 = 4;
	}
	
	var forLoopContent = "<li class=\"one\">RECENT POSTS<ul>";
	var listStyle = "";

	for (j=0; j<4; j++) {
		if (module[0].content[j].url != "") {
			if (j==3) {
				listStyle = " class=\"last\"";
			}
			else {
				listStyle = "";
			}
			forLoopContent += "<li" + listStyle + "><span class=\"timestamp\">" + module[0].content[j].pubday + " " + module[0].content[j].timestamp + "<\/span><a href=\"" + module[0].content[j].url + "\">" + module[0].content[j].headline + "<\/a><\/li>";
		}
	}

	forLoopContent += "<\/ul><\/li><li class=\"two\">PEOPLE ARE TALKING&hellip;<ul>";

	for (j=0; j<4; j++) {
		if (moduleTalking[0].content[j].url != "") {
			if (j==3) {
				listStyle = " class=\"last\"";
			}
			else {
				listStyle = "";
			}

			var commentString = "";
			var totalComments = parseInt(moduleTalking[0].content[j].comments);

			if (totalComments != 1) {
				commentString = totalComments + " Comments";
			}
			else {
				commentString = totalComments + " Comment";
			}
			
			forLoopContent += "<li" + listStyle + "><span class=\"timestamp\">" + moduleTalking[0].content[j].pubdate + "<\/span><a href=\"" + moduleTalking[0].content[j].url + "\">" + moduleTalking[0].content[j].headline + " (" + commentString + ")<\/a><\/li>";
		}
	}

	forLoopContent += "<\/ul><\/li>";
	
	document.write(forLoopContent);	
}


/* ////////////////////////////////////////////////////// */
/* ////////////////////////////////////////////////////// */


/* misc jQuery stuff */
$(document).ready(function(){

/* 2009.03.06 JBeam - open links in a new window (strict dtd-compliant).
Use discretion, but if we ever move to a strict DTD, we'll need to do something like this to validate.
Instructions: for any link that you want to open in a new browser window, don't use target="_blank".  Instead, use rel="new_window", which will trigger the script below. */
$('a[rel=new_window]').attr('target', '_blank');

});
/* end misc jQuery stuff */


/* ////////////////////////////////////////////////////// */
/* ////////////////////////////////////////////////////// */

// Begin launcher script for slide shows (written by A. Falcone 11/18/08; added by A. Falcone 08/27/09)
function launchSlideshowV2 (whichShow,whichSlide) {
	if (!whichSlide) {
		whichSlide = 0;
	}
	var slideshowURL = "http://www.budgettravel.com/bt-srv/gallery/" + whichShow + "/index.html?jumpToPic=" + whichSlide;
	popupWindow = window.open(slideshowURL,'bt_gallery_v2','toolbar=0,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no,width=900,height=675,left=0,top=0,screenX=0,screenY=0')
	popupWindow.focus()
}
// End launcher script for slide shows

/* ////////////////////////////////////////////////////// */
/* ////////////////////////////////////////////////////// */

// Begin generic e-mail validator (added by A. Falcone 08/27/09)

	function validEmail(email) {
		invalidChars = " /:,;"
		for (m=0; m<invalidChars.length; m++) {
			badChar = invalidChars.charAt(m);
			if (email.indexOf(badChar,0) > -1) {
				return false;
			}
		}
		atPos = email.indexOf("@",1);
		if (atPos == -1) {
			return false;
		}
		if (email.indexOf("@",atPos+1) > -1) {
			return false;
		}
		periodPos = email.indexOf(".",atPos);
          if (periodPos == -1) {
			return false;
		}
		if (periodPos+3 > email.length) {
			return false;
		}
		return true;
	}

// End generic e-mail validator
	
/* ////////////////////////////////////////////////////// */
/* ////////////////////////////////////////////////////// */

// Begin Deal Alerts sign-up form validator (added by A. Falcone 08/27/09)
	
	function validateSubscribeForm(form) {
		var requiredFields = new Array();
			requiredFields[1] = "e-mail address";
			requiredFields[2] = "zip code";
		for (i=1; i<=2; i++) {
			if (form[i].value.length==0) {
				form[i].focus();
				alert("Please provide your " + requiredFields[i] + ".");
				return false;
			}
			if (i==1) {
				if(!validEmail(form[i].value)) {
					form[i].select();
					form[i].focus();
					alert("Please check that you have typed your e-mail address correctly.");
					return false;
				}
			}
			if (i==2) {
				if (form[i].value.length != 5) {
					form[i].select();
					form[i].focus();
					alert("Please provide a valid 5-digit zip code.");
					return false;
				}
			}
		}
		return true;
	}

// End Deal Alerts sign-up form validator
