
/** Lausn, hugbunadur - www.lausn.is **/

var imgRoot = "http://www.lausn.is/tmp/orkusetur/images/";

var theCars = new Array();
var subCars;
var framleidendur = new Array();
var tegundir = new Array();
var theSubCars = new Array();

var theRoads = new Array();
var depart = new Array();
var selectedDepart = 0
var selectedArrive = 0;

var currentSelectedRow = new Array();
var btns = new Array();
var msie = false;
var lang = "is";

var firstTime = true;

function msg (txt) { }

function msg2( txt ) {
   document.getElementById( "msg" ).innerHTML += " " + txt + " /";
   //document.getElementById( "msg" ).innerHTML += txt + "<br/>";
}
function dbug( txt ) {
	return;
	document.getElementById( "msg" ).innerHTML += " " + txt + " /";
	//document.getElementById( "msg" ).innerHTML += txt + "<br/>";
}

function addClass( node, clss ) {
    removeClass( node, clss );
    var c = node.className;
    c += " " + clss;
    c = c.replace( "  ", " " );
    node.className = c;
}

function removeClass( node, clss ) {
    var c = node.className;
    c = c.replace( clss, "" );
    node.className = c;
}

function scanForAttribute( node, elms, attr, value ) {
    var ok = false;
    for( var i=0; i < node.childNodes.length; i++ ) {
        n = node.childNodes[i];
        if( n.nodeType == 1 ) {0
            var a = n.getAttribute( attr );
            if( attr == "class" ) 
                ok = n.className == value; /* MSIE doesn't see class as attribute... */
            else
                ok = n.getAttribute( attr ) == value;
            if ( ok ) elms.push( n );
            scanForAttribute( n, elms, attr, value );
        }
    }
}

function getElementsByClass( clss ) {
    var elms = new Array();
    scanForAttribute( document, elms, "class", clss );
    return elms;
}

function currency( num ) {
    if( lang == "en" ) 
        return formatNum( parseFloat(num) / 100.0, 2 );
    
    return formatNum( num );
}

function formatNum( num, dec ) {
    var numStr = "" + parseFloat( num );
    if( numStr.indexOf("e") > 0 ) {
        numStr = "" + parseFloat( num ).toFixed( dec );
    }
    msg( "n=" + numStr );
    var i = numStr.indexOf(".");
    
    var integral = numStr;
    if( i > -1 ) integral = numStr.substr( 0, i );
    msg( "i=" + integral );
    
    var fraction = "";
    if(dec) {
        fraction = parseFloat(num-integral).toFixed( dec );
        if( fraction.substr(0,1) == "." ) fraction = "0" + fraction;
    }
    msg( "f=" + fraction );
    
    /* thousand separator every three digits */
    var newInt = "";
    var j = 0;
    for( i=integral.length-1; i>-1; i-- ) {
        var c = integral.substr( i, 1 );
        if ( j !=0 && j % 3 == 0 ) newInt = "." + newInt;
        newInt = c + newInt;
        j++;
    }

    var newNum = newInt;
    var newFrac = "";
    
    /* fix decimal places to dec number of slots */
    if( dec ) newFrac = String(fraction).substr(2,48);

    /* strip fraction if fraction has no value */
    //if( parseFloat( newFrac ) == 0 ) newFrac = "";
    msg( "nf=" + newFrac );
    
    if( newFrac != "" ) newNum = newNum + "," + newFrac;
    
    return newNum;

}

function formatNumOldToo( num, dec ) {
    var n = "";
    if( dec ) {
		n1 = Math.pow(10, dec);
		n2 = Math.round(num * n1);
		n = "" + (n2 / n1);
		i = n.indexOf(".");
		if (i >= 0)
			n = n.substr(0, i) + "," + n.substr(i + 1, n.length - 1);
    }
    else
        n = ""+Math.round( num );

    /* thousand separator every three digits */
    var f = "";
    var j = 0;
    var p = "";
    var k = n.indexOf(",");
    if( k==-1 ) {
        k = n.length-1;
    } else {
        p = n.substr(k+1, n.length);
    }
        
    for( var i=k; i>-1; i-- ) {
        var c = n.substr( i, 1 );
        if ( j != 0 && j % 3 == 0 ) f = "." + f;
        f = c + f;
        j++;
    }
    
    if(p != "") f = f + p;
    
    return f;
}

