/**
 * External login_auto script useful for Demo purposes
 * @Installation:
 * 			copy this script into webmail directory and change sServerURL and sClientUrl paths below
 * @Date:	4.7.2007 9:04:47
 **/

function oExt_Login (){


	this.sServerURL = 'proxy.php';					//proxy.php path (or webmail.php path if it is in the same domain)
	this.sClientUrl = 'http://central.lucanet.com.br/webmail/';	//WebMail Pro URL


	//Mozilla & MSIE7
	if (window.XMLHttpRequest)
		this.oXMLHttp = new XMLHttpRequest();
	else
	//MSIE 6
	if(!navigator.__ice_version && window.ActiveXObject)
		this.oXMLHttp = new ActiveXObject('Microsoft.XMLHTTP');
};

oExt_Login.prototype.response = function(sInput){

	var xOutput = null;
	try {
		xOutput = new ActiveXObject('Microsoft.XMLDOM');
		xOutput.async = false;
		xOutput.resolveExternals = false;
		xOutput.validateOnParse = false;
		xOutput.loadXML(sInput);

		if (xOutput.parseError.errorCode)
			alert(	"Error code: "+ xOutput.parseError.errorCode +
					"\nLine: " + xOutput.parseError.line + ':'+ xOutput.parseError.linePos +
					"\nReason: "+ xOutput.parseError.reason +
					"\n" + xOutput.parseError.srcText);
	}
	catch (e) {
		var xParser = new DOMParser();
		xOutput = xParser.parseFromString(sInput, 'text/xml');
	}
	
	this.oXMLHttp.open('POST', this.sServerURL, false);
	this.oXMLHttp.send(xOutput);

	return this.oXMLHttp.responseXML;
};

oExt_Login.prototype.login = function(user,pass,ip,rsa){
	if (!this.oXMLHttp || !user || (!pass && !rsa)) return;

	//Escape username
	var text = document.createTextNode(user);
	var div = document.createElement('div');
		div.appendChild(text);
	user = div.innerHTML;

	var tmp;
	try{
		if(!rsa)
			pass = this.getrsa(user,pass);
		else
			pass = rsa;

		//SET LOGIN info
		tmp = this.response('<iq type="set"><query xmlns="webmail:iq:auth"><username>'+user+'</username><digest>'+pass+'</digest><method>RSA</method><ip>'+ip+'</ip></query></iq>');
		var sid = tmp.getElementsByTagName('iq')[0].getAttribute('sid');
		if (!sid) throw 'Invalid Login';
		this.redirect(sid);
	}
	catch(e){
		alert('Error - '+e);
	}
};

oExt_Login.prototype.getrsa = function(user,pass){
		//GET RSA public key
		tmp = this.response('<iq type="get" format="xml"><query xmlns="webmail:iq:auth"><username>'+user+'</username><method>RSA</method></query></iq>');
		var key = tmp.getElementsByTagName('hashid')[0].firstChild.nodeValue;

		//Prepare RSA library
		var rsa = new RSAKey();
			rsa.setPublic(key, '10001');
			
		return rsa.encrypt(pass);
};

oExt_Login.prototype.loginform = function(elm){
	this.login(elm.username.value,elm.password.value,elm.ip.value);
	return false;
};

oExt_Login.prototype.redirect = function(sid){
	document.location.href = this.sClientUrl+'?sid='+sid+(document.referrer?'':'&ref='+document.location.href);
};

Ext_Login = new oExt_Login();
