$(document).ready(function() {

   $('.clRedPrice').click(function(){return false;});

   $('.clRedPrice').hover(
       function(){$('div[id="hint'+$(this).attr("id")+'"]').stop().animate({ opacity: "show" },"fast").animate({ opacity: "1"},"fast");;},
       function(){$('div[id="hint'+$(this).attr("id")+'"]').stop().animate({ opacity: "hide" },"slow");}
   );

  $('.clDescrDiv').hover(
       function(){
		var desc = $('div[id="description'+$(this).attr("iid")+'"]');
		if (desc.html().length>110)
			desc.stop().animate({ opacity: "show"},"fast").animate({ opacity: "1"},"fast");
		},

       function(){
		var desc = $('div[id="description'+$(this).attr("iid")+'"]');
		if (desc.html().length>110)
			desc.stop().animate({ opacity: "hide" },"slow");
		}
   );

   function PrepareOrderForm()
   {
         $(".idClose").click(function(){tb_remove();return false;});

	 $(".cAddr").click(function(){
              var num = $(this).attr("id").replace("idAddr","");
	      $("#user_address").val($('input[id="user_address'+num+'"]').val());
	      return false;
	 });

	 var Orderoptions = { 
                url: "/catalog/process/makeorder.php",
		beforeSend: function(data)
		{
                  $("#idOrderSubmit").attr("disabled","disabled");
		},
		success: function(data) 
		{
                    if (data.Error==1)
		    {
	               $("#idOrderSubmit").attr("disabled","");
                       $("#ErrorText").html(data.Message);
		       $("#TB_ajaxContent").animate({scrollTop:0},"slow");
		    }
		    else
		    {
		       $.ajax({
				   type: "GET",          
				   url: "/catalog/process/noticeorder.php",
				   dataType: "json",
				   timeout: 10000
		       });
			
		       $("#ErrorText").html("<CENTER>"+data.Message+"</CENTER>");
		       $("#CloseLink").html("Закрыть окно");
		       $("#TB_ajaxContent").animate({scrollTop:0, height:"200"},"slow");
		       $("#idOrderFormDiv").animate({opacity: "hide" },"slow");

		       $('#cartdiv').stop().animate({ opacity: "hide"},"slow");
		       UpdateCart();
		    }	
		},
		dataType:  'json',
    		timeout: 4000 // тайм-аут
	};

    	jQuery.validator.addMethod("phone_req", function( value, element ) {

		$("#user_phone1").next().html("");
		$("#user_phone2").next().html("");

		if ($("#user_phone1").val().replace(/^\s+|\s+$/g, '').length < 1 && $("#user_phone2").val().replace(/^\s+|\s+$/g, '').length < 1) return false;
		return true;

	}, "Нужно указать хотя бы один тел.");

 	$("#idOrderForm").validate({

	submitHandler: function(form) {
		  $(form).ajaxSubmit(Orderoptions);
		  return false;
	},
 
	rules: {
		user_name: 
		{
			required: true,
			minlength: 3,
			maxlength: 100
		},
		user_email:
		{
                    required: true,
		    email:true
		},
		user_phone1:
		{
                    phone_req: true
		},
		user_phone2:
		{
                    phone_req: true
		},
		user_address:
		{
                    required: true,
		    minlength: 5
		},
		imgcode:
                {
                    required: true,
		    remote: 
		    {
				url: "/registration/process/check_imagecode.php",
				type: "post",
				data: {
						str: function() {
							return $("#str").val();
							}
				      }
		    }
		}
	},
	messages: {
		user_name: {
			required: "Укажите ФИО",
			minlength: "Подозрительно коротко",
			maxlength: "Слишком длинно"
		},
		user_email:
		{
                    required: "Укажите e-mail",
		    email:"Странный адрес"
		},
		user_address:
		{
		    required: "Укажите адрес",
		    minlenght: "Не похоже на адрес"
		},
		imgcode:
                {
                    required: "Укажите код с картинки",
		    remote: "Код не верен"
		}

	},
    	errorPlacement: function(error, element) {
			error.appendTo(element.next());
		}
       });       

   }

   function SetupCart()
   {
	   $('input[name^="cBuyCount"]').click(function(){$(this).select();});
   	   $('input[name^="cCartCount"]').click(function(){
		$(this).select();
	   });

	   $('input[name^="cCartCount"]').change(function(){
		$('#cart_change').animate({ opacity: "show"},"slow");
	   });

	   $('input[name^="cCartCount"]').keydown(function(){
		$('#cart_change').animate({ opacity: "show"},"slow");
	   });

	   $('.csDelPositionFromCart').click(function(){
                var link = $(this);
		$.ajax({
		   		type: "GET",          
				url: link.attr('href'),
				dataType: "json",		
 			        timeout: 4000,	
		                success: function(data) 
				{
				    if (data.Error==1)
				    {
					$("#cart_change").attr("disabled","");
			 	        $("#cart_clear").attr("disabled","");
				        $("#cart_order").attr("disabled","");		
				        alert(data.Message);
				    }
				    else
				    {	
						UpdateCart();
						$('#cart_change').animate({ opacity: "show"},"fast");
				                $("#cart_change").attr("disabled","");
			 	                $("#cart_clear").attr("disabled","");
				                $("#cart_order").attr("disabled","");		
				    }   
				}
			});               
		return false;
	   });

   	   $('#cart_clear').click(function(){
		if (confirm('Вы действительно хотите удалить из корзины все позиции ?'))
		{
	               $("#cart_change").attr("disabled","disabled");
	               $("#cart_clear").attr("disabled","disabled");
	               $("#cart_order").attr("disabled","disabled");

		       $.ajax({
		   		type: "GET",          
				url: '/catalog/process/clear_cart.php',
 			        timeout: 4000,	
				dataType: "json",		
		                success: function(data) 
				{
				    if (data.Error==1)
				    {
					$("#cart_change").attr("disabled","");
			 	        $("#cart_clear").attr("disabled","");
				        $("#cart_order").attr("disabled","");		
				        alert(data.Message);
				    }
				    else
				    {	
			 		        $('#cartdiv').stop().animate({ opacity: "hide"},"slow");
						UpdateCart();
						$('#cart_change').animate({ opacity: "show"},"fast");
				                $("#cart_change").attr("disabled","");
			 	                $("#cart_clear").attr("disabled","");
				                $("#cart_order").attr("disabled","");		
				    }   
				}
			});
                }
   	   });

	   ChangeOptions = { 
                url: "/catalog/process/ChangeCart.php",
		beforeSend: function(data)
		{
	               $("#cart_change").attr("disabled","disabled");
	               $("#cart_clear").attr("disabled","disabled");
	               $("#cart_order").attr("disabled","disabled");
		},
		success: function(data) 
		{
                    if (data.Error==1)
		    {
	               $("#cart_change").attr("disabled","");
	               $("#cart_clear").attr("disabled","");
	               $("#cart_order").attr("disabled","");

                       alert(data.Message);
		    }
		    else
		    {	
		       UpdateCart();
		       $('#cart_change').animate({ opacity: "hide"},"fast");
	               $("#cart_change").attr("disabled","");
	               $("#cart_clear").attr("disabled","");
	               $("#cart_order").attr("disabled","");
		    }		
		},
		dataType:  'json',
    		timeout: 4000
  	  };

	   jQuery.validator.addMethod("cCartCnt", function(value, element) { 
		  return (this.optional(element) || /^\d+$/.test(value)) && $.trim(value).length > 0 && parseInt($.trim(value))>0;
	   }, "*");

	  $("#idCartCountForm").validate({
                  submitHandler: function(form) {
		  	  $(form).ajaxSubmit(ChangeOptions);
			  return false;
    	          },
 		  errorPlacement: function(error, element) {
			error.appendTo(element.next()); 	
		  }
	  });


          $("#idShowDiscDetails").click(function(){
              $("#idDiscountDetails").slideToggle("slow");
	      return false;
	  });

          $('#idCloseCart').click(function(){
		$('#cartdiv').stop().animate({ opacity: "hide"},"slow");
		return false;	
	  });
          	 

	  $('#cart_order').click(function(){
                var t = null;
    		var a = "/catalog/order/?width=700&modal=true";
		var g = false;	
	        tb_show(t,a,g,PrepareOrderForm);
	        this.blur(); 
    
        	return false;
	  });
 	
   }


   function UpdateCart()
   {
	$.ajax({
   		type: "GET",
 	        timeout: 4000,	          
		url: '/catalog/data/get_cart_total.php',
		dataType: "json",		
                success: function(data) 
		{
		    if (data.Error==1)
		    {
		        alert(data.Message);
		    }
		    else
		    {			
                         $('#idShowCart').html(data.Message);
		    }   
		}
	});

	$('#cartdiv').load('/catalog/data/load_cart_positions.php',function(){SetupCart();});
   }

   $('#idShowCart').click(function(){
        $("#cartdiv").slideToggle("slow");
      return false;
   });


   $('.cProcessBuy').click(function(){
      var ivid= $(this).attr("ivid");
      var Cnt = 1;
      var cBuyCount = $('input[name="cBuyCount'+ivid+'"]');
	if (cBuyCount.length>0)
	{
	    var val = cBuyCount.val().replace(/^\s+|\s+$/g, '');
	    if (val!="" && /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(val))
	    {
		    try
		    {
	        	    Cnt = parseInt(cBuyCount.val().replace(/^\s+|\s+$/g, ''));
			    if (Cnt<=0) Cnt=1;
		    }
		    catch(e)
		    {
                	   Cnt=1;
		    }
	   }
	}
        $.ajax({
   		type: "GET",          
		url: '/catalog/process/addtocart.php',
		data: "ivid="+ivid+"&cnt="+Cnt,
		dataType: "json",		
 	        timeout: 4000,	
                success: function(data) 
		{
		    if (data.Error==1)
		    {
		        alert(data.Message);
		    }
		    else
		    {			
			UpdateCart();
		    }   
		}
	});

      return false;
   });

   UpdateCart();
   SetupCart();
});
