// Protospace Main Javascript file
// (C) 2007 Glan Thomas


// Cookie Management Class

CookieMan =
{
	setCookie : function (name, value, path, expires, domain, secure) {
		document.cookie= name + "=" + escape(value) +
			((expires) ? "; expires=" + expires.toGMTString() : "") +
			((path) ? "; path=" + path : "") +
			((domain) ? "; domain=" + domain : "") +
			((secure) ? "; secure" : "");
	},
	
	getCookie : function(name) {
		var dc = document.cookie;
		var prefix = name + "=";
		var begin = dc.indexOf("; " + prefix);
		if (begin == -1) {
			begin = dc.indexOf(prefix);
			if (begin != 0) return null;
		} else {
			begin += 2;
		}
		var end = document.cookie.indexOf(";", begin);
		if (end == -1) {
			end = dc.length;
		}
		return unescape(dc.substring(begin + prefix.length, end));
	},
	
	deleteAll : function()
	{
		var ca = document.cookie.split(';');
		for(var i=0;i<ca.length;i++) 
			document.cookie = ca[i].split('=')[0]+"=; path=/";
	}
}

// Icon Cache Class
// icons are caches to that when an item is Puffed the new image can be inserted without causing a flicker.

IconCache =
{
	icons : new Array(),
	
	init : function(win)
	{
		var images = win.getElementsByTagName('img');
		for(var i = 0; i<images.length; i++)
		{
			var icon = document.createElement('img');
			icon.src = images[i].src;
			this.icons[images[i].getAttribute('name')] = icon;
		}
	},
	
	getIcon : function(name)
	{
		return this.icons[name];
	}
}


// Application Launcher Class

AppLauncher =
{
	launchApp : function (theApp,launcher,args)
	{
		if (launcher)
		{
			var dup = launcher.cloneNode(true);
			var iconWidth = dup.getElementsByTagName('img')[0].style.width;
			if (!browser.isIE)
			{
				dup.removeChild(dup.getElementsByTagName('img')[0]);
				dup.insertBefore(IconCache.getIcon(launcher.getElementsByTagName('img')[0].getAttribute('name')),dup.firstChild);
			 	dup.getElementsByTagName('img')[0].style.width = iconWidth;	
			}
			dup.style.position = 'absolute';
			var pos = getGlobalPos(launcher);
			dup.style.top = pos[1];
			dup.style.left = pos[0];
			
			if (launcher.parentNode.id == 'desktop')
				$('desktop').appendChild(dup);	
			else
				$('lanuchEffects').appendChild(dup);
		
			Effect.Puff(dup,{ duration : 0.5, afterFinish : function () 
			{
				dup.parentNode.removeChild(dup);
				AppLauncher.initApp(theApp,args);
			}});
		}
		else
			AppLauncher.initApp(theApp,args);
	},
		
	initApp : function (theApp,args)
	{	
		new Ajax.Updater(document.getElementById('lanuchArea'),'apps/'+theApp+'/init.php',{parameters: ((args) ? args : ''), method: 'get', evalScripts: true});
	},
	
	openWindow : function(id,content_url,vars)
	{
		if (WindowMan.getWindowById(id))
			WindowMan.makeActive(WindowMan.getWindowById(id));
		else
		{
			vars.x = (vars.x ? vars.x : ($('screen').childNodes.length) * 25);
			vars.y = (vars.y ? vars.y : ($('screen').childNodes.length) * 25);
		
			vars.x = (CookieMan.getCookie('window_'+id+'_x') ? CookieMan.getCookie('window_'+id+'_x') : vars.x);
			vars.y = (CookieMan.getCookie('window_'+id+'_y') ? CookieMan.getCookie('window_'+id+'_y') : vars.y);
			if (vars.resize)
			{
				vars.w = (CookieMan.getCookie('window_'+id+'_w') ? CookieMan.getCookie('window_'+id+'_w') : vars.w);
				vars.h = (CookieMan.getCookie('window_'+id+'_h') ? CookieMan.getCookie('window_'+id+'_h') : vars.h);
			}
			WindowMan.makeActive(WindowMan.createWindow(id,vars)); 
		}
		new Ajax.Updater(WindowMan.getWindowContent(WindowMan.getWindowById(id)),content_url,{method: 'get', evalScripts: true});
	}
	
}


