$(document).ready(function() {

  $(".togglecats").click(function(e) {
  
    e.preventDefault();
    
    $(".toggle").toggle();
  
  });
  
  $(".goto_category").change(function() {
  
    var val = $(this).val();
    
    if(val > 0) {
    
      window.location = "/category.php?id="+val;
    
    }
  
  });

  $(".button").button();
  
  $(".search_button").button({icons:{primary:"ui-icon-search"}});
  
  $(".cart_button").button({icons:{primary:"ui-icon-cart"}});
  
	$("a.product_picture").fancybox({"hideOnContentClick":true});
  
  $("#qsearch").autocomplete({source:"/search_ajax_name.php",minLength:2});
  
  $(".autogrow").autogrow();
  
  /* ** */
  
  function add_to_cart(product_id) {

    $.ajax({
      type:"GET",
      url:"cart.php",
      data:"action=add&id="+product_id,
      success:function(data) {
        if(data == "E_KPL" || data == "E_NUM") {
          $("#cart").effect("highlight",{},1500);
          return false;
        }
        $("#cart_items").html(data);
        if($("#cart").is(":hidden")) $("#cart").effect("bounce",{times:3},350);
        else $("#cart").effect("highlight",{},1500);
      }
    });

  }
  
  $(".add_to_cart").click(function() {

    var product_id = $(this).attr("rel");
    
    add_to_cart(product_id);

  });

});

(function($) {

  $.fn.autogrow = function() {

    this.filter('textarea').each(function() {

      var $this = $(this), minHeight  = $this.height(), lineHeight = $this.css('lineHeight');

      var shadow = $('<div></div>').css({
        position:   'absolute',
        top:        -10000,
        left:       -10000,
        width:      $(this).width(),
        fontSize:   $this.css('fontSize'),
        fontFamily: $this.css('fontFamily'),
        lineHeight: $this.css('lineHeight'),
        resize:     'none'
      }).appendTo(document.body);

      var update = function() {

        var val = this.value.replace(/</g, '&lt;')
          .replace(/>/g, '&gt;')
          .replace(/&/g, '&amp;')
          .replace(/\n/g, '<br/>');

        shadow.html(val);
        
        $(this).css('height', Math.max(shadow.height() + 15, minHeight));

      }

      $(this).change(update).keyup(update).keydown(update);

      update.apply(this);

    });

    return this;

  }

})(jQuery);
