var XMLfiles = new Array();
var SiteParams = new Array();
var configPath = "";
var statsPath = "";
var baseURL = "";
var basePath = "";
var showFile = "";
var statView = "No file selected";
var browser = getBrowser();
var amiIE = (browser.match(/ie/) == "ie") ? true : false;
var currentFile = "";
var currentFileName = "";
var glob_separator = "";

function initializeScript(goon) {
	if (!goon) {
		baseURL = document.URL;
		getPaths();
		loadConfig(false);
	}
	else {
		computeStatsPath(glob_separator);
		// are we loaded up from a webserver?
		if (!checkExternal()) {
			document.getElementById("xmlflheader").innerHTML = "Please wait, processing directories...";
			// are we IE???? OMG!
			if (amiIE) IEProcessing();
			else normalProcessing();
			pumpOutLinks();
			document.getElementById("xmlflheader").innerHTML = "List of recorded match-statistics ";
		}
	}
}

function getPaths() {
	var splitted = baseURL.split("\\");
	// IE docURL
	if (splitted.length <= 1) {
		splitted = baseURL.split("/");
		// delete last two (import/html file)
		splitted.pop(); splitted.pop();
		splitted = splitted.join("/");
		basePath = splitted;
		configPath = splitted + "/configs/";
		glob_separator = "/";
	}
	else {
		splitted.pop(); splitted.pop();
		splitted = splitted.join("\\");
		basePath = splitted;
		configPath = splitted + "\\configs\\";
		glob_separator = "\\";
	}
}

function loadConfig() {
	// pump out iframe trick
	document.getElementById("loadconfig").innerHTML = '<iframe id="configloader" height="0" width="0" style="border:none; position:relative;" scrolling="no" onLoad="javascript:parseConfig();" frameborder="0" src="../configs/config_clientside.html"></iframe>'
}

function parseConfig() {
	var subcontent = document.getElementById('configloader').contentWindow.document.body.innerHTML;
	if (subcontent.length > 0) statsPath = subcontent;
	document.getElementById("loadconfig").innerHTML = "";
	initializeScript(true);
}

function computeStatsPath(separator) {
	var splitstatp = statsPath.split("../");
	var countofsub = splitstatp.length;
	var rootsubs = baseURL.split(separator);
	var thePath = "";
	// get rid of current file name
	rootsubs.pop();
	for (i = 1; i<countofsub; i++) {
		rootsubs.pop();
	}
	statsPath = rootsubs.join(separator) + separator + splitstatp[splitstatp.length - 1];
}

