var calculatorWindow;

if(getCookieValue('printContactInfo')==null){
	// code to set the print phone number cookies
	var printContactInfo = "(877) 941-4622";
	setSessionCookie("printContactInfo", printContactInfo);
}


function setCookie() {
    var name = "loginGMACMortgage";
    var value = "true";
    var expires = new Date ();

    var hostName = window.location.hostname;
    if(hostName=='localhost'){
    document.cookie = name + "=" + escape(value) + 
     		  "; path=/";

    }
    else{
	    document.cookie = name + "=" + escape(value) 
	     	  + "; path=/"
		  + "; domain=gmacmortgage.com";
	}
}

function getCookie () {
    var name = "loginGMACMortgage";
    var dcookie = document.cookie; 
    var cname = name + "=";
    var clen = dcookie.length;
    var cbegin = 0;

        while (cbegin < clen) {
        var vbegin = cbegin + cname.length;
            if (dcookie.substring(cbegin, vbegin) == cname) { 
            var vend = dcookie.indexOf (";", vbegin);
                if (vend == -1) vend = clen;
            return unescape(dcookie.substring(vbegin, vend));
            }
        cbegin = dcookie.indexOf(" ", cbegin) + 1;
            if (cbegin == 0) break;
        }
    return null;
    }

function getCookieValue (name) {
    var dcookie = document.cookie;
    var cname = name + "=";
    var clen = dcookie.length;
    var cbegin = 0;

    while (cbegin < clen) 
    {
    	var vbegin = cbegin + cname.length;
        if (dcookie.substring(cbegin, vbegin) == cname) 
        { 
        	var vend = dcookie.indexOf (";", vbegin);
            if (vend == -1) vend = clen;
			return unescape(dcookie.substring(vbegin, vend));
        }
	    cbegin = dcookie.indexOf(" ", cbegin) + 1;
        if (cbegin == 0) break;
    }
   return null;
}

function delCookie () {
    var name = "loginGMACMortgage";
    var expireNow = new Date();
    var hostName = window.location.hostname;

    if(hostName=='localhost'){
	    document.cookie = name + "=" +  
	    "; expires=Thu, 01-Jan-70 00:00:01 GMT" +  "; path=/"

    }
    else{
    document.cookie = name + "=" +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT" +  "; path=/"
     + "; domain=gmacmortgage.com";
	}


    }

function simpleRightNavLogin(){
	
	if(getCookie('loginGMACMortgage')){
	  document.writeln('<p class="secure_dynamic"><a href="/logoff/index.htm">Log Off</a></p>');
	}
	else{
	  document.writeln('<p class="secure_dynamic"><a href="/logon/index.htm">Secure Logon</a></p>');
	}
}

function complexRightNavLogin(){
	var hostName = window.location.hostname;
	if(hostName=='localhost'){
		hostName = hostName + ':7002';
	}
	var loginUrl = "https://"+hostName+"/secureLogin.htm";

	if(getCookie('loginGMACMortgage')){
	  document.writeln('<div id="right_securelogon" >');
	  document.writeln('<h4>Manage My Account</h4>');
	  document.writeln('<p class="secure"><a href="/logoff/index.htm">Log Off</a></p>');
	  document.writeln('</div>');		
	}
	else{
	  document.writeln('<div id="right_securelogon"  style="height:130px;">');
	  document.writeln('<h4>Manage My Account</h4>');
	  document.writeln('<form name="LoginForm" action="'+loginUrl+'" method="post">');
	  document.writeln('<div class="logon_field">');
	  document.writeln('<table>');
	  document.writeln('<tr><td>User Name</td><td><input type="text" name="j_username" maxlength="26" size="10"></td></tr>');
	  document.writeln('<tr><td>Password</td><td><input type="password" name="j_password" maxlength="26" size="10"></td></tr>');
	  document.writeln('<tr ><td colspan="2"><a href="/logon/forgotpassword/index.htm">Forgot password?</td></tr>');
	  document.writeln('<tr ><td valign="top" ><a href="/logon/registration/index.htm">Not&nbsp;Registered</a></td><td align="right"><input type="image"  src="/images/btn_logOnSecure.gif" alt="Log On" ></td></tr>');
	  document.writeln('<tr ><td colspan="2"><a href="/About_Us/Legal_Information/Privacy.html">Privacy Policy & Security</a></td></tr>');
	  document.writeln('</table>');
	  document.writeln('</div>');
	  document.writeln('</form>');	
	  document.writeln('</div>');			
	}
}

