var heating_sources = Array();

var heat_source_unit = '';
var heat_source_price = '';
var heat_source_name = '';
var heat_source_co2 = '';
var heat_source_price_user = '';
var heat_lost_per_unit = '';
var varme_tab = '';
var region = '';
var region_name ='';
var current_element = '';
var current_element_name = '';
var construction_thickness = {};
var product_thickness = {};
var matrix = {};
var selected_product = false;
var selected_product_name = '';
var selected_product_image = '';
var dbstr = '';
var constructions = {};
var products = {};
var computations = [];

function choose_heating_source(list)
{
    heat_source_unit = '';
    heat_source_price = '';
    heat_lost_per_unit = '';
    heat_source_co2 = '';

    var id = list.options[list.selectedIndex].value;
    if(id == '__none__') return;

    heat_source_name = list.options[list.selectedIndex].text;

    for(var i=0;i< heating_sources.length;i++)
    {
      if( id == heating_sources[i].id )
      {
        heat_source_unit = heating_sources[i].heat_source_unit;
        heat_source_price = heating_sources[i].heat_source_price;
        heat_lost_per_unit = heating_sources[i].heat_lost_per_unit;
        heat_source_co2 = heating_sources[i].heat_source_co2;
      }
    }

    document.getElementById('energy_price').style.display='block';
    field_by_name('energy_source_price').value = heat_source_price;
    document.getElementById('energy_unit').innerHTML = heat_source_unit;
    document.getElementById('heat_source_unit').innerHTML=heat_source_unit;
}
function field_by_name(name)
{
    return document.myform[name];
}
function update_energy_source_price(field)
{
    if(!check_int(field))
    {
        field.value = heat_source_price;
        return;
    }
    heat_source_price_user = field.value;  
}
function check_int(field)
{
    if( isNaN( parseInt( field.value ) ) )
    {
      return false; 
    }
    return true
}
function is_blank(s)
{
    if(s=='' || s == undefined) return;
    for(var i=0;i<s.length;i++)
    {
      var c = s.charAt(i);
      if(( c !=' ') && ( c!='\n') && ( c!='\t')) return false;
    }
    return true;
}
function load_element(element_id,cc)
{
    document.getElementById('house').style.display='none';
    document.getElementById('overview').style.display='none';
    document.getElementById('co2').style.display='none';
    document.getElementById('element_panel').style.display='block';

    current_element = element_id;
    current_element_name = constructions[element_id]['parent_name'];
    current_element_label = constructions[element_id]['name'];

    set_construction_name(element_id);
    clear_construction_area(); 
    load_construction_thickness(element_id);
    load_products(element_id,cc);
}
function load_construction_thickness(element_id)
{
    var tk = construction_thickness[element_id];
    var opt = document.myform.thickness.options;
    clear_option(opt);
    for(var i=0;i < tk.length;i++)
    {
        opt[opt.length] = new Option(tk[i]['thickness'], tk[i]['u_value']);
    }
}
function clear_option(list)
{
    for (x = list.length; x >= 0; x--) list[x] = null;
}
function clear_construction_area()
{
    document.myform.area.value = '';
}
function set_construction_name(element_id)
{
    document.getElementById('top_sub_heading').innerHTML = document.getElementById('tr_savings').innerHTML +' - '+ constructions[element_id]['name'];
    document.getElementById('construction_area').innerHTML = constructions[element_id]['area_label'];
    document.getElementById('thickness_of_existing_pipes').style.display='none';
    document.getElementById('thickness_of_existing').style.display='';
    document.getElementById('areal_unit').style.display='';
    document.getElementById('pipe_unit').style.display='none';

    if(current_element_is_pipe()) 
    {
        document.getElementById('thickness_of_existing_pipes').style.display='';
        document.getElementById('thickness_of_existing').style.display='none';

        document.getElementById('areal_unit').style.display='none';
        document.getElementById('pipe_unit').style.display='';
    }
}
function load_choose_element()
{
    document.getElementById('top_sub_heading').innerHTML = document.getElementById('tr_choose_construction').innerHTML; 
    document.getElementById('element_panel').style.display='none';
    document.getElementById('overview').style.display='none';
    document.getElementById('house').style.display='block';

    document.myform.savings.value='';
    document.myform.amounts.value='';
    document.myform.material_expences.value='';
    document.myform.roi_time.value='';
}
function load_overview()
{
    str = document.getElementById('tr_savings').innerHTML +' - ';
    str+= document.getElementById('tr_opsumering').innerHTML;
    document.getElementById('top_sub_heading').innerHTML = str;
    document.getElementById('element_panel').style.display='none';
    document.getElementById('overview').style.display='block';
    
    render_energy_overview();
    render_constructions();
    render_total();
}

