/**
 * Javascript functions for the KTH website.
 *
 * $Source$
 *
 * $Revision$
 *
 * Last modified: $Date$
 *
 * by $Author$
 *
 * Copyright (C) 2006 Kungl Tekniska H?gskolan
 * All rights reserved.
 */

/**
 * Set this to false if you dont want debug
 * info to be shown. Only works in Firefox.
 */
var DEBUG = false;

/**
 *
 * Method that is run when a page is loaded.
 */
function loadPage( ){	
	
	enterFunction( loadPage );
		
	exitFunction( loadPage );
	
} 

/**
 *
 * Method that is run when a page is unloaded.
 */
function unloadPage( ){	

	enterFunction( unloadPage );
	
	debugCleanUp( );
	
	exitFunction( unloadPage );
} 


/**
 *
 * Redirect to the selected link in the form.
 * Used in quickie.
 */
function redirectLinkSelect( form ){

	enterFunction( redirectLinkSelect );
	
	var link = getSelectedValue( form.linkSelect );
	
	debug( "Link is: '" + link + "'" ); 

	redirect( link );
		
	exitFunction( redirectLinkSelect );

}

/**
 *
 * Redirect the current window to a url.
 */
function redirect( url ) {

	debug( "Redirecting current window to: '"  + url + "'." );
	 
	window.location.href = url;

}


/**
 *
 * Get the selected value from an html select box.
 */
function getSelectedValue( select ){

    return select.options[ select.options.selectedIndex ].value;
    
}

/**
 *
 * In Cortina an external link is an complete URL.
 */
function isExternalLink( value ){

	debug( "Value '" + value + "' is ExternalLink : " + isUrl( value ) );
	return isUrl( value );
	
}

/**
 * 
 * Is the passed value an URL, ie contains "http".
 */
function isUrl( value ) {

	if ( value == null){
		
		return false;
		
	}
	
	if( value.length < 5 ){
	
		return false;
		
	} 

	if( value.indexOf( "http" ) > -1 ){
	
		return true;
	
	}
	
	return false;
	
} 

/**
 * Open a new window
 *
 */
function openHelpWindow( url ){

	var newWindow2 = window.open(url,'mywindow','resizable=yes,width=300,height=200,scrollbars=yes,status=no');
	newWindow2.focus( );
	
}

/**
 * Open a new window
 *
 */
function openNewWindow( url ){

	var newWindow = open( url );

}

/**
 *
 * Submits the education choice on the studentwebsite.
 * Later to be used for selecting content in the navigation.
 *
 * NOTE! This method uses an form by the name "rs" (Rember Selection)
 * that has to be present in the page to work. 
 */
function submitEducationChoice( form ){

	enterFunction( submitEducationChoice );
	
	form.rs.value = ( document.rsForm.rs.checked ) ? 'true' : 'false';

	exitFunction( submitEducationChoice );

    return true;
    
}

function help( title, message, language ){

	enterFunction( help );

	var url = '/script/help-www.jsp?t=' + title + '&m=' + message + '&l='+ language;

	debug( "URL: " + url );
	openHelpWindow( url );

	exitFunction( help );	

}

/**
 * Get element by id wrapping browser incompability. 
 * Overloads the document.getElementById
 */
function getElementById(id) {

	if (!document.getElementById){
		if (document.all) {
			document.getElementById = function() {
				
				if (typeof document.all[id] != "undefined") {
					return document.all[id];
				} else {
					return null;
				}
			}

		} else if (document.layers) {			
			document.getElementById = function(){
				if (typeof document[id] != "undefined") {
					return document[id];
				} else {
					return null;
				}
			}
		}
	}
	
	return document.getElementById(id);
}

/**
 * Gets the current browser.
 */
function getBrowser(){
	return navigator.appName
}

/**
 * Gets the browser version as int.
 */
function getBrowserVersion() {

	var result = -1;
	var version = navigator.appVersion;
	
	if (version != null) {
		result = parseInt(version);
	}
	
	return result; 
	
}

/**
 * Set up method for page load.
 */
