
// Fix flickering in IE6
try
{
	document.execCommand('BackgroundImageCache', false, true);
}
catch(e)
{}

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;
}

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="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)
{
	isUserValid=srResponse.isLoggedIn;
	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);
}

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()
}

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;
}




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);
}


function doAJAX(url, params, callbackFx, formMethod)
{
    if (window.XMLHttpRequest) {
		// Mozilla, Safari,...
        http_request = new XMLHttpRequest();
    } else {
        if (window.ActiveXObject) { // IE
            http_request = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    http_request.onreadystatechange = callbackFx;
    if (formMethod == "GET") {
        http_request.open("GET", url + "?" + params, true);
        http_request.send(null);
    } else {
        http_request.open("POST", url, true);
        http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        http_request.setRequestHeader("Content-length", params.length);
        http_request.setRequestHeader("Connection", "close");
        http_request.send(params);
    }
}



// JSONscriptRequest -- a simple class for making HTTP requests
// using dynamically generated script tags and JSON
//
// Author: Jason Levitt
// Date: December 7th, 2005
//
// A SECURITY WARNING FROM DOUGLAS CROCKFORD:
// "The dynamic <script> tag hack suffers from a problem. It allows a page
// to access data from any server in the web, which is really useful.
// Unfortunately, the data is returned in the form of a script. That script
// can deliver the data, but it runs with the same authority as scripts on
// the base page, so it is able to steal cookies or misuse the authorization
// of the user with the server. A rogue script can do destructive things to
// the relationship between the user and the base server."
//
// So, be extremely cautious in your use of this script.
//
//
// Sample Usage:
//
// <script type="text/javascript" src="jsr_class.js"></script>
//
// function callbackfunc(jsonData) {
//      alert('Latitude = ' + jsonData.ResultSet.Result[0].Latitude +
//            '  Longitude = ' + jsonData.ResultSet.Result[0].Longitude);
//      aObj.removeScriptTag();
// }
//
// request = 'http://api.local.yahoo.com/MapsService/V1/geocode?appid=YahooDemo&
//            output=json&callback=callbackfunc&location=78704';
// aObj = new JSONscriptRequest(request);
// aObj.buildScriptTag();
// aObj.addScriptTag();

// Constructor -- pass a REST request URL to the constructor
function JSONscriptRequest(fullUrl) {
    // REST request path
    this.fullUrl = fullUrl;
    // Keep IE from caching requests
    this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
    // Get the DOM location to put the script tag
    this.headLoc = document.getElementsByTagName("head").item(0);
    // Generate a unique script tag id
    this.scriptId = 'JscriptId' + JSONscriptRequest.scriptCounter++;
}

// Static script ID counter
JSONscriptRequest.scriptCounter = 1;

JSONscriptRequest.prototype.buildScriptTag = function () {
	this.scriptObj = document.createElement("script");
    this.scriptObj.setAttribute("type", "text/javascript");
    this.scriptObj.setAttribute("charset", "utf-8");
    this.scriptObj.setAttribute("src", this.fullUrl);
    this.scriptObj.setAttribute("id", this.scriptId);
}

JSONscriptRequest.prototype.removeScriptTag = function () {
    this.headLoc.removeChild(this.scriptObj);
}

JSONscriptRequest.prototype.addScriptTag = function () {
    this.headLoc.appendChild(this.scriptObj);
}


function promoBox1Refresh()
{
	var promoBox1 = new Array();
		promoBox1[0] = "http://www.budgettravel.com/bt-srv/images/122007/win_EgyptContest_255x90.jpg";
		promoBox1[1] = "http://www.budgettravel.com/bt-srv/images/122007/FreeTravelInfo_255x90.gif";

	var promoBox1Length = promoBox1.length;
	var promoBox1Preload = new Array();

	for (i = 0; i < promoBox1Length; i++) {
		promoBox1Preload[i] = new Image()
		promoBox1Preload[i].src = promoBox1[i]
	}

	//var promoBox1Random = Math.round(Math.random()*(promoBox1Length-1));
	var promoBox1Random = 1;

	if(promoBox1Random == 0) {
		document.write('<a href="http://www.budgettravel.com/bt-reg/PrepareNewReg.do?wpisrc=6000016"><img src="' + promoBox1[promoBox1Random] + '" border="0" alt="Got vacation photos or videos? Share them with Budget Travel\'s community!"></a>');
	}
	else if(promoBox1Random == 1) {
		document.write('<a href="http://www.budgettravel.com/bt-srv/contest/"><img src="' + promoBox1[promoBox1Random] + '" border="0" alt="Share your travel photos and you may get your photo published!"></a>');
	}
}


// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// http://blog.stevenlevithan.com/archives/parseuri
// MIT License

function parseUri (str) {
	var	o   = parseUri.options,
		m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
		uri = {},
		i   = 14;

	while (i--) uri[o.key[i]] = m[i] || "";

	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	});

	return uri;
};

parseUri.options = {
	strictMode: false,
	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
	q:   {
		name:   "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};

function selectTab($target)
{
	// Tabs must be in <ul> or <ol> tags
	// Each tab must be within an <li>, but can also be nested in a deeper tag
	// example: <li><a href="#foo">Tab</a></li>

	var $tab;

	if (!$target.is('li'))
		$tab = $target.parents('li');
	else
		$tab = $target;

	$tab.siblings('li.selected').removeClass('selected').addClass('unselected');
	$tab.removeClass('unselected').addClass('selected');
}