function render_constructions()
{
    var c = ''; 

    for(var i=0;i<computations.length;i++)
    {
        c+='<h3>'+ computations[i]['construction'] +'</h3>';

        if(computations[i]['product_image'] != '')
        {
            c+= '<img src="'+ computations[i]['product_image'] +'" align="right" style="margin-right:50px;margin-top:30px" onload="control_size(this,150)" />';
        }

        c+='<table cellpadding="4" class="overview_item" cellspacing="0" border="0">';
        if(computations[i]['is_pipe'])
        {

            c+='<tr><td valign="top" width="220">';
            c+= constructions[computations[i]['construction_id']]['area_label'];
            c+=':</td><td valign="top">'+ computations[i]['areal'] +' m</td></tr>';
        }
        else
        {
            c+='<tr><td valign="top" width="220">'+ trans('tr_area') +':</td><td valign="top">'+ computations[i]['areal'] +' m<sup>2</sup></td></tr>';
        }
        c+='<tr><td valign="top">'+ trans('tr_existing_insulation') +':</td><td valign="top">'+ computations[i]['existing_isolation']+' mm</td></tr>'; 
        c+='<tr><td valign="top">'+ trans('tr_product') +':</td><td valign="top">'+ computations[i]['product'] +'</td></tr>';
        c+='<tr><td valign="top">'+ trans('tr_insulation_thickness') +':</td><td valign="top">'+ rounding(computations[i]['new_isolation']) +' mm</td></tr>';

        c+='<tr><td valign="top">'+ trans('tr_saved_energy') +':</td><td valign="top">'+ rounding(computations[i]['energy']) +' '+ heat_source_unit +'</td></tr>';
        c+='<tr><td valign="top">'+ trans('tr_besparet_udgift') +':</td><td valign="top">'+ rounding(computations[i]['price']) +' '+ trans('country_currency') +'</td></tr>'; 
        c+='<tr><td valign="top">'+ trans('tr_material_price') +':</td><td valign="top">'+ rounding(computations[i]['product_price']) +' '+ trans('country_currency') +'</td></tr>'; 
        c+='<tr><td valign="top">'+ trans('tr_samlet_roi') +':</td><td valign="top"> '+  rounding( computations[i]['roi']) +' '+ trans('tr_years') +'</td></tr>';
        c+='</table><br>';

    }

    document.getElementById('overview_konstructioner').innerHTML=c;
}
function rounding(n)
{
    return Math.round( n * 100)/ 100;
}
function render_total()
{
    var total_energy_saved = 0;
    var total_money_saved = 0;
    var total_product_price = 0;
    var total_roi = 0;

    for(var i=0;i<computations.length;i++)
    {
        total_energy_saved += computations[i]['energy'];
        total_money_saved += computations[i]['price'];
        total_product_price += computations[i]['product_price'];
    }
    document.getElementById('total_energy_saved').innerHTML =  rounding(total_energy_saved);
    document.getElementById('total_energy_saved_source_unit').innerHTML =  heat_source_unit;
    document.getElementById('total_money_saved').innerHTML = total_money_saved;
    document.getElementById('total_product_price').innerHTML = total_product_price;

    //total_roi = total_money_saved / total_product_price;
    total_roi = total_product_price / total_money_saved;
    document.getElementById('total_roi').innerHTML = rounding(total_roi);
    
    render_co2(total_energy_saved,true);
}
function roundophundred(n)
{
    n = parseInt(n);
    return ( n + 100) - (n % 100);
}
function render_co2(n,istotal)
{
    var el_name ='co2';
    el_name += (istotal)?'total':'';
    var el_value = el_name +'value';

    if(isNaN(pFloat(heat_source_co2))) heat_source_co2 = 0;
    
    var hsc = pFloat(heat_source_co2);
    var n = pFloat(n);
    var co = n * hsc;
    co = roundophundred(co);

    var el = document.getElementById(el_name);
    el.style.display = (heat_source_co2==0)? 'none':'';

    document.getElementById(el_value).innerHTML = co;
}
function render_energy_overview()
{
   document.getElementById("heat_source_name").innerHTML = heat_source_name;
   price = heat_source_price;
   if(!isNaN(pFloat(heat_source_price_user))) price = heat_source_price_user;
   document.getElementById("overview_energy_price").innerHTML = price;
   document.getElementById("overview_heat_source_unit").innerHTML = heat_source_unit;

   if(region_name !='') 
   {
    document.getElementById("region_label").innerHTML = document.getElementById('tr_region').innerHTML +':';
    document.getElementById("region_name").innerHTML = region_name;
   }
}

