/*
 Software created by Martin Tramšak.
 You can use freely as long as you note who vrote this software (Martin Tramšak)
 and place a link to his website (http://www.vegasmetisce.com). Additionaly
 you mustn't use this software for commercial reasons.

 Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/3.0/
*/
var InputBoxOpen = '';
var activeMouseOver = new Array();
var statusOcene = null;
var ocenaForm = "hidden";
var odprt = null;
var box = new Object();
box.httpScript = "http://localhost/redovalnica/";
box.odprti = new Object();
var oceneArray = '';
var propArray = '{"boxOcenePredmet":"predmet", "boxOceneID":"ocena", "boxOceneKonf":"konf", "boxOceneDate":"date", "boxOceneZapisek":"zapisek", "boxOceneTip":"tip", "boxCalHeader":"header", "boxCalText":"vsebina"}'.evalJSON();
var status = 0;
var highlight = '';
box.currentOpt = "redholder";
box.fired = 0;

function AddMark() {
	action = "addmark";
}
var loading = function() {
	$('loader').show();
}
function newSubject(name) {
	//Lets get the field values
	var str = "&sa=addSub";
	var URL = box.http + str;
	new Ajax.Request(URL, {
		method: 'post', 
		onSuccess: newSubjectHandler,
		onCreate:loading,
		parameters: { novPredmet: encodeURIComponent(name)} ,
		encoding: 'UTF-8'});
}
var newSubjectHandler = function(t) {
	if (error.check(t.responseText)) return;
	len = Red.data.predmeti.length;
	var addField = error.ajax;
	Red.data.predmeti[len] = new Object();
	Red.data.predmeti[len].id = addField[1];
	Red.data.predmeti[len].name = addField[0];
	Red.data.predmeti[len].ocene = new Array();
	Red.data.predmeti[len].stat = new Array();
	Red.init();
}

function deleteSub(obj) {
	var res = new Array();
	res = obj.split("_");
	id = Red.data.predmeti[res[1]].id;
	out = "id_" + id;
	// to ni najbolj pametno samo se mi s tem ne da ukvarjat
	if (statusOcene && statusOcene[1] == res[1]) statusOcene = null;
	var str = "&sa=delSub&" + out +"=1";
	new Ajax.Request(box.http + str, {method: 'get', onSuccess: handlerFunc, onCreate:loading});
}
var handlerFunc = function(t) {
	if (error.check(t.responseText)) return;
	delField = error.ajax;
	Red.data = false;
	Red.init();
}

/* ocena Form */

function ocenaFormToggle(e) {
	x = Event.element(e).parentNode.childNodes[0];
	if ((x.style.display == "none") || (x.style.display == '')) {
		x.style.display = "inline";
		x.focus();
		x.value = '';
		if (odprt) {
			document.getElementById(odprt).style.display = "none";
		}
		odprt = x.id;
	} else {
		x.style.display = "none";
		odprt = null;
	}
}