function formatNumOld( num, dec ) {
    var n = "";
    if( dec ) 
        n = ""+Math.floor( num );
    else
        n = ""+Math.round( num );
    var f = "";
    j = 0;
    dbug("formatNum: " + num + " --> " + n);
    
    /* thousand separator every three digits */
    for( var i=n.length-1; i>-1; i-- ) {
        var c = n.substr( i, 1 );
        if ( j !=0 && j % 3 == 0 ) f = "." + f;
        f = c + f;
        j++;
    }
    
    /* decimal places */
    if( dec ) {
        f += ",";
        var fr = parseFloat(num-n).toFixed( dec );
        fr = "" + parseFloat( fr ); //strip trailing zeros from fraction
        var r = fr.substr( 2, fr.length );
        f += r;
    }
    
    /* Make sure we don't get smth like 1,  */
    if (f.substr(f.length - 1, 1) == ",")
        f += "0";
   
    return f;
}

function removeChildren( node ) {
    var x = node.childNodes.length;
    for( var i=0; i<x; i++ ) {
        node.removeChild( node.childNodes[0] );
    }
}

function mouseoverTR() {
    this.className = "subRowOver";
}

function mouseoutTR() {
    if( this != currentSelectedRow[1] && this != currentSelectedRow[2] )
        this.className = "subRow";
}

function clickTR( node, p ) {
    removeClass( document.getElementById( "undirtegundir"+p+"TD" ), "focus" );
    if( currentSelectedRow[p] ) currentSelectedRow[p].className = "subRow";
    if( node != currentSelectedRow[p] ) node.className = "subRowSelected";
    currentSelectedRow[p] = node;
}

function clickTR1() {
    var p = this.getAttribute( "panel" ); /* panel number ( 1 or 2 ) */
    clickTR( this, p );
    document.getElementById( "calc"+p ).className = "notHidden";
    calculateResult( this.getAttribute( "panel" ) );
}

function clickTR2() {
    clickTR( this, 1 );
    document.getElementById( "calcInnan" ).className = "";
    document.getElementById( "calcUtan" ).className = "";
    calculateInnanb();
    calculateUtanb();
}

function clickTRCO2() {
    clickTR( this, 1 );
    document.getElementById( "calcCO2" ).className = "";
    calculateCO2();
}

function clickTRLabb() {
    clickTR( this, 1 );
    document.getElementById( "calcLabb" ).className = "";
    calculateLabb();
}

function clickTREnergyClass() {
	clickTR( this, 1 );
	document.getElementById( "calcEnergyClass" ).className = "";
	calculateEngeryClass();
}

/** calculate Unit Conversion **/
function calcUnits(src) {
    var v = document.getElementById( "i"+src ).value
    var watts = parseFloat( document.getElementById( "pwatts" ).value );
    var jules = parseFloat( document.getElementById( "pjules" ).value );
    var x = parseFloat( v.replace(",",".") );
    var r, dst;
    if( v != "" ) {
        if( src=="watts" ) {
            r = "" + parseFloat( x * watts * (3600 / jules) ).toFixed(13);
            //r = "" + parseFloat(r).toFixed(3);
            r = "" + parseFloat(r);
            dst = "jules";
        } else {
            r = "" + parseFloat( (x / 3600) * jules / watts ).toFixed(13);
            //r = "" + parseFloat(r).toFixed(3);
            r = "" + parseFloat(r);
            dst = "watts";
        }
    } else {
        r = "";
    }
    document.getElementById( "i"+dst ).value = r.replace(".",",") ;

    var p = 1;
    var vatt = document.getElementById( "iwatts" ).value.replace(",",".") * watts;
    var jule = document.getElementById( "ijules" ).value.replace(",",".") * jules;
    
    for( var i=1; i<6; i++ ) {
        var w = parseFloat( vatt / p ).toFixed(13); //toFixed keeps number in decimal format
        var j = parseFloat( jule / p ).toFixed(13);
        w = formatNum( w , 6 );
        //w = w.replace(/\./, "");
        j = formatNum(  j , 6 );
        //j = j.replace(/\./, "");
        var wa = w.split(",");
        var ja = j.split(",");
        if( wa[0]=="" ) wa[0]="0";
        if( ja[0]=="" ) ja[0]="0";
        document.getElementById( "w"+i ).innerHTML = wa[0];
        document.getElementById( "j"+i ).innerHTML = ja[0];
        var lw = wa[0].length;
        var lj = ja[0].length;
        var sw = "";
        var sj = "";
        if( parseInt(wa[1]) > 0 ) /*only add fraction if fraction has value*/
            if( lw < 3 ) /* only add fraction for numbers lower than three digits */
                sw = "," + ( wa[1]  );
        if( parseInt(ja[1]) > 0 ) 
            if( lj < 3 )
                sj = "," + ( ja[1]  );
        document.getElementById( "wf"+i ).innerHTML = sw;
        document.getElementById( "jf"+i ).innerHTML = sj;
        p *= 1000;
    }
    unitDraw();
}