function control_size(img,width)
{
    if(img.src.indexOf('transp.gif') != -1) img.width = 5;
    else 
    {
      if(img.width > width) img.width = width;
    }
}
function load_products(element_id,cc)
{
    var prods = products[element_id];
    var pt = TABLE({'border':'0','cellpadding':'0','cellspacing':'0'});
    var ptb = TBODY(null);
    for(var i=0;i<prods.length;i++)
    {
       str = '\nid:'+ prods[i]['id'];
       str+= '\nname:'+ prods[i]['name'];
       str+= '\ndescription:'+ prods[i]['description'];
       str+= '\nlink:'+ prods[i]['link'];
       str+= '\nlink_label:'+ prods[i]['link_label'];
       str+= '\nlink_method:'+ prods[i]['link_method'];
       str+= '\nlink_method_label:'+ prods[i]['link_method_label'];
       str+= '\nproduct_image:'+ prods[i]['image_path'];

       prod = DIV({'class':'product_panel'},
                     INPUT({'type':'radio',
                            'name':'product_list',
                            'class':'product_list',
                            'id':'radio_'+ prods[i]['id'],
                            'value':prods[i]['id'],
                            'onclick':'load_product('+ prods[i]['id'] +')'}),
                     A({'href':'javascript:load_product('+ prods[i]['id'] +')',
                        'class':'product_name',
                        'id':'product_'+ prods[i]['id']},prods[i]['name'])
                    );

       if(prods[i]['description']) prod.appendChild( P({'id':'p_desc_'+ prods[i]['id']}) );

       if(prods[i]['link'] && prods[i]['link_label'])
       {
        prod.appendChild( DIV(null,
                          A({'href':prods[i]['link'],'target':'_blank'},
                          double_arrow() + prods[i]['link_label']) ) );
       }
       if(prods[i]['link_method'] && prods[i]['link_method_label'])
       {
        prod.appendChild( DIV(null,
                              A({'href':prods[i]['link_method'],'target':'_blank'},
                              double_arrow() + prods[i]['link_method_label']) ) );
       }
       p_img = '';
       if(prods[i]['image_path'])
       {
            p_img = IMG({'src':'../media/'+ cc +'/'+ prods[i]['image_path'],
                                'align':'right',
                                'id':'product_image_'+ prods[i]['id'] });
       }


       prod = TABLE({'border':'0','cellpadding':'0','cellspacing':'0'},
                        TBODY(null,
                                TR(null,
                                    TD({'valign':'top'},prod),
                                    TD(null,p_img)
                                )
                             )
                     );

       cell = TD({'valign':'top'},prod);
       c_row = TR(null,cell);
       c_row.appendChild(cell);
       ptb.appendChild(c_row);
    }

    pt.appendChild(ptb);
    replaceChildNodes('products',pt);

    for(var i=0;i<prods.length;i++)
    {
       id = 'product_desc_'+ prods[i]['id'];
       desc = document.getElementById(id);
       desc = desc.innerHTML;
       if(prods[i]['description']) document.getElementById('p_desc_'+ prods[i]['id']).innerHTML = desc; 
    }

    var opt = document.myform.product_amount.options;
    clear_option(opt);
    
    if(prods.length < 1) return;
    var el = document.getElementById('radio_'+ prods[0]['id'])
    if(el) el.checked = true;
    load_product(prods[0]['id']);
}
function load_product(p_id)
{
    var rs = getElementsByTagAndClassName('INPUT','product_list');
    for(var i=0;i< rs.length;i++) rs[i].checked = (p_id == rs[i].value);
    load_product_thickness(p_id);
    selected_product = p_id;
    selected_product_name = document.getElementById('product_'+ p_id).innerHTML;
    var el = document.getElementById('product_image_'+ p_id);
    if(el) selected_product_image = el.src;
}
function get_product_values(thickness)
{
    var p_data = product_thickness[selected_product];
    for(var i=0;i<p_data.length;i++)
    {
        if(p_data[i]['thickness'] == parseInt(thickness) ) return p_data[i];
    }
}
function load_product_thickness(p_id)
{
    var opt = document.myform.product_amount;
    clear_option(opt);
    opt[opt.length] = new Option('','__none__');
    var p_t= product_thickness[p_id];
    for(var i=0;i<p_t.length;i++)
    {
        opt[opt.length] = new Option(p_t[i]['thickness'],p_t[i]['thickness']);
    }
}
function double_arrow()
{
    return document.getElementById('double_arrow_right').innerHTML;
}
function choose_region(list)
{
    var v = list.options[list.selectedIndex].value;    
    region_name = list.options[list.selectedIndex].text;    
    document.myform.region.value= v;
}
function load_selected_heating_values()
{
    var opt = document.myform.heating_source;
    var id = opt.options[opt.selectedIndex].value;
    heat_source_name = opt.options[opt.selectedIndex].text;

    for(i=0;i<heating_sources.length;i++)
    {
      if( id == heating_sources[i]['id'] )
      {
        heat_lost_per_unit = heating_sources[i]['heat_lost_per_unit'];
        heat_source_price = heating_sources[i]['heat_source_price'];
        heat_source_unit = heating_sources[i]['heat_source_unit'];
      }
    }
}
function compute_energy_values()
{
    if(!check_region_selected() || !check_heat_source_selected()) return;
    load_selected_heating_values(); 

    region = pFloat(document.myform.region.value);
    forbruget = pFloat(heat_lost_per_unit);
    varme_tab = pFloat(heat_lost_per_unit);

    dbg = '';
    dbg += 'region: '+ region +'\n\n';
    dbg += 'usage: '+ forbruget +'\n\n';
    dbg += 'heat loss: '+ varme_tab +'\n\n';
    var graddogn = region * 24;

    dbg += graddogn + ' (graddogn) ='+ region +' (region) * 24 \n\n';
    var m1 = graddogn / forbruget;
    var m2 = m1 / 1000;
    heat_lost_per_unit = Math.round(m2 * 100) / 100;

    dbg += heat_lost_per_unit +' (heat lost per unit) = ('+ graddogn +' (graddogn) / ';
    dbg += forbruget +' (forbruget = density * efficiency * calorific_value) )/ 1000 ';

    document.getElementById('house').style.display='block';
    document.getElementById('energy_source').style.display='none';

    document.getElementById('debug').value += dbg;
}
function current_element_is_pipe()
{
    return (current_element_name.indexOf('pipe') > -1);
}
function u_value_from_matrix(existing_insulation,new_insulation)
{
   var m= matrix[selected_product]; 
   if(!m) return;
   for(var i=0;i<m.length;i++)
   {
    if(m[i]['existing_insulation'] == existing_insulation )
    {
       if(m[i]['new_insulation'] == new_insulation ) return m[i]['u_value'];
    }
   }
   return
}
function check_values(saving)
{
    var dbg = '';
    var construction_area = document.myform.area.value;
    if(isNaN( parseInt( construction_area ) ) ) return;


    var opt = document.getElementById("thickness");
    if(opt.selectedIndex < 0) return;
    var existing_insulation_u_value = opt[opt.selectedIndex].value;
    var existing_insulation_thickness = opt[opt.selectedIndex].text;
    if(existing_insulation_u_value == '__none__') return;

    var opt = document.getElementById("product_amount");
    if(opt.selectedIndex < 0) return;

    var new_insulation = opt[opt.selectedIndex].value;
    if(new_insulation=='__none__') return;
    
    construction_area = pFloat(construction_area);
    existing_insulation_thickness = pFloat(existing_insulation_thickness);
    existing_insulation_u_value = pFloat(existing_insulation_u_value);

    dbg = 'Area:'+ construction_area +'\n\n';
    dbg+= 'Existing insulation thickness:'+ existing_insulation_thickness +'\n\n';
    dbg+= 'Existing insulation u-value:'+ existing_insulation_u_value +'\n\n';

    total_thickness = pFloat(new_insulation);
    if(!current_element_is_pipe()) total_thickness += existing_insulation_thickness;

    
    var new_insulation_u_value = u_value_from_matrix(existing_insulation_thickness,new_insulation);
    if(!new_insulation_u_value) return;
    new_insulation_u_value = pFloat(new_insulation_u_value);

    dbg+= 'Total thickness:'+ total_thickness +'\n\n';
    dbg+= 'New insulation u-value:'+ new_insulation_u_value +'\n\n';

    if( current_element_is_pipe() )
    {
        heating_savings = ( pFloat(new_insulation_u_value) * construction_area * 8760) / 1000;
        heating_savings = heating_savings / varme_tab;
    }
    else
    {
        insulation = existing_insulation_u_value - new_insulation_u_value;
        heating_savings = heat_lost_per_unit * insulation * construction_area;
        heating_savings = heat_lost_per_unit * ( existing_insulation_u_value - new_insulation_u_value ) * construction_area;
        heating_savings = heat_lost_per_unit * insulation * construction_area;
    }

    /*
    
    dbg += ( Math.round(insulation * 100) /100 ) +' (Insulation) ='+ existing_insulation_u_value +' (Existing u-value) - ';
    dbg += new_insulation_u_value +' (new u-value) \n\n'; 
    dbg += ( Math.round(heating_savings * 100 ) /100) +' (heating savings)='+ heat_lost_per_unit;
    dbg +=' (heat lost per unit) * '+ insulation +' (insulation) * '+ construction_area +' (construction area)\n\n';
    */


    correction_factor = constructions[current_element]['correction_factor'];


    if(!isNaN( pFloat( correction_factor) ) )
    {
        heating_savings =heating_savings * pFloat(correction_factor);
        dbg += heating_savings +' (heating savings) ='+ heating_savings;
        dbg +=' (heating savings) * '+ correction_factor +' (correction factor)\n\n'; 
    }
    document.myform.savings.value = (heat_source_unit.indexOf('m3') != -1 )? (Math.round(heating_savings*100)/100):parseInt(heating_savings);

    
    dbg += heat_source_price +'(heating_source_price)\n\n'; 
    heat_price = heat_source_price;
    if(!isNaN(pFloat(heat_source_price_user))) heat_price = heat_source_price_user;
    if(isNaN(pFloat(heat_price))) heat_price = 1;
    price = heating_savings * pFloat(heat_price);

    document.myform.amounts.value = roundophundred(price); 

    dbg += heat_price +'(heat_price)\n\n'; 
    dbg += (Math.round(price * 100) / 100) +' (price) ='+ (Math.round(heating_savings*100)/100);
    dbg +=' (heating savings) * '+ heat_price +' (heating price)\n\n';

    var pv = get_product_values(new_insulation); 
    material_price = pFloat(pv['price']);

    dbg += material_price +'(material_price)\n\n'; 
    isolation_money = construction_area * material_price; 
    document.myform.material_expences.value = roundophundred(isolation_money); 

    dbg += (Math.round(isolation_money*100)/100) +' (Insulation money) ='+ construction_area +' (construction area) * ';
    dbg += material_price +' (material price)\n\n';

    var roi_time = isolation_money / price; 
    roi_time = Math.round(roi_time * 100) / 100;
    document.myform.roi_time.value = pFloat(roi_time); 

    dbg += roi_time +' (roi time) ='+ (Math.round(isolation_money*100)/100) +' (insulation money) / ';
    dbg += (Math.round(price*100)/100) +' (price)\n\n';
    
    if(saving != undefined)
    {
        computations[computations.length] = { 
                                          'construction_id':current_element,
                                          'construction':current_element_label,
                                          'areal':construction_area,
                                          'existing_isolation':existing_insulation_thickness,
                                          'new_isolation':new_insulation,
                                          'product':selected_product_name,
                                          'product_image':selected_product_image,
                                          'energy':heating_savings,
                                          'price':roundophundred(price),
                                          'product_price':roundophundred(isolation_money),
                                          'roi':pFloat(roi_time),
                                          'is_pipe':current_element_is_pipe()
                                        };
    }

    document.getElementById('overview_button').style.display = 'block';
    render_co2(heating_savings,false);
    document.getElementById('debug').value += dbg;
}
function add_to_matrix(product_id,u_value,existing_insulation,new_insulation)
{
    if(!matrix[product_id]) matrix[product_id]=[];
    matrix[product_id][matrix[product_id].length] = {'u_value':u_value,'existing_insulation':existing_insulation,'new_insulation':new_insulation};
}
 function getContent()
{
    var c = document.getElementById('print_area');
    if(!c) return '';

    var img = document.getElementById('tr_print_logo');

    var str='<html><head><title></title>';

    str+='<link rel="StyleSheet" href="print.css" type="text/css" />';
    str+='</head><body onload="printing()">';
    if(img) str+= img.innerHTML;
    
    str+= c.innerHTML;
    
    var co2 = document.getElementById('co2total');
    if(co2.style.display !='none') str+= '<div class="co2">' + co2.innerHTML + '</div>';
    str+= document.getElementById('tr_copyright').innerHTML;
    str+= document.getElementById('tr_company_info').innerHTML;
    str+='<script>function printing() { window.print();return false; } ';
    str+='function control_size(img,width) {if(img.src.indexOf(\'transp.gif\') !=-1) {img.width=5;}else{if(img.width>width) img.width=width;} }</s';

function control_size(img,width)
{
    if(img.src.indexOf('transp.gif') != -1) img.width = 5;
    else 
    {
      if(img.width > width) img.width = width;
    }
}
    str+='cript>';
    str+= '</body></html>';
    return str;
}
function pFloat(n)
{
    n = n.toString();
    if(isNaN(parseFloat(n))) return parseFloat(n);
    return parseFloat(n.replace(',','.'));
}
function print_friendly()
{
    var props ="width=570,height=580,toolbar=no,directories=no,status=no,location=no,menubar=no,resizable=no,scrollbars=yes";
    var w = window.open("about:blank","print",props);
    newdocument=w.document;
    newdocument.write(getContent());
    newdocument.close();
    w.focus();
}
function trans(msg)
{
    var el = document.getElementById(msg);
    if(!el) return msg;
    return el.innerHTML;
}

