/*** General javascript functions on www.dsek.lth.se ***/

/* function to add a callback to window.onload */
function jsOnload(callback) {
	if(typeof window.addEventListener != 'undefined'){
		//.. gecko, safari, konqueror and standard
		window.addEventListener('load', callback, false);
	}
	else if(typeof document.addEventListener != 'undefined'){
		//.. opera 7
		document.addEventListener('load', callback, false);
	}
	else if(typeof window.attachEvent != 'undefined'){
		//.. win/ie
		window.attachEvent('onload', callback);
	}
	else{
		//.. mac/ie5 and anything else that gets this far
		//if there's an existing onload function
		if(typeof window.onload == 'function'){
			//store it
			var existing = window.onload;

			//add new onload handler
			window.onload = function(){
				//call existing onload function
				existing();
				//call $javascriptFunction onload function
				callback();
			};
		}
		else{
			//setup onload function
			window.onload = callback;
		}
	}
}

/* function to reload CAPTCHA images */
/* (when image is unreadable or user is bored) */
function newCaptcha(id){
	// loads new CAPTCHA image
	if(document.getElementById)
	{
		// extract image name from image source (i.e. cut off ?randomness)
		src = document.getElementById(id).src;
		src = src.substring(0,src.lastIndexOf('.')+4);
		// add ?(random) to prevent browser/isp caching
		document.getElementById(id).src = src+'?'+Math.round(Math.random()*100000);
	} else {
		alert('Det går inte att ladda om bilden i din webbläsare. Skicka in formuläret med en felaktig kod så får du en ny.');
	}
}

/*** Begin quick user search. ***/

function topTableClick() {
	if (document.getElementById('quicksearch-window').style.visibility == 'visible'){
		closeQuickSearch();
	}else {
		document.getElementById('quicksearch-window').style.visibility = 'visible';
		document.getElementById('quicksearch-window').style.opacity = 1;
		document.quickSearchForm.quicksearch.focus();
	}
}

function quickSearchKeyDown(e) {
	key = getkeycode(e);

	if(key == 27) { //escape
		box = document.getElementById('suggest-results');
		if(box && box.style.visibility == 'hidden') {
			closeQuickSearch();
		}
	}
}

function closeQuickSearch() {
	document.quickSearchForm.quicksearch.value = '';
	document.quickSearchForm.quicksearch.blur();
	document.getElementById('quicksearch-window').style.visibility = 'hidden';
	
	/*Denna rad initierar toningseffekten i webkit. Det verkar dock som om vissa versioner av Chrome under Linux fÃ¥r problem. Ska undersÃ¶ka saken nÃ¤rmare*/
	document.getElementById('quicksearch-window').style.opacity = 0;
}
/*** End quick user search. ***/

/*** Begin table row highlight on mouseover. ***/

var arrayOfRolloverClasses = new Array();
var activeRow = false;

function highlightTableRow() {
	var tableObj = this.parentNode;
	if(tableObj.tagName != 'TABLE') {
		tableObj = tableObj.parentNode;
	}

	if(this != activeRow){
		this.setAttribute('origCl', this.className);
		this.origCl = this.className;
	}
	this.className = arrayOfRolloverClasses[tableObj.id];

	activeRow = this;
}

function resetRowStyle() {
	var origCl = this.getAttribute('origCl');
	if(!origCl)
		origCl = this.origCl;
	this.className = origCl;
}

function addTableRolloverEffect(tableId, whichClass) {
	arrayOfRolloverClasses[tableId] = whichClass;

	var tableObj = document.getElementById(tableId);
	var tBody = tableObj.getElementsByTagName('TBODY');
	if(tBody){
		var rows = tBody[0].getElementsByTagName('TR');
	}else{
		var rows = tableObj.getElementsByTagName('TR');
	}

	for(var no = 0; no <rows.length; no++) {
		if(rows[no].className != 'norollover') {
			rows[no].onmouseover = highlightTableRow;
			rows[no].onmouseout = resetRowStyle;
		}
	}

}

