$(document).ready(function() {
	$(".draggableitem").draggable({
		opacity: 0.5,
		zIndex: 2000, 
		revert: 'invalid',
		helper: 'clone'
	});
	$(".drop").droppable(	{
		accept: ".draggableitem",
		activeClass: 'droppable-active',
		tolerance: 'touch',
		out: function() {
      $("#cartbar").fadeTo("fast", 1); 
    },
		drop: function(event, ui) {
      addProduct(event, ui, '', '1');
    }
	});
	$("div.scrollable_cart").scrollable({
		navi: "#shoppingcart",
		items: "#listitems",
		clickable: false,
		speed: 200
	});
});

function addProd(productid) {
	if ($("#product" + productid + "_quantity").length > 0) { 
    var quantity = $("#product" + productid + "_quantity").val();
	} else { 
    var quantity = 1; 
  }
	addProduct('', '', productid, quantity); 
}

function addProduct(ev, ui, clicked, quantity) {
	if (clicked != '') { 
    var productid = clicked;
  } else { 
    var productid = $(ui.draggable).attr("productid");
  }
	if (quantity != parseInt(quantity)) { 
		if (isNaN(quantity)) { 
			alert("O valor digitado não é um número. Será acrescentado 1 item ao seu carrinho"); 
			quantity = 1;
		} else {
			quantity = parseInt(quantity);
			alert("O valor digitado não é um número inteiro. Serão acrescentados " + quantity + " itens ao seu carrinho");
		}
	}	else { 
		quantity = parseInt(quantity);
	}
	var name = $("#product" + productid + "_name").val();
	var image = $("#product" + productid + "_image").val();
	var price = parseInt($("#product" + productid + "_price").val());
	var prodlink = $("#product" + productid + "_prodlink").val();
	
	if ($("#cartitem" + productid).length > 0) { // If the product is already in the cart just increase the quantity
		increaseQty(productid, quantity);
		if ($("#cartbar").css("display") == "none")	{ 
      alert("Produto adicionado ao carrinho");
    }
	} else { // Add the product If it is not in the cart
		/* IMPORTANT: The cart item can be added by Js when the "buy" button is clicked and by PHP when the page is loaded, so the code below must 
		be identical to the cart item generated by the functions.php file in order not to display differences between the item added by js and php */
		// Creating the short name to be shown on the cart bar (long names don't fit)
		if (name.length > 12) {
      var shortname = name.substr(0, 12) + "...";
    } else {
      var shortname = name;
    }
		// Mounting the cart item
		var cartitem = '<div id="cartitem' + productid + '" class="cart_item">';
		cartitem += '<input type="hidden" id="cartitem' + productid + '_name" value="' + name + '" />';
		cartitem += '<input type="hidden" id="cartitem' + productid + '_image" value="' + image + '" />';
		cartitem += '<input type="hidden" id="cartitem' + productid + '_price" value="' + price + '" />';
		cartitem += '<input type="hidden" id="cartitem' + productid + '_prodlink" value="' + prodlink + '" />';
		cartitem += '<div class="cell_mini"><img src="' + image + '" /></div>';
		cartitem += '<div class="cell_product"><a href="' + prodlink + '">' + shortname + '</a></div>';
		cartitem += '<div class="cell_control">';
		cartitem += '<div class="cell_qty">' + quantity + '</div>';
		cartitem += '<div class="cell_add"><a href="javascript:increaseQty(\'' + productid + '\', 1)"><img src="' + $("#base_dir").val() + '/images/cart_cell_control_pt2.gif" /></a></div>';
		cartitem += '<div class="cell_delete"><a href="javascript:decreaseQty(\'' + productid + '\')"><img src="' + $("#base_dir").val() + '/images/cart_cell_control_pt3.gif" /></a></div>';
		cartitem += '</div>';
		cartitem += '</div>';
		$("#listitems").prepend(cartitem);
		var scrollapi = $("div.scrollable_cart").scrollable();
		scrollapi.reload().begin();
		// Animating the cart item to show to the user that the product was added
		$("#cartitem" + productid).fadeOut(300);
		$("#cartitem" + productid).fadeIn(300);
		$("#cartitem" + productid).fadeOut(300);
		$("#cartitem" + productid).fadeIn(300);
		if ($("#cartbar").css("display") == "none") {
      alert("Produto adicionado ao carrinho");
    }
		var oldtotal = parseInt($("#carttotal").val());
		var prodtotal = quantity * parseInt(price);
		var newtotal = oldtotal + prodtotal;
		$("#carttotal").val(newtotal);
		$("#carttotal_label").text(number_format(newtotal));
		$.post($("#jsphpbridge").val(), 
      {locator: "addproduct", productid: productid , qty: quantity});
	}
}