/* calculate window insulation */

function setTemp (temp) {
	document.getElementById( "medalhiti" ).innerHTML = temp;
	calcGluggi();
}
function setTemp2( temp ) {
	document.getElementById( "medalhiti" ).innerHTML = temp;
    calcKlaedning();
}
function calcGluggi() {
	var insulation = new Array( 1.9, 1.7, 1.9, 1.7, 1.4, 1.2 );
    var prices = new Array( 8160, 8910, 12027, 13027, 13074, 14037 );
    var selectedGluggi = parseInt( document.getElementById( "C2" ).value );
    var selectedPrice = prices[ selectedGluggi ];
    if( firstTime ) {
        document.getElementById( "fm_verd" ).setAttribute( "value", selectedPrice );
        document.getElementById( "fm_verd" ).innerHTML = formatNum( selectedPrice );
        firstTime = false;
    }
    
	var medalhiti = parseFloat( document.getElementById( "medalhiti" ).innerHTML );
	var oskahiti = parseFloat( document.getElementById( "hiti" ).getAttribute( "value" ) );
	var ferm = parseFloat( document.getElementById( "ferm" ).getAttribute( "value" ) );
	var C1 = parseFloat( document.getElementById( "C1" ).value );
	var C2 = insulation[ selectedGluggi ];
	var year = parseFloat( document.getElementById( "year" ).getAttribute( "value" ) );
	var verd = parseFloat( document.getElementById( "verd" ).getAttribute( "value" ) );
	var A3 = ( oskahiti - medalhiti ) * 24 * 365 / 1000;
	var kwh = ( C1 - C2 ) * A3 * ferm;
	var totalKwh = kwh * year;
	var totalKr = totalKwh * verd;
	 
	document.getElementById( "total_kwh" ).innerHTML = formatNum( totalKwh );
	document.getElementById( "total_kr" ).innerHTML = formatNum( totalKr );
	
	var fmkr = parseFloat( document.getElementById( "fm_verd" ).getAttribute( "value" ) );
	var totalFmkr = ferm * ( 1900 + fmkr ); //1900 er isetningarverd pr ferm.
	var endgrTimi = totalFmkr / ( kwh * verd );
	
	document.getElementById( "total_efni" ).innerHTML = formatNum( totalFmkr );
	document.getElementById( "endurgr_timi" ).innerHTML = formatNum( endgrTimi, 1 );
}

function calcKlaedning() {
	var medalhiti = parseFloat( document.getElementById( "medalhiti" ).innerHTML );
	var oskahiti = parseFloat( document.getElementById( "hiti" ).getAttribute( "value" ) );
	var ferm = parseFloat( document.getElementById( "ferm" ).getAttribute( "value" ) );
	var Uf = parseFloat( document.getElementById( "Uf" ).value );
	var d = parseFloat( document.getElementById( "d" ).value );
	var year = parseFloat( document.getElementById( "year" ).getAttribute( "value" ) );
	var verd = parseFloat( document.getElementById( "verd" ).getAttribute( "value" ) );

	var A3 = ( oskahiti - medalhiti ) * 24 * 365 / 1000;
	var Ue = 1 / ( ( d / 0.042 ) + ( 1 / Uf ) );
	var kwh = ( Uf - Ue ) * A3 * ferm;
	
	var totalKwh = kwh * year;
	var totalKr = totalKwh * verd;
	 
	document.getElementById( "total_kwh" ).innerHTML = formatNum( totalKwh );
	document.getElementById( "total_kr" ).innerHTML = formatNum( totalKr );
}

