
// Globals...
var oldStyles = [];
var currentTrsMoused = [];
var contextMenuOpen = [];
var TrsClicked = [];

var contextMenuEntries = Array();
contextMenuEntries["wertungdiv"] = [
	{
		"text" : "...Details für den Teilnehmer",
		"handlerFunction" : openStatsPopup,
		"custom": {
			"css": "statsPopup"
		}
	},
	{
		"text" : "...Für Vergleich (de)selektieren",
		"handlerFunction" : toggleCheckboxFromTR,
		"custom": { }
	},
	{
		"text" : "...Ausgewählte Starter vergleichen",
		"handlerFunction" : openComparePopup,
		"custom": {
			"css": "comparePopup"
		}
	}
];	



function trClicked(event, trElement, theName) {
	TrsClicked[theName] = trElement;

/*	sysdate = Date.now();
	trElement.id = "tr" + sysdate;
	FadeOpacity("tr" + sysdate, 100, 0, 300, 10);
*/

/*	loggi(event["srcElement"]["nodeName"]);
	loggi("--" + event["originalTarget"] + "--");
*/
	
	// Ignore clicks on checkbox images (first column of leftdiv table)
	if(event["srcElement"]) {
		if(event["srcElement"]["nodeName"] == "IMG") {
			return;
		}
	} else if(event["originalTarget"] instanceof HTMLImageElement) {
		return;
	}

	var coords = getCoords(event);
	openContextMenu(theName, coords[0]-7, coords[1]-7);
}



function openContextMenu(theName, left2, top2) {
	divId = 'contextMenu_' + theName + rand();
	trElement = TrsClicked[theName];

	contextMenuOpen[divId] = 0;
	
	var menu = document.createElement('div');
	menu.setAttribute('id', divId);
	menu.className = 'contextMenu_' + theName;
	menu.style.position = "absolute";
	menu.style.visibility = "visible"; 
	menu.style.left = left2;
	menu.style.top = top2;


	// Add menu entries...
	for (var contextMenuEntryIndex in contextMenuEntries[theName]) {
		menu.appendChild(
			createContextMenuItem(divId, theName, trElement, contextMenuEntries[theName][contextMenuEntryIndex])
		);
	}

	document.body.appendChild(menu);
	FadeOpacity(divId, 2, 100, 200, 15);
	
	dispatchDelayed('closeContextMenu("' + divId + '")', 500);

	return menu;
};


function closeContextMenu(divId) {
//	loggi("close." + contextMenuOpen[divId]);
	if(contextMenuOpen[divId] == 0) {
		contextMenu = _get(divId);
		contextMenu && document.body.removeChild(contextMenu);
		
/*		FadeOpacity(divId, 100, 1, 200, 15);
		contextMenuOpen[divId] = -1;
*/
	} else {
//		loggi("notting to close.");
	}
};


function createContextMenuItem (divId, theName, trElement, menuItemDetails) {
	var item = document.createElement("div");
	
	item.className = 'contextMenuEntry_' + theName;

	item.onmouseover = function() { 
//		loggi("moosedover..");
		contextMenuOpen[divId] = 1;
	}
	item.onmouseout = function() { 
//		loggi("moosedout..");
		contextMenuOpen[divId] = 0;
		dispatchDelayed('closeContextMenu("' + divId + '")', 50);
	}

	item.innerHTML = menuItemDetails["text"];

	var handlerFunc = menuItemDetails["handlerFunction"];
	var customParams = menuItemDetails["custom"];
	item.onclick = function(e) { 
		if (!e) var e = window.event;
		contextMenuOpen[divId] = 0;
		dispatchDelayed('closeContextMenu("' + divId + '")', 50);
		var coords = getCoords(e);
		handlerFunc(coords[1], coords[0], trElement, theName, customParams);
	}


	return item;
};



function createPopupWindow(aName) {
	// Clean up eventually left over isntances...
	if(_get(aName)) {
		alert("Should not happen!");
		document.body.removeChild(_get(aName));
	}


	newdiv = _get(aName);
	if(!newdiv) {
//		loggi("Creating new " + aName + "...");
		var newdiv = document.createElement('div');
   		newdiv.setAttribute('id', aName);
		newdiv.onclick = function() { 
//			loggi("removing " + aName + "...");
			document.body.removeChild(this);
		}
		document.body.appendChild(newdiv);
	}
	
	FadeOpacity(aName, 0, 100, 500, 15);
	return newdiv;
}


