// global.js : utility functions

if (document.images) {
	isIE6CSS = (document.compatMode && document.compatMode.indexOf("CSS1") >= 0) ? true : false;
}

function initApp() {

	// client side objecct manipulation
	assembleComponentLookup();
	global.user=assembleUser(global.user);

	// add trim function to String
	String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ""); };
	
	// time zone offset constant
	global.timezoneOffset = new Date().getTimezoneOffset() * 60000;

	// registries
	global.panels=new Object;	
	global.content=new Object;
	global.argProxy=new Object;
	global.windows=new Object;
	
	// slash command lookups
	command = new Command();
	command.inputKeypressObserver = command.onKeyPress.bindAsEventListener(command);	
	Event.observe(command.inputElement,'keypress',command.inputKeypressObserver,false);		
	
	// global hotkeys
	global.hotkeys = new Object;
	global.hotkeys[191] = function() {$('messageInput').focus();}
	global.hotkeys[220] = function() {$('messageInput').focus();}	
	
	//Event.observe(document.body,'keypress',function(e){checkHotkey(e)},false);
	
	// colophon
	global.colophon = new Object;
	global.colophon.tabButtonMouseOverColor='#E6C29E';
	global.colophon.tabButtonMouseOutColor='#FAFAD8';
	global.colophon.tabButtonActiveColor='#CCDCAC';
	
	// create panels
	pnlHome = new Panel({name:"Home",title:"SpaceLoot is under development",controlSetElement:"panelControlsHome",tabNames:['home','stats','credits']});
	pnlLoot = new Panel({name:"Loot",title:"Looted Component Database",controlSetElement:"panelControlsLoot",tabNames:['analysis','browser','detail','submit']});
	pnlChatArchive = new Panel({name:"ChatArchive",title:"Chat Archive"});
	pnlProfile = new Panel({name:"Profile",title:"empty",controlSetElement:"panelControlsProfile",tabNames:['user','toons','ships','stats','prefs']});
	pnlLoading = new Panel({name:"Loading",title:"Loading, please wait..."});
	
	extendProfilePanel(pnlProfile);
	extendLootPanel();
	
	// create windows
	winLogin = new Win("Login","Login","frmLogin","username");
	winChatSettings = new Win("ChatSettings","Chat Settings","frmChatSettings","");
	winWho = new Win("Who","Who's Online","dspWho","");	
	winSignUp = new Win("SignUp","Create an Account","frmSignUp","signup_username");
	winHelp = new Win("Help","SpaceLoot Help","dspHelp","");
	winLink = new Win("Link","Linkify","frmLink","linkInput");
	winAlerts = new Win("Alerts","Admin Alerts","dspAlerts","");
	winImageSub = new Win("ImageSub","Upload Image","frmImageSub","");
	winImage = new Win("Image","Image Viewer","dspImage","");
	winNotify = new Win("Notify","Please Note","dspNotify","");
	
	extendLinkWindow();
	extendAlertsWindow();

	setMasthead();
		
	if(global.user.username) {
		chat=initChat();
		chat.receive();
	}
	
	//set initial application state
	pnlHome.tabs['home'].open();
	pnlProfile.tabs['user'].open();	
	pnlLoot.tabs['analysis'].open();	
	pnlHome.open();		
	
	setTimeout("setPanelHeight()",100);
	
	if(!(global.launch == undefined)) {
		command.parse(global.launch);
		delete global.launch;
	}
	
	// eliminate any deep link settings forced by initial openings and closings
	delete global.deepLink;
	
	// watch for window resizes
	Event.observe(window,'resize',setPanelHeight,false);
}

function setPanelHeight() {
	var h=getInsideWindowHeight() - (getObjectHeight("chatContainer") + getObjectHeight("mastheadContainer") + 100);
	h=(h<100?100:h);
	Element.setStyle($('panelBody'),{height:h+'px'});
}

function setMasthead() {
	// set the personal masthead
	Element.hide('personalMasthead');
	Element.hide('guestMasthead');
	if(global.user.username) {
		Element.show('personalMasthead');
		Element.update('personalMastheadTitle',global.user.username + '.SpaceLoot');
		if(!global.user.isadmin && !global.user.islootadmin){
			Element.hide('userMastheadAlerts');
		}
	} else {
		Element.show('guestMasthead');	
	}
}

