/**************************************************************************************************
* Copyright(c) 2009 Fabian Gerold, http://www.alumniserver.net
*
* This script is part of the AlumniServer project. It is free software; you can redistribute it
* and/or modify it under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option) any later version.
*
* The GNU General Public License can be found at http://www.gnu.org/copyleft/gpl.html.
* A copy is found in the textfile GPL.txt
*
* This script is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* General Public License for more details.
*
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************************************************/

function createRequest(){
	var httpRequest
	if(window.XMLHttpRequest) httpRequest=new XMLHttpRequest()
 	else if(window.ActiveXObject) httpRequest=new ActiveXObject("Microsoft.XMLHTTP")
	if(httpRequest==null){ alert("Your browser does not support XMLHTTP."); return null; }
 	return httpRequest
}
function IsNumeric(sText){
	var ValidChars = "0123456789.";
	var IsNumber=true;
	var Char;

	for(i=0; i<sText.length && IsNumber==true; ++i){ 
		Char = sText.charAt(i); 
      	if(ValidChars.indexOf(Char)==-1){
			IsNumber = false;
		}
	}
	return IsNumber;
}
   
function setLoading(p){while(p.hasChildNodes()) p.removeChild(p.lastChild);var img=document.createElement('img');img.setAttribute('src','src/img/loading_small.gif');p.appendChild(img)}
function passwordForm(){
	var par=document.getElementById('passwdP');while(par.hasChildNodes()) par.removeChild(par.lastChild);
	var fm=document.createElement('form');
	var table=document.createElement('table');var tr0=table.insertRow(0);var tr1=table.insertRow(1);
	var tr2=table.insertRow(2);
	var td00=tr0.insertCell(0);
	var td01=tr0.insertCell(1);
	var td10=tr1.insertCell(0);
	var td11=tr1.insertCell(1);
	var td20=tr2.insertCell(0);
	var td21=tr2.insertCell(1);
	td00.appendChild(document.createTextNode(strPassword+': '));
	var I=document.createElement('input');I.setAttribute('name','chPwd');I.id='chPwd';I.className='inp';I.type='password';td01.appendChild(I);
	td10.appendChild(document.createTextNode(strRepeatPassword+': '));
	var rI=document.createElement('input');rI.setAttribute('name','chPwdr');rI.id='chPwdr';rI.className='inp';rI.type='password';td11.appendChild(rI);
	var ab=document.createElement('input');ab.setAttribute('type','button');ab.className='redbtn';ab.setAttribute('value',strCancel);ab.onclick=hidePasswordForm;td20.appendChild(ab);
	var s=document.createElement('input');s.setAttribute('type','button');s.className='btn';s.setAttribute('value',strSavePassword);s.onclick=savePasswordForm;
	td21.appendChild(s);
	fm.appendChild(table);par.appendChild(fm);
}
function hidePasswordForm(){
	var par=document.getElementById('passwdP');
	while(par.hasChildNodes())par.removeChild(par.lastChild);
	var a=document.createElement('a');a.setAttribute("href","javascript:void(0);");
	a.onclick=passwordForm;a.appendChild(document.createTextNode('['+strChangePassword+']'));par.appendChild(a)
}
function savePasswordForm(){
	var pwd=document.getElementById("chPwd").value;
	var pwdr=document.getElementById("chPwdr").value;
	if(pwd!=pwdr){alert(strPasswordsWereNotIdentical);
	return;}if(pwd.length<6){alert(strLengthOfPasswordsNeedsToBeAtLeast6);
	return;
	}
	savePw=createRequest();var postdata="chPwd="+encodeURI(pwd)+"&chPwdr="+encodeURI(pwdr);
	var par=document.getElementById('passwdP');
	while(par.hasChildNodes())par.removeChild(par.lastChild);par.appendChild(document.createTextNode('Saving password...'));
	savePw.onreadystatechange=function (){
		if(savePw.readyState==4){
			if(savePw.status==200){
				while(par.hasChildNodes()) par.removeChild(par.lastChild);
				var p=document.createElement("p");par.appendChild(p);
				if(savePw.responseText=="true"){
					p.className="green";
					p.appendChild(document.createTextNode(strPasswordHasBeenChanged+'.'));
				}else{
					p.className="red";p.appendChild(document.createTextNode(strNoChangesSaved+'.'))
				}
			}else alert("Problem retrieving XML data:"+savePw.statusText)
		}
	};
	savePw.open("POST","src/a/editPw.php",true);
	savePw.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	savePw.setRequestHeader("Connection","close");savePw.send(postdata)}

function setMaxLength(id){
	var x=document.getElementById(id)
	var counter=document.getElementById('max')
	if(x.getAttribute('maxlength')){
		counter.appendChild(document.createTextNode('0/'+x.getAttribute('maxlength')))
		x.onkeyup=x.onchange=checkMaxLength
		x.onkeyup()
	}
}

