function setCookie (name, value, path, expires, domain, secure){
   document.cookie = name + "=" + escape(value) +
   ((expires) ? "; expires=" + expires : "") +
   ((path) ? "; path=" + path : "") +
   ((domain) ? "; domain=" + domain : "") +
   ((secure) ? "; secure" : "");
}

function cookieVal(cookieName){
  thisCookie = document.cookie.split("; ")
  for(i = 0; i < thisCookie.length; i++){
      if(cookieName == thisCookie[i].split("=")[0]){
         return thisCookie[i].split("=")[1];
      }
  }
  return 0;
}

function addCommas(nStr){
//    nStr = nStr.replace(",", ".");
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? ',' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + '&nbsp;' + '$2');
  }
  
  return x1 + x2;
}

function form_submit(name){
  document.getElementById(name).submit();
}

function showCaptcha(){
  var secure = document.getElementById('secure'); 
  secure.innerHTML = '<img src="/kcaptcha/kcaptcha_view.php"/>';
}

function reload(){   
  var rndval = new Date().getTime();
  document.getElementById('dle-captcha').innerHTML = '<img src="/kcaptcha/kcaptcha_view.php?f='+rndval+'" width="120" height="50" border="0" alt="" /><br/><a href="javascript:void();" onclick="reload(); return false;" class="reloadcapcha">обновить</a>';
}

function shopping_cart_frm(mode){
  if(mode=='order'){
    ord_name = $("#ord_name").attr("value");
    ord_email = $("#ord_email").attr("value");
    if(ord_name==''){
      alert('Поле фамилия и имя пустое');
      return false;
    } 
    if(ord_email!=''){
      if(ord_email!=''){
        if (/^([\w-~_]+\.)*[\w-~_]+@([\w-_]+\.){1,3}\w{2,4}$/.test(ord_email)){       
        }
        else{
          alert("Не верный формат E-mail");

          return false;
        }
      }    
    }
    else{
      alert("Поле E-mail пустое");
      return false;
    }
  }
  document.getElementById('shopping_cart').method='post';
  document.getElementById('shopping_cart').action='/cart/'+mode+'/';
  document.getElementById('shopping_cart').submit();
}

function add2Cart(){
  $(".button").click(function () {
    id = $(this).attr("sid");
    thisTovar = $(this).parent();
    itm_count = $('#itm_count_'+id).val();
    if(itm_count > 0){
      $(this).parents('.content').prepend('<div id="tov_overlay" class="tov_overlay"></div>');
      $.getJSON('/ajax/addcart/',{item_id:id, itm_count:itm_count},function(result){
        if(result.res!=''){
          if(!$(thisTovar).find(".incard").hasClass('incardtrue')){
            $(thisTovar).find(".incard").addClass('incardtrue');
          }        
          $(thisTovar).find(".button").html(result.text);
          $("#cart").html(result.res);
          $('#tov_overlay').remove();
        }
      })
    }
    else{
      if(itm_count==0 || itm_count<0){
        alert('Количество указано неверно');
      }
    }    
  });

  $(".incard").click(function(){
    id = $(this).attr("fid");
    thisTovar = $(this).parent();
    itm_count = $('#itm_count_'+id).val();
    if(itm_count > 0){
      $(this).parents('.content').prepend('<div id="tov_overlay" class="tov_overlay"></div>');
      $.getJSON('/ajax/addcart/',{item_id:id, itm_count:itm_count},function(result){
        if(result.res!=''){
          if(!$(thisTovar).find(".incard").hasClass('incardtrue')){
            $(thisTovar).find(".incard").addClass('incardtrue');
          }        
          $(thisTovar).find(".button").html(result.text);
          $("#cart").html(result.res);
          $('#tov_overlay').remove();
        }
      })
    }
    else{
      if(itm_count==0 || itm_count<0){
        alert('Количество указано неверно');
      }
    }
  });
  
  $(".button2").click(function () {
    thisTovar = $(this).parent();
    $(thisTovar).find(".incard2").trigger('click');
  });

$(".incard2").click(function(){
			var this_count;
			var this_id;
      var jsonItem = '';
			var jsonCount = '';
      //var a=1;
      var hhh = $(this).parents('.colors').height();
      $(this).parents('.colors').prepend('<div id="tov_overlay" class="tov_overlay" ></div>');
      $("#tov_overlay").height(hhh);
			var countLength = $('.colors .count').length;
			$('.colors .count').each(function(index, count){
        this_count = $(count).val();
				this_count = this_count*1;
				this_id = $(count).attr('itid');
				if(this_count > 0){
          jsonItem+=this_id +'-';
					jsonCount+=this_count +'-';
				}     
        if(jsonItem!=''){                   
				  if(index == (countLength-1)){
					  $.get('/ajax/addcolorscart/', {'item_id':jsonItem, 'itm_count':jsonCount} ,function(result){
              if(result){
                $("#cart").html(result);
						    $('#tov_overlay').replaceWith('<div id="tov_overlay" class="tov_overlay2"></div>');
                $("#tov_overlay").height(hhh);
						    setTimeout(function() {$("#tov_overlay").remove()}, 1000);
              }
					  });
				  }
        }
        
			})
      
      if(jsonItem==''){
        $("#tov_overlay").remove();
        alert('Укажите необходимое количество товара');
      }
	});

}