function initChat() {
	return new Chat({
		containerElement:"chatContainer",
		bodyElement:"chatBody",
		inputElement:"messageInput",
		refreshIndicatorElement:"chatRefreshIndicator",	
		toggleElement:"chatToggle",
		displaySize:global.user.chatdisplaysize,
		bufferSize:global.chatbuffersize,
		refreshRate:global.chatrefreshrate,
		minRefreshRate:global.chatminrefreshrate,
		throttleThreshold:global.chatthrottlethreshold,
		throttleIncrement:global.chatthrottleincrement,
		lineSpacing:global.user.chatlinespacing,
		fontSize:global.user.chatfontsize,
		activate:(global.user.username?true:false)} );
}

function assembleComponentLookup() {
	var as = function(a,b) {
		return a.attributeid - b.attributeid;
	}
	
	var cs = function(a,b)  {
		var nameA=a.name.toLowerCase();
		var nameB=b.name.toLowerCase();
		return (nameA < nameB ? -1 : 1);
	}
	
	for(var att in global.lookup.attributes) {
		var attr=global.lookup.attributes[att];
		if(global.lookup.components[attr.componenttypeid].attributes == undefined) {
			global.lookup.components[attr.componenttypeid].attributes = new Array();
		}
		global.lookup.components[attr.componenttypeid].attributes.push(attr);
	}
	
 	for(var c in global.lookup.classes) {
		var cl=global.lookup.classes[c];
		if(global.lookup.components[cl.componenttypeid].levels == undefined) {
			global.lookup.components[cl.componenttypeid].levels = new Object();
		}
		
		if(global.lookup.components[cl.componenttypeid].levels[cl.relevel] == undefined) {
			global.lookup.components[cl.componenttypeid].levels[cl.relevel] = new Array();
		}
		
		global.lookup.components[cl.componenttypeid].levels[cl.relevel].push(cl);	
	}	 
	
	// sorts
	for(var c in global.lookup.components) {
		global.lookup.components[c].attributes.sort(as);
	}
	
 	for(var c in global.lookup.components){
		var comp = global.lookup.components[c];
		for(var l in comp.levels){
			comp.levels[l].sort(cs);
		}
	} 
}

function assembleUser(u) {
	var ts = function(a,b) {
		return a.sortorder-b.sortorder;
	}
	u.toons = new Array();
	for(t in u.toon) {
		u.toon[t].toonid=t;
		u.toons.push(u.toon[t]);
	}
	u.toons.sort(ts);
	return u;
}

function _(v){
	return(v==undefined?false:true);
}

function pause(m) {
	date = new Date();
	var curDate = null;
	
	do { var curDate = new Date(); } 
	while(curDate-date < m);
} 

function checkHotkey(e)  {
	if(global.chatFocus) {return;}
	var k = (e.charCode) ? e.charCode : ((e.which) ? e.which : e.keyCode);
	if(global.hotkeys[k])  {
		Event.stop(e);
		global.hotkeys[k]();
	}
}

function sortNumeric(a, b) {
	return a - b
}

// Following functions taken from script credited:
// DHTMLapi.js custom API for cross-platform
// object positioning by Danny Goodman (http://www.dannyg.com).
// Release 2.0. Supports NN4, IE, and W3C DOMs.
// modified by Charlie Arnold to eliminate v4 browser support

function getRealLeft(el) {
	el=$(el);
    var xPos = el.offsetLeft;
    var tempEl = el.offsetParent;
    while (tempEl != null) {
        xPos += tempEl.offsetLeft;
        tempEl = tempEl.offsetParent;
    }
    return xPos;
}	

function getRealTop(el) {
	el=$(el);
    var yPos = el.offsetTop;
    var tempEl = el.offsetParent;
    while (tempEl != null) {
        yPos += tempEl.offsetTop;
        tempEl = tempEl.offsetParent;
    }
    return yPos;
}	

// Retrieve the x coordinate of a positionable object
function getObjectLeft(obj)  {
	var elem = $(obj);
	var result = 0;
    if (document.defaultView) {
		var style = document.defaultView;
        var cssDecl = style.getComputedStyle(elem, "");
        result = cssDecl.getPropertyValue("left");
    } else if (elem.currentStyle) {
        result = elem.currentStyle.left;
    } else if (elem.style) {
        result = elem.style.left;
    } 
    return parseInt(result);
}

