var rpc = new RPCProxy("/inc/ajax_dispatcher.php5");
//var rpc = new RPCProxy("/noteti/inc/ajax_dispatcher.php5");

function init(){
	contextInit(); // init context menu API
	
	setLayout();	
	rpc.loginCookie();	
	window.onresize=setLayout;
}

var global_view_state="welcome";
function setView(state){
	global_view_state=state;	
	$("loader").style.display		="none";		
	$("mask").style.display			="none";		
	$("welcome").style.display		="none";	
	$("userTag").style.display		="none";		
	$("register").style.display		="none";
	$("profile").style.display		="none";			
	$("emailNote").style.display	="none";
	setLayout();
	
	if(state=="loader"){
		$("mask").style.display			="block";	
		$("loader").style.display		="block";		
	}else if(state=="welcome"){
		changeTheme(1);
		$("newbieAlert").style.display	="none";
		$("mask").style.display			="block";		
		$("welcome").style.display		="block";
		$("welcome").style.zIndex 		= "101";
	}else if(state=="register"){
		$("mask").style.display			="block";		
		$("newbieAlert").style.display	="block";
		$("userTag").style.display		="block";		
		$("register").style.display		="block";					
	}else if(state=="desktop"){
		$("userTag").style.display		="block";		
	}else if(state=="error"){
		$("mask").style.display			="block";	
		$("error").style.display 		= "block";
	}else if(state=="loginAction"){
		$("mask").style.display			="block";
		$("welcome").style.display 		= "block";
		$("welcome").style.zIndex 		= "99";
		$("loader").style.display 		= "block";
	}else if(state=="profile"){		
		$("mask").style.display			="block";
		$("profile").style.display		="block";		
	}else if(state=="emailNote"){
		$("mask").style.display			="block";
		$("emailNote").style.display	="block";
	}	
}

function setLayout(){
	var scrCenter = getCenter();	
	
	$("loader").style.top = (scrCenter.y-27)+"px";
	$("loader").style.left = (scrCenter.x-85)+"px";
	
	$("error").style.top = (scrCenter.y-35)+"px";
	$("error").style.left = (scrCenter.x-150)+"px";
		
	$("welcome").style.top = (scrCenter.y-190)+"px";
	$("welcome").style.left = (scrCenter.x-290)+"px";
	
	$("register").style.top = (scrCenter.y-100)+"px";
	$("register").style.left = (scrCenter.x-125)+"px";
	
	$("profile").style.top = (scrCenter.y-130)+"px";
	$("profile").style.left = (scrCenter.x-125)+"px";
	
	$("emailNote").style.top = (scrCenter.y-50)+"px";
	$("emailNote").style.left = (scrCenter.x-100)+"px";
		
	$("newbieAlert").style.left = (2*scrCenter.x-160)+"px";			
	$("userTag").style.left = (2*scrCenter.x-150)+"px";
	$("status").style.left = (2*scrCenter.x-70)+"px";				

}

function getCenter(){
	return {"y":parseInt(document.body.scrollTop+document.body.clientHeight/2),"x":parseInt(document.body.scrollLeft+document.body.clientWidth/2)};
}


function saveNote(win,viewOnly,create){	
	
	n = new Note(win.id.substr(3));
	if(!viewOnly){
		n.title = win.title;
		n.content = win.contentDiv.innerHTML;
	}
	n.pos_x = parseInt(win.mainDiv.style.left);
	if(!n.x) n.x=0;
	n.pos_y = parseInt(win.mainDiv.style.top);
	if(!n.y) n.y=0;
	n.width = parseInt(win.dimensions.width);
	n.height = parseInt(win.dimensions.height);
	n.focus_sequence = parseInt(win.focusSeq);
	
	if(create){
		rpc.createNote(n);
		return;
	}
	
	if(viewOnly)
		rpc.updateNoteView(n);
	else	
		rpc.updateNote(n);		
}

function saveNoteView(win){
	saveNote(win,true);
}

function removeNote(win){
	// mark es temporary deleted here	
	rpc.deleteNote(win.id.substr(3));		
	
}

function startEditNote(win){
	e = win.getEditor();
	
	if(e.value.indexOf("double-click to edit")>0){
		e.value="";
	}	

}

