
//For cart summary
/*function refreshCartSummary(){
$.ajax({
   			type: "POST",
   			url: "/cms/rub/shop/priceManager/ajaxPrice.jsp",
   			data: "actType=getTotal&cartKey="  + $("#cartKeySummary").val() + "&couponId=",
   			success: function(msg){
     			msg = $.trim(msg);
				tdPrice = $("#totalCart");
				if(msg != ''){
					tdPrice.html("&euro; " + msg);
				}else{
					tdPrice.html("ERRORE");
				}
				
   			},
			error: function(msg){
     			
   			}
 		});	
		
		$.ajax({
   			type: "POST",
   			url: "/cms/rub/shop/priceManager/ajaxPrice.jsp",
   			data: "actType=getTotalItems&cartKey="  + $("#cartKeySummary").val(),
   			success: function(msg){
     			msg = $.trim(msg);
				tdPrice = $("#itemsCount");
				if(msg != ''){
					tdPrice.html(msg);
				}else{
					tdPrice.html("ERRORE");
				}
				
   			},
			error: function(msg){
     			
   			}
 		});	
}*/


//For cart summary
function refreshCartSummary(){
$.ajax({
   			type: "POST",
   			url: "/cms/rub/shop/priceManager/ajaxPrice.jsp",
   			data: "actType=getTotal&cartKey="  + $("#cartKeySummary").val() + "&couponId=",
   			success: function(msg){
     			msg = $.trim(msg);
				tdPrice = $("#totalCart");
				if(msg != ''){
					tdPrice.html("&euro; " + msg);
				}else{
					tdPrice.html("ERRORE");
				}

   			},
			error: function(msg){

   			}
 		});

		$.ajax({
   			type: "POST",
   			url: "/cms/rub/shop/priceManager/ajaxPrice.jsp",
   			data: "actType=getSummaryCart&cartKey="  + $("#cartKeySummary").val(),
                        dataType: "json",
   			success: function(msg){
                            // alert(msg);
                            var cart = $( "#cartContent" );
                            cart.html('');

                           if(msg.items > 0){
                               cart.append($( "<thead><tr><th class=\"itemDesHeader\">PRODOTTO</th><th class=\"itemQtyHeader\">Q.t&agrave;</th></tr></thead><tbody>" ));
                               $.each(msg.itemsDes,function( intIndex, objValue ){

                                   cart.append($( "<tr><td class=\"itemDes\">" + objValue.des + "</td><td class=\"itemQty\">" + objValue.qty + "</td></tr>" ));

                               });
                                cart.append($("</tbody>"));

                               }
                           


   			},
			error: function(msg){

   			}
 		});
}

function isInteger(val){
    if(isBlank(val)){
        return false;
    }
    for(var i=0;i<val.length;i++){
        if(!isDigit(val.charAt(i))){
            return false;
        }
    }
    return true;
}

function isBlank(val){
    if(val==null){
        return true;
    }
    for(var i=0;i<val.length;i++){
        if((val.charAt(i)!=' ')&&(val.charAt(i)!="\t")&&(val.charAt(i)!="\n")&&(val.charAt(i)!="\r")){
            return false;
        }
    }
    return true;
}

function isDigit(num){
    if(num.length>1){
        return false;
    }
    var string="1234567890";
    if(string.indexOf(num)!=-1){
        return true;
    }
    return false;
}

//Add item qty
function checkForEnterQty(event) {
    if (event.keyCode == 13) {
        var addItem = $("#" + $(event.target).attr("idItemInput"));

        addItemShop(addItem);
    }
}