function submitenter(e){
	var keycode;
	var obj = Event.element(e);
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.keyCode;
	else return true;
	numcheck = /\d/;
	code = String.fromCharCode(keycode);
	if (keycode == 13 || numcheck.test(code)){
		if (numcheck.test(code)) x = code;
		else x = $(obj).value;
		index = obj.id.replace("tool_", "");
		var ind = new Array();
		ind = index.split("_");
		data = Red.data.predmeti[ind[0]].id + "_" + ind[1];
		box.ocenaNew = obj.id;
		URL = box.http +"&sa=addMark&mark=" + x + "_"+ data;
		new Ajax.Request(URL,
			{onSuccess: function(t) {
				if (error.check(t.responseText)) return;
				data = error.ajax;
				oceneNew = new Array();
				oceneNew.ocena = x;
				oceneNew.date = data.date;
				oceneNew.konf = data.konf;
				Red.data.predmeti[ind[0]].ocene.push(oceneNew);
				Red.data.predmeti[ind[0]].stat = data.stat;
				Red.dodana = new Array( ind[0], Red.data.predmeti[ind[0]].ocene.length-1 );
				Red.populate();
			}, onCreate:loading});
		odprt = null;
		obj.style.display="none";
		return false;
	} 
	if (keycode == Event.KEY_ESC) {
		obj.style.display="none";
		odprt = null;
	}
		
}
function showInfo(e){
	ID = Event.element(e).id;
	showInfoEvent(ID);
}
function showInfoEvent(ID){
	data = ID.split("_");
	ocenaID = data[1];
	predmetID = data[0];
	alias = Red.data.predmeti[predmetID].ocene[ocenaID];
	if ("boxOceneIDInput" != box.Tab) $("boxOceneIDInput").innerHTML = (typeof(alias.ocena) != "undefined" ? alias.ocena : "empty");
	if ("boxOceneDateInput" != box.Tab) $("boxOceneDateInput").innerHTML = (typeof(alias.date) != "undefined" ? alias.date : "empty");
	if ("boxOceneKonfInput" != box.Tab) $("boxOceneKonfInput").innerHTML = (typeof(alias.konf) != "undefined" ? alias.konf : "empty");
	if ("boxOcenePredmetInput" != box.Tab) $("boxOcenePredmetInput").innerHTML = (Red.data.predmeti[predmetID].name ? Red.data.predmeti[predmetID].name : "");
	if ("boxOceneTipInput" != box.Tab) $("boxOceneTipInput").innerHTML = Red.setClassToTip(alias.tip);
	s = null;
	if (alias.zapisek) s = nl2br(alias.zapisek.toString());
	if ("boxOceneZapisekInput" != box.Tab) $("boxOceneZapisekInput").innerHTML = (s != null ? s: "klikni tukaj");
	showFileInfo(alias.dat, predmetID, ocenaID);
	$("boxtitle").hide();
	$("dat").style.display = "block";
	$("ocene").style.display = "block";
	if (!disableAjax) toggle.init();
	oceneHighlight.init();
	initLightbox();
	document.upload.predmetID.value = Red.data.predmeti[predmetID].id;
	document.upload.ocenaID.value = data[1];
	if (statusOcene != null) $(statusOcene[1]+"_"+statusOcene[0]).removeClassName('selected');
	statusOcene = new Array(ocenaID, predmetID);
	$(statusOcene[1]+"_"+statusOcene[0]).addClassName('selected');
	
	if (Red.dodana) {
		$(Red.dodana[0]+"_"+Red.dodana[1]).removeClassName("dodana");
		Red.dodana = '';
	}
}
var oceneHighlight = {
	init: function() {
		id = $('ocene');
		for (i=0;i<id.childNodes.length;i++) {
			if (id.childNodes[i].tagName == "SPAN") {
				id.childNodes[i].onmouseover = oceneHighlight.change;
				id.childNodes[i].onmouseout = oceneHighlight.change;
			}
		}
	},
	change: function(e) {
		e = e || event;
		var obj = e.target || e.srcElement;
		evt = e.type || window.event.type;
		if (!propArray[obj.id]) obj = obj.parentNode;
		
		if (evt == "mouseover") { 
			obj.style.background = "#fff68f";
			activeMouseOver[obj] = true;
		} else {
			obj.style.background = "";
			activeMouseOver[obj] = false;
		}
	}
}
function showFileInfo(dataY, predmet, ocena) {
	x = $('dat');
	x.update('<span id="boxOceneDat">Pripete datoteke (</span><span id="pripni">+</span>)</span>');
	if (dataY) {
		for (num=0; num < dataY.length; num++) {
			split = dataY[num].type.split("/");
			if (split[0] != "image") x.insert('<span class="dat" id="dat_'+i+'">'+dataY[num].name+' (<a href="'+box.httpPath+'/down/'+dataY[num].file+'">*</a>) <span id="delAttach'+num+'">X</span></span>');
			else x.insert('<span class="dat" id="dat_'+num+'">'+dataY[num].name+' (<a href="'+box.httpPath+'/down/'+dataY[num].file+'" rel="lightbox">*</a>) <span id="delAttach'+num+'">X</span></span>');
			
			$('delAttach'+num).setAttribute("onclick", "delAttach("+predmet+", "+ocena+", "+num+");");
	}}
	initLightbox();
}
function delAttach(predmet, ocena, num) {
	dataY = Red.data.predmeti[predmet].ocene[ocena].dat;
	URL = box.httpPath+'/del/'+dataY[num].file;
	new Ajax.Request(URL, {method: 'get', onSuccess: function (t) {
			if (error.check(t.responseText)) return;
			Red.data.predmeti[predmet].ocene[ocena].dat.splice(num,1);
			showFileInfo(Red.data.predmeti[predmet].ocene[ocena].dat, predmet, ocena);
			toggle.init();
	}, onCreate:loading});
}
function nl2br(s) {
	while (s && s.toString().indexOf("\n") > -1)
		s = s.replace("\n","<br>");
	return s;
}
function br2nl(s) {
	while (s.indexOf("<br>") > -1)
	s = s.replace("<br>", "\n");
	while (s.indexOf("<BR>") > -1)
	s = s.replace("<BR>", "\n");
	return s
}
function passID(e, type) {
	if (!type)type = 'INPUT';
	id = Event.element(e).id;
	if (typeof(propArray[id]) == 'undefined') id = Event.element(e).parentNode.id;
	toggleInputBox(id, type);
}
function findType(tip) {
	if (propArray[tip]) {
		z = propArray[tip];
		if(z == "zapisek") return Red.data.predmeti[statusOcene[1]].ocene[statusOcene[0]].zapisek;
		if(z == "ocena") return Red.data.predmeti[statusOcene[1]].ocene[statusOcene[0]].ocena;
		if(z == "date") return Red.data.predmeti[statusOcene[1]].ocene[statusOcene[0]].date;
		if(z == "konf") return Red.data.predmeti[statusOcene[1]].ocene[statusOcene[0]].konf;
		if(z == "predmet") return Red.data.predmeti[statusOcene[1]].name;
		if(z == "tip") return Red.setClassToTip(Red.data.predmeti[statusOcene[1]].ocene[statusOcene[0]].tip);
		if(z == "header") return Cal.data.header;
		if(z == "vsebina") return Cal.data.vsebina;
	}
}
var toggle = {
	init: function(idji) {
		box.Fcache = {};
		if (!idji) idji = ['ocene']; /*prej je bil tuki še 'note'*/
		if (typeof(idji) != 'object') idji = [idji];
		idji.each(function(e) {
				x = $(e);
				if (e == "ocene") { 
					Event.observe($('pripni'), "click", function() { $("uploader").toggle(); });
					$('delMark').onclick = delMark; }
				
				for (i=0;i<x.childNodes.length;i++) {
					if (x.childNodes[i].tagName == "SPAN") {
						ID = x.childNodes[i].id;
						if (ID == 'boxOceneZapisek' || ID == 'boxCalText') x.childNodes[i].name = "TEXTAREA";
						else x.childNodes[i].name = "INPUT";
						Event.observe(x.childNodes[i], "click", toggle.open);
						//x.childNodes[i].className = "boxClass";
	}}});},
	open: function(e) {
		if (e.type) evt = Event.element(e);
		// maybe we manually called this function and supplied different data
		else { 
			if (typeof(e) == 'object') evt = e;
			if (typeof(e) != 'object') evt = $(e);
		}
				
		if (typeof(propArray[evt.id]) == 'undefined') evt = Event.element(e).parentNode;
		for (i=0;i<evt.childNodes.length;i++) {
			if (evt.childNodes[i].tagName == "INPUT" || evt.childNodes[i].tagName == "TEXTAREA") { return false; }
		}
		type = evt.name;
		id = evt.id;
		alerts.alert(id);
		var inputEl = document.createElement(type);
		InVal = findType(evt.id);
		inputEl.value = ( InVal ? htmlspecialchars_decode(InVal) : '');
		box.odprti[id] = findType(id);
		//Event.stopObserving(evt, "click", box.Fcache[evt.id])
		$(evt.childNodes[1]).remove();
		evt.appendChild(inputEl);
		Event.observe(inputEl, "keydown", function(e) {
			var obj = Event.element(e);
			if (e.keyCode == Event.KEY_ESC) {
				obj.value = box.odprti[id];
				toggle.close(obj.parentNode.id);
			}
			if (e.keyCode == Event.KEY_RETURN) {
				if (type != "TEXTAREA") {
					toggle.close(obj.parentNode.id);
				}
			}
			if (e.keyCode == Event.KEY_TAB) {
				if (obj.parentNode.id == "boxOceneZapisek") t = $("boxOcenePredmet");
				else t = obj.parentNode.next().next();
				setTimeout(function() {toggle.open(t)}, 100);
			}
		});
		Event.observe(inputEl,'blur',focus_out);
		inputEl.focus();
		inputEl.select();
	},
	close: function(id) {
		x = $(id);
		alerts.hide();
		if (box.odprti[id] != x.childNodes[1].value) {
			box.value = x.childNodes[1].value;
			box.open = id;
			box.openID = statusOcene[1];
			if (box.status == "red") id_mod = statusOcene[0] + "_" + Red.data.predmeti[statusOcene[1]].id + "_" + Red.data.predmeti[statusOcene[1]].ocene[statusOcene[0]].konf;
			else id_mod = Cal.openMesec + '_' + Cal.openDan;
			URL = box.http +"&sa=markUpdate&id="+ id_mod +"&prop=" + id +"&val=" + encodeURI(box.value); 
			new Ajax.Request(URL, {method: 'get', onSuccess: AjaxHandler, onCreate:loading});
		} else {
			box.value = box.odprti[id];
			closeInputBox(x);
		}}
}
function closeInputBox(x) {
	id = x.id;
	var inputEl = Builder.node("span");
	inputEl.innerHTML = nl2br(findType(id));
	inputEl.id = id + "Input";
	replaceEl = x.childNodes[1];
	Event.observe(x, "click", toggle.open);
	Event.stopObserving(replaceEl, "blur", focus_out);
	delNode = x.removeChild(replaceEl);
	x.appendChild(inputEl);
}