function toggleCheckboxFromTR(posY, posX, trElement, theName) {
	imgElement = _get('check' + theName + (trElement.rowIndex + 1));
	toggleCheckbox(imgElement);
}
function toggleCheckbox(imgElement) {
//	loggi("toggleCheckbox called...");

	theSrc = imgElement.src;
	imgSrc = theSrc.substr(theSrc.lastIndexOf("/") +1);

	if(imgSrc == "checked.png") {
		imgElement.src = "unchecked.png";
	} else {
		imgElement.src = "checked.png";
	}
}

function openComparePopup(posY, posX, trElement, theName, customParams) {
//	loggi("openComparePopup called...");

	newdiv = createPopupWindow("infoWindow");
	newdiv.style.visibility = 'visible';
	newdiv.className = customParams["css"];	
	newdiv.style.left = 100; //posX - 20;
	newdiv.style.top = posY -20;

	totalScores = "";
	names = "";
	tmpScore = 0;
	
	someImgs = _get("leftdiv" + theName).getElementsByTagName("img");

	var availColors = ["0000FF","00FF00","FF0000","0F0F0F","F0F0F0","F00F00","00F00F"];
	colorCount = 0;
	colors = "";
	
	for(i = 0; i < someImgs.length; i++) {
		theSrc = someImgs[i].src;
		imgname = theSrc.substr(theSrc.lastIndexOf("/") +1);

		if(imgname == "checked.png") {

			trElement2 = _get("leftdiv" + theName).firstChild.getElementsByTagName("tr")[i];
			
			tmpScore = 0;
			if(totalScores != "") { 
				totalScores += "|"; 
				colors += ",";
				names += "|";
			}

			names += escape(trElement2.getElementsByTagName("td")[2].innerHTML);
			colors += availColors[colorCount++];

			trElement2 = _get("maindiv" + theName).firstChild.getElementsByTagName("tr")[i];
			var tds = trElement2.getElementsByTagName("td");
			for(x = 1; x < tds.length; x++) {
				tmp = (tds[x].innerHTML != '--' ? tds[x].innerHTML : "0" );
				totalScores += ("" + (tmpScore + parseInt(tmp)));
				tmpScore += parseInt(tmp);
				if(x < (tds.length -1)) {
					totalScores += ",";
				}
			}
		}
	}
	
	
	totalScoresChartSrc = 
		"http://chart.apis.google.com/chart?1=1" + 
		"&cht=lc" + 
		"&chs=600x300" +
		"&chxt=x,y,r,x" + 
		"&chxl=" + 
			"0:|1|2|3|4|5|6|7|8|9|10|" + 
			"1:|0|50|100|150|200|250|300|" + 
			"2:|0|50|100|150|200|250|300|" + 
			"3:||||Bewerbe|||" + 
		"&chd=t:" + totalScores +  
		"&chds=0,300" + 
		"&chco=" + colors + 
		"&chdl=" + names + 
		"&chtt=Gesamtpunkte";

//	alert(totalScoresChartSrc);

	foo = '';
	foo += "<br><br>";
	foo += 
	'<iframe src="' + totalScoresChartSrc + '" ' + 
	' marginwidth=0 frameborder=0 scrolling="no" style="width: 600px; height:400px; padding: 0px; margin:0px; border:1px solid black;"></iframe>';

	foo += '<br><div style="font-size: 10px; color: white; background: #303030; text-align: center; font-weight:normal;">Fenster schliessen</div>';
	
	newdiv.innerHTML = foo;

}