$(document).ready(function(){
  add2Cart();
  
  $("#sigin_form").keypress(function (e) {
      if ((e.which == 17)&&(e.which == 13)||(e.which == 13)) {
         $(this).submit();
      }
  });
  
  $("form").keypress(function (e) {
    var thisID = $(this).attr("id");
    if ((e.which == 17)&&(e.which == 13)||(e.which == 13)) {
      $(this).submit();
    }
  });
  
  if(errCapcha){
    window.scroll(0,10000);
    $("#capcha").focus();
    alert("Вы не правильно ввели символы на картинке!");
  }else{
    $(".ask:not(#feedback)").hide();
  }
  
  $(".reload").click(function () {
    $('input:checked').each(function(index, count){
      id = 0;
      id = $(count).attr("fid");      
      name = '#cart_'+id;
      $(name).remove();
      
      $.getJSON('/ajax/delfromcart/',{item_id:id},function(result){
        if(result){                       
          $("#cart").html(result.res);
          $(".optskid").html(result.cart_percent);
          $('.prices span').html(addCommas(result.total_price));          
          $(".reload").hide();
          if(result.total_price==0){            
            $("#tovar .content").html('<h1 class="tovhead">Корзина</h1>Ваша корзина пуста');
          }
        }
      })      
    });    
  });
  
  ///////////////////////////////////////////////////////////////////////////////////////
  
  $("#zakaz").click(function(event){ event.preventDefault();});
  $("#zakaz").click(function(){
    var errorVal = "поле обязательно для заполнения";
    //var starArr = new Array;
    var starLenght;
    var k = 0;
    star = $("#form .red");
    starLenght = $(star).length;
    for (i=0; i<starLenght; i++ ){
      idInput = $(star[i]).parent().attr("for");
      valInput = $("#"+idInput).val();
      if ((valInput=="")||(valInput==errorVal)){
        k++;
        $("#"+idInput).addClass("star2").val(errorVal);
      }
    }
    if (k==0){
      $('#cart_form').submit();
    }else{
      formInpuVal();
    }
  });
  
  $("#askk").click(function(event){ event.preventDefault();});
  $("#askk").click(function(){
    var errorVal = "поле обязательно для заполнения";
    var starArr = new Array;
    var starLenght;
    var k = 0;
    star = $(".ask .red");
    starLenght = $(star).length;
    for (i=0; i<starLenght; i++ ){
      idInput = $(star[i]).parent().attr("for");
      valInput = $("#"+idInput).val();
      if ((valInput=="")||(valInput==errorVal)){
        k++;
        $("#"+idInput).addClass("star2").val(errorVal);
      }
    }

    if (k==0){    
      $('#cart_form').submit();
    }else{
      formInpuVal();
    }
  });

  function formInpuVal(){
    var asInitVals = new Array();
    $("#form input").each( function (i) {
        asInitVals[i] = this.value;
        
      });
    
    $("#form input").focus( function () {
        if ( this.className == "star2" ){
          this.className = "";
          this.value = "";
        }
      });
    $("#form input").blur( function (i) {
          thisValue = str = jQuery.trim(this.value);
        if (thisValue == "" ){
          this.className = "star2";
          this.value = asInitVals[$("#form input").index(this)];
        }
      });
  }
  
})