function setup() {

	enterFunction(setup);
	
	if (isIE7()) {
		columnHeights();
  	}
  	
  	exitFunction(setup);
  	
  	

}
function toogle(id) {
	var element = getElementById(id);
	if (isDisplaying(element)) {		
		element.style.display = 'none';
	} else {
		element.style.display = 'block';
	}
}

function isDisplaying(element){
	if (element == null) {
		return false;
	}
	
	if (element.style.display == null) {
		return true;
	}

	if (element.style.display == "") {
		return true;
	}

	if (element.style.display.toLowerCase() == 'block') {
		return true;
	}
	
	return false;

}


/* -------------------------------------------------------------------- */

var SHADE_SPEED_MS = 60;
 
function hover(id) {
	enterFunction(hover);
	up(id, null, 4, null); 
	exitFunction(hover);
}

function up (id, hex, offset,  index) {
	
	enterFunction(up);

	debug("id", id);
	debug("hex", hex);
	debug("offset", offset);
	debug("index", index);
	
	
	var element = getElementById(id);
	var rgb = null;

	if (hex == null) {
		rgb = getBackgroundColor(id);
	} else {
		var hexadecimal = new Hexadecimal(hex);
		rgb = hexadecimal.toRGB();
	}
	
	if (offset == null) {
		offset = 10;
	}
	
	if (index == null) {
		index = 0;
	}
	
	rgb.brighten();
		
	element.style.background = rgb.toHexadecimal();

	if (parseInt(offset) > parseInt(index)) {
		debugValue("setTimeout method call", "up('" + id + "', '" + rgb.toHexadecimal() + "', "  + offset + ", " + index++ + ")");
		setTimeout("up('" + id + "', '" + rgb.toHexadecimal() + "', "  + offset + ", " + index++ + ")", SHADE_SPEED_MS);	
	} else {
		down(id, hex, offset, null);
	}
	debugValue("Background", element.style.background);
		
	exitFunction(up);
}

function down (id, hex, offset,  index) {
	
	enterFunction(up);

	infoValue("index", index);
	debugValue("id", id);
	debugValue("hex", hex);
	debugValue("offset", offset);
	debugValue("index", index);
	
	
	var element = getElementById(id);
	var rgb = null;

	if (hex == null) {
		rgb = getBackgroundColor(id);
	} else {
		var hexadecimal = new Hexadecimal(hex);
		rgb = hexadecimal.toRGB();
	}
	
	if (offset == null) {
		offset = 10;
	}
	
	if (index == null) {
		index = 0;
	}
		
	rgb.darken();
		
	element.style.background = rgb.toHexadecimal();

	if (parseInt(offset) > parseInt(index)) {
		debugValue("setTimeout method call", "up('" + id + "', '" + rgb.toHexadecimal() + "', "  + offset + ", " + index++ + ")");
		setTimeout("down('" + id + "', '" + rgb.toHexadecimal() + "', "  + offset + ", " + index++ + ")", SHADE_SPEED_MS);	
	} 
	debugValue("Background", element.style.background);
	
	exitFunction(up);
}

function getBackgroundColor(id) {
	return new RGB(193,193,193);
}


/**
 * STATIC STRING REPRESENTING HEX VALUES.
 */
var HEXADECIMALS = "0123456789ABCDEF";

/**
 * Takes a hexadecimal rgb value like #c345a4.
 * Case insensitive.
 */
function Hexadecimal(hexadecimal){
	
	this.hexadecimal = hexadecimal;
	
	this.toRGB = toRGB;
	this.toString = toString;
	this.getValue = getValue;
	
	function toString() {
		return this.hexadecimal;
	}
	
	function getValue() {
		return this.hexadecimal;
	}
	
	function toRGB(){
		enterFunction(toRGB);
		var result = null;
		var hexValue = this.hexadecimal;
		if (hexValue.charAt(0) == "#") {
			debug("Striping value of '#'.");
			hexValue = hexValue.slice(1);
		}
		hexValue = hexValue.toUpperCase();
		
		var rgb = new Array(3);
		var index = 0;
 
		var first, second;
	 
		for (var i = 0; i < 6; i += 2) {
			first = HEXADECIMALS.indexOf(hexValue.charAt(i));
			second = HEXADECIMALS.indexOf(hexValue.charAt(i+1)); 
			rgb[index] = (first * 16) + second;
			index++;
		}

		exitFunction(toRGB);

		return new RGB(rgb[0], rgb[1], rgb[2]);		
	}
}

