// JavaScript - General Inclusion

window.reserveTop = 16;
window.reserveBottom = 34;

var searchfader, searchdiv, search_display;
var gen_opacitytimers = new Array();
var search_isfull = false;
/*
var cn_notes = new Array();
var cn_note_clickPos = new Array();
*/

//var screensaver_timer = setTimeout("application('ScreenSaver')",5000);

var cn_resize_area_active = false;

var generalloadold = window.onload ? window.onload : function () {};
window.onload = function (e) { window.cn_loadE=e; generalloadold(); cn_init(); cn_clockUpdate(); };

//window.onmousemove = function(e) { clearTimeout(screensaver_timer); setTimeout("application('ScreenSaver')",5000); };
//window.onmousedown = function(e) { clearTimeout(screensaver_timer); setTimeout("application('ScreenSaver')",5000); };
//window.onkeypress = function(e) { clearTimeout(screensaver_timer); setTimeout("application('ScreenSaver')",5000); };

window.oncontextmenu = function(e) { if(!e) e=window.event; if(e.returnValue) e.returnValue=false; return false; };
window.onclick = function(e) { if(!e) e=window.event; if((e.button&&e.button==2)||(e.which&&e.which==2)) { cn_contextMenu(e); if(e.returnValue) e.returnValue=false; return false; } };

/////////// general lower level functions: /////////////

function gen_ids(id) {
	return document.getElementById(id);
}

function getElementsByAttribute(attribute,tag) {
    var elements = new Array();
    var hits = new Array();
    elements = document.getElementsByTagName(tag);
    for(var t=0; t<elements.length; t++)
        if(elements[t].getAttribute(attribute) != null)
            hits[hits.length] = elements[t];
    return hits;
}


function cn_init(e) {
	if(e != cn_loadE)
		return false;
	document.oncontextmenu = window.oncontextmenu;		//IE fix
}




function gen_mouse(e,which) {
	if(!e) { e=window.event; }
	
	var mouseX, mouseY;
	if(e.pageX) { mouseX = e.pageX; mouseY = e.pageY; }
	else if(e.clientX) { mouseX = e.clientX+document.body.scrollLeft+document.documentElement.scrollLeft; mouseY = e.clientY+document.body.scrollTop+document.documentElement.scrollTop; }
	
	if(which.toLowerCase()=="y")
		return mouseY;
	else if(which.toLowerCase()=="x")
		return mouseX;
	else
		return false;
}

function cn_contextMenu(e) {
	//alert(e.button + " - "+e.which);
}

///////////////// XMLHTTP GET Functions: /////////////////
var xmlhttp_data = new Array();
function xmlhttp_get(url,output,returnf) {
	xmlhttp_data[output]=GetXmlHttpObject()
	if (xmlhttp_data[output]==null) {
		alert ("Your browser does not support HTTP requests.\nPlease visit www.mozilla.com to download the world's best web browser for free.");
		window.open("http://www.mozilla.com/en-US/");
		return false;
	} 
	xmlhttp_data[output].onreadystatechange=function() { if (xmlhttp_data[output].readyState==4 || xmlhttp_data[output].readyState=="complete") {eval(returnf);} };
	xmlhttp_data[output].open("GET",url,true);
	xmlhttp_data[output].send(null);
} 

function GetXmlHttpObject() {
	var xmlHttp=null;
	try { xmlHttp=new XMLHttpRequest(); }
	catch (e) {
		try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); }
		catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); }
	}
	return xmlHttp;
}