function openStatsPopup(posY, posX, trElement, theName, customParams) {
//	loggi("openStatsPopup called...");

	newdiv = createPopupWindow("infoWindow");
	newdiv.style.visibility = 'visible';
	newdiv.className = customParams["css"];	
	newdiv.style.left = 100; //posX - 20;
	newdiv.style.top = posY -20;

	singleScores = "";
	singleScoreScales = "";
	totalScores = "";
	tmpScore = 0;
	
	singleScoresChartScale = new Array();
	singleScoresChartScale = [6,12,18,24,30,36,42,48,54,60];
	
	trElement2 = _get("maindiv" + theName).firstChild.getElementsByTagName("tr")[trElement.rowIndex];
	var tds = trElement2.getElementsByTagName("td");
	for(x = 1; x < tds.length; x++) {
//		tmp = (tds[x].innerHTML != '--' ? tds[x].innerHTML : "0" );
		totalScores += ("" + (tmpScore + parseInt((tds[x].innerHTML != '--' ? tds[x].innerHTML : "0" ))));
		if(x < (tds.length -1)) {
			totalScores += ",";
		}

		tmp = tds[x].innerHTML;
		if(tmp != '--') {
			singleScoreScales += ("" + singleScoresChartScale[x - 1]);
			singleScores += tmp;
			tmpScore += parseInt(tmp);
			if(x < (tds.length -1)) {
				singleScores += ",";
				singleScoreScales += ",";
			}
		}
	}

//	imgSrc = theSrc.substr(theSrc.lastIndexOf("/") +1);

	if(singleScoreScales.lastIndexOf(",") +1 == singleScoreScales.length) {
		singleScoreScales = singleScoreScales.substr(0, singleScoreScales.lastIndexOf(","));
		singleScores = singleScores.substr(0, singleScores.lastIndexOf(","));
	} else {
		alert("no, no comma");
	}

	singleScoresChartSrc = 
		"http://chart.apis.google.com/chart?1=1" + 
		"&cht=s" + 
		"&chs=225x200" + 
//		"&chd=t:6,12,18,24,30,36,42,48,54,60|" + singleScores + 
		"&chd=t:" + singleScoreScales + "|" + singleScores + 

		"&chxt=x,y,r,y,x" + 
		"&chds=0,60" + 
		"&chxl=" + 
			"0:|0|1|2|3|4|5|6|7|8|9|10|" + 
			"1:|0|10|20|30|40|50|60|" + 
			"2:|0|10|20|30|40|50|60|" + 
			"3:||||Punkte||||" + 
			"4:||||Bewerb|||" + 
		"&chg=10,16.66667" + 
		"&chtt=Punkte pro Bewerb";
//		"&chdl=woifal"; 
	
	alert(singleScoresChartSrc);

	totalScoresChartSrc = 
		"http://chart.apis.google.com/chart?1=1" + 
		"&cht=lc" + 
		"&chs=225x200" +
		"&chxt=x,y,r,x" + 
		"&chxl=" + 
			"0:|1|2|3|4|5|6|7|8|9|10|" + 
			"1:|0|50|100|150|200|250|300|" + 
			"2:|0|50|100|150|200|250|300|" + 
			"3:||||Bewerbe|||" + 
		"&chd=t:" + totalScores +  
		"&chds=0,300" + 
		"&chco=0000FF,00FF00" + 
		"&chtt=Gesamtpunkte";



	foo = '';
	foo += '<span align=center>Michael Menzel</span><br>';
	foo += '<table border="0"><tr><td width="180px">';
	foo += '<img src="http://www.herpanierer.com/images/morfeoshow/2009_teilneh-7447/big/MenzelMichael.jpg" style="width:150px"/>';
	foo += '</td><td><div id="containerPopup" class="container"/></div></td></tr></table>';
	
	
	foo += "<br><br>";
	foo += 
	'<iframe src="' + singleScoresChartSrc + '" ' + 
	' marginwidth=0 frameborder=0 scrolling="no" style="width: 225px; height:200px; padding: 0px; margin:0px; border:1px solid black;"></iframe>';
	foo += 
	'<iframe src="' + totalScoresChartSrc + '" ' + 
	' marginwidth=0 frameborder=0 scrolling="no" style="width: 225px; height:200px; padding: 0px; margin:0px; border:1px solid black;"></iframe>';

	foo += '<br><div style="font-size: 10px; color: white; background: #303030; text-align: center; font-weight:normal;">Fenster schliessen</div>';
	
	newdiv.innerHTML = foo;

	var table2 = new HPScrollTable(
		{
			sourceTableName: 'wertungtable2',
			targetElementName: 'containerPopup',
			width: 260,
		 	height: 200,
			theName: 'blerl',
			scrollStepSize: 30,
			scrolling: false,
			mouseOvered: false
		}
	);
	table2.show();

}



function scrollLeft() {
	alert("scrolling left..");
	_get("maindiv" + "foo").scrollLeft -= scrollStepSize;
	_get("topdiv" + "foo").scrollLeft -= scrollStepSize;
}
function scrollRight() {
	alert("scrolling right");
	_get("maindiv" + "foo").scrollLeft += scrollStepSize;
	_get("topdiv" + "foo").scrollLeft += scrollStepSize;
}
function scrollUp() {
	_get("maindiv" + "foo").scrollTop -= scrollStepSize;
	_get("leftdiv" + "foo").scrollTop -= scrollStepSize;
}
function scrollDown() {
	_get("maindiv" + "foo").scrollTop += scrollStepSize;
	_get("leftdiv" + "foo").scrollTop += scrollStepSize;
}




