/************************************************************************
	UebiMiau is a GPL'ed software developed by 
	 - Aldoir Ventura - aldoir@users.sourceforge.net
	 - http://uebimiau.sourceforge.net São Paulo - Brasil
   		
	***********************************************************************
	Version 3.2.0 Upgrades and templates developed by
	 - Todd Henderson - Lead Developer - http://tdah.us 
	 - Dave Rodgers - Developer - http://www.manvel.net 
	 - Laurent (AdNovea) - Developer - http://adnovea.free.fr
	 
	***********************************************************************
	 - Special thanks to the developers at 
	codeworxtech.com, tinymce.moxiecode.com
	telaen.org, phptoys.com, winged.info, ngcoders.com
	without help this project wouldn't be possible 
	
	***********************************************************************
	- File:			functions.js
	- Developer: 	Created by Laurent (AdNovea)
	- Date:			November 4, 2008
	- version:		(3.2.0) 1.0
	- Description:  All common javascript functions (eg. toolbar)
		PHP->JS variable passing is managed into functions.php

************************************************************************ */


// FUNCTIONS USED BY MESSAGES, FOLDERS and ALL TEMPLATES
// ===================================================

// Menu functions
	function refreshlist() { window.location.href  = 'process.php?lid=' + js_lid + '&tid=' + js_tid + '&refr=true&folder=' + js_encode_folder + '&pag=' + js_pag; }
	function goinbox() 	{ window.location.href  = 'messages.php?tid=' + js_tid + '&lid=' + js_lid + '&folder=inbox'; }
	function chat() 		{ window.location.href  = 'chat.php?lid=' + js_lid + '&tid=' + js_tid; }
	function newmsg() 		{ window.location.href  = 'newmsg.php?lid=' + js_lid + '&tid=' + js_tid + '&pag=' + js_pag + '&folder=' + js_encode_folder; }
	function calendar()   	{ window.location.href  = 'calendar.php?lid=' + js_lid + '&tid=' + js_tid; }
	function addresses() 	{ window.location.href  = 'addressbook.php?lid=' + js_lid + '&tid=' + js_tid; }
	function folderlist() 	{ window.location.href  = 'folders.php?lid=' + js_lid + '&tid=' + js_tid + '&folder=' + js_encode_folder; }
	function search() 		{ window.location.href  = 'search.php?lid=' + js_lid + '&tid=' + js_tid; }
	function prefs() 		{ window.location.href  = 'preferences.php?lid=' + js_lid + '&tid=' + js_tid; }
	function goend() 		{ window.location.href  = 'logout.php?lid=' + js_lid + '&tid=' + js_tid; }
	function help()		{ window.open('help.php?lid=' + js_lid + '&tid=' + js_tid,'Help','width=635, height=500, top=200, left=200, directories=no, toolbar=no, status=no, scrollbars=no, resizable=yes'); }
	function main() 	{ window.location.href  = 'main.php?tid=' + js_tid + '&lid=' + js_lid + '&folder=inbox'; }



// Submenu: messages flag/mark functions
	function flagmsg() 	{ with (document.form1) { decision.value = 'flagmsg'; submit(); } }
	function deflagmsg()  	{ with (document.form1) { decision.value = 'deflagmsg'; submit(); } }
	function markmsg() 	{ with (document.form1) { decision.value = 'mark'; submit(); } }
	function unmarkmsg() 	{ with (document.form1) { decision.value = 'unmark'; submit(); } }



// Submenu: Action functions
	function reply() 		{ document.msg.submit(); }
	function replyall() 	{ with (document.msg) { rtype.value = 'replyall'; submit(); } }
	function forward() 	{ with (document.msg) { rtype.value = 'forward'; submit(); } }
	function headers() 	{ mywin = window.open('headers.php?lid=' + js_lid + '&tid=' + js_tid + '&folder=' + js_encode_folder + '&ix=' + js_ix ,'Headers','width=550, top=200, left=200, height=320,directories=no,toolbar=no,status=no,scrollbars=yes,resizable=yes'); }
	function printit() 	{ window.open('printmsg.php?lid=' + js_lid + '&folder=' + js_encode_folder + '&ix=' + js_ix,'PrintView','resizable=1,top=100,left=100,width=700,height=500,scrollbars=1,status=0'); }


