//<script>

/**
 * DEFINITIONS AND AJAX FUNCTIONS
 */
window = this;
this.urlVars = {};
this.userVars = {};
this.ajaxTarget = "";
this.ajaxFunctions = {};
ajaxFunctions.onLoaded_standard = function(html){
	$("#"+ajaxTarget).html(html);
};
ajaxFunctions.onLoaded_clear = function(html){
	$("#"+ajaxTarget).html("");
};
ajaxFunctions.onLoaded_sheet = function(html){
	$("#"+ajaxTarget).html(html);
	doLocalisation();
	doTablesorter('#sheet');
};
ajaxFunctions.onLoaded_infoWindow = function(html){
	if(html != "0"){
		$("#div_infoWindow").html(html);
		$("#div_infoWindow").fadeIn('fast');
		doLocalisation("#div_infoWindow");
	}else{
		$("#div_infoWindow").hide();
	}
};
ajaxFunctions.preSend_standard = function(){
	$("#"+ajaxTarget).html('<div align="center" style="margin:auto; width:100%;"><img src="img/ajax.gif" /><br /><span rel="localize[lng.general.ajaxLoading]">Loading...</span></div>');
	doLocalisation();
};
ajaxFunctions.preSend_sheet = function(){
	$("#div_sheetReload").css("display","block");
};
ajaxFunctions.preSend_miningTimer = function(){
	$("#div_miningTimer").html('<div align="right" style="margin:auto; width:100%;"><img src="img/ajax.gif" /><br /><span rel="localize[lng.general.ajaxLoading]">Loading...</span></div>');
	doLocalisation();
};
ajaxFunctions.onError_standard = function(XMLHttpRequest, textStatus, errorThrown){
	var errorText = "";
	if(XMLHttpRequest.status === 0){
		errorText = "Internet Connection Timeout or other unkown HTTP Problem.";
	}else{
		errorText = "HTTP-Status: "+XMLHttpRequest.status;
	}
	$("#"+ajaxTarget).html("<b><u>AJAX Error!</u></b><br /> "+errorText+"<br /><br />If you keep getting this message,<br />please post it on the forums.");
};


/**
 * PARSER, GETTER AND SETTER FOR HASH VARIABLES
 */
function parseUrlVars(){
	var hashVars = window.location.hash;
	if(hashVars != "" && hashVars !== undefined && hashVars != "#"){
		var hashArr = hashVars.substr(1).split(';');
		for(var i = 0; i < hashArr.length; i++){
			variable = hashArr[i].split(':');
			urlVars[variable[0]] = variable[1];
		}
	}else{
		urlVars = {"site":"ore"};
		window.location.hash = "#site:ore";
	}
}
function getUrlVars(){
	return window.location.hash;
}
function setUrlVars(hash){
	for(var item in hash){
		urlVars[hash[item][0]] = hash[item][1];
	}
	var hashString = "";
	for(var variable in urlVars){
		if(urlVars[variable] != undefined){
			hashString += ';'+variable+':'+urlVars[variable];
		}
	}
	hashString = "#"+hashString.substr(1);
	window.location.hash = hashString;
}


/**
 * GENERAL AJAX FUNCTION
 */
function ajaxLoad(data, destination, onLoadedFunc, preSendFunc, onErrorFunc, dataType){
	var ajaxCache = "";
	
	if(destination === undefined || $(destination) === undefined){
		destination = "content";
	}
	ajaxTarget = destination;
	
	if((onLoadedFunc === undefined && data == "ore") || (onLoadedFunc === undefined && data == "ice") || (onLoadedFunc === undefined && data == "alloy")){
		onLoadedFunc = ajaxFunctions.onLoaded_sheet;
	}else if(onLoadedFunc === undefined){
		onLoadedFunc = ajaxFunctions.onLoaded_standard;
	}
	if(preSendFunc === undefined){
		preSendFunc = ajaxFunctions.preSend_standard;
	}
	if(onErrorFunc === undefined){
		onErrorFunc = ajaxFunctions.onError_standard;
	}
	
	if(dataType === undefined){
		dataType = "html";
	}

	$.ajax({
		url: "load.php",
		data: "l="+data,
		timeout: 10000,
		dataType: dataType,
		type:"POST",
		beforeSend: preSendFunc,
		error: onErrorFunc,
		success: onLoadedFunc
	});
	pageTracker._trackEvent("ajaxLoad", "l="+data);
}