function focus_out(e) {
	status = 1;
	y = Event.element(e);
	toggle.close(y.parentNode.id);
	status = 0;
}
function boxAction(data) {
	ID = data['id'].split("_");
	ID[1] = box.openID;
	switch(data['prop']) {
	case "ocena":
		Red.data.predmeti[ID[1]].ocene[ID[0]].ocena = data['value'];
		if (data['value'] == "?")
			Cal.populate();
		break;
	case "predmet":
		index = 0;
		Red.data.predmeti.each(function(t) {
			if (t.id == data['value'])
				Red.data.predmeti[index].ocene.push(Red.data.predmeti[ID[1]].ocene[ID[0]]);
			index++;
		})
		Red.data.predmeti[ID[1]].ocene.splice(ID[0], 1);
		statusOcene = new Array(ID[0], ID[1]);
		break;
	case "konf":
		Red.data.predmeti[ID[1]].ocene[ID[0]].konf = data['value'];
		break;
	case "date":
		Red.data.predmeti[ID[1]].ocene[ID[0]].date = data['value'];
		if (Red.data.predmeti[ID[1]].ocene[ID[0]].ocena == "?")
			Cal.populate();
		else {
			var dat = new Array();
			trenutni = Cal.getFullDate(data['value']);
			
			danes = new Date();
			if (danes<trenutni) {
				Red.data.predmeti[ID[1]].ocene[ID[0]].ocena = "?";
				$("boxOceneIDInput").update("?");
			}
		}
		break;
	case "tip":
		Red.data.predmeti[ID[1]].ocene[ID[0]].tip = data['value'];
		break;
	case "zapisek":
		Red.data.predmeti[ID[1]].ocene[ID[0]].zapisek = data['value'];
		break;
	case "header":
		Red.data.koledar[Cal.mesecID].data[Cal.current].header = data['value'];
		break;
	case "vsebina":
		Red.data.koledar[Cal.mesecID].data[Cal.current].vsebina = data['value'];
		break;
	}
	if (data.stat) {
		Red.data.predmeti[ID[1]].stat = data.stat;
	}
}
var AjaxHandler = function(t) {
	if (error.check(t.responseText)) return;
	phpArray = error.ajax;
	boxAction(phpArray);
	if (box.status == "red") Red.init();
	if (box.status == "cal") Cal.populate();
	closeInputBox($(phpArray.inputId));
}
var Red = {
	init: function() {
		unFocus.History.addEventListener('historyChange', toggleNote.history);
		box.status = "red";
		load = Builder.node("div",{id: "loading" }, "loading...");
		load.appendChild(Builder.node("img", {src: "img/ajax-loader.gif"}));
		$('redholder').innerHTML = '';
		$('redholder').appendChild(load);
		Red.obj = Builder.node("table");
		Red.obj.onmouseover = Red.high;
		Red.obj.onmouseout = Red.high;
		if ($('redovalnica')) {
			x = $('redholder');
			x.removeChild($('redovalnica'));
		}
		if (!Red.data) {
			new Ajax.Request(box.http+"&sa=oceneArray", {method: 'get',  onSuccess: Red.store}); 
		} else {
			Red.create();
		}
	},
	high: function(e) {
		e = e || event;
		var obj = e.target || e.srcElement;
		evt = e.type || window.event.type;
		defObj = obj;
		var ocenaHigh = false;
		var x = ["Neznan", "Pisna", "Ustna", "Projektna"];
		if (x.indexOfArray(obj.className)) ocenaHigh = true;
		if (obj.tagName != "TR") {
			//alert(obj.tagName)
			while (obj.parentNode != null) {
				if (obj.parentNode.tagName == "TR"){
					objekt = obj.parentNode;
				}
				obj = obj.parentNode;
			}
			//alert(objekt.tagName)
		}
		if (evt == "mouseover") {
			if (ocenaHigh)
				defObj.style.textDecoration = "underline";
			objekt.style.background = "#fff68f";
			activeMouseOver[objekt] = true;
		} else {
			if (ocenaHigh)
				defObj.style.textDecoration = "none";
			objekt.style.background = "";
			activeMouseOver[objekt] = false;
		}
	},
	populate: function() {
		for (i=1;i<=konference;i++) {
			for (j=0;j<Red.data.predmeti.length;j++) {
				if (Red.data.predmeti[j] != null) {
					predmetID = j;
					currentEl = $('ocene_'+j+'_'+i);
					Red.removeChilds(currentEl);
					sortArr = new Array();
					for (k=0;k<Red.data.predmeti[predmetID].ocene.length;k++) {
						cur = Red.data.predmeti[predmetID].ocene[k];
						if (cur.konf == i) {
							sortArr.push(new Array(cur.date, cur.ocena, cur.tip, k));
						}}
						sorted = sortArr.sort(Cal.sortfunc)
						sorted.each(function(cur) {
							newElement = document.createElement("span");
							textNode = document.createTextNode(cur[1]);
							newElement.appendChild(textNode);
							newElement.id = predmetID+"_"+cur[3]
							Element.observe(newElement, "click", showInfo);
							newElement.className = Red.setClassToTip(cur[2]);
							currentEl.appendChild(newElement);
							
							if (cur[1] == "?")
								newElement.className = "Test";
							
							if (Red.dodana && Red.dodana[0] == predmetID && Red.dodana[1] == cur[3])
								newElement.addClassName("dodana");
						});
						if (i == 1) {
							Red.removeChilds($('stat_' + j))
							$('stat_' + j).className="statTd";
						}
						//alert(Red.data.predmeti[predmetID].stat[i]['sum'])
						if (Red.data.predmeti[predmetID].stat && Red.data.predmeti[predmetID].stat[i]) {
							pov = Math.round(Red.data.predmeti[predmetID].stat[i]['sum'] / Red.data.predmeti[predmetID].stat[i]['vse']*100)/100;
							povSum = Math.round(Red.data.predmeti[predmetID].stat[0]['sum'] / Red.data.predmeti[predmetID].stat[0]['vse']*10)/10;
							if (pov) currentEl.appendChild(Builder.node("span",{className: "statistika"}, "~ "+pov));
							Red.removeChilds($('stat_' + j));
							if (povSum) $('stat_' + j).appendChild(Builder.node("span", povSum));
							$('stat_' + j).className = (povSum > 1.5 ? "statTdPoz" : "statTdNeg");
						} else currentEl.appendChild(Builder.node("span", ""));
					}			
				}
			n = n+2;
		}
	},
	setClassToTip: function(tip) {
		switch(parseInt(tip)) {
		case 1: return "Ustna";
		case 2: return "Pisna";
		case 3: return "Projektno";
		default: return "Neznan";
		}
	},
	store: function(t) {
		Red.data = t.responseText.evalJSON();
		if (!Red.data.koledar) Red.data.koledar = new Array();
		if (!Red.data.predmeti) Red.data.predmeti = new Array();
		//alert(Red.data.map(Object.extend()).inspect())
		Cal.populate();	
		
		// timeout dodan zaradi nekompatibilnosti opere. :D
		var b = setTimeout(Red.create,0);
		var b = setTimeout(checkUrl,0);
	},
	removeChilds: function(cell) {
		if (cell.hasChildNodes()){
			while (cell.childNodes.length >= 1){
				cell.removeChild(cell.firstChild);       
			}}
	},
	create: function() {
		
		theadTR = Builder.node("thead");
		thead = Builder.node("tr");
		Red.tbody = Builder.node("tbody");
		rowTh = document.createElement("th");
		rowThA = document.createElement("ul");
		rowThA.id ="krneki";
		rowThA.innerHTML = '<li><span id="slika" style="font-size:12px;"> menu<img src="img/icns.gif"></span><div id="div"><a href="#" id="PrX" rel="SubjectName" class="lbOn">Nov predmet</a><a href="#" id="rearrange">Razvrsti</a></div></li>';
		rowTh.setAttribute("colSpan",1);
		rowThText = Builder.node("span", {style:'float:left;'}, "Predmet");
		rowTh.appendChild(rowThText);
		if (!disableAjax) rowTh.appendChild(rowThA);
		thead.appendChild(rowTh);
		for (var i=1;i<=konference;i++) {
			rowTh = document.createElement("th");
			rowTh.setAttribute("colSpan",1);
			rowThText = document.createTextNode(i + ". Konferenca");
			rowTh.appendChild(rowThText);
			thead.appendChild(rowTh);
		}
		rowTh.setAttribute("colSpan",2);
		index = 0;
		if (!Red.li){
			Red.data.predmeti.each(function(i) {
				if (i != null) {
					n = new Array(i.name, index);
					row = createRow(n);
					Red.tbody.appendChild(row);
					index++;
				}
			});
		}else 
			arange.init();
		theadTR.appendChild(thead);
		Red.obj.appendChild(theadTR);
		//$('redholder').appendChild(Red.obj);
		if (!Red.li){ 
			Red.obj.appendChild(Red.tbody); 
			$('redholder').appendChild(Red.obj);
		}else { 
			$('redholder').appendChild(Red.obj);
			$('redholder').appendChild(Red.tbody);
			Sortable.create('sortable',{ghosting:true,constraint:'vertical'});
			}
		Red.obj.setAttribute("id" , "redovalnica");
		Red.obj.className = "redovalnica";
		
		if (!disableAjax) dropdown.init();
		initialize();
		if (!disableAjax) Event.observe("rearrange", 'click', arange.sortables);
		Red.populate();
		$('redholder').removeChild($('loading'));
	}
}