// Window Manager Class

WindowMan =
{
	activeWindow : null,
	currentZindex : 0,

	getWindowById : function (id)
	{
		 return document.getElementById('window_'+id);
	},

	makeActive : function(node)
	{
		if (this.activeWindow)
			this.activeWindow.style.opacity = '0.85';
		
		if (node)
		{
			this.activeWindow = node.parentNode;
			this.activeWindow.style.opacity = '1.0';
			this.activeWindow.style.zIndex = ++this.currentZindex;
			document.getElementById('desktop').parentNode.className = 'inactive';
		}
		else
		{
			this.activeWindow = null;
			document.getElementById('desktop').parentNode.className = 'active';
		}
	},
	
	closeWindow : function (node)
	{
		Effect.Fade(node,{ duration: 0.4, afterFinish: function () 
		{ 
			WindowMan.activeWindow = null;
			node.parentNode.parentNode.removeChild(node.parentNode); 
			var nodes = document.getElementById('screen').childNodes;
			var z = -1;
			var nextWindow = null;
			for(var i=0; i<nodes.length;i++)	
			{
				if (nodes[i].style)
				{
					if (nodes[i].style.zIndex > z)
					{
						z = nodes[i].style.zIndex;
						nextWindow=nodes[i];
					}
				}
			}
			if (nextWindow)
				WindowMan.makeActive(nextWindow.firstChild);	
			else
				WindowMan.makeActive(null);	
		}});
	},
	
	getWindowOptions : function(win)
	{
		var panels = win.getElementsByTagName('div');
		for(var i=0; i<panels.length; i++)
			if (panels[i].className == 'options')
				return panels[i];
		return null;
	},
	
	optionsWindow : function(win)
	{
		var options = this.getWindowOptions(win.parentNode.parentNode);
		if (options.style.display == 'none')
		{
			Effect.SlideDown(options,{duration:0.4});
			win.style.backgroundPosition= "0 -75px";
		}
		else
		{
			Effect.SlideUp(options,{duration:0.4});
			win.style.backgroundPosition= "0 0";
		}
	},
	
	showOptionsWindow : function(win)
	{
		var options = this.getWindowOptions(win.parentNode.parentNode);
		if (options.style.display == 'none')
		{
			Effect.SlideDown(options,{duration:0.4});
			win.style.backgroundPosition= "0 -75px";
		}
	},
	
	hideOptionsWindow : function(win)
	{
		var options = this.getWindowOptions(win.parentNode.parentNode);
		if (options.style.display != 'none')
		{
			Effect.SlideUp(options,{duration:0.4});
			win.style.backgroundPosition= "0 0";
		}
	},
	
	createWindow : function (id,vars)
	{		
		var element = document.createElement("div");
		element.style.display = 'none';
		element.style.position = 'relative';
		var html = '';
		html+='<div id="window_'+id+'" class="window" style="left:'+vars.x+'; top:'+vars.y+'; width:'+vars.w+'; height:'+vars.h+';" onclick="WindowMan.makeActive(this)">' +
					'<div class="top_left" onmousedown="if (navigator.vendor) return false;"><div class="close_button" onclick="WindowMan.closeWindow(this.parentNode.parentNode);"></div></div>' +
					'<div class="top_center" onmousedown="WindowTool.moveStart(event,this);"><div></div></div>' +
					'<div class="top_right" onmousedown="if (navigator.vendor) return false;">' +
						((vars.options) ? '<div class="options_button" onmousedown="WindowMan.optionsWindow(this);"></div>' : '') +
					'</div>' +
					'<div class="middle_left"><div class="window_options_holder"></div><div class="middle_right"><div class="middle_center">' +
						'<table style="height: 100%; width: 100%; vertical-align: middle; text-align: center;" cellpadding="0" cellspacing="0"><tr><td>' +
						'<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0" width="24" height="24" id="myMovieName" wmode="transparent"><param name="wmode" value="transparent"/><param name="movie" value="images/loading.swf"/><param name="quality" value="high"/>' +
						'<embed src="images/loading.swf" wmode="transparent" quality="high" width="24" height="24" name="myMovieName" align="" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed></object>' +
						'</td></tr></table></div></div></div>' +
					'<div class="bottom_left" onmousedown="if (navigator.vendor) return false;"></div><div class="bottom_center" onmousedown="if (navigator.vendor) return false;"></div><div class="bottom_right" onmousedown="if (navigator.vendor) return false;">' +
				((vars.resize) ? '<div class="resize_handle" onmousedown="WindowTool.resizeStart(event,this);"></div>' : '') +
			'</div></div>';
		
		element.innerHTML = html;
		document.getElementById('screen').appendChild(element);
		Effect.Appear(element,{ duration: 0.4});
		return(element.firstChild);
	},
	
	getWindowContent : function (win)
	{
		var content_div = win.getElementsByTagName('div');	
		for(var i=0; i<content_div.length; i++)
			if (content_div[i].className == 'middle_center')
				return content_div[i];
		return null;
	},
	
	setWindowTitle : function (win,title)
	{
		var content_div = win.getElementsByTagName('div');	
		for(var i=0; i<content_div.length; i++)
			if (content_div[i].className == 'top_center')
				content_div[i].firstChild.innerHTML = title;
	}
}