// Empty functions
//	function emptytrash() 	{ window.location.href  = 'folders.php?empty=trash&folder=' + js_encode_folder + '&goback=true';}
	function emptytrash() 	{ window.location.href  = 'folders.php?tid=' + js_tid + '&lid=' + js_lid + '&empty=' + js_sysmap_trash + '&folder=' + js_encode_folder + '&goback=true';}
	function emptyspam() 	{ window.location.href  = 'folders.php?tid=' + js_tid + '&lid=' + js_lid + '&empty=' + js_sysmap_spam + '&folder=' + js_encode_folder + '&goback=true';}


// Address management (Address book and block)
	function catch_addresses()	{ window.open('catch_address.php?lid=' + js_lid + '&tid=' + js_tid + '&folder=' + js_encode_folder + '&ix=' + js_ix,'Catch','width=550, top=200, left=200, height=200,directories=no,toolbar=no,status=no,scrollbars=yes'); }
	function block_addresses()	{ window.open('block_address.php?lid=' + js_lid + '&tid=' + js_tid + '&folder=' + js_encode_folder + '&ix=' + js_ix,'Block','width=400, top=250, left=250, height=200,directories=no,toolbar=no,status=no,scrollbars=yes'); }
	function spam_addresses() 	{ window.open('spam_address.php?lid=' + js_lid + '&tid=' + js_tid + '&folder=' + js_encode_folder + '&ix=' + js_ix,'Spam','width=400, top=250, left=250, height=200,directories=no,toolbar=no,status=no,scrollbars=yes'); }
	function add_address() 	{ window.location.href  = 'addressbook.php?lid=' + js_lid + '&tid=' + js_tid + '&opt=new'; }


// Read message either from message list or search	
	function readmsg(ix,read,folder) {
		if ( folder === undefined ) var folder = js_encode_folder;
	 window.location.href  = 'readmsg.php?lid=' + js_lid + '&tid=' + js_tid + '&folder=' + folder + '&pag=' + js_pag + '&ix='+ ix; 
	}
	
	function viewmsg(ix,read) {
	if(!read && no_quota)
		alert(quota_msg)
	else
  	document.getElementById('inline').src = 'viewmsg.php?folder=".urlencode($folder)."&pag=$pag&ix='+ix+'&tid=$tid&lid=$lid'; 
}
  
  function initIFrame () {document.getElementById('inline').src = 'iframe.php?tid=$itd&lid=$lid'; }
	

// Delete currently read message or multiple selected  messages from a folder
	function deletemsg() 	{ if (confirm(js_confirm_delete)) with (document.form1) { decision.value = 'delete'; submit(); } }

// Send to spam currently multiple selected  messages from a inbox
	function spammsg() 	{ if (confirm(js_confirm_spam)) with (document.form1) { decision.value = 'spam'; submit(); } }
	
//	function movemsg() { document.move.submit(); }
	function movemsg() { 
		 {
			with (document.form1) { decision.value = 'move'; submit(); } 
		}
	}

	
// Check/uncheck all items
	function sel() {
		with (document.form1) {
			for (i=0;i<elements.length;i++) {
				thiselm = elements[i];
				if (thiselm.name.substring(0,3) == 'msg') thiselm.checked = !thiselm.checked
			}
		}
	}


// Sort column ASC/DESC
	function sortby(col) {
		if(col == sort_colum) ord = (sort_order == 'ASC')?'DESC':'ASC';
		else ord = 'ASC';
		window.location.href  = 'process.php?lid=' + js_lid + '&tid=' + js_tid + '&folder=' + js_folder + '&pag=' + js_pag + '&sortby='+col + '&sortorder='+ord;
	}