function calculateEngeryClass() {
    var node = currentSelectedRow[1]; //the selected node from undirtegund
    
    classesBensin = new Array( 18.2, 15.3, 14.2, 12.4, 11.7, 10.4, 0.0 );
    classesDisel = new Array(  20.5, 17.3, 16.1, 14.1, 13.2, 11.9, 0.0 );
    var theClasses = classesBensin;
    if( node.getAttribute("engine") == "disel" ) 
        theClasses = classesDisel;
    
    var e = 100 / node.getAttribute( "medal" );
    
    /* hide all indicators */
    for( var i = 0; i < 7; i++ ) {
        c = "ABCDEFG".substr(i,1);
        var indicator = document.getElementById("indicator" + c);
        indicator.style.display = "none";
    }
    
    /* show the calculated indicator */
    for( var i = 0; i < 7; i++ ) {
        if( e > theClasses[i] ) {
            c = "ABCDEFG".substr(i,1);
            var indicator = document.getElementById("indicator" + c);
            indicator.style.display = "block";
            break;
        }
    }
    document.getElementById( "ecC02" ).innerHTML = "<sub>&nbsp;</sub>" + node.getAttribute( "co2" ); //dummy sub to align with previous cell
    // document.getElementById( "ecKmLtr" ).innerHTML = formatNum( 100 / node.getAttribute( "medal"), 1 ) ;
    document.getElementById( "ecInnan" ).innerHTML = formatNum( node.getAttribute( "innanb" ), 1 );
    document.getElementById( "ecUtan" ).innerHTML = formatNum( node.getAttribute( "utanb" ), 1 );
    document.getElementById( "ecBland" ).innerHTML = formatNum( node.getAttribute( "medal" ), 1);
}
    
/* this is just a nicety for browsers that can */ 
function unitDraw() {
    var ut = document.getElementById( "unitsTable" );
    var st = document.getElementById( "unitsTableSum" );
    var w = ut.clientWidth;
    var h = ut.clientHeight;
    var c = document.getElementById( "unitbox" );
    if(c) {
        c.setAttribute("width", w);
        c.setAttribute("height", h);
    }
    var ctx;
    try {
      ctx = c.getContext("2d");
    } catch(e) { return; }
    ctx.clearRect( 0,0,w,h );
    ctx.strokeStyle = "gray";
    ctx.beginPath();
    ctx.moveTo( 5, 1 );
    ctx.lineTo( w-5, 1 );
    ctx.lineTo( w-1, 5 );
    ctx.lineTo( w-1, h-5 );
    ctx.lineTo( w-5, h-1 );
    ctx.lineTo( 5, h-1 );
    ctx.lineTo( 1, h-5 );
    ctx.lineTo( 1, 5 );
    ctx.lineTo( 5, 1 );
    ctx.moveTo( 1, h - st.clientHeight - 10 );
    ctx.lineTo( w, h - st.clientHeight - 10 );
    ctx.stroke();
}

/** calculate labb **/
function calculateLabb() {
    var node = currentSelectedRow[1];
	var t = document.getElementById( "times" ).getAttribute( "value" );
	var d = document.getElementById( "distance" ).getAttribute( "value" );
	
    /* utblastur kg */
    var u = t * d * node.getAttribute( "co2" ) / 1000;
    document.getElementById( "co2" ).innerHTML = formatNum( u, 1 );
    
     /* eydsla */
    var e = t * d * node.getAttribute( "medal" ) / 100;
    document.getElementById( "fuel" ).innerHTML = formatNum( e, 1 );
    
    /* kostnadur - 'engine' denotes bensin or disel */
    var k = document.getElementById( node.getAttribute( "engine" ) ).getAttribute( "value" ) * e;
    document.getElementById( "saving" ).innerHTML = currency( k );

	/* kaloriur - gengid */
	var w = document.getElementById( "weight" ).getAttribute( "value" );
	var kal = t * ((( 3.785 * 3.5 * w ) / 200 ) * 12 ) * d;
	document.getElementById( "walk" ).innerHTML = formatNum( kal );
	
	/* kaloriur - hjolad */
	kal = t * ((( 8.059 * 3.5 * w ) / 200 ) * 3 ) * d;
	document.getElementById( "cycle" ).innerHTML = formatNum( kal );
}

/** calculate CO2 emission and binding **/
function calculateCO2() {
    var node = currentSelectedRow[1];
    dbug( node )
    /* utblastur kg */
    var u = document.getElementById( "akstur" ).getAttribute( "value" ) * node.getAttribute( "co2" ) / 1000;
    document.getElementById( "utblastur" ).innerHTML = formatNum( u, 0 );
    dbug( u )
    
    /* hektarar */
    var h = parseFloat(u) / 4404;
    document.getElementById( "hekt" ).innerHTML = formatNum( h, 1 );
    
    /* tre */
    var t = h * 2200;
    document.getElementById( "tre" ).innerHTML = formatNum( t, 0 );

}

