/* ########## START LOAD SCRIPTS ######### */

var apiPage = {};

// Function for getting a cookie
function apiGetCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}

// Function for setting a cookie
function apiSetCookie(name, value, expires, path, domain, secure) {
  // Handling expiration
  // If no value is provided to "expires", the cookie will live to the end of the session
		var fDate = new Date()
		var exDate = fDate.getTime()
		exDate += 1000*3600*24*expires
		fDate.setTime(exDate)

  // Setting the cookie
  document.cookie= name + "=" + escape(value) +
      ((expires) ? "; expires=" + fDate.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
}

// Function for deleting a cookie
function apiDeleteCookie(name, path, domain){
		if(getCookie( name ) ) document.cookie = name + "=" +
		    ((path) ? ";path=" + path : "") +
		    ((domain) ? ";domain=" + domain : "" ) +
		    ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

// Function for checking if it's possible to set a cookie or not
function apiCookiesOn(){
		var cookieson = "false"

		var fDate = new Date()
		var exDate = fDate.getTime()
		exDate += 1000*5
		fDate.setTime(exDate)

  apiSetCookie("apiCookiesOnCheck", "true", fDate)

  if(apiGetCookie("apiCookiesOnCheck") == "true"){
    cookieson = "true"
  }
  return cookieson;
}

window.onload = init;
function init(){
	apiSetBrowser();
	fixIE();
	fixAdSplit();
}

function apiSetBrowser(){
	apiPage.browser = _apiDB();
	apiPage.browser.isIe = false;
	apiPage.isIe = (apiPage.browser=="ie5" || apiPage.browser=="ie6" || apiPage.browser=="ie7");
	apiPage.isIeLt7 = (apiPage.browser=="ie5" || apiPage.browser=="ie6");
	apiPage.Body = document.getElementsByTagName("body")[0];
}

function fixIE(){
  /* Workaround for challenge top disappearing (BUG-509) */
	var el = document.getElementById("apiChallengeTop-1");
	if (el != null) {
    el.style.display = "block";
  }
}

function fixAdSplit(){ // Skal inn i koden. Gjelder for alle browsere
	if(!!$("apiAdSplit"))$("apiAdSplit").appendChild(_apiBH("div",{className:"apiAdSplitFooter"}));
	if(!$("apiDeck-6-1-4"))if(!!$("apiListWrap"))$("apiListWrap").appendChild(_apiBH("div",{className:"apiEndSep apiEndSepId4"}));
	if(!$("apiDeck-8-1-4"))if(!!$("apiListWrap2"))$("apiListWrap2").appendChild(_apiBH("div",{className:"apiEndSep apiEndSepId4"}));
}

function toggleBox(header){
	var box = header.parentNode;
	var boxContent = $(box.id+"Content");
	if(/\bapiBoxOpen\b/.test(box.className)){
		box.className = box.className.replace(/\bapiBoxOpen\b/,"apiBoxClosed")
		boxContent.style.display = "none";
	}else{
		box.className = box.className.replace(/\bapiBoxClosed\b/,"apiBoxOpen")
		boxContent.style.display = "block";
	}
	apiFixIe()
}

function apiFixIe(){
	if(apiPage.isIe)$('apiContentLeft').className = $('apiContentLeft').className;
}

function _apiBH(n,a){ // BuildHTML
	if(n!="text"){obj = document.createElement(n);for(var i in a)eval("obj."+i+"='"+a[i]+"'")}
	else obj = document.createTextNode(a);
	return obj;
}

function _apiDB() { // Detect Browser
	var b='', ua = navigator.userAgent.toLowerCase();
	if(ua.indexOf("opera") != -1) { b="opera"; }
	else if(ua.indexOf("safari") != -1) { b="safari";}
	else if(ua.indexOf("msie 7") != -1) { b="ie7";}
	else if(ua.indexOf("msie 6") != -1) { b="ie6";}
	else if(ua.indexOf("msie 5") != -1) { b="ie5";}
	else if(ua.indexOf("netscape") != -1) { b="netscape";}
	else if(ua.indexOf("firefox") != -1) { b="firefox";}
	else if(ua.indexOf("gecko") != -1) { b="mozilla";}
	return b;
}

/**
  * Launches a pop-up window
  */
function launchPopup(url, name, width, height, resizable, scrollbars, toolbar, location) {
  popup_window = window.open(url, name, 'width='+width+',height='+height+',resizable='+resizable+',scrollbars='+scrollbars+',toolbar='+toolbar+',location='+location+'');
  popup_window.focus();
}


/**
  * Prototype.js erstatninger
  */

/**
  * Check to se if the $ function is already defined, i.e we are using prototype
  * as well as global.js.
  */
if (typeof($) != "function") {
	function $(x){
		if (typeof x == 'string') {
		  return document.getElementById(x);
		}
		else {
			return x;
		}
	}
}

function getElementsByClassName(c,o,t){
	o=o||document; t=t||"*";
	var retnode = [];
	var myclass = new RegExp('\\b'+c+'\\b');
	var elem = o.getElementsByTagName(t);
	for (var i = 0; i < elem.length; i++) {
		var classes = elem[i].className;
		if (myclass.test(classes)) retnode.push(elem[i]);
	}
	return retnode;
}

function apiCumulativeOffset(element) {
    var valueT = 0, valueL = 0;
    do{
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
    } while (element);
    return [valueL, valueT];
}

function apiGetDimensions(element) {
    return {width: element.offsetWidth, height: element.offsetHeight};
}

/**
  * Javascript for search bar in top menu
  */
function apiSubmitMenuSearch(locSearchUrl) {
  var sTypeZett = $('eceRadioZett');
  var sTypeDDB = $('eceRadioDDB');
  var sTypeAvis = $('eceRadioAvis');
  if((!!sTypeZett) && sTypeZett.checked) {
    loc = "http://www.zett.no/q_index.html";
    loc += "?setText="+$('eceExpr').value;
    loc += "&zt_o=forside";
    loc += "&zt_t=simplesearch";
  } else if((!!sTypeDDB) && sTypeDDB.checked) {
    loc = "http://www.derdubor.no/searchMainAction.do";
    loc += "?option=news&encoding=iso-8859-1&servicearea="+$('ecePubId').value+"&querystring="+$('eceExpr').value;
  } else {
    loc = locSearchUrl;
    loc += "?eceMode="+$('eceMode').value;
    loc += "&eceForm="+$('eceForm').value;
    loc += "&eceSort="+$('eceSort').value;
    loc += "&eceMaxDateSortedHits="+$('eceMaxDateSortedHits').value;
    loc += "&eceMaxDateSortedHitsOrder="+$('eceMaxDateSortedHitsOrder').value;
    loc += "&eceSection="+$('eceSection').value;
    loc += "&eceExpr="+$('eceExpr').value;
  }
  this.location.href = loc;
}


/**
  * Handling ads
  */
  
function moveAd (cuid) {
  // set browser
  if (apiPage.browser == null) {
    apiSetBrowser();
  }
  // move ad  
  var pos = document.getElementById("ad_"+cuid);
  var ad = document.getElementById("tmpad_"+cuid);
  if (pos && ad) {
    // setting height of sorrounding div to "auto" to enable expanding ads
    pos.style.height="auto";
    // traverse all script elements and set src to null to make sure IE doesn't reload the scripts
    var x=ad.getElementsByTagName('script');
    if (x != null) {
      for (i=0;i<x.length;i++) {
        var t=x[i];
        if (apiPage.isIe) {
          t.src="http://template.api.no/template/js/adsEmptyScript.js";
        } else {
          t.src.replace="http://template.api.no/template/js/adsEmptyScript.js";
        }
      }
    }
    var body = ad.parentNode;
    body.removeChild (ad);
    pos.innerHTML='';
    pos.appendChild (ad);
  }
}


/**
 * Handling polls
 */

var pollResults = [];
var pollParent = [];
var pollCounter = [];
var pollCookieName = "apiPoll";

function apiPoll(id,par){
	var poll = {};
	poll.data = $('apiPoll-'+id+"-"+par).getElementsByTagName("input");// Henter Form for gjeldene poll
	for(var i=0;i<poll.data.length;i++){ // Skringer verdier til poll objektet
		if(i<2)poll[poll.data[i].name] = poll.data[i].value;
		else if(!!poll.data[i].checked)poll[poll.data[i].name] = poll.data[i].value;
	}
	
	if(!eval("poll.radio"+id)){return}; // Ingen stemme avgitt
	var reDir = "/template/gfx/ver2-1r2/default/header/pngfix.gif"; // retur for request
	var url = '/do/test?mentometerId=' + escape(poll.mentometerId) + 
			  '&publicationId=' + escape(poll.publicationId) + 
			  '&redirectTo=' + escape(reDir) + 
			  '&vote=' + escape(eval("poll.radio"+id)); // url for stemme

	for(var i=2;i<poll.data.length;i++) // Finner hvilet nummer som er besvart
		if(poll.data[i].checked){ // Hvis besvart
			pollResults[id][i-2]+=1; // Legger til avgitt stemme i koden
			apiSetCookie(pollCookieName+id,(i-2),365); // Set cookie med avgitt stemme
			continue; // Avbryter for loop
		};
	//document.getElementsByTagName("body")[0].appendChild(_apiBH("img",{src:url}));
	$("pollSpacer_"+id+"_"+par).src = url;
	apiPollSetResult(id); // Regn ut og vis resultat
}

function apiChkPoll(id,c,par){ // Kj�res for hver poll under lasting
	pollCounter[id] = c; // setter antall svaralternativ i global array
	var pollParObj = "apiPoll-"+id+"-"+pollParent[id][pollParent[id].length-1];
	var cookie = apiGetCookie(pollCookieName+id); // Leser cookie
	if(!!cookie){ // Hvis cookie er satt
		var data = $(pollParObj).getElementsByTagName("input");
		data[Number(cookie)+2].checked = "checked" // Setter avgitt stemme fra cookie
		apiPollSetResult(id); // Regn ut og vis resultat
	}
	document.write('<img id="pollSpacer_'+id+'_'+par+'" src="/template/gfx/ver2-1r2/default/header/pngfix.gif" width="1" height="1">')
}

function apiPollSetResult(id){
	for(var pls=0;pls<pollParent[id].length;pls++){
		var c = pollCounter[id];
		var pollParObj = "apiPoll-"+id+"-"+pollParent[id][pls];
		var total = 0;
		for(var i=0;i<c;i++)total += Number(pollResults[id][i]); // summerer alle stemmer
		for(var i=0;i<c;i++){
			var p=(total==0)?0:Math.round((pollResults[id][i]/total)*1000)/10; // Regner ut prosent med en desimal
			$("apiPollBar-"+id+"-"+pollParent[id][pls]+"-"+i).style.width = p+"%"; // Setter bredde p� pollBar
			$("apiPollResultPercent-"+id+"-"+pollParent[id][pls]+"-"+i).innerHTML = p+"%"; // Skriver inn prosent
		}
		$("apiPollCount-"+id+"-"+pollParent[id][pls]).innerHTML = total; // Skriver inn antall stemmer
		$(pollParObj).className += ' apiPollSubmited'; // Endrer visning til resultat
		var cookie = apiGetCookie(pollCookieName+id); // Leser cookie
		var data = $(pollParObj).getElementsByTagName("input");
		data[Number(cookie)+2].checked = "checked" // Setter avgitt stemme fra cookie
		for(var i=2;i<data.length;i++)data[i].disabled = "disabled" // Deaktiverer radioknappene
	}
}


// DERDUBOR

var ddbBox = {
	"listLoaded":false,
	"gT":function(){var t=false;if(window.XMLHttpRequest)t=new XMLHttpRequest();else if(window.ActiveXObject){try{t=new ActiveXObject("Msxml2.XMLHTTP")}catch(e){try{t=new ActiveXObject("Microsoft.XMLHTTP")}catch(E){t=false}}} return t;},
	"gG":function(url,c,p){
		var xh=new ddbBox.gT();
		if(xh)xh.onreadystatechange=function(){
			if(xh&&xh.readyState==4)
				if(xh.status==200){
					eval(c+'(xh,'+p+')');
				}else if(xh.status==404){
					ddbBox.go404(p);
				}else throw(xh.statusText)
			};
		xh.open("GET",url,true);xh.send(null);
	},
	"bh":function(n,a){/* Build HTML */
		if(n!="text"){
			var o=document.createElement(n);
			for(var i in a){
				if(i=="class"||i=="className"||i=="cl")o.className=a[i];
				else if(i=="innerHTML"||i=="ih")o.innerHTML=a[i];
				else if(i.indexOf("style.") > -1){
					var iS=i.split(".");
					o[iS[0]][iS[1]]=a[i];
				}else o.setAttribute(i,a[i]);
			}
		}else var o=document.createTextNode(a);return o;
	},
	"go404":function(p){
		var e = $("apiDDBBoxCatalogList");
		var title = ddbBox.bh("div",{"cl":"ddbBoxListHeader","ih":"404: XML ikke funnet..."});e.appendChild(title);
	},
	"cb":function(x,p){
		ddbBox.listLoaded = p;
		var xml = x.responseXML;
		var e = $("apiDDBBoxCatalogList");
		var header = xml.getElementsByTagName("header")[0];
		var items = xml.getElementsByTagName("item");
		var title = ddbBox.bh("div",{"cl":"ddbBoxListHeader","ih":header.getElementsByTagName("title")[0].firstChild.nodeValue});e.appendChild(title);
		
		for(var i=0;i<items.length;i++){
			var itm = ddbBox.bh("a",{"cl":"ddbBoxListItemLink","href":items[i].getElementsByTagName("link")[0].firstChild.nodeValue,
			"ih":items[i].getElementsByTagName("linktext")[0].firstChild.nodeValue});e.appendChild(itm);
		}
		
		var footer = ddbBox.bh("div",{"cl":"ddbBoxListFooter"});e.appendChild(footer);
		var footerlink = ddbBox.bh("a",{"cl":"ddbBoxListFooterLink","href":header.getElementsByTagName("link")[0].firstChild.nodeValue,
			"ih":header.getElementsByTagName("linktext")[0].firstChild.nodeValue});footer.appendChild(footerlink);
		apiFixIe();
	},
	"swap" : function(x){
		$("apiDDBBox-1").className = (x==1)?"apiDDBBox_search":"apiDDBBox_catalog";
		if(x==2&&(!ddbBox.listLoaded)){
			ddbBox.gG("/static/global/derdubor/ddbBox.xml","ddbBox.cb",true);
		}else{
			apiFixIe();
		}
	}
}


/**
 * E-Mail Byline
 */
function devmssdea (anchor) {
	var href = anchor.getAttribute('href');
	var address = href.replace(/\[at\]/gmi, '@');
	address = address.replace(/\[dot\]/gmi, '.');
	if (href != address) { anchor.setAttribute('href',address);}
}


/**
 * Google Maps
 */

// Load the Google Map Script when the user requests a dynamic map
function loadScript(callbackScript, googleMapKey) {
    var script = document.createElement("script");
    script.setAttribute("src", "http://maps.google.com/maps?file=api&v=2.x&key=" + googleMapKey + "&c&async=2&callback=" + callbackScript);
    script.setAttribute("type", "text/javascript");
    document.documentElement.firstChild.appendChild(script);
}

// Creating a marker on the map
function createMarker(longitude, latitude, comment) {

  // Construct position
  var position = new GLatLng(longitude,latitude);

  // Construct custom icon similar to the one used on the static map
  var defaultApiIcon = new GIcon();
  defaultApiIcon.image = "http://template.api.no/template/gfx/ver2-1r2/default/maps/marker-blue.png";
  defaultApiIcon.shadow = "http://template.api.no/template/gfx/ver2-1r2/default/maps/marker-blue-shadow.png";
  defaultApiIcon.iconSize = new GSize(35, 35);
  defaultApiIcon.shadowSize = new GSize(53, 35);
  defaultApiIcon.iconAnchor = new GPoint(18, 35);
  defaultApiIcon.infoWindowAnchor = new GPoint(30, 0);
  markerOptions = {icon:defaultApiIcon};

  // Set nax with of the infobox on the markers (given in pixels (added by Google))
  var markerMaxWidth = {maxWidth:"300"}

  // Create marker
  var marker = new GMarker(position, markerOptions);
  if(!(comment==null || comment=="")){
    GEvent.addListener(marker, "click", function() {
      marker.openInfoWindowHtml(comment,markerMaxWidth);
    });
  }
  return marker;
}

// Creating an map
function createMap(elementIdToAttachMapTo, centerOfMapLatitude, centerOfMapLongitude, mapZoom, markersOnMap){
  if (GBrowserIsCompatible()) {
      // Create the map
      var map = new GMap2(document.getElementById(elementIdToAttachMapTo));
      map.setCenter(new GLatLng(centerOfMapLatitude,centerOfMapLongitude), mapZoom);
      map.addControl(new GSmallMapControl());

      // Place markers on the map
      if(!(markersOnMap==0||markersOnMap==null)){
         for(i=0;i<markersOnMap.length;i++){
             map.addOverlay(markersOnMap[i]);
         }
      }
  }
}

// START SKATTESØK 2007
    function zipSearchForm(f){
        f.onsubmit = doZipSearch;
        f.ziptextfield.onkeyup = zipSearch;
        f.ziptextfield.output = f.getElementsByTagName("div")[1];
    }

    function zipSearch(){
        var o=this.output;
        var v=$F(this);
        if($F(this) == '0000' || isNaN($F(this))) {
            o.className = 'zipResultError apiTaxSearchExample';
            o.innerHTML = taxZipError;
        }else if(v.length==4){
            if(v==this.last)return; else
            this.last = v;
            var jsonUrl = "/skattelisten/zipsearch.json?zipcode=" + $F(this);
            new Ajax.Request(jsonUrl, {
                method :'get',
                requestHeaders : { Accept :'application/json' },
                onSuccess : function(transport) {
                    searchResult = transport.responseText.evalJSON(true);
                    if (searchResult.searchResult == 'zipFound') {
                        o.className = 'zipResultOk apiTaxSearchExample';
                        o.innerHTML = searchResult.cityName;
                    } else {
                        o.className = 'zipResultError apiTaxSearchExample';
                        o.innerHTML = taxZipError;
                    }
                }
            });
        }else if(this.value.length < 4) {
            o.className = 'apiTaxSearchExample';
            o.innerHTML = taxZipExample;
        }
    }

    function doZipSearch() {
        if (/zipResultOk/.test(this.ziptextfield.output.className)) {
            document.location = "/skattelisten/sted/" + this.ziptextfield.value + "/oversikt.html";
        }
        return false;
    }
// END SKATTESØK 2007