// Open attached document dialog box
	function openmessage(attach) 	{ 
		window.open('readmsg.php?lid=' + js_lid + '&tid=' + js_tid + '&folder=' + js_encode_folder + '&pag=' + js_pag + '&ix=' + js_ix +
		 '&attachment='+attach,'','resizable=1,top=200,left=200,width=700,height=250,scrollbars=1,status=0'); 
	}


// MISCELLANEOUS FUNCTIONS
// ===================================================
	function admin() 				{ window.location.href  = 'admin.php?lid=' + js_lid + '&tid=' + js_tid; }
	
// Check folders names
// ---------------------------------------------------
	function create_form() {
		strPat = /[^A-Za-z0-9\s\-]/;
		frm = document.forms[0];
		strName = frm.newfolder.value
		mathArray = strName.match(strPat)
		if(mathArray != null) {
			alert(js_error_invalid_name)
			return false;
		} else {
			frm.submit();
		}
	}


// Enable selected stylesheet
// ---------------------------------------------------
	function setActiveStyleSheet(title) {
		
		var i, a, main;
		for (i=0; (a = document.getElementsByTagName("link")[i]); i++) {
			if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
				a.disabled = true;
				if(a.getAttribute("title") == title) a.disabled = false;
			}
		}
		document.getElementById('selskin').value = title;
	}


// Address book card's photo
// ---------------------------------------------------
	function Add_Photo(photo_id) {
	
		if (window.document.getElementById('email').value == "1") {
			alert(photo_msg);
			return;
		} else
			window.open('uploadphoto.php?lid=' + js_lid + '&tid=' + js_tid + '&id=' + photo_id + "&email=" + document.getElementById('email').value,'mywindow','width=350,height=125,left=200,top=200,screenX=0,screenY=100,scrollbars=0,menubar=0,status=0');
	}

	function remove_Photo() {
		window.document.getElementById('id_photo').src= '';
		window.document.form1.picturepath.value = '';
	}
	


// SPECIFIC FUNCTIONS FOR NEW MESSAGES
// ===================================================
// Add signature to message
	function addsig() {
		with (document.composeForm) {
			if(bsig_added || sig.value == '') return false;
			if(cksig.checked) {
				if(bIs_html) {					
					body.value +='<br><br>----<br>'+sig.value;
				} else
					body.value += '\\r\\n\\r\\n----\\r\\n'+sig.value;
			}
			cksig.disabled = true;
			bsig_added = true;
		}
		return true;
	}
	
// Attach document to message
	function upwin(rem) { 
		mywin = 'upload.php?lid=' + js_lid  + '&tid=' + js_tid;
		if (rem != null) mywin += '&rem='+rem ;
		else mywin += '';
		window.open(mywin,'Upload','width=400,height=100,left=200,top=200,scrollbars=0,resizable=0,menubar=0,status=0'); 
	}
	
	function doupload() {
		document.composeForm.tipo.value = 'edit';
		document.composeForm.submit();
	}
	

	function textmode() {
		with (document.composeForm) {
			textmode.value = 1;
			tipo.value = 'edit';
			submit();
		}
	}
	
// Send new message
	function sendmsg() {
		error_msg = new Array();
		frm = document.composeForm;
		check_mail(frm.to.value);
		check_mail(frm.cc.value);
		check_mail(frm.bcc.value);
		errors = error_msg.length;
	
		if(frm.to.value == '' && frm.cc.value == '' && frm.bcc.value == '')
			alert(js_error_no_recipients);
	
		else if (errors > 0) {
	
			if (errors == 1) errmsg = js_error_compose_invalid_mail1_s;
			else  errmsg = js_error_compose_invalid_mail1_p;
	
			for(i=0;i<errors;i++)
				errmsg += error_msg[i] + '\\r';
	
			if (errors == 1) errmsg += js_error_compose_invalid_mail2_s;
			else  errmsg += js_error_compose_invalid_mail2_p;
	
			alert(errmsg)
	
		} else {
			frm.tipo.value = 'send';
			frm.submit();
		}
	}
		