function tooltip(el,m) {
	if(!el || !m)
		return false;
	el.onmousemove = function(e) {
		if(!e){ e=window.event; }
		var mouseX, mouseY;
		if(e.pageX) { mouseX = e.pageX; mouseY = e.pageY; }
		else if(e.clientX) { mouseX = e.clientX+document.body.scrollLeft+document.documentElement.scrollLeft; mouseY = e.clientY+document.body.scrollTop+document.documentElement.scrollTop; }
		var tip = document.getElementById('tooltip');
		if(!tip) {
			tip = document.createElement('div');
			tip.setAttribute("id","tooltip");
			tip.style.left = "-999em";
			tip.style.top = "-999em";
			tip.innerHTML = m;
			document.body.appendChild(tip);
		}
		
		var winW = 800, winH = 600;
		if (parseInt(navigator.appVersion)>3) {
			if (navigator.appName=="Netscape") { winW = window.innerWidth;	winH = window.innerHeight; }
			if (navigator.appName.indexOf("Microsoft")!=-1) { winW = document.documentElement.clientWidth; winH = document.documentElement.clientHeight; }
		}
		
		if(mouseY+10+tip.offsetHeight > winH - 200)
			tip.style.top = (mouseY-20 - tip.offsetHeight)+"px";
		else
			tip.style.top = (mouseY+20)+"px";
		if(mouseY+10+tip.offsetHeight > winH - 200)
			tip.style.left = (mouseX-20 - top.offsetWidth)+"px";
		else
			tip.style.left = (mouseX+20)+"px";
	}
	el.onmouseout = function() { document.getElementById("tooltip").parentNode.removeChild(document.getElementById("tooltip")); }
	return true;
}


function gen_changeOpacity(iid, finalo, delay)
{
	if(!gen_ids(iid))
		return false;
	var IE = document.all?true:false;

	var what = gen_ids(iid);
	if(gen_opacitytimers[iid])
		clearTimeout(gen_opacitytimers[iid]);
	var currentopac;
	if(IE &&  what.filters.alpha)
		currentopac = parseFloat(what.style.filter.substring(what.style.filter.indexOf('=')+1,what.style.filter.length-1));
	else
		currentopac = what.style.opacity*100;

	var factor = 5;
	if(currentopac != finalo && currentopac <= 100 && currentopac >= 0)
	{
		if(navigator.userAgent.toLowerCase().indexOf('safari') > 0) {	factor *= 2;	}														////////////////////////////NOTE
		var opacity = (currentopac + factor*(finalo-currentopac)/Math.abs(finalo-currentopac) );
		
		if(IE && what.filters.alpha)	//IE
  			what.style.filter="alpha(opacity="+ opacity + ")";
		else
			what.style.opacity = opacity/100;

		gen_opacitytimers[iid] = setTimeout("gen_changeOpacity('"+iid+"',"+finalo+","+delay+");",[delay]);
	}
	else
	{
		if(IE && what.filters.alpha)	//IE
  			what.style.filter="alpha(opacity="+ finalo + ")";
		else
			what.style.opacity = finalo/100.0;
	}
}


