function StartCountDown(countDownControlId, secondsRemaining, finishedMessage)
{	        
    var countDownControl = document.getElementById(countDownControlId);
    
    var tmpCalc, days, hours, minutes, seconds;
    
    if(!secondsRemaining){
        if(document.all){
            secondsRemaining = countDownControl.innerText;
        } 
        else{
            secondsRemaining = countDownControl.textContent;
        }
    }        
    secondsRemaining--;
    tmpCalc = secondsRemaining;

    days = Math.floor(tmpCalc / 86400);
    tmpCalc -= days * 86400;

    hours = Math.floor(tmpCalc / 3600);
    tmpCalc -= hours * 3600;

    minutes = Math.floor(tmpCalc / 60);
    tmpCalc -= minutes * 60;

    seconds = tmpCalc;

    var message = '';

    if(secondsRemaining > 0) 
    {		
	    if(days > 0) {message = message + days + 'd ';}
	    if(hours > 0) {message = message + hours + 't ';}
	    if(minutes >0) {message = message + minutes + 'm ';}
	    message = message + seconds + 's';
    }
    else
    {	    
        document.location.replace(String(document.location));
    }

    if (countDownControl != null)
    {
	    document.getElementById(countDownControlId).innerHTML = message;
    }	

    if(secondsRemaining > 0) 
    {	    
	    setTimeout("StartCountDown('" + countDownControlId + "'," + secondsRemaining + ",'" + finishedMessage + "')", 1000);    	
    }	
}


function getBrowserDimensions() {
    var browserWidth = 0;
    var browserHeight = 0;
    if (window.innerWidth) { //if browser supports window.innerWidth
        browserWidth = window.innerWidth;
        browserHeight = window.innerHeight;
    }
    else if (document.all) { //else if browser supports document.all (IE 4+)
        browserWidth = document.body.clientWidth;
        browserHeight = document.body.clientHeight;
    }
    return [browserWidth, browserHeight];
}

function getDocumentScrollOffsetCoordinates() {
    var iebody = (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body

    var dsocleft = document.all ? iebody.scrollLeft : pageXOffset
    var dsoctop = document.all ? iebody.scrollTop : pageYOffset
    return [dsocleft, dsoctop];
}

function showImage(source, offsetX, offsetY, imageDivName, imageDivImgName, imageUrl)
{              
    var imageDiv = document.getElementById(imageDivName);            
    var coors = findPos(source);

    var coordsBrowser = getBrowserDimensions();
    var coordsDsoc = getDocumentScrollOffsetCoordinates();

    var midBrowserWidth = coordsBrowser[0] / 2;
    var midBrowserHeight = coordsBrowser[1] / 2;
    var sourceVisibleLeft = coors[0] - coordsDsoc[0];
    var sourceVisibleTop = coors[1] - coordsDsoc[1];

    //imageDiv.style.left = (sourceVisibleLeft <= midBrowserWidth ? (coors[0] - offsetX) : (coors[0] + offsetX)) + 'px';
    imageDiv.style.left = (sourceVisibleLeft <= midBrowserWidth ? (coors[0] + offsetX) : (coors[0] + offsetX)) + 'px';
    imageDiv.style.top = (sourceVisibleTop <= midBrowserHeight ? (coors[1] + offsetY) : (coors[1] - offsetY - 300)) + 'px';

//    imageDiv.style.top = (coors[1] + offsetY) + 'px';
//    imageDiv.style.left = (coors[0] + offsetX) + 'px';                
    
    var imageDivImg = document.getElementById(imageDivImgName);
    
    imageDivImg.src = imageUrl;    
    imageDivImg.style.visibility = "visible";
    
    imageDiv.style.visibility = "visible";
}


function zImg(imageDivImgName, imageDivName, it)
{              
    var imageDiv = document.getElementById(imageDivName);            
    var imageDivImg = document.getElementById(imageDivImgName);
    imageDivImg.src = "i.ashx?w=400&it="+it;    
    imageDivImg.style.visibility = "visible";
    imageDiv.style.visibility = "visible";
}

function setImageSrc(imageID, it)
{              
    var image = document.getElementById(imageID);
    image.src = "i.ashx?w=400&it="+it;    
}

function hideImage(source, imageDivName, imageDivImgName)
{   
    var imageDiv = document.getElementById(imageDivName);
    imageDiv.style.visibility = "hidden";
    
    var imageDivImg = document.getElementById(imageDivImgName);   
    
    imageDivImg.src = "space.gif";
    imageDivImg.style.visibility = "hidden";
}


function findPos(obj)
{
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        curleft = obj.offsetLeft
        curtop = obj.offsetTop
        while (obj = obj.offsetParent) {
	        curleft += obj.offsetLeft
	        curtop += obj.offsetTop
        }
    }
    return [curleft,curtop];
}  