// Window Functions (moving and resizing)

WindowTool =
{
	init : function(event,win)
	{
		var x, y;
		
		this.window = win;
		WindowMan.makeActive(this.window);
		
		if (browser.isIE)
		{
			x = window.event.clientX + document.documentElement.scrollLeft
			  + document.body.scrollLeft;
			y = window.event.clientY + document.documentElement.scrollTop
			  + document.body.scrollTop;
		}
		else
		{
			x = event.clientX;
			y = event.clientY;
		}
		
		this.cursorStartX = x;
		this.cursorStartY = y;
		this.elStartWidth = parseInt(this.window.style.width, 10);
		this.elStartHeight = parseInt(this.window.style.height,  10);
		
		if (isNaN(this.elStartWidth)) this.elStartWidth = 0;
		if (isNaN(this.elStartHeight)) this.elStartHeight  = 0;	
		
		this.elStartTop = parseInt(this.window.style.top, 10);
		this.elStartLeft = parseInt(this.window.style.left,  10);
		
		if (isNaN(this.elStartTop)) this.elStartTop = 0;
		if (isNaN(this.elStartLeft)) this.elStartLeft  = 0;	
		
		//alert(win.handler);
	},
	
	stop : function(event)
	{
		if (browser.isIE)
		{
			CookieMan.setCookie(WindowTool.window.id+'_x',WindowTool.window.style.left,'/');
			CookieMan.setCookie(WindowTool.window.id+'_y',WindowTool.window.style.top,'/');
			CookieMan.setCookie(WindowTool.window.parentNode.id+'_w',WindowTool.window.style.width,'/');
			CookieMan.setCookie(WindowTool.window.parentNode.id+'_h',WindowTool.window.style.height,'/');
					
			document.detachEvent("onmousemove", WindowTool.moveUpdate);
			document.detachEvent("onmousemove", WindowTool.resizeUpdate);
			document.detachEvent("onmouseup",   WindowTool.stop);
		}
		else
		{
			CookieMan.setCookie(WindowTool.window.id+'_x',WindowTool.window.style.left,'/');
			CookieMan.setCookie(WindowTool.window.id+'_y',WindowTool.window.style.top,'/');
			CookieMan.setCookie(WindowTool.window.id+'_w',WindowTool.window.style.width,'/');
			CookieMan.setCookie(WindowTool.window.id+'_h',WindowTool.window.style.height,'/');		
			
			document.removeEventListener("mousemove", WindowTool.moveUpdate,true);
			document.removeEventListener("mousemove", WindowTool.resizeUpdate,true);
			document.removeEventListener("mouseup",   WindowTool.stop,true);
		}
	},	

	moveStart : function (event, node)
	{		
		this.init(event,node.parentNode);
		
		if (browser.isIE)
		{
			document.attachEvent("onmousemove", WindowTool.moveUpdate);
			document.attachEvent("onmouseup",   WindowTool.stop);
			window.event.cancelBubble = true;
			window.event.returnValue = false;
		}
		else
		{
			document.addEventListener("mousemove", WindowTool.moveUpdate,   true);
			document.addEventListener("mouseup",   WindowTool.stop, true);
			event.preventDefault();
		}
	},

	moveUpdate : function (event)
	{	
		var x, y;
		
		if (browser.isIE) {
			x = window.event.clientX + document.documentElement.scrollLeft
			  + document.body.scrollLeft;
			y = window.event.clientY + document.documentElement.scrollTop
			  + document.body.scrollTop;
		}
		else
		{
			x = event.clientX;
			y = event.clientY;
		}
		
		WindowTool.window.style.left = (WindowTool.elStartLeft + x - WindowTool.cursorStartX) + "px";
		WindowTool.window.style.top  = (WindowTool.elStartTop  + y - WindowTool.cursorStartY) + "px";
		
		if (browser.isIE) {
			window.event.cancelBubble = true;
			window.event.returnValue = false;
		}
		else
			event.preventDefault();
	},

	resizeStart : function(event, node) 
	{
		var tds = node.parentNode.parentNode.parentNode.getElementsByTagName('div');	
		for(var i=0; i<tds.length; i++)
			if (tds[i].className == 'window')
				this.init(event,tds[i]);
		
		if (browser.isIE) 
		{
			document.attachEvent("onmousemove", WindowTool.resizeUpdate);
			document.attachEvent("onmouseup",   WindowTool.stop);
			window.event.cancelBubble = true;
			window.event.returnValue = false;
		}
		else
		{
			document.addEventListener("mousemove", WindowTool.resizeUpdate,   true);
			document.addEventListener("mouseup",   WindowTool.stop, true);
			event.preventDefault();
		}
	},

	resizeUpdate : function(event)
	{
		var x, y;
		
		if (browser.isIE)
		{
			x = window.event.clientX + document.documentElement.scrollLeft
			  + document.body.scrollLeft;
			y = window.event.clientY + document.documentElement.scrollTop
			  + document.body.scrollTop;
		}
		else
		{
			x = event.clientX;
			y = event.clientY;
		}
		
		WindowTool.window.style.width = (WindowTool.elStartWidth + x - WindowTool.cursorStartX) + "px";
		WindowTool.window.style.height  = (WindowTool.elStartHeight + y - WindowTool.cursorStartY) + "px";
		
		// preview window resize hack
		var img = WindowTool.window.getElementsByTagName('img');	
		for(var i=0; i<img.length; i++)
			if (img[i].className == 'preview_image')
				Preview.positionImage(img[i],{});
		
		if (browser.isIE) {
			window.event.cancelBubble = true;
			window.event.returnValue = false;
		}
		else
			event.preventDefault();
	}
}