/** calculate for comparing results **/
function calculateResult( p ) {
    var node = currentSelectedRow[p];
    if( !node ) return;
    var y = parseInt( document.getElementById( "years" ).getAttribute( "value" ) );
    document.getElementById( "ar"+p ).innerHTML = y;
    
    /* eydsla */
    var e = y * document.getElementById( "akstur" ).getAttribute( "value" ) * node.getAttribute( "medal" ) / 100;
    document.getElementById( "eydsla"+p ).innerHTML = formatNum( e );

    /* kostnadur - 'engine' denotes bensin or disel */
    var k = document.getElementById( node.getAttribute( "engine" ) ).getAttribute( "value" ) * e;
    document.getElementById( "kostnadur"+p ).setAttribute( "value", k );
    document.getElementById( "kostnadur"+p ).innerHTML = currency( k );

    /* utblastur */
    var u = y * document.getElementById( "akstur" ).getAttribute( "value" ) * node.getAttribute( "co2" ) / 1000000;
    document.getElementById( "utblastur"+p ).setAttribute( "value", u );
    document.getElementById( "utblastur"+p ).innerHTML = formatNum( u, 1 );
    
    /* bifreidargjald */
    var t = node.getAttribute( "kg" );
    var a = 999 - t < 0 ? 999 : t;
    var b = 999 - t < 0 ? t - 999 : 0;
    var gjald = (( a * 6.83 ) + ( b * 9.21 )) * 2 * y ;
    if( lang == "en" ) gjald = 0;
    document.getElementById( "bifrgj"+p ).setAttribute( "value", gjald );
    document.getElementById( "bifrgj"+p ).innerHTML = formatNum( gjald );
    
    /* mismunur */
    var alls1 = parseInt( document.getElementById( "kostnadur1" ).getAttribute( "value" ) ) + parseInt( document.getElementById( "bifrgj1" ).getAttribute( "value" ) );
    var alls2 = parseInt( document.getElementById( "kostnadur2" ).getAttribute( "value" ) ) + parseInt( document.getElementById( "bifrgj2" ).getAttribute( "value" ) );
    var mismKostn = Math.abs( alls1 - alls2 );
    var k1 = parseFloat( document.getElementById( "utblastur1" ).innerHTML.replace( ",","." ) );
    var k2 = parseFloat( document.getElementById( "utblastur2" ).innerHTML.replace( ",","." ) );
    
    if( k2 > 0 ) 
        document.getElementById( "bottom" ).className = "";
    else
        document.getElementById( "bottom" ).className = "hidden";
        
    var mismUtblast = Math.abs( k1 - k2 );
//    var mismUtblast = Math.abs( document.getElementById( "utblastur1" ).getAttribute( "value" ) - document.getElementById( "utblastur2" ).getAttribute( "value" ) );
    
    var suffix = " kr ";
    if( lang == "en" ) suffix = " &euro;";
    document.getElementById( "diffKostn" ).innerHTML = currency( mismKostn ) + suffix;
    suffix = " tonn";
    if( lang == "en" ) suffix = " tons";
    document.getElementById( "diffUtblast" ).innerHTML = formatNum( mismUtblast, 1 ) + suffix;
}

function calculateInnanb() {
    var node = currentSelectedRow[1];
    
    var d = document.getElementById( "distance" ).getAttribute( "value" );

    /* eydsla */
    var e = d * node.getAttribute( "innanb" ) / 100;

    /* kostnadur - 'engine' denotes bensin or disel */
    var k = document.getElementById( node.getAttribute( "engine" ) ).getAttribute( "value" ) * e;
    document.getElementById( "kostnadurInnanb" ).innerHTML = currency( k );

    /* utblastur */
    var u = document.getElementById( "distance" ).getAttribute( "value" ) * node.getAttribute( "co2" ) / 1000;
    document.getElementById( "utblasturInnanb" ).innerHTML = formatNum( u, 1 );
}

function calculateUtanb() {
    var node = currentSelectedRow[1];
    
    /* vegalengd */
    var r = theRoads[ selectedArrive ];
    var dp = selectedDepart + 1;
    var d = r[ dp ];
    document.getElementById( "distanceUtanb" ).innerHTML = formatNum( d );
    
    /* eydsla */
    var e = d * node.getAttribute( "utanb" ) / 100;

    /* kostnadur - 'engine' denotes bensin or disel */
    var k = document.getElementById( node.getAttribute( "engine" ) ).getAttribute( "value" ) * e;
    document.getElementById( "kostnadurUtanb" ).innerHTML = currency( k );

    /* utblastur */
    var u = d * node.getAttribute( "co2" ) / 1000;
    document.getElementById( "utblasturUtanb" ).innerHTML = formatNum( u, 1 );    
}