function smoothresize(el, newW, newH, innerDiv) {
	if(document.getElementById(el)) { el=document.getElementById(el); }
	if(!el) { return false; }
	
	if(!el.id || el.id.length < 1)	{ el.id = "smoothresize_auto_id_"+Math.random()+"_"+Math.random(); }
	
	if(innerDiv && document.getElementById(innerDiv)) { innerDiv=document.getElementById(innerDiv); }
	if(innerDiv)
		gen_changeOpacity(innerDiv.id, 0, 20);
	
	var oldW = parseInt(el.style.width.substring(0, el.style.width.length - 2));
	var oldH = parseInt(el.style.height.substring(0, el.style.height.length - 2));

	var top,dsoctop;
	if(navigator.appName.indexOf("Microsoft") != -1)
		top = document.body.scrollTop;
	else
		top = window.pageYOffset;
	var dsoctop = top; //document.all? iebody.scrollTop : pageYOffset
	
	
	var winW = 2000, winH = 1500;
	if (parseInt(navigator.appVersion)>3) {
		if (navigator.appName=="Netscape") {	winW = window.innerWidth;	winH = window.innerHeight;	}
		if (navigator.appName.indexOf("Microsoft")!=-1) {	winW = document.documentElement.clientWidth;		winH = document.documentElement.clientHeight;	}
	}

	var mozmess = 0;
	var opacWait = 500;
	var factor = 1;
	var t = 0;
	if(oldW < newW) {
		for(var o=(oldW); o<=(newW); o+=1) {
			setTimeout("gen_ids('"+el.id+"').style.left = \""+(winW/2 - (o/2) - mozmess)+"px\";", (t)*factor + opacWait);
			setTimeout("gen_ids('"+el.id+"').style.width = '"+o+"px';", (t)*factor + opacWait);
			t += 1;
		}
	}
	else if(oldW > newW) {
		for(var o=(oldW); o>=(newW); o-=1) {
			setTimeout("gen_ids('"+el.id+"').style.left = \""+(winW/2 - (o/2) - mozmess)+"px\";", (t)*factor + opacWait);
			setTimeout("gen_ids('"+el.id+"').style.width = '"+o+"px';", (t)*factor + opacWait);
			t += 1;
		}
	}
	
	if(oldH < newH) {
		for(var p=(oldH); p<=(newH); p+=1) {
			setTimeout("gen_ids('"+el.id+"').style.top = \""+(dsoctop + winH/2 - p/2 - mozmess)+"px\";", (t)*factor + opacWait);
			setTimeout("gen_ids('"+el.id+"').style.height = '"+p+"px';",  (t)*factor + opacWait);
			t += 1;
		}
	}
	else if(oldH > newH) {
		for(var p=(oldH); p>=(newH); p-=1) {
			setTimeout("gen_ids('"+el.id+"').style.top = \""+(dsoctop + winH/2 - p/2 - mozmess)+"px\";", (t)*factor + opacWait);
			setTimeout("gen_ids('"+el.id+"').style.height = '"+p+"px';",  (t)*factor + opacWait);
			t += 1;
		}
	}
	if(innerDiv)
		setTimeout("gen_changeOpacity('"+innerDiv.id+"', 100, 50);", (t)*factor + (opacWait*2) );
	return ( (t)*factor + (opacWait*3) )
}

////////////// Cellnotes clock update: /////////////////

function cn_clockUpdate() {
	var clock = document.getElementById('cn_clock');
	if(clock) {
		var today=new Date()
		clock.innerHTML = ( today.getHours()==0 ? 12 : (today.getHours()<13?today.getHours():today.getHours()-12) ) + ":" + (today.getMinutes()<10?"0"+today.getMinutes():today.getMinutes()) + ":" + (today.getSeconds()<10?"0"+today.getSeconds():today.getSeconds()) + (today.getHours()<12?" AM":" PM");
	}
	setTimeout("cn_clockUpdate();",1000);
}


////////////// Cellnotes Search function: //////////////

function cn_search() {
	var u = cn_fade('searchfader',60,true);
	searchfader = gen_ids('searchfader');
	searchfader.onclick = function() { document.body.removeChild(searchfader); document.body.removeChild(searchdiv); }
	
	searchdiv = document.createElement("div");
	searchdiv.setAttribute("id","searchdiv");
	searchdiv.setAttribute("style","overflow:hidden; z-index:1000; position:absolute; width:0px; height:0px; top:50%; left:50%; padding:0px; background:#FFFFFF; border:1px solid #999999; opacity:1; filter:alpha(opacity=100); text-align:center;");
	searchdiv.style.cssText = "overflow:hidden; z-index:1000; position:absolute; width:0px; height:0px; top:50%; left:50%; padding:0px; background:#FFFFFF; border:1px solid #999999; opacity:1; filter:alpha(opacity=100); text-align:center;";
	searchdiv.innerHTML = "<span class=\"icon_close\" onclick=\"document.getElementById('searchfader').parentNode.removeChild(document.getElementById('searchfader')); document.getElementById('searchdiv').parentNode.removeChild(document.getElementById('searchdiv'));\"></span>";
	searchdiv.innerHTML += "<input type=\"text\" id=\"search_keywords\" title=\"Enter your search keywords\" style=\"display:block; width:80%; margin-left:10%; margin-right:10%; font-size:16px; font-weight:bold; font-family:Arial,Helvetica,Sans-Serif; color:#555555;\" />";
	searchdiv.innerHTML += "<input type=\"submit\" id=\"search_button\" value=\"Search\" onclick=\"document.getElementById('search_display').innerHTML = 'Searching...'; xmlhttp_get('http://www.cellnotes.ca/search.php?sid='+Math.random()+'&amp;q='+document.getElementById('search_keywords').value,'cn_search','cn_search_display(\\\'search_display\\\');');\" />";
	searchdiv.innerHTML += "<div id=\"search_display\" style=\"opacity:0; filter:alpha(opacity=0); overflow:auto; width:100%;\"></div>";
	document.body.appendChild(searchdiv);
	search_display = gen_ids('search_display');
	
	gen_ids('search_keywords').onkeydown = function(e) { if(!e) { e=window.event; } if( (e.keyCode && e.keyCode == 13) || (e.which && e.which == 13) ) { gen_ids('search_button').click(); } }
	
	setTimeout("smoothresize('searchdiv',200,50);",50+u);
	setTimeout("gen_ids('search_keywords').focus();",1050+u);
}

