var timer;
function StartCountDown(countDownControlId, secondsRemaining, finishedMessage)
{	        
    var countDownControl = document.getElementById(countDownControlId);
    var tmpCalc, days, hours, minutes, seconds;
    if(!countDownControl) return;
    
    
    if(!secondsRemaining){
        secondsRemaining = countDownControl.innerText;
    }        
  
    if(!secondsRemaining || secondsRemaining == "") return;

    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 setHourglass()
{
//    alert(document.body.style.cursor);
    document.body.style.cursor = 'wait';
}

function showImage(source, offsetX, offsetY, imageDivName, imageDivImgName, imageUrl)
{              
    var imageDiv = document.getElementById(imageDivName);            
    var coors = findPos(source);
    
    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 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 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
d    : SESSION.DB
*/


 var id = obj.getAttribute("id");
 
 var application = obj.getAttribute("a");
 var url = document.location.href;
 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 db = obj.getAttribute("d");
 var fileName;
 
if(!application)
{
    if( db == "SKF-NO" )
    {
      // if enkeltmerker: navigate to ArtLst2.aspx
      if( id.substring(0,6) == "101000" )
        url = "ArtLst2.aspx";
      else url = "ArtLst.aspx";
    }
    
    if(url.toUpperCase().indexOf("ARTLST2.ASPX")>1) fileName = "ArtLst2.aspx";
    if(url.toUpperCase().indexOf("ARTLST.ASPX")>1) fileName = "ArtLst.aspx";
    if(url.toUpperCase().indexOf("LOTMENU.ASPX")>1) fileName = "LotMenu.aspx";
    query = "?";
    query = ReplaceQuery("n",id,query,"replace");  
    url = fileName + query;
    if(!navigateUrl) document.location.href = url;
}
   
   /*
  
  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 = "LotMenu.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;

 }
 */
 
 }


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
d    : SESSION.DB
*/


 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 db = obj.getAttribute("d");
 
 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;

 // Overrule ajax nodes...
 hasSibling = false;
 hasChildren = false;
 
 
 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(id.length != 6 && !application && hasChildren){
    // Do postback to get children nodes
    var postBackUrl;
    if(db == "SKF-NO"){
      postBackUrl = "WgrNodeSkf.ashx?n="+id;
    }
    else
    {
        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);
            }
        }
    } 
    
  }
  else if((!application && !hasChildren) || id.length == 6){
    if( db == "SKF-NO" )
    {
      // if enkeltmerker: navigate to ArtLst2.aspx
      if( id.substring(0,6) == "101000" )
        url = "ArtLst2.aspx";
      else url = "ArtLst.aspx";
    }
    else url = "LotMenu.aspx";
    query = "?";
    query = ReplaceQuery("n",id,query,"replace");  
    url += query;
    if (!navigateUrl) {
        document.location.href = url;
        return;
    }
    
 }
  
  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 = "LotMenu.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 BreadCrumb(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 currentUrl = document.location.href.toUpperCase();
 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){
 
    if(currentUrl.indexOf("ART")>1){
        url = "ArtLst.aspx";
    }
    else{
        url = "LotMenu.aspx";
    }        
    var subSection = id.substring(6,0);
    if(subSection == "101000"){
        url = "ArtLst2.aspx";
    }    
    query = "?";
    query = ReplaceQuery("n",id,query,"replace");  
    url += query;
    if(!navigateUrl) document.location.href = url;
 }
 else{
        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;
}

function ClearSearchBox(obj){
    var txt = obj.value;
    if(txt.indexOf("eller nr.") > 1)
    {
        obj.value = "";    
    }
}

function RemoveThumbnailBorders() {
    var imgthmb0 = document.getElementById(imgthmb0CID);
    if (imgthmb0) imgthmb0.style.border = "solid 1px gray";
    var imgthmb1 = document.getElementById(imgthmb1CID);
    if (imgthmb1) imgthmb1.style.border = "solid 1px gray";
    var imgthmb2 = document.getElementById(imgthmb2CID);
    if (imgthmb2) imgthmb2.style.border = "solid 1px gray";
    var imgthmb3 = document.getElementById(imgthmb3CID);
    if (imgthmb3) imgthmb3.style.border = "solid 1px gray";
    var imgthmb4 = document.getElementById(imgthmb4CID);
    if (imgthmb4) imgthmb4.style.border = "solid 1px gray";
    var imgthmb5 = document.getElementById(imgthmb5CID);
    if (imgthmb5) imgthmb5.style.border = "solid 1px gray";
}

function SwitchImageFromThumbnailToMain(thumbnail) {
    var imgMain = document.getElementById(imgMainCID);
    if (imgMain) {
        var imgMainSrc = imgMain.src;
        var imgMainSrc1 = imgMainSrc.split('&')[0];
        var imgMainSrcDocid = imgMainSrc.split('&')[1];
        var thumbnailSrc = thumbnail.src;
        var thumbnailSrc1 = thumbnailSrc.split('&')[0];
        var thumbnailSrcDocid = thumbnailSrc.split('&')[1];
        imgMain.src = imgMainSrc1 + '&' + thumbnailSrcDocid;
        RemoveThumbnailBorders();
        thumbnail.style.border = "solid 3px white";
    }
}

function ShowBigImage() {
    var imgMain = document.getElementById(imgMainCID);
    if (imgMain) {
        var imgMainSrc = imgMain.src;
        var imageSrcDocid = imgMainSrc.split('&')[1];
        var aImgLink = document.getElementById('aImgLink');
        if (aImgLink) {
            aImgLink.href = "i.ashx?w=1024&" + imageSrcDocid;
        }
    }
}
