/*
	a front-end prototype for the toolbox login process
	grant 31/08/05
	modified for webmail

	requires:
		prototype.js
		behaviour.js
		scriptaculous.js
*/
function getBaseURL() {
	var location = window.location.pathname;
	if (location.match(/^\/~/)) {
		return location.match(/^\/~(\w*)?\//)[0];
	}
	return '/';
}

function checkAuth(){
	var url = getBaseURL()+'cgi-bin/basicauth.cgi';
	var regex = /^([a-zA-Z0-9_\.\-])+\@([a-zA-Z0-9\.\-])+$/;
  	var inputstr = $F('username')

	// Select list takes precedence.
	if ($F('pop3host_select'))
		document.form_webmail_login.pop3host.value = $F('pop3host_select');

	// No pop3host set at all, read from cookie or set a default.
	if (!$F('pop3host')) {
       	if (!readCookie('TISP')) {
			document.form_webmail_login.pop3host.value = "iinet.net.au";
		} else {
			var TISP = readCookie('TISP');
			document.form_webmail_login.pop3host.value = TISP;
		}
    }

	// username contains domain name
	if (regex.test(inputstr)){
		var splitarr = $F('username').split('@');
		document.form_webmail_login.pop3host.value = splitarr[1];
		var url_params = 'username='+escape($F('username'))+'&password='+escape($F('password'))+'&action=login';
	} else {
		var url_params = 'username='+escape($F('username'))+'@'+escape($F('pop3host'))+'&password='+escape($F('password'))+'&action=login';
	}

	var myAjax = eval(new Ajax.Updater(
		'control',
		url,
		{evalScripts:true, method: 'get', parameters: url_params, onFailure: reportError1}));
	//alert('maybe waiting');
	function reportError1(request){
		// if we fail to retreive a list of realms, we could do something here.
		// ..or we could ignore the error and use the default list of all realms.
	}
}

function getRealms(){

	var url = getBaseURL()+'cgi-bin/tisplist.cgi';
	var url_params = 'username='+ $F('username');
	
	new Ajax.Updater(
		{success: 'pop3host_list'},
		url,
		{asynchronous:'false', method: 'post', parameters: url_params, onFailure: reportError2});

	function reportError2(request){
		// if we fail to retreive a list of realms, we could do something here.
		// ..or we could ignore the error and use the default list of all realms.
	}

	// display the list of realms (if it's not already displayed)
	if ($('form_row_pop3host').style.display == 'none'){
		//$('realm_list').style.display = 'block';
	    if (!readCookie('TISP')) {
			new Effect.BlindDown('form_row_pop3host');
	    } else {
	    	$F('username') = $F('username')+'@'+$F('pop3host');
			checkAuth();
	    }
	}
}

function doLogin(){

	if ($F('username') && $F('password')){	
		if ($F('pop3host_select') || $('form_row_pop3host').style.display == 'none')
			new Effect.Appear('busy');
	}

	// reset the appearance of the form fields (background colour)
	var fields = $('username','password','pop3host_select');
	for(i=0; i<fields.length; i++){
		fields[i].style.background = "#fff";
	}

	// highlight any blank fields
	if (!$F('username')){
		new Effect.Highlight('username');
		$('label_username').innerHTML = '<img src=\"/img/ex.png\" /> email address:';
	}
	if (!$F('password')){
		new Effect.Highlight('password');
		$('label_password').innerHTML = '<img src=\"/img//ex.png\" />  password:';
	}
	if (!$F('pop3host_select') && $('form_row_pop3host').style.display != 'none'){
		new Effect.Highlight('pop3host_select');
    	new Effect.Fade('busy');
		return false;
	}

	if ($F('username') && $F('password')){
	    checkAuth();
	}
	

	return false;
}

function AuthFailed(){

    new Effect.Fade('busy');

	var regex = /^([a-zA-Z0-9_\.\-])+\@([a-zA-Z0-9\.\-])+$/;
  	var inputstr = $F('username')
	var firstlogin = 'Enter your email address and password to log in to WebMail';
	var badlogin = 'Sorry, we couldn\'t log you in to your <span>'+$F('pop3host')+'</span> account. If your details below are correct, you can try again, or give us a call on <strong>13 22 58</strong>';
	//var nodomain = '<h2>Is your password correct?</h2>\nTry entering your password again';
	var nodomain = 'Is your password and domain correct?<br /><br />\nTry selecting your domain and entering your password again.';

	// basicauth failed
	if (readCookie('TISP'))
		eraseCookie('TISP');

	if ($('form_errorhead'))
		new Effect.BlindUp('form_errorhead');
	if ($('form_errorbody'))
		new Effect.BlindUp('form_errorbody');

	// Username with domain suffix
	if (regex.test(inputstr)){
		$('form_prompt').innerHTML = badlogin;
       	new Effect.Appear('form_prompt');
	// Plain username, default pop3host
	} else {
   		if ($('form_row_pop3host').style.display == 'none'){
    		$('form_prompt').innerHTML = nodomain;
    		getRealms();
           	new Effect.Appear('form_prompt');
           	$('password').style.background = '#fff9ca';
           	$('password').focus();
		} else {
			$('form_prompt').innerHTML = badlogin;
       		new Effect.Appear('form_prompt');
		}

	}

    return false;
}


function AuthOK(){
    //var regex = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    var regex = /^([a-zA-Z0-9_\.\-])+\@([a-zA-Z0-9\.\-])+$/;
    var inputstr = $F('username')

    var pop3host = $F('pop3host'); 
    if (!$F('pop3host')) {
		pop3host = "iinet.net.au";
	}

    if (!regex.test(inputstr)){
        if (!readCookie('TISP') && pop3host) {
        	$('username').value = $F('username')+'\@'+pop3host;
        }
    } else {
		var splitemail = document.form_webmail_login.username.value.split('@');
		document.form_webmail_login.username.value = splitemail[0];
		document.form_webmail_login.pop3host.value = splitemail[1];
	}

	createCookie('TISP', pop3host);
    document.form_webmail_login.submit();
    return false;

}

//----------------------------------------

// let the user know if their caps lock key is on

function checkCaps( e ) {
  if( !e ) { e = window.event; } if( !e ) { return; }

  var theKey = 0;
  if( e.which ) { theKey = e.which; }
  else if( e.keyCode ) { theKey = e.keyCode; } 
  else if( e.charCode ) { theKey = e.charCode }

  var theShift = false;
  if( e.shiftKey ) { theShift = e.shiftKey; } 
  else if( e.modifiers ) { //Netscape 4
    //check the third bit of the modifiers value (says if SHIFT is pressed)
    if( e.modifiers & 4 ) { //bitwise AND
      theShift = true;
    }
  }
  //if we see upper case without shift key, caps lock is on
  if( theKey > 64 && theKey < 91 && !theShift ) {
	capsAlert();
  }
  //if we see lower case with the shift key, caps lock is on
  else if( theKey > 96 && theKey < 123 && theShift ) {
	capsAlert();
  }
  else{
    hideCapsAlert();
  }
}

function capsAlert(){
    if (document.getElementById('caps_alert').style.display == 'none'){
	document.getElementById('caps_alert').style.display = 'inline';
//	new Effect.Appear('caps_alert');
    }
}
function hideCapsAlert(){
    if (document.getElementById('caps_alert').style.display != 'none'){
	document.getElementById('caps_alert').style.display = 'none';
//	new Effect.Fade('caps_alert');
    }
}

//----------------------------------------

// define all our javascript events
var event_rules = {
	'#form_webmail_login' : function(el){
		el.onsubmit = doLogin;
	},
	'#username' : function(el){ //resetting form labels when the user updates input
		el.onchange = function(){$('label_username').innerHTML = 'email address: '};
	},
	'#password' : function(el){
		el.onchange = function(){$('label_password').innerHTML = 'password: '};
	}

};
Behaviour.register(event_rules);

// initial set up on page load.
function init(){
	if ($('form_row_pop3host')) {
        $('form_row_pop3host').style.display = 'none';
    }
}
Behaviour.addLoadEvent(init);