function out(){	
	maskScreen(1);
	var goOut = false;
	
	if(global_user_info.status==1) // is registered user
		goOut = confirm("Are you sure to logout?");
	else	
		goOut = confirm("You've logged in as a guest!\nIf you logout now, you won't be able to login to this account and all of your notes will be lost!\nIn order to make your notes permament, create a FREE user account by clicking 'Sign Up' button on the right.\nAre you sure to logout?");
	if(goOut){
		setView("loader");
		rpc.logout();
	}else{
		setView("desktop");
	}
}

function profile(){	
	if(global_user_info.status!=1){ // not a  registered user
		$("changePasswordTable").style.display="none";
	}else{
		$("changePasswordTable").style.display="block";
		$("changePassword").checked = false;		
		$("passwordChangeDiv").style.display="none";
		$("new_password").value = "";
		$("new_password_confirm").value = "";	
	}
	setView("profile");		
}

function pdfExport(){	
	if(WindowMng.windows.length==0){
		alert("You don't have any notes to export ?!");
		return;
	}
	window.open("note2pdf.php5");
}

function maskScreen(on){
	el = document.getElementById("mask");
	if(!el){
			el = document.createElement("div");
			el.id="mask";						
			el.style.position="absolute";
			el.style.top=0;
			el.style.left=0;
			el.style.width="100%";
			el.style.height="100%";
			el.style.zIndex=100;
			document.body.appendChild(el);
	}
	
	if(on){		
		el.style.display="block";
	}else{
		el.style.display="none";
	}
}


function setMenuInfo(s){	
	if(s==""){
		$("menuInfo").innerHTML=s;	
		if(typeWriterTimer)
			window.clearTimeout(typeWriterTimer);
	}
	else
		type('menuInfo',s,1);
	
}

typeWriterTimer = null;
function type(id,str,n){
	
	$(id).innerHTML = str.substr(0,n);
	if(n<str.length)
		typeWriterTimer  = window.setTimeout("type('menuInfo','"+str+"',"+(n+1)+")", (document.all)?25:15)  
}

function cascade(){
	if(WindowMng.windows.length==0){
		alert("You don't have any notes?!");
		return;
	}
	WindowMng.cascade();
	saveAllNotePos();

}

function tile(){
	if(WindowMng.windows.length==0){
		alert("You don't have any notes?!");
		return;
	}
	WindowMng.tile();
	saveAllNotePos();
}

function saveAllNotePos(){
	var poslist = new Array();
	for(i=0;i<WindowMng.windows.length;i++){		
		if(WindowMng.windows[i].editable){
			w = WindowMng.windows[i];
			poslist.push({"id":w.id.substr(3),"pos_x":parseInt(w.mainDiv.style.left),"pos_y":parseInt(w.mainDiv.style.top)})			
		}
	}
	rpc.updateNotePosMulti(poslist);
}

var month=new Array(12);
	month[0]="Jan";
	month[1]="Feb";
	month[2]="Mar";
	month[3]="Apr";
	month[4]="May";
	month[5]="June";
	month[6]="July";
	month[7]="Aug";
	month[8]="Sep";
	month[9]="Oct";
	month[10]="Nov";
	month[11]="Dec";

var day = Array(7);
	day[0] = "Sun";
	day[1] = "Mon";
	day[2] = "Tue";
	day[3] = "Wed";
	day[4] = "Thu";
	day[5] = "Fri";
	day[6] = "Sat";
	

function create(){	
	if(WindowMng.windows.length>=20){
		alert("Sorry, you can not have more than 20 notes");
		return;
	} 	
	var now = new Date();		
	var fDate = day[now.getDay()]+", ";
	
	var dateOfM= now.getDate();	
	if(dateOfM<=10)
		dateOfM = "0"+dateOfM;
		
	var hours = now.getHours();	
	if(hours<10)
		hours ="0"+hours;
	var mins = now.getMinutes();
	if(mins<10)
		mins ="0"+mins;
	var secs = now.getSeconds();
	if(secs<10)
		secs = "0"+secs;
		
	fDate +=dateOfM+" "+month[now.getMonth()]+" "+now.getFullYear()+" "+hours+":"+mins+":"+secs;	
	var w = new Window("",fDate,{"editable":true,"width":300,"height":150,"onChange":saveNote,"onMove":saveNoteView,"onClose":removeNote,"onEnterEditor":startEditNote});	
	w.setContent("<span class=\"hintText\">double-click to edit</span>");	
	saveNote(w,false,true);		
}