function checkMaxLength(){
	var maxLength=this.getAttribute('maxlength')
	var counter=document.getElementById('max')
	var currentLength=this.value.length
	while(counter.hasChildNodes())counter.removeChild(counter.lastChild)
	if(currentLength>maxLength){
		counter.appendChild(document.createTextNode('maximum length of '+maxLength+' characters reached.'))
		this.value=this.value.substr(0,2000);
		this.scrollTop = this.scrollHeight;
	}
}
function checkUncheck(checkbox,send) {
	if(checkbox.checked==true){
		send.disabled = false;
	}
	else {
		send.disabled = true;
	}
}

//chkBox= new Image(15,15) 
//chkBox.src="src/img/msgDelete.gif" 
//chkBoxC= new Image(15,15) 
//chkBoxC.src="src/img/msgDelete2.gif" 
var sMsgs=new Array()
function selectMsg(mid,cell){
	unselect=false;for(i=0;i<sMsgs.length;++i)if(mid==sMsgs[i]){unselect=true;sMsgs.splice(i,1);break}
	var d=document.getElementById('msgDiv'+mid);
	if(unselect){d.style.border='#fff 1px solid';}else{d.style.border='#b55454 1px solid';sMsgs.push(mid);document['onkeypress']=detectEvent;}
	if(sMsgs.length>0){document.getElementById('del1').style.visibility='visible';}
	else{document.getElementById('del1').style.visibility='hidden';}
}
function unselectAll(){
	for(i=0;i<sMsgs.length;++i){
		var d=document.getElementById('msgDiv'+sMsgs[i]);d.style.border='#fff 1px solid';
	}
	sMsgs.length=0;document.getElementById('del1').style.visibility='hidden'
}
function delMsgs(box){
	if(!confirm(sMsgs.length+' '+strReallyDeleteSelectedMessages+'?')) return;
	if(sMsgs.length==0) return;
	var r=createRequest();
	r.onreadystatechange=function(){
		if(r.readyState==4){
			if(r.status==200){
				var numDeleted=r.responseText;
				if(numDeleted>0){
					for(i=0; i<sMsgs.length; ++i){
						var mid=sMsgs[i];
						var d=document.getElementById('msgDiv'+mid);
						while(d.hasChildNodes())d.removeChild(d.lastChild)
						var p = document.createElement("div");p.appendChild(document.createTextNode(strMessageDeleted));d.appendChild(p);
						d.style.border='0px';
					}
					sMsgs.length=0;
					document.getElementById('del1').style.visibility='hidden';
				}
				else alert('Could not delete message.'+r.responseText);
			}else alert('There was a problem with the request.');
		}
	}
	r.open('POST','src/a/delMsg.php', true);r.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	var ids=sMsgs[0];
	for(i=1;i<sMsgs.length;++i)ids+='a'+sMsgs[i];
	if(box=='inbox')r.send('mids='+ids);
	else if(box=='sent')r.send('midss='+ids)
}

var answerDiv=document.createElement("div")
var hiddenLink=document.createElement("div")
function hideLink(mid){
	//hiddenLink.style.visibility='visible'
	hiddenLink=document.getElementById('link'+mid)
	hiddenLink.style.visibility='hidden'
}

var m=new Array()
var curMsgDiv
var curMsg
function writeMsg(uid_to,div,mid){
	hide=false;for(i=0;i<m.length;++i)if(mid==m[i]){hide=true;m.splice(i,1);break}
	if(hide){
		answerDiv=document.getElementById(div)
		while(answerDiv.hasChildNodes()) answerDiv.removeChild(answerDiv.lastChild)
		return;
	}
	m.push(mid)
	curMsg=mid
	curMsgDiv=div
	answerDiv=document.getElementById(div)
	while(answerDiv.hasChildNodes()) answerDiv.removeChild(answerDiv.lastChild)
	var f=document.createElement("form")
	f.setAttribute("name","msgForm")
	answerDiv.appendChild(f)
	
	var input=document.createElement("textarea");input.id="msg";input.className="writeMsg";f.appendChild(input)
	f.appendChild(document.createElement("br"))
	document['onkeypress'] = detectEvent;
	var to=document.createElement("input");to.type="hidden";to.id="to";to.setAttribute("value",uid_to);f.appendChild(to)
	var c=document.createElement("input");c.type="button";c.setAttribute("value",strCancel);c.className="redbtn";c.style.marginRight='3px';f.appendChild(c)
	c.onclick=function(){
		answerDiv=document.getElementById(div)
		while(answerDiv.hasChildNodes()) answerDiv.removeChild(answerDiv.lastChild)
	}
	var s=document.createElement("input");s.type="button";s.setAttribute("value",strSend);s.className="btn";s.onclick=function(){sendMsg(div)};f.appendChild(s)
	input.focus()
}