// Get address from address book
	function addrpopup(where) {
		url = 'quick_address.php?lid=' + js_lid + '&tid=' + js_tid + '&where=' + where;
		mywin = window.open(url,'AddressBook','width=420,height=350,top=200,left=200,scrollbars=0,menubar=0,status=0');
	}
	
// Add addresses into the address book
	function AddAddress(strType,strAddress) {
		obj = eval('document.composeForm.'+strType);
		if(obj.value == '') obj.value = strAddress
		else  obj.value = obj.value + ', ' + strAddress
	}
	
	function check_mail(strmail) {
		if(strmail == '') return;
		chartosplit = ',;';
		protectchar = '\"';
		temp = '';
		armail = new Array();
		inthechar = false; 
		lt = '<';
		gt = '>'; 
		isclosed = true;
	
		for(i=0;i<strmail.length;i++) {
			thischar = strmail.charAt(i);
			if(thischar == lt && isclosed) isclosed = false;
			if(thischar == gt && !isclosed) isclosed = true;
			if(thischar == protectchar) inthechar = (inthechar)?0:1;
			if(chartosplit.indexOf(thischar) != -1 && !inthechar && isclosed) {
				armail[armail.length] = temp; temp = '';
			} else temp += thischar;
		}
	
		armail[armail.length] = temp; 
	
		for(i=0;i<armail.length;i++) {
			thismail = armail[i]; strPat = /(.*)<(.*)>/;
			matchArray = thismail.match(strPat); 
			if (matchArray != null) strEmail = matchArray[2];
			else {
				strPat = /([-a-zA-Z0-9_$+.]+@[-a-zA-Z0-9_.]+[-a-zA-Z0-9_]+)((.*))/; matchArray = thismail.match(strPat); 
				if (matchArray != null) strEmail = matchArray[1];
				else strEmail = thismail;
			}
			if(strEmail.charAt(0) == '\"' && strEmail.charAt(strEmail.length-1) == '\"') strEmail = strEmail.substring(1,strEmail.length-1)
			if(strEmail.charAt(0) == '<' && strEmail.charAt(strEmail.length-1) == '>') strEmail = strEmail.substring(1,strEmail.length-1)
	
			strPat = /([-a-zA-Z0-9_$+.]+@[-a-zA-Z0-9_.]+[-a-zA-Z0-9_]+)((.*))/;
			matchArray = strEmail.match(strPat); 
			if(matchArray == null)
				error_msg[error_msg.length] = strEmail;
		}
	}
	

// Used in new message
	function set_newmsg_timeout() {
		window.setInterval(function() {
				new Ajax.Request('./inc/auth.php', {
						method: 'post',
						parameters: {action: 'pingSession'}
				});
		}, 100000);
	}
	

// Used in read message
	function sendReceipt(subj, msg) {
		new Ajax.Request('./inc/auth.php', {
			method: 'post',
			parameters: {action: 'sendReceipt', recipient: '" . $email["receipt-to"] . "', receipt_subj: subj, receipt_msg: msg}
		}); 
	}