var Cal = {
	populate: function() {
		if (!Red.data) Red.init();
		Cal.eventArr = new Array();
		//first lets delete previous entries
		var daysinmonth = $('daysinmonth').value;
		for(n=1;n<=daysinmonth;n++) {
			x = Cal.getID($("cal_"+n));
			var header = $("cal_"+n).childNodes[0];
			x.innerHTML = "";
			Red.removeChilds(header);
			span = header.appendChild(Builder.node('span',{style:'float: right; position:relative;', name:n}, n));
			if (!disableAjax) Event.observe(span, "click", Cal.inputOptions);
		}
		if (!Red.data.koledar[Cal.findMonth($('mesec').value)]) {
			arr = new Array();
			data = {mesec: $('mesec').value, data: arr};
			Red.data.koledar.push(data);
		} else {
			Red.data.koledar[Cal.findMonth($('mesec').value)].data.each(function(t, index) {
				k = Cal.getID($("cal_"+t.dan));
				k.innerHTML += '<span>'+t.header+'</span>';
				Cal.eventArr.push(new Array(t.dan + ' ' + Cal.datesRe($('mesec').value), t.header));
			})
		}
		Red.removeChilds($("eventsList"));
		Red.data.predmeti.each(function(t) {
			if (t != null) {
			t.ocene.each(function(obj) {
				if (obj.ocena == "?") {
					var dat = new Array();
					var dat = obj.date.split(" ");
					m = Cal.dates(dat[1]);
					var mesec = $('mesec').value;
					if (mesec == m) {
						k = Cal.getID($("cal_"+dat[0]));
						k.innerHTML += '<span>'+t.name+'</span>'; //class="'+Red.setClassToTip(obj.tip)+'"
					}
					Cal.eventArr.push(new Array(obj.date, t.name));
					
				}
			})};
		});
		
		Cal.eventArr.push(new Array(Red.data.event[0], Red.data.event[1]));
		sorted = Cal.eventArr.sort(Cal.sortfunc);
		counter = 1;
		today = new Date();
		for (i =0;i<sorted.length;i++) {
			if (today<=Cal.getFullDate(sorted[i][0]) && counter < 5) {
				if (sorted[i][1] == "počitnice") fixedEvent = true;
				Cal.events(sorted[i][0], sorted[i][1], trenutni);
				counter++;
			}
		}
		trenutni = Cal.getFullDate(Red.data.event[0]);
		if (typeof(fixedEvent) != 'undefined') Cal.events(Red.data.event[0], Red.data.event[1], trenutni);
	},
	getFullDate: function(date) {
		var data = new Array();
		data = date.split(" ");
		trenutni=new Date();
		year = (data[2] ? data[2] : trenutni.getFullYear());
		trenutni.setFullYear(year ,Cal.dates(data[1]) - 1, data[0]);
		return trenutni;
	},
	sortfunc: function(a,b) {
		a = Cal.getFullDate(a[0]);
		b = Cal.getFullDate(b[0]);
		if (a>b) { return 1; }
		if (a<b) return -1;
		return 0;
	},
	findMonth: function(month) {
		for (i=0;i<Red.data.koledar.length;i++) {
			if (Red.data.koledar[i].mesec == month)
				return i;
		}
	},
	showDay:function(e) {
		box.status = "cal";
		e = e || event;
		var obj = e.target || e.srcElement;
		if (obj.tagName != "TD") {
			while (obj.parentNode != null) {
				if (obj.parentNode.tagName == "TD") objekt = obj.parentNode;
				obj = obj.parentNode;
			}
			obj = objekt;
		}
		var dan = new Array();
		dan = obj.id.split("_");
		mesec = parseInt($('mesec').value);
		Cal.openDan = dan[1];
		Cal.openMesec = mesec;
		Cal.data = '';
		Cal.mesecID = Cal.findMonth(mesec);
		$('dayHeader').innerHTML= dan[1] + " " + $('mesecIme').value;
		if (Red.data.koledar[Cal.mesecID]) {
			for(i=0;i<Red.data.koledar[Cal.mesecID].data.length;i++){
				t = Red.data.koledar[Cal.mesecID].data[i];
				if (t.dan == Cal.openDan){
					Cal.data = t;
					Cal.current = i;
				}
			}
		}
		$('calDay').show();
		if (typeof(Cal.data) != 'object') {
			a = {"dan": Cal.openDan, "header": "", "vsebina": ""};
			if (Cal.openMesec && Cal.openDan) {
				Cal.data = a;
				Red.data.koledar[Cal.mesecID].data.push(a);
				Cal.current = Red.data.koledar[Cal.mesecID].data.length -1;
			}
		}
		$('boxCalHeaderInput').innerHTML = (Cal.data.header ? Cal.data.header : "none");
		$('boxCalTextInput').innerHTML = (Cal.data.vsebina ? Cal.data.vsebina : "none");
		toggle.init('dayData');
	},
	dodaj: function() {
		$('dayDodaj').hide();
		$('dayData').show();
		Cal.showDay();
	},
	getID: function(id) {  // id je objekt :D
		return id.childNodes[2];
	},
	dates: function(mesec) {
		meseci = {"januar":1, "februar":2, "marec":3, "april":4,"maj":5, "junij":6, "julij":7, "avgust":8, "september":9, "oktober":10,"november":11,"december":12};
		if (meseci[mesec]) return meseci[mesec];
		else return false;
	},
	datesRe: function(mesec) {
		meseci = {1:"januar", 2:"februar", 3:"marec", 4:"april",5:"maj", 6:"junij", 7:"julij", 8:"avgust", 9:"september", 10:"oktober",11:"november",12:"december"};
		if (meseci[mesec]) return meseci[mesec];
		else return false;
	},
	events: function(date, name, trenutni) {
		o = document.createElement("span");
		diff = Math.floor((trenutni.getTime() -today.getTime())/ (1000 * 60 * 60 * 24));
		dan = (diff == 1 ? "dan" : "dni");
		y = document.createTextNode(date+": "+ name +" ("+diff+" "+dan+")");
		o.appendChild(y);
		o.className = "eventsList";
		$("eventsList").appendChild(o);
	},
	inputOptions: function(e) {
		el= Event.element(e);
		Cal.dayC = el.innerHTML;
		$('dayHeader').innerHTML= el.innerHTML + " " + $('mesecIme').value;
		$('CalIzbira').show();
		$('calDay').show();
		$('CalDogodek').hide();
	},
	izbira: function(el) {
		if (el.name == 1) {
			if (Cal.dropdownBox) return;
			Cal.dropdownBox = true;
			//create predmeti dropdown
			dropdownBox = Builder.node("select");
			Cal.dropdownBoxEl = dropdownBox;
			Red.data.predmeti.each(function(d) {
				option = Builder.node("option",{id: d['id']} ,d['name']);
				dropdownBox.appendChild(option);
			})
			Event.observe(dropdownBox, 'change', function(e) {
				evt = Event.element(e);
				data = '?_'+ evt.options[evt.selectedIndex].id+'_?';
				URL = box.http + "&sa=addMark&mark=" + data+'&date='+Cal.dayC+'-'+$('mesec').value+'-'+$('leto').value;
				new Ajax.Request(URL, {method: 'post', onSuccess: function(text) {
					if (error.check(text.responseText)) return;
						data = error.ajax;
						oceneNew = {ocena: '?', date: data.date, konf: data.konf};
						Red.data.predmeti[data['predmet']].ocene.push(oceneNew);
						Red.data.predmeti[data['predmet']].stat = data.stat;
						Red.populate();
						$('CalIzbira').hide();
						$('calDay').hide();
						$('CalDogodek').hide();
						Cal.dropdownBox = false;
						Cal.populate();
						Element.remove($(Cal.dropdownBoxEl));
				}})
			})
			Element.insert(el, {after: dropdownBox});
		}
	}
}
function calChange(a) {
	new Ajax.Updater('redCal', a, { onComplete: function(t) { Cal.populate(); $('loader').hide(); }, onCreate:loading});
	return false;
}
function createRow(addField) {
	row = Builder.node('tr');

	
	var cellLeft = Builder.node('td');
	var cellLeftCB = Builder.node('div');
	if (!Red.li)cellLeftCB.className = "formCheckbox";
	else cellLeftCB.className = "formCheckboxSort";
	cellLeft.appendChild(cellLeftCB);
	
	cellLeft.className = 'predmet';
	cellLeft.id =  addField[1];
	var textLink = document.createElement('a');
	textLink.href = '#';
	
	textLink.onclick = function() { deleteSub('id_' + addField[1])};
	textLink.innerHTML = "X";
	var textNode = document.createElement("div");
	textNode.className = "subdeleteDiv";
	textNode.appendChild(Builder.node("span", addField[0]));
	if (!disableAjax) Event.observe(textNode.childNodes[0], "click", function() {togglePredmetiInput(addField[1]);});
	cellLeft.appendChild(textNode);
	row.appendChild(cellLeft);
	
	var cellLeftX = Builder.node('div');
	cellLeftX.className = "tools";
	if (!disableAjax) cellLeftX.appendChild(textLink);
	cellLeft.appendChild(cellLeftX);
	for (var i=1;i<=konference;i++) {
		var cellLeftOcene = Builder.node('td', { className: "ocene" + konference });
		OceneDiv = Builder.node('div', { className: "oceneDiv", id: "ocene_" + addField[1] +"_" + i });
		row.appendChild(cellLeftOcene);
		cellLeftOcene.appendChild(OceneDiv);
		
		var cellLeftPlus = Builder.node('div', { className: "tools"});
		var inputBox = Builder.node('input', { type: "text", className:"textInput", id:"tool_"+addField[1]+"_"+i});
		Event.observe(inputBox, "keydown", submitenter);
		var SpanEl = Builder.node('span', { className: "addMark", align:"right", title: "S klikom na plus dodate oceno"}, "+")
		Event.observe(SpanEl, "click", ocenaFormToggle);
		cellLeftPlus.appendChild(inputBox);
		if (!disableAjax) cellLeftPlus.appendChild(SpanEl);
		cellLeftOcene.appendChild(cellLeftPlus);
	}
	stat = Builder.node('td', { id: 'stat_' + addField[1], className : 'statTd' });
	row.appendChild(stat);
	return row;
}
function togglePredmetiInput(t) {
	x = document.getElementById(t).childNodes[1];
	if (x.childNodes[0].tagName == "SPAN") {
		val = x.childNodes[0].innerHTML;
		cre = document.createElement("input");
		cre.value = val;
		box.predmet = val;
		x.removeChild(x.childNodes[0]);
		x.appendChild(cre);
		cre.focus();
		cre.select();
		Event.observe(cre, "keydown", function(e) {
			if (e.keyCode == Event.KEY_ESC) {
				novi = document.createElement("span");
				novi.innerHTML = box.predmet;
				Event.observe(novi, "click", function() {togglePredmetiInput(t);});
				x.removeChild(x.childNodes[0]);
				x.appendChild(novi);
			}
			if (e.keyCode == Event.KEY_RETURN) togglePredmetiInput(t);
		});}
	else if (x.childNodes[0].tagName == "INPUT") {
		URL = box.http + "&sa=predmetUpdate&id=" + Red.data.predmeti[t].id + "&val=" + x.childNodes[0].value;
		new Ajax.Request(URL, {method: 'post', onSuccess: function(text) {
				error.check(text.responseText)
				if (error.s === true) { val = box.predmet; }
				else {val = x.childNodes[0].value }
				novi = document.createElement("span");
				novi.innerHTML = val;
				Red.data.predmeti[t].name = val;
				x.removeChild(x.childNodes[0]);
				x.appendChild(novi);
				Event.observe(novi, "click", function() {togglePredmetiInput(t);});
		}, onCreate:loading});
}}
var toggleNote = {
	toggle: function(what) {
		$(box.currentOpt).style.display = "none";
		$(what).style.display= "block";
		// hide all modules first
		x = $("left").getElementsByTagName("DIV")
		for (i =0;i<x.length;i++) {
			x[i].style.display="none"
		}
		if (modules[what]["modules"]) {
			modules[what]["modules"].each(function(t) { 
					$(t).style.display= "block"; 
			});
		}
		unFocus.History.addHistory(what);
		box.currentOpt = what;
		if (typeof(modules[what]["func"]) == 'function') modules[what]["func"]();
	},
	history: function(hash) {
		if (hash == '') hash = 'redholder'
		toggleNote.toggle(hash);
	}
}
var AIM = {
	frame: function(c) {
		var n = 'f' + Math.floor(Math.random() * 99999);
		var d = document.createElement('DIV');
		d.innerHTML = '<iframe style="display:none" src="about:blank" id="'+n+'" name="'+n+'" onload="AIM.loaded(\''+n+'\')"></iframe>';
		document.body.appendChild(d);
		var i = document.getElementById(n);
		if (c && typeof(c.onComplete) == 'function') {
			i.onComplete = c.onComplete;
		}
		return n;
	},
	form: function(f, name) {
		f.setAttribute('target', name);
	},
	submit: function(f, c) {
		AIM.form(f, AIM.frame(c));
		if (c && typeof(c.onStart) == 'function') 
			return c.onStart();
		else 
			return true;
	},
	loaded: function(id) {
		var i = document.getElementById(id);
		if (i.contentDocument) {
			var d = i.contentDocument;
		} else if (i.contentWindow) {
			var d = i.contentWindow.document;
		} else {
			var d = window.frames[id].document;}
		if (d.location.href == "about:blank") 
			return;
		if (typeof(i.onComplete) == 'function') 
			i.onComplete(d.body.innerHTML);
	}
}
function startCallback() {
	return true;
}
function completeCallback(response) {
	if (error.check(response)) return;
	dataX = error.ajax;
	index = 0;
	Red.data.predmeti.each(function(t) {
		if (t.id == dataX.predmetID)
			pr = index;
		index++;
	})
	ocena = Red.data.predmeti[pr].ocene[dataX.ocenaID];
	if (typeof(Red.data.predmeti[pr].ocene[dataX.ocenaID].dat) != 'object')
		Red.data.predmeti[pr].ocene[dataX.ocenaID].dat = new Array();
	Red.data.predmeti[pr].ocene[dataX.ocenaID].dat.push(dataX.file);
	showFileInfo(Red.data.predmeti[pr].ocene[dataX.ocenaID].dat, pr, dataX.ocenaID);
	$("uploader").toggle();
	toggle.init();
}
function delMark() {
	URL = box.http + "&sa=delMark&predmet="+Red.data.predmeti[statusOcene[1]].id+"&ocena="+statusOcene[0];
	new Ajax.Request(URL, {method: 'get', onSuccess: function(text) {
		if (error.check(text.responseText)) return;
		data = error.ajax;
		//alert(statusOcene[1] + statusOcene[0]);
		ocena = Red.data.predmeti[statusOcene[1]].ocene[statusOcene[0]].ocena;
		Red.data.predmeti[statusOcene[1]].ocene.splice(statusOcene[0],1);
		Red.data.predmeti[statusOcene[1]].stat = data['stat'];
		if (ocena == "?")
			Cal.populate();
		Red.populate();
		$("dat").style.display = "none";
		$("ocene").style.display = "none";
		$("boxtitle").show();
		statusOcene = null;
	}, onCreate:loading});
}
var importData = {
	submit: function() {
		$('importForm').request({ onComplete: function(t){ alert(t.responseText) } });
	}
}
/* Dropdown div */
var odprt = false;
var closetimer = '';
var dropdown = {
	init: function (){
		$('slika').onclick = function() {
			if (!odprt) {
				$('div').style.display = "block";
				$('krneki').onmouseout = dropdown.timer;
				$('krneki').onmouseover = dropdown.cancelTimer;
				$('div').onclick = dropdown.close;
				odprt = true;
			} else {
				$('div').style.display = "none";
				odprt = false;
			}
		}
	},
        timer: function() { closetimer = window.setTimeout(dropdown.close, 500); },
	cancelTimer: function() {
		if (closetimer) {
			window.clearTimeout(closetimer);
			closetimer = null;
		}
	},
	close: function() {
		$('div').style.display = "none";
		odprt = false;
	}
}

