// Submit attribute form to obtain new price and stock (global)

var $java_language = 
  {
    in_stock: 'Op voorraad',
    less_than_3_days: 'Minder dan 3 dagen',
    more_than_3_days: 'Meer dan 3 dagen',
    product_added: 'Produkt is toegevoegd. Klik op de winkelwagen voor details.',
    product_added_title: 'Produkt is toegevoegd'    
  };

function supplyStatusIDTosupplyStatus(supplyStatusID)
{
    var supplyStatus = '<img src="/tp3/images/stock/stock'+supplyStatusID+'.png" />';
    var description;
    switch(supplyStatusID)
    {
    case 0:
      description = $java_language.in_stock;
      break;
    case 1:
      description = $java_language.less_than_3_days;
      break;
    case 2:
    default:
      description = $java_language.more_than_3_days;
      break;

    }
    supplyStatus = supplyStatus + '<br>('+description+')';
    return supplyStatus;
}

   function UpdatePriceAndStock(frm)
   {
	 	 //radio button clicked to choose
		frm.ajaxSubmit({
		 	url: "/ajax_updatePriceWorking.php",
			dataType: "json",
			timeout: 3000,
			beforeSubmit:  function(formData, jqForm, options){;
				$(".productAttrForm .loading").html('<img src="/tp3/images/ajax-loader.gif" />');
				$(".productAttrForm span[id=adjustedPrice]").html("");
			},
			success: function(responseText, statusText, xhr, $form){            			
				var adjustedPrice = responseText.adjustedPrice;
				var supplyStatusID = supplyStatusIDTosupplyStatus(responseText.supplyStatusID);
                                //var supplyStatusID = 'x'+responseText.supplyStatusID+'x';
				$(".productAttrForm span[id=adjustedPrice]").html(adjustedPrice);
				$(".productAttrForm span[id=supplyStatusID]").html(supplyStatusID);
				$(".productAttrForm .loading").html("");
			}
		 });
	}
	  
    
    // Update cartbox
    function updateCartBox(){
              $.ajax({
                    url: "/ajax_getCartbox.php",
                    dataType: "json",
                    type: "GET",
                    success: function(data){
                            $("#cartbox #noOfProducts").text(data.noOfProducts);
                            $("#cartbox #subTotalPrice").html(data.subTotalPrice);
                    }
             });
         };
         
	// Callback: Show response after user adds item to cart (from products.php attribute dropdown)
	// Global!
	function showProductAttrFormResponse(responseText, statusText, xhr, $form)  
  {
        if (responseText.status == false)
        {
          jAlert(responseText.message, "Error inserting item in cart");
        }
        if (responseText.url != null && responseText.url != '')
        { 
            window.location = responseText.url;
        }
        else
        {
          updateCartBox();
          jAlert($java_language.product_added, $java_language.product_added_title);
        }
    }         

