
/* SOL.js, version 0.9.8 (c) 2008 SOL.dk
/*--------------------------------------------------------------------------*/

/*
 * Set body id and class due to eniro header and template engine not temp. able to change body tag
 */
function eniroBodyFixDueToUncrontrollableTemplateEngine() {
	document.body.id = '';
	document.body.className = 'front dk_da';
}
// Most browsers have 250ms delay before rendering begins. 100 should be good
//setTimeout("eniroBodyFixDueToUncrontrollableTemplateEngine()", 50);

/*
 * Set display mode for an id
 */
function styleDisplay(id, style) {
	document.getElementById(id).style.display = style;
}

/*
 * Set value for an id
 */
function setValue(id, value) {
	document.getElementById(id).value = value;
}

/*
 * Set inner HTML for an id
 */
function setInnerHTML(id, value) {
	document.getElementById(id).innerHTML = value;
}
	
/**
 * Here for compatability
 * 
 * @see #get_c
 */
function getCookie(tmp) {
	return get_c(tmp);
}
function setCookie(name, value, expires, path, domain, secure) {
	return set_c(name, value, expires, path, domain, secure);
}

/**
 * Cookie tester - Test if browser accepts cookies
 * 
 * @return boolean
 */
function cookietest() {
	set_c("cookietest", 'valuehere');
	if (get_c("cookietest")) {
		del_c("cookietest");
		return true;
	}
	del_c("cookietest");
	return false;
}

/**
 * Set cookie
 * 
 * @param {String} name Cookiename
 * @param {String} value Value
 * @param {String} expires Expiry
 * @param {String} path Cookiepath
 * @param {String} domain Cookiedomain
 * @param {String} secure Secure cookie
 * @return void
 */
function set_c(name, value, expires, path, domain, secure) {
	var today = new Date();
	today.setTime(today.getTime());

	if (expires) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date(today.getTime() + (expires));

	document.cookie = name + "=" +escape(value) +
	((expires) ? ";expires=" + expires_date.toGMTString() : "" ) +
	((path) ? ";path=" + path : "" ) +
	((domain) ? ";domain=" + domain : "" ) +
	((secure) ? ";secure" : "" );
}

/**
 * Get raw cookie value
 * 
 * @param {String} name Cookiename
 * @return string
 */
function get_c_raw(name) {
	var valuesRaw = "";
	var theCookie = getCookie(name);
	if(theCookie){
		var first = theCookie.indexOf("=");
		var last = theCookie.length;
		valuesRaw = theCookie.substring(first+1,last);
	}
	return valuesRaw;
}

/**
 * Get cookie value
 * 
 * @param {String} name Cookiename
 * @return string Cookie value
 */
function get_c(name) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ((!start) && (name != document.cookie.substring( 0, name.length ))) {
		return null;
	}
	if ( start == -1 ) {
		return null;
	}
	var end = document.cookie.indexOf(";", len);
	if ( end == -1 ) {
		end = document.cookie.length;
	}
	return unescape( document.cookie.substring(len, end));
}

/**
 * Delete cookie
 * 
 * @param {String} name Cookiename
 * @param {String} path Cookie serverpath
 * @param {String} domain Cookie domain
 * @return void
 */
