function toggleVisibility(elementID)
{
  var element = document.getElementById(elementID);
  if (element.style.display == "none"){
    element.style.display = "block";
    element.parentNode.style.listStyleImage = "url(images/collapse.gif)";
  }
  else {
    element.style.display = "none";
    element.parentNode.style.listStyleImage = "url(images/expand.gif)";
  }
}

function hiiri14init()
{
  var map = new Array();
  var s   = "abcdefghijklmnopqrstuvwxyz";
  for (i=0; i<s.length; i++)
    map[s.charAt(i)]			= s.charAt((i+13)%26);
  for (i=0; i<s.length; i++)
    map[s.charAt(i).toUpperCase()]	= s.charAt((i+13)%26).toUpperCase();
  return map;
}

function hiiri14(a)
{
  var hiiri14map;
  if (!hiiri14map)
    hiiri14map=hiiri14init();
  s = "";
  for (i=0; i<a.length; i++)
    {
      var b = a.charAt(i);
      s	+= (b>='A' && b<='Z' || b>='a' && b<='z' ? hiiri14map[b] : b);
    }
  return s;
}

var Pesa650 = {
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        while (i < input.length) {
            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
            output = output + String.fromCharCode(chr1);
            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
        }
        output = Pesa650._utf8_decode(output);
        return output;
    },
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
        while ( i < utftext.length ) {
            c = utftext.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
}



function naytapostit() {
	var spans = document.getElementsByTagName("SPAN");
	var etsi = /:=:(.+):=:/;
	for(var i=0;i<spans.length;i++) {
		var matches = spans[i].innerHTML.match(etsi);
		if(matches != null) {
			spans[i].innerHTML = "";
			var clearText = Pesa650.decode(hiiri14(Pesa650.decode(matches[1])));
			spans[i].style.visibility = "visible";
			spans[i].appendChild(document.createTextNode(" "));
			spans[i].appendChild(document.createTextNode(clearText));
		}
	}
}
YAHOO.util.Event.onDOMReady(naytapostit);

var valittuValikko;
var piilotusTimeout;
function keskita() {
	var alavalikkoName = YAHOO.util.Dom.getElementsByClassName("valittu", "div", "paavalikko");
	keskitaAlavalikko(alavalikkoName[0]);
	valittuValikko = alavalikkoName[0];
}
YAHOO.util.Event.onDOMReady(keskita);

function keskitaAlavalikko(paavalikkoElement) {
	var alavalikko = document.getElementById("alavalikko_"+paavalikkoElement.id);
	var palkkialue = YAHOO.util.Dom.getRegion("murupolku");
	var oikeaRaja = palkkialue.right;
	var paaValikkoAlue = YAHOO.util.Dom.getRegion(paavalikkoElement);

	var valikkoAlue = YAHOO.util.Dom.getRegion(alavalikko);
	alavalikko.style.width = (valikkoAlue.width+2)+"px";
	var vasenReuna = paaValikkoAlue.left + (paaValikkoAlue.width / 2) - ((valikkoAlue.width+4) / 2);
	if(vasenReuna > (palkkialue.right - (valikkoAlue.width+4))) {
		vasenReuna = palkkialue.right - (valikkoAlue.width+4);
	}
	YAHOO.util.Dom.setX(alavalikko, vasenReuna);
}

/*
function naytaAlavalikko(paavalikkoElement) {
	var alavalikot = YAHOO.util.Dom.getElementsByClassName("alavalikko", "div", "murupolku");
	for(var i;i<alavalikot.length;i++) {
		if(alavalikot[i].id == "alavalikko_"+paavalikkoElement.id) {
			YAHOO.util.Dom.removeClass(alavalikot[i], "hidden");
			keskitaAlavalikko(paavalikkoElement);
		} else {
			YAHOO.util.Dom.addClass(alavalikot[i], "hidden");
		}
	}
}

function piilotaAlavalikko(paavalikkoElement) {
	piilotusTimeout = setTimeout(function(){piilotaAlavalikkoOikeasti(paavalikkoElement);}, 250);
}

function piilotaAlavalikkoOikeasti(paavalikkoElement) {
	YAHOO.util.Dom.addClass("alavalikko_"+paavalikkoElement.id, "hidden");
	YAHOO.util.Dom.removeClass();
}
*/

var infocards = {};



function f_scrollLeft() {
	return f_filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}



function close_infocard() {
	//Record current position
	var currLeft = f_scrollLeft();
	var currTop = f_scrollTop();


	var overlay = document.getElementById("overlay");
	var mask = document.getElementById("mask");
	mask.style.display = "none";
	overlay.style.display = "none";

	var table = document.getElementById("infocard_table");
	var tableParent = table.parentNode;

	tableParent.removeChild(table);

	// Scroll the page back to it's original position
	setTimeout(function() {window.scroll(currLeft, currTop);}, 50);

}


