var IE = (navigator.appName == "Microsoft Internet Explorer") ? true : false;//is the current browser IE?
var DOCUMENT = (document.documentElement) ? document.documentElement : document.body;//body element to use for screen dimensions
var jrequest = new JsonRequest();	
var binder = new DataBinder();
var new_faces_popup = null;
var new_faces_binder = null;
var passBoxClicked = false;
var clear_interval = -1;//timeout to clear the status message

function SubGPoints(a,b) {
	return new GPoint(a.x-b.x,a.y-b.y);
}

function ChangeColor(obj,color) {
	obj.style.color = color;
}

Array.prototype.remove = function(from, to) {
	var rest = this.slice((to || from) + 1 || this.length);
	this.length = from < 0 ? this.length + from : from;
	return this.push.apply(this, rest);
}

function CreateOption(list,value,label) {
	if(label == null) label = value;
	var obj = document.createElement("OPTION");
	var txt = document.createTextNode(value);
	obj.appendChild(txt);
	obj.value = value;
	list.appendChild(obj);
}

function GetSelectedValue(type) {
	var list = document.getElementById(type+"_list");
	var index = list.selectedIndex;
	if(index < 0) return "";
	return list.options[index].value;
}

function SetSelectedValue(type,value) {
	if(value == null) return;
	var list = document.getElementById(type+"_list");
	for(var i = 0; i < list.options.length; i++) {
		if(list.options[i].value == value) {
			list.selectedIndex = i;
			break;
		}
	}
}

/*
 * Returns the dimension of the window in pixels.
 * OUTPUT: array dim with dim[0] = width and dim[1] = height
 */
function GetScreenDimensions() {
	var dim = [-1,-1];
	if(!IE) {
		dim[0] = window.innerWidth;
		dim[1] = window.innerHeight;
	} else if(document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) { 
		dim[0] = document.documentElement.clientWidth;
		dim[1] = document.documentElement.clientHeight;
	} else if(document.body && (document.body.clientWidth || document.body.clientHeight)) {
		dim[0] = document.body.clientWidth;
		dim[1] = document.body.clientHeight;
	}
	return dim;
}

/*
 * Appends a function to a JavaScript event of the given object.
 * INPUT: Object whose event object must change, type of event, and the new function.
 */
function AddEvent(elm,evt,fn) {
	if(elm.addEventListener)
        elm.addEventListener(evt,fn,false);
    else if(elm.attachEvent)
        elm.attachEvent('on'+evt,fn);
    else
        elm['on'+evt] = fn;
}

function RemoveEvent(elm,evt,fn) {
	if(elm.removeEventListener)
		elm.removeEventListener(evt,fn,false);
	else if(elm.detachEvent)
		elm.detachEvent('on'+evt,fn);
	else
		elm['on'+evt] = null;
}

function deselect() {
	if(window.selection)
 		document.selection.empty();
 	else
 		window.getSelection().removeAllRanges();
}

function getMouseCoordinates(ev) {
	if(ev.pageX || ev.pageY)
		return {x:ev.pageX, y:ev.pageY};
	return {
		x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
		y:ev.clientY + document.body.scrollTop  - document.body.clientTop
	};	 
}

function catchEnterKey(e,callBack){ //e is event object passed from function invocation
	var characterCode;// literal character code will be stored in this variable
	if(e && e.which)//if which property of event object is supported (NN4)
		characterCode = e.which //character code is contained in NN4's which property
	else if(e && e.charCode)
		characterCode = e.charCode
	else {
		if(window.event) e = window.event;
		characterCode = e.keyCode //character code is contained in IE's keyCode property
	}
	if(characterCode == 13) { //if generated character code is equal to ascii 13 (if enter key)
		callBack();
		return false;
	} else return true;
}

function shrinkText(str,len) {
	var output = "";
	if (str.length <= len) output = str;
	else output =  str.substring(0,len-3) + "...";
	return output;
}

function initLogPopup() {
	var list = document.getElementsByTagName('a');
	for(i = 0;i<list.length;i++) {
		if(list[i].className == 'emptyclass132')
	   		list[i].onmousemove = setLogPopupPos;
	}
	binder['media'] = new ImageSrcRenderer(BASE_URL+'/media','','?maxWidth=120&maxHeight=90&pad=ffffff');
	binder['rating'] = new IconListRenderer(BASE_URL+'/image/rating_on.png',
			BASE_URL+'/image/rating_off.png',5,true);
	binder['difficulty'] = new IconListRenderer(BASE_URL+'/image/difficulty_on.png',
			BASE_URL+'/image/difficulty_off.png',5,true);
	binder['finished'] = new BooleanRenderer(LAB_YES,LAB_NO,'color:green','color:red');
 	binder['playtime'] = new DefaultRenderer('',' min.');
 	binder['playState'] = new EnumRenderer(new Array({'name':'PLAYING','html':'<span style=\"color:green\">'+LAB_PLAYING+'</span>'},
			 {'name':'FINNISHED','html':'<span style=\"color:green\">'+LAB_FINISHED+'</span>'},
			 {'name':'ABORTED','html':'<span style=\"color:red\">'+LAB_ABORTED+'</span>'}));
}