/**
 * Takes three numeric rbg values. like "234, 12, 3".
 */
function RGB(red, green, blue) {

	this.red = red;
	this.green = green;
	this.blue = blue;
		
	this.toHexadecimal = toHexadecimal;
	this.getRed = getRed;
	this.getGreen = getGreen;
	this.getBlue = getBlue;	
	this.brighten = brighten;
	this.darken = darken;			
	this.toString = toString;
	this.getValue = getValue;
	
	function toString() {
		return "rgb(" + this.getRed() + "," + this.getGreen() + "," + this.getBlue() + ")";
	}
	
	function getValue() {
		return "rgb(" + this.getRed() + "," + this.getGreen() + "," + this.getBlue() + ")";
	}
	
	function toHexadecimal(){	
		
		enterFunction(toHexadecimal);

		var result = "#";
		
		result += getHexadecimalValue(this.red);
		result += getHexadecimalValue(this.green);
		result += getHexadecimalValue(this.blue);
		
		exitFunction(toHexadecimal);
		
		return result;
	
	}
	
	function getRed(){
		return this.red;
	}

	function getGreen(){
		return this.green;
	}

	function getBlue(){
		return this.blue;
	}

	function getHexadecimalValue(color){
		enterFunction(getHexadecimalValue);
		debugValue("Color", color);		
		var first = color / 16;
		var second = color % 16;
				
		var result = HEXADECIMALS.charAt(first);
		result += HEXADECIMALS.charAt(second);
	
		debugValue("Hex", result);		
	
		exitFunction(getHexadecimalValue);	
		return result;
	}
	
	function brighten() {
		this.red += 1;
		this.green += 1;
		this.blue += 1;
	}
	
	function darken() {
		this.red -= 1;
		this.green -= 1;
		this.blue -= 1;
	}
}
/* -------------------------------------------------------------------- */


//********************************************************************************************
//*********************************** DEBUG **************************************************
//********************************************************************************************
//********************************************************************************************
//************ To turn on debugging change var DEBUG_LEVEL at bottom of page *****************
//********************************************************************************************
//********************************************************************************************



/**
 * Debug info to use when entering a function .
 */
function enterFunction( method ){

	if( !isDebugMode( ) ){
		return;
	}
	
	debug( "<p  style='color:gray'>DEBUG: <strong>Entering function:</strong> " + method.name + "</p>");

}

/**
 * Debug info to use when entering a function .
 */
function exitFunction( method ){

	if (!isDebugMode()) {
		return;
	}
	
	debug( "<p  style='color:gray'>DEBUG: <strong>Exiting function:</strong> " + method.name + "</p>");

}


/**
 * Simple debug method for FireFox.
 */
function debug(message){
	
	if (isDebugMode()) {
		
		var display = getDebugView( ).document;
		
		display.write( "<p  style='color:gray'>DEBUG: " + message + "<p>" );		
		
	}
	
}

function info(message){
	
	if (isInfoMode()) {
		
		var display = getDebugView( ).document;
		
		display.write( "<p  style='color:green'>INFO: " + message + "<p>" );		
		
	}
	
}



function warning(message){
	
	if (isWarningMode()) {
		
		var display = getDebugView( ).document;
		
		display.write( "<p  style='color:orange'>WARNING: " + message + "<p>" );		
		
	}
	
}

function fatal(message){
	
	if (isWarningMode()) {
		
		var display = getDebugView( ).document;
		
		display.write( "<p  style='color:black; background-color: red;'>FATAL: " + message + "<p>" );		
		
	}
	
}