/* Rearrange subjects */
var arange = {
	init: function() {
		
		as = Builder.node('ul', {id: 'sortable'});
		Red.data.predmeti.each(function(text, index) {
			li = Builder.node('li', {id: 'item_'+text.id});
			n = new Array(text.name, index);
			rowas = createRow(n);
			li.appendChild(Builder.node("table", {className: "redovalnica"}, rowas));
			//li.appendChild(Red.obj);
			as.appendChild(li);
		})
		Red.tbody = as;
		x = document.getElementsByClassName("formCheckbox");
		for (i=0;i<x.length;i++) { x[i].style.cursor ="crosshair" }
	},
	send: function() {
		y = Sortable.serialize('sortable');
		x = new Ajax.Request(box.http + '&sa=sort', {method: 'post',postBody: y, onSuccess: function(t) {
			if (error.check(t.responseText)) return;
			$('razvrsti').hide();
			Red.li = false;
			Red.data = '';
			Red.init();
		}, onCreate:loading})
	},
	sortables: function() {
		if (Red.li) arange.send();
		Red.li = true;
		Red.init();
		$('razvrsti').appear();
		$('rearrange').innerHTML = "potrdi razvrstitev";
		Red.removeChilds($('razvrsti'));
		$('razvrsti').appendChild(Builder.node("p", "potrdi razvrstitev"));
		$('razvrsti').onmouseover = function() { $('razvrsti').className = "boxGreenOver" }
		$('razvrsti').onmouseout = function() { $('razvrsti').className = "boxGreen" }
		$('razvrsti').onclick = arange.send;
	}
}
var alerts = {
	init: function() {
		alerts.obj = $('alerts');
		alerts.objParent = $('redAlert');
		alerts.objParent.hide();
		alerts.status = false;
		alerts.dic = new Array();
		alerts.dic['predmet'] = "kateremu predmetu pripada ocena<br><br>Note: predmet mora že obstajati";
		alerts.dic['tip'] = "Tip ocene:<ul><li>ustna (1)</li><li>Pisna (2)</li><li>projektna (3)</li></ul>";
		alerts.dic['ocena'] = "Ocena, ki ste jo prejeli. Če ocene še niste prejeli vnesite '?'";
		alerts.dic['konf'] = "V kateri konferenci ste oceno prejeli";
		alerts.dic['date'] = "Datum ko ste oceno prejeli. Možne 2 obliki formata: <ul><li>3 september 2008 (3 sep)</li><li>3.07.2008</li></ul>";
		alerts.dic['zapisek'] = "lahko dopišete kratko pripombo";
	},
	insert: function(text) {
		alerts.obj.update(text);
	},
	alert: function(id) {
		if (!alerts.status) { alerts.objParent.show(); alerts.status = true; }
		key = propArray[id];
		alerts.insert(alerts.dic[key]);
	},
	hide: function() {
		if (alerts.status) { alerts.objParent.hide(); alerts.status = false; }
	}
}
var error = {
	check: function(data) {
		$('loader').hide();
		error.ajax = data.evalJSON();
		if ((!error.ajax.status) || (error.ajax.status != "error")) {
			$("errors").hide();
			if (error.ajax.notice) {
				$("errors").show();
				$("errors").update(error.ajax.notice);
			}
			error.s = false;
			return false;
		} else {
			error.s = true;
			$("errors").innerHTML = error.ajax.reason;
			$("errors").show();
			return true;
		}
	},
	add: function(error) {
		$("errors").show();
		$("errors").update(error);
	}
}
Event.observe(document, 'keydown', function(e) {
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.keyCode;
	var obj = Event.element(e);
	if (keycode == Event.KEY_DELETE && statusOcene && obj.tagName != "INPUT" && obj.tagName != "TEXTAREA") {
		delMark();
	}
	if (keycode == 65 && obj.tagName != "INPUT" && obj.tagName != "TEXTAREA") {
		box.a = new lightbox();
		box.a.content = "SubjectName";
		box.a.activate();
		Event.stop(e);
	}
	//katerakoli smerna tipka, nobena izbrana ocena
	if (obj.tagName != "INPUT" && obj.tagName != "TEXTAREA" && 
		!statusOcene && keycode > 36 && keycode < 41 && Red.data.predmeti.length > 0) {
		for (i=0;i<Red.data.predmeti.length;i++) {
			parent = $("ocene_"+i+"_"+1);
			if (parent.childNodes.length > 0) showInfoEvent(parent.childNodes[0].id)
			return;
		}
	}
	if (obj.tagName != "INPUT" && obj.tagName != "TEXTAREA" && statusOcene){
		cur = $(statusOcene[1]+"_"+statusOcene[0])
		parent = cur.parentNode;
		res = parent.id.split("_");
		for (i=0;i<parent.childNodes.length;i++) 
			if (parent.childNodes[i].id == cur.id) curID = i;
		if (keycode == Event.KEY_TAB) {
			setTimeout(function() {toggle.open($("boxOcenePredmet"))}, 100);
		}
		if (keycode == 37) {
			if (curID < 1) {
				if (1<res[2]) {
					if ($(res[0]+"_"+res[1]+"_"+(parseInt(res[2])-1)).childNodes.length != 0)parent = $(res[0]+"_"+res[1]+"_"+(parseInt(res[2])-1));
					else return;
					curID = parent.childNodes.length-1;
				}else return;
			}
			showInfoEvent(parent.childNodes[curID-1].id)
		}
		if (keycode == 39) {
			if (curID >= (parent.childNodes.length-2)) {
				if (res[2]<konference) {
					if ($(res[0]+"_"+res[1]+"_"+(parseInt(res[2])+1)).childNodes.length != 1)parent = $(res[0]+"_"+res[1]+"_"+(parseInt(res[2])+1));
					else return;
					curID = -1;
				}else return;
			}
			showInfoEvent(parent.childNodes[curID+1].id)
		}
		if (keycode == 40) {
			if (res[1]<Red.data.predmeti.length) 
				for (i=0;i<Red.data.predmeti.length;i++)
					if (i>res[1])
						if ($("ocene_"+i+"_"+res[2]).childNodes.length != 1) {
						parent = $("ocene_"+i+"_"+res[2]);
						break;
			}
			if ((parent.childNodes.length-2) < curID && parent.childNodes.length!=1) curID = parent.childNodes.length-2
			showInfoEvent(parent.childNodes[curID].id)
			Event.stop(e);
		}
		if (keycode == 38) {
			if (res[1]>0) 
				for (i=Red.data.predmeti.length;i>=0;i--)
					if (i<res[1])
						if ($("ocene_"+i+"_"+res[2]).childNodes.length != 1) {
						parent = $("ocene_"+i+"_"+res[2]);
						break;
			}
			if ((parent.childNodes.length-2) < curID) curID = parent.childNodes.length-2
			showInfoEvent(parent.childNodes[curID].id)
			Event.stop(e);
		}
	}
});
function graf(data) {
	href= "index.php?action=graf&sa=img&sort="+data;
	$('graph').src= href;
	return false;
}
function htmlspecialchars_decode(string, quote_style) {
    string = string.toString();
    string = string.replace('/&amp;/g', '&');
    string = string.replace('/&lt;/g', '<');
    string = string.replace('/&gt;/g', '>');
    if (quote_style == 'ENT_QUOTES') {
        string = string.replace('/&quot;/g', '"');
        string = string.replace('/&#039;/g', '\'');
    } else if (quote_style != 'ENT_NOQUOTES') {
        string = string.replace('/&quot;/g', '"');
    }
    return string;
}
Array.prototype.indexOfArray = function(obj){
	var status = false;
        for(var i=0; i<this.length; i++){
		if(obj.indexOf(this[i]) > -1) status = true;
        }
        return status;
}


