$(document).ready(function() {
  setupCatalogMenu();
  setupFlash();
  setupThickBox();
  setupSearchField();
  setupShop();
  setupPopup();
  $.ajaxSetup({type:"get"});
});

function setupThickBox(){   
	tb_init('a.thickbox, area.thickbox, input.thickbox');
	imgLoader = new Image();
	imgLoader.src = tb_pathToImage;
}

function setupFlash(){
    $('#cf_content').flash(
        { src: '../images/slideshow/slideshow.swf',
        menu:false,
        wmode: 'transparent',
        width: 457,
        height: 200 },
       { version: 8 }
        
    );
}

function openBox() {
		return tb_show('A Loja da Maria: Sorteio Homebox','../sorteio.html?KeepThis=true&TB_iframe=true&height=640&width=460');
}


function setupSearchField() {
  var defaultValue = "Pesquisar";
  $('#search_field')
    .val(defaultValue)
    .addClass('empty')
    .focus(function(){
      if(this.value == defaultValue){
        this.value = "";
        $(this).toggleClass('empty');
      }
    })
    .blur(function(){
      if(this.value == ""){
        $(this).toggleClass('empty');
        this.value = defaultValue;
      }
    })
}
function setupCatalogMenu(){
  $("#CatMenu").treeview({
		animated: "fast",
		collapsed: true,
		persist: "location",
		unique: true
	});
}

function setupPopup(){ 
var COOKIE_NAME = 'lojadamaria';
if ($.cookie(COOKIE_NAME) != null){
}
else
{
$.cookie(COOKIE_NAME, 'lojadamaria', {expires: 15, path: '/'});
tb_show('winowsname', '../maiorde18.html?placeValuesBeforeTB_=savedValues&TB_iframe=true&height=150&width=300&modal=true', null); 
}
};

////// SHOP //////
function setupShop() {
  var path = document.location.pathname
  if(path.indexOf('review_cart')>0){
    setupReviewCart();
  } else {
    setupCart();
    setupProducts();
  }
}

function setupReviewCart() {
  $('#center_cart input').change(function(){
    if(isNaN(this.value) || this.value < 0) this.value = 0;
    updateSum(this);
    alterQuantityRemote($(this.parentNode.parentNode).attr('id'), this.value);
  })
}

function updateSum(input) {
  var cell = $(input.parentNode)
  var price = parseCurrency(cell.prev().text());
  var quantity = parseInt(input.value);
  var newSum = price * quantity;
  var oldSum = parseCurrency(cell.next().text());
  cell.next().text(formatCurrency(newSum))
  var totalCell = $('#total td');
  var oldTotal = parseCurrency(totalCell.text());
  totalCell.text(formatCurrency(oldTotal + (newSum - oldSum)));
}

function alterQuantityRemote(product_id, new_quantity) {
  $.post("/alter_item_quantity",
         {
           id:       product_id,
           quantity: new_quantity
         }
  );
}

function setupCart() {
  $('#cart').load("/mini_cart", function(){
    $('#cart a.remove_item').click(function(){
		  removeFromCart(this.parentNode);
		  return false;
		});
  })
  .Droppable(
    {
      accept:      'product', 
      activeclass: 'activeCart', 
      hoverclass:  'hoverCart',
      tolerance:	 'intersect',
      onDrop:			  addProductToCart
    }
  );
}

function setupProducts() {
  $('a.add-button')
  .bind(
    'click',
    function() {
      $(this.parentNode)
      .TransferTo(
        {
          to:addProductToCart(this.parentNode.parentNode),
          className:'transferProduct',
          duration: 400
        }
      );
      return false;
    }
  );
  $('div.product').Draggable({revert: true, fx: 300, ghosting: true, opacity: 0.4});
}

function removeFromCart(item) {
  $.post("/remove_from_cart",
         {
           index: $('.productCart', item.parentNode).index(item)
         }
  );
  $(item).DropOutDown(
    400,
    function() {
      $(this).remove();
      calculateCartTotal();
    }
  );
}

var addProductToCart = function(dragged)
{
	var cartItem;
	var productName = $('.product_name', dragged).html();
	var productPrice = parseCurrency($('span', dragged).html());
	var productId = $(dragged).attr('id');
	var productURL = $('a',dragged).eq(0).attr('href');
	var isInCart = $('#' + productId + '_cart');
	if (isInCart.size() == 1) {
		var quantity = parseInt(isInCart.find('span.quantity').html()) + 1;
		isInCart.find('span.quantity').html(quantity+'').end().Pulsate(300, 2);
		cartItem = isInCart.get(0);
	} else {
		$('#cartProducts')
		.append('<div class="productCart" id="' + productId + '_cart"><a href="'+productURL+'">' + productName + '</a> <a class="remove_item" href="#">remover</a><br>qtd: <span class="quantity">1</span><br>preço: <span class="price">' + formatCurrency(productPrice) + '</span></div>')
		.find('div.productCart:last').fadeIn(400)
		.find('a:last').click(function(){
		  removeFromCart(this.parentNode);
		  return false;
		});
		cartItem = $('div.productCart:last').get(0);
	}
	calculateCartTotal();
	addItemRemote(productId);
	return cartItem;
};

function addItemRemote(id) {
	$.post("/add_to_cart", { id: id });
}

function parseCurrency(currency) {
  return parseFloat(currency.replace(/\D*(\d+),(\d+)/, "$1.$2"));
}

function formatCurrency(number) {
  return number.toFixed(2).replace(/(\d+).(\d+)/, "€$1,$2");
}

var calculateCartTotal = function()
{
	var total = 0;
	$('#cartProducts .productCart').each(
		function()
		{
			var price = parseCurrency($('span.price', this).html());
			var quantity = parseInt($('span.quantity', this).html());
			total += price * quantity;
		}
	);
	$('#cartTotal').html(formatCurrency(total));
	$('#cart p').Highlight(500, '#ff0', function(){$(this).css('backgroundColor', 'transparent');});
};
////// END SHOP //////
