


officeHours = function() {
	this.phoneTollfreeUS = '1.800.272.9676';
	this.phoneTollfreeUK = '0.808.234.4107';
	this.phoneOutside = '+1.617.321.3100';
	this.hoursWeekdays = 'Our agents are available 24 hours a day, every day of the week';
	this.hoursWeekends = '';
	this.alternative = '';
	}

function checkAll(checkedStatus) { 
	$('INPUT.compareToLink[type=checkbox]').attr('checked', checkedStatus);
}

function toggleCheckAll() { 
	var checkAllBox = $('INPUT#compareCheckbox-checkall[type=checkbox]');
	var checkedStatus = checkAllBox.attr('checked');
	checkAllBox.attr('checked', !checkedStatus);
	checkAll(checkAllBox.attr('checked'));
}


// ***************************** SHOPPINGCART.JSP ***************************** //
	var offHours = new officeHours();
	function deleteItem(id) {
		if (confirm('Are you sure you want to delete this flight?')) {
			submitAjaxFromQuery("deleteAirItem",deleteReturn,"POST","item_pk="+id,"Deleting flight" );
		}
    }
	
	function deleteReturn(returnJSONTxt) {
		var json = eval("new Object(" + returnJSONTxt + ")");
		if ( json.errors ) {
			alert(json.errors);
		}
		if ( defined(json.returnView) ) {
			goToURL( views[json.returnView] );
		}
		else {
			var id = "cartItem-" + json.returnMsg.replace("Deleted air item: ","");
			hideElement(id);
			window.scrollTo(0,0);
		}
	}
	
	var views = new Object();
	views["homePage"] = "/";
	views["cart"] = "/shoppingcart";
	views["results"] = "/fly/airsearchResults.jsp";
	views["flyPage"] = "/";  // fly page is the home page since the grid redesign
	views["searchError"] = "/?err=true";
	views["airsearchWait"] = "/includes/airsearchWait.jsp";
	views["myAccount"] = "/register/update";
	
	function focusOnPhone() {
		if ( getJoinForm().passengerPhone.value == '') {
			getJoinForm().passengerPhone.focus();
		}
	}
	
	function setCheckedValue(radioObj, newValue) {
	if(!radioObj)
		return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		radioObj.checked = (radioObj.value == newValue.toString());
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false;
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].checked = true;
		}
		else {
			radioObj[i].checked = false;
		}
	}
}

	function matchSelectBoxValue(selObj1,selObj2) {
		var selIndex = selObj1.options[selObj1.selectedIndex].value;
		selObj2.length=0;
		for ( var i=0 ; i < selObj1.options.length ; i++ ) {
			selObj2.length++;
			newOption=new Option( selObj1.options[i].text );
			newOption.value= selObj1.options[i].value;
			if ( selIndex == newOption.value ) newOption.selected=true;
			selObj2.options[i]=newOption;
		}
		
	}

    
    function check_onClick(checkbox) {
		thisForm=checkbox.form;
		var countryName = thisForm.billcountry.options[thisForm.billcountry.selectedIndex].value;
		
		if ( checkbox.checked && ( countryName == "United States" || countryName == "Canada")  ) {
			thisForm.shipname.value=thisForm.nameoncard.value;
			thisForm.shipaddress1.value=thisForm.billaddress1.value;
        	thisForm.shipaddress2.value=thisForm.billaddress2.value;
        	thisForm.shipcity.value=thisForm.billcity.value;
			matchSelectBoxValue(thisForm.billstate,thisForm.shipstate);
			setCheckedValue(thisForm.shipcountry,countryName);
        	thisForm.shippostalcode.value=thisForm.billpostalcode.value;
			if ( thisForm.name == "requestToPayForm" ) {
				thisForm.shipphone.value=thisForm.billphone.value;
			}
			else {
				thisForm.shipphone.value=thisForm.billingPhone.value;
			}
		}
		
		else { //not checked - clear shipping info
			if ( checkbox.checked ) {
				alert("Shipping address must be in the United States or Canada");
				checkbox.checked = false;
			}	
			else {
				setCheckedValue(thisForm.shipcountry,"United States");
			}
			
			
			thisForm.shipname.value='';
			thisForm.shipaddress1.value='';
        	thisForm.shipaddress2.value='';
        	thisForm.shipcity.value='';
        	thisForm.shipstate.value='';
        	thisForm.shippostalcode.value='';
			thisForm.shipphone.value='';
		}
		
	}
	

	function group_check_same_as_billing(checkbox) {
		thisForm = checkbox.form;
		 		
		if ( checkbox.checked ) {
			thisForm.shipname.value = thisForm.nameoncard.value;
			thisForm.shipaddress1.value = thisForm.billaddress1.value;
        		thisForm.shipaddress2.value = thisForm.billaddress2.value;
        		thisForm.shipcity.value = thisForm.billcity.value;
        		thisForm.shipstate.value = thisForm.billstate.value;
        		thisForm.shipcountry.value = thisForm.billcountry.value;
        		thisForm.shippostalcode.value = thisForm.billpostalcode.value;
        		thisForm.shipphone.value = thisForm.billphone.value;
		}
		
		else { //not checked - clear shipping info
			thisForm.shipname.value = '';
			thisForm.shipaddress1.value = '';
        		thisForm.shipaddress2.value = '';
        		thisForm.shipcity.value = '';
        		thisForm.shipstate.value = '';
        		thisForm.shipcountry.value = '';
        		thisForm.shippostalcode.value = '';
			thisForm.shipphone.value = '';
		}
		
	}
	
    
	function finalizeOrder() {
		if ( get("agreeToTerms").checked ) {
			goToURL("/shoppingcart/finalizeWait");
		}
		else {
			alert('You must check the box above the Finalize Order button, agreeing to the Fare Rules & Terms of Use');
		}
	}
	
	function showFinalizeTimeoutWarning() {
	    alert('We\'re sorry, we could not get confirmation for your flight from the airline, so you have not yet purchased a ticket for this flight.  Please contact us at '+offHours.phoneTollfreeUS+' (outside the U.S. '+offHours.phoneOutside+') to book this flight. See office hours below: \n\n'+offHours.hoursWeekdays+'\n'+offHours.hoursWeekends+'\n'+offHours.alternative+'');
	}
	
	function showOptions(query){
    document.airOptionsForm.deal.value=query;
    document.airOptionsForm.submit();
}
	
	function selectOption(query, outindex, inindex){
    document.airOptionsForm.deal.value=query;
    document.airOptionsForm.inboundOption.value=inindex;
    document.airOptionsForm.outboundOption.value=outindex;
    document.airOptionsForm.submit();
}

