(function($) {

  $.fn.solarPanelCalculator = function(conf){
    var defaultConf = {
      roof:   $('#roof'),
      width:  $('#width'),
      height: $('#height'),
      panel:  $('#panel'),
      result: $('#numPanels'),
      maxWidth  : 50,
      maxHeight : 20,
      gap:    18
    }

    var countBarrier = 0;
    var busy = false;
    
    conf = $.extend({}, defaultConf);

    conf.width.bind('change' , _calculate);
    conf.height.bind('change', _calculate);
    conf.panel.bind('change' , _setPanel);


    conf.width.parent().append('<span id="widthSlider"></span>');
    conf.height.parent().append('<span id="heightSlider"></span>');


    // Aktuelles Panel setzen
    _setPanel();


    // Hindernisse
    $('.addBarrier').bind('click', _addBarrier);
    $('.removeBarrier').bind('click', _removeBarrier);


    // Width Slider
    $('#widthSlider').addClass('slider');
    $("#widthSlider").slider({
      value:25,
      min: 0,
      max: conf.maxWidth,
      step: 0.1,
      slide: function(event, ui) {
        var value = String(ui.value);
        value = value.split('.').join(',');
        conf.width.val(value);
        _calculate();
      },
      stop: function(event, ui) {
        _calculate();
      }
    });
    conf.width.val($("#widthSlider").slider("value"));

    // Height Slider
    $('#heightSlider').addClass('slider');
    $("#heightSlider").slider({
      value:10,
      min: 0,
      max: conf.maxHeight,
      step: 0.1,
      slide: function(event, ui) {
        var value = String(ui.value);
        value = value.split('.').join(',');
        conf.height.val(value);
        _calculate();
      },
      stop: function(event, ui) {
        _calculate();
      }
    });
    conf.height.val($("#heightSlider").slider("value"));

    _calculate();


    /* Hindernis hinzufügen */
    function _addBarrier(){
      if(countBarrier>=5){
        alert('Sie können maximal 5 Hindernisse einfügen!');
        return;
      }

      countBarrier ++;
      
      var left = 1 + (countBarrier-1) * 3;

      var barrier = '';
      barrier = '<div class="barrier" id="barrier' + countBarrier + 'div" style="left:' + (left*10) + 'px;">' + countBarrier + '</div>';

      var opts = '';
      opts = '<div class="options" id="barrier' + countBarrier + '" >'
           + '<label>Nr. ' + countBarrier + '</label>'
           + '<div class="opt">links <input name="left" value="' + left + '" />m</div>'
           + '<div class="opt">oben <input name="top" value="1" />m</div>'
           + '<div class="opt">breite <input name="width" value="2" />m</div>'
           + '<div class="opt">höhe <input name="height" value="2" />m</div>'
           + '</div>';

      $(conf.roof).append(barrier);
      $('#barriers').append(opts);
      $('#barriers input').unbind().bind('change' , function(){ _updateBarrier(this) } );

      $(".barrier").resizable({
        containment: 'parent',
        resize: function(){ _updateBarrierOptions(this, true) },
        stop:   function(){ _updateBarrierOptions(this, true) }
      });
      
      $(".barrier").draggable({
        containment: 'parent',
        drag: function(){ _updateBarrierOptions(this, true) },
        stop: function(){ _updateBarrierOptions(this, true) }
      });

      _calculate();
    }


    /* Hindernis entfernen */
    function _removeBarrier(){
      if(countBarrier>0){
        $('.options:last', '#barriers').remove();
        $('.barrier:last', conf.roof).remove();
        countBarrier--;
        _calculate();
      }
    }


    /* Werte des Hindernisses anzeigen */
    function _updateBarrierOptions(obj, calc){
      var id = $(obj).attr('id').substring(0,8);

      var width  = String((parseInt($(obj).css('width'))+2)/10).split('.').join(',');
      var height = String((parseInt($(obj).css('height'))+2)/10).split('.').join(',');
      var left   = String(parseInt($(obj).css('left'))/10).split('.').join(',');
      var top    = String(parseInt($(obj).css('top'))/10).split('.').join(',');

       
      $('#' + id + ' input[name="width"]').val(width);
      $('#' + id + ' input[name="height"]').val(height);
      $('#' + id + ' input[name="left"]').val(left);
      $('#' + id + ' input[name="top"]').val(top);

      if(calc){
        _calculate();
      }
    }


    /* Hindernis aktualisieren */
    function _updateBarrier(obj){
      var id = $(obj).parent().parent().attr('id');
      var name = $(obj).attr('name');
      var value = _prepareValue( $(obj).val())/100 ;

      if(name=='width' || name=='height'){
        value -=2;
      }
      
      $('#'+id+'div').css(name, value+'px');

      _calculate();
    }


    /* Modul setzen */
    function _setPanel(){
      if(conf.panel.length){
        var panelHeight = parseInt(conf.panel.val().split('x')[1]) / 10;
        $('table',conf.roof).css('height', panelHeight + 'px');
        _calculate();
      }
    }


    /* Berechnen */
    function _calculate(){
      if(busy) return;
      
      
      // Check ob alle Daten angegeben worden sind
      if (!conf.width.val() || !conf.height.val() || !conf.panel.val() || conf.panel.val().split('x').length != 3) {
        conf.result.html('0');

      }else{

        if(conf.width.val()>conf.maxWidth){
          alert('Wert ist zu groß! \nMaximal ' + conf.maxWidth + ' Meter.');
          //conf.width.val(conf.maxWidth);
          return;
        }

        if(conf.height.val()>conf.maxHeight){
          alert('Wert ist zu groß! \nMaximal ' + conf.maxHeight + ' Meter.');
          //conf.height.val(conf.maxHeight);
          return;
        }
        
        busy = true;

        // Alle Angaben sind in Millimeter
        var roofWidth   = _prepareValue(conf.width.val()); // Dachbreite
        var roofHeight  = _prepareValue(conf.height.val()); // Dachhöhe
        var panelWidth  = parseInt(conf.panel.val().split('x')[0]) * 10; // Modulbreite
        var panelHeight = parseInt(conf.panel.val().split('x')[1]) * 10; // Modulhöhe

        var rows = Math.floor(roofHeight / panelHeight); // Anzahl Reihen
        var cols = Math.floor((roofWidth + conf.gap) / (panelWidth + conf.gap));

        var roofWidthDiv  = roofWidth / 100;
        var roofHeightDiv = roofHeight / 100;
        var roofLegendTop = Math.floor((roofHeightDiv-104)/2);

        // Fläche anpassen
        conf.roof.css('width', roofWidthDiv + 'px');
        conf.roof.css('height', roofHeightDiv + 'px');
        if(roofLegendTop>0){
          $('#legend .height').css('top', roofLegendTop + 'px');
        }
        _fillRoof(rows, cols);
      }
      busy = false;
    }


    /* Zahl formatieren */
    function _prepareValue(value){
      // , in . umwandeln
      value = value.split(',').join('.');
      // in eine Zahl umwandeln
      value = parseFloat(value);
      // in Millimeter umwandeln
      value = parseInt(value * 1000);

      return value;
    }


    /* Dachfläche auffüllen */
    function _fillRoof(rows, cols){

      if(rows * cols == 0){
        $('table', conf.roof).hide();
      }else{
        $('table', conf.roof).show();
      }

      // Reset
      $('.clone',conf.roof).remove();
      $('td:gt(0)',conf.roof).remove();
      $('td',conf.roof).removeClass('panel_hidden');

      // Spalten (td clonen)
      for(n=1; n<cols; n++){
        $('td:first', conf.roof).clone().appendTo($('#roof .row'));
      }

      // Zeilen (table clonen)
      for(n=1; n<rows; n++){
        $('.source', conf.roof).clone().removeClass('source').addClass('clone').appendTo(conf.roof);
      }

      // Überlagerungen der Hindernisse ermitteln
      var intersection = $('.barrier').collidesWith('#roof td');
      $(intersection).addClass('panel_hidden');
      
      var all    = $('td:visible',conf.roof).length;
      var hidden = $('td.panel_hidden',conf.roof).length;
      var result = all - hidden;

      // Fläche
      // var panelWidth  = parseInt(conf.panel.val().split('x')[0]) / 100;
      // var panelHeight = parseInt(conf.panel.val().split('x')[1]) / 100;
      // var squareMeter = String(Math.round(panelWidth * panelHeight * result*10)/10).split('.').join(',');
      
      // Lesitung
      var panelPower  = parseInt(conf.panel.val().split('x')[2]);
      var totalPower  = String(Math.round(panelPower * result) / 1000).split('.').join(',');

      var info = totalPower + ' kWp / ' + result + ' St.';
      conf.result.html(info);

    }
  }
})(jQuery);

