jQuery(document).ready(function() {  
    
    $(".addToCart").click(function () { 
        
        if($(".addToCart").attr('id')!='' && $(".addToCart").attr('id')>0) {
              jQuery.ajax({
                type: "POST",
                url: baseUrl+"cart/add",
                data: "id="+$(".addToCart").attr('id'),
                async: false,
                cache: false,
                success: function(msg){
                    
                    $('.infoMessage').html(msg);    
                                
                    for(i = 0; i < 3; i++)
                    {
                        $(".infoMessage").fadeIn(400);
                        $(".infoMessage").fadeOut(200);
                    }
                    
                    $(".infoMessage").fadeIn(400);
                   // $('.infoMessage').fadeOut(5000); 
                    
                }
               });
        }
        
        return false;
    });
    
    $(".orderInCatalog").click(function () {     	
    	
    	var articul = '#articul_'+$(this).attr('id');
    	
    	if ($(articul).val()=='') {
    		alert("Please select the product property");
    		return false;
    	}
    	
        if ( $(this).attr('id')!='' && $(this).attr('id') > 0) {
	        var mess = "#mess"+$(this).attr('id');
	        var priceBlock = "#price"+$(this).attr('id');
	        $(priceBlock).hide();
	        $(mess).show();
	        $(mess).html('<img src="/images/mini-ajax-loader.gif" height="16" width="16"/>');	        
	        
	        
	        jQuery.ajax({
	            type: "POST",
	            url: baseUrl+"cart/add",
	            data: "id="+$(this).attr('id')+"&articul="+$(articul).val(),
	            async: false,
	            cache: false,
	            success: function(msg) {	            	
	                $(mess).html(msg);	            
	                for(i = 0; i < 3; i++)
	                {
	                   $(mess).fadeIn(200);
	                   $(mess).fadeOut(200);
	                }
	                $(priceBlock).fadeIn(4000);
	                //$(mess).fadeIn(400);
	            } 
	        });
	     }
         return false;
     });
     
   
    //передача данных на сервер, если покидает корзину    
   $(".productNum").keyup( function(event){
     // var str = "( " + e.pageX + ", " + e.pageY + " )";
     
       //check if was entered number
      if (!((event.keyCode >= 27 && event.keyCode<= 57) || event.keyCode == 46) && !( event.keyCode>=96 && event.keyCode<=106)) {
       //alert($(this).attr('value').substr(0,$(this).attr('value').length - 1));
        var newValue = $(this).attr('value').substr(0,$(this).attr('value').length - 1);
        if(newValue.length==0) newValue = 0;
        $(this).attr('value', newValue);
      }

      var pId = $(this).attr('id');   
      $total = $(".mprice_"+pId).html() * $(this).attr('value');
      $total = $total!='' ? $total : '0';      
       
      jQuery.ajax({
        type: "POST",
        url: baseUrl+"cart/edit",
        data: "id="+pId+'&qty='+$(this).attr('value'),
        success: function(msg){
        	$("#tmprice_"+pId).html($total);
        	refrechCart(); 
        }
       });         
      
      
    });
    
    
    //delete product from cart
    $(".removeProcuct").bind( 'click', function(){
        
     //if(confirm("Вы уверены?")){
     if(confirm(msg.areYouSure)){ 
         var elementId = '#block_'+$(this).attr('id');
         jQuery.ajax({
            type: "POST",
            url: baseUrl+"cart/del/",
            data: "id="+$(this).attr('id'),
            success: function(msg){
            	$(elementId).toggle(1000);
                $(elementId).remove();
            	$('#total_price').html('0');
                refrechCart();                    	
            }
        });    
        
        
     }
      return false;
    });
    
    
    if ( $('#bonus').html()*1 < $("#total_price").html()*1 ) {    	
    	$('#addressBlock').hide();
    	$('#warning').show();
    } else {
    	$('#warning').hide();
    }
    
    function refrechCart()
    {
      var $totalCart = 0;
      $(".tmprice").each(function(i){
          $totalCart += +$("#"+this.id).html();         
         });
      if($totalCart=='' || $totalCart==0)    {
          $('#infoRow').removeClass();
          $('#sendOrder').hide();
          $('#clearOrder').hide();
          $('#addressBlock').hide();          
      } else {
          $('#sendOrder').show();
          $('#clearOrder').show();
          $('#addressBlock').show();
      }
      
      if ($('#bonus').html()*1 < $totalCart*1) {
    	$('#addressBlock').hide();
    	$('#warning').show();
      } else if($totalCart!=0 || $totalCart!='') {
       	$('#addressBlock').show();
       	$('#warning').hide();
      }
      
      $totalCart = $totalCart!='' ? $totalCart : '0';
      
      $("#total_price").html($totalCart);
    }
    
    //clear cart
    $("#clearOrder").click(function(){
      if(confirm(msg.areYouSure)){
         
         $('.cartRow').each( function(){
           $(this).remove();
         });
         
         jQuery.ajax({
            type: "POST",
            url: baseUrl+"cart/clearAll/",
            data: "",
            success: function(msg){}
        });    
        
         $('#total_price').html('');   
         $('#infoRow').removeClass();
         $('#sendOrder').hide();
         $('#clearOrder').hide();
         $('#addressBlock').hide();
      }
    
    });  
    
   /**              submit cart form         **/
    $("#sendOrder").click(function() {    	    	    	
    	
    	if($("#listPosBlock :selected").val()== -1 || $("#listPosBlock :selected").val()==undefined) {
    		alert(msg.selectAZS);
    	    return false;
    	} 
    	return true;
    });
    
    
    /**         Autorization form   ****/ 
    $("#login").focus( function(){       	
    	$("#errLogMsg").html('');
    });
    
    $("#password").focus(function(){
        $("#errLogMsg").html('');
    });    
    
    $("#login").keydown( function(event){
    	if (event.keyCode==13 ) {
    	    submitLoginForm();   
    	}    	
    });
    
    $("#password").keydown( function(event){
    	if (event.keyCode==13 ) {
    	    submitLoginForm();   
    	}    	
    });
    
    /*$("#loginForm").submit(function () {*/
    $("#loginBtn").click(function () {    	
        return submitLoginForm();
    });
    
    
    
    function submitLoginForm()
    {
    	var result = false;
        
        if($("#login").val()==''){        	
          	$("#errLogMsg").html(msg.fillField);          	
          	return false;
        }
        
        if($("#password").val()=='') {        	
        	$("#errLogMsg").html(msg.fillField);
          	return false;        	
        }
        $("#loadingBlock").show("fast");
        
        jQuery.ajax({
                type: "POST",
                url: baseUrl+"auth/checkform",
                dataType : "json", 
                data: {"login": $("#login").val(), 'password': $("#password").val()},
                async: false,
                cache: false, 
                success: function (data, textStatus) {                    
                    $("#loadingBlock").hide("slow");
                    $.each(data, function(i, val) {                        
                       if ( i=='success' && val == 'true') {
                       	    $("#loginForm").submit();
                            result = false;
                         return;
                       }
                       //if error show message
                       if ( i=='error' && val != '') {
                       	 $("#authBlock").fadeOut(200);
    	                 $("#authBlock").fadeIn(200);        
                         $("#errLogMsg").html(val);
                         result = false;
                         return;
                       }
                       
                    })
                }    
               });               
        return result;
    }
    
    
    $("#listRegions").change(function () {
    	$("#sendOrder").attr("disabled", true);	
	    $("#sendOrder").addClass('disable');
    	$("#listPosContainer").html('');
    	if($("#listRegions  :selected").val()!= -1) {
    		$("#listPosContainer").html('<img src="/images/mini-ajax-loader.gif" height="16" width="16"/>');	        
    		$("#listPosContainer").load( baseUrl+"cart/getposlist", {"posid": $("#listRegions  :selected").val()} );
    	}
    });
    
    
    $(".haveSubrics").click(function () { 
        	
        if($(".haveSubrics").attr('id')!='' && $(".haveSubrics").attr('id')>0) {
          var subblock = "#subrubblock_"+$(this).attr('id');
          var link = $(this).attr('link');
          
          jQuery.ajax({
              type: "POST",
              url: baseUrl+"auth/menuposition",
              data: "id="+$(this).attr('id')+"&"+"disp="+$(subblock).css("display"),
              async: true,
              cache: false,
              success: function(msg){
              	if (link!=undefined || link!="#") {                  		
              		document.location.href = link;                  		
              	}
              	
              }
          });
          
          //for ie6 set hack
          //if ( jQuery.browser.msie && jQuery.browser.version=='6.0') {
          if ( jQuery.browser.msie) {
          	$(subblock).toggle();
          } else {
            $(subblock).slideToggle();              
          }
          $(this).toggleClass("activeItem");
          
           
          //return false;
          return true;
        }  
    
    });
    
    $("#markSearchBtn").click(function () {         	
    	if ( $("#fromMarks").val()=='' && $("#toMarks").val()=='') {
    		$("#marksFormMsg").show();
    		return false;
    	}
    });
    
    $("#fromMarks").focus(function(){$("#marksFormMsg").hide()});
    $("#toMarks").focus(function(){$("#marksFormMsg").hide()});
       
});

