/* Globala variabler *******************************************************************************************************/

var elevatorDiv, elevatorDownLimit, elevatorUpLimit; var elevatorUpIeLimit = 0; var elevatorDelay = 1;

/* Körs när DOM laddats klart *******************************************************************************************************/
function localDomLoaded() {

//Lägg till Trade Doubler info
document.getElementsByTagName('head')[0].appendChild(document.createTextNode("\n<!-- TradeDoubler site verification 1680096 -->\n"));

//Faux.js
scanColumns.init();

//Kolla om det finns någon fokus-kampanj, isåfall gör rätt anrop (se mer info om vilka parametrar som är tilåtna längre ner)
//if( document.getElementById('focusAdLeft') ) { activateFocusEffect('left',200,900,33,0,getScrollY()); }

//#5413: ModalWindow öppnas inte i IE8 (finns redan uppladdad i Polopoly av Adeprimo, onödigt med dubbelanrop)
//ModalWindow.flashiframefix = function(e){ return; };

//Stäng av den grå hover-fyrkanten för att poppa upp bildtext (fungerar ej, se annan lösning nedan)
//var disabledFeatures = ['ImageCaption'];

//Döper om H2.structural till rätt avdelning. Loopar igenom H2. *fredrik*
var newstr = 'Nyheter';
for(var x=0, ln0 = document.getElementsByTagName("h1").length; x<ln0; x++) {
	if( document.getElementsByTagName("h1")[x].className == 'structural') { 
		newstr = document.getElementsByTagName("h1")[x].innerHTML;
		break;
	}
}
for(var x=0, ln0 = document.getElementsByTagName("h2").length; x<ln0; x++) {
	if( document.getElementsByTagName("h2")[x].className == 'structural') { 
		document.getElementsByTagName("h2")[x].innerHTML = newstr;
		break;
	}
}


//Loopa igenom divar
for(var x=0, ln0 = document.getElementsByTagName("div").length; x<ln0; x++)
{
	if( document.getElementsByTagName("div")[x].className == 'row' && document.getElementsByTagName("div")[x].innerHTML.match(/&amp;/gi) )
	{
		//Ersätta konstiga tecken i TT-artiklarna
		var str = document.getElementsByTagName("div")[x].innerHTML;
		str = str.replace(/&amp;#xD;/gi,'<br />');
		str = str.replace(/&amp;#x0096;/gi,'-');
		str = str.replace(/–/gi,'-');
		document.getElementsByTagName("div")[x].innerHTML = str;
	}
	else if( document.getElementsByTagName("div")[x].id == 'articleContent' && document.getElementsByTagName("div")[x].innerHTML.match(/&amp;/gi) )
	{
		//Ersätta konstiga tecken i TT-artiklarna
		var str = document.getElementsByTagName("div")[x].innerHTML;
		str = str.replace(/&amp;#xD;/gi,'<br />');
		str = str.replace(/&amp;#x0096;/gi,'-');
		str = str.replace(/–/gi,'-');
		document.getElementsByTagName("div")[x].innerHTML = str;
	}
	else if( document.getElementsByTagName("div")[x].className.match(/review/gi) )
	{
		//Stajla om recensioner
		var review = document.getElementsByTagName("div")[x];
		var headlineContainer = h3Node = "null";
		for(var y=0, ln1 = review.getElementsByTagName("div").length; y<ln1; y++)
		{
			if( review.getElementsByTagName("div")[y].className.match(/headlineContainer/gi) ) { headlineContainer = review.getElementsByTagName("div")[y]; }
			else if( review.getElementsByTagName("div")[y].className.match(/bodyContainer/gi) )
			{
				var bodyContainer = review.getElementsByTagName("div")[y];
				if( bodyContainer.getElementsByTagName('h3')[0].className.match(/header_bodyContainer/gi) ) { h3Node = bodyContainer.getElementsByTagName('h3')[0]; }
				if( headlineContainer != 'null' && h3Node != 'null' )
				{	
					headlineContainer.insertBefore(h3Node,headlineContainer.getElementsByTagName('div')[0]);
					if( bodyContainer.getElementsByTagName('p')[0].className.match(/articlePreamble/gi) ) {
						headlineContainer.insertBefore(bodyContainer.getElementsByTagName('p')[0],headlineContainer.getElementsByTagName('div')[0]);
					}
				}
				break;
			}
		}
		review.style.display = "block";
	}
	else if( document.getElementsByTagName('div')[x].id.match(/articleContainer/g) ) {
		var par = document.getElementsByTagName('div')[x];
		for(var j=0, ln2=par.getElementsByTagName('div').length; j<ln2; j++)
		{
			if( par.getElementsByTagName('div')[j].className.match(/photoAlbumContainer/g) ) {
				var ch = par.getElementsByTagName('div')[j];
				ch.innerHTML = ch.innerHTML.replace("<h3>",""); ch.innerHTML = ch.innerHTML.replace("</h3>","");
				ch.getElementsByTagName('span')[0].className = 'label';
				ch.getElementsByTagName('em')[0].innerHTML = 'Bildextra';
				ch.getElementsByTagName('span')[0].style.display = 'block';
				break;
			}
		}
	}
	else if( document.getElementsByTagName('div')[x].className == 'imageCaptionIcon' ) {
		//Stäng av den grå hover-fyrkanten för att poppa upp bildtext
		var n = document.getElementsByTagName('div')[x]; var par = n.parentNode;
		if( par.className == 'imageWrapper' ) { n.style.display = 'none'; }
	}
	else if( document.getElementsByTagName('div')[x].className.match(/adElevator/g) ) {
		//Kolla om det finns någon annons på hiss-annonsens position
		if( document.getElementsByTagName('div')[x].innerHTML.match(/zoneid=26/g) ) {
			elevatorDiv = document.getElementsByTagName('div')[x];
			beginElevator();
		}
	}
}

//Loopa igenom iframes och ta bort frameborder
/*for(var x=0, ln0 = document.getElementsByTagName("iframe").length; x<ln0; x++) {
	if( document.getElementsByTagName("iframe")[x].frameBorder != 0 || document.getElementsByTagName("iframe")[x].frameBorder != "0" ) {
		document.getElementsByTagName("iframe")[x].frameBorder = "0";
	}
}*/
}


/* Funktioner **************************************************************************************************/

//Funktion som döper krönikören / bloggaren i huvudet till rätt namn
function createAuthor(cName) {
	var arr = cName.split("_"); var name = arr[0].replace(" ","");
	var author = document.createElement('div');
	author.className = 'opinionAuthor';
	if( document.getElementById(name) ) author.innerHTML = document.getElementById(name).innerHTML;
	else author.innerHTML = "Ny skribent";
	return author;
}

//Funktion som Jonas anropar från swf-filen för att scrolla till viss punkt (används i himmelsannonsen)
function scrollToFunction() { scrollTo(scrollX,scrollY); }

//Popup-funktioner
function vvpopper () { window.open ("http://2.st.nu/banners/vv/index.html","vvwindow","location=0,status=0,scrollbars=0,width=800,height=645,resizable=0"); return; }
function tnpopper () { window.open ("http://2.st.nu/banners/toyotanytt/index.html?fromST=1","tnwindow","location=0,status=0,scrollbars=0,width=800,height=645,resizable=0"); return; }
function Lyssna_Live(url) { var day = new Date(); var id = day.getTime();
eval("page" + id + " = window.open(url, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=300,height=450,left=25,top=25');"); }

//Plugga tom OpenX annons
function oxPlugg(zid) {
	var par = a_pluggNoder[zid].parentNode;
	par.insertBefore(document.getElementById('plugg_'+zid),a_pluggNoder[zid]);
	par.removeChild(a_pluggNoder[zid]);
}

//Ta reda på skärmhöjd och bredd
function getClientHeight() { return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientHeight:document.body.clientHeight; }
function getClientWidth() { return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientWidth:document.body.clientWidth; }

//Ta reda på scrollbarens y-position
function getScrollY() {
  var scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) { scrOfY = window.pageYOffset; }
  else if( document.body && document.body.scrollTop ) { scrOfY = document.body.scrollTop; }
  else if( document.documentElement && document.documentElement.scrollTop ) { scrOfY = document.documentElement.scrollTop; }
  return scrOfY;
}

//Returnerar värdet på den parameter i URL:en vars namn vi skickar in
function getUrlParam(pn){
	var strReturn = ""; var strHref = window.location.href;
	if( strHref.indexOf("?") > -1 ) {
		var strQueryString = strHref.substr(strHref.indexOf("?"));
		var aQueryString = strQueryString.split("&");
		for( var iParam = 0; iParam < aQueryString.length; iParam++ ){
			if( aQueryString[iParam].indexOf(pn + "=") > -1 ){
				var aParam = aQueryString[iParam].split("=");
				strReturn = aParam[1];
				break;
			}
    	}
  	}
	return unescape(strReturn);
}

//Funktion som positionerar ut fokus-effekten. Får den ett giltigt värde på variabeln plac så centreras fokus-effekten
//inom namngiven spalt. Det går även att skicka in specifik x- eller y-pos.
//Slutligen går det även att skicka in id för en nod som posX, då kommer denna nods offsetLeft bli posX.
function activateFocusEffect(plac,adWidth,adHeight,zoneid,posX,posY) {
	if( plac ) {
		switch( plac ) {
			case "top":
			case "page":
			var sWidth = 990; break;
			case "left": var sWidth = 482; break;
			case "right": var sWidth = (783+482+8); break;
			case "ad": var sWidth = (783+482+294+21+200); break;
			default: var sWidth = 0; break;
		}
		if( sWidth > 0 ) { var posX = ((getClientWidth() - 990)/2) + ((sWidth - adWidth)/2); }
	}
	else if( posX ) {
		if( !(toString(posX)).match(/[^0-9]/gi) ) var posX = document.getElementById(posX).offsetLeft;
	}
	
	if( posX ) {
		document.write("<div id='special_"+zoneid+"' class='specialAdFocus'>\n"+OA_output[zoneid]+"\n</div>");
		if( document.getElementById('special_'+zoneid) ) {
			var div = document.getElementById('special_'+zoneid);
			div.style.display = 'block';
			div.style.width = adWidth+'px'; div.style.height = adHeight+'px';
			div.style.left = posX+'px';
			if( posY ) div.style.top = posY+'px';
			var p = document.getElementById('mainWrapper');
			p.insertBefore(div,p.getElementsByTagName('div')[0]);
		}
	}
}

function closeFocusAd() {
	if( document.getElementById('focusAdLeft') ) { document.getElementById('focusAdLeft').style.display = 'none'; }	
}

//Start på Funktioner för elevator
function animateElevator(dir,offset) {
	if( !elevatorDelay && getScrollY() > 300 ) {
		var tp = parseInt(elevatorDiv.style.top.replace(/[^0-9]/gi));
		if( !isVisible('t') || !isVisible('b') ) {
			if( dir == 'd' && (elevatorDownLimit-20) > (elevatorDiv.offsetTop+elevatorDiv.offsetHeight) ) {
				if( tp < offset ) { elevatorDiv.style.top = (tp+10)+'px'; }
				if( tp+10 < offset ) setTimeout("animateElevator('"+dir+"','"+offset+"')",100);
			}
			else if( dir == 'u' && (elevatorUpLimit+10) < elevatorDiv.offsetTop ) {
				if( tp < offset ) { elevatorDiv.style.top = (tp-10)+'px'; }
				if( tp-10 < offset ) setTimeout("animateElevator('"+dir+"','"+offset+"')",100);
			}
		}
	}
	else { elevatorDelay = 0; setTimeout("animateElevator('"+dir+"','"+offset+"')",1000); }
}
function beginElevator() {
	if( elevatorDiv.getElementsByTagName('div')[0].className == 'advertising' ) { var str = elevatorDiv.getElementsByTagName('div')[0].innerHTML; elevatorDiv.innerHTML = str; }
	elevatorDownLimit = document.getElementById('mainBottom').offsetTop;
	elevatorUpLimit = elevatorDiv.offsetTop;
	elevatorDiv.marginTop = '10px';
	elevatorDiv.style.position='absolute';
	elevatorDiv.style.top = elevatorDiv.offsetTop+'px';
	elevatorLeft();
	if( window.addEventListener ) { window.addEventListener("scroll", moveElevator, false); }
	else if (window.attachEvent) { window.attachEvent("onscroll", moveElevator); }
	else if (document.getElementById) { window.onscroll=moveElevator; }
	if( window.addEventListener ) { window.addEventListener("resize", elevatorLeft, false); }
	else if (window.attachEvent) { window.attachEvent("onresize", elevatorLeft); }
	else if (document.getElementById) { window.onresize=elevatorLeft; }
}
function elevatorLeft() { if( elevatorDiv ) { elevatorDiv.style.left = (document.getElementById('mainWrapper').offsetLeft+790) + 'px'; } }
function isVisible(edge) {
	if( edge == 't' ) return ((elevatorDiv.offsetTop-getScrollY()) <= getClientHeight()) ? ( (getScrollY() >= elevatorDiv.offsetTop) ? false : true ) : false;
	else if( edge == 'b' )	
		return (((elevatorDiv.offsetTop+elevatorDiv.offsetHeight)-getScrollY()) <= getClientHeight()) ? ( (getScrollY() >= (elevatorDiv.offsetTop+elevatorDiv.offsetHeight)) ? false : true ) : false;
}
function moveElevator() {
	elevatorDelay = 1;
	var sY = getScrollY(); var cH = getClientHeight(); var fT = document.getElementById('mainBottom').offsetTop;
	if( sY < 300 ){	
		if( navigator.appName == 'Microsoft Internet Explorer' && document.getElementById('topjobsContainer') ) {
			//Kompensera för TopJobs i IE
			if( elevatorUpIeLimit == 0 ) {
				var tpc = document.getElementById('topjobsContainer'); var tp=0;
				for(var i=0, ln=document.getElementsByTagName('div').length; i<ln; i++) {
					if( document.getElementsByTagName('div')[i].className == 'lokus_topjobs') { tp = document.getElementsByTagName('div')[i].offsetTop; break; }
				}
				var tpch = (tpc.offsetHeight < 20 || !tpc.offsetHeight) ? 40 : (tpc.offsetHeight);
				elevatorUpIeLimit = tp + tpch + 27 + 27 +(tpch*2.1) + 200;
				elevatorUpLimit = elevatorUpIeLimit;
			}
		}
		elevatorDiv.style.top = (elevatorUpLimit+10)+'px';
	}
	else if( (sY+cH) >= fT ) { elevatorDiv.style.top = (elevatorDownLimit - (elevatorDiv.offsetHeight+20))+'px'; }
	else {
		var top = isVisible('t'); var bottom = isVisible('b'); var dir = '';
		if( !top && bottom && elevatorDownLimit > (elevatorDiv.offsetTop+elevatorDiv.offsetHeight) ) { dir = 'd'; }
		else if( !bottom && top ) { dir = 'u'; }
		else if( !bottom && !top && elevatorUpLimit < (elevatorDiv.offsetTop-20) ) { elevatorDiv.style.top = sY+'px'; dir = '';  }
		if( dir ) { animateElevator(dir,(elevatorUpLimit + sY)); }
	}
}
//Slut på Funktioner för elevator

//Extra funktionalitet för modalfönstret
if(typeof ModalWindow != 'undefined'){
    ModalWindow.time = {
        delay : 210, // how long to show loader before quiting
        durationShrink : 0.8, // how long the window shrink time is
        // overlay fade in and out
        durationOverlay : 0.3, 
        fpsOverlay : 20,
        // loader fade in and out
        durationLoader : 0.8, 
        fpsLoader : 20
    }
}

//JSON-funktionalitet
JSONscriptRequest.scriptCounter = 1;
function JSONscriptRequest(fullUrl) {
    this.fullUrl = fullUrl; 
    this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
    this.headLoc = document.getElementsByTagName("head").item(0);
    this.scriptId = 'YJscriptId' + JSONscriptRequest.scriptCounter++;
}

JSONscriptRequest.prototype.buildScriptTag = function () {
    this.scriptObj = document.createElement("script");
    this.scriptObj.setAttribute("type", "text/javascript");
    this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
    this.scriptObj.setAttribute("id", this.scriptId);
}
JSONscriptRequest.prototype.removeScriptTag = function () { this.headLoc.removeChild(this.scriptObj);   }
JSONscriptRequest.prototype.addScriptTag = function () { this.headLoc.appendChild(this.scriptObj); }

//Faux.js (jämna ut kolumner som ligger jämsides med vitt så de ser lika höga ut) 
var scanColumns = { 
  init: function() { 
	if(this.exists()) this.install();
  },
  exists: function() { 
    return $$('div.pageBlockContainer').length > 0;
  },
  install: function(attempt) { 
	if ($$('div.pageBlockContainer').length < 1) {
      attempt = attempt ? attempt + 1 : 1;
      if (attempt < 10) window.setTimeout(this.install, 100, attempt);
      return;
    } 
	$$('div.pageBlockContainer').each(function(container) {
		var arr = container.className.split(" ");
		for(var i=0, ln=arr.length; i<ln; i++) { if( arr[i].match(/[0-9]/gi) ) { arr[i] = "faux"+arr[i]; break; } }
		container.className = arr.join(" ");
	});
  }
}

//Bloguser.js
var a_blogs = new Array();
var a_blogPosts = new Array();
function blog(ob) {
	this.makeDiv = function() {
		var container = document.createElement('div');
		for(var i=0, ln=this.blogPosts.length; i<ln; i++) {
			container.appendChild(this.blogPosts[i].makePost(false));
		}
		makeBlogTeaserDiv(container,this.parentId);
	}
	this.dbId = ob.dbId;
	this.blogPosts = Array();
	this.alias = ob.alias;
	this.parentId = ob.parentId;
	for(var i=0, ln=ob.blogPosts.length; i<ln; i++) { this.blogPosts[i] = new blogPost(ob.blogPosts[i]); }
	this.makeDiv();
}
function blogPost(ob) {
	this.url = ob.url;
	this.topic = ob.topic;
	this.posted = ob.posted;
	this.alias = ob.alias;
	this.authorId = ob.authorId;
	this.makePost = function(showAlias) {
		var container = document.createElement('div');
		container.className = 'row';
		var spanDiv = document.createElement('span');
		spanDiv.className = 'articleDate';
		spanDiv.appendChild(document.createTextNode(this.posted));
		var linkDiv = document.createElement('div');
		linkDiv.className = 'linkDiv';
		var aLink = document.createElement('a');
		aLink.href = this.url;
		aLink.target = '_blank';
		aLink.innerHTML = this.topic;
		if( showAlias ){
			var authorDiv = document.createElement('i');
			authorDiv.className = 'author';
			authorDiv.innerHTML += '&nbsp;- '+makeReadable(this.alias.replace(/\//gi,""))+'';
		}
		var clearer = document.createElement('div');
		clearer.className = 'clearer';
		linkDiv.appendChild(aLink);
		if( showAlias && authorDiv ) linkDiv.appendChild(authorDiv);
		container.appendChild(spanDiv);
		container.appendChild(linkDiv);
		container.appendChild(clearer);
		return container;
	}
}
function getBlog(alias,numPosts,insertionId) {
	if( alias.length > 0 && numPosts > 0 && document.getElementById(insertionId) ) {
		var url = "";
		if( alias == "senaste" ) { url = 'http://blog.st.nu/polopolyGetLatest.php?'; }
		else { url = 'http://blog.st.nu/polopolyGetBlog.php?alias='+alias; }
		url += '&numPosts='+numPosts;
		url += '&parentId='+insertionId;
		var jsonObj = new JSONscriptRequest(url);
		jsonObj.buildScriptTag();
		jsonObj.addScriptTag();
	}
}
function makeBloggerTeaser(arr)  {
	if( arr ) { for(var i=0, ln=arr.length; i<ln; i++) { a_blogs[i] = new blog(arr[i]); } }
}
function makeBlogTeaser(arr,parentId) {
	if( arr && parentId ) {
		for(var i=0, ln=arr.length; i<ln; i++) { a_blogPosts[i] = new blogPost(arr[i]); }
		var container = document.createElement('div');
		for(var i=0, ln=arr.length; i<ln; i++) {
			container.appendChild(a_blogPosts[i].makePost(true));
		}
		makeBlogTeaserDiv(container,parentId);
	}
}
function makeBlogTeaserDiv(postsDiv,parentId) {
	if( parentId ) {
		var container = document.createElement('div');
		container.className = "articleTeaser";
		container.appendChild(postsDiv);
		var parent = document.getElementById(parentId).parentNode;
		parent.insertBefore(container,document.getElementById(parentId).nextSibling);
		parent.removeChild(document.getElementById(parentId));
	}
}
function makeReadable(mini) {
	switch( mini ) {
		case "nasti": return "Nu &auml;r skrivaren trasig igen";
		case "ledarbloggen": return "Ledarbloggen";
		case "fridas": return "Fridas blogg";
		case "tikare": return "Tikar-bloggen";
		case "maitraiders": return "Maitraiders";
		case "niccis": return "Nicola Stewart";
		case "korslaget": return "K&ouml;rslaget";
		case "kennedy": return "Kennedy Katende";
		case "vaningochvilla": return "V&aring;ning &amp; Villa";
		case "gomorron": return "Gomorron-bloggen";
		case "15": return "15-bloggen";
		case "gatufestbloggen": return "Gatufestbloggen";
		case "unga": return "Unga-bloggen";
		default: return "bloggare";
	}
}