/**
 * ENCODES AN OBJECT INTO AN JSON-STRING
 */
function jsonEncode(jsonObj){
    var parts = [];

    for(var key in jsonObj) {
   	    var value = jsonObj[key];
        var str = '"' + key + '":';

        if(typeof value == "number"){
            str += value;	
        } else if(typeof value == "object") {
        	str += jsonEncode(value);
		} else if(value === false){
       	    str += 'false';
        } else if(value === true){
       	    str += 'true';
        } else {
       	    str += '"' + value + '"';
   	    }
        
        parts.push(str);
    }
    var json = parts.join(",");

    return '{' + json + '}';
}

/**
 * HELPER FUNCTION FOR TABBED MENUS TO SWITCH TAB-STYLE
 */
function toggleTabs(newTab, tabsTable, onFinish){
	$(tabsTable + ' tr[class=tabsrow] td').removeClass("tabsactive");
	$(newTab).addClass("tabsactive");
	
	if(onFinish !== undefined){
		onFinish();
	}
}

/**
 * FUNCTION TO LOAD SITE-CONTENT
 */
function loadSite(site){ //TODO:0
	if(!$('#menu_'+site).hasClass("tabsactive")){
		toggleTabs('#menu_'+site, '#menu');
		ajaxLoad(site,"content");
		setUrlVars([["site",site]]);
		pageTracker._trackPageview("/eve/oretable/index.html"+getUrlVars());
	}
}

/**
 * GETTER AND SETTER FOR USER SETTINGS
 */
var userSettings_iid;

function changeUserSettings(vars, seconds){
	for(var i = 0; i < vars.length; i++){
		userVars[vars[i][0]] = vars[i][1];
	}
	
	if(seconds === undefined || seconds == ''){
		seconds = 1;
	}
	seconds = parseInt(seconds);
	userSettings_iid = setTimeout(saveUserSettings, seconds);
}
function loadUserSettings(){
	$.ajax({
		url: "load.php",
		data: "l=user&a=get",
		dataType: "json",
		timeout: 10000,
		type:"POST",
		success: function(userObj){
			userVars = userObj;
			if(userVars.userName != "!TEMP"){
				toggleLogin(true);
			}else{
				$('#div_userInfo').html('<a href="javascript:void(0);" onClick="toggleLogin();">Login</a>');
			}
			pageTracker._trackEvent("user", "load; "+escape(userVars.userName));
		}
	});
}
function saveUserSettings(){
	if(userVars.userName != "!TEMP"){
		$.ajax({
			url: "load.php",
			data: "l=user&a=set&d="+encodeURI(jsonEncode(userVars)),
			dataType: "json",
			timeout: 10000,
			type:"POST",
			beforeSend: ajaxFunctions.preSend_sheet,
			success: function(userObj){
				userVars = userObj;
				ajaxLoad(urlVars.site+"&sheetOnly","div_sheet",ajaxFunctions.onLoaded_sheet,ajaxFunctions.preSend_sheet);
				pageTracker._trackEvent("user", "save; "+escape(userVars.userName));
			},
			error: function(XMLHttpRequest, textStatus, errorThrown){ alert("saveUserSettings: "+textStatus); }
		});
	}else{
		alert("Attention: You have to be logged in with a profile\nin order to save user settings.");
	}
}
function userChangeTableSort(sortArray){
	if(userVars.userName != "!TEMP"){
		var sendData = {};
		userVars['sortTable_'+String(urlVars.site)] = sendData['sortTable_'+String(urlVars.site)] = Object(sortArray);
		$.ajax({
			url: "load.php",
			data: "l=user&a=changeTableSort&d="+encodeURI(jsonEncode(sendData)),
			dataType: "json",
			timeout: 10000,
			type:"POST",
			error: function(XMLHttpRequest, textStatus, errorThrown){ alert("saveUserSettings: "+textStatus); }
		});
	}	
}

/**
 * LOGIN FUNCTIONS
 */
