/* vim: set tabstop=4 textwidth=100: */
	
	alreadySubmitted = 0;
	emailCookie = null;
	usesslCookie = null;
	passCookie = null;
	oldpassCookie = null;
	cpCookie = null;
	borderCookie = null;
	cpPass = null;
	cpOldPass = null;
	reallyclear = null;
	startedtyping = null;
	newWin = null;

	_login_form = null;
	
	// {{{ login_init 
	function login_init(action_val) {
		
		document.login.onsubmit = function() { return false; };

		var whichLog = '';
		/* Change this to CSS default */
		if(!startedtyping)
			document.login.user_name.style.color = '#888888';

		/* Check for "remember me" cookie */
		bites = document.cookie.split("; ");
		emailCookie = getCookie("emailAddress");
		if (!emailCookie) {
			emailCookie = getCookie('user_name');
		}
		oldpassCookie 	= getCookie("password");
		passCookie 	= getCookie("passwordenc");
		usesslCookie = getCookie("useSSL");
		if (oldpassCookie != "") {
			passCookie = oldpassCookie;
		} else {
			passCookie = unescape(passCookie);
			passCookie = TEAdecrypt(passCookie, document.domain);
		}

		borderCookie = getCookie("noborder");

		cpCookie   = getCookie("username");
		cpOldPass     = getCookie("password_cp");
		cpPass     = getCookie("password_cpenc");
		if (cpOldPass != "") {
			cpPass = cpOldPass;
		} else {
			cpPass = unescape(cpPass);
			cpPass = TEAdecrypt(cpPass, document.domain);
		}

		/* Prevent multiple form submissions */
		alreadySubmitted = 0;

		if (cpCookie && cpPass) {
			whichLog = 'cp';
		} else {
			whichLog = 'email';
		}

		if ( action_val != undefined ) {
			whichLog = action_val;
		}

		changeLogin(whichLog);

		if (newWin && !newWin.closed) {
			newWin.focus();
		}
	}
	// }}}

	// {{{ changeLogin
	/**
	 * Change the login, based on the type of account that's trying to login.
	 */
	function changeLogin( optional ) { 
		var useSSL = document.getElementById("ssl");
		var sslicon = document.getElementById("forcessl_icon");
		var theform  = document.login;
		var logButton = theform.submit_btn;
		var option_label = document.getElementById("options_label");
		var toolbars = document.getElementById('toolbars');
		var password = theform.password;
		var emailAddress = theform.user_name;

		var boxone   = emailAddress;
		var boxtwo   = password;

		if (theform.type && !optional) {
			var theindex = theform.type.selectedIndex;
			var thevalue = theform.type.value;
		}

		// Switch to EMAIL
		if( optional == "email" || thevalue == "email" ) {
			theform.action = theform._email_action || theform.action;
			useSSL.style.display = '';
			sslicon.style.display='none';
			option_label.style.display = '';
			toolbars.style.display = '';
			password.style.display = 'none';

			if( emailCookie && passCookie && emailCookie != 'null' && passCookie != 'null') {
				setValues( emailCookie , passCookie , "#000" );
				theform.remember.checked = true;
			} else {
				startedtyping = 0;
				setValues( "Email Address" , "" , "#888" );
				boxone.defaultValue = boxone.value;
				theform.remember.checked = false;
			}
	
			if (usesslCookie != null && usesslCookie == "0") {
				document.getElementById("usessl").checked = false;
			}
	
			var hidetoolbars = document.getElementById('hide_toolbars');
			
			if (borderCookie == 'true' && alreadySubmitted == 0) {
				hidetoolbars.checked = true;
			}

			boxone.name = "user_name";
			boxtwo.name = "password";	
			
		// Switch to CONTROL PANEL
		} else if( optional == "cp" || thevalue == "cp" ) {
			theform.type.value = 'cp';
			theform._email_action = theform.action;
			theform.action = "https://admin.mailtrust.com/login/login2.asp";		
			theform.target = '';
			option_label.style.display = 'none';
			useSSL.style.display = 'none';
			sslicon.style.display = '';
			toolbars.style.display = 'none';

			if ( cpCookie && cpPass ) {
				setValues( cpCookie , cpPass , "#000" );
				theform.remember.checked = true;
			} else {
				startedtyping = 0;
				setValues( "Administrative ID" , "" , "#888" );
				boxone.defaultValue = boxone.value;
				theform.remember.checked = false;
			}

			boxone.name = "username";
			boxtwo.name = "password";
		
		// EMAIL DEFAULT IF NOT SPECIFIED
		} else {
			changeLogin('email');
		}

		boxone.focus();

		if(newWin && boxone.name == 'user_name' && !newWin.closed) {
			newWin.focus();
		};
	}
	// }}} changeLogin()

	// {{{ hidePasswordInput()
	function hidePasswordInput(input) {
		if (!input) {
			input = document.login.password;
		}
		if (input.value == '') {
			input.style.display = 'none';
			document.login.fake_pwd.style.display = '';
		}
	}
	// }}}
	
	// {{{ showPasswordInput()
	function showPasswordInput(input) {
		if (!input) {
			input = document.login.fake_pwd;
		}
		var real = document.login.password;
		input.style.display = 'none';
		real.style.display = '';
		real.focus();
	}
	// }}}

	// {{{ setValues
	/**
	 * Sets the values of the two input boxes as the cookie values.
	 */
	function setValues(username,password,color) {
		if(!startedtyping) {
			document.login.user_name.value = username;
			document.login.password.value = password;
			showPasswordInput();
			document.login.user_name.style.color = color;
		}
		
	}
	// }}} setValues() 

	// {{{ clearBox
	/**
	 * Clears a normal input field.
	 * 
	 * @param	inputReference	$thisbox	Input box to clear, used onFocus
	 */
	function clearBox( thisbox ) {
		if( thisbox.value == thisbox.defaultValue && !startedtyping ) {
			thisbox.value = '';
			thisbox.style.color = '#000';
		}
		startedtyping = 1;
	}
	// }}} clearBox()

	// {{{ checkDefault() 
	// IE wanted them to be separate...odd but works BRL
	function checkDefault( thisbox ) {
		if( thisbox.value == thisbox.defaultValue && reallyclear == 1 ) {
			thisbox.value = '';
			thisbox.style.color = '#000';
		}
	}
	// }}}

	// {{{ checkForm
	/**
	 * Checks the form for required fields? Needed?
	 */
	function checkForm() {
		submitForm();
	}
	// }}} checkForm()

	// {{{ forgotPassword()
	function forgotPassword() {
				
		var type = document.login.type.value;
		switch (type) {
			case 'cp':
				var location = 'https://admin.mailtrust.com/login/retrieve-password.asp';
				document.location = location;
				break;
			
			case 'email':
				var width=400;
				var height=250;
				var left =(screen.width - width) / 2;
				var top = (screen.height - height - 60) /2;
				window.open('p/popups/forgot_password.html', 'pwd',
					'toolbar=0,height='+height+',width='+width+',left='+left+',top='+top);
				break;
			
			default:
				break;
		}
		
		
	}
	// }}}

	// {{{ getCookie
	/**
	 * Gets the cookie from the UA
	 *
	 * @param	string	$name	Name of the cookie to get from this domain
	 */
	function getCookie( name ) {
		var cookie=" "+String(document.cookie);
		  var pos=cookie.indexOf(" "+name+"=");
		  if(pos!=-1){
			var end=cookie.indexOf(";",pos);
			return cookie.substring(pos+name.length+2,end==-1?cookie.length:end);
		  }
		  return '';
	}
	// }}} getCookie()

	// {{{ setupSession
	/**
	 * Sets up the session for the user, setting the cookies/hostnames/login cleanup/etc
	 */
	function setupSession () {	
		
		today = new Date();

		var nextYearDate =
				new Date(	today.getFullYear()+1,
							today.getMonth(),
							today.getDate(),
							today.getHours(),
							today.getMinutes(),
							today.getSeconds()    );

		// only used for email accounts
		if (document.getElementById('ssl').style.display != 'none')
		{
			document.login.target = '';
			sslcookievalue = (document.getElementById("usessl").checked ? "1" : "0");
			document.cookie = "useSSL=" + sslcookievalue + "; expires=" + nextYearDate.toGMTString() + ";";

			// Backwards compat - instead the form action should be filled in on the html page
			if (window.post_url) {
				document.login.action = 'http://' + window.post_url;
			}

			var is_ssl = (document.getElementById("usessl").checked == true);
			var url = document.login.getAttribute('action');
			var prot = url.substr(0, 6);
			if (prot == 'http:/') {
				var action = (is_ssl ? 'https://' : 'http://');
				action += url.substr(7);
			} else if (prot == 'https:' && !is_ssl) {
				var action = 'http' + url.substr(5);
			} else if (prot == 'https:' && is_ssl) {
				var action = url;
			} else if (url.substr(0, 1) == '/') {
				var action = (is_ssl ? 'https://' : 'http://');
				action += document.domain + url;
			} else {
				var loc = String(document.location);
				var lsl = loc.substr(8).lastIndexOf('/');
				if (lsl != -1) {
					loc = loc.substr(0, lsl+9);
				}

				var action = (is_ssl ? 'https://' : 'http://');
				action += loc.substr(loc.indexOf('//')+2) + url;
			}

			document.login.action = action;
			
			hidetoolbars = document.getElementById('hide_toolbars');

			if ( !hidetoolbars.checked ) {
				document.login.target = '_blank';
			} else if ( hidetoolbars.checked ) {
				param = 'toolbars=0, resizable=1, left=0, top=0,' + ',width=' + (screen.width * 0.95) + ',height=' + 
					(screen.height- 100);
				newWin = window.open('','newWin',param);
				document.login.target = 'newWin';
			}
		}else {
			document.login.target = window.name;
		}

		//If "remember" checkbox is checked, drop cookie to remeber "user_name" & "hostname"
		//Else if not checked, delete any existing cookie
		user = document.login.user_name.name;
		pass = document.login.password.name;

		if (document.login.user_name.is_exchange) {
			user = 'user_name';
		}

		if( user == "username") {
			pass = "password_cp";
		} else {
			// Clear control panel password for next remember load
			document.cookie = "password_cpenc=; expires=" + nextYearDate.toGMTString() + ";";
		}

		// Clear old unencrypted password
		document.cookie = pass + "=; expires=" + nextYearDate.toGMTString() + ";";

		//new encrypted cookie
		pass += "enc";

		var passval = document.login.password.value;
		passval = escape(TEAencrypt(passval, document.domain));
		
		if (document.login.remember.checked == true) {
			document.cookie = user + "=" + document.login.user_name.value + 
				"; expires=" + nextYearDate.toGMTString() + ";";
			document.cookie = pass + "=" + passval + 
				"; expires=" + nextYearDate.toGMTString() + ";";

			//set cookies only if it was email
	        if (document.getElementById('ssl').style.display != 'none')
	        {
				document.cookie = "noborder=" + hidetoolbars.checked + "; expires=" +
				nextYearDate.toGMTString() + ";";

			}
  		} else {
			document.cookie = user + "=" + document.login.user_name.value + 
				"; expires=Sun, 01-Jan-1995 01:00:00 GMT;";
			document.cookie = pass + "=; expires=Sun, 01-Jan-1995 01:00:00 GMT;";
  		}
		
	}
	// }}} setupSession()
	
	// {{{ submitForm
	/**
	 * Called when form is submitted, prevents multiple subs
	 
	 */
	 
	function clear_form() {
		document.login.reset(); 
	}
	 
	function submitForm(got_url) {
	
  		if (!alreadySubmitted || newWin) {
  		  		
			if (window.is_beta || got_url) {
			
   				alreadySubmitted = 1;
   				setupSession();

				if (window.is_beta) {
					
					document.login.submit();
					
					setTimeout('clear_form()', 3000)
					
				}
			} else {
			
				getPostUrl();
				
				setTimeout('clear_form()', 3000)
				
			}
   			return false;
  		} else {
			return false;
  		}
  		  		
	}
	// }}} submitForm()

	// {{{ addBookmark()
	function addBookmark() {
		title = document.title;
		url = document.URL;
		if (window.sidebar) {
			window.sidebar.addPanel(title,url,"");
		} else {
			if (document.all) {
				window.external.AddFavorite(url,title);
			} else {
				alert('Your browser does not support this feature. Please add a bookmark manually.');
			}
		}
	}
	// }}}

	// {{{ makeUrlSsl()
	function makeUrlSsl(url) {
		var prot = url.substr(0, 6);
		if (prot == 'http:/') {
			return 'https' + url.substr(4);
		} else if (prot == 'https:') {
			return url;
		} else if (url.substr(0, 1) == '/') {
			return 'https://' + document.domain + url;
		} else {
			var loc = String(document.location);
			var lsl = loc.substr(8).lastIndexOf('/');
			if (lsl != -1) {
				loc = loc.substr(0, lsl+9);
			}

			return 'https://' + loc.substr(loc.indexOf('//')+2) + url;
		}
	}
	// }}}

	// {{{ getPostUrl()
	function getPostUrl() {
	
		if (document.login.user_name.name == 'username') {
			setupSession();
			document.login.submit();
			return;
		}

		_login_form = document.login;

		var s = document.createElement('script');
		if (window._ext_js_path) {
			s.src = window._ext_js_path;
		} else {
			s.src = 'https://iad.wm.mlsrvr.com/mail6/';
		}
		s.src += 'ext/login/submit.php?e='+document.login.user_name.value+'&h=';
		if (document.login.hostname && document.login.hostname.value) {
			s.src += document.login.hostname.value;
		}
		document.body.appendChild(s);
	}
	
	// }}}

// 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, passwd)
{
    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(passwd.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 

    var ciphertext = longsToStr(v);

    return escCtrlCh(ciphertext);
}

//
// TEAdecrypt: Use Corrected Block TEA to decrypt ciphertext using password
//
function TEAdecrypt(ciphertext, passwd)
{
    if (ciphertext.length == 0) return('');
    var v = strToLongs(unescCtrlCh(ciphertext));
    var k = strToLongs(passwd.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:
    plaintext = plaintext.replace(/\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\t\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)); });
}