// Increase the quantity of a product
function increaseQty(productid, quantity) {
	var price = parseInt($("#cartitem" + productid + "_price").val());
	var newqty = parseInt($("#cartitem" + productid + " > .cell_control > .cell_qty").text()) + quantity;
	$("#cartitem" + productid + " > .cell_control > .cell_qty").text(newqty);
	var oldtotal = parseInt($("#carttotal").val());
	var prodprice = quantity * price;
	var newtotal = oldtotal + prodprice;
	$("#carttotal").val(newtotal)
	$("#carttotal_label").text(number_format(newtotal));
	if ($("#summary").length > 0)	{
		$("#summaryline" + productid + " .qtybox").val(newqty);
		$("#summaryline" + productid + " .prodtotal").val(newqty * price);
		$("#summaryline" + productid + " .prodtotal_label").text(number_format(newqty * price));
		
		$("#summary_subtotal").val(newtotal);
		$("#summary_subtotal_label").text(number_format(newtotal));
	}
	if($("#checkout").length > 0) {
    checkout_UpdatePrices();
  }
	$.post($("#jsphpbridge").val(), 
    {locator: "increaseqty", productid: productid, qty: quantity});
}

// Decrease the quantity of a product. It removes the product if the quantity is 0
function decreaseQty(productid) {
	var newqty = parseInt($("#cartitem"+productid+" > .cell_control > .cell_qty").text()) - 1;
	var price = parseInt($("#cartitem" + productid + "_price").val());

	var oldtotal = parseInt($("#carttotal").val());
	var newtotal = oldtotal - price;
	if(newqty == 0) {
		// Removing the control buttons (increase and decrease) to avoid more clicks 
		$("#cartitem"+productid+" > .cell_control").remove();
		$("#cartitem"+productid).fadeOut(500, 
		  function() {
        $("#cartitem"+productid).remove();
        var scrollapi = $("div.scrollable_cart").scrollable(); 
        scrollapi.reload().prev();
      });
		$("#carttotal").val(newtotal);
		$("#carttotal_label").text(number_format(newtotal));
		if ($("#summary").length > 0) { 
			$("#summaryline"+productid).fadeOut(500,
        function() {
          $("#summaryline"+productid).remove();
        });
			$("#summary_subtotal").val(newtotal); 
			$("#summary_subtotal_label").text(number_format(newtotal)); 
		}
		if ($("#checkout").length > 0) {
      checkout_UpdatePrices();
    }
	} else {
		$("#cartitem"+productid+" > .cell_control > .cell_qty").text(newqty);
		$("#carttotal").val(newtotal)
		$("#carttotal_label").text(number_format(newtotal));
    if ($("#summary").length > 0) {
			$("#summaryline" + productid + " .qtybox").val(newqty);
			$("#summaryline" + productid + " .prodtotal").val(newqty * price);
			$("#summaryline" + productid + " .prodtotal_label").text(number_format(newqty * price));
			
			$("#summary_subtotal").val(newtotal);
			$("#summary_subtotal_label").text(number_format(newtotal));
		}
		if ($("#checkout").length > 0) {
      checkout_UpdatePrices();
    }
	}
  $.post($("#jsphpbridge").val(), 
    {locator: "decreaseqty", productid: productid});
}