// Retrieve the y coordinate of a positionable object
function getObjectTop(obj)  {
    var elem = $(obj);
    var result = 0;
    if (document.defaultView) {
        var style = document.defaultView;
        var cssDecl = style.getComputedStyle(elem, "");
        result = cssDecl.getPropertyValue("top");
    } else if (elem.currentStyle) {
        result = elem.currentStyle.top;
    } else if (elem.style) {
        result = elem.style.top;
    } 
    return parseInt(result);
}


function getObjectWidth(obj)  {
    var elem = $(obj);
    var result = 0;
    if (elem.offsetWidth) {
		result = elem.offsetWidth;
    } else if (elem.clip && elem.clip.width) {
        result = elem.clip.width;
    } else if (elem.style && elem.style.pixelWidth) {
        result = elem.style.pixelWidth;
    }
    return parseInt(result);
}

// Retrieve the rendered height of an element
function getObjectHeight(obj)  {
    var elem =$(obj);
    var result = 0;
    if (elem.offsetHeight) {
        result = elem.offsetHeight;
    } else if (elem.clip && elem.clip.height) {
        result = elem.clip.height;
    } else if (elem.style && elem.style.pixelHeight) {
        result = elem.style.pixelHeight;
    }
    return parseInt(result);
}

function shiftTo(obj, x, y) {
    var theObj = $(obj);
    if (theObj) {
		var units = (typeof theObj.style.left == "string") ? "px" : 0;
		theObj.style.left = x + units;
		theObj.style.top = y + units;  
    }
}

function shiftBy(obj, deltaX, deltaY) {
    var theObj = $(obj);
    if (theObj) {
		var units = (typeof theObj.left == "string") ? "px" : 0;
		theObj.left = getObjectLeft(obj) + deltaX + units;
		theObj.top = getObjectTop(obj) + deltaY + units;
    }
}

// Return the available content width space in browser window
function getInsideWindowWidth() {
    if (window.innerWidth) {
        return window.innerWidth;
    } else if (isIE6CSS) {
        // measure the html element's clientWidth
        return document.body.parentElement.clientWidth;
    } else if (document.body && document.body.clientWidth) {
        return document.body.clientWidth;
    }
    return 0;
}
// Return the available content height space in browser window
function getInsideWindowHeight() {
    if (window.innerHeight) {
        return window.innerHeight;
    } else if (isIE6CSS) {
        // measure the html element's clientHeight
        return document.body.parentElement.clientHeight;
    } else if (document.body && document.body.clientHeight) {
        return document.body.clientHeight;
    }
    return 0;
}

// center an element in the window
function centerOnWindow(elemID) {
	var obj=$(elemID);	
	var scrollX=0;
	var scrollY=0;

 	if(document.body && typeof document.body.scrollTop != "undefined") {
		scrollX += document.body.scrollLeft;
		scrollY += document.body.scrollTop;
		if(document.body.parentNode && typeof document.body.parentNode.scrollTop != "undefined") {
			scrollX += document.body.parentNode.scrollLeft;
			scrollY += document.body.parentNode.scrollTop;
		} else if (typeof window.pageXOffset != "undefined") {
			scrollX += window.pageXOffset;
			scrollY += window.pageYOffset;
		}
	}  
	var x = Math.round((getInsideWindowWidth()/2) - (getObjectWidth(obj)/2)) + scrollX;
	var y = Math.round((getInsideWindowHeight()/2) - (getObjectHeight(obj)/2)) + scrollY;
	shiftTo(obj,x,y);
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function createCookie(name,value,days) {
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}


function eraseCookie(name) {
	createCookie(name,"",-1);
}

function formatMessageDate(d,doOffset) {
	if(doOffset == undefined) {doOffset = true;}
	var d=new Date(d);
	var ticks = d.getTime();
	
	var n=new Date();
	var om = n.getTimezoneOffset() * (doOffset?120000:60000);
	
	var adjTicks = ticks - om;
	
	var adjDate = new SimpleDate(adjTicks);
	return adjDate.toFormattedString("~h:~m:~s ~a");
}

function formatArchiveMessageDate(d,doOffset) {
	var d=new Date(d);
	var ticks = d.getTime();
	
	var n=new Date();
	var om = n.getTimezoneOffset() * 120000;
	
	var adjTicks = ticks - om;
	
	var adjDate = new SimpleDate(adjTicks);
	return adjDate.toFormattedString("~M ~d, ~Y ~h:~m:~s ~a");
}