function cancelWriteMsg(){
	if(m.length==0)return
	for(i=0;i<m.length;++i)if(curMsg==m[i]){m.splice(i,1);break}
	answerDiv=document.getElementById(curMsgDiv)
	while(answerDiv.hasChildNodes()) answerDiv.removeChild(answerDiv.lastChild)
}
		
function detectEvent(e) {
	var evt = e || window.event;
	if(evt.keyCode==27){
		cancelWriteMsg()
		unselectAll()
	}
	return document.defaultAction;
}

function writeMsgTo(uid_to,div){
	var d=document.getElementById(div);while(d.hasChildNodes())d.removeChild(d.lastChild)
	var f=document.createElement("form");d.appendChild(f)
	var ta=document.createElement("textarea");ta.id="msg";ta.setAttribute("name","msg");ta.className="writeMsg";f.appendChild(ta)
	f.appendChild(document.createElement("br"))
	var to=document.createElement("input");to.type="hidden";to.id="to";to.setAttribute("value",uid_to);f.appendChild(to)
	var c=document.createElement("input");c.type="button";c.setAttribute("value",strCancel);c.className="redbtn";c.style.marginRight='3px';f.appendChild(c)
	c.onclick=function(){while(d.hasChildNodes()) d.removeChild(d.lastChild)}
	var s=document.createElement("input");s.type="button";s.setAttribute("value",strSend);s.className="btn";s.onclick=function(){sendMsg(div)};f.appendChild(s)
	ta.focus()
}

function sendMsg(div){
	var msg=document.getElementById("msg").value;
	var to=document.getElementById("to").value
	var d=document.getElementById(div)
	setLoading(d)
	d.appendChild(document.createElement('br'));d.appendChild(document.createTextNode('Sending message...'))
	var m=createRequest();m.onreadystatechange=function(){
		if(m.readyState==4){
			while(d.hasChildNodes()) d.removeChild(d.lastChild);
			var p=document.createElement("p");d.appendChild(p);
			if(m.responseText=='true'){
				p.className="green";
				p.appendChild(document.createTextNode(strMessageHasBeenSentSuccessfully));
			}else{
				p.className="red";
				p.appendChild(document.createTextNode('Sending the message failed. Please try again.\n'));
				var pm=document.createElement("p");d.appendChild(pm);pm.appendChild(document.createTextNode(strMessage+':\n'+msg))
			}
		}
	}
	var msge=encodeURIComponent(msg)
	var data='msgTo='+to+'&msg='+msge;
	m.open('POST','src/a/sendMsg.php',true);
	m.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	m.send(data)
}
function loadMsg(m_id,box){
	setLoading(document.getElementById('msg'+m_id));
	var rm=createRequest();
	rm.onreadystatechange=function(){
		if(rm.readyState==4){
			var d=document.getElementById('msg'+m_id);
			d.innerHTML=rm.responseText.replace(/&lt;br \/&gt;/g,'<br />');
		}
	};
	var data;
	if(box=='inbox')data='mid='+m_id;
	else if(box=='sent')data='mids='+m_id;
	rm.open('POST','src/a/getMsg.php',true);
	rm.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	rm.send(data)
}

function searchFS(){
	var so=document.getElementById('searchOption2Div');
	so.innerHTML='';
	if(document.form1.searchOption1.value!='graduation')return;
	var sel='<select name="searchOption2" class="combo" style="width:80px;">';
	for(k=0;k<4;++k){
		
		if(k==1)
			sel+='<option value="' + k + '" selected>\u00b1 '+ +k+' '+strYear+'</option>';
		else
			sel+='<option value="' + k + '">\u00b1 '+ +k+' '+strYears+'</option>';
	}
	so.style.width='80px'
	so.innerHTML=sel;
}


function setPicture(path,owner,c){
	document['fullsize'].src=path
	var so=document.getElementById('owner');while(so.hasChildNodes())so.removeChild(so.lastChild);
	so.appendChild(document.createTextNode(owner));
	so.appendChild(document.createElement('br'));
	so.appendChild(document.createTextNode(c));
}
function checkVersion(){
	var dversion=document.getElementById('newestversion');
	if(dversion=='undefined'||dversion==null){
		return;
	}
	dversion.innerHTML='checking for newest version...';
	
	var rv=createRequest();
	rv.onreadystatechange=function(){
		if(rv.readyState==4){
			if(rv.status==200){
				var newest=rv.responseText;
				if(!IsNumeric(newest)){
					dversion.innerHTML='An error occured while checking for newest version.';
					return;
				}
				if(newest>version){
					dversion.innerHTML=newest+'<br/> A newer than the installed version is available.';
				}
				else if(newest==version){
					dversion.innerHTML=newest+'<br/> <div style="color:green;">You have the newest version installed.</div>';
				}
				else{
					dversion.innerHTML='An error occured while checking for newest version.';
				}
				
			}
		}
	}
	rv.open('POST','src/a/proxyAlumniServer.php', true);
	rv.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	rv.send('load=checknewestversion&lang='+lang)
}