// Update the quantity of a product in the summary
function updateSummaryQty(productid) {
	var newqty = $("#summaryline" + productid + " .qtybox").val();
	if (newqty == 0) { // If the quantity is 0 remove the product from cart
		var prodtotal = parseInt($("#summaryline" + productid + " .prodtotal").val());
		var oldtotal = parseInt($("#carttotal").val());
		var newtotal = oldtotal - prodtotal;
		$("#summaryline" + productid + " .updlink").remove();
		$("#summaryline" + productid).fadeOut(500,
		  function() {
        $("#summaryline" + productid).remove();
      });
		$("#cartitem"+productid+" > .cell_control").remove();
		$("#cartitem"+productid).fadeOut(500, 
		  function() {
			$("#cartitem"+productid).remove();
			
			var scrollapi = $("div.scrollable_cart").scrollable(); 
			scrollapi.reload().prev();
		});
		$("#summary_subtotal").val(newtotal);
		$("#summary_subtotal_label").text(number_format(newtotal));
		
		$("#carttotal").val(newtotal);
		$("#carttotal_label").text(number_format(newtotal));
		if ($("#checkout").length > 0) {
      checkout_UpdatePrices();
    }
	}	else { // Just update the quantity
		var oldprodtotal = parseInt($("#summaryline" + productid + " .prodtotal").val());
		var oldtotal = parseInt($("#carttotal").val());
		var newqty = parseInt($("#summaryline" + productid + " .qtybox").val());
		var prodprice = parseInt($("#summaryline" + productid + " .price").val());
		var parctotal = oldtotal - oldprodtotal;
		var newprodtotal = newqty * prodprice;
		var newtotal = parctotal + newprodtotal;
		$("#summaryline" + productid + " .prodtotal").val(newprodtotal);
		$("#summaryline" + productid + " .prodtotal_label").text(number_format(newprodtotal));
		$("#summary_subtotal").val(newtotal);
		$("#summary_subtotal_label").text(number_format(newtotal));
		$("#carttotal").val(newtotal);
		$("#carttotal_label").text(number_format(newtotal));
		$("#cartitem"+productid+" > .cell_control > .cell_qty").text(newqty);
		if ($("#checkout").length > 0) {
      checkout_UpdatePrices();
    }
	}
  $.post($("#jsphpbridge").val(),
    {locator: "updateqty", productid: productid, qty: newqty});
}

function checkout_UpdatePrices() {
	var summary_subtotal = parseInt($("#summary_subtotal").val());
	var shipping = parseInt($("#shipping").val());
	var coupontotal = parseInt($("#checkout_coupon_total").val());

  var finalprice = 0;
  if(summary_subtotal - coupontotal > 0)
    finalprice = summary_subtotal - coupontotal + shipping;
  else
    finalprice = shipping;

  subtotal = summary_subtotal + shipping;
	$("#total_label").text(number_format(subtotal));
	
	$("#checkout_finalprice").val(finalprice);
	$("#checkout_finalprice_label").text(number_format(finalprice));
}

function checkout_UseCoupon(couponid) {
	if ($("#checkout_coupon" + couponid).is(":checked")) { // If the user has checked
		var couponvalue = parseInt($("#checkout_coupon" + couponid + "_value").val());
		var oldcoupontotal = parseInt($("#checkout_coupon_total").val());
		var newcoupontotal = couponvalue + oldcoupontotal;
		$("#checkout_coupon_total").val(newcoupontotal);
		var oldcouplist = $("#checkout_coupon_used").val();
		var newcouplist = oldcouplist + couponid + ",";
		$("#checkout_coupon_used").val(newcouplist);
		checkout_UpdatePrices();
	} else { 	// If the user has unchecked
		var couponvalue = parseInt($("#checkout_coupon" + couponid + "_value").val());
		var oldcoupontotal = parseInt($("#checkout_coupon_total").val());
		var newcoupontotal = oldcoupontotal - couponvalue;
		$("#checkout_coupon_total").val(newcoupontotal);
  	var oldcouplist = $("#checkout_coupon_used").val();
		var delcouponid = couponid + ",";
		var newcouplist = oldcouplist.replace(delcouponid, "");
		$("#checkout_coupon_used").val(newcouplist);
		checkout_UpdatePrices();
	}
}

// Function used to find products by name
function searchProducts(divname) {
	window.location.href = $("#search_page").val() + "/name/" + $("#" + divname + "_string").val();
	return false;
}

function setProductPic(image) {
  $("#product_pic").empty().html('<img src="' + $("#base_dir").val() + '/images/loading.gif" />');
  $("#product_pic").empty().html(image);
  return false;
}