function setLogPopupPos(event) {
	var log_popup = document.getElementById('playLogPop');
	if(event == null) event = window.event;
	var offset;
	var left = 0;
	var top = 0;
	if(jQuery.browser.msie) {
		left = event.clientX + document.documentElement.scrollLeft-15-parseInt(log_popup.offsetWidth);
		top = event.clientY + document.documentElement.scrollTop+15;
	} else {
		left = event.pageX-15-parseInt(log_popup.offsetWidth);
		top = event.pageY;
	}
	
	if(left < 0) left = 0;
	if(top < 0) top = 0;
	log_popup.style.left = left + "px";
	log_popup.style.top = top + "px";
}

function showLogPopup(player,qid) {

	var url = BASE_URL+'/QueryPlayLog?user=' + player + '&quest_id=' + qid;
 	jrequest.send(url,displayLogData);
	var log_popup = document.getElementById('playLogPop');
	log_popup.style.display = "inline";
	
}

function displayLogData(data) {
	binder.bindDataToElem('playLogPop',data);
}

function hideLogPopup() {
	var log_popup = document.getElementById('playLogPop');
	log_popup.style.display = "none";
	log_popup.style.left = "0px";
	log_popup.style.top = "0px";
}

function NegativeMod(a,b) {
	if(b <= 0) return 0;
	if(a < 0) {
		var posa = Math.abs(a);
		var temp = posa%b;
		if(temp == 0) return 0;
		else return b-temp;
	} else return a%b;
}

function CancelEvent(e) {
	if(!e) e = window.event;
	e.cancelBubble = true;
	if(e.stopPropagation) e.stopPropagation();
}

function isEvent() {
	if(typeof arguments[0] == 'object') {
		var search = arguments[0].constructor.toString().match(/event/i); 
		return (search != null);  
	}
	return false;
}

function isString() {
	if(typeof arguments[0] == 'string') return true;
	if(typeof arguments[0] == 'object') {
		var search = arguments[0].constructor.toString().match(/string/i); 
		return (search != null);
	}
	return false;
}

function GoTo(url) {
	window.location = url;
}

/*
 * STRING PROCESSING FUNCTIONS
 */

/*
 * Returns the width of the string in pixels using the ruler
 * provided by the user.  The ruler defines the font size,
 * font style, font family, etc.
 */
function GetPixelLength(str) {
	var ruler = document.getElementById(RULER);
	ruler.appendChild(document.createTextNode(str));
	var width = ruler.offsetWidth;
	ruler.removeChild(ruler.lastChild);
	return width;
}

/*
 * Calculates the width of a string after trimming the
 * surrounding whitespace and returns whether the pixel
 * width of the string is less than the maximum width
 * provided by the user.
 */
function IsWordTooLong(str) {
	var temp = TrimWhiteSpace(str);
	var pixels = GetPixelLength(temp);
	return (pixels > MAX_WORD_LENGTH);
}

/*
 * Trims the whitespace from the beginning and from the
 * end of the string.
 */
function TrimWhiteSpace(str) {
	var begin = /^[\s]*/g;
	var end = /[\s]*$/g;
	return str.replace(begin,'').replace(end,'');
}

/*
 * Calculates a substring x of the parameter string whose pixel
 * width is less than the maximum pixel width provided by the
 * user in MAX_WORD_LENGTH.  Any substring y of the parameter
 * string that contains x has a pixel width larger than the
 * maximum width.  These substrings begin at index 0 of the
 * parameter string.
 */
function GetLongestSubstring(str) {
	var result = "";
	while(!IsWordTooLong(result)) result = str.substring(0,result.length+1);
	return result.substring(0,result.length-1);
}

/*
 * Processes the words in this string and shortens those that do 
 * not fit in a given pixel width.
 */
function ProcessLongWords(str) {
	var r = /\s*(\S+)\s*/g;
	var result = null;
	var new_str = "";
	while (result = r.exec(str)) {//loop through the words
		var word = result[0];
		while(IsWordTooLong(word)) {//cut up the word if it is too long
			var temp = GetLongestSubstring(word);
			new_str += temp+" ";
			word = word.substring(temp.length);
		}
		new_str += word;
	}
	return new_str;
}

/*
 * NEW FACES FUNCTIONS
 */

/*
 * Set the position of the popup where the mouse is located.
 */