function login(){
	$("loginFailed").innerHTML="&nbsp;";
	setView("loginAction");
	rpc.login($("uname").value,$("pass").value,$("remember").checked);
	$("uname").value="";
	$("pass").value="";
	$("remember").checked=false;
	
}

function passRecovery(){
	if($("email").value.length>0)
		rpc.resetPassword($("email").value);

}

function signup(){	
	setView("loader");
	rpc.signup($("reg_uname").value,$("reg_pass").value,$("reg_pass2").value,$("reg_email").value,$("reg_agree").checked?1:0)
}

function handleEnter(e,action){
	if(getPressedKeyCode(e)==13)
		action();
}

function changeTheme(id){
	if(id)
		$("themeSelector").selectedIndex=id-1;
	var skin = $("themeSelector").options[$("themeSelector").selectedIndex].value;
	$("skin").href="css/"+skin+".css";
}

function enablePasswordChange(){	
	$("new_password").disabled = !$("changePassword").checked;
	$("new_password_confirm").disabled = !$("changePassword").checked;
	$("passwordChangeDiv").style.display = $("changePassword").checked?"block":"none";
}


function updateUser(){
	setView("loader");	
	$("profile_error_msg").style.display="none";	
	if($("changePassword").checked){
		if($("new_password").value=="" || $("new_password_confirm").value=="" ){
			$("profile_error_msg").style.display="block";
			$("profile_error_msg").innerHTML = "Enter your new password!";
			setView("profile");
			return;
		}
		rpc.updateUser($("themeSelector").selectedIndex+1,$("new_password").value,$("new_password_confirm").value);
	}else	
		rpc.updateUser($("themeSelector").selectedIndex+1);		
}

/* bean class for Ajax interaction */
function Note(id){
	this.id 	= id;
	this.title  = "";
	this.content = "";
	this.pos_x		= 0;
	this.pos_y		= 0;
	this.width	= 0;
	this.height = 0;
	this.focus_sequence = 1;
	this.createdOn ="";
	this.lastModified = "";	
	
}	

function showTooltip(msg,x,y,timeout){
	var tEl = document.createElement("div");
	tEl.className="tooltip";
	tEl.style.opacity="1.0";
	tEl.style.filter="alpha(opacity=99)";
	
	tEl.style.top=parseInt(y)+"px";
	tEl.style.left=parseInt(x)+"px";
	tEl.innerHTML=msg;	
	document.body.appendChild(tEl);	
	tEl.id = "tip"+Math.ceil(Math.random()*10000);
	if(typeof(timeout)!="undefined"){		
		window.setTimeout("fadeoutTooltip('"+(tEl.id)+"')",timeout*1000)
	}
}

function fadeoutTooltip(id){		
	var tEl = $(id);
	if(document.all){
		var opa = parseInt(tEl.style.filter.substring(14,17))-10;
		tEl.style.filter="alpha(opacity="+opa+")";
		if(opa<=0)
			return;		
	
	}else{
		
		tEl.style.opacity = parseFloat(tEl.style.opacity)-0.1;
		if(tEl.style.opacity<=0)
			return;
	}		
	window.setTimeout("fadeoutTooltip('"+id+"')",70);
}

function fadeOutMessage(msg,x,y,cssClassName){
	var div = document.createElement("div");
	div.id = "fadingMsg"+Math.ceil(Math.random()*10000);
	div.className = cssClassName;
	div.style.position = "absolute";
	div.style.left   = x+"px";
	div.style.top	 = y+"px";
	div.innerHTML = msg;
	document.body.appendChild(div);						
	fadeOut(div.id,1.0);
}
		
function fadeOut(id,tOp){			
	var el = document.getElementById(id);
	el.style.opacity = tOp;
	if(document.all)
		el.style.filter = "alpha(opacity="+tOp*100+")";
	el.style.top = parseInt(el.style.top)-3+"px";
	if(tOp<=0){
		el.style.display = "none";
		return;
	}
	setTimeout("fadeOut('"+id+"',"+(tOp-0.02)+")",40);
}

function markNoteAsImportant(winId){
	WindowMng.getWinById(winId).titleDiv.childNodes[1].style.color="#FF3333";	
}

function emailNote(){
	if($("emailnote_email").value.length>0){			
		rpc.emailNote(WindowMng.windows[WindowMng.windows.length-1].id.substr(3),$("emailnote_email").value);
		$("emailnote_email").value="";
		setView("desktop");
	}
}