/**
 * Compact labels plugin
 */
(function($){$.fn.compactize=function(){return this.each(function(){var label=$(this),input=$('#'+label.attr('for'));input.focus(function(){label.hide();}).blur(function(){if(input.val()===''){label.show();}});window.setTimeout(function(){if(input.val()!==''){label.hide();}},50);});};})(jQuery);

/*
 * hrefID jQuery extention - returns a valid #hash string from link href attribute in Internet Explorer
 */
(function($){$.fn.extend({hrefId:function(){return $(this).attr('href').substr($(this).attr('href').indexOf('#'));}});})(jQuery);

/*
 * Scripts
 *
 */
jQuery(function($) {
 
	var Engine = {
		utils : {
			links : function(){
				$('a[rel*=external]').click(function(e){
					e.preventDefault();
					window.open($(this).attr('href'));						  
				});
			},
			mails : function(){
				$('a[href^=mailto:]').each(function(){
					var mail = $(this).attr('href').replace('mailto:','');
					var replaced = mail.replace('/at/','@');
					$(this).attr('href','mailto:'+replaced);
					if($(this).text() == mail) {
						$(this).text(replaced);
					}
				});
			}
		}
	};

	Engine.utils.links();
	Engine.utils.mails();
	
});

// Cart
$(function() {
  var addToCartButtons = $("input.cartadd");
  if(addToCartButtons.length > 0){
    var inputText = $("input.text");
    for(var i = 0; i < inputText.length; i++){
      var o = $(inputText[i]);  
      o.focus(function(){
        this.select();
      });
    };
  }
  for(var i = 0; i < addToCartButtons.length; i++){
    var o = $(addToCartButtons[i]);
    o.click(function(){
      $('#cart-message').html('Please wait while we add the item to your cart...');
      var product_id = this.getAttribute('data-product-id');
      var q = $("#variants_" + product_id).val();
      $('#cart-message').dialog({title: 'Updating Shopping Cart', modal: true});
      var d = 'variants[' + product_id + ']' + '=' + q + '&authenticity_token=' + AUTH_TOKEN;
      $.post("/orders", d,
       function(data){
          $.getJSON('/cart_details', function(data) {
            $('#cart-message').html(
              '<p>The item has been added to your cart!</p><p><strong>Cart Totals</strong><br />Items: ' +
              data.order_items +
              '<br />Amount: $' + data.order_price + '</p>' +
              '<p><a href="/orders/' + data.order_id + '/edit">Checkout Now</a> | <a href="#" id="close-dialog">Keep Shopping</a>');  
            $('#cart-link').html('<a href="/orders/' + data.order_id + '/edit">Cart:('+ data.order_items +') $' + data.order_price + '</a>');
            $("#close-dialog").click(function(){ $('#cart-message').dialog('close'); });
            Cufon.refresh();
          });
          //setTimeout(function () { $('#cart-message').dialog('close');  }, 3000);
       });
      return false;
    });
  };
});