function cn_search_display(op) {
	if(search_isfull == true) {
		cn_search_update();
		return false;
	}
	/*
	var d = document.getElementById(op);
	if(!d) { alert("could not locate search output area"); return false; }
	*/
	/*gen_ids('search_display').style.opacity = "0";
	gen_ids('search_display').style.filter = "alpha(opacity=0)";*/
	/*gen_ids('search_display').style.height = "350px";
	gen_ids('search_display').style.position = "absolute";
	gen_ids('search_display').style.bottom = "0px;";*/
	var x = smoothresize('searchdiv',500,400,'search_display');
	setTimeout("gen_ids('search_display').style.height = '350px';",x);
	setTimeout("document.getElementById('"+op+"').innerHTML = xmlhttp_data['cn_search'].responseText; search_isfull = true;",x+1000);
}

function cn_search_update() {
	gen_ids('search_display').innerHTML = xmlhttp_data['cn_search'].responseText;
}


/////////////////////////////// login: ///////////////////////////////////

function cn_login() {
	var u = cn_fade('loginfader',60, true);
	//setTimeout("loginfader = document.getElementById('loginfader');",1000);
	//loginfader.onclick = function() { document.body.removeChild(loginfader); document.body.removeChild(logindiv); }
	
	logindiv = document.createElement("div");
	logindiv.setAttribute("id","logindiv");
	logindiv.setAttribute("style","overflow:hidden; z-index:1000; visibility:hidden; position:absolute; width:290px; height:290px; top:50%; left:50%; padding:0px; background:#FFFFFF; border:1px solid #999999; opacity:1; filter:alpha(opacity=100); text-align:center;");
	logindiv.style.cssText = "overflow:hidden; z-index:1000; visibility:hidden; position:absolute; width:290px; height:290px; top:50%; left:50%; padding:0px; background:#FFFFFF; border:1px solid #999999; opacity:1; filter:alpha(opacity=100); text-align:center;";
	//logindiv.innerHTML = "<span class=\"icon_close\" onclick=\"document.body.removeChild(document.getElementById('loginfader')); parentNode.parentNode.removeChild(parentNode);\"></span>";
	logindiv.innerHTML = "<img id=\"cn_title\" src=\"http://www.cellnotes.ca/images/logo_blur.png\" style=\"padding:5px; display:block; margin-left:auto; margin-right:auto; height:100px;\" />";
	logindiv.innerHTML += "<div style=\"margin:22px;\"><a href=\"javascript: void('Login as Guest');\" style=\"background:url('http://www.cellnotes.ca/images/guest_account.png') left no-repeat #CCCCCC; border:2px solid #006699; margin:22px; padding:20px; padding-left:52px; padding-right:6px;\" onclick=\"document.body.removeChild(document.getElementById('loginfader')); document.body.removeChild(logindiv);\">Guest Account</a></div>";
	logindiv.innerHTML += "<div>username</div><input type=\"text\" id=\"login_username\" style=\"display:block; width:80%; margin-left:10%; margin-right:10%; font-size:16px; font-weight:bold; font-family:Arial,Helvetica,Sans-Serif; color:#555555;\" />";
	logindiv.innerHTML += "<div>password</div><input type=\"password\" id=\"login_password\" style=\"display:block; width:80%; margin-left:10%; margin-right:10%; font-size:16px; font-weight:bold; font-family:Arial,Helvetica,Sans-Serif; color:#555555;\" />";
	logindiv.innerHTML += "<input type=\"submit\" id=\"login_button\" value=\"Login\" onclick=\"document.getElementById('login_display').innerHTML = 'Logging In...'; xmlhttp_get('http://www.cellnotes.ca/useraction.php?sid='+Math.random()+'&amp;a=login&amp;username='+document.getElementById('login_username').value+'&amp;password='+document.getElementById('login_password').value,'cn_login','cn_login_display(\\\'login_display\\\');');\" />";
	logindiv.innerHTML += "<div id=\"login_display\" style=\"opacity:0; filter:alpha(opacity=0); overflow:auto; margin-top:5px; height:auto; width:100%;\"></div>";
	document.body.appendChild(logindiv);
	//login_display = gen_ids('login_display');

	gen_ids('login_username').onkeydown = function(e) { if(!e) { e=window.event; } if( (e.keyCode && e.keyCode == 13) || (e.which && e.which == 13) ) { gen_ids('login_button').click(); } }
	gen_ids('login_password').onkeydown = function(e) { if(!e) { e=window.event; } if( (e.keyCode && e.keyCode == 13) || (e.which && e.which == 13) ) { gen_ids('login_button').click(); } }
	
	setTimeout("smoothresize('logindiv',300,300);",50+u);
	setTimeout("gen_ids('logindiv').style.visibility = 'visible'; gen_ids('login_username').focus();",1050+u);
}

