var myCookies = new Array();
if (document.cookie.length > 0) {
 tempcookies = document.cookie.split(';');
	for (var cookie = 0; cookie < tempcookies.length; cookie++) {
		var oneCookie = tempcookies[cookie].split('=');
		var cookieName = oneCookie[0].replace(/^\s+|\s+$/, '');
		myCookies[cookieName] = oneCookie[1];
	}
}

function HPSearch(frm) { if_queryForm(frm); return true; }

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}
String.prototype.commafy = function() { 
	return this.replace(/(\D?)(\d{4,})/g, function($0, $1, $2) { 
			return /[.\w]/.test($1) ? $0 : $1 + $2.replace(/\d(?=(?:\d\d\d)+(?!\d))/g, '$&,'); 
	}); 
}; 
Number.prototype.commafy = function() { 
	return String(this).commafy(); 
};


function elevenLength(MPNO) {
    var id = TrimString(MPNO.value);
    if (MPNO && id!="" && id.length < 11) {
        while (id.length < 11) {
            id="0"+id;
        }
		MPNO.value = id;
    }
}

function isDigit(c) {
    return((c>="0")&&(c<="9"))
}

function IsNumeric(a,addChars) {
    var i;
    if (a.value.length == 0) {
        return true;
    }
    for(i=0;i < a.value.length;i++) {
        var c=a.value.charAt(i);
        if (!isDigit(c) && !isCharInString(c,addChars)) {
            return false;
        }
    }
    return true;
}

function IsUserIdNumeric(a,addChars) {
    var i;
	var id = TrimString(a.value);
    if (id.length == 0) {
        return true;
    }
    for(i=0;i < id.length;i++) {
        var c = id.charAt(i);
        if (!isDigit(c) && !isCharInString(c,addChars)) {
            return false;
        }
    }
    return true;
    }


function isCharInString(sc,s) {
    return(!sc||!s)?false:(s.indexOf(sc)>-1)?true:false;
}

function isMpNumber(MPNO){
		 if(MPNO != null && MPNO.length == 11 && !(MPNO =="00000000000")) {
				var s = MPNO;
				var  w60count1 =0;
				var  w60count2 = 0;
				w60count1 = s.substring(0,1) * 5 +
							s.substring(1,2) * 4 +
							s.substring(2,3) * 3 +
							s.substring(3,4) * 2 +
							s.substring(4,5) * 7 +
							s.substring(5,6) * 6 +
							s.substring(6,7) * 5 +
							s.substring(7,8) * 4 +
							s.substring(8,9) * 3 +
							s.substring(9,10) * 2;

			 var w60remainder = w60count1 % 11;
			   w60count1 = w60count1/11;
			  if (w60remainder != 0){
			      w60count2 = 11 - w60remainder;
			   } else {
			      w60count2 = 0;
			   }
			  if (w60count2 == 10){
			   		w60count2 = 0;
			   }
			  if (w60count2 != s.substring(10)){
				  	return false;
			   } else { 
				return true; 
			   }
			}
			
	return false;
}


function remMP(name) 
{   
var today = new Date();
var expires = new Date();
   expires.setTime(today.getTime() + 1000*60*60*24*365*2)
   setCookie("getMP", name, expires);
}

function remEMAIL(email) {
var today = new Date();
var expires = new Date();
   expires.setTime(today.getTime() + 1000*60*60*24*365*2)
   setCookie("rememberEMAIL", email, expires);
}
function getCookie(Name) {
   var search = Name + "=";
   if (document.cookie.length > 0) { // if there are any cookies      
		offset = document.cookie.indexOf(search)       
		if (offset != -1) { 
			// if cookie exists         
	 		offset += search.length          
	 		// set index of beginning of value         
	 		end = document.cookie.indexOf(";", offset)          
	 		// set index of end of cookie value         
	 		if (end == -1)             
	 			end = document.cookie.length         
	 		return unescape(document.cookie.substring(offset, end))      
	 	}    
	 }
}

function setCookie(name, value, expire) {  
	var curCookie = name + "=" + escape(value) +
      ((expire) ? "; expires=" + expire.toGMTString() : "") + "; path=/";
//      ((domainmp) ? "; domain=" + domainmp : ""); 
	document.cookie = curCookie;
}

