$(document).ready(function(){
  
  $('.add_to_cart').live('click',function(){
    var id = $(this).attr('id');
    handle_cart('add_to',id,'cart',true);
    handle_cart('remove_from',id,'wishlist',false);
  });
  
  $('.remove_from_cart').live('click',function(){
    var id = $(this).attr('id');
    handle_cart('remove_from',id,'cart',true);
  });
  
  $('.add_to_wishlist').live('click',function(){
    var id = $(this).attr('id');
    handle_cart('add_to',id,'wishlist',true);
  });
  
  $('.remove_from_wishlist').live('click',function(){
    var id = $(this).attr('id');
    handle_cart('remove_from',id,'wishlist',true);
  });
  
  function handle_cart(action,id,type,show_message){
    $.ajax({
      type:'post',
      async:false,
      url:'/modules/cart/' + action + '_cart/ajax/index.php',
      data:'id=' + id + '&type=' + type,
      success:function(returnText){
        if(returnText.indexOf("Error") >= 0){
          $.fn.colorbox({html:returnText});
          setTimeout('$.fn.colorbox.close()',3000);
        }
        else{
          display_cart(returnText);
          display_cart_page();
          if(show_message == true){
            $.fn.colorbox({html:'<p>The <b>product</b> has been successfully <b>' + action.replace('_',' ').replace('add','added').replace('remove','removed') + '</b> your <b>' + type + '</b>.</p>'});
            setTimeout('$.fn.colorbox.close()',3000);
          }
        }
      },
      error:function(){
        //alert an error;
      }
    });
  }
  
  function display_cart(id){
    $.ajax({
      type:'post',
      url:'/modules/cart/side_panel/index.php',
      data:'id=' + id,
      success:function(returnText){
        $('#basket_panel').html(returnText);
      },
      error:function(){
        //alert an error;
      }
    });
  }
  
  function display_cart_page(){
    if(window.location.pathname == "/cart/checkout"){
      $.ajax({
        type:'post',
        url:'/modules/cart/checkout/index.php',
        data:'',
        success:function(returnText){
          $('#main_content').html(returnText);
        },
        error:function(){
          //alert an error;
        }
      });
    }
  }
  
});
