function productTableZebraBind(){
  $('.cProductList tr:even').addClass('even');
}

/* Clear text by alfavit */
function clearByAlfavit(txt, alfavit){
  if (txt && alfavit){
    txtLength = txt.length;
    result = "";
    for (var i = 0; i < txtLength; i++){
      symbol = txt.charAt(i);
      if ( alfavit.indexOf(symbol) != -1){
        result += symbol;
      }
    }
    return result;
  }
  return null;
}

function checkOrder() {
  var forma = $('.cOfferForm.mCart');
  var errors = new Array();
  if ($.trim(forma.find('input[name="fio"]').val()) == '') {
    errors.push('Введите, пожалуйста, ваше имя!');
  }
  if ($.trim(forma.find('input[name="phone"]').val()) == '') {
    errors.push('Введите, пожалуйста, контактный телефон!');
  }
  if (errors.length > 0) {
    daAlert('Ошибка', errors.join('<br>'), 'ok', 'msgError');
  } else {
    //Удалить данные из cookie
	$(".tovarList:last tr:gt(0)").each(function() {
		var rel = $(this).attr("rel");
		if (typeof(rel) != "undefined") $.cookie('product[' + rel + ']', null, {path:'/'});
	});
    //
      
    forma.submit();
  }
}

function clearInt(txt){
  return clearByAlfavit(txt, "0123456789");
}

Number.prototype.isInt = function() {
  return (Math.round(this) == this);
}
Number.prototype.roundTo = function(n) {
  var x = 0;
  if (typeof(n) == 'number') if (n.isInt()) if (n >= -6 && n <= 6) x = n;
  x = Math.pow(10,x);
  return Math.round(this*x)/x;
}
Math.roundTo = function(i,n) {
  return (typeof(i) == 'number') ? i.roundTo(n) : false;
}

/*
toNormal(value) - приводит число в нормальный вид (довольно часто арифметические операции в JavaScript
возвращают число типа 1.9999999999999998, данная функция его округляет)
**/

function toNormal(value) {
  if (arguments.length == 1 && value != null) {
    value = value.toString();
    value = parseFloat(value.replace(/\,/, "."));
    if (!isNaN(value) && value !== null) {
      value = value.roundTo(3);
    }
  }
  return (!isNaN(value)) ? value : 0;
}
/* Приводит число к денежному формату 0.00 */
function toMoney(value) {
  value = toNormal(value);
  value = value.roundTo(2);
  return value.toFixed(2);
}

/* Делаем деление сумм на разряды */
function divideMoney(money){
  if (money.length < 6) return money;
  else {
    var result = "";
    var leftMoney = money.slice(0, (money.length-6));
    var rightMoney = money.slice(-6);
    var leftMoneyCount = leftMoney.length;
    var k = 0;
    for (var i = leftMoneyCount-1; i >= 0; i--){
      if (((k % 3) == 0) && (k != 0)) result = '&nbsp;'+result;
      k++;
if ($.browser.msie) {
    result = leftMoney.substring(i, i+1)+result;
  } else {
      result = leftMoney[i]+result;
}
    }
    result += "&nbsp;"+rightMoney;
    return result;
  }
}

/* Ищем родительский элемент по имени класса */
function findParent(el, className){
  var parent = el.parent();
  if (parent != null){
    if (parent.hasClass(className)) return parent;
    else return findParent(parent, className);
  } else {
    return null;
  }
}

/***********************************
 **********   Корзина   ************
 ***********************************/
function Cart(){}//Создаём объект Корзины

/* Запуск корзины */
Cart.init = function(existsPrice){
  if ($(".mCart.mCartModule").find(".tovarList li.item").length == 0) {
    $(".mCart.mCartModule .hdr h2").html('Корзина пуста');
  }

  Cart.productPricesExists = existsPrice;
  Cart.cartTovarBind();
  
  /* Навешивание событий по кнопки добавления элементов */
  $('.cProductList .buy .button').click(function(){
    var tovarItem  = findParent($(this), 'item');
    var countVal   = tovarItem.find('.count .text').val();
    var tovarId    = $(this).attr('rel');
    var tovarName  = tovarItem.find('.name').text();
    var tovarPrice = tovarItem.find('.tradePrice').text();
    Cart.addTovarAnimation(tovarItem);
    Cart.addTovar(tovarId, tovarName, tovarPrice, countVal);
  });
}

/* Навешивание событий по изменению цен */
Cart.cartTovarBind = function() {
  $('.mCart .tovarList .kolvo').each(function() {
    $(this).unbind('change').unbind('keydown').unbind('keyup')
		   .change(function(){Cart.updateKolvo($(this));})
		   .keydown(function(){Cart.updateKolvo($(this));})
		   .keyup(function(){Cart.updateKolvo($(this));});
    Cart.updateKolvo($(this));
  });
  
  $('.mCart .tovarList .close a').unbind('click').click(function(){
    var tovarId = $(this).attr('rel');
    Cart.delTovar(tovarId);
    Cart.updateSum();
    return false;
  });
  
  $('.mCart .btns .cart').unbind('click').click(function(){
    Cart.delAllTovar();
  });

  Cart.updateSum();
}

