String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

/* Add Mailbox */
function copyValue(o,sTo){
	if(el('allow_copy').checked) el(sTo).value = o.value;
}

function dupeAddMailbox(o){
	if(o.checked){
		el('email').value=el('login').value;
		el('password').value=el('login_password').value;
		el('password2').value=el('login_password2').value;
	}
}

//Partner signup screen: forces quota to 2GB for free account
function force2gb(){
	
	if(el('quota_type').value=='Free' && el('quota').value!='2'){
		alert("Free accounts ust be set to 2GB");
		return false;
	}
	
	return true;
	
}

/* Render Preview Msg */
var oReq;
var oPreviewParentNode;
var iCheckLoginId = null;
var iPreviewTimer = null;
var sCheckLoginUrl = '';

function checkLoginStart(url){
	
	if(iCheckLoginId!=null) clearTimeout(iCheckLoginId);
	iCheckLoginId = setTimeout(checkLogin,1000);
	sCheckLoginUrl = url;
	el('reg_login_msg').innerHTML = "";
	
}

function checkLogin(url){
	
	sLogin = el('reg_login').value;
	if(reqSetup()){
	
		if(sLogin!=''){
			//sLogin = urlencode(sLogin);
			req(sCheckLoginUrl+"checklogin?login="+sLogin,checkLogin2)
			
		}
		
	}
	
}

function checkLogin2(){

	if(oReq.readyState==4){
		
		sResult = oReq.responseText;
		
		if(sResult=='true'){
			el('reg_login_msg').innerHTML = "&#160;&#160;Available";
		} else if(sResult=='false') {
			el('reg_login_msg').innerHTML = "&#160;&#160;Already in use";
		}
		
	}
	
	iCheckLoginId = null;
	
}

function renderMsgPreview(sParent,msgno){
	clearTimeout(iPreviewTimer);
	
	if((el(sParent).childNodes.length<10 && gsBrowser!='ie') || (gsBrowser=='ie' && el(sParent).childNodes.length<5) ){
		el('spin'+msgno).style.display = "block";
		iPreviewTimer = setTimeout("renderMsgPreviewStart('"+sParent+"',"+msgno+")",1000);
	}
}

function renderMsgPreviewStart(sParent,msgno){
	
	if(reqSetup()){
	
		if(el(sParent).childNodes.length<10){
		
			oPreviewParentNode = el(sParent);
			req("render_msg?context=preview&msgno="+msgno,renderMsgPreview2)
			
		}
		
	}
	
}

function sendMsg(msgno){
var sendto,url;

	el('sendMsgResult').innerHTML = "Sending..";
	if(reqSetup()){
		sendto = el('sendto').value;
		url = "render_msg?context=send&msgno="+msgno+"&sendto="+sendto;
		req(url,sendMsg2);
	}
	
}


function sendMsg2(){
	
	if(oReq.readyState==4){
		
		sResult = oReq.responseText;

		if(sResult.substr(0,2)=='OK'){
			el('sendMsgResult').innerHTML = "Sent"
		} else {
			el('sendMsgResult').innerHTML = "Error"
		}
		
	}
	
}

function restore1(mbx){
var sendto,url;

	if(el('genArchive').style.display=='block'){
		el('genArchive').style.display='none';
		return;
	}

	el('genArchive').style.display = 'block';
	el('genArchive').className = "genArchive";
	el('genArchiveMsg').innerHTML = "Please wait...";
	
	if(reqSetup()){
		genArchiveMailbox = mbx;
		if(mbx!=null){
			url = "restore_destinations?_nodt&mailbox="+mbx;
		} else {
			url = "restore_destinations?_nodt";
		}
		req(url,restore1cb);
	}
	
}


function restore1cb(){
	
	if(oReq.readyState==4){
		
		sResult = oReq.responseText;
		sResult = sResult.trim();

		el('genArchive').className = 'genArchive_nobg';
		
		if(sResult.substr(0,1)=='<'){
			el('genArchiveMsg').innerHTML = sResult;
		} else {
			el('genArchiveMsg').innerHTML = "Error"
		}
		
	}
	
}

function restoreStart(mbx){
var o, destfolder, s, o, iSel,url;

	if(mbx!=null){
		s = mbx;
	} else {
		o = el('selectRestoreDestination');
		iSel = o.selectedIndex;
		s = o.item(iSel).innerHTML;
	}
	
	oDestfolder = el('destfolder');
	try {
		destfolder = oDestfolder.value;
		
	} catch(err) {
		
	}
	oToinbox = el('restore_toinbox');
	try {
		if(oToinbox.checked){
			toinbox = 'true';
		} else {
			toinbox = 'false';
		}
	} catch(err) {}


	el('genArchive').className = "genArchive";
	el('genArchiveMsg').innerHTML = "Commencing restore...";
	
	if(reqSetup()){
		url = "restore_start?destination="+s;
		if(destfolder!=''){
			urlencode(destfolder);
			url += "&destfolder="+destfolder;
		}
		url += "&toinbox="+toinbox;

		req(url,restoreStartcb);
	}
	
}