/**
 * Simple debug method for FireFox.
 */
function debugValue(label, value){
	
	if (isDebugMode()) {
		
		var display = getDebugView( ).document;
		
		display.write( "<p style='color:gray'>DEBUG: <strong>" + label + "</strong> '" + value + "'<p>" );		
		
	}
	
}

function infoValue(label, value){
	
	if (isInfoMode()) {
		
		var display = getDebugView( ).document;
		
		display.write( "<p style='color:green'>INFO: <strong>" + label + "</strong> '" + value + "'<p>" );		
		
	}
	
}

function warningValue(label, value){
	
	if (isWarningMode()) {
		
		var display = getDebugView( ).document;
		
		display.write( "<p style='color:orange'>WARNING: <strong>" + label + "</strong> '" + value + "'<p>" );		
		
	}
	
}



function fatalValue(label, value){
	
	if (isFatalMode()) {
		
		var display = getDebugView( ).document;
		
		display.write( "<p style='color:black; background-color: red;'>FATAL: <strong>" + label + "</strong> '" + value + "'<p>" );		
		
	}
	
}

/**
 * Get the view to display debug messages in. Normally a window.
 */
var debugView;

function getDebugView( ){

	if (debugView == null){
		debugView = open( 'debug_window', window, 'resizable=yes,width=400,height=250,scrollbars=yes' );
	}
	
	return debugView;
	
}

function debugCleanUp( ){ 

	if( debugView != null ){
		getDebugView( ).close( );
		debugView = null;
	}
	
}

/**
 * 
 * Is this javascript set in debug mode.
 * Normally this is set in DEBUG varible.  
 */

var NO_LOGGING = 100;
var DEBUG = 1;
var INFO = 2;
var WARNING = 3;
var FATAL = 4;

function isDebugMode( ){	
	return DEBUG >= DEBUG_LEVEL;
}

function isInfoMode( ){
	return INFO >= DEBUG_LEVEL;
}

function isWarningMode( ){
	return WARNING >= DEBUG_LEVEL;
}

function isFatalMode( ){
	return FATAL >= DEBUG_LEVEL;
}


/**
 * Set this to false if you dont want debug
 * info to be shown. Only works in Firefox.
 */
var DEBUG_LEVEL = DEBUG_LEVEL;

/**
 * SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
if(typeof deconcept=="undefined"){var deconcept=new Object();}if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"detectflash";this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params=new Object();this.variables=new Object();this.attributes=new Array();if(_1){this.setAttribute("swf",_1);}if(id){this.setAttribute("id",id);}if(w){this.setAttribute("width",w);}if(h){this.setAttribute("height",h);}if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},setAttribute:function(_e,_f){this.attributes[_e]=_f;},getAttribute:function(_10){return this.attributes[_10];},addParam:function(_11,_12){this.params[_11]=_12;},getParams:function(){return this.params;},addVariable:function(_13,_14){this.variables[_13]=_14;},getVariable:function(_15){return this.variables[_15];},getVariables:function(){return this.variables;},getVariablePairs:function(){var _16=new Array();var key;var _18=this.getVariables();for(key in _18){_16[_16.length]=key+"="+_18[key];}return _16;},getSWFHTML:function(){var _19="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute("swf",this.xiSWFPath);}_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\"";_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";var _1a=this.getParams();for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}var _1c=this.getVariablePairs().join("&");if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute("swf",this.xiSWFPath);}_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\">";_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";var _1d=this.getParams();for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}var _1f=this.getVariablePairs().join("&");if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}return _19;},write:function(_20){if(this.getAttribute("useExpressInstall")){var _21=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){this.setAttribute("doExpressInstall",true);this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){var n=(typeof _20=="string")?document.getElementById(_20):_20;n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}return false;}};deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}}return _23;};deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major){return false;}if(this.major>fv.major){return true;}if(this.minor<fv.minor){return false;}if(this.minor>fv.minor){return true;}if(this.rev<fv.rev){return false;}return true;};deconcept.util={getRequestParameter:function(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return "";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;