function buyNow(uuid) {
		
	$("BUTTON.selectButton").attr("disabled", "disabled"); //disable double clicks
	
	showWaitMsg("Adding flight to cart");
    url="/nospring/ajax/addToCart?outboundIndex=0&inboundIndex=0&itinUUID="+uuid;
	xmlBasicRequest(url,addedToCart);
}

function replaceItinerary(itinUUID) {
	updatedItinID="itinerary-"+itinUUID;
	if ( get("thisItineraryHTML") ) {
		get(updatedItinID).innerHTML=get("thisItineraryHTML").innerHTML;
		layoutPage();
	}
}

function join(signUpStartForm) {
	hideErrors("error");
	var errorMsg = "";
	if(document.getElementById("firstName").value == null 
	|| document.getElementById("firstName").value.replace(/ /,"") == ""){
		errorMsg = errorMsg + "fname:Please enter your first name.";
	}else if(! validateName(document.getElementById("firstName").value)) {
		errorMsg = errorMsg + "\nfname:Enter a valid first name.";
	}
	
	if(document.getElementById("lastName").value == null 
	|| document.getElementById("lastName").value.replace(/ /,"") == ""){
		errorMsg = errorMsg + "\nlname:Please enter your last name.";
	}else if(! validateName(document.getElementById("lastName").value)) {
		errorMsg = errorMsg + "\nlname:Enter a valid last name.";
	}
	var emailFilter=/^.+@.+\..+$/;
	if(document.getElementById("signUpEmail").value == null 
	|| document.getElementById("signUpEmail").value.replace(/ /,"") == ""
	|| document.getElementById("signUpEmail").value.indexOf("@") < 0
	|| !(emailFilter.test(document.getElementById("signUpEmail").value))){
		errorMsg = errorMsg + "\nemail1:Please enter a valid email address.";
	}
	if(errorMsg != '') {
		showErrors("error",errorMsg);
	}else {
		var fName = document.getElementById("firstName").value;
		var lName = document.getElementById("lastName").value;
		var signUpEmail = document.getElementById("signUpEmail").value;

		var invalidCharMsg = "<br><a href=\"javascript:popupWindow('/popups/acceptableChars.jsp',500,200,'scrollbars')\">Click</a> for acceptable characters.";
		
		var returnFunction1 = function(returnMsg1) {
	
			if ( returnMsg1.indexOf("invalidFLName") >= 0 ){
				errorMsg = errorMsg + "\nfname:Please enter a valid first name."+invalidCharMsg;
				errorMsg = errorMsg + "\nlname:Please enter a valid last name."+invalidCharMsg;
			}
			if ( returnMsg1.indexOf("invalidFName") >= 0 ){
				errorMsg = errorMsg + "\nfname:Please enter a valid first name."+invalidCharMsg;
			}
			if ( returnMsg1.indexOf("invalidLName") >= 0 ){
				errorMsg = errorMsg + "\nlname:Please enter a valid last name."+invalidCharMsg;
			}
			if(returnMsg1.indexOf("invalidEmail") >= 0 ){
				errorMsg = errorMsg + "\nemail1:Please enter a valid email address.";
			}
			if(returnMsg1.indexOf("dupEmail") >= 0 ){
				errorMsg = errorMsg + "\nemail1:Email in use, please login.";
				document.getElementById("loginEmail").value = signUpEmail;
			}
			if(errorMsg != ""){
					showErrors("error",errorMsg);
			}else{
				    url="/register/new?firstName="+fName+"&lastName="+lName+"&email="+signUpEmail;
					goToURL(url);
			}
		
		}
		submitAjaxFromQuery("checkName",returnFunction1,"POST","firstname="+fName+"&lastname="+lName+"&signUpEmail="+signUpEmail,"Checking Name");
		
		
		
	}
}

