$(document).ready(function() {

  quickInventory();

  //$('#inventoryOrder').quicksand($('#inventory .itemID'), {adjustHeight: false});

  $('.colorpick').each(function() {
    var hexVal = $(this).val();
    while(hexVal.length < 6) hexVal = "0" + hexVal; 
    $(this).parent("td").css("background-color", "#"+hexVal); 
  });
  $('.colorpick').ColorPicker({
  	onSubmit: function(hsb, hex, rgb, el) {
  		$(el).val(hex);
  		$(el).parent("td").css("background-color", "#"+hex);
  		$(el).ColorPickerHide();
  	},
  	onBeforeShow: function () {
  		$(this).ColorPickerSetColor(this.value);
  	}
  })
  .bind('keyup', function(){
  	$(this).ColorPickerSetColor(this.value);
  });

  
  bindItems();
  
  $(".submitConfirm").click(function() {
    return confirm("Are you sure you want to proceed?");
  });
  
  $("#sendUserButton").click(function() {
    if($("#sendUserValue").val() > 0) {
      $("#sendUser").load("mini/user_info.php?id="+$("#sendUserValue").val());
    }
  });
  
  $("#fetchSimilar").click(function() {
    $("#similar").load("mini/suggestions.php?id="+$("#gryffID").val());
  });
  
  $(".toggleall").click(function() {
    var checked_status = this.checked;
    $("input.not").each(function() {
      $(this).attr("checked", checked_status);
    });
  });

});



function quickInventory() {
  var filterType = $('#filter input[name="type"]');
  var inventoryBackup = $('#inventory').clone();
  filterType.bind("change", {inventory: inventoryBackup}, function(e) {
    var inventoryClone = e.data.inventory.clone();
    var filteredData = null;
    if ($(filterType+':checked').val() == 'all') {
      filteredData = inventoryClone.find('.itemID');
    } else {
      filteredData = inventoryClone.find('.itemID[data-type=' + $(filterType+":checked").val() + ']');
    }
    $('#inventory').quicksand(filteredData, function() {
      $(".item").unbind();
      bindItems();
    });
  });
}

function bindItems() {
  $(".item").click(function() {
    var item = $(this).parent(".itemID").attr('id');
    $(this).parent(".itemID").children(".itemInfo").load("mini/item.php?id="+item, function() {
      $(this).show("slow");
      $(".cancel").click(function() {
        $(this).parents(".itemInfo").html("");
        $(".itemInfo").hide();
      });
    });
  });
}
