var windowsOpen = 0; // Number | How many windows are currently open
var alertCommands; // Array | The current set of alert commands
var keyCodes = new Array(); // Array | A list of key code for the keyboard event manager
var keyCommands = new Array(); // Array | A list of key commands for the keyboard event manager
var cellSheetManagerCol; // Number | The column ID that is currently selected
var cellSheetManagerRow; // Number | The row ID that is currently selected
var cellSheetManagerTarget; // String | The id of the table to be used
var cellSheetManagerScrollField; // Object | The Field that handles the scrolling for the page
var deleteBoxId = 0; // Number | The id of the currently created delete box
var deleteCommand = new Array(); // Array | An array of delete commands
var imagesToPreload = new Array("/templates/images/main_nav_roll_over.jpg","/templates/images/buttons/yellow_button_right_over.jpg","/templates/images/buttons/yellow_button_left_over.jpg");


function addLeftColumnFiller(){
	if(document.getElementById('leftColumnFillerHolder') != undefined){
		var rightCol = document.getElementById('standardSectionRightColumn').offsetHeight;
		var leftCol = document.getElementById('standardSectionLeftColumn').offsetHeight;
		
		if(leftCol < rightCol){
			document.getElementById('leftColumnFillerHolder').className = "visible";
			document.getElementById('leftColumnFiller').style.height = (rightCol-leftCol-document.getElementById('leftColumnFillerHolder').offsetHeight-1)+"px";
		};
	};
};


function bustFrames(){
	if (top.location != self.location) top.location.replace(self.location+"&google_images=true");
};


function checkBrowser(){
	if (document.all && !window.opera && !window.XMLHttpRequest) {
		document.getElementById('alertMessage').innerHTML = lang['ie6'];
		document.getElementById('alertMessage').className = "alert_message";
		document.body.scrollTop = 0;
	};
};

function bodyLoad(){
	checkBrowser();
	addLeftColumnFiller();
	
};

function preloadImages(){
	for(var i = 0;i<imagesToPreload.length;i++){
		var temp = new Image();
		temp.src = imagesToPreload[i];
	};
};


/** Returns the user to the homepage **/
function returnHome(){
	goToURL("/");
};

function goToURL(target){
	window.location = target;
};

/** Creates a delete button with confirmation
** @param command What is to be places in the href of the confirmation 
**/
function createDelete(command){
	deleteBoxId ++;
	string = "<a href='javascript:confirmDelete("+deleteBoxId+")'>"+lang['delete']+"</a>";
	deleteCommand["del"+deleteBoxId] = command
	return string;
};


/** Displays the delete confirmation
** @param deleteBoxId The id number of the delete box to have it's confirmation shown
**/	
function confirmDelete(deleteBoxId){
	openWindow("<h1>"+lang['delete_confirm']+"</h1>",new Array(lang['delete_yes'],lang['delete_no']),new Array(deleteCommand["del"+deleteBoxId],""),"alert");
};

/** Displays a preset loading animation 
** @param loader Which loading animation to use
**/
function loadingAnimation(loader){
	if(loader == undefined){loader = 1;};
	return "<div class='loading_holder'><img src='/templates/images/loading/animation_"+loader+".gif' /></div>";
};

/** Displays a window with the loading animation **/
function loadingWindow(message){
	openWindow("<h1>"+message+"</h1><img src='/templates/images/loading/animation_1.gif' class='loading_window_img' />",new Array(),new Array(),"alert");
};

/** Closes the current loading window **/
function closeLoadingWindow(){
	closeWindow("alert");
};

/** Removes all visisble CSS properties from a div, essentialy making it non existant
** @param divId The id of the div to be killed
**/
function killDiv(divId){
	document.getElementById(divId).className  = "dead";
};

/** Searches through a string and replaces all instances of one sting, with another sting (replaces the normal replace method in that it does not require regexp to replace all version, thus allowing you to store the findString in a variable
** @param string The string to be searched through
** @param findString The string that will be swapped out
** @param newString The string that will be swapped in
** @returns String
**/
function replaceAll(string,findString,newString){
	while (string.indexOf(findString) > -1){
		string = string.replace(findString,newString);
	};
		
	return string;
};