function tegundirChange( node, action ) {
//    document.getElementById( node.id+"TD" ).className = "";
    removeClass( document.getElementById( node.id+"TD" ), "focus" );
    var engine = "";
    var p = node.id.substr( node.id.length - 1, 1 ); /* panel number */
   
    /* get the data for this tegund */
    var data = new Array();
    for( var i in theSubCars ) {
        if( theSubCars[i][10] == node.value ) {
            data.push( theSubCars[i] );
        }
    }
    
    /* create table and headers */
    var ths;
    if( lang=="is")
        ths = new Array( "Undirtegund", "Vél", "Skipting", "Slagrými" );
    else
        ths = new Array( "Type", "Engine", "Transm.", "Cubic cm" );
        
    //var tbl = document.createElement( "table" );
    var tbl = document.getElementById( "undirtegundir"+p );
//    document.getElementById( tbl.id+"TD" ).className = "focus";
    addClass( document.getElementById( tbl.id+"TD" ), "focus" );
    removeChildren( tbl );
    var tr = document.createElement( "tr" );
    for( var i=0; i<ths.length; i++ ) {
        var th = document.createElement( "th" );
        th.innerHTML = ths[i];
        th.className = "small";
        tr.appendChild( th );
    }
    tbl.appendChild( tr );
    
    /* create data */
    for( var i in data ) {
        tr = document.createElement( "tr" );
        tr.onmouseover = mouseoverTR;
        tr.onmouseout = mouseoutTR;
        tr.onclick = action;
        tr.className = "subRow";
        tr.setAttribute( "panel", p );
    
        var td = document.createElement( "td" );
        td.innerHTML = data[i][0];
        td.className = "small";
        tr.appendChild( td );
        
        td = document.createElement( "td" );
        var str = data[i][1];
        var e = str.substr( 1, 1 );
        if( e == "B" )
            engine = "bensin";
        else if( e == "D" )
            engine = "disel";
        else if( e == "H" )
        	engine = "bensin";
        tr.setAttribute( "engine", engine );
        
        str = str.replace( "B", document.getElementById( "bensin_"+lang ).innerHTML );
        str = str.replace( "D", document.getElementById( "disel_"+lang ).innerHTML );
        str = str.replace( "H", "Hybrid" );
        str = str.replace( "(", " " );
        str = str.replace( ")", "" );
        td.innerHTML = str;
        td.className = "small";
        tr.appendChild( td );
    
        td = document.createElement( "td" );
        str = data[i][2];
        if( str.indexOf( "B" ) > -1 )
            str = str.replace( "B", document.getElementById( "beinskiptur_"+lang ).innerHTML );
        else
            str = str.replace( "S", document.getElementById( "sjalfskiptur_"+lang ).innerHTML );
        str = str.replace( "(2)", "" );
        str = str.replace( "(3)", "" );
        str = str.replace( "(4)", "" );
        str = str.replace( "(5)", "" );
        str = str.replace( "(6)", "" );
        str = str.replace( "(7)", "" );
        td.innerHTML = str;
        td.className = "small";
        tr.appendChild( td );
    
        tr.setAttribute( "co2", data[i][3] );
        tr.setAttribute( "innanb", data[i][4] );
        tr.setAttribute( "utanb", data[i][5] );
        tr.setAttribute( "medal", data[i][6] );
        tr.setAttribute( "kg", data[i][9] );
        
        td = document.createElement( "td" );
        td.innerHTML = data[i][7] + "<small>cm<sup>3</sup></small>";
        td.className = "small";
        tr.appendChild( td );
        
        /*
        td = document.createElement( "td" );
        td.appendChild( document.createTextNode(  data[i][9] + "kg" ) );
        tr.appendChild( td );
        */
        
        tbl.appendChild( tr );
    }
    
    node.blur();
}

function tegChange1() {
    tegundirChange( this, clickTR1 );
    //document.getElementById( "calc1" ).className = "hidden";
}