function headerNavLogin(){
	
	if(getCookie('loginGMACMortgage')){
	  document.writeln('<li><a href="/logoff/index.htm" title="Log Off">Log Off</a></li>');
	}
	else{
	  document.writeln('<li><a href="/logon/index.htm" title="Log On">Log On</a></li>');
	}
}

function mainNavLogin(){
	if(getCookie('loginGMACMortgage')){
	  document.writeln('<a $cmignore href="/accounts/index.htm" /$cmignore id="02" >My Account</a>');
	}
	else{
	  document.writeln('<a $cmignore href="/logon/index.htm" /$cmignore id="02" >My Account</a>');
	}
}

function contactInfoPrint(){
	//alert("printContactInfo = " + getCookieValue("printContactInfo"));
	//alert("document.cookie = " + document.cookie);
	document.writeln(getCookieValue("printContactInfo"));
}

function ratesNavLogin(){
	if(getCookie('loginGMACMortgage')){
	  document.writeln('<a href="/logoff/index.htm" title="Log Off" ><img src="../images/btn_logout.gif" border="0" /></a>');
	}
	else{
	  document.writeln('<a href="/logon/index.htm" title="Log On"><img src="../images/btn_logOnSecure.gif" border="0" /></a>');	}
}

function validateZipCode(zipcode){
	var zipcodePattern=/^[0-9]{5,5}$/;
	if (!zipcode.match(zipcodePattern))
  	{

		window.location = "http://www.gmacm.net/branches/branches.jsp";
		return false;

	}
	return true;
}


//Survey Functions//

//added variable so that every link doesn't bring up the survey
//to stop sending survey change value below to false.
sendSurvey = false;

function popupSurvey(){
     //set expiration date for survey
     var expireDate = new Date ("Thursday, May 25, 2006 4:00:00 AM");
     var currentDate = new Date();
	var ie=(document.all);
	//for testing remove comment out lines below.
	//alert("sendSurvey "+ sendSurvey + " getSurveyCookie() "+  getSurveyCookie());
	//alert(" expireDate and currentDate " + (expireDate>currentDate) );
	if(sendSurvey && expireDate>currentDate && !getSurveyCookie()){
		setSurveyCookie(expireDate);
		window.open('https://websurveyor.net/wsb.dll/10446/gmacmortgage.htm','survey','toolbar=no,scrollbars=yes,resizable=yes,location=no, status=no,width=600,height=450');
	}
	return true;
}
function setLinks() { 
	if (document.links) { 
		for (var i=0;i<document.links.length;i++) {
			if(document.links[i].onclick==null){
			document.links[i].onclick=new Function("sendSurvey=false"); 
			}			
		}
		for (var j=0;j<document.forms.length;j++) 
			if(document.forms[j].onclick==null){
			document.forms[j].onclick=new Function("sendSurvey=false"); 
			}
	}
} 

function setSurveyCookie(expireDate) {
    var name = "surveyGMACMortgage";
    var value = "true";
 
    	//set expiration date for survey
	expireDate = expireDate.toGMTString();
    var hostName = window.location.hostname;
    if(hostName=='localhost'){
    document.cookie = name + "=" + escape(value) + 
     		  "; path=/" +
		  ";expires="+expireDate+";";
    }
    else{
	    document.cookie = name + "=" + escape(value) 
	     	  + "; path=/"
		  + "; domain=gmacmortgage.com"+
		  ";expires="+expireDate+";";
	}
}

function getSurveyCookie () {
    var name = "surveyGMACMortgage";
    var dcookie = document.cookie; 
    var cname = name + "=";
    var clen = dcookie.length;
    var cbegin = 0;

        while (cbegin < clen) {
        var vbegin = cbegin + cname.length;
            if (dcookie.substring(cbegin, vbegin) == cname) { 
            var vend = dcookie.indexOf (";", vbegin);
                if (vend == -1) vend = clen;
            return unescape(dcookie.substring(vbegin, vend));
            }
        cbegin = dcookie.indexOf(" ", cbegin) + 1;
            if (cbegin == 0) break;
        }
    return null;
}