function addedToCart(returnMsg) {
	if ( returnMsg.indexOf("error") >= 0 ) {
		goToURL("/airItemCartError.html");
	}
	else if ( returnMsg == "login" ) goToURL("/register");
	else goToURL(views["cart"]);
	//else hideWaitMsg();
}

function submitAjaxForm(formObj) {
	params=getParams(formObj);
	url=formObj.action+params;
	returnFunction=eval(formObj.target);
	xmlBasicRequest(url,returnFunction,formObj.method,false);
}

function updateProfileReturn(returnMsg) {
	if ( returnMsg.indexOf("success") >= 0 ) replaceURL("/");
	else showErrors("errorTop",returnMsg,true);
}

function showErrors(errorClass,errorReturnMsg,showPrompt) {
	currentErrors=getElementsByClassName(document,'*',errorClass);
	for ( var i=0 ; i < currentErrors.length ; i++ ) {
		currentErrors[i].style.display="none";
	}
	errors=errorReturnMsg.split("\n");
	for ( var i=0 ; i < errors.length ; i++ ) {
		thisError=errors[i];
		if ( thisError.indexOf(":") >= 0 ) {
			firstColon=thisError.indexOf(":");
			errorField=thisError.substring(0,firstColon);
			errorMsg=thisError.substring(firstColon+1);
			//errorMsg=thisError.split(":")[1];
			errorDiv="errorField-"+errorField;
			if ( get(errorDiv) ) {
				get(errorDiv).innerHTML=errorMsg;
				get(errorDiv).style.display='block';
			}
		}
	}
	layoutPage();
	scroll(0,0);
	if ( showPrompt ) {
		showElement("error-message");
	}
}

function hideErrors(errorClass) {
	currentErrors=getElementsByClassName(document,'*',errorClass);
	for ( var i=0 ; i < currentErrors.length ; i++ ) {
		currentErrors[i].style.display="none";
	}
}

function billShipReturn(returnMsg) {
	if ( returnMsg.indexOf("success") >= 0 ) goToURL("/shoppingcart/reviewOrder");
	else if ( returnMsg.indexOf("error:null invoice id") == 0 ) {
		goToURL("/cart/expired.jsp");
	}else if(returnMsg.indexOf("booked") >= 0){
		goToURL("/shoppingcart/finalizeWait");
	}
	else {//check expected error msg
		if(returnMsg.indexOf("cvv:") >=0 ||
		returnMsg.indexOf("passengerPhone:")>=0 ||
		returnMsg.indexOf("passengerCellPhone:")>=0 ||
		returnMsg.indexOf("email:")>=0 ||
		returnMsg.indexOf("nameoncard:")>=0 ||
		returnMsg.indexOf("cardtype:")>=0 ||
		returnMsg.indexOf("cardnumber:")>=0 ||
		returnMsg.indexOf("expiryyear:")>=0 ||
		returnMsg.indexOf("billcountry:")>=0 ||
		returnMsg.indexOf("billaddress1:")>=0 ||
		returnMsg.indexOf("billaddress2:")>=0 ||
		returnMsg.indexOf("billcity:")>=0 ||
		returnMsg.indexOf("billstate:")>=0 ||
		returnMsg.indexOf("billpostalcode:")>=0 ||
		returnMsg.indexOf("billingPhone:")>=0 ||
		returnMsg.indexOf("promotionCode:")>=0 
		){
			if (returnMsg.indexOf("cardnumber:") < 0 && get("cardnumber").value.length == 0 ) 
				returnMsg += "cardnumber:Please re-enter your credit card number.\n";
			showErrors("errorTop",returnMsg,true);
			get("error-message").innerHTML="Please correct the errors found below";
			get("error-message").style.margin="0 0 0 200px";
			get("error-message").style.display="block";
		}else{//not expected?
			goToURL("/cart/expired.jsp");
		}
	}
}

function chooseProgram(destContentName,programIndex) {
	document.requestToPayChooser.destContentName.value=destContentName;
	document.requestToPayChooser.programIndex.value=programIndex;
	document.requestToPayChooser.submit();
}

function buyAirItem(airItemID){
    var returnFunction=function(returnMsg) {
		if ( returnMsg.indexOf("redirect") == 0 ) {
			var bookingURL = returnMsg.substring(9);
			get("orbitzURL").value = bookingURL;
			get("redirectToOrbitzForm").submit();
		}
		else if ( returnMsg == "eticket" || returnMsg == "billship" ) goToURL("/shoppingcart/billShip");
		else if ( returnMsg == "error" ) goToURL("/airItemCartError.html");
	}
	var query="airItemID="+airItemID;
	submitAjaxFromQuery("buyAirItem",returnFunction,"POST",query,"Proceeding to checkout");
}

function setSessionData(name,value) {
	url="/nospring/ajax/setSessionData?name="+name+"&value="+value;
	xmlBasicRequest(url,nullFunction);
}

function nullFunction(returnMsg) {}