function deleteCookie(name,path) {
  if (getCookie(name)) {
    document.cookie = name + "=" + 
    ((path) ? "; path=" + path : "") +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}


/*updated chngbox to refer to passed form name rather than just form name=MileagePlus*/
function chngbox(f){
	if(f.remMP.checked == false){
	deleteCookie("getMP","/")
	deleteCookie("getMP");
	deleteCookie('rememberME');
	deleteCookie('rememberEMAIL');
	deleteCookie('rememberMP');
	}	else {
	// this is for retriving the mileage plus number.
		var gotMPno = getCookie("getMP");
	
		if (gotMPno != null) { 
		 if(f.userId.value) {
	 	 	f.userId.value=gotMPno;
		 }
		 f.remMP.checked=true;
		}
	}
}


/*function chngbox(f){
	if(f.remMP.checked == false){
	deleteCookie("getMP","/")
	}
	// this is for retriving the mileage plus number.
	var gotMPno = getCookie("getMP");
	if (gotMPno != null) { 
	 if(document.MileagePlus.userId.value) {
 	 	document.MileagePlus.userId.value=gotMPno;
	 }
	 document.MileagePlus.remMP.checked=true;
	}
}*/

function ValidateUserId (f) {	
	if (f.sel_return_to.value == "") {return false;}
	var MPNO = f.userId;
	var id = TrimString(MPNO.value);
	var cr='\n';
	var msg='';
	var isMP = false;
	var valid = true;
	var pwd = TrimString(f.password.value);
	if (id.length == 0) {
	    valid = false;
		msg='Mileage Plus # or email address is a required field. ' + cr; 
   	}
   	if (valid) {
   		var isNum = IsUserIdNumeric(MPNO, null);
	    if (isNum) {
		    isMP = true;
			elevenLength(MPNO);
			id = TrimString(MPNO.value);
	   	}
	   	if (isMP) {
	   		valid = isMpNumber(id);
	   		if (!valid) {
				msg='The Mileage Plus number you have entered is invalid. Please check the number and resubmit.' + cr;
			}
		}
		else {
		    valid = isEmail(id);
			if (!isMP & !valid) {
	    		msg='The Mileage Plus number or the email address you have entered is invalid. Please check the number or email address and resubmit.' + cr; 
	    	}
		}
	}
	if (pwd.length==0) {
		msg+='Password is a required field.' + cr    	
	}
	if (msg) {
        msg='Please Supply the Following:' + cr + cr + msg;
        alert(msg);
        return false;
    }
	f.action="https://www.ua2go.com/ci/DoLogin.jsp?stamp=NEWCOOKY*itn/ord=NEWREC,itn/air/united"+f.sel_return_to.value; 
	//if_queryForm(f); insight first tag, deactivated
	return true;
}

function isEmail(str) {
		var at="@";
		var dot=".";
		var lat=str.indexOf(at);
		var lstr=str.length;
		var ldot=str.indexOf(dot);
		if (str.indexOf(at)==-1) {
		   return false;
		}
		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr) {
		   return false;
		}
		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return false;
		}
		 if (str.indexOf(at,(lat+1))!=-1){
		    return false;
		 }
		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    return false;
		 }
		 if (str.indexOf(dot,(lat+2))==-1){
		    return false;
		 }
		 if (str.indexOf(" ")!=-1){
		    return false;
		 }

 		 return true;					
	}

function TrimString(_data) {
  return _data.replace(/^\s+|\s+$/g, '');
}

function bTrimString(sInString) {
  if ( sInString ) {
    sInString = sInString.replace( /^\s+/g, "" );// strip leading
    return sInString.replace( /\s+$/g, "" );// strip trailing
  }
}

function toggleGLL() {
document.getElementById('swnGLLform').style.display='inline';
document.getElementById('swnGLLtext').innerHTML='<img id="swnGLLarrow" src="'+writeSWNprotocol+'://www.united.com/ual/asset/swn_2007_loginarrowdown.gif" height="11" width="11" alt="">&nbsp;&nbsp;Login';
//document.getElementById('swnGLLnotamemtable').style.display='none';
}


function isDefined(variable){//alert("in isdefined with :"+variable+"\ngoing to return: "+(!(!( variable||false ))));
return (!(!( variable||false )))
//return eval('(typeof('+variable+') != "undefined");');
}