$(document).ready(function(){

    updateCartBox();


	 /*ajax call when clicking addtocart button in productbox without attributes*/
	 $(".addToCartBtn").click(function(){
	 	 var productID = $(this).parents(".putincart").siblings(".generatedProductInfo").find("input[name=productID]").val();
		 $.ajax({
			url: "/ajax_addToCart.php",
			dataType: "json",
			type: "POST",
      success: function(data) {          
          updateCartBox();
	   jAlert($java_language.product_added, $java_language.product_added_title);
      },
			data: {productID:productID}
		 });
		 return false;
	 });
	 

  // make all productAttrForms ajax, add handles for click, and keyup and update price and stock info on each form
	 $(".productAttrForm").ajaxForm(               //"In Winkelwagen" button clicked
	     {
            dataType: "json",
            success: showProductAttrFormResponse  // post-submit callback
      }
    ); 
	 $(".productAttrForm input[type=radio]").click(function() 
    { 
                  UpdatePriceAndStock($(this).parents(".productAttrForm")); 
    });   		 
	 $(".productAttrForm input[type=text]").keyup(function(e){
	 	 //radio button clicked to choose      
		 $(".productAttrForm").ajaxSubmit({
		 	url: "/ajax_updatePriceWorking.php",
			dataType: "json",
			timeout: 3000,
			beforeSubmit:  function(formData, jqForm, options){;
				$(".productAttrForm .loading").html('<img src="/images/ajax-loader.gif" />');
			},
			success: function(responseText, statusText, xhr, $form){			
				var adjustedPrice = responseText.adjustedPrice;
				var supplyStatusID = supplyStatusIDTosupplyStatus(responseText.supplyStatusID);
                                //var supplyStatusID = 'x'+responseText.supplyStatusID+'x';
                                $(".productAttrForm span[id=adjustedPrice]").html(adjustedPrice);
                                $(".productAttrForm span[id=supplyStatusID]").html(supplyStatusID);
				$(".productAttrForm .loading").html("");
			}
		 });
	 });
	 // Update price and stock info on all productAttrForms!
   UpdatePriceAndStock($(".productAttrForm")); 

	 /*shopping cart ajax action when click delete button*/
	 $("#shoppingcart .delItemBtn").click(function(){
	 	$(this).parents("tr").remove();
		var totalPrice = 0;
		var totalAmount = 0;
		var productInCart = "";
		$(".productRow").each(function(){
			  var amount = parseInt($(this).find(".itemAmount").val());
			  var itemPrice = parseFloat($(this).find(".itemPrice").text());
			  totalPrice+=amount*itemPrice;
			  totalAmount+=amount;
			  productInCart = productInCart+$(this).find(".productID").val().toString()+'_'+amount+',';
		});
		$(".allTotalPrice").text(totalPrice.toFixed(2).toString());
		$(".totalAmount").text(totalAmount);

		//send productID and amount in cart to server
		$.ajax({
			url: "/ajax_changeCart.php",
			dataType: "html",
			type: "POST",
			data: {productInCart:productInCart}
		 });

		return false;
	 });

	 /*shopping cart ajax action when change amount*/
	 $(".itemAmount").each(function(){
		$(this).keyup(function(){
			var amount=parseInt($(this).val());
			//var itemPrice = parseFloat($(this).parents(".productRow").find(".itemPrice").text());
                        //var totalPrice = amount*itemPrice;
                        var itemPrice = $(this).parents(".productRow").find(".itemPrice").text();
                        var itemValue = parseFloat(itemPrice.match(/\b[0-9.]+\b/g));
			var totalPrice = amount*itemValue;
			$(this).parents(".productRow").find(".totalPrice").html("&euro;&nbsp;"+totalPrice.toFixed(2).toString());

			var allTotalPrice = 0;
			var totalAmount = 0;
			var productInCart = "";
			$(".productRow").each(function(){
				  //var totalPrice = parseFloat($(this).find(".totalPrice").text());
                                  var totalPrice = $(this).find(".totalPrice").text();
                                  var totalValue = parseFloat(totalPrice.match(/\b[0-9.]+\b/g));
				  var amount = parseInt($(this).find(".itemAmount").val());
				  allTotalPrice+=totalValue;
				  totalAmount+=amount;
				  productInCart = productInCart+$(this).find(".productID").val().toString()+'_'+amount+',';
			});
			$(".totalAmount").text(totalAmount);
			$(".allTotalPrice").html("&euro;&nbsp;"+allTotalPrice.toFixed(2).toString());

			//send productID and amount in cart to server
			$.ajax({
				url: "/ajax_changeCart.php",
				dataType: "html",
				type: "POST",
				data: {productInCart:productInCart}
			 });

		});
	 });



	 /*In afrekenen box,when change radio button*/
	 var changeAfrekenen = function(){
	 	var packagesRadio=$("#purchasebox").find("input[name=packages]");
		 if(packagesRadio.attr("checked")==true)
		 {
	 	      var packages = packagesRadio.val();
		 }
		 else
		 {
			  var packages = 0;
		 }
		 var bindingsRadio=$("#purchasebox").find("input[name=bindings][checked]");
	 	 var bindings = bindingsRadio.val();
         var antal = parseInt($("#purchasebox").find("input[name=antal]").val());

		 $.ajax({
			url: "ajax_afrekenen.php",
			dataType: "json",
			type: "POST",
			data: {packages:packages,bindings:bindings,antal:antal},
			beforeSend : function(){
				$("#purchasebox .totalPrice").html('<img src="images/ajax-loader.gif" />');
			},
			success: function(data){
				$("#purchasebox .totalPrice").html(data.adjustedPrice);
                                //var supplyStatusID = '<img src="/tp3/images/stock/stock'+data.supplyStatusID+'.png" />';
                                var supplyStatusID = supplyStatusIDTosupplyStatus(data.supplyStatusID);
				$("#purchasebox #SupplyStatusID").html(supplyStatusID);
			}
		 });
	 };
	 $("#purchasebox .radio").click(function(){
          changeAfrekenen();
	 });

	 $("#purchasebox #antal").keyup(function(){
          changeAfrekenen();
	 });






});