function getParams(obj) {
      //var getstr="?";
      var getstr="";
      
	  for (var i=0; i < obj.getElementsByTagName("input").length ; i++) {
			inputObj=obj.getElementsByTagName("input")[i];
			if (inputObj.type == "text" || inputObj.type == "hidden" || inputObj.type == "password" ) {
               getstr += inputObj.name+"="+inputObj.value+"&";
            }
            if (inputObj.type == "checkbox") {
               if (inputObj.checked) {
                  getstr += inputObj.name+"="+inputObj.value+"&";
               }
            }
            if (inputObj.type == "radio") {
               if (inputObj.checked) {
                  getstr += inputObj.name+"="+inputObj.value+"&";
               }
            }
	  }
	  for (var i=0; i < obj.getElementsByTagName("select").length ; i++) {
			var sel=obj.getElementsByTagName("select")[i];
			if ( sel.options.length > 0 ) {
				getstr += sel.name+"="+sel.options[sel.selectedIndex].value+"&";
			}  
	  }
      return getstr;
   }

function focusOnField() {
	if (document.form1.email.value == '') 
		document.form1.email.focus();
	else if (document.form1.firstname.value == '') 
		document.form1.firstname.focus();
	else if (document.form1.lastname.value == '') 
		document.form1.lastname.focus();
	else if (document.form1.universityLocationID.value == '') 				
		document.form1.universityLocationID.focus();
	else if (document.form1.universityCountryID.value == '') 			
		document.form1.universityCountryID.focus();		
	else if (document.form1.universityID.value == '') 				
		document.form1.universityID.focus();
}

function monitorFields() {
	if (document.form1 != null && document.form1.universityLocationID != null && document.form1.universityLocationID.options != null && document.form1.universityLocationID.options.length > 1 
	 && document.form1.universityLocationID.selectedIndex == 0
	 && document.form1.universityID.options[document.form1.universityID.options.selectedIndex].value == '-1') {
    	resetUniv();
	}
}

// ***************************** GENERAL UTILITIES ***************************** //

// this defines which url patterns should be sent to a secure page - all others, forced to insecure
var securePages=new Array("/shoppingcart/","/register","/study/requestToPay","confirmJoin.html","/membership/updatePassword","ambassador.html");

// THIS TAKES A RELATIVE URI and determines its correct scheme, returning the correct full url with updated scheme, host, and uri
function fullPathToMe(uri) {
	var correctHost=insecureHost;
	var securePage=false; 
	for ( var i=0 ; i < securePages.length; i++ ) {
		if ( uri.indexOf(securePages[i]) >= 0 ) {
			correctHost=secureHost;
			securePage=true;
			break;
		}
	}
	fullPath=correctHost+uri;
	if ( securePage && secureHost.indexOf("https") != 0 && fullPath.indexOf("#secure") < 0 ) {
		fullPath += "#secure";
	}
	return fullPath;
}

function getFullPathCurrentScheme(url) {
	if ( window.location.href.indexOf(secureHost) == 0 ) hostToUse=secureHost;
	else hostToUse=insecureHost;
	var uri=getURI(url);
	return hostToUse+uri;
}

function getURI(url) {
	if ( url.indexOf("http") == 0 ) return url.substring(url.indexOf("/",8));
	else return url;
}

// THIS TAKES A FULLY QUALIFIED URL (from link href) and determines its correct scheme, returning the correct full url with updated scheme
function resolveScheme(url) {
	// abort if this isn't a regular url ("javascript:" or something)
	if ( url.indexOf("http") != 0 ) return url; 
	// abort if this url isn't on the current domain (external link)
	else if ( url.indexOf(insecureHost) != 0 && url.indexOf(secureHost) != 0 ) return url;
	var uri=getURI(url);
	return fullPathToMe(uri);
}

function goToURL(uri) {
	window.location.href=fullPathToMe(uri);
}

function replaceURL(uri) {
	window.location.replace( fullPathToMe(uri) );
}

function getElementsByTagName(tagName) {
	elementList=document.getElementsByTagName(tagName);
	elementArray=new Array();
	for ( var i=0 ; i < elementList.length ; i++ ) {
		elementArray.push(elementList[i]);
	}
	return elementArray;
}

function switchStyles(selector) {
	url=window.location.href;
	if ( url.indexOf('?stylesheet=') > 0 ) {
		url=url.substring(0,url.indexOf('?stylesheet='));
		url += '?stylesheet='+ selector.options[selector.selectedIndex].value;
	}
	else if ( url.indexOf('?') > 0 ) {
		url += '&stylesheet='+ selector.options[selector.selectedIndex].value;
	}
	else {
		url += '?stylesheet='+ selector.options[selector.selectedIndex].value;
	}
	window.location=url;
}

function classMatches(element,classToMatch) {
	if ( element.className && 
		 element.className == classToMatch ||
		 element.className.indexOf(" "+classToMatch) >= 0 ||
		 element.className.indexOf(classToMatch+" ") >= 0 ) {
		return true 
	}
	else return false;
}

function prepopGatewayPageSearch(inboundAPCode) {
	switchToRoundTrip();
	SearchForm.setInboundAirport(inboundAPCode);
	get("inboundAirport").value = inboundAPCode;
}

function lookupCodes(anchorTag) {
	now=new Date();
	dataURL=anchorTag.href+"&time="+now.getTime();
	xmlBasicRequest(dataURL,showCodes);
}