function embedGLL()		
{

var mpSummaryReturnToVal = "mpsummary"; 
var gllMyItinsPath = "https://www.ua2go.com/ci/Login.jsp?return_to=newitin";
if (window.currentUALsite)
	{ 
		if (currentUALsite == "US-EN") 
		{ 
			mpSummaryReturnToVal="mpsummary_us"; //used to append _us for mpsummary for US-EN customers
			gllMyItinsPath += "&navSource=LeftNav07&linkTitle=My+itineraries"; // domestic customers get IF tracking added
		}
	}

//Intl embedGLL patch SHD 02/11/2007
// start with generic link 
var redeemStr = '<tr><td valign="top" class="swnRelatedLinksgt">></td><td valign="top" class="swnRelatedLinksitem"><a href="http://www.united.com/page/article/0,6722,3831,00.html">Redeem miles</a></td></tr>';
var itinStr = '<tr><td valign="top" class="swnRelatedLinksgt">></td><td valign="top" class="swnRelatedLinksitem"><a href="'+gllMyItinsPath+'">View my itineraries</a></td></tr>';
//check for awardURL string--only defined in Intl sites.
if (typeof(awardURL) != 'undefined') {
	if(awardURL == null)
	{  //non-booking sites, suppress link
		redeemStr ="";
		itinStr = "";
	} else if (awardURL) { //intl booking site with link
		redeemStr = '<tr><td valign="top" class="swnRelatedLinksgt">></td><td valign="top" class="swnRelatedLinksitem"><a href="'+awardURL+'">Redeem miles</a></td></tr>';
	} 
}
		
// rcc patch begin
var isRedCarpet = false;
var rccURL = document.location.href;
rccURL = rccURL.toLowerCase();
if(rccURL.indexOf('/rcc/') != -1){isRedCarpet=true;}
// rcc patch end
// ua2go patch begin
var isAppServer = false;
var appServerURL = document.location.href;
appServerURL = appServerURL.toLowerCase();
if( (appServerURL.indexOf('www.ua2go.com') == -1) || (appServerURL.indexOf('travel.united.com') == -1) ){isAppServer=true;}
// ua2go patch end



//var profile=getCookie("rememberProfile");
//var issecure=getCookie("isSecure");
//if(profile!=undefined)
// var parsedValue=profile.split("||");
//if (issecure!= undefined && issecure=="true") {
	if (isDefined(myCookies["rememberProfile"]) && isDefined(myCookies["isSecure"]) && myCookies["isSecure"]=="true") {
		var profile=myCookies["rememberProfile"];
		profile = unescape(profile); 
 var parsedValue=profile.split("||");
var mpiNumber=parsedValue[0];
var firstName=parsedValue[1];
var lastName=parsedValue[2];
var mpLevel=parsedValue[3];
var mpBal=parsedValue[4];
var homeArpt=parsedValue[5];

var swnlogoutUrl = "https://www.ua2go.com/ci/Logout.jsp"; 
if (!isAppServer && !isRedCarpet)
	{swnlogoutUrl+='?static=true';}


if (document.location.href.indexOf("etc/webcheckin/nonrevenue") != -1) // for NRSA Logins
	{ swnlogoutUrl = "https://www.ua2go.com/etc/webcheckin/nonrevenue/logout.do"; } 


if (firstName.length <= 6) // hello firstName on one line
	{ document.write('<div id="swnGLLhello">Hello '+firstName+'</div>'); }
if ((firstName.length > 6) && (firstName.length <= 9))  // hello firstName on two lines
	{ document.write('<div id="swnGLLhello">Hello<br>	'+firstName+'</div>'); }
if (firstName.length > 9) // hello no name (name is too long 
	{ document.write('<div id="swnGLLhello">Hello</div>'); }

 
 
document.write('<div id="swnGLLstatus">'+mpLevel+'</div>'
+'<table border="0" cellpadding="0" cellspacing="0" width="100%">'
+'<tr><td valign="top" class="swnRelatedLinksgt">></td><td valign="top" class="swnRelatedLinksitem"><a href="https://www.ua2go.com/ci/Login.jsp?return_to='+mpSummaryReturnToVal+'">'+mpBal.commafy()+' miles</a></td></tr>'
+redeemStr
+itinStr
+'</table>'
+'<div id="swnGLLmyproflogout"><a href="https://www.ua2go.com/ci/UpdateProfile.jsp">My profile</a>&nbsp;<span id="swnGLLmyproflogoutPipe">|</span> <a href="'+swnlogoutUrl+'">Log out</a></div>'
);

}
else
{
document.write(
 '<div id="swnGLLid">' 
+'	<span id="swnGLLtext"><img id="swnGLLarrow" src="'+writeSWNprotocol+'://www.united.com/ual/asset/swn_2007_loginarrowright.gif" height="11" width="11" alt="" border="0">&nbsp;&nbsp;<a href="#" onmousedown="toggleGLL();">Login</a></span>'
+'</div>'
+'<div id="swnGLLform">'
+'	<form class="nospace" method="POST" action="https://www.ua2go.com/ci/DoLogin.jsp?stamp=NEWCOOKY*itn/ord=NEWREC,itn/air/united&return_to=ff_acct_hist" name="MileagePlus" onSubmit="return ValidateUserId(this);" style="margin:0;" target="_top">'
+'		<div id="swnGLLlogin">Mileage Plus #<br>or email address</div>'
+'		<div id="swnGLLloginbox"><input type="text" id="swnGLLuserid" name="userId"></div>'
+'		<div id="swnGLLpass">Password</div>'
+'		<div id="swnGLLpassbox"><input type="password" id="swnGLLpassword" name="password"></div>'
+'		<div id="swnGLLremem"><input type="checkbox" name="remMP">Remember me</div>'
+'		<div id="swnGLLstartin">Start in</div>'
+'		<div id="swnGLLdrop">'
+'			<select id="swnGLLdropdown" name="sel_return_to">'
+		'<option value="&return_to='+mpSummaryReturnToVal+'" selected>My mileage summary</option>'+
		'<option value="&return_to=newitin_us">My itineraries</option>'+
		'<option value="">-------------------</option>'+
		'<option value="&return_to=booking_us" >Shop for flights</option>'+
		'<option value="&return_to=awardShop_us">Book with miles</option>'+
		'<option value="&return_to=rccupd">Red Carpet Club</option>'+
		'<option value="">-------------------</option>'+
		'<option value="&return_to=easy_checkin">Check-in online</option>'+
		'<option value="&return_to=rax">Change itineraries</option>'+
		'<option value="&return_to=eug_sum">Upgrades</option>'+
		'<option value="&return_to=refund">Ticket refunds</option>'+
		'<option value="">-------------------</option>'+
		'<option value="&whereto=UpdateProfile.jsp">My profile</option>'+
		'<option value="&return_to=centerPost">Flight notification</option>'+
		'<option value="&return_to=triptemplate">My trip templates</option>'
+'			</select>'
+'		</div>'
+'		<div id="swnGLLsubmit"><input type="image" src="'+writeSWNprotocol+'://www.united.com/ual/asset/swn_2007_buttonlogin.gif" border="0"></div>'
+'	</form>'
+'</div>'
+'<table border="0" cellpadding="0" cellspacing="0" width="100%" id="swnGLLnotamemtable">'
+'<tr><td valign="top" id="swnGLLnotamem" colspan="2">Not a member?</td></tr>'
+'<tr><td valign="top" class="swnRelatedLinksgt">></td><td valign="top" class="swnRelatedLinksitem"><a href="https://www.ua2go.com/ci/JoinMileagePlus.jsp?jumpLink=%2Fjoinmp">Sign up now</a></td></tr>'
+'</table>'
);

// this is for retriving the mileage plus number.
var rememberME = getCookie("rememberME");
	  if (rememberME!= undefined && rememberME=="E") {
	    var rememberEmail = getCookie("rememberEMAIL");
	  	document.MileagePlus.userId.value=rememberEmail;
	  	document.MileagePlus.remMP.checked=true;
	  }
	  else
	  	{
		  	var rememberMP; // init to null
			// then reassign if necessary
			if	(getCookie("getMP")) // *.united.com
				{ rememberMP = getCookie("getMP"); }
			if	(getCookie("rememberMP")) // ua2go.com
				{ rememberMP = getCookie("rememberMP"); }
		  	if (rememberMP != null)
				{ 
			  		document.MileagePlus.userId.value=rememberMP;
			  		document.MileagePlus.remMP.checked=true;
		  		}
	  	}
	}
}