/** Converts the first letter of the string to caps
** @param string The string to be converted
** @returns String
**/
function firstLetterToCap(string){
	string = string.substring(0,1).toUpperCase() + string.substring(1,string.length);	
	return string;
};

/** Takes a snapshop of the current content area in case in needs to be later restored **/
var contentsOfContentArea = "";
var contentsOfSecondaryContentArea = "";
function snapShotContentArea(){
	contentsOfContentArea = document.getElementById("primaryContentArea").innerHTML;
	contentsOfSecondaryContentArea = document.getElementById("secondaryContentArea").innerHTML;
};

/** Restores a prevously taken snapshop of the content area **/
function restoreContentArea(){
	document.getElementById("primaryContentArea").innerHTML = contentsOfContentArea;
	document.getElementById("secondaryContentArea").innerHTML = contentsOfSecondaryContentArea;
};

/** Clears all the content in the main content areas **/
function clearContent(){
	document.getElementById("primaryContentArea").innerHTML = "";
	document.getElementById("secondaryContentArea").innerHTML = "";
};

/** Displays an error in an alert window
** @param error The desired error message
**/
function displayError(error){
	openWindow("<h1>"+lang['error']+"</h1><h2>"+error+"</h2>",new Array("Ok"),new Array(""),"error");
	if(contentsOfContentArea != ""){restoreContentArea();};
};

/** Creates and opens a new window
** @param contents The desired contents of the window
** @param buttons An array of strings to be used as button copy
** @param buttonCommands An array of strngs containing javascript functions to be called when the buttons are clicked
** @param type The type of window to be displayed, for example, alert or admin
**/
function openWindow(contents,buttons,buttonCommands,type){	
	document.getElementById(type+"WindowBg").className = type+"_window_bg";
	document.getElementById(type+"Window").className = type+"_window";
	
	
	var string = contents;
	
	string += "<div class='window_controls'>";
	for(var i = 0;i<buttons.length;i++){
		string += "<a href='javascript:"+buttonCommands[i]+"closeWindow(\""+type+"\");'>"+buttons[i]+"</a>";	
	}
	string += "</div>";
	
	document.getElementById(type+"Window").innerHTML = string;
	
	document.getElementById(type+"WindowBg").style.top = getScrollPositionY() +"px";
	document.getElementById(type+"Window").style.top = (getScrollPositionY() + document.getElementById(type+"WindowBg").offsetHeight/2 - document.getElementById(type+"Window").offsetHeight/2) + "px";
	document.getElementById(type+"Window").style.left = (getScrollPositionX() + document.getElementById(type+"WindowBg").offsetWidth/2 - document.getElementById(type+"Window").offsetWidth/2) + "px";
	windowsOpen ++;	
	if(windowsOpen == 1){
		document.body.style.overflow = "hidden";
	};
	
	if(type == "alert"){
		//addKeyEvent(13,buttonCommands[0]+"closeWindow('alert');");
		addKeyEvent(27,buttonCommands[buttonCommands.length-1]+"closeWindow('alert');");
		cellSheetManagerDisable();
		alertCommands = buttonCommands;
	};
};

/** Closes an open window
** @param Type The window's type
**/
function closeWindow(type){
	document.getElementById(type+"WindowBg").className = "";
	document.getElementById(type+"Window").className = "";
	//document.body.style.overflow = "auto";
	document.getElementById(type+"Window").innerHTML = "";
	
	windowsOpen --;
	if(windowsOpen == 0){
		document.body.style.overflow = "auto";
	};
	
	if(type == "alert"){
	//	removeKeyEvent(13,alertCommands[0]+"closeWindow('alert');");
	removeKeyEvent(27,alertCommands[alertCommands.length-1]+"closeWindow('alert');");
		cellSheetManagerEnable();
	};
	
};

/** Gets the current Y scroll position on the page
** @returns Number
**/
function getScrollPositionY() {
	return window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
};

/** Gets the current X scroll position on the page
** @returns Number
**/
function getScrollPositionX() {
	return window.pageXOffset ? window.pageXOffset : document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft;
};

/** Converts a number date string (ex 091231) to a more readable one (ex 12/31/2009)
** @param string The string to convert
** @returns String
**/
function convertNumberDate(string){
	return string.substr(2,2)+"/"+string.substr(4,2)+"/20"+string.substr(0,2);
};