function showCodes(htmlResponse) {
	$(".facebox").each(
		function (){
			if($(this).css("display")!="none"){
				var o = $(this).find("#codesArea");
				if(o){
					o.html(htmlResponse);
					//get("codesArea").innerHTML=htmlResponse;
					//popup page add scroll bar
					$(this).find(".scroll-pane").jScrollPane({showArrows:true, scrollbarWidth:17});
				}
			}
		}
	);	
}

var debugTimerStartTime;

function timerStart() {
	debugTimerStartTime=new Date();
}

function timerEnd() {
	endTime=new Date();
	totalTime=endTime.getTime() - debugTimerStartTime.getTime();
	window.status=totalTime;
}

function removeElement(element) {
	element.parentNode.removeChild(element);
}

/*function cleanUpForIE() {
	if ( isIE() ) {
		var sliders=getElementsByClassName(document,'IMG',"slider");
		for ( var i = 0 ; i < sliders.length ; i++ ) {
			sliders[i].sliderObj = null;
		}
	}
}*/

function trackEchoTarget(inboundAirport) {
	var echoIframe = get("echoTargetIframe");
	if ( echoIframe ) {
		var echoURL = "http://pbid.pro-market.net/engine?site=sud" + inboundAirport + "+size=1x1";
		echoIframe.src = echoURL;
	}
}

function convertToInteger(string) {
	return parseInt(string,10);
}

function searchHotelsToo(apCode,outboundDate,inboundDate,tripType) {
	var days = 3;
	if ( tripType > 1 ) {
		var timeDiff = inboundDate.getTime() - outboundDate.getTime();
		days = timeDiff / (24*60*60*1000);
	}
	days = Math.min(days,3);
	var url = "/includes/hotelsWait.jsp?airport=" + apCode + "&date=" + outboundDate.getTime() + "&days=" + days;
	openComparePopup(0,url,"Search_Hotels_Too");
}

function openComparePopup(index,compareURL,windowLabel) {
	var width = Math.floor(screen.width * 0.5 );
	var height = Math.floor(screen.height * 0.5 );
	var left = (screen.width - width - 180 ) + ( index * 50);
	var top = index * 50;
	var options = "width="+width+",height="+height+",left="+left+",top="+top+",screenX="+left+",screenY="+top+",resizable,scrollbars,location,directories,status,titlebars,menubar";
	var thisPopup = window.open(compareURL,windowLabel,options);
}

function compareToSite(website,index,method) {
	var compareURL = "/fly/compareSearch.jsp?website=" + website +"&method=" + method;
	var windowLabel = "Search_" + website;
	
	if ( index != -1 ) {
		windowLabel = "Search" + index;
	}
	else {
		index = 0;
	}
	
	openComparePopup(index,compareURL,windowLabel);
}

function compareTo(website,method) {
	if ( website != "null" ) {
		compareToSite(website, -1, 'link');
		return;
	}
	
	var checkedSites = $("input.compareToLink:checked");
	var num_checked = checkedSites.length; // number of checked

	var random_num = new Array(num_checked+1);
	var compare_arr = new Array(num_checked);
	
	for ( i = 0 ; i < num_checked; i++ ) {
		var thisCheckbox = checkedSites[i];
		compare_arr[i] = thisCheckbox.alt;
	}
	
	for (i = 1; i < num_checked+1; i++) {
		random_num[i] = i;
	}
	//Shuffling the numbers in the array
	for (i = 1; i < num_checked+1; i++) {
		newnumber = (Math.random() * num_checked) + 1;
		newnumber = parseInt(newnumber, 10);
		temp = random_num[i];
		random_num[i] = random_num[newnumber];
		random_num[newnumber] = temp;
	}
	
	if(num_checked == 0){
		alert("You must select at least one site to compare results with.");
	}else{
		for (i = 1; i < num_checked+1; i++) {
			if(isSafari()||isChrome()){
				setTimeout(compareToSite(compare_arr[random_num[i]-1],(i-1),method),0);
			}else{
				setTimeout("compareToSite('"+compare_arr[random_num[i]-1]+"',"+(i-1)+",'" + method + "')",0);
		}
	}
	}

}
			
function upd_shortcn_img(img_src){
	if(img_src == 1){
	
		get("shortChinesePopupImg").src ="http://images.studentuniverse.com/zh_CN/images/buttons/shortchinese_blue.jpg";
	}else{
	
		get("shortChinesePopupImg").src ="http://images.studentuniverse.com/zh_CN/images/buttons/shortchinese_black.jpg";	
	}


}			

function getURLParam(href, strParamName){
  var strReturn = "";
  var strHref = href;
  if ( strHref.indexOf("?") > -1 ){
    var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
    var aQueryString = strQueryString.split("&");
    for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
      if (aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1 ){
        var aParam = aQueryString[iParam].split("=");
        strReturn = aParam[1];
        break;
      }
    }
  }
  return unescape(strReturn);
}

function updateHref(){
	if(get("loginEmail") != null && get("loginEmail").value.replace(" ","") != "" ){
		if(get("login-page-forgotPassword") != null){
			get("login-page-forgotPassword").href = get("login-page-forgotPassword").href +"?email="+get("loginEmail").value.replace(" ","");
		}	
	}
}