/* Обновление количества товара */
Cart.updateKolvo = function(thisKolvo) {
  var kolvo        = thisKolvo.find('input').val();
  var tovarItem    = findParent(thisKolvo, 'item');
  var tovarId      = tovarItem.attr('id').slice(7);
  
  //if (tovarId) {
  //alert('updateKolvo - product['+tovarId+'] - ' + kolvo);
  if (tovarId) $.cookie('product[' + tovarId + ']', kolvo, {path:'/'}); // Сохраняем товар в куки
  
  var cleanKolvo   = clearInt( kolvo );
  var priceElement = tovarItem.find('.price');
  var price        = priceElement.attr('rel')*100;
  var resultPrice  = String( cleanKolvo * price / 100 );
  resultPrice      = toMoney(resultPrice);
  resultPriceMoney = divideMoney( toMoney(resultPrice));
  priceElement.find('div').html( resultPriceMoney ).attr('rel', resultPrice).attr('title', resultPrice);
  if (cleanKolvo != kolvo) thisKolvo.find('input').val(cleanKolvo);
  //Обновить данные в корзине
  var li = $("#product" + thisKolvo.parent().attr("rel"));
  li.find(".kolvo input").val(kolvo);
  li.find(".price div").html(resultPriceMoney).attr('rel', resultPrice).attr('title', resultPrice);
  //}
  Cart.updateSum();
}

/* Обновление суммы заказа */
Cart.updateSum = function(){
  var sum = 0;
  $('.mCart:last .tovarList .price div').each(function() {
    sum += $(this).attr('rel')*1;
  });

  var sumString = String(sum);
  sumString = divideMoney( toMoney(sumString) );
  if (!Cart.productPricesExists) {sumString = null;}
  $('.mCart .itogo span').html(sumString).attr('title', sumString);
  var buttons = $('.mCart .btns');
  if (sumString == '0.00') {
    buttons.slideUp()
  } else if (!Cart.productPricesExists && $("li[id^='product']").length > 0) {
    buttons.slideDown();
  } else if ($("li[id^='product']").length == 0) {
    buttons.slideUp();
  } else {
    buttons.slideDown();
  }
}


/* Добавление товара в карзину */
Cart.addTovar = function(tovarId, tovarName, tovarPrice , countVal){
  countVal = clearInt(countVal)*1;
  if (countVal) {
	  var existedTovar = $('#product'+tovarId);
	  if (existedTovar.length > 0){
	    // Товар уже есть в списке, добавляем к нему элементы
	    var tovarKolvo = existedTovar.find('.kolvo');
	    tovarKolvo.find('input').val( tovarKolvo.find('input').val()*1 + countVal);
	    Cart.updateKolvo(tovarKolvo);
	  } else {
	    var tovarBlank = $('.mCart .tovarBlank li').clone();
	    tovarBlank.attr('id', 'product'+tovarId);
	    tovarBlank.find('.close a').attr('rel', tovarId);
	    tovarBlank.find('.name').html(tovarName);
	    tovarBlank.find('.price').attr('rel', tovarPrice);
	    var tovarKolvo = tovarBlank.find('.kolvo');
	    tovarKolvo.find('input').val(countVal);
	    $('.mCart .tovarList').append(tovarBlank);
	    Cart.updateKolvo(tovarKolvo);
	    Cart.cartTovarBind();
	  }
	  if ($(".mCart.mCartModule").find(".tovarList li.item").length == 0) {
	    $(".mCart.mCartModule .hdr h2").html('Корзина пуста');
	  } else {
	    $(".mCart.mCartModule .hdr h2").html('Ваш заказ');
	  }
  } else alert('Введите количество товара "' + tovarName + '"');
}

Cart.addTovarAnimation = function(tovarItem){
  var productX      = tovarItem.offset().left;
  var productY      = tovarItem.offset().top;
  var productWidth  = tovarItem.width();
  var productHeight = tovarItem.height();

  var cartTovarList = $(".mCart .itogo");
  var basketX       = cartTovarList.offset().left;
  var basketY       = cartTovarList.offset().top;

  var gotoX         = basketX - productX;
  var gotoY         = basketY - productY;

  var newWidth      = tovarItem.width() / 20;
  var newHeight     = tovarItem.height() / 10;

  $('<div style="background:#eee; position:absolute; top:'+productY+'; left:'+productX+'; width:'+productWidth+'; height:'+productHeight+'"></div>').prependTo("body")
    .animate({opacity: 0.8}, 100)
    .animate({opacity: 0.1, marginLeft: gotoX, marginTop: gotoY, width: newWidth, height: newHeight}, 1200, function (){ $(this).remove() }); 
}

/* Удаление товара из корзины */
Cart.delTovar = function(tovarId){
  $('#product' + tovarId).remove();
  $('tr.product' + tovarId).remove();
  
  //alert('delTovar - product['+tovarId+']');
  $.cookie('product['+tovarId+']', null, {path:'/'}); // Удаляем товар из куки
  
  if ($(".mCart.mCartModule").find(".tovarList li.item").length == 0) {
    $(".mCart.mCartModule .hdr h2").html('Корзина пуста');
  }
  
  if ($(".tovarList").length > 1) {
	  if ($(".tovarList:last tr:not(.itogo)").length == 1) $(".tovarList:last").replaceWith('<div style="margin-left:10px;">Корзина пуста</div>');
  }
}

Cart.delAllTovar = function(){
  $('.mCart .tovarList .close a').each(function(){
    tovarId = $(this).attr('rel');
    Cart.delTovar(tovarId);
  });
  Cart.updateSum();
}