//For adding item in cart
 	function addItemShop(addedItem){

            if(isInteger($("#qty_" + $(addedItem).attr("idItem")).val()) && $("#qty_" + $(addedItem).attr("idItem")).val() != 0){

                var qty = parseInt($("#qty_" + $(addedItem).attr("idItem")).val());
                var max = parseInt($("#qty_" + $(addedItem).attr("idItem")).attr('maxqty'));
                var min = parseInt($("#qty_" + $(addedItem).attr("idItem")).attr('minqty'));
                if( qty > max ){
                     $("#dialogShopDetContent").html("La quantit&agrave; inserita supera il massimo consentito");
                    $("#dialogShopDet").dialog('open');
                    $("#qty_" + $(addedItem).attr("idItem")).val('1');

                }else if(qty < min){
                     $("#dialogShopDetContent").html("La quantit&agrave; inserita &egrave; inferiore al minimo ordinabile");
                 $("#dialogShopDet").dialog('open');
                    $("#qty_" + $(addedItem).attr("idItem")).val('1');

                }else{
				$.ajax({
   					type: "POST",
   					url: "/cms/rub/shop/cartCommand.jsp",
   					data: "actType=addItem&itemCode=" + $(addedItem).attr("idItem") + "&qty=" + $("#qty_" + $(addedItem).attr("idItem")).val(),
					dataType: "json",
   					success: function(itemRes){
						$("#dialogShopDetContent").html(itemRes.msg);
                                               
					        $("#dialogShopDet").dialog('open');
							refreshCartSummary();
                                                $("#qty_" + $(addedItem).attr("idItem")).val('1');
   					},
					error: function(msg){
     					$("#dialogShopDetContent").html(msg);
					    $("#dialogShopDet").dialog('open');
                                            $("#qty_" + $(addedItem).attr("idItem")).val('1');
   					}
 				});
                    }
            }else{

                $("#dialogShopDetContent").html("Quantit&agrave; inserita non valida");
                $("#dialogShopDet").dialog('open');
                $("#qty_" + $(addedItem).attr("idItem")).val('1');

            }


                }



	function changeQty(itemShop){
            //alert('itemshop: ' + itemShop)
            //alert($(itemShop).val());

           // alert(testInteger($(itemShop).val()));

            if(testInteger($(itemShop).val())){

	    $("#dialogCart").dialog('option', 'buttons', {"OK": function() {$(this).dialog("close");}});
		$.ajax({
   			type: "POST",
   			url: "/cms/rub/shop/cartCommand.jsp",
   			data: "actType=modQty&itemCartKey=" + $(itemShop).closest("tr").attr("itemKey") + "&qty=" + $(itemShop).val(),
   			success: function(msg){
     			//alert( "Data Saved: " + msg );
				$("#dialogCartContent").html('Totale carrello aggiornato');
				$("#dialogCart").dialog('open');
                                validateCoupon();
				refreshSingle($(itemShop).closest("tr").attr("itemKey"),true);
                                refreshCartSummary();
   			},
			error: function(msg){
				$("#dialogCartContent").html(msg);
				$("#dialogCart").dialog('open');
   			}
 		});
            }else{
                $(itemShop).val(1);
                 $("#dialogCart").dialog('option', 'buttons', {"OK": function() {$(this).dialog("close");}});
		$.ajax({
   			type: "POST",
   			url: "/cms/rub/shop/cartCommand.jsp",
   			data: "actType=modQty&itemCartKey=" + $(itemShop).closest("tr").attr("itemKey") + "&qty=1",
   			success: function(msg){
     			//alert( "Data Saved: " + msg );
				$("#dialogCartContent").html('Quantit&agrave; immessa non valida');
				$("#dialogCart").dialog('open');
                                validateCoupon();
				refreshSingle($(itemShop).closest("tr").attr("itemKey"),true);
                                refreshCartSummary();
   			},
			error: function(msg){
				$("#dialogCartContent").html(msg);
				$("#dialogCart").dialog('open');
   			}
 		});

            }
	}




	function refreshTotal(){
		$.ajax({
   			type: "POST",
   			url: "/cms/rub/shop/priceManager/ajaxPrice.jsp",
   			data: "actType=getTotal&cartKey=" + $("#cartKey").val() + "&couponId=" + $("#couponId1").val(),
   			success: function(msg){
     			msg = $.trim(msg);
				tdPrice = $("#total_" + $("#cartKey").val());
				if(msg != ''){
					tdPrice.html("&euro; " + msg);
				}else{
					tdPrice.html("ERRORE");
				}

   			},
			error: function(msg){
     			$("#dialogCartContent").html(msg);
				$("#dialogCart").dialog('open');
   			}
 		});

		$.ajax({
   			type: "POST",
   			url: "/cms/rub/shop/priceManager/ajaxPrice.jsp",
   			data: "actType=getTotalPound&cartKey=" + $("#cartKey").val() + "&couponId=" + $("#couponId1").val() + "&transport=true&shipType=" + $("input[name='SpedType']:checked").val(),
   			success: function(msg){
     			msg = $.trim(msg);
				tdPrice = $("#totalpound_" + $("#cartKey").val());
				if(msg != ''){
					tdPrice.html("&euro; " + msg);
				}else{
					tdPrice.html("ERRORE");
				}

   			},
			error: function(msg){
     			$("#dialogCartContent").html(msg);
				$("#dialogCart").dialog('open');
   			}
 		});


		$.ajax({
   			type: "POST",
   			url: "/cms/rub/shop/priceManager/ajaxPrice.jsp",
   			data: "actType=getTotalPound&cartKey=" + $("#cartKey").val() +  "&transport=false",
   			success: function(msg){
     			msg = $.trim(msg);
				if(msg != ''){
				    $("#discountTot_" + $("#cartKey").val()).html("&euro; " + msg)
				}else{

				}

   			},
			error: function(msg){
     			$("#dialogCartContent").html(msg);
				$("#dialogCart").dialog('open');
   			}
 		});

		getShippingCosts();
	}


	function refreshSingle(itemKey,total){
		$.ajax({
   			type: "POST",
   			url: "/cms/rub/shop/priceManager/ajaxPrice.jsp",
   			data: "actType=getPrice&itemCartKey=" + itemKey,
   			success: function(msg){
     			msg = $.trim(msg);
				tdPrice = $("#price_" + itemKey);
				if(msg != ''){
					tdPrice.html("&euro; " + msg);
					if(total)
						refreshTotal();
				}else{
					tdPrice.html("ERRORE");
				}

   			},
			error: function(msg){
     			$("#dialogCartContent").html(msg);
				$("#dialogCart").dialog('open');
   			}
 		});
	}


	function calculateDiscount(){
		$.ajax({
   			type: "POST",
   			url: "/cms/rub/shop/priceManager/ajaxPrice.jsp",
   			data: "actType=getDiscount&couponId=" + $("#couponId1").val() + "&cartKey=" + $("#cartKey").val(),
   			success: function(msg){
     			msg = $.trim(msg);
				$("#discount_" +  $("#cartKey").val()).html("&euro; - " + msg);
   			},
			error: function(msg){
     			$("#dialogCartContent").html(msg);
				$("#dialogCart").dialog('open');
   			}
 		});
	}

	function getShippingCosts(){
		$.ajax({
   			type: "POST",
   			url: "/cms/rub/shop/priceManager/ajaxPrice.jsp",
   			data: "actType=getTotalShipping&cartKey=" + $("#cartKey").val() + "&shipType=" + $("input[name='SpedType']:checked").val(),
   			success: function(msg){
     			msg = $.trim(msg);
				$("#shipping_" +  $("#cartKey").val()).html("&euro; " + msg);
   			},
			error: function(msg){
     			$("#dialogCartContent").html(msg);
				$("#dialogCart").dialog('open');
   			}
 		});
	}


        function selectSpedType(){
		getShippingCosts();
                refreshTotal();
	}


	function validateCoupon(){
            //alert('validate coupon')
            if($("#couponId1").val()!=''){
		$.ajax({
   			type: "POST",
   			url: "/cms/rub/shop/coupon/ajaxCoupon.jsp",
   			data: "actType=validate&couponId=" + $("#couponId1").val() ,
   			success: function(msg){
     			msg = $.trim(msg);
				spanMess = $("#messCoupon");
				discRow = $("#discountRow");
				totalRow = $("#discountTotal");
				if(msg == 'true'){
					spanMess.html(" Coupon valido");
					calculateDiscount();
					discRow.show();
					totalRow.show();
					refreshTotal();
				}else{
					discRow.hide();
					totalRow.hide();
					spanMess.html(" Coupon non valido");
					refreshTotal();
				}
				if(!spanMess.is(":visible"))spanMess.toggle();
   			},
			error: function(msg){
     			$("#dialogCartContent").html(msg);
				$("#dialogCart").dialog('open');
   			}
 		});
            }
                //alert('fine validate')
	}

	function delItemConfirmed(itemKey){
		$("#dialogCart").dialog('option', 'buttons', {"OK": function() {$(this).dialog("close");}});
		$.ajax({
   			type: "POST",
   			url: "/cms/rub/shop/cartCommand.jsp",
   			data: "actType=delItem&cartKey=1&itemCartKey=" + itemKey,
			dataType: "json",
   			success: function(itemRes){
			    $("#dialogCartContent").html(itemRes.msg);
				$("#dialogCart").dialog('open');
				if(itemRes.msgState == 'true'){
					$("tr[itemKey='" + itemKey + "']").remove();
				}
                                //validateCoupon();
				//refreshTotal();
                                //refreshCartSummary();
                                document.location.replace("/home.jsp?idrub=-14");
   			},
			error: function(msg){
     			$("#dialogCartContent").html(msg);
				$("#dialogCart").dialog('open');
   			}
 		});

	}

	function delItem(itemKey){
	$("#dialogCartContent").html("Cancellare prodotto?");
	$("#dialogCart").dialog('option','buttons',{"Elimina": function() {delItemConfirmed(itemKey);}, "Annulla": function() {$(this).dialog("close");$(this).dialog('option', 'buttons', {"OK": function() {$(this).dialog("close");}});}} );

		$("#dialogCart").dialog('open');
	}	


function testInteger(value){

    if (value.match(/^\d+$/) == null){
        return false;
    }else{
        if(parseInt(value, '10') == 0)
            return false;
        else
            return true;
    }


}