/** Checks to see if a string is empty, and if it is, place a space in the string
** @param target The string to be checked
**/
function replaceEmptyStringWithSpace(target){
	if(target == ""){
		return "&nbsp";
	}else{
		return target;
	};
};

/** Opens the benchMarking tool window **/
function openBenchMark(){
	var list = bench_mark_data.split(",");
	var string = "<h1>"+lang['benchMarking']+"</h1><table class='benchMark_table'>";	
	var total = list[list.length-2].split(":")[1];	
	for(var i=0;i<list.length-1;i++){
		var data = list[i].split(":");
		string += "<tr><th>"+data[0]+"</th><td>"+data[1]+"</td><td>"+Math.round(data[1]/total*100);
		string += "%</td></tr>";
	};	
	string += "</table>";	
	openWindow(string,new Array("Close"),new Array(""),"alert");
};

/** Parses a set of name value pairs
** @param $string Contains the name value pairs seperated by [&] and [=]
** @retruns Array
**/
function parseNameValuePairs(string){
	array = new Array();
	
	if(string != undefined){	
		var data = string.split("[&]");
		for(var i = 0;i<data.length;i++){
			var singleData = data[i].split("[=]");
			array[singleData[0]] = singleData[1];	
		};	
	};
	return array;
};

/** checks to see if any sections are emppty and hide's their containers **/
function checkForEmptySections(){
	var sectionsToCheck = new Array("primaryContentArea","secondaryContentArea");
	for(var i = 0;i<sectionsToCheck.length;i++){		
		if(trim(document.getElementById(sectionsToCheck[i]).innerHTML) == ""){
			document.getElementById(sectionsToCheck[i]+"Container").style.display = "none";	
		}else{
			document.getElementById(sectionsToCheck[i]+"Container").style.display = "block";	
		};
	};
};

/** Trims from the front and back of a string
** @param str The desired string
** @param chars Any characters to ignore
**/
function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
};
 
/** Trims from the front of a string
** @param str The desired string
** @param chars Any characters to ignore
**/
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
};
 
 /** Trims from the back of a string
** @param str The desired string
** @param chars Any characters to ignore
**/
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
};

/** If the user hand unread mail, display the icon
** @param count How many unread msgs the user has
**/
function userInbox(count){
	if(count > 0){
		document.getElementById("mainTemplateHeader").innerHTML += "<div class='mail_icon'><a href='http://www.jitzul.com/fanCentral/index.php?action=pm'><img src='/templates/images/icons/mail_icon.png' /></a></div>";
	};
};

function loadTemplate(target,callback){
	sendData(Array("action","target"),Array("gatherTemplate","/templates/"+target),callback);
};

/** Adds the clone method to an array **/
Object.prototype.clone = function () {var o = new Object(); for (var property in this) {o[property] = typeof (this[property]) == 'object' ? this[property].clone() : this[property]} return o}

Array.prototype.clone = function () {var a = new Array(); for (var property in this) {a[property] = typeof (this[property]) == 'object' ? this[property].clone() : this[property]} return a}

keyEventManager();

/** Manages Keyboard events **/
function keyEventManager(){
	document.onkeydown = keyEvent;
};

/** Adds a key event to the keyboard event manager 
* @param code The numeric value of the key to be listened for
* @param command A string containing the code to be resolved once the event has been triggered
**/
function addKeyEvent(code,command){
	var exists = false;
	for(var i = 0;i<keyCodes.length;i++){
		if(code == keyCodes[i] && command == keyCommands[i]){
			exists = true;
		};
	};
	if(exists != true){
		keyCodes.push(code);
		keyCommands.push(command);
	};
};

/** Removes a key event to the keyboard event manager 
* @param code The numeric value of the key to be listened for
* @param command A string containing the code to be resolved once the event has been triggered
**/
function removeKeyEvent(code,command){
	var newCodes = Array();
	var newCommands = Array();
	
	for(var i = 0;i<keyCodes.length;i++){
		if(code == keyCodes[i] && command == keyCommands[i]){
			//keyCodes.splice(i,1);
		//	keyCommands.splice(i,1);
		}else{
			newCodes.push(keyCodes[i]);
			newCommands.push(keyCommands[i]);
		}
	};
	keyCodes = newCodes;
	keyCommands = newCommands;
};