var selected = false;
var current_text = false;
var selected_list = false;

function element_name(el)
{
    var n =el.id.split('xx');
    return n[n.length-1];
}
function img_over_(img)
{
    var n = 'mxx'+ img.id;
    var el = document.getElementById(n);
    if(!el) return;
    el.style.background='#508fc4';
    img.src= img.src.replace('off/','on/'); 
}
function img_out_(img)
{
    var n = 'mxx'+ img.id;
    var el = document.getElementById(n);
    if(!el) return;
    el.style.background='#90bade';
    img.src= img.src.replace('on/','off/'); 
}
function img_over(building)
{
    /*
    var n = 'mxx'+ building;
    var el = document.getElementById(n);
    if(!el) return;
    el.style.background='#508fc4';
    */
    var img = document.getElementById('house_img');
    img.src= 'scandic/hus_'+ building +'.jpg'; 
}
function img_out(building)
{
    var n = 'mxx'+ building;
    var el = document.getElementById(n);
    if(!el) return;
    el.style.background='#90bade';

    var img = document.getElementById('house_img');
    img.src= 'scandic/hus.jpg'; 
}
function tiltag_over(a)
{
    var el_name = element_name(a);
    var img = document.getElementById('house_img');
    img.src = 'scandic/hus_'+ el_name +'.jpg';
}
function tiltag_out(a)
{
    if(selected_list==a) return;
    var img = document.getElementById('house_img');
    img.src = 'scandic/hus.jpg';
}
function ScrollToElement(theElement){

  var selectedPosX = 0;
  var selectedPosY = 0;
              
  while(theElement != null){
    selectedPosX += theElement.offsetLeft;
    selectedPosY += theElement.offsetTop;
    theElement = theElement.offsetParent;
  }
                        		      
 window.scrollTo(selectedPosX,selectedPosY);

}