function tegChange2() {
    tegundirChange( this, clickTR2 );
    document.getElementById( "calcInnan" ).className = "hidden";
    document.getElementById( "calcUtan" ).className = "hidden";
}

function tegChangeCO2() {
    tegundirChange( this, clickTRCO2 );
    document.getElementById( "calcCO2" ).className = "hidden";
}

function tegChangeLabb() {
    tegundirChange( this, clickTRLabb );
    document.getElementById( "calcLabb" ).className = "hidden";
}

function tegChangeEnergyClass() {
	tegundirChange( this, clickTREnergyClass );
	document.getElementById( "calcEnergyClass" ).className = "hidden";
}

function framleidendurChange( node, action ) {
//    document.getElementById( node.id+"TD" ).className = "";
    removeClass( document.getElementById( node.id+"TD" ), "focus" );
    var val = node.value;
    var p = node.id.substr( node.id.length - 1, 1 ); /* panel number */
    msg( "&lt;"+val+"&gt;" );
    var sel = document.getElementById( "tegPopup"+p );
    sel.focus();
//    document.getElementById( sel.id+"TD" ).className = "focus";
    addClass( document.getElementById( sel.id+"TD" ), "focus" );
    
    removeChildren( sel );
    sel.onchange = action;
    sel.className = "";
    var opt = document.createElement( "option" );
    opt.value = "xxx"
    opt.innerHTML = document.getElementById( "tegund_"+lang ).innerHTML;
    sel.appendChild( opt );
    
    for( var i=0; i<tegundir.length; i++ ) {
        var f = tegundir[ i ];
        if( f[0].indexOf( node.value ) > -1 ) {
            opt = document.createElement( "option" );
            opt.innerHTML = f[1];
            opt.value = f[2];
            sel.appendChild( opt );
        }
    }
    removeChildren( document.getElementById( "undirtegundir"+p ) );
}

function frmlChange1() {
    framleidendurChange( this, tegChange1 );
   // document.getElementById( "calc1" ).className = "hidden";
}

function frmlChange2() {
    framleidendurChange( this, tegChange2 );
    document.getElementById( "calcInnan" ).className = "hidden";
    document.getElementById( "calcUtan" ).className = "hidden";
}

function frmlChangeCO2() { //kolefnisreiknir
    framleidendurChange( this, tegChangeCO2 );
}

function frmlChangeLabb() { //göngutúrareiknir
    framleidendurChange( this, tegChangeLabb );
}

function frmlChangeEnergyClass() { //energy class reiknir
	framleidendurChange( this, tegChangeEnergyClass );
	document.getElementById( "calcEnergyClass" ).className = "hidden";
}

function installBtns( action ) {
   // if( document.images ) {
        btns[0] = new Image;
        btns[0].src = imgRoot + "btnUp1.gif";
        btns[1] = new Image;
        btns[1].src = imgRoot + "btnUp2.gif";
        btns[2] = new Image;
        btns[2].src = imgRoot + "btnDown1.gif";
        btns[3] = new Image;
        btns[3].src = imgRoot + "btnDown2.gif";
   // }

    var b = getElementsByClass( "btn" );
    for( var i=0; i<b.length; i++ ) {
        b[i].onclick = action;
        b[i].onmousedown = btnDown;
        b[i].onmouseup = btnUp;
        var img = document.createElement( "img" );
        var s = btns[ b[i].getAttribute( "btnID" ) ].src;
        img.src = s;
        b[i].appendChild( img );
    }
}

function btnDown() {
    var b = parseInt( this.getAttribute( "btnID" ) ) + 1;
    this.firstChild.src = btns[ b ].src;
}

function btnUp() {
    var b = this.getAttribute( "btnID" );
    this.firstChild.src = btns[ b ].src;
}

function doClick( btn ) {
    var t = document.getElementById( btn.getAttribute( "target" ) );
    var i = parseInt( btn.getAttribute( "inc" ) );
    var v = parseInt( t.getAttribute( "value" ) );
    var m = parseInt( t.getAttribute( "min" ) );
    v += i;
    if( v < m ) v = m;
    t.setAttribute( "value", v );
    if( t.getAttribute( "type" ) == "currency" )
        t.innerHTML = currency( v );
    else
        t.innerHTML = formatNum( v );
}

function btnClick1() {
    doClick( this );
    calculateResult( 1 );
    calculateResult( 2 );
}

function btnClick2() {
    doClick( this );
    calculateInnanb();
    calculateUtanb();
}

function btnClickCO2() {
    doClick( this );
    calculateCO2();
}

