jQuery(document).ready(function() {

  function eShopClick($this) {
    try {
      var itemID = $this.attr('href');
      var action = $this.hasClass('eShopAdd') ? 'addItem' : 'remItem';
      jQuery.ajax({
        url : uriEShop + '/' + action
      , dataType: 'json'
      , data: {
          itemID: itemID
        , documentIdentifier: documentIdentifier
        }
      , success: function(response) {
          if(response.success) {
            var $new = jQuery(response.data.html);
            $new.click(function() { return eShopClick(jQuery(this)); });
            $this.parent().append($new);
            $this.empty().remove();
//            $this.replaceWith($new);
//            $this.replaceWith(response.data.html);
//            $this.click(function() { return eShopClick(jQuery(this)); });
            jQuery('.eShopSummary').each(function() {
              var $this = jQuery(this);
              $this.find('span.eShopItems').html(response.data.items);
              $this.find('span.eShopTotal').html(response.data.total);
            });
          } else {
            alert('Error: ' + response.message);
          }
        }
      , error : function(response) {
          alert(response.responseText);
        }
      });
    } catch(ex) {
      alert(ex);
    } finally {
      return false;
    }
  }

  jQuery('a.eShopButton.eShopClick').click(function() { return eShopClick(jQuery(this)); });

  jQuery.eShop = {
    reload: function(url, data) {
      try {
        var step = 0;
        jQuery.each(data, function(i, field){
          if(field.name == 'step') {
            step = parseInt(field.value);
          }
        });
        data.push({name:'documentIdentifier', value:documentIdentifier});
        if(step < 2) {
          jQuery('div.eShopSlip').load(url, data);
        } else {
          jQuery.ajax({
            url : url
          , data: data
          , dataType: 'json'
          , success: function(json) {
              alert(json.message);
              window.location.reload();
            }
          , error : function(data) {
              window.location.reload();
            }
          });
        }
      } catch(ex) {
        alert(ex);
      } finally {
        return false;
      }
    }
  };

  jQuery('a.eShopBuy').click(function() {
    return jQuery.eShop.reload(jQuery(this).attr('href'), []);
  });

});