function SetNewFacesPopupPosition(e) {
	if(new_faces_popup == null) InitializeNewFacesPopup();
	if(e == null) e = window.event;
	var offset;
	var left = 0;
	var top = 0;
	var dim = GetScreenDimensions();
	if(jQuery.browser.msie) {
		left = e.clientX + document.documentElement.scrollLeft+15;
		top = e.clientY + document.documentElement.scrollTop+15;
	} else {
		left = e.pageX+15;
		top = e.pageY+15;
	}
	if(left < 0) left = 0;
	if(top < 0) top = 0;
	if(jQuery.browser.safari) DOCUMENT = document.body;
	if((left-DOCUMENT.scrollLeft)+new_faces_popup.offsetWidth > dim[0])
		left = dim[0]+DOCUMENT.scrollWidth-new_faces_popup.offsetWidth;
	if((top-DOCUMENT.scrollTop)+new_faces_popup.offsetHeight > dim[1])
		top = dim[1]+DOCUMENT.scrollTop-new_faces_popup.offsetHeight;
	new_faces_popup.style.left = left+"px";
	new_faces_popup.style.top = top+"px";
}

/*
 * Initializes the new_faces_popup and new_faces_binder
 * variables.
 */
function InitializeNewFacesPopup() {
	new_faces_popup = document.getElementById("newfacespopup");
	new_faces_popup.parentNode.removeChild(new_faces_popup);
	document.body.appendChild(new_faces_popup);
	new_faces_binder = new DataBinder();
	new_faces_binder.bindAttr("src","profile_image");
	new_faces_binder.bindAttr("src","hidden_download");
	new_faces_binder.bindAttr("class","loader_padding");
}

/*
 * Sets the data in the popup to the active user and then 
 * shows the popup.
 */
var uploaded_new_faces_image = "";
function ShowNewFacesPopup(img,name) {
	if(new_faces_binder == null) return;
	uploaded_new_faces_image = img;
	$("#newfacespopup #loader_padding").css("padding-top","23px");
	new_faces_binder.bindData(new_faces_popup,
		{"hidden_download":img+"?maxWidth=100&maxHeight=75&pad=ffffff",
			"username":name,"profile_image":BASE_URL+"/gfx/loader_white.gif"});
	new_faces_popup.style.display = "inline";
}

function ShowNewFaceInPopup() {
	if(new_faces_binder == null) return;
	$("#newfacespopup #loader_padding").css("padding-top","1px");
	new_faces_binder.bindData(new_faces_popup,
		{"profile_image":uploaded_new_faces_image+"?maxWidth=100&maxHeight=75&pad=ffffff"});
	new_faces_popup.style.display = "inline";
}

/*
 * Remove the popup from the screen.
 */
function HideNewFacesPopup() {
	if(new_faces_popup == null) return;
	new_faces_popup.style.display = "none";
}


/***********************************************
* Disable Text Selection script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/

function disableSelection(target){
if (typeof target.onselectstart!="undefined") //IE route
	target.onselectstart=function(){return false}
else if (typeof target.style.MozUserSelect!="undefined") //Firefox route
	target.style.MozUserSelect="none"
else //All other route (ie: Opera)
	target.onmousedown=function(){return false}
target.style.cursor = "default"
}

function enableSelection(target){
if(jQuery.browser.msie) //IE route
	target.onselectstart=function(){return true}
else if(jQuery.browser.firefox) //Firefox route
	target.style.MozUserSelect="all"
}

/***********************************************
* http://www.quirksmode.org/js/cookies.html
***********************************************/
function createCookie(name,value,hours) {
	var expires = "";
	if(hours) {
		var date = new Date();
		date.setTime(date.getTime()+(hours*60*60*1000));
		expires = "; expires="+date.toGMTString();
	}
	document.cookie = name+"="+value+expires+"; path=/";
}

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 eraseCookie(name) {
	createCookie(name,"",-1);
}

function clearPassBox()	{
	var lb = document.getElementById('passwordbox');
	if (passBoxClicked == false)
	{
		lb.value = "";
		if(IE) {
			var nlb = lb.cloneNode(false);
			nlb.type='password';
			lb.parentNode.replaceChild(nlb,lb);
			setTimeout("document.getElementById('passwordbox').focus()",30);
		} else lb.type = "password";
		passBoxClicked = true;
	}
	if(!IE) lb.focus();
	lb.select();
}

function SetStatus(msg,color) {
	if(color == null) color = "green";
	if(clear_interval >= 0) window.clearInterval(clear_interval);
	clear_interval = -1;
	var panel = document.getElementById("message_box");
	while(panel.firstChild) panel.removeChild(panel.firstChild);
	panel.appendChild(document.createTextNode(msg));
	panel.style.color = color;
	if(color != "red") clear_interval = window.setTimeout(ClearStatus,10000);
}

function SetError(msg) {
	SetStatus(msg,"red");
}

function ClearStatus() {
	var panel = document.getElementById("message_box");
	while(panel.firstChild) panel.removeChild(panel.firstChild);
	clear_interval = -1;
}

//JUNK CODE
//var punctuation = /[!\\\'#$%&"\(\)\*\+,-\.\/:;<=>\?@[\]\^_{|}~]/g;
//punctuation has been tested