function sendSabreEmail() 
{
	var sendBtn = get("sendEmailButton");
	var sendBtnText = sendBtn.innerHTML + "";
	var returnFunction=function(returnMsg) {
        var json = eval("new Object(" + returnMsg + ")")
        if ( json.returnMsg == "Success" ) {
            var msg = "<p>Success!  Email has been sent!</p>";
			get("returnMsg").innerHTML = msg;
            get("returnMsg").className = "success";
            sendBtn.style.display = "none";
		}else if( json.returnMsg == "ERROR" ) {
            sendBtn.className = "";
            sendBtn.innerHTML = sendBtnText;
            get("returnMsg").innerHTML = "Error sending email: " + json.returnMSG;
            get("returnMsg").className = "failure";
        }else {
			var msg = "<p>Sending Email Now..</p>";
			get("returnMsg").innerHTML = msg;
            sendBtn.style.display = "none";
        }
    }

	if ( sendBtnText == "SEND" ) {
	
		var validated=new Boolean(false);
		var email = get("sendEmailForm").emailtextarea.value;
		email = email.replace(/^\s+|\s+$/g, '') ;
		email = email.replace('\n', ',');

		var email_array=email.split(",");
		var part_num=0;
		
		while (part_num < email_array.length)
		 {
		  var emailString = email_array[part_num];
		  
		  part_num+=1;
		  emailString = emailString.replace(/ /g,"");;
		  
     	  validated = checkEmail(emailString);
		}
		
		if( validated) {  
			var pnr = document.getElementById("pnr").value;
			var invoiceId = document.getElementById("invoiceId").value;
			var charged = document.getElementById("charged").value;
			var query = "pnr=" + pnr;
			query = query + "&emails=" + email;
			query = query + "&invoiceId=" + invoiceId;			
			if(charged == 'false'){
				submitAjaxFromQuery("sendSUConfirmationEmail",returnFunction,"GET",query);
			} else {
				submitAjaxFromQuery("addNSendSabreEmail",returnFunction,"GET",query);
			}
		}
		else{
			sendBtn.className = "";
            sendBtn.innerHTML = sendBtnText;
            get("returnMsg").innerHTML = "Please correct your email address(es)";
            get("returnMsg").className = "failure";
		}
		
	}
	
}


/**--------------------------
//* Check email address format
---------------------------**/
function checkEmail(emailAddress) {
	var at="@"
	var dot="."
	var lat=emailAddress.indexOf(at)
	var lstr=emailAddress.length
	var ldot=emailAddress.indexOf(dot)
	if (emailAddress.indexOf(at)==-1){
	   alert("Please enter a valid email address")
	   return false
	}
	
	if (emailAddress.indexOf(at)==-1 || emailAddress.indexOf(at)==0 || emailAddress.indexOf(at)==lstr-1){
	   alert("Please enter a valid email address")
	   return false
	}
	
	if (emailAddress.indexOf(dot)==-1 || emailAddress.indexOf(dot)==0 || emailAddress.indexOf(dot)==lstr-1){
	    alert("Please enter a valid email address")
	    return false
	}

	 if (emailAddress.indexOf(at,(lat+1))!=-1){
	    alert("Please enter a valid email address")
	    return false
	 }

	 if (emailAddress.substring(lat-1,lat)==dot || emailAddress.substring(lat+1,lat+2)==dot){
	    alert("Please enter a valid email address")
	    return false
	 }

	 if (emailAddress.indexOf(dot,(lat+2))==-1){
	    alert("Please enter a valid email address")
	    return false
	 }
	
	 if (emailAddress.indexOf(" ")!=-1){
	    alert("Please enter a valid email address")
	    return false
	 }
	 
	 return true					
}
function officeHoursLoad(){
	$("span.phoneTollfreeUS").html(offHours.phoneTollfreeUS);
	$("span.phoneTollfreeUK").html(offHours.phoneTollfreeUK);
	$("span.phoneOutside").html(offHours.phoneOutside);
	$("span.hoursWeek").html('<br><b>See office hours below:</b><br>'+offHours.hoursWeekdays +'<br> '+offHours.hoursWeekends+'<br>'+offHours.alternative+'<br>');
}

function updateVerifiedStatus(){
	$("#checkingStatus, #penddingVerify").attr("onclick","").unbind();
	//$("#penddingVerify").css("float","left");
	//$("#verifyWait").show();
	//$("#checkingStatusWait").show();
	$.ajax({
		url: '/nospring/ajax/updateVerifyStatus',
		type: 'POST',
		dataType: 'json',
		error: function(){
			//$("#verifyWait").hide();
			//$("#checkingStatusWait").hide();
			//$("#penddingVerify").css("float","right");
			$("#checkingStatus, #penddingVerify").bind("click",updateVerifiedStatus);
		},
		success: function(json){
			//$("#verifyWait").hide();
			//$("#checkingStatusWait").hide();
			if(json.success=="true"){
				$("#checkingStatus, #penddingVerify, #verifyWait, #checkingStatusWait").hide();
				$("#checkVerificationSuccess").show();
				clearInterval(autocheckVerifiedStatus);
				autocheckVerifiedStatus = null;
				$("#veriedUserPopupWindow").click();
				setTimeout(function(){
					var checkReloadPage = setInterval(function(){
						if(!($("#facebox_overlay") != null && $("#facebox_overlay").css("display") != null 
								&& ($("#facebox_overlay").css("display") == "" || $("#facebox_overlay").css("display") == "block"))){
							clearInterval(checkReloadPage);
							window.location.reload();
						}
					}, 1000);
				},100)
				return false;
			}else{
				//$("#penddingVerify").css("float","right");
				$("#checkingStatus, #penddingVerify").bind("click",updateVerifiedStatus);
				return false;
			}
		}
	});
	return false;
}