function WgrEvt(obj){
/*
id   : WGR.DOCID
h    : WGR.HASCHILDREN
a    : WGR.APPLICATION
t    : WGR.TARGET
u    : WGR.URL
i    : WGR.ITLIST
ac   : WGR.TCLLIST
s    : WGR.SEARCHSTRING
f    : WGR.FILTER
*/


 var id = obj.getAttribute("id");
 
 var application = obj.getAttribute("a");
 var url = "";
 var query = "";
 var target = obj.getAttribute("t");
 var navigateUrl = obj.getAttribute("u");
 var itList = obj.getAttribute("i");
 var tclList = obj.getAttribute("ac");
 var searchString = obj.getAttribute("s");
 var filter = obj.getAttribute("f");
 
 var sibling = obj.nextSibling;
 var hasSibling = false;
 var hasChildren = false;
 
 
 if(sibling && sibling.getAttribute("id")=="") hasSibling = true;
 if(sibling && sibling.getAttribute("id") == null) hasSibling = true; 
 if(obj.getAttribute("h")=="1") hasChildren = true;
 
 if(hasSibling){
    // Hide or show node.
    if(sibling.style.visibility == "hidden"){
        sibling.style.display = "block";    
        sibling.style.visibility = "visible";
    }
    else{
        sibling.style.display = "none";
        sibling.style.visibility = "hidden";
    }   
  }
  else if(!application && hasChildren){
    // Do postback to get children nodes
    var postBackUrl = "WgrNode.ashx?n="+id;
    var http = XmlHttp();
   
    try{
        http.open("GET",postBackUrl,true);
        http.setRequestHeader('content-type', 'text/plain');
    }
    catch(e){
        alert("PostBack from node failed: " +id + "\n" + postBackUrl);
    }
    http.send(null);   
    
    http.onreadystatechange=function()
    {
        if(http.readyState==4)
        {
            if ( http.status == 200 ) {
                // Alt OK i fra server
                var newDiv = document.createElement("div");
                newDiv.innerHTML = http.responseText;
                obj.parentNode.insertBefore(newDiv,obj.nextSibling);
            } else {
                // Fikk en feil i fra server, f.eks. statuskode 404 eller liknende
                alert("Fikk feilkode i fra server: "+http.status+", "+http.statusText);
            }
        }
    } 
  }
  
  if(application){
        switch (application.toUpperCase()){
          case "ARTDETAIL" : 
            url = "ArtDtl.aspx";
          break;
          case "ARTLIST" : 
            url = "ArtLst.aspx";         
          break;
          case "ARTPROFILE" : 
            url = "ArtPrf.aspx";         
          break;
          case "AUCDETAIL" : 
            url = "AucDtl.aspx";         
          break;
          case "AUCLIST" : 
            url = "AucLst.aspx";         
          break;
          case "SPOTS" : 
            url = "Spots.aspx";
          break;          
        }
    query = "?";
    if(itList){
        //query = ReplaceQuery("i",escape(itList),query,"replace");
    }
    if(id){
        query = ReplaceQuery("n",id,query,"replace");  
    }
    if(tclList){
        query = ReplaceQuery("ac",tclList,query,"replace");  
    }
    if(searchString){
        query = ReplaceQuery("s",searchString,query,"replace");    
    }
    if(filter){
        query = ReplaceQuery("f",filter,query,"replace");      
    }
    url += query;
    if(!navigateUrl) document.location.href = url;
  }

  if(navigateUrl){
     var s = navigateUrl.split("?");
     if(s.length>2){
       navigateUrl =  s[0]+"?"+s[1];
     }
     document.location.href = navigateUrl;
  }  
}

function leseFraTxtFil(){
    http.open("get", "test.txt"); // Opner en kobling med filen test.txt med metoden "get"
    http.onreadystatechange = lagAlertBoks; // Når hele filen er lastet kjør funksjon
    http.send(null); // Sender ingen ting, etter som vi brukte metoden "get"
}

function lagAlertBoks(){ 
    if(http.readyState == 4){ // Hvis xmlHttpRequest-objektet er helt klart
        alert(http.responseText); // Lag en advarselsboks med test.txt som innhold
    }
}