function checkExternal() {
	if (document.URL.match(/^http:\/\//)) {
		document.getElementById("viewtype").innerHTML = "Usage error";
		document.getElementById("xmlflheader").innerHTML = "External use of MAXStats' clientside part (webserver) currently NOT supported!";
		document.getElementById("fmenu_r").innerHTML = "Couldn't process directories";
		return true;
	}
	return false;
}


function IEProcessing() {
	loadStatDirs_activex();
}

function normalProcessing() {
	getSiteParameters();
	loadStatDirs_evil();
}

function getBrowser() {
	if(document.ids)x='nc4';
	else if( document.all && !document.getElementById )x='ie4';
	else if( window.opera && !document.createElement )x='op5';
	else if( window.opera && window.getComputedStyle )  {
			  if(document.createRange)x='op8';
				else if(window.navigate)x='op7.5';
								 else x='op7.2';                   }
	else if( window.opera && document.compatMode )x='op7';
	else if( window.opera && document.releaseEvents )x='op6';
	else if( document.contains && !window.opera )x='kq3';
	else if(window.pkcs11&&window.XML)x='f15';
	else if( window.getSelection && window.atob )x='nn7';
	else if( window.getSelection && !document.compatMode )x='nn6';
	else if( window.clipboardData && document.compatMode )x='ie6';
	else if( window.clipboardData ){x='ie5';
		 if( !document.createDocumentFragment ) x+='.5';
		 if( document.doctype && !window.print ) x+='m';}
	else if( document.getElementById && !document.all ) x='op4';
	else if( document.images && !document.all ) x='nn3';
	else if(document.clientWidth&&!window.RegExp)x='kq2';
	else x='???';
	return x;
}

function getSiteParameters() {
	var doccu = document.URL;
	doccu = doccu.split("?");
	baseURL = doccu[0];
	if (doccu.length > 1) {
		doccu = doccu[1].split("&");
		for (var i = 0; i < doccu.length; i++) {
			newindex = SiteParams.length;
			SiteParams[newindex] = new Object();
			SiteParams[newindex]["name"] = doccu[i].split("=")[0];
			SiteParams[newindex]["value"] = doccu[i].split("=")[1];
			if (SiteParams[newindex]["name"] == "show") showFile = SiteParams[newindex]["value"];
		}
	}
}

function loadStatDirs_evil() {
	/*
	This function searches for stat files in q4maxdir/stats
	using a java applet hack
	
	Only for FFox remote!	
	*/
	// get xml filenames folder
	var tempDir = "";
	// year-dir
	//alert(window.location.href);
	//alert(statsPath+'/blabla.html');
	//var rootDir = getContents(statsPath+'/blabla.html', "2006/");
	rootDir = readFile("");
	if (rootDir.indexOf(".") == -1) {
		rootDir = rootDir.split("\n");
		// process all root-year dirs
		for (var ir = 0; ir < rootDir.length; ir++) {
			if (rootDir[ir].length > 0 && rootDir[ir] != "img") {
				tempDir = rootDir[ir];
				// month-dir
				var subDir = getContents(tempDir);
				if (subDir.indexOf(".") == -1) {
					var subberDir = subDir.split("\n");
					for (var is = 0; is < subberDir.length; is++) {
						if (subberDir[is].length > 0) {
							// run through found month dirs
							var monthDir = getContents(tempDir + "/" + subberDir[is]);
							if (monthDir.indexOf(".") == -1) {
								var smonthDir = monthDir.split("\n");
								for (var id = 0; id < smonthDir.length; id++) {
									if (smonthDir[id].length > 0) {
										// run through found day dirs
										var dayDir = getContents(tempDir + "/" + subberDir[is] + "/" + smonthDir[id]);
										if (dayDir.indexOf(".") != -1) {
											var dayDir = dayDir.split("\n");
											for (var ix = 0; ix < dayDir.length; ix++) {
												if (dayDir[ix].length >0) {
													if (dayDir[ix].substring(dayDir[ix].length-3) == "xml") {
														// fill up xmlfiles array
														var arrlen = XMLfiles.length;
														XMLfiles[arrlen] = new Object();
														XMLfiles[arrlen]["foldername"] = tempDir + "/" + subberDir[is] + "/" + smonthDir[id];
														XMLfiles[arrlen]["year"] = rootDir[ir];
														XMLfiles[arrlen]["month"] = subberDir[is];
														XMLfiles[arrlen]["day"] = smonthDir[id];
														XMLfiles[arrlen]["filename"] = dayDir[ix];
													}
												}
											}
										}
									}
								}
							}
						}
					}
				}
			}
		}
	}
}

function loadStatDirs_activex() {
	/*
	This function searches for stat files in q4maxdir/stats
	using ActiveX functions
	
	Only for IE local/remote!	
	*/
	var yearDir = "";
	var monthDir = "";
	var dayDir = "";
	var subFolderName = "";
	var tempName = "";
	var yearName = "";
	var monthName = "";
	var dayName = "";

	var fso = new ActiveXObject("Scripting.FileSystemObject");
	folderObj = fso.GetFolder(fso.GetParentFolderName(document.URL.replace(/file:\/\//, "")));
	
	// year-dirs
	rootDir = fso.GetFolder(careFolder(statsPath));
	var yearDirs = new Enumerator(rootDir.SubFolders);
	for (; !yearDirs.atEnd(); yearDirs.moveNext()) {
		yearDir = yearDirs.item();
		if (yearDir != "img") {
			yearDir = fso.GetFolder(yearDir);
			yearName = yearDir.Name;
			subFolderName = yearName + "/";
			// get xml filenames folder
			yearDir = new Enumerator(yearDir.SubFolders);
			
			// month-dirs
			for (; !yearDir.atEnd(); yearDir.moveNext()) {
				monthDir = yearDir.item();
				monthDir = fso.GetFolder(monthDir);
				monthName = monthDir.Name;
				subFolderName = yearName + "/" + monthName + "/";
				monthDir = new Enumerator(monthDir.SubFolders);
				// run through found month dirs
				for (; !monthDir.atEnd(); monthDir.moveNext()) {
					dayDir = monthDir.item();
					dayDir = fso.GetFolder(dayDir);
					dayName = dayDir.Name;
					subFolderName = yearName + "/" + monthName + "/" + dayName;
					// run through found day dirs
					files = new Enumerator(dayDir.Files);
					for (; !files.atEnd(); files.moveNext()) {
						if (files.item().Name.substring(files.item().Name.length-3) == "xml") {
							// fill up xmlfiles array
							var arrlen = XMLfiles.length;
							XMLfiles[arrlen] = new Object();
							XMLfiles[arrlen]["foldername"] = subFolderName.replace(/\\/, "/");
							XMLfiles[arrlen]["filename"] = files.item().Name;
							XMLfiles[arrlen]["year"] = yearName;
							XMLfiles[arrlen]["month"] = monthName;
							XMLfiles[arrlen]["day"] = dayName;
						}
					}
				}
			}
		}
	}
}

var externalDirlist = new Array();
var externalDirlist_racked = new Object();
externalDirlist_racked["years"] = new Array();
externalDirlist_racked["months"] = new Array();
externalDirlist_racked["days"] = new Array();
var end = false;
var status = "years";
var currentDir = 0;

function loadStatDirs_link() {
	document.getElementById("statinclude").src = "dirListing.html?stats";
}

function careFolder(folder) {
	// function for activex folderlisting
	var processed = "";
	processed = folder.replace(/file:\/\/\//,"");
	processed = processed.replace(/file:\/\//,"");
	processed = processed.replace(/\//g,"\\");
	processed = processed.replace(/%20/g," ");
	return processed;
}

function loadLinkInFrame() {
	if (document.URL.match(/serverside\.php/)) {
		var selected = document.getElementsByName('xmlfile')[0].options[document.getElementsByName('xmlfile')[0].selectedIndex].text;
		if (!selected.match(/Detailed/)) {
			if (selected.match(/Reload/) && currentFile.length > 0) {
				document.getElementById("statinclude").src = currentFile;
				document.getElementById("statview_name").innerHTML = currentFileName;
				document.getElementById("statsubTR").style.display = "block";
			}
			else {
				if (!selected.match(/Reload/)) {
					currentFile = document.getElementsByName('xmlfile')[0].options[document.getElementsByName('xmlfile')[0].selectedIndex].value;
					currentFileName = document.getElementsByName('xmlfile')[0].options[document.getElementsByName('xmlfile')[0].selectedIndex].text;
					document.getElementById("statinclude").src = currentFile;
					//document.getElementById("statview_name").innerHTML = "bla";
					document.getElementById("statview_name").innerHTML = document.getElementsByName('xmlfile')[0].options[document.getElementsByName('xmlfile')[0].selectedIndex].text;
					document.getElementById("statsubTR").style.display = "block";
				}
				else {
					alert("Nothing to reload ;)");
					document.getElementsByName('xmlfile')[0].options[0].selected = true;
				}
			}
			//document.getElementsByName('xmlfile')[0].options[0].selected = true;
		}
	}
	else {
		var selected = document.getElementsByName('xmlfile')[0].selectedIndex;
		if (selected == 1) reloadCurrentFile(currentFile);
		else {
			document.getElementById("statview_name").innerHTML = XMLfiles[selected-2]["filename"];
			document.getElementById("viewtype").innerHTML = "MAXStats Clientside Statistics";
			document.getElementById("statsubTR").style.display = "block";
			document.getElementById("statinclude").src = statsPath + glob_separator + XMLfiles[selected-2]["foldername"] + '/' + XMLfiles[selected-2]["filename"];
			currentFile = selected;
		}
	}
}

function reloadCurrentFile(oldindex) {
	javascript:document.getElementById('statinclude').contentWindow.location.reload();
	document.getElementsByName('xmlfile')[0].options[oldindex].selected = true;
}

function pumpOutLinks() {
	var htmlout = "<select name=\"xmlfile\" onChange=\"javascript:loadLinkInFrame();\"><option disabled selected>Please Select the XML file</option><option>Reload current file</option>";
	var year = "";
	var month = "";
	var day = "";
	XMLfiles.reverse();
	for (var i = 0; i < XMLfiles.length; i++) {
		//var splitted = XMLfiles[i]["foldername"].split("/");
		year = XMLfiles[i]["year"];
		month = XMLfiles[i]["month"];
		day = XMLfiles[i]["day"];
		htmlout += '<option value="'+i+'">['+month+'/'+day+'/'+year+'] '+XMLfiles[i]["filename"]+'</option>\n\r';
	}
	// fill space with links
	htmlout += '</select>';
	document.getElementById("linkout").innerHTML = htmlout;
	document.getElementById("xmlfcount").innerHTML = XMLfiles.length;
}

function processParameters() {
	if (showFile.length != 0) {
		document.getElementById("statview_name").innerHTML = XMLfiles[showFile]["filename"];
		document.getElementById("viewtype").innerHTML = "MAXStats Clientside Statistics";
		document.getElementById("statsubTR").style.display = "block";
		document.getElementById("statinclude").src = XMLfiles[showFile]["foldername"] + '/' + XMLfiles[showFile]["filename"];
	}
	else {
		document.getElementById("statview_name").innerHTML = "No File selected";
		document.getElementById("viewtype").innerHTML = "MAXStats Clientside Root";
	}
}

function iFrameHeight() {
	if (!amiIE) {
		// opera?
		if (browser.match(/op/)) {
			theobj = document.all.statinclude;
			theiframeheight = document.frames('statinclude').document.body.scrollHeight;
			//theiframeheight = window.frames.statinclude.document.body.scrollHeight;
			//theiframeheight = 1500;
		}
		else {
			theobj = document.getElementById('statinclude');
			theiframeheight = theobj.contentWindow.document.body.scrollHeight;
		}
		h=theiframeheight;
		w=window.innerWidth;
		theobj.height=h;
		//document.getElementById('statinclude').width=100;
		theobj.width=654;
	}
	else {
		// this sucks with IE ....
		h = document.frames('statinclude').document.body.scrollHeight;
		document.all.statinclude.height = h;
	}
}

function getContents(resname) {
	return readFile(resname);
}

function pooalert(content) {
	document.write("<textarea>"+content+"</textarea>");
}

var rcnt = 1;
function readFile(file) {
    var source = "";
    var url = new java.net.URL(statsPath + '/'+ file);
	var stream = new java.io.DataInputStream(url.openStream());
    var line    = "";
    while ((line = stream.readLine()) != null) {
        source += line + "\n";
    }
    stream.close();
    return source;
}

function processFilter(win) {
	// does basic REGEXP name filtering, evil poo
	// does a dynamic resizing of the "awards" tab, for optical improvement
	// does a datetime convert for matches
	with (win) {
		var probplayers = document.getElementsByTagName("span");
		for (var i = 0; i<probplayers.length; i++) {
			var varName = probplayers[i].id;
			if (varName == "filterme") {
				var plname = probplayers[i].firstChild.data;
				if (plname.indexOf("^") != -1 ) {
					var stripped = plname.replace(/[\^][a-zA-Z]{0,4}[0-9]{0,3}/g, "");
					probplayers[i].firstChild.data = stripped;
				}
			}
		}
		var doresize = document.getElementsByName("checkheight");
		var biggest = 0;
		// get biggest tablerow
		for (i=0; i<doresize.length; i++) {
			if (doresize[i].offsetHeight > biggest) biggest = doresize[i].offsetHeight;
		}
		// set biggest for everyone
		for (i=0; i<doresize.length; i++) {
			doresize[i].style.height = biggest*10;
			doresize[i].style.minheight = 800;
			document.getElementsByName("checkheight")[i].height = 1000;
		}
		/*var datetime = document.getElementById("filterdatetime");
		var datetimedate = document.getElementById("filterdatetime_date");
		var year = "";
		var month = "";
		var day = "";
		var hour = "";
		var minute = "";
		var second = "";	
		var Monat = new Array("January", "February", "March", "April", "May", "June",
                      "July", "August", "September", "October", "November", "December");	
		var data = datetime.firstChild.data;
		var dayname = "th";
		year 		= data.substring(0, 4);
		month 		= data.substring(5, 7);
		day 		= Number(data.substring(8, 10));
		hour 		= data.substring(11, 13);
		minute 		= data.substring(14, 16);
		second 		= data.substring(17, 19);
		if (day == "1") dayname = "st";
		if (day == "2") dayname = "nd";
		if (day == "3") dayname = "rd";
		datetime.firstChild.data = hour + ":" + minute + "h";
		datetimedate.firstChild.data = day + dayname + " " + Monat[Number(month)] + " of " + year;*/
	}
}