var FIELD_COST="cost", FIELD_AMOUNT="amount";

/*
 _   _
| | | | ___  _   _ ___  ___
| |_| |/ _ \| | | / __|/ _ \
|  _  | (_) | |_| \__ \  __/
|_| |_|\___/ \__,_|___/\___|
*/
var House = Class.create({
  initialize: function () {
    this.floors = [];
    this.energies = [];
  },
  addFloor: function () {
    if (this.floors.size()<6) {
      if (!this.hasGroundFloor()) {
        this.groundFloorLevel=this.floors.size();
      }
      var newFloor = new Floor(this, this.floors.size(), !this.hasGroundFloor());
      this.floors.push(newFloor);
      editFloor(newFloor);
      this.updateKwhSum();
    }
  },
  getContainer: function () {
    return $('floors');
  },
  moveGroundFloor: function (toFloor) {
    this.floors.each(function (elmt) {
      if (elmt != toFloor) {
        elmt.showGroundFloor(false);
      }
    });
    this.groundFloorLevel = toFloor.level;
  },
  deleteFloor: function (delFloor) {
    var houseList = [];
    var counter = 0;
    this.floors.each(function (elmt) {
      if (elmt != delFloor) {
        houseList.push(elmt);
        elmt.setFloorLevel(counter++);
      }
    });
    this.floors = houseList;
    delFloor.removeHTMLitems();
  },
  hasGroundFloor: function () {
    var hasGf = false;
    this.floors.each(function (elmt) {
      if (elmt.isGroundFloor) {
        hasGf = true;
      }
    });
    return hasGf;
  },
  computeFloorNr: function (ofFloor) {
    floorNr = ofFloor.level-this.groundFloorLevel;
    return floorNr;
  },
  getTotalArea: function () {
    var area = 0;
    this.floors.each(function (elmt) {
      area+=elmt.area;
    });
    this.area = area;
    return area;
  },
  addEnergyRow: function () {
    if (this.energies.size()<5) {
      this.energies.push(new EnergyType(this, $('energy_table')));
      $('klassen').style.top=(400+this.energies.size()*30)+"px";
    }
  },
  updateKwhSum: function () {
    var energysum = 0;
    this.energies.each(function (elmt) {
      energysum += (!isNaN(elmt.getKwh())) ? elmt.getKwh() : 0;
    });
    $('kwhSum').innerHTML = energysum;
    this.energysum = energysum;
    this.computeClass();
  },
  computeClass: function () {
    var relative = 0;
    var energyClass = "G";
    var num = 7;
    var lnum = "klassen";
    var advice = "<br/>&nbsp;<br/>";
    if (this.energysum<=0) {
      energyClass = "0";
      num = 0;
      advice+="Kein Energieverbrauch angegeben";
    } else if (this.area<=0) {
      energyClass = "0";
      num = 0;
      advice+="Keine beiheizte Fläche angegeben";
    } else {
      relative = Math.round(this.energysum/this.area*10)/10;
      if (relative <= 25) {
        energyClass = "A";
        num = 1;
        lnum = "klasse_a";
        advice+="Gratulation, nur kleine Verbesserungen möglich<br />Mehr Informationen erhalten Sie auf ";
      } else if (relative <= 50) {
        energyClass = "B";
        num = 2;
        lnum = "klasse_b";
        advice+="Gratulation, über den aktuellen Vorschriften!<br />Hinweis auf mögliche Verbesserungen unter ";
      } else if (relative <= 70) {
        energyClass = "C";
        num = 3;
        lnum = "klasse_c";
        advice+="Entspricht nicht ganz den Vorschriften. Informationen über mögliche Massnahmen unter ";
      } else if (relative <= 90) {
        energyClass = "D";
        num = 4;
        lnum = "klasse_d";
        advice+="Entspricht nicht den Vorschriften.<br />Wir empfehlen ihnen Massnahmen auf ";
      } else if (relative <= 120) {
        energyClass = "E";
        num = 5;
        lnum = "klasse_e";
        advice+="Entspricht nicht heutigem Baustandard.<br />Dringende Massnahmen auf ";
      } else if (relative <= 160) {
        energyClass = "F";
        num = 6;
        lnum = "klasse_f";
        advice+="Entspricht gar nicht heutigem Baustandard.<br />Dringende Massnahmen auf ";
      } else {
        energyClass = "G";
        num = 7;
        lnum = "klasse_g";
        advice+="Entspricht gar nicht heutigem Baustandard.<br />Sehr dringende Massnahmen auf ";
      }
      advice+=' <a href="http://www.optimacasa.ch/site/'+lnum+'.0.html" target="_blank">folgender Seite</a>';
      advice+='<br />&nbsp;<br /><a href="javascript:addPersonalities();">Kontaktdaten angeben</a>';
      advice+=' <a href="javascript:saveRestart();">speichern &amp; neu starten</a>';
    }
    $('istklasse').style.top=((num-1)*30+10)+"px";
    $('istklasse').innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>Klasse "+energyClass+": "+relative+" kWh/(m<sup>2</sup>a)</strong>"+advice;
    //$('klasse').innerHTML = "<strong>Klasse "+energyClass+": "+relative+" kWh/(m<sup>2</sup>a)</strong>";
  }
});