/** When a key event is registered, check to see if it matches any of the listeners 
* @param evt Contains the event data
**/
function keyEvent(evt){
	for(var i = 0;i<keyCodes.length;i++){
		if(evt.keyCode == keyCodes[i]){
			eval(keyCommands[i]);
		};
	};
};

/** Launches the cellsheet manager
** @param target The desired table to be managed
** @param scrollField The desired scroll field that contains the table
** @param column The default column to be selected
** @param row The default row to be selected
**/
function cellSheetManager(target,scrollField,column,row){
	cellSheetManagerTarget = target;
	cellSheetManagerScrollField = scrollField;
	if(column == undefined){
		cellSheetManagerCol = 0;
	}else{
		cellSheetManagerCol = column;
	};
	if(row == undefined){
		cellSheetManagerRow = 1;
	}else{
		cellSheetManagerRow = row;
	};
	cellSheetManagerSelectCell(cellSheetManagerCol,cellSheetManagerRow);	
	cellSheetManagerEnable();
};

/** Disables the cellsheet manager **/
function cellSheetManagerDisable(){
	removeKeyEvent(39,"cellSheetManagerSlideCell(1,0);");
	removeKeyEvent(37,"cellSheetManagerSlideCell(-1,0);");
	removeKeyEvent(40,"cellSheetManagerSlideCell(0,1);");
	removeKeyEvent(38,"cellSheetManagerSlideCell(0,-1);");
	removeKeyEvent(16,"cellSheetManagerActivateCell();");
};

/** Enables the cellsheet manager **/
function cellSheetManagerEnable(){
	addKeyEvent(39,"cellSheetManagerSlideCell(1,0);");
	addKeyEvent(37,"cellSheetManagerSlideCell(-1,0);");
	addKeyEvent(40,"cellSheetManagerSlideCell(0,1);");
	addKeyEvent(38,"cellSheetManagerSlideCell(0,-1);");
	addKeyEvent(16,"cellSheetManagerActivateCell();");
};

/** Selects a specific cell on the table
** @param column The column of the cell
** @param row The row of the cell
**/
function cellSheetManagerSelectCell(column,row){
	if(cellSheetManagerCol != undefined){
		document.getElementById(cellSheetManagerTarget).getElementsByTagName("tr")[cellSheetManagerRow].getElementsByTagName("td")[cellSheetManagerCol].className = "";
	};	
	if(row > document.getElementById(cellSheetManagerTarget).getElementsByTagName("tr").length-1){
		row = 1;
	};
	if(row < 1){
		row = document.getElementById(cellSheetManagerTarget).getElementsByTagName("tr").length-1;
	};	
	if(column > document.getElementById(cellSheetManagerTarget).getElementsByTagName("tr")[row].getElementsByTagName("td").length-1){
		column = 0;
	};
	if(column < 0){
		column = document.getElementById(cellSheetManagerTarget).getElementsByTagName("tr")[row].getElementsByTagName("td").length-1;
	};	
	document.getElementById(cellSheetManagerTarget).getElementsByTagName("tr")[row].getElementsByTagName("td")[column].className = "selected";	
	cellSheetManagerRow = row;
	cellSheetManagerCol = column;
	cellSheetManagerScrollToCell(column,row);	
	document.getElementById(cellSheetManagerTarget).getElementsByTagName("tr")[row].getElementsByTagName("td")[column].focus();
};

/** Slides the current selected cell
** @param column How many columns to slide it by
** @param row How many rows to slide it by
**/
function cellSheetManagerSlideCell(column,row){
	cellSheetManagerSelectCell(cellSheetManagerCol+column,cellSheetManagerRow+row);
};

/** Activates the contents of the current cell **/
function cellSheetManagerActivateCell(){	
	//eval(document.getElementById(cellSheetManagerTarget).getElementsByTagName("tr")[cellSheetManagerRow].getElementsByTagName("td")[cellSheetManagerCol].getElementsByTagName("a")[0].href.substr(11));
};