//start code to add referrer cookie
//pswd 
var username = "gmacmortgage";
var referrer = "";
if(document.referrer.length>0){
	var urlstrarray=document.referrer.split("/");

	if((urlstrarray[2].length<=15 && urlstrarray[2].toLowerCase() != "localhost:7001")|| 
		(urlstrarray[2].length>15 && urlstrarray[2].toLowerCase().substring(urlstrarray[2].length-16,urlstrarray[2].length) != "gmacmortgage.com" )){
		referrer = document.referrer;
		if(document.referrer.indexOf("?") != -1){
			referrer = referrer + "&" + window.location.search.substring(1);
		}
		else{
			referrer = referrer + "?" + window.location.search.substring(1);
		}
		var encryptedValue = TEAencrypt(referrer,username);
		setSessionCookie("gmacReferrerCookie", encryptedValue);
		setSessionCookie("gmacReferrerCookie_Unenc", referrer);
			
	}
}
		

function showPopupHeader()
{
	var cntr=0;
	var tmpWindow=window.opener;
	while ( tmpWindow != null)
	{
		cntr++;
		if (cntr > 5  ) break;
		tmpWindow=tmpWindow.opener;
	}
	if(cntr > 0){
		document.getElementById('popUpHead').style.display = 'block';
		document.getElementById('popup_footer_nav').style.display = 'block';
		document.getElementById('main_content_calcs').style.display = 'block';
	}
	else
	{
		document.getElementById('header_nav').style.display = 'block';
		document.getElementById('left_column_nav').style.display = 'block';
		document.getElementById('right_column_nav').style.display = 'block';
		document.getElementById('page_footer_nav').style.display = 'block';
		document.getElementById('main_content_calcs').style.display = 'block';
	}
	window.focus();
}



function show(id,tab,content,apply)
{
	if(document.getElementById(id).style.display=='none')
	{
		document.getElementById(id).style.display= '';
		document.getElementById(content).style.display= '';
		document.getElementById(apply).style.display= '';
		document.getElementById(tab).className= 'tab_active';
	}
}
function hide(id,tab,content,apply)
{
	document.getElementById(id).style.display='none';
	document.getElementById(content).style.display='none';
	document.getElementById(apply).style.display='none';
	document.getElementById(tab).className= 'tab_inactive';
}

function openCalculatorWindow(methodName)
{

var XPos=screen.availWidth-760;
try
{
calculatorWindow.document.write("<center><br/><br/><br/><br/><br/><br/><br/>Loading Calculator...</center>");
calculatorWindow.focus();
}
catch(e){}
calculatorWindow=window.open('/calculators.do?method='+methodName+'&amp;popup=true','calculatorPopupWindow','toolbar=no,scrollbars=yes,resizable=yes,location=no,status=no,width=700,height=600,top=10,left='+XPos);


}

function setSessionCookie(cookieName, cookieValue) {
    var name = cookieName;
    var value = cookieValue;

    var hostName = window.location.hostname;
    if(hostName=='localhost'){
    document.cookie = name + "=" + escape(value) + 
     		  "; path=/";

    }
    else{
	    document.cookie = name + "=" + escape(value) 
	     	  + "; path=/"
		  + "; domain=gmacmortgage.com";
	}
}

function getSessionCookie (cookieName) {
    var name = cookieName;
    var dcookie = document.cookie; 
    var cname = name + "=";
    var clen = dcookie.length;
    var cbegin = 0;

        while (cbegin < clen) {
        var vbegin = cbegin + cname.length;
            if (dcookie.substring(cbegin, vbegin) == cname) { 
            var vend = dcookie.indexOf (";", vbegin);
                if (vend == -1) vend = clen;
            return unescape(dcookie.substring(vbegin, vend));
            }
        cbegin = dcookie.indexOf(" ", cbegin) + 1;
            if (cbegin == 0) break;
        }
    return null;
    }