function toggleLogin(showUserName){
	if(showUserName){
		$('#div_userInfo').html('Profile: <b>'+userVars.userName+'</b> - <a href="javascript:void(0);" onClick="loginUser(\'!TEMP\');">Logout</a>');
	}else{
		$('#div_userInfo').html('<input type="text" id="login_userName" size="22" value="Profilename goes here" onclick="if(this.value == \'Profilename goes here\'){this.value=\'\';}" /> <input type="button" value="Login" onClick="loginUser($(\'#login_userName\').val());" />');	
	}
}
function loginUser(userName){
	$.ajax({
		url: "load.php",
		data: "l=user&a=login&u="+escape(userName),
		timeout: 10000,
		type:"POST",
		error: function(XMLHttpRequest, textStatus, errorThrown){
			alert("Error: "+textStatus);
		},
		success: function(html){
			if(html == "false"){
				alert("ERROR #lU");
			}else{
				loadUserSettings();
				ajaxLoad(urlVars.site+"&sheetOnly","div_sheet",ajaxFunctions.onLoaded_sheet,ajaxFunctions.preSend_sheet);
			}
		}
	});
	pageTracker._trackEvent("user", "login; "+escape(userName));
}


/**
 * FORMULA FUNCTIONS
 */
function preParseFormula(formlaInput){
	var regexps = {
		'Arkonor': 'Ak',
		'Bistot': 'Bs',
		'[(Crok|Crokite)]': 'Ck',
		'[(Ochre|Dark Ochre)]': 'Do',
		'Gneiss': 'Gn',
		'[(Hed|Hedbergite)]': 'Hb',
		'[(Hem|Hemorphite)]': 'Hm',
		'Jaspet': 'Js',
		'Kernite': 'Kn',
		'Mercoxit': 'Mx',
		'Omber': 'Om',
		'[(Plag|Plagioclase)]': 'Pg',
		'[(Pyro|Pyroxeres)]': 'Py',
		'[(Scor|Scordite)]': 'Sc',
		'[(Spod|Spodumain)]': 'Sp',
		'[(Veld|Veldspar)]': 'Vd'
	};
	
	var input = '2*275000 * dark ochre';
	var output = '';
	
	for(var i in ores) {
		var test = new RegExp(i, 'ig');
		if(input.match(test)) {
			output = input.replace(test, ores[i]);
		}
	}
	
	alert(output);
	
	var testFormula = "2 * Arko ";
	var unparsed = [/[\s]*(ar[.^\s]*)[\s]*/ig];
	var parsed = ["A"];
	alert(testFormula.replace(unparsed[0],parsed[0]));
}
function parseFormula(formula){
/*	formula = formula.replace(/\s/ig,"");
	formula = formula.replace(/arkonor/ig,"A");
	formula = formula.replace(/bistot/ig,"B");
	formula = formula.replace(/crokite/ig,"C");
	formula = formula.replace(/darkochre/ig,"D");
	formula = formula.replace(/gneiss/ig,"G");
	formula = formula.replace(/hedbergite/ig,"Hd");
	formula = formula.replace(/hemorphite/ig,"Hm");
	formula = formula.replace(/jaspet/ig,"J");
	formula = formula.replace(/kernite/ig,"K");
	formula = formula.replace(/mercoxit/ig,"M");
	formula = formula.replace(/omber/ig,"O");
	formula = formula.replace(/plagioclase/ig,"Pl");
	formula = formula.replace(/pyroxeres/ig,"Py");
	formula = formula.replace(/scordite/ig,"Sc");
	formula = formula.replace(/spodumain/ig,"Sp");
	formula = formula.replace(/veldspar/ig,"V");
	alert(eval(formula));*/
}


/**
 * DOES THE LOCALISATION
 */
function doLocalisation(objId){
/*	if(objId === undefined){
		$("[rel*=localize]").localize("lng_cerlestes",{pathPrefix:"js",skipLanguage: /^en/});
	}else{
		$(objId).localize("lng_cerlestes",{pathPrefix:"js",skipLanguage: /^en/});
	}*/
}

/**
 * INITIALIZES THE TABLESORTER
 */