function btnClickLabb() {
    doClick( this );
    calculateLabb();
}

function btnClickGluggar() {
	doClick( this );
	calcGluggi();
}
function btnClickKlaedning() {
    doClick( this );
    calcKlaedning();
}
function btnClickEngergyClass() {
	doClick( this );
	calculateEngeryClass();
}
function changeDepart() {
    msg( "depart: " + this.value );
    selectedDepart = parseInt( this.value );
    calculateUtanb();
}

function changeArrive() {
    msg( "arrive: " + this.value );
    selectedArrive = parseInt( this.value );
    calculateUtanb();
}

/** install car data
** count is number of cars ( 2 for compare, 1 for others )
** action is the function to call at onchange for selection menu
**/
function init1( count, action ) {
    try { lang = document.getElementById( "currentLanguage" ).innerHTML; } catch (e) {}
    var pFramleidandi, pTegund, pUndirtegund;
    var tegundID = 0;
    var theCars = document.getElementById( "cars" ).innerHTML.split( "/" );
    
    for( var i=0; i<theCars.length; i=i+12 ) {
        var framleidandi = trimString(theCars[i]);
        var tegund = theCars[i+1];
        var undirtegund = theCars[i+2];
        var vel = theCars[i+3];
        var skipting = theCars[i+4];
        var co2 = theCars[i+5];
        var innanb = theCars[i+6];
        if( innanb ) innanb = innanb.replace(",",".");
        var utanb = theCars[i+7];
        if( utanb ) utanb = utanb.replace(",",".");
        var medal = theCars[i+8];
        if( medal) medal = medal.replace(",", ".");
        var cm2 = theCars[i+9];
        var kw = theCars[i+10];
        var kg = theCars[i+11];
        if( framleidandi != pFramleidandi ) {
            framleidendur.push( framleidandi );
            msg("Pushing: " + framleidandi + "(" + pFramleidandi + ")");
            pFramleidandi = framleidandi;
        }
        if( tegund != pTegund ) {
            var a = new Array();
            a.push( framleidandi );
            a.push( tegund );
            a.push( tegundID + 1 );
            tegundir.push( a );
            tegundID++;
        }
        subCars = new Array();
        
        subCars.push( undirtegund );
        subCars.push( vel );
        subCars.push( skipting );
        subCars.push( co2 );
        subCars.push( innanb );
        subCars.push( utanb );
        subCars.push( medal );
        subCars.push( cm2 );
        subCars.push( kw );
        subCars.push( kg );
        subCars.push( tegundID );
        theSubCars.push( subCars );
        pFramleidandi = framleidandi;
        pTegund = tegund;
    }
    
    /* create producer's popup menu */
    for( var p=1; p < count + 1; p++ ) {
        msg( p );
        var d = document;
        var sel = d.getElementById( "framleidendur"+p );
        var opt = d.createElement( "option" );
        opt.innerHTML = document.getElementById( "framleidandi_"+lang ).innerHTML;
        opt.setAttribute( "value", "null" );
        sel.appendChild( opt );
        sel.value = "xxx";
        sel.onchange = action;
        for( var i=0; i<framleidendur.length; i++ ) {
            opt = d.createElement( "option" );
            txt = d.createTextNode( framleidendur[i] );
            opt.value = framleidendur[i];
            opt.appendChild( txt );
            sel.appendChild( opt );
        }
    }
    
    msg( "ready" );
}

function init2() {
    
    /* install roads and distances */
    var d = document.getElementById( "roads" ).innerHTML.split( "|" );
    /* read columns */
    var c = d[0].split( "/" );
    var sel = document.getElementById( "depart" );
    sel.onchange = changeDepart;
    for(var i in c ) {
        depart.push( c[i] );
        var opt = document.createElement( "option" );
        opt.value = i;
        opt.innerHTML = c[i];
        sel.appendChild( opt );
    }
    
    /* read rows and distances */
    var r = d[1].split( "*" );
    sel = document.getElementById( "arrive" );
    sel.onchange = changeArrive;
    for(var i in r ) {
        var t = r[i].split( "/" );
        theRoads.push( t );
        var opt = document.createElement( "option" );
        opt.value = i;
        opt.innerHTML = t[0];
        sel.appendChild( opt );
    }
}

function trimString(sInString) {
  sInString = sInString.replace( /^\s+/g, "" );// strip leading
  return sInString.replace( /\s+$/g, "" );// strip trailing
}