﻿$(function() {
  $('#but input').css('display', 'none');
  var form = $('#product-add');
  form.submit(function() {
    return false;
  });
  var sciezka = 'catalog/template/default/image/';
  var tout = null;
  //function zmien() { return this.name.replace('quantity','remove'); }
  $('#product-add table input').each(function() {
    $(this).parent().parent().addClass('icn'); //[chrome ma problemy z zaznaczaniem dynamicznie wygenerowanych elementow]
    if ($.trim($(this).val()) != '') $(this).addClass('k');
  }).keyup(function() {
    if (tout) clearTimeout(tout);
	var $$ = $(this);
    tout = setTimeout(function() {
	var val = $$.val();
	if(!val.match(/^[0-9]*$/)) {
      $$.removeClass('k').addClass('err2');
	  $('.err').remove();
      $('#res').after('<p class="err">Ilość musi być wartością liczbową.</p>');
    } else {
      $$.next('img').remove();
      $$.after('<img src="' + sciezka + 'in.gif" alt="" />');
      $.ajax({
        url: form.attr('action'),
        type: form.attr('method'),
        data: $$.attr('name') + '=' + val,
        success: function() {
          $('#kosz').load('index.php?controller=cart&ajax=1');
          if ($.trim(val) != '') {
            $$.removeClass('err2').addClass('k').next().attr({
              src: sciezka + 'ok2.png',
              alt: 'ok',
              title: 'wysłano do koszyka'
            }).animate({
              opacity: 1.0
            },
            1500).fadeOut('slow',
            function() {
              $(this).remove();
            });
          } else {
            $$.removeClass('k err2').next().remove();
          }
		if($('.err2').length==0) $('.err').fadeOut(function() { 
		  $(this).remove(); 
		});
        },
        error: function() {
          alert("błąd: produkt nie został dodany do koszyka!");
        }
      });
	}
    },
    300);
  });
});