function del_c(name, path, domain) {
	if ( get_c( name ) ) document.cookie = name + "=" +
	( ( path ) ? ";path=" + path : "") +
	( ( domain ) ? ";domain=" + domain : "" ) +
	";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

/**
 * Add Eniro search engine to Mozilla sidebar
 * Not really sure why this is here..
 * 
 * @param {String} name Search-engine name
 * @param {String} cat Search-engine category
 * @return void
 */
function addEngine(name, cat) {
	if ((typeof(window.sidebar) == "object") && (typeof(window.sidebar.addSearchEngine) == "function")) {
		window.sidebar.addSearchEngine(
			"http://www.eniro.dk/firefox/enirodk.src",
			"http://www.eniro.dk/firefox/enirodk.gif",
			name,
			cat
		);
	}
}

/**
 * Function for string replacing
 * used in this manner:
 * goReplace(this, with that, in this)
 * 
 * @param (String) Regex to be replaced
 * @param (String) String to replace result
 * @param (String) String to do replace in
 * @return string Replaced string
 */
function goReplace(regex, r, src) {
	return (src == null ? '' : src.replace(new RegExp(regex, "mg"), r));
}

/**
 * Login input validator.
 * Is executed upon loginbox click. Will put values to other form
 * to avoid browser-caching and execute 
 * insertPleasewait() after a short timeout
 * 
 * @return boolean
 */
function validateInput(e) {
	if (typeof(e) != "undefined") {
		var code;
		if (!e) var e = window.event;
		if (e.keyCode) code = e.keyCode;
		else if (e.which) code = e.which;
		if (code!="13"){
			return false;
		}
	}
	if (document.login.user_name.value == 'Brugernavn' || document.login.user_name.value == '') {
		new Effect.Pulsate('login_user_name', {duration:2, from:0.3, pulses:3});
		return false;
	}
	else if (document.login.passwd.value == '') {
		new Effect.Pulsate('login_passworddummy', {duration:2, from:0.3, pulses:3});
		new Effect.Pulsate('login_passwd', {duration:2, from:0.3, pulses:3});
		return false;
	}
	
	document.login2.user_name.value = document.login.user_name.value;
	document.login2.passwd.value = document.login.passwd.value;
	document.login2.wanted_url.value = document.login.wanted_url.value;
	document.login2.store_pw.checked = document.login.store_pw.checked;
	if (document.login.store_pw.checked) {
		set_c('store_pw', 'true', 14, '/');
	} else {
		del_c("store_pw", '/');
	}
	new Effect.Fade('loginform');
	setTimeout('insertPleasewait()', 1250);
	
	return false;
}

/**
 * Should be executed by validateInput()
 * 
 * @return void
 */
function insertPleasewait() {
	$('loginbox2').innerHTML = '<div style="text-align: center"><br />Vent venligst mens der logges ind...<br /><img src="http://www.sol.dk/elements/i/indicator.gif" /></div>';
	$('login2').submit();
}

/**
 * Writes out the necessary links for the small 
 * topnavigation login-tabs.
 * 
 * @param (String) referer URL to be redirected back to on login.
 * @return void
 */
function insertLoginTabs(referer) {
	// replace a debate write page (write.cgi$) with nothing to fix a redirection 'bug'
	referer = goReplace('write.cgi$', '', referer);
	referer = goReplace('bruger.sol.dk/logout/', 'www.sol.dk', referer);
	// set wanted_url
	var href = (referer ? '?wanted_url='+ escape(referer) : '');
	
	if (get_c("SOLauth") == null) {
		document.write('<li><a id="loginleft" accesskey="L" href="http://bruger.sol.dk/login/login.fcgi' + href + '" target="_top" title="Log ind" >Log ind</a></li>');
		document.write('<li><a id="loginright" href="http://medlem.sol.dk/" target="_top" title="Bliv medlem og f&aring; alle fordelene">Bliv medlem</a></li>');
	}
	else {
		href = '?wanted_url=http://bruger.sol.dk/logout/';
		document.write('<li><a id="loggedinleft" href="http://bruger.sol.dk/login/logout.fcgi' + href + '" target="_top">Log ud</a>');
		document.write('<li><a id="loggedinright" href="http://medlem.sol.dk/indlogget/" target="_top">Dine tjenester</a>');
	}
}

/**
 * Writes out the necessary text for the small 
 * topnavigation link-box.
 * 
 * @return void
 */
function insertLoginText() {
	if (get_c("SOLauth") == null) {
		document.write ('<a href="http://www.sol.dk/support/drift/" target="_top">Driftstatus</a>');
		document.write (' · ');
		document.write ('<a href="http://www.sol.dk/support/" target="_top">Medlemssupport</a>');
	}
	else {
		var days	= new Array("S&oslash;ndag", "Mandag", "Tirsdag", "Onsdag", "Torsdag", "Fredag", "L&oslash;rdag");
		var months	= new Array("jan.", "feb.", "marts", "april", "maj", "juni", "juli", "aug.", "sep.", "okt.", "nov.", "dec.");
		
		var time	= new Date();
		var lday	= days[time.getDay()];
		var lmonth	= months[time.getMonth()];
		var day		= time.getDate();
		var year	= time.getFullYear();
		
		document.write ('<div id="logindate">');
		document.write (lday + " d. ");
		document.write (day + ". " + lmonth + " " + year);
		//document.write (date + ". " + lmonth);
		document.write ('</div>');
	}
}

/**
 * Writes out the entire (large) loginbox, with shortcuts etc.
 * Function can be applied with three parameters.
 * Note: If only one parameter is applied, it will be used to identify
 * the default loginurl to display. 
 * Note: If two parameters is applied, those will be used as default 
 * loginurl to display.
 * 
 * @param {String} selected Identifying default redirection
 * @param {String} alttext Text for alternate redirect
 * @param {String} alturi Url for alternate redirect.
 * @return void
 */
function insertLogin(selected, alttext, alturi) {
	if (get_c('SOLauth') == null) {
		var redirects = new Array(
								new Array('SOL Forside', 'http://www.sol.dk/'),
								new Array('Dine tjenester', 'http://medlem.sol.dk/indlogget/'),
								new Array('E-mail', 'http://mail.sol.dk'),
								new Array('Debat', 'http://debat.sol.dk'),
								new Array('Profilside', 'http://medlem.sol.dk/indlogget/show_services/show_services.cgi?template=profilepage')
							);
		
		if (alttext && alturi) {
			redirects.push(new Array(alttext, alturi));
		}
		selected = (typeof(selected) == 'undefined' ? '' : selected);
		
		document.write ('<form id="login" method="post" name="login" action="http://bruger.sol.dk/login/dk_login.fcgi">');
		document.write ('<div id="loginform">');
		document.write ('<input type="text" alt="Brugernavn" name="user_name" id="login_user_name" value="Brugernavn" class="formuser" onfocus="if(this.value==\'Brugernavn\')this.value=\'\';" onblur="if(this.value==\'\')this.value=\'Brugernavn\';" onkeydown="validateInput(event);" accesskey="L" />');
		document.write ('<input type="text" alt="Password" name="passworddummy" id="login_passworddummy" value="Password" class="formuser" onfocus="this.form.passworddummy.style.display=\'none\'; this.form.passwd.style.display=\'inline\'; this.form.passwd.focus();" /><input type="password" alt="Password" name="passwd" id="login_passwd" value="" class="formuser" onblur="if(this.value == \'\'){this.form.passwd.style.display=\'none\'; this.form.passworddummy.style.display=\'inline\';}" style="display: none;" onkeydown="validateInput(event);" />');
		document.write ('<select name="wanted_url" class="formselect" onkeydown="validateInput(event);">');
		for (var i=0; i < redirects.length; i++) {
			if (redirects[i][0].toLowerCase() == selected.toLowerCase()) {
				document.write ('<option class="formselectelements" value="' + redirects[i][1] + '" selected="selected">' + redirects[i][0] + '</option>');
			} else {
				document.write ('<option class="formselectelements" value="' + redirects[i][1] + '">' + redirects[i][0] + '</option>');
			}
		}
		document.write ('</select>');
		document.write ('&nbsp;<input type="checkbox" name="store_pw" id="store_pw" onkeydown="validateInput(event);" '+ (get_c('store_pw') ? 'checked="checked" ' : '') +'/>&nbsp;<label for="store_pw" title="Automatisk log-in">Husk mig</label>');
		document.write ('&nbsp;<input type="button" value="Log-in" class="formsubmit" onclick="validateInput();" />');
		document.write ('</div>');
		document.write ('</form>');
	}
	else {
		document.write ('<div id="profile">');
		document.write ('<a http://medlem.sol.dk/indlogget/show_services/show_services.cgi?template=profilepage\';" href="http://medlem.sol.dk/indlogget/show_services/show_services.cgi?template=profilepage"><img id="profileimg" src="/elements/i/prof.gif" width="46" height="46" border="0" align="left" /></a>');
		document.write ('<strong id="profilelinks"><a http://medlem.sol.dk/indlogget/show_services/show_services.cgi?template=profilepage\';" href="http://medlem.sol.dk/indlogget/show_services/show_services.cgi?template=profilepage">Profil</a> | <a href="http://mail.sol.dk/">E-mail</a> | <a href="http://debat.sol.dk/">Debat</a> | <a href="http://medlem.sol.dk/indlogget/">Dine tjenester</a></strong><div id="profilespacer"></div>');
		document.write ('<a href="http://www.sol.dk/support/drift/">Driftstatus</a> | <a href="http://www.sol.dk/support/">Medlemssupport</a>');
		document.write ('</div>');
	}
}

/**
 * Insert tabs from given array at runtime
 * 
 * @param (Array) localtabs Array with according tabinfo
 * @param (String) id Wanted id on containing ul
 * @return void
 */
function insertTabs(localtabs, id) {
	var tmp = '<ul class="tabbox_head"' + (typeof(id) != "undefined" ? ' id="' + id + '"' : '') + '>';
	for (var i = 0; i < localtabs.length; i++) {
		tmp += '<li><a ';
		tmp += 'id="' + localtabs[i][0] + (i + 1) +'" ';
		tmp += (i == 0 ? 'class="sel" ' : '');
		tmp += 'href="javascript:void(0);" ';
		tmp += 'onclick="return focusTab(\'' + localtabs[i][0] + '\', \''+ (i + 1) +'\', \''+ localtabs[i][2] + '\', \'' + (typeof(localtabs[i][3]) == "undefined" ? 0 : localtabs[i][3]) + '\');">';
		tmp += localtabs[i][1];
		tmp += '<\/a><\/li>';
	}
	tmp += '</ul>';
	document.write(tmp);
}

/**
 * Initialise tabs - Set focus on tab based on
 * previous state.
 * 
 * @see #focusTab
 * @param (String) name Cookiename to check for prev. state 
 * @param (Array) localtabs Array with according tabinfo
 * @return void
 */
function initTabs(name, localtabs) {
	var id = 1;
	if (typeof(name) != "undefined" && get_c(name)) {
		id = get_c(name);
		for (var i = 0; i < localtabs.length; i++) {
			if (i == (id - 1)) {
				focusTab(name, id, localtabs[i][2], localtabs[i][3]);
			}
		}
	}
	else {
		focusTab(name, 1, localtabs[0][2], localtabs[0][3]);
	}
}

/**
 * Reset status on all tabs with same 'name'.
 * Load current tab from given url.
 * Set status on selected tab.
 * Start an update process if specified. 
 * Save selection in cookie for later use.
 * 
 * @param {String} id Element to focus
 * @param {Integer} nr Tab number to focus
 * @param {String} url Url to load into tab
 * @param {Integer} reload Interval in Seconds between reload
 * @return boolean False to prevent link for redirecting
 */
var ajaxupdate;
function focusTab(id, nr, href, reload) {
	// reset tabs
	for (i = 1; i < 6; i++) {
		if ($(id + i)) {
			$(id + i).className = "";
		} else {
			break;
		}
	}
	
	// reload tab with new content
	reloadTab(id + 'content', href);
	
	// set selected
	$(id + nr).className = "sel";
	
	
	// clear / set update interval - minimum 5 seconds between reloading
	clearInterval(ajaxupdate);
	if (typeof(reload) != "undefined" && parseInt(reload) > 5) {
		ajaxupdate = setInterval('reloadTab(\''+ id + 'content\', \'' + href + '\')', (parseInt(reload) * 1000));
	}
	
	// set remembering cookie
	set_c (id, nr, 365, '/', '');
	
	return false;
}

/**
 * Reload a tab from given url to given 
 * container id using ajax call.
 * Note: Is only updated on true success.
 * 
 * @param (String) id Container id to update
 * @param (String) href URL to fetch
 * @return void
 */
function reloadTab(id, href) {
	// create unique uri to avoid caching
	href += (href.indexOf('?') != -1 ? '&' : '?') + (((1+Math.random())*0x100000)|0);
	
	document.getElementById(id).innerHTML = '<div style="padding: 10px;">&nbsp;Vent venligst mens siden bliver indl&aelig;st.&nbsp;<img src="http://www.sol.dk/elements/i/indicator.gif" alt="Siden loader..." \/><\/div>';
	
	var tmp = new Ajax.Updater(
		{success: id},
		href,
		{
			asynchronous : true,
			method: 'get'
		}
	);
}

/**
 * Makes an ad slide and sticks that
 * ad to the window (onresize, etc).
 * Note: Only one ad can be used with this at a time!
 * 
 * @param (String) id Id of html container to be controlled
 * @return void
 */
function slideAd(id) {
	if (window.external && !document.getElementById) {
		document.getElementById = function(s) {
			return document.all[s]
		};
	}
	if (!document.getElementById)
		return;
	sb = (document.documentElement && document.documentElement.clientWidth && document.documentElement.clientWidth > 0) ? document.documentElement : document.body;
	se = document.getElementById(id);
	if(sb && se) {
		sr = function() {
			var yOffset = null;
			if (!isNaN(sb.scrollTop))
				yOffset = sb.scrollTop;
			else if(!isNaN(window.pageYOffset))
				yOffset = window.pageYOffset; 
			if(yOffset == null) 
				return;
			var clientWidth = null; 
			if(!isNaN(sb.clientWidth)) 
				clientWidth = sb.clientWidth; 
			else if(!isNaN(window.innerWidth)) 
				clientWidth = window.innerWidth; 
			if (clientWidth == null) 
				return;
			se.style.top = yOffset+(Math.max(0,279-yOffset)-6) + "px"; 
			se.style.left = ((clientWidth-760)/2)+765 + "px"; 
			se.style.visibility = "visible";
		}
		window.onscroll = sr;
	}
	if (window.resizeManager)
		window.resizeManager[id] = "sr()";
	else
		window.onresize = sr; sr();
}

/**
 * Initiates a wallpaper on page
 * Sets global variables: wallpaperImage & wallpaperLink
 * 
 * @param (String) image Image to display at body background
 * @param (String) link Url to redirect to on body click
 * @return void
 */
function initWallpaper(image, link) {
	wallpaperImage = image;
	wallpaperLink = link;
	if (wallpaperImage) {
		document.body.style.backgroundImage = 'url(' + wallpaperImage + ')';
		document.body.style.backgroundRepeat = 'repeat';
		document.body.style.backgroundPosition = 'top center';
		document.body.style.backgroundAttachment = 'fixed';
		document.write('<link rel="stylesheet" href="http://www.sol.dk/elements/css/modules/wallpaper.css" type="text/css" />');
	}
	if (wallpaperLink) {
		document.body.style.cursor = 'pointer';
	}
	document.onclick = wallpaperClick;
}
var wallpaperImage;
var wallpaperLink;

/**
 * Event for onclick at wallpaper
 */
wallpaperClick = function(e) {
	if (wallpaperLink) {
		EE = e ? e:event;
		if (!EE)
			return;
		var t = EE.target ? EE.target : EE.srcElement;
		if (!t || t.tagName != "BODY")
			return;
		var ad = window.open(wallpaperLink);
	}
}

/**
 * Initiates on all pages. Used for themes
 */
function initLogo() {
	_setLogo('Vinter 2010', 'vinter', false, false);
	//_setLogo('Jul på SOL', 'jul', 'http://www.sol.dk/jul/', 'Jul på SOL');
}

/**
 * Sets a custom logo / link on page
 * 
 * @id (String) gives possibility to differentiate themes later on
 * @param (String) image Image to display at body background
 * @param (String) link Url to redirect to on body click
 * @return void
 */
function _setLogo(id, Image, URL, title) {
	container = $('sol-logo');
	
	if (container && Image) {
		var background = 'http://cdn.sol.dk/img/layout/logo/sol_' + Image + '.png';
		if (Image.indexOf(".") != -1) {
			background = Image;	// Input could be a file too
		}
		container.style.background = 'transparent url("' + background + '") no-repeat 0% 0%';
	}
	
	if (container && URL) {
		var link = Builder.node('a', {href: URL, id: 'sol-logo-link' }, ' ');
		link.title = (title ? title : '');	// Title is optional
		container.appendChild(link);
	}
}

/**
 * Changes language for searches in Eniro-bar.
 * 
 * @param (String) webLang Language as a string
 * @return void
 */
function setLang(webLang) {
	var id = webLang.id.replace(/global|lang(Global_bottom|Global)/,"global");
	var id = id.replace(/national|lang(Local_bottom|Local)/,"national");
	var newSettings = get_c_raw("egoSettings");
	
	if (newSettings != "") {
		var regExp = /webLang?(national|global)/;
		newSettings = newSettings.replace(regExp, "webLang?" + id);
	} else {
		newSettings = "webLang?" + id;
	}
	var today = new Date();
	var expire = new Date();
	expire.setTime(today.getTime() + 3600000*24*1000);
	set_c('egoSettings', newSettings, expire, '/', -1, '');
}

/**
 * Toogle box
 */
function toogleBox(id, method) {
	method = (typeof(method) == "undefined" ? 'blind' : method);
	Effect.toggle(id, 'blind',
	{
		duration: 1
	});
}

var pp_gemius_identifier;	// Gemius container
var tmsec;					// TNS Metrix container
