// Common JavaScript code across your application goes here.

$(document).ready(function() {
  
  initDeleteLink();
  initPlaceholder();
  initPutLink();
  initAddToCart();
  initRemoveFromCart();
  $('#empty_cart').live('click', function(e){
    e.preventDefault();
    if ( confirm('Are you sure you want to empty your shopping cart?') ) emptyShoppingCart();
  })
    
});

function initDeleteLink() {
  $('.delete_link').live('click', function(e) {
    e.preventDefault();
    var path = $(this).attr('href');
    var prompt = $(this).attr('rel');
    var redirect = $(this).attr('rev');

    if (confirm(prompt)) {
      $.post(path, {'_method' : 'delete'}, function(ret){
        if (ret == "OK") {
          if (redirect.match(/^#eval__/)) {  
            var run = redirect.replace(/^#eval__/,'');
            eval(run);
          }
          else {
            window.location = redirect;
          }
        } else {
          error_message = $.trim( ret.replace('ERROR', '') );
          alert("Error deleting this object. " + error_message);
          return false;
        }
      });
    }
  });
}

function initPutLink(link, callback) {
  $('.put_link').live('click', function(e) {
    e.preventDefault();
    var link = $(this).attr('href');
    var callback = $(this).attr('rev');
    $.post( link, {_method:'put'}, function(result) {
      eval(callback);
    });
  });
}

// Labels within fields. Use the the "placeholder" HTML 5 attribute.
function initPlaceholder() {
  if ($.browser.webkit) return false;

  $('input[placeholder]').each(function(index) {
    var target = $(this);
    
    if (! $.trim(target.val())) {
      $(target).addClass('placeholder');
      $(target).val($(target).attr('placeholder'));
    }
 
    $(target).focus(function() {
      if ($(this).val() == $(this).attr('placeholder')) {
        $(this).removeClass('placeholder');
        $(this).val('');
      }
    });

    $(target).blur(function() {
      if ($.trim($(this).val()) == '' ) {
        $(this).addClass('placeholder');
        $(this).val( $(this).attr('placeholder') );
      }
    });
  });
  
  // The form shouldn't send the placeholder text as the value
  // TODO: write back the labels after submit
  $('form').submit(function(){
    $(this).find('input[placeholder]').each(function(index) {
      var target = $(this);
      if ($(target).val() == $(target).attr('placeholder')) {
        $(target).val('');
      }
    });
  });
    
}

// Initializing "add_to_cart buttons"
function initAddToCart() {
  // Drop publications to the cart
  $(".add_to_cart").click(function(e) {
    e.preventDefault();
    
    var id_parts = /add_to_cart_(\w+)_(\d+)(?:_(\w+)?)$/.exec( $(this).attr('id') );
    var item_type = id_parts[1];
    var item_id = id_parts[2];
    var version = id_parts[3]
    
    $.post( $(this).attr('href'), {'_method':'put','item_type':item_type,'item_id':item_id,'version':version}, function(result) {
       if (result == "OK") {
         refreshShoppingCart();
       } else {
         alert("Adding this element to the shopping cart was not successful. Please try again or contact us.");
       }
     });
  });
}

// Initializing "remove from shopping cart" buttons
function initRemoveFromCart() {
  $('[id^="remove_line_item_"]').live('click', function(e){
    e.preventDefault();
    
    var id_parts = /remove_line_item_(\w+)_(\d+)$/.exec( $(this).attr('id') );
    var item_type = id_parts[1];
    var item_id = id_parts[2];
    
    $.post('/orders/remove_item', {'_method':'put', 'item_type':item_type, 'item_id':item_id}, function(result){
      if (result == "OK") {
        refreshShoppingCart();
      } else {
        alert("Sorry, I can't remove this element from the shopping cart due to an error.");
      }
    });
  });  
}

function updateShoppingCart(content) {
  var cart = '#shopping_cart';
  if (content != '') {
    $(cart).fadeIn('fast');
  } else {
    $(cart).fadeOut('fast');
  }
  $(cart).html(content);
}

function refreshShoppingCart() {
  $.get('/shopping-cart', function(result){
    updateShoppingCart(result);
  });
}


function emptyShoppingCart() {
  $.post( '/orders/empty', {_method:'put'}, function(result) {
    updateShoppingCart(result);
  });
}