// Desktop Class
// Handles global keydown events

Desktop =
{
	activeWindow : null,
	
	init : function ()
	{
		if (!browser.isIE)
			document.addEventListener('keydown',Desktop.handleKeydownEvent,false);
		else
			document.attachEvent('onkeydown',Desktop.handleKeydownEvent);
				
		var iconsize = CookieMan.getCookie('desktop_icon_size');
		if (iconsize)
		{
			var icons = $('desktop').getElementsByTagName('img');
			for (var i=0; i<icons.length; i++)
				icons[i].style.width = iconsize+ '%';
		}
		
		Sortable.create('desktop',{tag:'a', constraint:false});
		
		IconCache.init($('desktop'));
	},
		
	handleKeydownEvent : function(event)
	{
		var as;
		var parent;
		if (!WindowMan.activeWindow)
		{
			as = document.getElementById('desktop').getElementsByTagName('a');
			parent = null;
		}
		else
		{
			as = WindowMan.activeWindow.getElementsByTagName('a');
			parent = WindowMan.activeWindow.firstChild;
		}
		
		if (event.keyCode == 39)  // 'right' move between selected desktop and folder items
		{
			for(var i=as.length-2; i>=0; i--)
				if (as[i].className == 'selected')
				{
					Desktop.selectItem(as[i+1],parent);
					return false;
				}
			Desktop.selectItem(as[as.length-1],parent);
			return false;
		}
		else if (event.keyCode == 37) // 'left' move between selected desktop and folder items
		{
			for(var i=1; i<as.length; i++)
				if (as[i].className == 'selected')
				{
					Desktop.selectItem(as[i-1],parent);
					return false;
				}
			Desktop.selectItem(as[0],parent);
			return false;
		}
		if ( event.keyCode == 40)  // 'down' move between selected desktop and folder items
		{
			var offy = 0;
			var	offx = 0;
			var found = false;
			for(var i=0; i<as.length; i++)
			{
				if (as[i].className == 'selected')
				{
					offy=as[i].offsetTop;
					offx=as[i].offsetLeft;
					found = true;
				}
				if (found && as[i].offsetTop > offy && as[i].offsetLeft == offx)
				{
					Desktop.selectItem(as[i],parent);
					return false;
				}
			}
			Desktop.selectItem(as[as.length-1],parent);
			return false;
		}
		else if (event.keyCode == 38) // 'up' move between selected desktop and folder items
		{
			var offy = 0;
			var	offx = 0;
			var found = false;
			for(var i=as.length-1; i>=0; i--)
			{
				if (as[i].className == 'selected')
				{
					offy=as[i].offsetTop;
					offx=as[i].offsetLeft;
					found = true;
				}
				if (found && as[i].offsetTop < offy && as[i].offsetLeft == offx)
				{
					Desktop.selectItem(as[i],parent);
					return false;
				}
			}
			Desktop.selectItem(as[0],parent);
			return false;
		}
		else if (event.keyCode == 13) // 'return' to open selected desktop item
		{
			for(var i=0; i<as.length; i++)
				if (as[i].className == 'selected')
				{
					as[i].ondblclick(event);
					return false;
				}
		}
		else if (event.keyCode == 9) // 'tab' between windows
		{
			if (!WindowMan.activeWindow)
			{
				if (document.getElementById('screen').firstChild.nextSibling)
					WindowMan.makeActive(document.getElementById('screen').firstChild.nextSibling.firstChild);	
			}
			else if (WindowMan.activeWindow.nextSibling)					
				WindowMan.makeActive(WindowMan.activeWindow.nextSibling.firstChild);	
			else
				WindowMan.makeActive(null);			
		}
	},
	
 	selectItem : function(item,parent,event)
	{
		if (!parent)
		{
			WindowMan.makeActive(null);
			panels = $('desktop').getElementsByTagName('a');
		}
		else
		{
			WindowMan.makeActive(parent);
			panels = parent.getElementsByTagName('a');
		} 
		
		for(var i=0; i<panels.length; i++)
			if (panels[i].className == 'selected')
				panels[i].className = '';
		if (item)
			item.className = 'selected';
			
		if (event && !browser.isIE)
			event.stopPropagation();
		else if (event)
			window.event.cancelBubble = true;
		return false;
	}
}






