var plate;
var id = 1;
var products = []; // Products' collection
var SALT_LIMIT = 5; // gramm
var tp = $("<div></div").addClass("tooltip").hide();

// Extend array
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

$(function() {
  
  // Append to body tooltip
  tp.appendTo("body");
  
  // Overide CSS
  $(".slide img, #addSalt").css("cursor", "move").css("z-index", id);
  
  // Get the plate object
  plate = $("#plateArea");

  // Apply draggable droppable funcionality
  $(".slide img, #addSalt").draggable({
    helper: 'clone',
    appendTo: '#plateArea',
    start: function(event,ui) {},
    stop: function(event, ui) {}
    
  });
 
  $("#plateArea").droppable({
    accept: '.slide img, #addSalt',
    activeClass: "ui-state-default",
    hoverClass: "ui-state-hover",
    drop: function(event, ui) {
      var clone = ui.helper.removeAttr("id").clone();
      
      var alt = clone.attr("alt");
      //add unique id to alt tag
      clone.attr("alt", id + "|" + alt );
      alt = clone.attr("alt");
      
      //add product to global object
      addProduct(alt.split('|'));
      
      clone.unbind();
      clone.bind("mouseout", hideTooltip);

      // Here is use trick to imitate dropout. Standart 'out' function doesn't
      // work as we need.
      clone.draggable({
        helper: "original",
        appendTo: "#plateArea",
        stop: function(event, ui) {
          var hw = $(ui.helper.width());
          var hh = $(ui.helper.height());
          hw = hw[0];
          hh = hh[0];
          if(
            (ui.position.left < -hw/2 || ui.position.left > 295-hh/2) ||
            (ui.position.top < 0 || ui.position.top > 295-hh/2)
            )
          {
            // If out of bound code to remove this
            var params = ui.helper.attr("alt").split("|");
            removeProductByName(params[1]);
            ui.helper.fadeOut("fast", function() { $(this).remove() });
          }
        }
      })
      plate.append(clone);
    }
  });
  
  $(".slide img, #addSalt").bind("mousemove", showTooltip);
  $(".slide img, #addSalt").bind("mouseout", hideTooltip);
  
  // Tabs
  $tabs = $("#tabs").tabs({
    selected: 0
  });
  
}); // end of main

/**
* @param array
*/
function addProduct(params)
{
  var obj = {
    id: parseInt(params[0]),
    name: params[1],
    type: params[2],
    weight: parseFloat(params[3]),
    salt: parseFloat(params[4]),
    count: 1
  };
  var exists = false;
  for( var i = 0; i < products.length; i++) {
    if( products[i].name == obj.name) {
      products[i].count++;
      exists = true;
    }
  }
  if( !exists) {
    products.push(obj);
    id++;
  }
  buildResults();
}

/**
* @param integer
*/
function removeProductByName(name)
{
  for( var i = 0; i < products.length; i++) {
    if( products[i].name == name) {
      if(products[i].count > 1) {
        products[i].count--;
      } else {
        products.remove(i);
      }
      break;
    }
  }
  buildResults();
}

/**
* @param object
*/
function buildTableTemplate(object)
{
  var tpl = $("<tr></tr>").attr("id", "product_" + object.id);
  tpl.append($("<td></td>").append( $("<span></span>").addClass("data1").html(object.name)  ));
  tpl.append($("<td></td>").append( $("<span></span>").addClass("data2").html(object.type + " (" + object.count +")" ) ));
  tpl.append($("<td></td>").append( $("<span></span>").addClass("data3").html(object.weight + "") ));
  tpl.append($("<td></td>").attr("align", "right").append( $("<span></span>").addClass("data4").html(object.salt.toFixed(2)) ));
  return tpl;
}

function buildSumOfSalt()
{
  var salt = 0;
  for( var i = 0; i < products.length; i++) {
    salt += parseFloat(products[i].salt * products[i].count);
  }
  var percent = 100*(salt / SALT_LIMIT);
  if( percent >= 100) {
    $("#percentage p strong").addClass("overdose");
    $("#overdoseNote").show();
  } else {
    $("#percentage p strong").removeClass("overdose");
    $("#overdoseNote").hide();
  }
  $("#percentage p strong").text(percent.toFixed(1) + " %");
  $(".total_wieght").text(salt.toFixed(2));
}

function buildResults()
{
  var tbody = $("<tbody></tbody>");
  for( var i = 0; i < products.length; i++) {
    tbody.append(buildTableTemplate(products[i]));
  }
  $("#resultSpan table tbody").replaceWith(tbody);
  buildSumOfSalt();
}

function hideTooltip()
{
  tp.hide();
}

function showTooltip(event)
{
  var txt = $(this).attr("alt").split("|");
  tp.css("top", event.clientY + $(document).scrollTop() - 40).css("left", event.clientX + 10).show();
  tp.html(txt[0]);
} 