// leightbox, mainly for naming the new subject
/*
Created By: Chris Campbell
Website: http://particletree.com
Date: 2/1/2006

Adapted By: Simon de Haan
Website: http://blog.eight.nl
Date: 21/2/2006
*/
var OS,browser,version,total,thestring;

var lightbox = Class.create();

lightbox.prototype = {

	yPos : 0,
	xPos : 0,

	initialize: function(ctrl) {
		if (ctrl) {
			this.content = ctrl.rel;
			if (!box.fired) this.actions();
			box.fired = 1;
			Event.observe(ctrl, 'click', this.activate.bindAsEventListener(this), false);
			ctrl.onclick = function(){return false;};
		}
	},
	
	// Turn everything on - mainly the IE fixes
	activate: function(){
		if (Prototype.Browser.IE){
			this.getScroll();
			this.prepareIE('100%', 'hidden');
			this.setScroll(0,0);
			this.hideSelects('hidden');
		}
		this.displayLightbox("block");
		inputs = $(this.content).getElementsByTagName("input");
		for (i = 0; i < inputs.length; i++) {
			if (inputs[i].type == 'text') inputs[i].focus();
			if (inputs[i].title == "submit") {
				this.submit = inputs[i];
				this.cache = this.leightboxEnter.bindAsEventListener(this);
				Event.observe(this.content, "keydown", this.cache);
			}
		}
	},
	
	// Ie requires height to 100% and overflow hidden or else you can scroll down past the lightbox
	prepareIE: function(height, overflow){
		bod = document.getElementsByTagName('body')[0];
		bod.style.height = height;
		bod.style.overflow = overflow;
  
		htm = document.getElementsByTagName('html')[0];
		htm.style.height = height;
		htm.style.overflow = overflow; 
	},
	
	// In IE, select elements hover on top of the lightbox
	hideSelects: function(visibility){
		selects = document.getElementsByTagName('select');
		for(i = 0; i < selects.length; i++) {
			selects[i].style.visibility = visibility;
		}
	},
	
	// Taken from lightbox implementation found at http://www.huddletogether.com/projects/lightbox/
	getScroll: function(){
		if (self.pageYOffset) {
			this.yPos = self.pageYOffset;
		} else if (document.documentElement && document.documentElement.scrollTop){
			this.yPos = document.documentElement.scrollTop; 
		} else if (document.body) {
			this.yPos = document.body.scrollTop;
		}
	},
	
	setScroll: function(x, y){
		window.scrollTo(x, y); 
	},
	
	displayLightbox: function(display){
		$('overlay2').style.display = display;
		$(this.content).style.display = display;
		
		//if(display != 'none') this.actions();	
	},
	
	// Search through new links within the lightbox, and attach click event
	actions: function(){
		lbActions = document.getElementsByClassName('lbAction');

		for(i = 0; i < lbActions.length; i++) {
			Event.observe(lbActions[i], 'click', this[lbActions[i].name].bindAsEventListener(this), false);
			lbActions[i].onclick = function(){return false;};
		}

	},
	
	// Example of creating your own functionality once lightbox is initiated
	deactivate: function(){
		if (Prototype.Browser.IE){
			this.setScroll(0,this.yPos);
			this.prepareIE("auto", "auto");
			this.hideSelects("visible");
		}
		inputs = $(this.content).getElementsByTagName("input");
		for (i = 0; i < inputs.length; i++) {
			if (inputs[i].title == "submit") {
				Event.stopObserving(this.content, "keydown", this.cache, false);
			}
		}
		$('SubjectInput').value = ''
		this.displayLightbox("none");
		box.a = '';
	},
	
	deactivateSubmit: function(){
		if ($('SubjectInput').value) newSubject($('SubjectInput').value);
		this.deactivate();
	},
	leightboxEnter: function(e) {
		if (e.keyCode == Event.KEY_RETURN) {
			func = $(this.submit).name;
			this[func]();
		}
		if (e.keyCode == Event.KEY_ESC) {
			inputs = document.getElementsByTagName('input');
			this.deactivate();
		}
	}
}