// CHAT FUNCTIONs
// ===================================================
	var httpObject = null;
	var link = "";
	var timerID = 0;
	var js_lang = "";
	var js_nickName = "";

	var CHAT_SOUND_PLAYER 	= "inc/addons/dewplayer.swf";
	var CHAT_SOUND_PATH 	= "chat/sound/";
	var js_chatsound 		=  new Array();
	js_chatsound[0] 		= "alert.mp3";
	js_chatsound[1] 		= "login.mp3";
	js_chatsound[2] 		= "logout.mp3";
	js_chatsound[3] 		= "receive.mp3";
	js_chatsound[4] 		= "send.mp3";

	function clearchat() 	{ window.location.href  = './clearchat.php?lid=' + js_lid + '&tid=' + js_tid; }
	function endchat() 	{ window.location.href  = './logoutchat.php?lid=' + js_lid + '&tid=' + js_tid; }
	function updatechat() 	{ window.location.href  = './chat.php?lid=' + js_lid + '&tid=' + js_tid; }
	function loginchat() 	{ window.location.href  = './startchat.php?lid=' + js_lid + '&tid=' + js_tid; }
	
	
	

	function chat_beep(id) {
		var js_sound = CHAT_SOUND_PLAYER+"?mp3="+CHAT_SOUND_PATH+js_chatsound[id]+"&autostart=1";
		document.getElementById("chat_sound").data = js_sound; 
		document.getElementById("chat_audio").src = CHAT_SOUND_PATH+js_chatsound[id];
	}
	
	// TO BE DONE : Check if something has changed to output sound - USE THIS TO REFRESH USER AND FILES LIST
	// **************************************************************************
	function chat_check_change() {
		if (js_msg_size > js_msg_size_new) chat_beep(3);	// New message arrives
		if (js_msg_size < js_msg_size_new) chat_beep(0);	// Chat room has been cleared
		if (js_send_size > js_send_size_new) chat_beep(4);	// New file uploaded
		if (js_usr_size > js_usr_size_new) chat_beep(1);	// Someone has joined
		if (js_usr_size < js_usr_size_new) chat_beep(2);	// Someone has left
	// update file size values with new values
		js_msg_size = js_msg_size_new;
		js_send_size = js_send_size_new;
		js_usr_size = js_usr_size_new;
	}
	

	// Get the HTTP Object
	function getHTTPObject(){
		if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
		else if (window.XMLHttpRequest) return new XMLHttpRequest();
		else {
			alert("Your browser does not support AJAX.");
			return null;
		}
	}   
	
	// Change the value of the outputText field
	function setOutput(){
		if(httpObject.readyState == 4){
			var response = httpObject.responseText;
			var randomnumber=Math.floor(Math.random()*10000);
			var objDiv = document.getElementById("result");
			objDiv.innerHTML += response;
			objDiv.scrollTop = objDiv.scrollHeight;
			var inpObj = document.getElementById("msg");
			inpObj.value = "";
			inpObj.focus();
		}
	}
	
	// Change the value of the outputText field
	var chat_lastupdate;
	var chat_status;
	function setAll() {
		if(httpObject.readyState == 4){
			var response = httpObject.responseText;
			var randomnumber=Math.floor(Math.random()*10000);
			var objDiv = document.getElementById("result");
			var prev_length = objDiv.innerHTML.length;

			// Check for users/Files lists update
			update = response.split(':');					// Get timestamp and remove it
			chat_timestamp = update[0];
			if (chat_timestamp!=null && !isNaN(chat_timestamp)) {
				if (chat_lastupdate == undefined) chat_lastupdate = update[0];
				if (chat_timestamp != chat_lastupdate) { 
				// Force refresh ONLY if the chatter is NOT writing something (otherwise it erased the message and upset)
					if (document.getElementById('msg').value == "") {
						chat_lastupdate = chat_timestamp;		// If timestamp has changed, update users/file lists
						 window.location="chat.php?lid=" + js_lid + "&tid=" + js_tid;
					}
				}
				response = response.substring(chat_timestamp.length+1,response.length);
			} 
			update = response.split(':');					// Get status and remove it
			chat_status = update[0];
			if (chat_status!=null && !isNaN(chat_status)) {
				response = response.substring(chat_status.length+1,response.length);
				document.getElementById('status').value = chat_status;
			}
			objDiv.innerHTML = response;					// Display content

			// Generate sounds only when status is online
			if (chat_status < 2) {
				var cur_length = objDiv.innerHTML.length;		
				if (cur_length > prev_length) chat_beep(3);
				if (cur_length < prev_length) chat_beep(0);
			}
			// Scroll to the bottom of the discussion
			objDiv.scrollTop = objDiv.scrollHeight;
		}
	}
	
	// Encode the string into number to become insensitive to entities
	function encode_msg(stt) {
		var result = "";
		for (var i=0; i < stt.length; i++) result += ":"+stt.charCodeAt(i);
		return result;
	}

	// Implement business logic    
	function doWork(){    
		httpObject = getHTTPObject();
		if (httpObject != null) {
			var msg = encode_msg(document.getElementById('msg').value);
			link = "./message.php?nick=" + js_nickName+"&msg=" + msg + "&lid=" + js_lid + "&tid=" + js_tid;
			httpObject.open("GET", link , true);
			httpObject.onreadystatechange = setOutput;
			httpObject.send(null);
		}
	}
	
	// Implement business logic    
	function doReload(){    
		httpObject = getHTTPObject();
		var randomnumber=Math.floor(Math.random()*10000);
		if (httpObject != null) {
			link = "./message.php?all=1&rnd=" + randomnumber + "&lid=" + js_lid + "&tid=" + js_tid;
			httpObject.open("GET", link , true);
			httpObject.onreadystatechange = setAll;
			httpObject.send(null);
		}
	}
	
	// Setup time for page refresh
	function UpdateTimer() {
		doReload();   
		timerID = setTimeout("UpdateTimer()", 2000);
	}
	
	// On key pressed, process line user entry
	function keypressed(e){
		if(e.keyCode=='13'){
			doWork();
		}
	}
	