/** Scrolls the page to a cell 
** @param column The column of the cell
** @param row The row of the cell
**/
function cellSheetManagerScrollToCell(column,row){
	var cellPos = cellSheetManagerGetCellPosition(document.getElementById(cellSheetManagerTarget).getElementsByTagName("tr")[row].getElementsByTagName("td")[column]);	
	if(cellPos>(cellSheetManagerScrollField.scrollTop + cellSheetManagerScrollField.offsetHeight - document.getElementById(cellSheetManagerTarget).getElementsByTagName("tr")[row].getElementsByTagName("td")[column].offsetHeight)){
		cellSheetManagerScrollField.scrollTop = cellPos - cellSheetManagerScrollField.offsetHeight + document.getElementById(cellSheetManagerTarget).getElementsByTagName("tr")[row].getElementsByTagName("td")[column].offsetHeight;	};
	
	if(cellPos<cellSheetManagerScrollField.scrollTop){
		cellSheetManagerScrollField.scrollTop = cellPos;
	};
}

/** returns the Y position of a cell
** @param cell The desired cell
** @returns Number
**/
function cellSheetManagerGetCellPosition (cell) {
    var cellPos = 0;
    while (cell) {
      cellPos += cell.offsetTop;
      cell = cell.offsetParent;
    };	
	var field = cellSheetManagerScrollField;
	var fieldPos = 0;
	while (field) {
      fieldPos += field.offsetTop;
      field = field.offsetParent;
    };
    return cellPos-fieldPos;
}

/** Capitalized the first letter of a string
** @param string The desired string
**/
function cap(string) {		
		return string.substring(0,1).toUpperCase() + string.substring(1)		
};

/** Loops through the imagesToPreload array and loads those images **/
preLoadImages();
function preLoadImages(){
	for(var i=0;i<imagesToPreload.length;i++){
		var pic = new Image();
		pic.src = imagesToPreload[i]; 
	};
};

/** Preloads an image and resizes it if needed
** @param target The id of the image to be loaded
** @optionalParam class A class associated with the image
** @optionalParam maxWidth The maximum width the image can be
** @optionalParam maxHeight The maximum height the image can be
** @optionalParam linkToOriginal If the image has been resized, link to the original one
**/
var jitSitesDomain = 0;
function displayImage(target,cssClass,maxWidth,maxHeight,linkToOriginal){	
	var imagePath = document.getElementById(target).src;
	var originalImage = document.getElementById(target).src;
	
	if(imagePath.substr(0,25) == "http://media.jitsites.com"){
		
		jitSitesDomain = (jitSitesDomain-1)*-1;
		imagePath = "http://media"+jitSitesDomain+".jitsites.com/imageLoader.php?target="+imagePath.substr(26)+"&width="+maxWidth+"&height="+maxHeight;
	}else if(imagePath.substr(0,35) == "http://"+locale+".jitzul.com/images"){
		imagePath = "http://"+locale+".jitzul.com/images/imageLoader.php?target="+imagePath.substr(36)+"&width="+maxWidth+"&height="+maxHeight;
	}else if(imagePath.substr(0,28) == "http://"+locale+".jitzul.com/images"){
		imagePath = "http://"+locale+".jitzul.com/images/imageLoader.php?target="+imagePath.substr(29)+"&width="+maxWidth+"&height="+maxHeight;
	};
	
	document.getElementById(target).src = "/templates/images/empty.gif";
	document.getElementById(target).className = "dead";
	var image = new Image();
	image.onload = function (){		
		
		var width = image.width;
		var height = image.height;		
		if(maxWidth != undefined && maxHeight != undefined){
			var percent;
			if(width > maxWidth){
				percent = maxWidth/width;
				width = width*percent;
				height = height*percent;	
			};
			if(height > maxHeight){
				percent = maxHeight/height;
				width = width*percent;
				height = height*percent;
			};
		};		
		document.getElementById(target).src = imagePath;
		document.getElementById(target).width = width;
		document.getElementById(target).height = height
		if(cssClass != undefined){document.getElementById(target).className = cssClass};		
		if(linkToOriginal){
			document.getElementById(target).onclick = function(){
				openPopUp(originalImage);
			};				
			document.getElementById(target).onmouseover = function(){
				document.getElementById(target).style.cursor="pointer";
			};
		};
	};	
	image.src = imagePath;
};


/** Opens a popup window
** @param url The desired URL of the item in the popup
**/
function openPopUp(url){
	window.open(url,"_blank", 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0');
};




