/*
 * Cart Script
 * version 0.1
 */

var cart = new function() {

  this.add_url = '/include/ajax.php';
  this.delete_url = '/include/ajax.php';
  this.refresh_url = '/cart/index.php';
  this.currTimer = 2;


  // Init
  this.init = function() {
  },

  // Add product to cart
  this.addToCart = function(id, obj) {
    var cartObject = this;
    $.post(this.add_url, {id: id, type: 'addToCart'}, function(data) {
      if (data) {
        $('#cart').empty().append(data);

        $('#product-title').text($(obj).attr('rel'));
        
        $('#window').css({
          'top': ($(window).height() / 2 + $(window).scrollTop())
        }).fadeIn('fast');

        $('#window').find('a.close').click(function(){
          $('#window').fadeOut('fast');
          return false;
        });

        cartObject.popupTimer();

      }
    });

    return false;
  },

  this.popupTimer = function() {
    var cartObject = this;
    
    $('#seconds').text(cartObject.currTimer);

    setTimeout(function() {
      cartObject.currTimer--;
      $('#seconds').text(cartObject.currTimer);
      if (cartObject.currTimer > 0) {
        cartObject.popupTimer();
      }
      else {
        $('#window').fadeOut('fast');
        cartObject.currTimer = 2;
      }
    }, 1000);
    
  },

  // Delete from cart
  this.deleteItem = function(id, obj) {
    var cartObject = this;
    $.get(this.delete_url, {'delete': id}, function(data) {
      if (data) {
        $('#html_cart').empty().append(data);
        cartObject.getCart();
      }
    });
    
    return false;
  },

  this.getCart = function() {
    $.post(this.add_url, {type: 'getCart'}, function(data) {
      if (data) {
        $('#cart').empty().append(data);
      }
    });
  },

  // Refresh cart
  this.refreshCart = function() {
    var cartObject = this;
    var form_data = $('#cart_form').serialize();
  //  alert(form_data);
    $.post(this.refresh_url, form_data, function(data) {

      if (data) {
        $('#html_cart').empty().append(data);
        cartObject.getCart();
      }

      return false;
    });
  }

};