/*** End table row highlight on mouseover. ***/



/*** Begin sortable tables. ***/

var tableWidget_okToSort = true;
var tableWidget_arraySort = new Array();
var tableWidget_tableCounter = 1;
var activeColumn = new Array();

function sortNumeric(a, b){
	a = a.replace(/, /, '.');
	b = b.replace(/, /, '.');
	a = a.replace(/[^\d\.\/]/g, '');
	b = b.replace(/[^\d\.\/]/g, '');
	if(a.indexOf('/') >= 0)
		a = eval(a);
	if(b.indexOf('/') >= 0)
		b = eval(b);

	return a / 1 - b / 1;

}

function stripHTML(oldString) {
	return oldString.replace(/<\S[^><]*>/g, '');
}

function sortString(a, b) {
	var cmpA = stripHTML(a);
	var cmpB = stripHTML(b);
	if(cmpA.toUpperCase() < cmpB.toUpperCase())
		return -1;
	if(cmpA.toUpperCase() > cmpB.toUpperCase())
		return 1;
	return 0;
}

function sortTable() {
	if(!tableWidget_okToSort)
		return;
	tableWidget_okToSort = false;

	/* Getting index of current column */
	var obj = this;
	var indexThis = 0;

	while(obj.previousSibling) {
		obj = obj.previousSibling;
		if(obj.tagName) {
			if(obj.tagName == 'TD' || obj.tagName == 'TH')
				indexThis++;
		}
	}

	if(this.getAttribute('direction') || this.direction) {
		var direction = this.getAttribute('direction');
		if(navigator.userAgent.indexOf('Opera') >= 0)
			direction = this.direction;
		if(direction == 'ascending') {
			direction = 'descending';
			this.setAttribute('direction', 'descending');
			this.direction = 'descending';
		} else {
			direction = 'ascending';
			this.setAttribute('direction', 'ascending');
			this.direction = 'ascending';
		}
	} else {
		var direction = 'ascending';
		this.setAttribute('direction', 'ascending');
		this.direction = 'ascending';
	}

	var tableObj = this.parentNode.parentNode.parentNode;
	var tBody = tableObj.getElementsByTagName('TBODY')[0];

	var widgetIndex = tableObj.getAttribute('tableIndex');
	if(!widgetIndex)
		widgetIndex = tableObj.tableIndex;

	var sortMethod = tableWidget_arraySort[widgetIndex][indexThis]; // N = numeric, S = String
	if(activeColumn[widgetIndex] && activeColumn[widgetIndex]!= this) {
		if(activeColumn[widgetIndex])
			activeColumn[widgetIndex].removeAttribute('direction');
	}

	activeColumn[widgetIndex] = this;

	var cellArray = new Array();
	var cellObjArray = new Array();
	for(var no = 1; no < tableObj.rows.length; no++) {
		if(tableObj.rows[no].cells[indexThis]) {
			var content = tableObj.rows[no].cells[indexThis].innerHTML + '';
			cellArray.push(content);
			cellObjArray.push(tableObj.rows[no].cells[indexThis]);
		}
	}

	if(sortMethod=='N') {
		cellArray = cellArray.sort(sortNumeric);
	} else {
		cellArray = cellArray.sort(sortString);
	}

	if(direction == 'descending') {
		for(var no = cellArray.length; no >= 0; no--) {
			for(var no2 = 0; no2 < cellObjArray.length; no2++) {
				if(cellObjArray[no2].innerHTML == cellArray[no] && !cellObjArray[no2].getAttribute('alreadySorted')) {
					cellObjArray[no2].setAttribute('alreadySorted', '1');
					tBody.appendChild(cellObjArray[no2].parentNode);
				}
			}
		}
	} else {
		for(var no = 0; no < cellArray.length; no++) {
			for(var no2 = 0;no2 < cellObjArray.length; no2++) {
				if(cellObjArray[no2].innerHTML == cellArray[no] && !cellObjArray[no2].getAttribute('alreadySorted')) {
					cellObjArray[no2].setAttribute('alreadySorted', '1');
					tBody.appendChild(cellObjArray[no2].parentNode);
				}
			}
		}
	}

	for(var no2 = 0; no2 < cellObjArray.length; no2++){
		cellObjArray[no2].removeAttribute('alreadySorted');
	}

	tableWidget_okToSort = true;

}