function searchfor() {
	scrollDown();
	for(var i = 0; i < 500000; i++) { i=i; }
	scrollDown();
	for(var i = 0; i < 500000; i++) { i=i; }
	scrollDown();
	for(var i = 0; i < 500000; i++) { i=i; }
	scrollDown();
	for(var i = 0; i < 500000; i++) { i=i; }
	scrollDown();
	for(var i = 0; i < 500000; i++) { i=i; }
	scrollDown();
	alert(_get("searchme").value);

}


function trMoused(event, trElement, theName) {
	currentTrMoused = currentTrsMoused[theName]; 
	// Mouse out old TR
	if(currentTrMoused) {
		currentTrIndex = currentTrMoused.rowIndex;
		_get("leftTr" + theName + currentTrIndex).className = oldStyles[theName];
		_get("mainTr" + theName + currentTrIndex).className = oldStyles[theName];
	}

	// Mouse over current TR
	oldStyles[theName] = trElement.className;
	currentTrsMoused[theName] = trElement;
	newTrIndex = trElement.rowIndex;
	_get("leftTr" + theName + newTrIndex).className = "mousedover";
	_get("mainTr" + theName + newTrIndex).className = "mousedover";
}



/****************************************************
	HPScrollTable
 	
 	Generates a table which can be scrolled through.
		- The header column is always visible
		- the right side area of the table can be scrolled horizontally
		- the left side area of the table is always visible
		- if a row is mouse overed, the row is highlighted in areas on both sides of the table
		- a click handler can be specified to be installed
		- scroll buttons can be shown
		- CSS styles for the table can be specified. See wertung.css for details.

****************************************************/
function HPScrollTable(newopts) {
	this.opts = {
		sourceTableName: "", 	// id of html table element to use as input
		targetElementName: "", 	// id of html element to attach scroll table as child
		width: 0,  			// widht of the scrolling table 
		height: 0,  			// height of the scrolling table
		theName: "", 			// a unique name for the table
		scrollStepSize: 30, 	// pixels to scroll per click on arrows
		scrolling: false, 		// enable synced scrolling
		clickHandling: false, 	// install click handlers?
		avoidSelection: false, 	// allow selection in table
		mouseOvered: false, 		// highlight mouse overed rows
		displayCheckboxes: false, 		// show checkboxes to provide for selection of rows
		fixedColumnsCount: 2
	};

	for (var optionKey in newopts) {
		this.opts[optionKey] = newopts[optionKey];
	}
	

	this.show = function() {
//		alert("Building results table...");
		opts = this.opts;
		theName = opts.theName;
		fixedColumnsCount = opts.fixedColumnsCount;

		var wertungtable = _get(opts.sourceTableName);
		var lines = wertungtable.getElementsByTagName("tr");
		
		var widthArray = Array();
		var totalWidth = 0;
		var fixedWidth = 0;
	
	    var splitTable = 0;
	
		// Header line 
		headerLine = lines[0];
		var fixedDescTable = 
			'<div id="fixeddiv' + theName + '" class="fixeddiv" style="padding: 0px; margin: 0px">' + 
				'<table>' + 
				'<tr>';
		var colDescTable = 
			'<div id="topdiv' + theName + '" class="topdiv" style="padding: 0px; margin: 0px">' + 
				'<table id="topdivtable' + theName + '">' + 
				'<tr>';
		var tds = headerLine.getElementsByTagName("td");
        if (tds.length > fixedColumnsCount) {
            splitTable = 1;
        }
		for(x = 0; x < tds.length; x++) {
			td = tds[x];
			widthArray[x] = td.getAttribute("width");

			if(x <= (fixedColumnsCount -1)) {
				fixedWidth += parseInt(td.getAttribute("width"));
				fixedDescTable += 
						'<td ' + (opts.avoidSelection ? ' onmousedown="return false;" onselectstart="return false;" ' : '') + ' width="' + td.getAttribute("width") + '">' + td.innerHTML + '</td>';
			} else {
				totalWidth += parseInt(td.getAttribute("width"));
				colDescTable += 
						'<td ' + (opts.avoidSelection ? ' onmousedown="return false;" onselectstart="return false;" ' : '') + ' width="' + td.getAttribute("width") + '">' + td.innerHTML + '</td>';
			}
		}
		fixedDescTable += 
				'</tr>' + 
				'</table>' +
			'</div>';
		colDescTable += 
				'</tr>' + 
				'</table>' +
			'</div>';
	
		// Content
		var lineDescTable = 
			'<div id="leftdiv' + theName + '" class="leftdiv" style="padding: 0px; margin: 0px">' + 
				'<table id="leftdivtable' + theName + '">';
		var scrollTable = 
			'<div id="maindiv' + theName + '" class="maindiv" style="padding: 0px; margin: 0px">' + 
				'<table id="maindivtable' + theName + '">';
	
		for(i = 1; i < lines.length; i++) {
			line = lines[i];
			lineStyle = i%2== 0;
			if(lineStyle) {
				lineStyle="even";
			} else {
				lineStyle="uneven";
			}
	
			var tds = line.getElementsByTagName("td");
	
			mouseOverHTML = opts.mouseOvered ? ' onMouseOver="trMoused(event, this, \'' + theName + '\')" ' : '';
			onClickHTML = opts.clickHandling ? ' onClick="trClicked(event, this, \'' + theName + '\')"' : '';

			lineDescTable += 
				'<tr id="leftTr' + theName + (i - 1) + '" class="' + lineStyle + '" ' + mouseOverHTML + onClickHTML + '>';
			lineDescTable += 
					(opts.displayCheckboxes ? '<td width="20"><img src="unchecked.png" onClick="toggleCheckbox(this)" style="border: none;" id="check' + theName + i + '"/></td>' : '');
            
			for(x = 0; x < fixedColumnsCount && x < tds.length; x++) {
                lineDescTable +=
    			    '<td ' + (opts.avoidSelection ? ' onmousedown="return false;" onselectstart="return false;" ' : '') + ' width="' + widthArray[x] + '">' + tds[x].innerHTML + '</td>'; 
            }	
			lineDescTable += 
				'</tr>';


			scrollTable +=
				'<tr id="mainTr' + theName + (i - 1) + '" class="' + lineStyle + '" ' + mouseOverHTML + onClickHTML + '>';
			for(x = fixedColumnsCount; x < tds.length; x++) {
				scrollTable +=
					'<td ' + (opts.avoidSelection ? ' onmousedown="return false;" onselectstart="return false;" ' : '') + ' width="' + widthArray[x] + '">' + tds[x].innerHTML + '</td>';
			}
			scrollTable += 
				'</tr>';
		}
	
		lineDescTable += 
				'</table><br><br>' + 
			'</div>';
	
		scrollTable += 
				'</table>' + 
			'</div>';
	
		
	
		if(splitTable) {
		    _get(opts.targetElementName).innerHTML += fixedDescTable + colDescTable + '<div style="clear:both"></div>' + lineDescTable + scrollTable;
        } else {
		    _get(opts.targetElementName).innerHTML += fixedDescTable + '<div style="clear:both"></div>' + lineDescTable;
        }

        if(splitTable) {
		    _get("topdivtable" + theName).style.width = totalWidth + "px";
		    _get("topdiv" + theName).style.width = (opts.width - fixedWidth) + "px";
		    _get("maindivtable" + theName).style.width = totalWidth + "px";
		    _get("maindiv" + theName).style.width= ((opts.width - fixedWidth) + (opts.scrolling == 1 ? 15 : 0)) + "px";
		    _get("maindiv" + theName).style.height= (opts.height + (opts.scrolling == 1 ? 17 : 0)) + "px";
	        _get("fixeddiv" + theName).style.width = fixedWidth + "px" ;
	        _get("leftdiv" + theName).style.width = fixedWidth + "px";
            _get(opts.targetElementName).style.width = (opts.width + 17)+ "px";

		 }

		_get("leftdiv" + theName).style.height= opts.height + "px";

   		if(!splitTable) {
    	    _get("leftdiv" + theName).style.width = (fixedWidth + 16) + "px";
            _get("leftdiv" + theName).style.borderTop = "1px solid white";
		    _get("leftdiv" + theName).style.overflow = "auto";

            _get("fixeddiv" + theName).style.width = (fixedWidth) + "px" ;
            _get("fixeddiv" + theName).style.borderBottom = "0px solid white";
            _get(opts.targetElementName).style.width = opts.width + "px";
	        
	    }
		
		if(splitTable) {
		    this.syncScrolling("maindiv" + theName, "leftdiv" + theName, "topdiv" + theName);
		}
		return 1;
	};
	
	
	this.syncScrolling = function(srcName, vertName, horiName) {
		srcDiv = _get(srcName);
		vertDiv = _get(vertName);
		horiDiv = _get(horiName);
	
		srcDiv.onscroll = function() {
			srcDiv = _get(srcName);
			vertDiv = _get(vertName);
			horiDiv = _get(horiName);
			vertDiv.scrollTop = srcDiv.scrollTop;
			horiDiv.scrollLeft = srcDiv.scrollLeft;
		}
	}
	


}




