$(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");
			// keyed in value is not a number; one item will added to your cart
			quantity = 1;
		} else {
			quantity = parseInt(quantity);
			alert("O valor digitado não é um número inteiro. Serão acrescentados " + quantity + " itens ao seu carrinho");
			// keyed in type is not an integer. quantity itens will be added to your cart
		}
	}	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");
      //     product added to the cart
    }
	} 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)
    //Masutani R10028 start
		if($(".cart_item").length >= 99){
		alert("This cart accepts up to 99 products.");
	} else {
    //Masutani R10028 end
		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");
      //     product added to the cart
    }
		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});
	}
    //Masutani R10028 start
	}
    //Masutani R10028 end
}

// 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();
      checkout_alcohol_check(productid);
    }
	} 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();
      checkout_alcohol_check(productid);
    }
	}	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_alcohol_check(productid){
	var oldproductcatlist = $("#checkout_producti_catlist").val();
	var alcoholcat = $("#alcohol_cat").val();
	var newproductcatlist = "";
	listarray = new Array();
	listarray = oldproductcatlist.split(",");
	var alcoholflag = false;
	for(i = 0; i < listarray.length; i++){
		if(productid == listarray[i].substr(0, productid.length) ){  
			listarray.splice(i,1); 
		}else{
			newproductcatlist = newproductcatlist + listarray[i] + ",";
			if(listarray[i].substr(listarray[i].length - 4, 4) == alcoholcat)
				alcoholflag = true;
		}
	}
	$("#checkout_producti_catlist").val(newproductcatlist);
	if(!alcoholflag && $("#alcohol_check").length > 0)
	    $("#alcohol_check").remove();
}

function checkout_UpdatePrices() {
	var summary_subtotal = parseInt($("#summary_subtotal").val());
	var point_balance = parseInt($("#point_balance").val());
	var point_percentage = parseInt($("#point_percentage").val());
	var checkout_points_str = $("#checkout_points").val();

	if(!checkout_points_str){
		checkout_points_str = "0";
	}

// Delete comma and period.
	checkout_points_str = checkout_points_str.replace(/,|\./g, "");

// Check points is a number
	if(isNaN(checkout_points_str)){
		var error_msg = $("#error_points_not_number").val();
		alert(error_msg);
		$("#checkout_points").val(0);
		var checkout_points = 0;
	}else{
		var checkout_points = Number(checkout_points_str);
		checkout_points = Math.abs(checkout_points);
		$("#checkout_points").val(checkout_points);
	}

// Check in units of 100 points
	if(checkout_points % 100 != 0){
		var error_msg = $("#information_05").val();
		alert(error_msg);
		$("#checkout_points").val(0);
		checkout_points = 0;
	}
// Check points greater than subtotal
	if(summary_subtotal < checkout_points){
		var error_msg = $("#error_points_greater_than_total").val();
		alert(error_msg);
		$("#checkout_points").val(0);
		checkout_points = 0;
	}
// Check points greater than balance
	if(point_balance < checkout_points){
		var error_msg = $("#error_points_greater_than_balance").val();
		alert(error_msg);
		$("#checkout_points").val(0);
		checkout_points = 0;
	}
	
	var subtotal = 0;
	subtotal = summary_subtotal - checkout_points;

	var shipping = checkout_Shippingupdate(subtotal);
	var finalprice = subtotal + shipping;
	var estimated_points = Math.floor(subtotal * (point_percentage / 100));
		
	$("#subtotal_label").text(number_format(subtotal));
	$("#checkout_finalprice").val(finalprice);
	$("#checkout_finalprice_label").text(number_format(finalprice));
	$("#estimated_points").val(estimated_points);
	$("#estimated_points_label").text(number_format(estimated_points));

}

function checkout_Shippingupdate(subtotal) {
	var additional_shipping_fee = parseInt($("#additional_shipping_fee").val());
	var additional_shipping_limit = parseInt($("#additional_shipping_limit").val());
	var free_shipping_limit = parseInt($("#free_shipping_limit").val());
	var regular_shipping = parseInt($("#regular_shipping").val());
	var information_01 = $("#information_01").val();
	var information_02 = $("#information_02").val();
	var information_03 = $("#information_03").val();
	var information_04 = $("#information_04").val();

	if(subtotal >= free_shipping_limit){
		var shipping_discount = 0 - regular_shipping;
		$("#shipping_discount_label").text(number_format(shipping_discount));
		$("#shipping_discount_label").css({"color":"black"});
		var shipping_discount_information = information_01.replace("%limit%", number_format(free_shipping_limit));
		$("#shipping_discount_information").text(shipping_discount_information);
		$("#shipping_information").empty();
	}else{
		var shipping_discount = 0;
		$("#shipping_discount_label").text(number_format(shipping_discount));
		$("#shipping_discount_label").css({"color":"black"});
		var shortage = free_shipping_limit - subtotal;
		var shipping_information = information_02.replace("%shortage%", number_format(shortage));
		$("#shipping_information").text(shipping_information);
		$("#shipping_information").css({"color" :"red", "font-weight" :"bold"});
		$("#shipping_discount_information").empty();
	}

	if(subtotal < additional_shipping_limit){
		var extra_shipping_charge = additional_shipping_fee;
		$("#extra_shipping_label").text(number_format(extra_shipping_charge));
		$("#extra_shipping_label").css({"color":"black"});
		var extra_shipping_charge_information = information_04.replace("%limit%", number_format(additional_shipping_limit));
		$("#extra_shipping_charge_information").text(extra_shipping_charge_information);
		$("#extra_shipping_charge_information").css({"color" :"red", "font-weight" :"bold"});
	}else{
		var extra_shipping_charge = 0;
		$("#extra_shipping_label").text(number_format(extra_shipping_charge));
		$("#extra_shipping_label").css({"color":"black"});
		var extra_shipping_charge_information = information_03.replace("%limit%", number_format(additional_shipping_limit));
		$("#extra_shipping_charge_information").text(extra_shipping_charge_information);
		$("#extra_shipping_charge_information").css({"color":"black", "font-weight" :"normal"});
	}
	var shipping = regular_shipping + shipping_discount + extra_shipping_charge;
	$("#shipping").val(shipping);
	$("#shipping_discount").val(shipping_discount);
	$("#extra_shipping_charge").val(extra_shipping_charge);
	return(shipping);
}

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);
		$("#coupon_total").text(number_format(newcoupontotal));
		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);
		$("#coupon_total").text(number_format(newcoupontotal));
		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);
          window.location.reload();
        } else {
          window.location.reload();
        };
      }
    }
  );
	return false;
}

function logout() {
  $.post($("#jsphpbridge").val(),
    {locator: "logout"},
    function(data) {
      $("#loginbox").html(data);
      window.location.reload();
		});
	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;
}