function initSortTable(objId, sortArray) {

	var obj = document.getElementById(objId);

	var tHead = obj.getElementsByTagName('THEAD')[0];
	if(tHead) {
		var cells = tHead.getElementsByTagName('TD');
	} else {
		var firstTr = obj.getElementsByTagName('TR')[0];
		if(firstTr) {
			var cells = firstTr.getElementsByTagName('TH');
		} else {
			return false;
		}
	}

	if(!sortArray) {
		sortArray = Array();
		for(var no = 0; no < cells.length; no++) {
			if(cells[no].className == 'sortNot') {
				sortArray[no] = false;
			} else if(cells[no].className == 'sortAsNumber') {
				sortArray[no] = 'N';
			} else {
				sortArray[no] = 'S';
			}
		}
	}

	obj.setAttribute('tableIndex', tableWidget_tableCounter);
	obj.tableIndex = tableWidget_tableCounter;
	tableWidget_arraySort[tableWidget_tableCounter] = sortArray;

	for(var no = 0; no < cells.length; no++) {
		if(sortArray[no]) {
			cells[no].className = 'sortableTableHeading';
			cells[no].onclick = sortTable;
		}
	}

	/* Right align numeric cells */
	for(var no2 = 0; no2 < sortArray.length; no2++){
		if(sortArray[no2] && sortArray[no2] == 'N')
			obj.rows[0].cells[no2].style.textAlign = 'right';
	}

	tableWidget_tableCounter++;

	return true;

}

/*** End sortable tables. ***/

/*** Begin Paginator In Place Editing. ***/

function paginatorEdit(button) {
	var select = button.parentNode.getElementsByTagName('select')[0];
	button.style.display = 'none';
	var input = document.createElement('input');
	input.type =  'text';
	input.name = 'page';
	input.size = '3';
	input.value = select.value;
	select.parentNode.replaceChild(input, select);
	input.focus();
	input.select();
	input.onblur = function() { paginatorTextBlur(select, input, button); }
	input.onkeydown = function(e) { if (getkeycode(e) == 27) { input.value = select.value; input.blur(); } }
}

function paginatorTextBlur(select, input, button) {
	select.value = input.value;
	if (select.value != input.value) { //option for selected value didn't exist
		var newoption = document.createElement('option');
		newoption.selected = true;
		newoption.value = newoption.innerHTML = input.value;
		select.appendChild(newoption);
	}
	input.parentNode.replaceChild(select, input);
	button.style.display = '';
}

/*** End Paginator In Place Editing. ***/

/* halt event function */
function haltEvent(e) {
	if (e == undefined) {
		return;		
	}
	if (e.ctrlKey) return true;

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

/* function to get pressed key from event */
function getkeycode(e) {
	e = e || window.event;

    if (document.layers)
        return e.which;
    else if (document.all)
        return event.keyCode;
    else if (document.getElementById)
        return e.keyCode;
    return 0;
}

function toggleQuickSearch(show) {
	if(show=='funkis'){
		document.getElementById('quicksearch-person-div').style.display = 'none';
		document.getElementById('quicksearch-funkis-div').style.display = 'block';
	}else if(show=='person'){
		document.getElementById('quicksearch-person-div').style.display = 'block';
		document.getElementById('quicksearch-funkis-div').style.display = 'none';
	}
}