/*
 _____ _
|  ___| | ___   ___  _ __
| |_  | |/ _ \ / _ \| '__|
|  _| | | (_) | (_) | |
|_|   |_|\___/ \___/|_|

*/

var Floor = Class.create({
  initialize: function(house, level, isGroundFloor) {
    
    this.house = house;
//    this.abslevel = this.house.getAbsFloorLevel();
    this.isGroundFloor = isGroundFloor;
    
    this.floorImage = document.createElement('div');
    this.floorImage.corrObject = this;
    
    this.groundImage = document.createElement('div');
    
    this.setFloorType(TYPE_FULL);
    
    this.makeFloorImage();

    this.setFloorLevel(level);
    
    this.fieldValues = [7,7,2,2];
    
  },
  makeFloorImage: function () {
    this.floorImage.className="floor floor_"+this.floorType+"_d";
    this.groundImage.className="floor groundfloor";
    
    this.floorImage.onclick=function(e) { this.corrObject.doClick(); cancelEvent(e); };
    this.floorImage.appendChild(document.createTextNode(" "));
    
    this.groundImage.style.display = (this.isGroundFloor) ? "block" : "none";
    
    this.getContainer().appendChild(this.groundImage);

    this.getContainer().appendChild(this.floorImage);
    
  },
  setFloorType: function (floorType) {
    this.floorType = floorType;
    this.floorImage.setAttribute("floorType", floorType);
    do_over(this.floorImage, false);
  },
  getContainer: function () {
    return this.house.getContainer();
  },
  doClick: function () {
    editFloor(this);
  },
  changedFloorType: function (val) {
    this.setFloorType(val);
    this.floorImage.className="floor floor_"+this.floorType;
    $('bigFloorImage').className = "bigImage bigImage_"+this.floorType;
    this.changeFieldVisibility();
    this.countArea();
  },
  changeFieldVisibility: function () {
    $('sizeField1_div').className = "sizeField sizeField1_"+this.floorType;
    $('sizeField2_div').className = "sizeField sizeField2_"+this.floorType;
    $('sizeField3_div').className = "sizeField sizeField3_"+this.floorType;
    $('sizeField4_div').className = "sizeField sizeField4_"+this.floorType;
  },
  changedIsGroundFloor: function (val) {
    this.showGroundFloor(val);
    this.house.moveGroundFloor(this);
    this.updateTitle();
  },
  changedSizeField: function (val, fieldNr) {
    this.fieldValues[fieldNr-1]=val;
    this.countArea();
  },
  showGroundFloor: function (val) {
    this.isGroundFloor = val;
    this.groundImage.style.display = (this.isGroundFloor) ? "block" : "none";
  },
  displayFieldValues: function () {
    $('sizeField1').value = this.fieldValues[0];
    $('sizeField2').value = this.fieldValues[1];
    $('sizeField3').value = this.fieldValues[2];
    $('sizeField4').value = this.fieldValues[3];
    $('f_isGroundFloor').checked = this.isGroundFloor;
    this.countArea();
    this.updateTitle();
  },
  updateTitle: function () {
    var nr = this.house.computeFloorNr(this);
    var str = "";
    if (nr>0) 
      str = nr+". OG";
    else if (nr<0) {
      str = Math.abs(nr)+". UG";
    } else {
      str = "EG";
    }
    $('floorTitle').innerHTML = "Stockwerk: "+str;
  },
  setFloorLevel: function (newlevel) {
    this.level = newlevel;
    this.groundImage.style.top = (300 - this.level * 40) + "px";
    this.floorImage.style.top = (300 - this.level * 40) + "px";
  },
  removeHTMLitems: function () {
    this.getContainer().removeChild(this.floorImage);
    this.getContainer().removeChild(this.groundImage);
  },
  countArea: function () {
    this.area = 0;
    switch (this.floorType) {
      case "full": 
        area = this.fieldValues[0]*this.fieldValues[1];
        break;
      case "cold":
        area = 0;
        break;
      case "part":
        area = this.fieldValues[0]*this.fieldValues[1]-this.fieldValues[2]*this.fieldValues[3];
        break;
      case "half":
        area = this.fieldValues[0]*this.fieldValues[1];
        break;
      case "middle_hot":
        area = this.fieldValues[0]*this.fieldValues[3];
        break;
      case "middle_cold":
        area = this.fieldValues[0]*this.fieldValues[1]+ this.fieldValues[0]*this.fieldValues[2];
        break;
    }
    this.area = area;
    $('areaField').value = this.area;
  }
});