function doTablesorter(table){
	if(urlVars.site == "ore"){
		$(table).tablesorter({
			headers: {
				0: {sorter:'text'},
				1: {sorter:'mineralvalue'},
				2: {sorter:'mineralvalue'},
				3: {sorter:'mineralvalue'},
				4: {sorter:'mineralvalue'},
				5: {sorter:'mineralvalue'},
				6: {sorter:'mineralvalue'},
				7: {sorter:'mineralvalue'},
				8: {sorter:'mineralvalue'},
				9: {sorter:'price'},
				10:{sorter:'security'}
			},
			sortList: [userVars['sortTable_ore'] || [0,0]]
		});
	}else if(urlVars.site == "alloy"){
		$(table).tablesorter({
			headers: {
				0: {sorter:'text'},
				1: {sorter:'digit'},
				2: {sorter:'digit'},
				3: {sorter:'digit'},
				4: {sorter:'digit'},
				5: {sorter:'digit'},
				6: {sorter:'digit'},
				7: {sorter:'digit'},
				8: {sorter:'digit'},
				9: {sorter:'price'}
			},
			sortList: [userVars['sortTable_alloy'] || [0,0]]
		});
	}else if(urlVars.site == "ice"){
		$(table).tablesorter({
			headers: {
				0: {sorter:'text'},
				1: {sorter:'digit'},
				2: {sorter:'digit'},
				3: {sorter:'digit'},
				4: {sorter:'digit'},
				5: {sorter:'digit'},
				6: {sorter:'digit'},
				7: {sorter:'digit'},
				8: {sorter:'price'},
				9: {sorter:'security'}
			},
			sortList: [userVars['sortTable_alloy'] || [0,0]]
		});
	}
}


/**
 * THE MININGTIMER FUNCTIONS
 */
var mT_afterSeconds = 180;
var mT_currentSeconds = 0;
var mT_iid = 0;
var mT_alarmJustHappened = false;

function toggleMiningTimer(forced){
	if($('#div_miningTimer').hasClass("show") && forced === undefined){
		$('#div_miningTimer').removeClass("show");
		$('#div_miningTimer').html('<a href="javascript:void(0);" onClick="toggleMiningTimer();" rel="localize[lng.miningtimer.show]">Show Miningtimer</a>');
	}else{
		$('#div_miningTimer').addClass("show");
		ajaxLoad('miningTimer','div_miningTimer', undefined, ajaxFunctions.preSend_miningTimer);
		doLocalisation();
	}
}

function initMiningTimer(afterSeconds){
	mT_afterSeconds = afterSeconds;
	mT_currentSeconds = 0;
	mT_alarmJustHappened = false;
	mT_iid = window.clearInterval(mT_iid);
	mT_iid = window.setInterval("doMiningTimer()",1000);
	doMiningTimer();
}
function killMiningTimer(finalEnd){
	mT_iid = window.clearInterval(mT_iid);
	mT_iid = window.clearTimeout(mT_iid);
	if(finalEnd){
		$('#mT_text').html('Alarm stopped.');
	}else{
		mT_iid = window.setTimeout("killMiningTimer(true)",2000);
	}
}

function doMiningTimer(){
	if(mT_currentSeconds < mT_afterSeconds){
		mT_currentSeconds++;

		if(mT_alarmJustHappened){
			mT_alarmJustHappened = false;
		}else{
			$('#mT_text').html('<span rel="localize[lng.miningtimer.alarmin]">Alarm in</span> '+(mT_afterSeconds-mT_currentSeconds+1)+' <span rel="localize[lng.miningtimer.seconds]">seconds</span>!');
		}
	}else{
		$('#mT_text').html('<span rel="localize[lng.miningtimer.alarm]">ALARM!</span> <embed src="img/miningtimer.swf?playalarm=yes" quality="high" pluginspage="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" width="1" height="1"></embed>');
		if($('#mT_loop').attr('checked')){
			mT_currentSeconds = 0;
			mT_alarmJustHappened = true;
		}else{
			killMiningTimer();
		}
	}
}




/**
 * ONLOAD
 */
$(document).ready(function(){	
	// UrlVars parsen, um Variablen zu bekommen
	parseUrlVars();
	
	// Usersettings laden
	loadUserSettings();
	
	// Init Miningtimer
	$('#div_miningTimer').addClass("show");
	if(String(userVars.miningTimer_show) == "true"){
		toggleMiningTimer(true);
	}else{
		toggleMiningTimer();
	}
	
	// Infofenster laden, vor Content!!! (sonst Bug)
	ajaxLoad('infoWindow', 'div_infoWindow', ajaxFunctions.onLoaded_infoWindow, ajaxFunctions.preSend_infoWindow);
	
	// Übergebene Seite laden (parseUrlVars setzt "ore" als Standard, wenn nichts übergeben wird)
	loadSite(urlVars.site, $('#menurow > td').get(0));

//	changeUserSettings({'0':['foo','bar']});
});