function restoreStartcb(){
	
	if(oReq.readyState==4){
		
		sResult = oReq.responseText;
		
		el('genArchive').className = "genArchive_nobg";
		if(sResult!="OK"){
			el('genArchiveMsg').innerHTML = "Error";
		} else {
			el('genArchiveMsg').innerHTML = "Restore commencing. Messages will appear in your Inbox or requested folder.";
		}
		
	}
	
}

var genArchiveMailbox = null;

function genArchive(mbx){
var sendto,url;

	el('genArchive').className = 'genArchive';
	el('genArchive').style.display = 'block';
	el('genArchiveMsg').innerHTML = "Generating archive. Please wait...";
	
	if(reqSetup()){
		genArchiveMailbox = mbx;
		if(mbx!=null){
			url = "generate_archive?mailbox="+mbx;			
		} else {
			url = "generate_archive";
		}
		req(url,genArchive2);
	}
	
}


function genArchive2(){
	
	if(oReq.readyState==4){
		
		sResult = oReq.responseText;

		if(sResult.substr(0,2)=='OK'){
			el('genArchiveMsg').innerHTML = "Transferring archive. Please wait...";
			if (genArchiveMailbox != null) {
				url = "download_archive?mailbox=" + genArchiveMailbox;
			} else {
				url = "download_archive";
			}
			if (reqSetup()) {
				req(url, genArchive3);
			}
		} else {
			el('genArchiveMsg').innerHTML = "Error"
		}
		
	}
	
}

function genArchive3(){
	
	if(oReq.readyState==4){
		
		sResult = oReq.responseText;
		if(sResult.substr(0,2)=='OK'){
			el('genArchive').style.display = 'none';
			if (genArchiveMailbox != null) {
				window.location = "stream_archive?mailbox=" + genArchiveMailbox;
			} else {
				window.location = "stream_archive";
			}
		} else {
			el('genArchiveMsg').innerHTML = "Error"
		}
		
	}
}


//Make an ajax request
function req(url,callback){
	
	oReq.open("GET",url,true);
	oReq.onreadystatechange=callback;
	oReq.send(null);
	
}

//Shout going out
function reqSetup(){

	
		if(gsBrowser=='ie'){
			oReq = new ActiveXObject("Msxml2.XMLHTTP");
		} else {	
			oReq = new XMLHttpRequest();
		}
	

	if(oReq){

		return true;

	}
	
	return false;

}

function renderMsgPreview2(){

	if(oReq.readyState==4){
		
		sResult = oReq.responseText;
		
		if(sResult!=''){
		
			//Add to browser
			newNode = document.createElement("div");
			//newNode.setAttribute("class","resultspreview");
			//newNode.setAttribute("onclick","closeWindow(this)"); //Doesn't work in IE. Sigh.
			newNode.innerHTML = "<div class=\"resultspreview\" onclick=\"closeWindow(this)\"><pre>"+sResult+"</pre></div>";
			oPreviewParentNode.appendChild(newNode);
			//oPreviewParentNode.childNodes.item(1).style.display = "none";

		}
		
	}

	return true;

}


function closeWindow(o){

	o.parentNode.parentNode.removeChild(o.parentNode);

}

/* Email list */
function searchinSelectAll(oCheck){
var o;
	
	o = document.getElementsByName('searchin[]');
	for(i=0;i<o.length;i++){
		oBox = o.item(i);
		if(oBox.type=='checkbox'){
			if((oCheck!=null && oCheck.checked) && !oBox.disabled ){
				oBox.checked = true;
			} else {
				oBox.checked = false;
			}
		}
	}

}

function selectAll(oCheck,sTarget){
var o;
	
	o = document.getElementsByName(sTarget);
	for(i=0;i<o.length;i++){
		oBox = o.item(i);
		if(oBox.type=='checkbox'){
			if(oCheck!=null && oCheck.checked){
				oBox.checked = true;
			} else if(!oBox.disabled) {
				oBox.checked = false;
			}
		}
	}

}

function addInviteField(ilimit){
	
	o = el('emaillist');
	if(ilimit<=o.childNodes.length){
		alert('You do not have any more invites available');

	} else {
		newNode = document.createElement("div");
		newNode.innerHTML = "<input type=\"text\" name=\"email[]\" value=\"\" class=\"w250\" />"
		o.appendChild(newNode);
	}
}

/* Select folders */
function folderSelectAll(oCheck){
var o;

	o = document.form_folder_selection;
	for(i=0;i<o.elements.length;i++){
		oBox = o.elements.item(i);
		if(oBox.type=='checkbox'){
			if(oCheck!=null && oCheck.checked){
				oBox.checked = true;
			} else {
				oBox.checked = false;
			}
		}
	}
	

}

function selectTree(oCheck){
	//Do we have a nested UL?
	oKids = oCheck.parentNode.childNodes;
	for(i=0;i<oKids.length;i++){
		oNode = oKids.item(i);
		if(oNode.tagName=='UL') {
			selectTreeRec(oNode,oCheck.checked);		
		}
	}
}