/*
 _____                           _____
| ____|_ __   ___ _ __ __ _ _   |_   _|   _ _ __   ___
|  _| | '_ \ / _ \ '__/ _` | | | || || | | | '_ \ / _ \
| |___| | | |  __/ | | (_| | |_| || || |_| | |_) |  __/
|_____|_| |_|\___|_|  \__, |\__, ||_| \__, | .__/ \___|
                      |___/ |___/     |___/|_|
*/

var EnergyType = Class.create({
  initialize: function(house, container) {
    this.house = house;
    this.container = container;
    
    this.drawRow();
    
  },
  drawRow: function () {
    var tr = document.createElement("tr");
    var energy_field = energy_select.cloneNode(true);
    
    var td1 = document.createElement("td");
    tr.appendChild(td1);
    this.energyField = energy_select.cloneNode(true);
    this.energyField.corrObject = this;
//    this.energyField.onchange = function () {
//      this.corrObject.changedEnergyType();
//    }
    this.energyField.onclick = function () {
      this.corrObject.changedEnergyType();
    }
    td1.appendChild(this.energyField);
    
    var td2 = document.createElement("td");
    tr.appendChild(td2);
    this.consumField = document.createElement("input");
    this.consumField.onkeyup = function (e) {
      this.corrObject.enteringField(FIELD_AMOUNT);
    }
    this.consumField.corrObject = this;
    this.consumField.className="bigNumField";
    this.dimSpan = document.createElement("span");
    this.dimSpan.className="dimensionField";
    td2.appendChild(this.dimSpan);
    td2.appendChild(this.consumField);
    
    this.consumkwhField = document.createElement("td");
    tr.appendChild(this.consumkwhField);
    
    var td3 = document.createElement("td");
    tr.appendChild(td3);
    this.costField = document.createElement("input");
    this.costField.onclick = function (e) {
      this.corrObject.enteringField(FIELD_COST);
    }
    this.costField.onkeyup = function (e) {
      this.corrObject.enteringField(FIELD_COST);
    }
    this.costField.corrObject = this;
    this.costField.className="bigNumField";
    td3.appendChild(this.costField);
    td3.appendChild(document.createTextNode(" sFr."));
    
    var td4 = document.createElement("td");
    tr.appendChild(td4);
    this.yearField = year_select.cloneNode(true);
    this.yearField.selectedIndex = 18;
    this.yearField.corrObject = this;
    this.yearField.onclick = function () {
      this.corrObject.updatePrice();
    }
    this.yearField.onchange = function () {
      this.corrObject.updatePrice();
    }
    td4.appendChild(this.yearField);
    
    this.container.appendChild(tr);
    this.changedEnergyType();
  },
  enteringField: function (field) {
    if (field==FIELD_AMOUNT) {
      this.costField.className="bigNumField fieldPassive";
      //this.costField.value="";
      this.consumField.className="bigNumField";
      this.editing = field;
      
      this.updateKwhField();
      
    } else if (field==FIELD_COST) {
      this.consumField.className="bigNumField fieldPassive";
      //this.consumField.value="";
      this.costField.className="bigNumField";
      this.editing = field;
    }
    this.updatePrice();
  },
  updateKwhField: function () {
    
    var roundMult = 10;
    var fld = $("energy_select_"+this.energyField.value);
    this.kwh = (!isNaN(this.consumField.value) && this.consumField.value!="") ? Math.round(parseInt(this.consumField.value)*fld.getAttribute("inkwh")*roundMult)/roundMult : 0;
    this.consumkwhField.innerHTML = this.kwh;
    this.house.updateKwhSum();
  },
  changedEnergyType: function () {
    var fld = $("energy_select_"+this.energyField.value);
    fld.getAttribute("inkwh");
    this.dimSpan.innerHTML=fld.getAttribute("dimension");
    this.enteringField(FIELD_AMOUNT);
  },
  changeDimension: function () {
  },
  getKwh: function () {
    return this.kwh;
  },
  setEnergyPrice: function (energytype) {
    //alert(energytype.toJSON());
    if (this.editing == FIELD_AMOUNT) {
      this.costField.value=(Math.round(this.consumField.value*energytype.preis*20)/20).toFixed(2);
    } else if (this.editing == FIELD_COST) {
      this.consumField.value=(Math.round(this.costField.value/energytype.preis*20)/20).toFixed(2);
      this.updateKwhField();
    }
  },
  updatePrice: function () {
    var params = new Hash();
    params.set('energietypID', this.energyField.value);
    params.set('jahr', this.yearField.value);
    var tester = this;
//    alert(params.toJSON());

    this.preisreq = new Ajax.Request('energiepreis.php', { 
      method: 'get', 
      parameters: params,
      onSuccess: function(resp){
//        alert(tester.setEnergyPrice);
        tester.setEnergyPrice(resp.responseJSON);
//        var response = resp.responseText || "no response text";
//      
//        var energietypen = response.evalJSON(true);
      }, 
      onFailure: function(){ 
        alert('Something went wrong...') }
      }
    );
  }
});