function cn_login_display() {
	
	var r = xmlhttp_data['cn_login'].responseText;
	if(r=="true") {	//username + password are valid
		gen_ids('login_display').innerHTML = "Login Successful.";
		var x = smoothresize('logindiv',0,0);
		setTimeout("document.body.removeChild(document.getElementById('loginfader')); document.body.removeChild(document.getElementById('logindiv'));", x);
	}
	else {
		var x = smoothresize('logindiv',300,315,'login_display');
		gen_ids('login_username').value = "";
		gen_ids('login_password').value = "";
		gen_ids('login_username').focus();
		gen_ids('login_display').innerHTML = r=="username_fail"?"Unknown Username":"Incorrect Password";
		var c=0;
		var d = 2;
		for(var t=0; t<5; t++) {
			for(var y=0; y<20; y+=2) {	//right
				setTimeout("gen_ids('logindiv').style.marginLeft = '"+y+"px';",c*d);
				c++;
			}
			for(var y=20; y>-20; y-=2) {	//left
				setTimeout("gen_ids('logindiv').style.marginLeft = '"+y+"px';",c*d);
				c++;
			}
			for(var y=-20; y<=0; y+=2) {	//back
				setTimeout("gen_ids('logindiv').style.marginLeft = '"+y+"px';",c*d);
				c++;
			}
		}
	}
}



///////////////////// WINDOWS FOR CELLNOTES: ///////////////////////

var cn_application_id = 0;
var cn_application_windows = new Array();

function application(app) {
	var q = "id="+app;
	if(app.length)
		q = "name="+app;
	//xmlhttp_get("http://www.cellnotes.ca/application.php?sid="+Math.random()+"&amp;"+q,"cn_application_xml_"+cn_application_id,"cn_application_framework("+cn_application_id+");");
	xmlhttp_get("http://www.cellnotes.ca/application.php?sid="+Math.random()+"&"+q,"cn_application_xml_"+cn_application_id,"cn_application_framework("+cn_application_id+");");
	cn_application_id++;
}

var cn_window_clickPos = new Array();
var cn_window_titlebarEvents = new Array();
var cn_window_document_onmousemove;
var cn_window_maxZ = 0;
var cn_window_mousedowns = new Array();