//==============================================================================
// AJAX functions
//==============================================================================
function login(divname) {
	var email = $("#" + divname + "_email").val();
	var password = $("#" + divname + "_password").val();
  $.post($("#jsphpbridge").val(), 
    {locator: "login", email: email, password: password}, 
    function(data) {
		  if(data.indexOf("login_error") > -1) {
        $("#" + divname + "_error").html(data);
        $("#" + divname + "_error").fadeOut(500);
        $("#" + divname + "_error").fadeIn(500);
		  } else {
		    if(divname == "loginbox") {
          $("#" + divname).html(data);
        } else {
          window.location.reload();
        };
      }
    }
  );
	return false;
}

function logout() {
  $.post($("#jsphpbridge").val(), 
    {locator: "logout"}, 
    function(data) {
      $("#loginbox").html(data);
		});
	if($("#checkout").length > 0)	{
    window.location.href = $("#home_page").val();
  }
}

function recoverPassword() {
  var email = $("#recoverpassword_email").val();
  $.post($("#jsphpbridge").val(), 
    {locator: "password", email: email}, 
    function(data) {
		  if(data.indexOf("email_not_found") > -1) {
        $("#recoverpassword_error").html(data);
        $("#recoverpassword_error").fadeOut(500);
        $("#recoverpassword_error").fadeIn(500);
		  } else {
        $("#recoverpassword").empty().html(data);
      }
    }
  );
	return false;
}

function addProductFromDb(productid) {
	if($("#cartitem"+productid).length > 0) {
    increaseQty(productid, 1);
  } else {
    var newitem = '<div id="cartitem' + productid + '" class="cart_item"><img src="' + $("#base_dir").val() + '/images/loading.gif" alt="Loading" /></div>';
    $("#listitems").prepend(newitem);
		$.post($("#jsphpbridge").val(), 
      {locator: "addproductfromdb", productid: productid, qty: 1}, 
		  function(data) { 
        $("#cartitem" + productid).remove();
        $("#listitems").prepend(data);
        var price = parseInt($("#cartitem" + productid + "_price").val());
        var oldtotal = parseInt($("#carttotal").val());
        var newtotal = oldtotal + price;
        $("#carttotal").val(newtotal)
        $("#carttotal_label").text(number_format(newtotal));
        var scrollapi = $("div.scrollable_cart").scrollable();
        scrollapi.reload().begin();
		  });
	}
}

//==============================================================================
// Utilities
//==============================================================================
function number_format( number, decimals, dec_point, thousands_sep ) 
{
    // *     example 1: number_format(1234.56);
    // *     returns 1: '1,235'
    // *     example 2: number_format(1234.56, 2, ',', ' ');
    // *     returns 2: '1 234,56'
    // *     example 3: number_format(1234.5678, 2, '.', '');
    // *     returns 3: '1234.57'
    // *     example 4: number_format(67, 2, ',', '.');
    // *     returns 4: '67,00'
    // *     example 5: number_format(1000);
    // *     returns 5: '1,000'
    // *     example 6: number_format(67.311, 2);
    // *     returns 6: '67.31'
    // *     example 7: number_format(1000.55, 1);
    // *     returns 7: '1,000.6'
    // *     example 8: number_format(67000, 5, ',', '.');
    // *     returns 8: '67.000,00000'
    // *     example 9: number_format(0.9, 0);
    // *     returns 9: '1'
    // *     example 10: number_format('1.20', 2);
    // *     returns 10: '1.20'
    // *     example 11: number_format('1.20', 4);
    // *     returns 11: '1.2000'
    // *     example 12: number_format('1.2000', 3);
    // *     returns 12: '1.200'
    var n = number, prec = decimals;
 
    var toFixedFix = function (n,prec) {
        var k = Math.pow(10,prec);
        return (Math.round(n*k)/k).toString();
    };
 
    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
    var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;
 
    var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;
 
    var abs = toFixedFix(Math.abs(n), prec);
    var _, i;
 
    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;
 
        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }
 
    var decPos = s.indexOf(dec);
    if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) {
        s += new Array(prec-(s.length-decPos-1)).join(0)+'0';
    }
    else if (prec >= 1 && decPos === -1) {
        s += dec+new Array(prec).join(0)+'0';
    }
    return s;
}