//-- Needed to resize on user Update request --//
	function chatroom_resize() {
		var BoxHeight = parent.document.body.clientHeight;
		var BoxWidth = parent.document.body.clientWidth;
		
		if (BoxHeight != "") {
			BoxHeight -= 140;	// Webmail Banner and Toolbar heights
			BoxHeight -= 53+24;	// Chat box banner, tabs and sender heights
			document.getElementById('result').style.height = BoxHeight + 'px';
			BoxHeight -= 11;	// Div alignement
			document.getElementById('users').style.height = (BoxHeight*0.7) + "px";
			document.getElementById('files').style.height = (BoxHeight*0.3)+ "px";
			document.getElementById('smileys').style.top = (BoxHeight-20)+ "px";
		}
		if (BoxWidth != "") {
			BoxWidth -= 180; // Left panel width
			document.getElementById('upfiles').style.left = (BoxWidth-295) + "px";
			BoxWidth -= 360; // Send button and Status width
			document.getElementById('msg').style.width = BoxWidth+ "px";
		}
	}

	function show_smileys() {
		if (document.getElementById('smileys').style.display == 'block')
			document.getElementById('smileys').style.display = 'none';
		else 
			document.getElementById('smileys').style.display = 'block';
	}
	
	function add_smiley(id) {
		document.getElementById('smileys').style.display = 'none';
		document.getElementById('msg').value += " "+smiley_code[id]+" ";
		document.getElementById('msg').focus();
	}
	
			
//-- Needed to resize on user Update request --//
	function admin_resize() {
		var BoxHeight = parent.document.body.clientHeight;
		var BoxWidth = parent.document.body.clientWidth;
		
		if (BoxHeight != "") {
			BoxHeight -= 140;	// Webmail Banner and Toolbar heights
			BoxHeight -= 53+24;	// Chat box banner, tabs and sender heights
			document.getElementById('result').style.height = BoxHeight + 'px';
			BoxHeight -= 11;	// Div alignement
			document.getElementById('users').style.height = (BoxHeight*0.7) + "px";
			document.getElementById('files').style.height = (BoxHeight*0.3)+ "px";
			document.getElementById('smileys').style.top = (BoxHeight-20)+ "px";
		}
		if (BoxWidth != "") {
			BoxWidth -= 180; // Left panel width
			document.getElementById('upfiles').style.left = (BoxWidth-295) + "px";
			BoxWidth -= 360; // Send button and Status width
			document.getElementById('msg').style.width = BoxWidth+ "px";
		}
	}
	
	
				
				