function verifyMe(){
	$(".verifyMeButton").attr("onclick","").unbind().removeClass("verifyMeButton").addClass("verifyMeDisableButton");
	$(".orMessage").hide();
	$(".verifyMeDisableButton").attr("disabled", "disabled")
	$.ajax({
		url: '/nospring/ajax/verifyMe',
		type: 'POST',
		dataType: 'json',
		error: function(){},
		success: function(json){
			if(json.success=="true"){
				$("#notVerifyingMeInfo").hide();
				$("#isVerifyingMeInfo").show();
				$("#penddingVerify").show();
				$("#verifyWait").show();
				$("#verificationProcessInfo").show();
				//verifyOnlyUpdateTime define in appData.jsp
				if(parseInt(verifyOnlyUpdateTime)>0 && autocheckVerifiedStatus == null){
					autocheckVerifiedStatus = setInterval(updateVerifiedStatus, verifyOnlyUpdateTime);
				}
			}else{
				$(".verifyMeDisableButton").removeAttr("disabled").removeClass("verifyMeDisableButton").addClass("verifyMeButton").bind("click",verifyMe);
				$(".orMessage").show();
			}
		}
	});
	return false;
}


// ***************************** init functions ***************************** //

onLoad = function() { this.funcStack = new Array(); this.tasksRan = false; }

onLoad.prototype = {
    funcStack: null,
	tasksRan: null,
	
	add: function(funcObj) {
        this.funcStack.push(funcObj);
    },
	
	unshift: function(funcObj) {
        this.funcStack.unshift(funcObj);
    },
	
	run: function() {
		if ( !this.tasksRan ) {
			for ( var i = 0 ; i < this.funcStack.length ; i++ ) {
				thisFunc = this.funcStack[i];
				if (undefined != thisFunc) thisFunc();
			}
			this.tasksRan = true;
		}
	}
	
}

windowLoadTasks = new onLoad();
windowLoadTasks.add(layoutPage);
windowLoadTasks.add(initTextPrompts);
windowLoadTasks.add(sessionTimer);


var aryClassElements = new Array();
function getLoopElementsByClassName( strClassName, objBody ) {
    if ( objBody.className == strClassName ) {
        aryClassElements[aryClassElements.length] = objBody;
    }
    for ( var i = 0; i < objBody.childNodes.length; i++ )
        getLoopElementsByClassName( strClassName, objBody.childNodes[i] );
}

suTransaction = new Object();suInvoiceItem = new Object();suInsuranceItem = new Object();
function googleSetTrans() {
	pageTracker._addTrans(suTransaction.invoiceNumber,suTransaction.affiliation,suTransaction.total,suTransaction.tax,suTransaction.shipping,suTransaction.billCity,suTransaction.billState,suTransaction.billCountry);
	pageTracker._addItem(suInvoiceItem.invoiceNumber,suInvoiceItem.pnr,suInvoiceItem.productName,suInvoiceItem.tripType,suInvoiceItem.conversionValue,suInvoiceItem.quantity);
	if ( suInsuranceItem.invoiceNumber ) {
		pageTracker._addItem(suInsuranceItem.invoiceNumber,suInsuranceItem.policyNumber,suInsuranceItem.productName,suInsuranceItem.category,suInsuranceItem.insuranceTotal,suInsuranceItem.quantity);
	}
	pageTracker._trackTrans();
}

function initTextPrompts() {
	setTextPrompt("outboundAirport",""," City name or code");
	setTextPrompt("inboundAirport",""," City name or code");
	setTextPrompt("outboundJawAirport",""," City name or code");
	setTextPrompt("inboundJawAirport",""," City name or code");
	setTextPrompt("email",""," Enter your email");
	
	setTextPrompt("groupEmail",""," For Confirmation");
	getLoopElementsByClassName( 'groupFirstName', document.body );
	promptVal = " First";
    for ( var i = 0; i < aryClassElements.length; i++ ) {
        if ( aryClassElements[i].value == "" )  aryClassElements[i].value = promptVal;
    }
    getLoopElementsByClassName( 'groupMiddleName', document.body );
    promptVal = " Middle (optional)";
    for ( var i = 0; i < aryClassElements.length; i++ ) {
        if ( aryClassElements[i].value == "" )  aryClassElements[i].value = promptVal;
    }
    getLoopElementsByClassName( 'groupLastName', document.body );
    promptVal = " Last";
    for ( var i = 0; i < aryClassElements.length; i++ ) {
        if ( aryClassElements[i].value == "" )  aryClassElements[i].value = promptVal;
    }
    
}