function WgrTopEvt(obj){
/*
id   : WGR.DOCID
h    : WGR.HASCHILDREN
a    : WGR.APPLICATION
t    : WGR.TARGET
u    : WGR.URL
i    : WGR.ITLIST
ac   : WGR.TCLLIST
s    : WGR.SEARCHSTRING
f    : WGR.FILTER
*/

 var id = obj.getAttribute("id");

 var application = obj.getAttribute("a");
 var url = "";
 var query = "";
 var target = obj.getAttribute("t");
 var navigateUrl = obj.getAttribute("u");
 var itList = obj.getAttribute("i");
 var tclList = obj.getAttribute("ac");
 var searchString = obj.getAttribute("s");
 var filter = obj.getAttribute("f");
 var sibling = obj.nextSibling;
 var hasSibling = false;
 var hasChildren = false;

  if(application){
        switch (application.toUpperCase()){
          case "ARTDETAIL" : 
            url = "ArtDtl.aspx";
          break;
          case "ARTLIST" : 
            url = "ArtLst.aspx";         
          break;
          case "ARTPROFILE" : 
            url = "ArtPrf.aspx";         
          break;
          case "AUCDETAIL" : 
            url = "AucDtl.aspx";         
          break;
          case "AUCLIST" : 
            url = "AucLst.aspx";         
          break;
          case "SPOTS" : 
            url = "Spots.aspx";
          break;          
          
        }
    query = "?";
    if(itList){
        //query = ReplaceQuery("i",escape(itList),query,"replace");
    }
    if(id){
        query = ReplaceQuery("n",id,query,"replace");  
    }
    if(tclList){
        query = ReplaceQuery("ac",tclList,query,"replace");  
    }
    if(searchString){
        query = ReplaceQuery("s",searchString,query,"replace");    
    }
    if(filter){
        query = ReplaceQuery("f",filter,query,"replace");      
    }
    url += query;
    //alert("Application to navigate to: " + application + "\n\n" + url);
    if(!navigateUrl) document.location.href = url;
  }

  if(navigateUrl && navigateUrl != ""){
    if(target && target!=""){
        open(navigateUrl,target);
    }
    else{ 
        document.location.href = navigateUrl;
    }
  }  
}

// mouseover mouseout
function hover(obj){
   //obj.style.background = "#dcdcdc";
}
function hoverOut(obj) {
/*
    if(obj.tagName == "DIV"){
        obj.style.background = "transparent";
    }
    else{
        obj.style.background = "transparent";
        obj.style.backgroundImage = "url('App_Themes/default/images/background_gray.gif')";
    }
*/
}

  function XmlHttp(){
  var xmlhttp=false;
  /*@cc_on @*/
  /*@if (@_jscript_version >= 5)
  // JScript gives us Conditional compilation, we can cope with old IE versions.
  // and security blocked creation of the objects.
   try {
    xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
   } catch (e) {
    try {
     xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (E) {
     xmlhttp = false;
    }
   }
  @end @*/
  if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
    xmlhttp = new XMLHttpRequest();
  }
  return xmlhttp;
}

  function ReplaceQuery(name,value,loc,mode){ // mode : replace(insert) or delete
  var queryString = String(loc);
  var n = (queryString.indexOf("?") + 1);
  if (queryString != ""){
    var data,aData,aOut
    var insert = false
    var outValue = "?";
    data = queryString.slice(n,queryString.length);
    aData = data.split("&");
    for(i=0;i<aData.length;i++){
      aOut = aData[i].split("=");
      if(aOut[0].toUpperCase() == name.toUpperCase()){
        if(mode != "delete"){
          if(outValue != "?") outValue += "&";
  	  outValue += name + "=" + value; 
	}
	insert = true;
      }
      else{
        if(outValue != "?") outValue += "&";	
        outValue += aData[i]; 				
      }
    }
    if(insert != true && mode != "delete"){
      if(outValue != "?") outValue += "&";
      outValue += name + "=" + value;
    }			
    return outValue;
  }
  else{
    return null;
  }
}

function textCounter(field, countfield, maxlimit) {
	if (field.value.length > maxlimit){
	     // if too long...trim it!
	    field.value = field.value.substring(0, maxlimit);
	}
	else{ 
	    // otherwise, update 'characters left' counter
		countfield.value = maxlimit - field.value.length;
	}
}

function popitup(url)
{
	newwindow=window.open(url,'GECalculator','height=420,width=400');
	if (window.focus)
	{
		newwindow.focus()
	}
	return false;
}