//
// TEAencrypt: Use Corrected Block TEA to encrypt plaintext using password
//             (note plaintext & password must be strings not string objects)
//
// Return encrypted text as string
//
function TEAencrypt(plaintext, password)
{
    if (plaintext.length == 0) return('');  // nothing to encrypt
    // 'escape' plaintext so chars outside ISO-8859-1 work in single-byte packing, but  
    // keep spaces as spaces (not '%20') so encrypted text doesn't grow too long, and 
    // convert result to longs
    var v = strToLongs(escape(plaintext).replace(/%20/g,' '));
    if (v.length == 1) v[1] = 0;  // algorithm doesn't work for n<2 so fudge by adding nulls
    var k = strToLongs(password.slice(0,16));  // simply convert first 16 chars of password as key
    var n = v.length;

    var z = v[n-1], y = v[0], delta = 0x9E3779B9;
    var mx, e, q = Math.floor(6 + 52/n), sum = 0;

    while (q-- > 0) {  // 6 + 52/n operations gives between 6 & 32 mixes on each word
        sum += delta;
        e = sum>>>2 & 3;
        for (var p = 0; p < n-1; p++) {
            y = v[p+1];
            mx = (z>>>5 ^ y<<2) + (y>>>3 ^ z<<4) ^ (sum^y) + (k[p&3 ^ e] ^ z)
            z = v[p] += mx;
        }
        y = v[0];
        mx = (z>>>5 ^ y<<2) + (y>>>3 ^ z<<4) ^ (sum^y) + (k[p&3 ^ e] ^ z)
        z = v[n-1] += mx;
    }
    // note use of >>> in place of >> due to lack of 'unsigned' type in JavaScript 

    return escCtrlCh(longsToStr(v));
}

//
// TEAdecrypt: Use Corrected Block TEA to decrypt ciphertext using password
//
function TEAdecrypt(ciphertext, password)
{
    if (ciphertext.length == 0) return('');
    var v = strToLongs(unescCtrlCh(ciphertext));
    var k = strToLongs(password.slice(0,16)); 
    var n = v.length;

    var z = v[n-1], y = v[0], delta = 0x9E3779B9;
    var mx, e, q = Math.floor(6 + 52/n), sum = q*delta;

    while (sum != 0) {
        e = sum>>>2 & 3;
        for (var p = n-1; p > 0; p--) {
            z = v[p-1];
            mx = (z>>>5 ^ y<<2) + (y>>>3 ^ z<<4) ^ (sum^y) + (k[p&3 ^ e] ^ z)
            y = v[p] -= mx;
        }
        z = v[n-1];
        mx = (z>>>5 ^ y<<2) + (y>>>3 ^ z<<4) ^ (sum^y) + (k[p&3 ^ e] ^ z)
        y = v[0] -= mx;
        sum -= delta;
    }

    var plaintext = longsToStr(v);
    // strip trailing null chars resulting from filling 4-char blocks:
    if (plaintext.search(/\0/) != -1) plaintext = plaintext.slice(0, plaintext.search(/\0/));

    return unescape(plaintext);
}


// supporting functions

function strToLongs(s) {  // convert string to array of longs, each containing 4 chars
    // note chars must be within ISO-8859-1 (with Unicode code-point < 256) to fit 4/long
    var l = new Array(Math.ceil(s.length/4))
    for (var i=0; i<l.length; i++) {
        // note little-endian encoding - endianness is irrelevant as long as 
        // it is the same in longsToStr() 
        l[i] = s.charCodeAt(i*4) + (s.charCodeAt(i*4+1)<<8) + 
               (s.charCodeAt(i*4+2)<<16) + (s.charCodeAt(i*4+3)<<24);
    }
    return l;  // note running off the end of the string generates nulls since 
}              // bitwise operators treat NaN as 0

function longsToStr(l) {  // convert array of longs back to string
    var a = new Array(l.length);
    for (var i=0; i<l.length; i++) {
        a[i] = String.fromCharCode(l[i] & 0xFF, l[i]>>>8 & 0xFF, 
                                   l[i]>>>16 & 0xFF, l[i]>>>24 & 0xFF);
    }
    return a.join('');  // use Array.join() rather than repeated string appends for efficiency
}

function escCtrlCh(str) {  // escape control chars which might cause problems with encrypted texts
    return str.replace(/[\0\n\v\f\r\xa0!]/g, function(c) { return '!' + c.charCodeAt(0) + '!'; });
}

function unescCtrlCh(str) {  // unescape potentially problematic nulls and control characters
    return str.replace(/!\d\d?\d?!/g, function(c) { return String.fromCharCode(c.slice(1,-1)); });
}