function changeStation(value) {
	if(value== -1) {		
	    $("#sendOrder").attr("disabled", true);	
	    $("#sendOrder").addClass('disable');
	} else {		
		$("#sendOrder").attr("disabled", false);	
		$("#sendOrder").removeClass('disable');
	}
};

function setArticul(propId, acticul)
{
	document.getElementById(propId).value = acticul;	
}

function setArticulByWin(prodId, articul)
{
	var property = "articul_"+prodId;
	document.getElementById(property).value = articul;	
	$.nyroModalRemove();
	
	order(prodId, articul);
}

function order(pId, articul)
{
	var mess = "#mess"+pId;
	var priceBlock = "#price"+pId;
	$(priceBlock).hide();
	$(mess).show();
	$(mess).html('<img src="/images/mini-ajax-loader.gif" height="16" width="16"/>');	        
	
	jQuery.ajax({
	    type: "POST",
	    url: baseUrl+"cart/add",
	    data: "id="+pId+"&articul="+articul,
	    async: false,
	    cache: false,
	    success: function(msg) {	            	
	        $(mess).html(msg);	            
	        for(i = 0; i < 3; i++)
	        {
	           $(mess).fadeIn(200);
	           $(mess).fadeOut(200);
	        }
	        $(priceBlock).fadeIn(4000);
	        //$(mess).fadeIn(400);
	    } 
	});
}
     