function CalculateAndDisplayMinimumPayment(LoanAmount)
{
    //document.writeln("");
    //return;
    var period = "";
	var CreditLimitPercentage = 0.03;
	var MimimumLoanAmountAllowed = 1999;
	var MaximumLoanAmountAllowed = 75000;
	var MimimumMonthlyPaymentAllowed = 199;
	
	
	var FinancedAmount = LoanAmount;
    var DownPaymentPeriod = 12;
	var MonthlyPaymentRef = new Array(0);
	var TotalFinancingCostRef = new Array(0);
	var EffectiveInterestRateRef = new Array(0);
	var TotalFinancingCostAfterTaxRef = new Array(0);

	
	
	if ((LoanAmount >= MimimumLoanAmountAllowed) && (LoanAmount <= MaximumLoanAmountAllowed))
	{
	    if(LoanAmount>=1999 && LoanAmount <= 3200) period = 12;
	    if(LoanAmount>=3200 && LoanAmount <= 4300) period = 24;
	    if(LoanAmount>=4300 && LoanAmount <= 50000) period = 36;	
	    DownPaymentPeriod = period;
	    if(period == "") return;
	    
	    GECalculator_GetMonthlyPayment(FinancedAmount, DownPaymentPeriod, MonthlyPaymentRef, TotalFinancingCostRef, EffectiveInterestRateRef, TotalFinancingCostAfterTaxRef);
	    
    	
		var MonthlyPayment = CreditLimitPercentage * LoanAmount;
  	    var CreditAmount = GECalculator_FormatToCurrency((period*MimimumMonthlyPaymentAllowed));
		
		if (MonthlyPayment < MimimumMonthlyPaymentAllowed)
		{
			document.writeln("<b style='text-decoration:none'>Kun " + MonthlyPaymentRef[0] +" pr mnd</b><br/>");
			document.writeln("<span style='text-decoration:none;color:silver'>Kredittkj&oslash;pspris " + TotalFinancingCostRef[0] + "&nbsp;</span><span style='text-decoration:underline;color:silver'>Effektiv rente</span>");
			return;
		}
		else
		{
			document.writeln("<b style='text-decoration:none'>Kun " + MonthlyPaymentRef[0] + " pr mnd</b><br/>");
			document.writeln("<span style='text-decoration:none;color:silver'>Kredittkj&oslash;pspris " + TotalFinancingCostRef[0] + "&nbsp;</span><span style='text-decoration:underline;color:silver'>Effektiv rente</span>");
			document.writeln("<br/>");
			return;
		}
	}
	document.writeln("");
	return;
}

function CalculateMinimumPayment(LoanAmount)
{
    LoanAmount = Math.ceil(LoanAmount);
	var CreditLimitPercentage = 0.03;
	var MimimumLoanAmountAllowed = 1999;
	var MaximumLoanAmountAllowed = 75000;
	var MimimumMonthlyPaymentAllowed = 199;
	var result = "";
	
	var FinancedAmount = LoanAmount;
    var DownPaymentPeriod = 12;
	var MonthlyPaymentRef = new Array(0);
	var TotalFinancingCostRef = new Array(0);
	var EffectiveInterestRateRef = new Array(0);
	var TotalFinancingCostAfterTaxRef = new Array(0);
	
	if ((LoanAmount >= MimimumLoanAmountAllowed) && (LoanAmount <= MaximumLoanAmountAllowed))
	{
	    if(LoanAmount>=1999 && LoanAmount <= 3200) period = 12;
	    if(LoanAmount>=3200 && LoanAmount <= 4300) period = 24;
	    if(LoanAmount>=4300 && LoanAmount <= 50000) period = 36;	
	    DownPaymentPeriod = period;
	    

	    GECalculator_GetMonthlyPayment(FinancedAmount, DownPaymentPeriod, MonthlyPaymentRef, TotalFinancingCostRef, EffectiveInterestRateRef, TotalFinancingCostAfterTaxRef);
	    

		var MonthlyPayment = CreditLimitPercentage * LoanAmount;
  	    var CreditAmount = GECalculator_FormatToCurrency((period*MimimumMonthlyPaymentAllowed));

		if (MonthlyPayment < MimimumMonthlyPaymentAllowed)
		{
			result += "Kun " + MonthlyPaymentRef[0] +" pr mnd!";
			result += "Kredittkjøpspris " + TotalFinancingCostRef[0] + " Effektiv rente";
		}
		else
		{
			result += "Kun " + MonthlyPaymentRef[0] + " pr mnd!";
			result += "Kredittkjøpspris " + TotalFinancingCostRef[0] + "Effektiv rente";
		}
	}
	return result;
}