function open_infocard(username) {
	//Record current position
	var currLeft = f_scrollLeft();
	var currTop = f_scrollTop();

	// Make mask visible
	var mask = document.getElementById("mask");
	mask.style.display = "block";


	// Adjust the overlay div
	var overlay = document.getElementById("overlay");
	overlay.className = "infocard";
	
	// Adjust overlay's width if specified
	if (infocards[username].width === undefined) {
		overlay.style.width = "500px";
		overlay.style.marginLeft = "-250px";
	} else {
		overlay.style.width = infocards[username].width.toString() + "px";
		overlay.style.marginLeft = "-" + (infocards[username].width / 2).toString() + "px";
	}

	// Change the header image
	var headerImg = overlay.getElementsByTagName("p")[0].getElementsByTagName("img")[0];
	headerImg.src = infocards[username].titleImage;

	// Create the table
	var table = document.createElement("table");
	table.id = "infocard_table";
	var tableRow = document.createElement("tr");
	var leftCell = document.createElement("td");
	var rightCell = document.createElement("td");
	
	// Add infocard image
	var image = document.createElement("img");
	image.src = infocards[username].image;
	image.alt = infocards[username].title;
	leftCell.appendChild(image);

	// Add other infocard information
	rightCell.innerHTML = infocards[username].innerHTML;

	// Decode e-mail addresses found in the information
        var spans = rightCell.getElementsByTagName("SPAN");
        var etsi = /:=:(.+):=:/;
        for(var i=0;i<spans.length;i++) {
                var matches = spans[i].innerHTML.match(etsi);
                if(matches != null) {
                        spans[i].innerHTML = Pesa650.decode(hiiri14(Pesa650.decode(matches[1])));
                        spans[i].style.visibility = "visible";
                }
        }

	// Add the cells to the table
	tableRow.appendChild(leftCell);
	tableRow.appendChild(rightCell);
	table.appendChild(tableRow);
	
	// Add the table to the parent div
	var parentDiv = overlay.getElementsByTagName("p")[0].parentNode;
	parentDiv.appendChild(table);	
	
	// Enable the closing button
	var closeDiv = document.getElementById('overlay_close');
	closeDiv.getElementsByTagName('a')[0].onclick = close_infocard;
	
	// Finally display the overlay
	overlay.style.display = "block";

	// Scroll the page back to it's original position
	setTimeout(function() {window.scroll(currLeft, currTop);}, 50);
}


function diashow(tunniste, hakemisto, sivuja) {
	this.sivuja = sivuja;
	this.tunniste = tunniste;
	this.hakemisto = hakemisto;
	this.imgtag = document.getElementById(tunniste);
	
	this.valikko = document.createElement("div");
	this.valikko.style.textAlign = "center";
	this.valikko.style.width = "100%";
	
	var self = this;
	
	this.nappiAlkuun = document.createElement("A");
	this.nappiAlkuun.appendChild(document.createTextNode("« Alkuun"));
	this.nappiAlkuun.onclick = function(){self.alkuun();};
	this.nappiAlkuun.style.cursor = "pointer";
	this.nappiAlkuun.style.margin = "10px";
	this.valikko.appendChild(this.nappiAlkuun);
	
	this.nappiEdellinen = document.createElement("A");
	this.nappiEdellinen.appendChild(document.createTextNode("< Edellinen"));
	this.nappiEdellinen.onclick = function(){self.edellinen();};						
	this.nappiEdellinen.style.cursor = "pointer";
	this.nappiEdellinen.style.margin = "10px";
	this.valikko.appendChild(this.nappiEdellinen);
	
	this.sivunumero = document.createElement("SPAN");
	this.valikko.appendChild(this.sivunumero);
	
	this.nappiSeuraava = document.createElement("A");
	this.nappiSeuraava.appendChild(document.createTextNode("Seuraava >"));
	this.nappiSeuraava.onclick = function(){self.seuraava();};
	this.nappiSeuraava.style.cursor = "pointer";
	this.nappiSeuraava.style.margin = "10px";
	this.valikko.appendChild(this.nappiSeuraava);

	this.nappiLoppuun = document.createElement("A");
	this.nappiLoppuun.appendChild(document.createTextNode("Loppuun »"));
	this.nappiLoppuun.onclick = function(){self.loppuun();};
	this.nappiLoppuun.style.cursor = "pointer";
	this.nappiLoppuun.style.margin = "10px";
	this.valikko.appendChild(this.nappiLoppuun);

	YAHOO.util.Dom.insertAfter(this.valikko, this.imgtag);
	
	this.vaihdasivu = function(nro) {
		if(nro < 1 || nro > this.sivuja) return false;
		this.sivunyt = nro;
		this.imgtag.src = this.hakemisto+"/"+this.tunniste+"_"+(this.sivunyt-1)+".jpg";
		this.sivunumero.innerHTML = "("+this.sivunyt+"/"+this.sivuja+")";
	}
	
	this.alkuun = function() {
		this.vaihdasivu(1);
	}
	
	this.loppuun = function() {
		this.vaihdasivu(this.sivuja);
	}
	
	this.seuraava = function() {
		this.vaihdasivu(this.sivunyt + 1);
	}
	
	this.edellinen = function() {
		this.vaihdasivu(this.sivunyt - 1);
	}
	
	this.vaihdasivu(1);
}