function getGlobalPos(obj) {
	var curleft = curtop = 0;
	do
	{
		curleft += obj.offsetLeft - obj.scrollLeft;
		curtop += obj.offsetTop  - obj.scrollTop;
	}
	while (obj = obj.offsetParent)
	return [curleft,curtop];
}




//*****************************************************************************
// Do not remove this notice.
//
// Copyright 2001 by Mike Hall.
// See http://www.brainjar.com for terms of use.
//*****************************************************************************

// Determine browser and version.

function Browser() {

  var ua, s, i;

  this.isIE    = false;
  this.isNS    = false;
  this.version = null;

  ua = navigator.userAgent;

  s = "MSIE";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isIE = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  s = "Netscape6/";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  // Treat any other "Gecko" browser as NS 6.1.

  s = "Gecko";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = 6.1;
    return;
  }
}

var browser = new Browser();


/*if (navigator.platform == "Win32" && navigator.appName == "Microsoft Internet Explorer" && window.attachEvent) {
	window.attachEvent("onload", alphaBackgrounds);
}

function alphaBackgrounds(){
	var rslt = navigator.appVersion.match(/MSIE (\d+\.\d+)/, '');
	var itsAllGood = (rslt != null && Number(rslt[1]) >= 5.5);
	for (i=0; i<document.all.length; i++){
		var bg = document.all[i].currentStyle.backgroundImage;
		if (itsAllGood && bg){
			if (bg.match(/\.png/i) != null){
				var mypng = bg.substring(5,bg.length-2);
				document.all[i].style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+mypng+"', sizingMethod='scale')";
				document.all[i].style.backgroundImage = "url('images/blank.gif')";
			}
		}
	}
}*/