function needTimeout() {
	var uri = getURI(window.location.href);
	if ( (loggedIn || hasResults || (uri.indexOf("/fly/airsearchResults") == 0)) && (uri.indexOf("/shoppingcart/printitinerary") != 0) && (uri.indexOf("/shoppingcart/final") != 0) ) {
		return true;
	}
	else return false;
}

var checkSessionTimer;
var warningShown = false;

function sessionTimer() {
	if ( needTimeout() ) checkSessionTimer = setTimeout("checkSession()",sessionWarningPeriod);
}

function checkSession() {
	submitAjax("sessionTimer",reactToSessionTimeLeft,null,null,null);
}

function reactToSessionTimeLeft(thisData) {
	if ( thisData == "expired" ) goToURL("/sessionExpired.html");
	else sessionTimer();
}

function getNowDate() {
	return new Date();
}

function unitSpec(number,singularTxt,pluralTxt) {
	if ( number == 1 ) return singularTxt;
	else return pluralTxt;
}

function keepAlive() {
	if ( needTimeout() ) {
		submitAjax("keepAlive",reactToSessionTimeLeft,null,null,null);
	}
}

function setTextPrompt(inputObjID,emptyVal,promptVal) {
	inputObj = get(inputObjID);
	
	// this semi-hack prevents setting prompt for non-newsletter fields labeled "email"
	if ( inputObjID == "email" && inputObj && inputObj.form.id != "newsletter" ) return;
	
	if ( inputObj && inputObj.type == "text" ) {
		if ( inputObj.value == emptyVal ) inputObj.value = promptVal;
		else if ( inputObj.id.indexOf("Airport") >= 0 &&  inputObj.value.length == 3 ) {
			//var varID = inputObj.id + "";
			//get(varID).value = inputObj.value;
		}
	}
}

function initUniversityDropdowns() {
	var selectTags = getElementsByTagName("select");
	if ( selectTags && selectTags.length > 0 ) {
		for ( i = 0 ; i < selectTags.length ; i++ ) {
			thisSelectTag = selectTags[i];
			if ( thisSelectTag.id == "universityCountryID" ) {
				thisSelectTag.onchange = function() { loadStates(this) };
			}
			else if ( thisSelectTag.id == "universityLocationID" ) {
				thisSelectTag.onchange = function() { loadUnivs(this) };
			}
			else if ( thisSelectTag.id == "dobMonth" ) {
				thisSelectTag.onchange = function() { loadDays(this) };
			}
		}
	}
}


/* Script by GalaSoft Laurent Bugnion */
/* 27.01.2001                         */
/* www.galasoft-LB.ch                 */

var cookiePath = '/';

// Cookie functions ---------------------------------------------------------
// Thanx a lot to Jerry Aman, Optima System
// and Bill Dortch, hIdaho Design for the free use of their code.
// Found on http://www.cookiecentral.com/js_cookie8.htm

//---------------------------------------------------------------------------
// Utility function to get the cookie's value

function getCookieVal( offset )
{
  var endstr = document.cookie.indexOf ( ";", offset );

  if ( endstr == -1 )
  {
    endstr = document.cookie.length;
  }
  return unescape( document.cookie.substring( offset, endstr ) );
}

//---------------------------------------------------------------------------
// Returns the value of a cookie corresponding to the name
// Returns null if the cookie can't be found

function getCookie( name )
{
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;
  while ( i < clen )
  {
    var j = i + alen;

    if ( document.cookie.substring( i, j ) == arg )
    {
      return getCookieVal ( j );
    }

    i = document.cookie.indexOf( " ", i ) + 1;

    if ( i == 0 )
    {
      break;
    }
  }
  return null;
}

//---------------------------------------------------------------------------
// Sets a cookie according to the name and value.
// Optional parameters:
// - expires (Date object)
// - path (use cookiePath for the whole domain)
// - domain
// - secure
// For more information about those parameter, check www.cookiecentral.com

function setCookie( name, value )
{
  var argv = setCookie.arguments;
  var argc = setCookie.arguments.length;
  var expires = (argc > 2) ? argv[2] : null;
  var path = (argc > 3) ? argv[3] : null;
  var domain = (argc > 4) ? argv[4] : null;
  var secure = (argc > 5) ? argv[5] : false;

  document.cookie = name + "=" + escape (value) +
    //( ( expires == null ) ? "" : ( "; expires=" + expires.toGMTString() ) ) +
    ( ( path == null ) ? "" : ( "; path=" + path ) ) +
    ( ( domain == null ) ? "" : ( "; domain=" + domain ) ) +
    ( ( secure == true ) ? "; secure" : "" );
}

function deleteCookie ( name ) {
  var exp = new Date();
  exp.setTime ( exp.getTime() - 1 );  // This cookie is history
  setCookie( name,"",exp,cookiePath);
}


//---------------------------------------------------------------------------
// Tests if cookies are enabled.

function testCookie() {
  var expDate = new Date();
  expDate.setTime( expDate.getTime() + ( 60000 ) ); //valid one minute
  setCookie("testCookie","OK",expDate);
  testing = getCookie( "testCookie" );
  
  if ( testing == "OK" ) return true;
  else return false;
}

if ( !testCookie() ) {
	replaceURL("/cookiesRequired.html");
}else {
	deleteCookie("testCookie" );
}