function cn_application_framework(id) {
	var me = xmlhttp_data["cn_application_xml_"+id].responseXML;
	var maximum = cn_application_windows.length;
	
	
	
	window.eval(me.getElementsByTagName('javascript')[0].childNodes[0].nodeValue);
	
	
	var el = document.getElementsByTagName('div');
	for(var i in el) {
		if(el[i] && el[i].className && el[i].className.indexOf('cn_window_titlebar') > -1) {

			cn_window_document_onmousemove = document.onmousemove ? document.onmousemove : function(){};
			
			if(parseInt(el[i].parentNode.style.zIndex) > cn_window_maxZ)
				cn_window_maxZ = parseInt(el[i].parentNode.style.zIndex);

			if(el[i] && el[i].parentNode) {
				cn_window_mousedowns[el[i]] = el[i].parentNode.onmousedown?el[i].parentNode.onmousedown:function(){};
				el[i].parentNode.onmousedown = function(e) { cn_window_mousedowns[this](); cn_window_maxZ++; this.style.zIndex = cn_window_maxZ; };
			}
			el[i].onselectstart = new Function ("return false");

			el[i].onmousedown = function(e) {
							this.className += " cn_moveme";
							cn_window_document_onmousemove = document.onmousemove ? document.onmousemove : function(){};

							cn_window_clickPos[this] = new Array();
							cn_window_clickPos[this]['x'] = gen_mouse(e,'x')-this.parentNode.offsetLeft;
							cn_window_clickPos[this]['y'] = gen_mouse(e,'y')-this.parentNode.offsetTop;
							//cn_window_maxZ++;
							//this.parentNode.style.zIndex = cn_window_maxZ;
							document.onmousemove = function(e) {
											if(!e) { e=window.event; }
											cn_window_document_onmousemove();
											var el = document.getElementsByTagName('div');
											for(var i in el) {
												if(el[i] && el[i].className && el[i].className.indexOf('cn_moveme') > -1) {
													el[i].parentNode.style.top = (gen_mouse(e,'y') - cn_window_clickPos[el[i]]['y']) +"px";
													el[i].parentNode.style.left = (gen_mouse(e,'x') - cn_window_clickPos[el[i]]['x']) +"px";
												}
											}
										};
							return false;
						};
			el[i].onmouseup = function() {
							document.onmousemove = cn_window_document_onmousemove;
							if(this.className && this.className.indexOf("cn_moveme") > -1) {
								this.className = this.className.substring(0,this.className.indexOf("cn_moveme")-1);
								cn_window_clickPos[this] = null;
								}
							};
		}
	}
	
}

function cn_trash_empty(icon) {
	if(document.title.indexOf('Emptying Trash...') == -1) {
		var oldtitle=document.title;
		document.title = oldtitle+" | Emptying Trash...";
		setTimeout("document.title='"+oldtitle+"';",2000);
		md_icons[icon]=md_siteroot+"images/icons/trash_empty.png";
		md_refresh(true);	//just update images
	}
}

function cn_fade(iid, finalo, duration) {
	if(!iid)
		iid = "faded_"+Math.random();
	if(!finalo)
		finalo = 70;
	var div = document.createElement("div");
	div.setAttribute("id",iid);
	div.setAttribute("style","position:absolute; left:0px; top:0px; width:100%; height:2000px; background:#000000; opacity:0; filter:alpha(opacity=0); z-index:999;");
	div.style.cssText = "position:absolute; left:0px; top:0px; width:100%; height:2000px; background:#000000; opacity:0; filter:alpha(opacity=0); z-index:999;";
	//div.onclick = function() { document.body.removeChild(div); document.body.removeChild(logindiv); }
	document.body.appendChild(div);
	for(u=5; u<=finalo; u+=5)
		setTimeout("document.getElementById(\""+iid+"\").style.opacity="+u/100+"; document.getElementById(\""+iid+"\").style.filter='alpha(opacity="+u+")';",u*10);
	if(duration)
		return (u*10);
	else
		return iid;
}