function initialize(){
	addLightboxMarkup();
	lbox = document.getElementsByClassName('lbOn');
	for(i = 0; i < lbox.length; i++) {
		if (!disableAjax) valid = new lightbox(lbox[i]);
	}
}
function addLightboxMarkup() {
	bod 				= document.getElementsByTagName('body')[0];
	overlay 			= document.createElement('div');
	overlay.id			= 'overlay2';
	bod.appendChild(overlay);
}
var checkUrl = function() {
	var url = window.location;
	var parts = url.toString().split('#');
	if (typeof(parts[1]) != 'undefined') {
		loc = parts[1];
		toggleNote.toggle(loc);
	}
	
}
var urnik = {
	load: function() {
		new Ajax.Request(box.http+ '&sa=urnik', {method: 'get', onSuccess: urnik.init, onCreate:loading});
	},
	init: function(t) {
		if (error.check(t.responseText)) return;
		urnik.data = error.ajax;
		minus = Builder.node("span", "-");
		plus = Builder.node("span", "+");
		$("urnikFieldAdd").appendChild(minus)
		$("urnikFieldAdd").appendChild(plus)
		plus.onclick = urnik.addField;
		minus.onclick = urnik.delField;
		urnik.zacetekMin = urnik.clockConvert(urnik.data.zacetek,1);
		urnik.fields = 0;
		//lets build the table
		if (urnik.data.first == 1) {
			
			urnik.data.dnevi = new Array()
			for (var i = 0; i<5; i++) {
				urnik.data.dnevi[i] = new Array();
			}
			urnik.addField()
		}
		else {
			longest = 1;
			for (var i = 0; i<5; i++) {
				if (longest < urnik.data.dnevi[i].length) longest = urnik.data.dnevi[i].length
			}
			for (var i = 0; i<longest; i++) {
				urnik.addField();
			}
		}
	},
	addField: function() {
		row = $("urnikField").insertRow(urnik.fields+1);
		y=row.insertCell(0);
		span = Builder.node("span", urnik.clockConvert(urnik.zacetekMin+((urnik.fields)*50),2)+" - "+urnik.clockConvert(urnik.zacetekMin+((urnik.fields+1)*50)-5,2));
		y.appendChild(span)
		for (i = 1;i<6;i++) {
			input = Builder.node("input", {size:20});
			y=row.insertCell(i);
			y.appendChild(input)
		}
		urnik.fields+=1;
		$("urnikFieldAdd").rowSpan=urnik.fields+1;
		//alert(mainBody.style.height())
	},
	clockConvert: function(clock, way) {
		if (way == 1) {
			str = clock.toString().split(":")
			return parseInt(str[0])*60 + parseInt(str[1]);
		}
		else {
			ura = clock / 60;
			minuta = clock % 60;
			return Math.floor(ura)+":"+minuta;
		}
	},
	delField: function() {
		row = $("urnikField").deleteRow($("urnikField").childNodes[0].childNodes.length-1);
		urnik.fields-=1;
		$("urnikFieldAdd").rowSpan=urnik.fields+1;
	}
}