function rekry_open_sektori(checkbox) {
	if(checkbox.checked) {
		checkbox.parentNode.parentNode.parentNode.parentNode.getElementsByTagName('input')[0].checked = true;
	}
}

function rekry_checked(field) {
        var parent = field.parentNode.getElementsByTagName('ul')[0];
        if(field.checked) {
                parent.style.display = 'block';
        } else { 
                var children = parent.getElementsByTagName('li');
                for(var i=0;i<children.length;i++) {
			var childLabel = children[i].getElementsByTagName('label')[0];
			var childInput = childLabel.getElementsByTagName('input')[0];
                        childInput.checked = false;
                }
                parent.style.display = 'none';
        }
}

function rekry_show_description(id, atag, no_open) {
	if(!no_open) {
		var parent = atag.parentNode.getElementsByTagName('ul')[0];
		if(parent.style.display == 'block') {
			parent.style.display = 'none';
		} else {
			parent.style.display = 'block';
		}
	}
        var divtoshow = document.getElementById(id);
        var palsta = document.getElementById('vasenpalsta');
        for(var i=0;i<palsta.childNodes.length;i++) {
                if(palsta.childNodes[i].tagName == 'DIV' && palsta.childNodes[i].id != 'rekrykuvaus') {
                        palsta.childNodes[i].style.display = 'none';
                }
        }
        divtoshow.style.display = 'block';
        return false;
}

function rekry_show_etusivu() {
        var palsta = document.getElementById('vasenpalsta');
        for(var i=0;i<palsta.childNodes.length;i++) {
        	if(palsta.childNodes[i].tagName != 'DIV') continue;
                if(palsta.childNodes[i].id == 'rekrykuvaus' || palsta.childNodes[i].id == 'haehallitukseen' || palsta.childNodes[i].id == 'nainhaethallitukseen') {
                        palsta.childNodes[i].style.display = 'block';
                } else {
                	palsta.childNodes[i].style.display = 'none';
                }
        }
        return false;
}

function rekry_check() {
        var rekrylista = document.getElementById('rekrylista');
        var ok = false;
        for(var i=0;i<rekrylista.childNodes.length;i++) {
                if(rekrylista.childNodes[i].tagName == 'LI') {
                        for(var j=0;j<rekrylista.childNodes[i].childNodes.length;j++) {
                                if(rekrylista.childNodes[i].childNodes[j].tagName == 'INPUT') {
                                        if(rekrylista.childNodes[i].childNodes[j].checked) {
                                                ok = true;
                                                break;
                                        }
                                }
                        }
                }
        }
        if(!ok) {
                alert("Valitse jokin rekryvaihtoehto!");
                return false;
        }
        var nimikentta = document.getElementById('yhteystiedot_nimi');
        var emailkentta = document.getElementById('yhteystiedot_email');
        var puhelinkentta = document.getElementById('yhteystiedot_puhelin');
        var vkvalikko = document.getElementById('yhteystiedot_vuosikurssi');
        if(nimikentta.value.length < 5) {
                alert("Anna koko nimesi.");
                nimikentta.focus();
                return false;
        }
        var emailreg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
        if(emailreg.test(emailkentta.value) == false) {
                alert("Virheellinen sähköpostiosoite.");
                emailkentta.focus();
                return false;
        }
        if(puhelinkentta.value.length < 8) {
                alert("Anna puhelinnumerosi.");
                puhelinkentta.focus();
                return false;
        }
        if(vkvalikko[vkvalikko.selectedIndex].value == 'Valitse') {
                alert("Valitse vuosikurssi.");
                vkvalikko.focus();
                return false;
        }
        return true;
}

// Fade effect

var fadeEffect = function() {
	return {
		init : function(id, flag, target) {
			this.elem = document.getElementById(id);
			clearInterval(this.elem.si);
			this.target = target ? target : flag ? 100 : 0;
			this.flag = flag || -1;
			this.alpha = this.elem.style.opacity ? parseFloat(this.elem.style.opacity) * 100 : 0;
			this.si = setInterval(function(){fadeEffect.tween()}, 20);
		},
		
		tween : function() {
			if (this.alpha == this.target) {
				clearInterval(this.si);
			} else {
				var value = Math.round(this.alpha + ((this.target - this.alpha) * .05)) + (1 * this.flag);
				this.elem.style.opacity = value / 100;
				this.elem.style.filter = 'alpha(opacity=' + value + ')';
				this.alpha = value;
			}
		}
	}
}();