function selectTreeRec(oUL,bSelect){
	//Find child UL
	oKids = oUL.childNodes;
	for(i=0;i<oKids.length;i++){
		oNode = oKids.item(i);
		if(oNode.tagName=='LI'){
			//Go through all LIs
			oNode.childNodes[2].checked = bSelect;
			//Do we need to recurse into a nested UL?
			for(i2=0;i2<oNode.childNodes.length;i2++){
				oNode2 = oNode.childNodes.item(i2);
				if(oNode2.tagName=='UL') {
					selectTreeRec(oNode2,bSelect);		
				}
			}
		} 
	}
	
}

function toggleTreeview(o){
	//Find child UL
	oKids = o.childNodes;
	for(i=0;i<oKids.length;i++){
		oNode = oKids.item(i);
		if(oNode.tagName=='UL'){
			if(oNode.style.display =='block'){
				oNode.style.display = 'none';
			} else {
				oNode.style.display = 'block';
			}
		}
	}
}

/* Dialogs */
function closeDialog(){
	deleteNode('dialogs_container');
	el('whiteout').style.display = 'none';
}

/* Useful */
function el(id){
	return document.getElementById(id);
}

function deleteNode(id){
	el(id).parentNode.removeChild(el(id));
}

/* Cookie Help */
function remember_username(){
	username = document.getElementById('username').value;
	checkval = document.getElementById('checkbox_remember').checked;
	if(checkval){
		createCookie('mb_username',username,365);
	} else {
		eraseCookie('mb_username');
	}
	
	//Pass to to formal login
	return true;

}

function get_username(){
	if(document.getElementById('username')){
		if(document.getElementById('username').value==''){
			username = readCookie('mb_username');
			if(username!=null){
				document.getElementById('username').value=username;
				document.getElementById('checkbox_remember').checked=true;
				document.getElementById('password').focus();
			} else {
				document.getElementById('username').focus();
			}
		}
	}
}

function createCookie(name,value,days) {
if (days) {
	var date = new Date();
	date.setTime(date.getTime()+(days*24*60*60*1000));
	var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

/* Signet */
function _signet_xdebug_client_enabled(){
var state = false;
	state = el('_signet_xdebug_client_enabled').checked;
	iForms = document.forms.length;
	for(i=0;i<iForms;i++){
		oForm = document.forms.item(i);
		if(state){		
			if(!oForm.XDEBUG_SESSION_START){
				newChild = document.createElement("input");
				newChild.setAttribute("type","hidden");
				newChild.setAttribute("name","XDEBUG_SESSION_START");
				newChild.setAttribute("value","1");
				oForm.appendChild(newChild);
			}
			if(oForm.XDEBUG_SESSION_STOP){
				oldNode = oForm.XDEBUG_SESSION_STOP;
				oParent = oldNode.parentNode;
				oParent.removeChild(oldNode);
			}
		} else {
			if(!oForm.XDEBUG_SESSION_STOP){
				newChild = document.createElement("input");
				newChild.setAttribute("type","hidden");
				newChild.setAttribute("name","XDEBUG_SESSION_STOP");
				newChild.setAttribute("value","1");
				oForm.appendChild(newChild);
			}
			if(oForm.XDEBUG_SESSION_START){
				oldNode = oForm.XDEBUG_SESSION_START;
				oParent = oldNode.parentNode;
				oParent.removeChild(oldNode);
			}
		}
	}
	
}

function _signet_xdebug_showxml_enabled(){
var state = false;
	state = el('_signet_xdebug_showxml_enabled').checked;
	iForms = document.forms.length;
	for(i=0;i<iForms;i++){
		oForm = document.forms.item(i);
		if(state){		
			if(!oForm.debug){
				newChild = document.createElement("input");
				newChild.setAttribute("type","hidden");
				newChild.setAttribute("name","debug");
				newChild.setAttribute("value","1");
				oForm.appendChild(newChild);
			} else {
				oldNode = oForm.debug;
				oParent = oldNode.parentNode;
				oParent.removeChild(oldNode);
			}
		} else {
			if(oForm.debug){
				oldNode = oForm.debug;
				oParent = oldNode.parentNode;
				oParent.removeChild(oldNode);
			}
		}
	}
	
}

function urlencode( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // %          note: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'
    // *     example 2: urlencode('http://kevin.vanzonneveld.net/');
    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
                                     
    var histogram = {}, histogram_r = {}, code = 0, tmp_arr = [];
    var ret = str.toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The histogram is identical to the one in urldecode.
    histogram['!']   = '%21';
    histogram['%20'] = '+';
    
    // Begin with encodeURIComponent, which most resembles PHP's encoding functions
    ret = encodeURIComponent(ret);
    
    for (search in histogram) {
        replace = histogram[search];
        ret = replacer(search, replace, ret) // Custom replace. No regexing
    }
    
    // Uppercase for full PHP compatibility
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
        return "%"+m2.toUpperCase();
    });
    
    return ret;
}

