$(function(){
  $('a.subscribe').livequery('click', function(event){
    event.preventDefault();
    event.stopPropagation();
    var url = $(this).attr('href');
    var target = $(this).parents('div.subscribe-form:first');
    var data = $(this).parents('form:first').serializeArray();
    $.post(url, data, function(html){
      target.replaceWith(html);
    });
  });
  // правое меню
  $('div.treeable div.nav a').livequery('click', function(event){
    event.stopPropagation();
    $(this).parents('.nav').find('li').removeClass('current');            // deleting class "current" everywere
    $(this).parents('li:first').toggleClass('collapsed').toggleClass('current').find('ul:first').toggle('slide');
    $(this).parents('li').addClass('current');                            // adding class "current" to all <li> parents
    
    /* inside items "current" styles */
    $(this).parents('.nav').find('li').css("font-weight", "normal");
    $(this).parents('li').css("font-weight", "bold");

    if (!$(this).hasClass('goto'))
    {
      event.preventDefault();
    }
  });

  
    $(function(){
      $("a[rel^='prettyPhoto']").prettyPhoto({
        theme: 'light_square',
        allowresize: false
      });
    });

  $('table.recalc-table input.recalc-qty').livequery('focus', function(event){
    $(this).select();
    event.preventDefault();
  });




  var gridTable = function(table, height){
    if (!height) height = 700;
    var table = $(table);
    var tableNew = table.clone();
    tableNew.removeClass('gridable').removeAttr('id');
    tableNew.addClass('clone');
    var container = $('<div class="clone-area" style="overflow: auto;"></div>');
    container.insertAfter(table);
    tableNew.appendTo(container);

    tableNew.find('thead').remove();
    fixWidthGrid(table, tableNew, container);
    table.find('thead th:last').addClass('last');
    if (!$.browser.opera){
      table.find('thead th:last').corner('round tr 5px cc:#EEF9FD');
      table.find('thead th:first').corner('round tl 5px cc:#EEF9FD');
    }
    $('td', table).livequery('html', function(event){
      fixWidthGrid(table, tableNew, container);
    });
    var totalHeight =  tableNew.height();
    
    if (totalHeight < height){
      height = totalHeight;
    }
    
    container.height(height);
  }

  var fixWidthGrid = function(table, tableNew, container){
    tableNew.find('thead').remove();
    table.find('thead th').each(function(i,elm){
      var width = $(elm).width();
      tableNew.find('tbody tr td').eq(i).width(width);
    });

    table.find('tbody').remove();
    tableNew.find('tbody tr:first td').each(function(i, elm){
      var width = $(elm).width();
      table.find('thead th').eq(i).width(width);
    });
    container.width(table.width());
  }

  $('#table:first, #table-mat:first, table.gridable').livequery(function(){
    gridTable(this);
  });
  

  // форма заказа
  $('input.recalc-qty').livequery('change', function(){
    $(this).val($(this).val().replace(',','.'));
    var qty = parseFloat($(this).val());
    var row = $(this).parents('tr:first');
    var max = $(this).attr('max');
    if (qty>max)
    {
      alert('Вы указали количество большее, чем имеется на складе');
      $(this).val(max);
      qty = max;
      // return false;
    }
    
    var width = parseFloat(parseInt($(this).attr('propwidth')));
    var length = parseFloat(parseInt($(this).attr('proplength')));
    if (!/(\d+)/.test(length)) length= 0;
    var square = ( (width * length) / 1000000 ) * qty;
    var weight = parseFloat(parseInt($(this).attr('propweight')) / 1000);
    var price = $(this).attr('price');
    if ($(this).attr('priceeur')) price = $(this).attr('priceeur');
    var tot_weight = square * weight;
    if ($(this).attr('nopaperrecalc')){
      $(row).find('span.recalc-weight').html(parseFloat(tot_weight).toFixed(2));
      $(row).find('span.recalc-summ').html(parseFloat(qty * price).toFixed(2));
    }else{
      $(row).find('span.recalc-weight').html(parseFloat(tot_weight).toFixed(2));
      $(row).find('span.recalc-summ').html(parseFloat(tot_weight * price).toFixed(2));
    }
    
    var total = 0;
    var total_weight = 0;
    $('tr', $(row).parents('table:first')).each(function(i, elm){
      if (!$(elm).hasClass('jqgfirstrow'))
      {
        total+= parseFloat($(elm).find('span.recalc-summ').text());
        total_weight+= parseFloat($(elm).find('span.recalc-weight').text());
      }
    });
    $('td span.cart-total-cell').each(function(i, elm){
      total+= parseFloat($(elm).text());
    });

    $('div.cart-total p.total span').html(parseFloat(total).toFixed(2));
    $('div.cart-total p.weight span').html(parseFloat(total_weight).toFixed(2));
  });
  $('input[type="submit"].proccess-cart').livequery('click', function(event){
    var total = 0;
    $('table#table tr').each(function(i, elm){
      total+= parseFloat($(elm).find('span.cart-total-cell').text());
    });
    if (total <= 0){
      alert('Вы не заказали ни одного продукта');
      event.preventDefault();
      event.stopPropagation();
    }
  });


  $('table.cart-table input.cart-qty-change, input.recalc-qty').livequery('keypress', function(event)
  {
      if( event.which!=8 && event.which!=0 && (event.which<48 || event.which>57 ) && event.which!=46 && event.which!=44)
      {
        return false;
      }
      $(this).val($(this).val().replace(',','.'));
  });

  $('table.cart-table input.cart-qty-change').livequery('change', function(event){
    $(this).val($(this).val().replace(',','.'));
    var input = $(this);
    if (input.val()=='') input.val(0);
    var qty = parseFloat(input.val());
    var max = input.attr('max');
    if (qty>max)
    {
      alert('Вы указали количество большее, чем имеется на складе');
      $(this).val(max);
      qty = max;
    }

    var row = input.parents('tr:first');
    var priceSrc  = input.attr('price');
    if (input.attr('priceeur')) priceSrc = input.attr('priceeur');
    var price = parseFloat(priceSrc).toFixed(2);
    var total = parseFloat(price * qty).toFixed(2);
    $('td span.cart-total-cell:first', row).html(total);
    var table = $(row).parents('table:first');
    var subtotal = 0;
    $('td span.cart-total-cell').each(function(i, elm){
      if (!$(elm).hasClass('jqgfirstrow')){
        subtotal+= parseFloat($(elm).text());
      }
    });
    $('td span.recalc-summ').each(function(i, elm){
      if (!$(elm).hasClass('jqgfirstrow')){
        subtotal+= parseFloat($(elm).text());
      }
    });
    $('div.cart-total p.total strong span').html(parseFloat(subtotal).toFixed(2));

  });

  $('form.poll-form a.doPoll').livequery('click', function(event){
    event.preventDefault();
    event.stopPropagation();
    var form = $(this).parents('form:first');
    var target = $(this).parents('div.block-poll:first');
    $.post(form.attr('action'), form.serializeArray(), function(html){
      $(target).replaceWith(html);
    });
  });

  // Архив новостей
  function redrawMonths(year){
    var str = '';
    for(var i=0; i<12; i+=4){
      str += '<li><ul class="links">';
      for(var j=i; j<i+4; j++){
        if (available[year] && available[year][j+1]) {
          str += '<li><a rel="'+(j+1)+'" href="#">'+months[j]+'</a></li>';
        } else {
          str += '<li>'+months[j]+'</li>';
        }
      }
      str += '</ul></li>';
    }
    $('#calendar ul.months').html(str);
  }

  $('div#calendar a.prev').livequery('click', function(event){
    event.preventDefault();
    event.stopPropagation();
    var year = $('#calendar-form input[name=year]').val();
    year--;
    $('#calendar-form input[name=year]').val(year);
    $('#year-element').html(year);
    redrawMonths(year);
  });

  $('div#calendar a.next').livequery('click', function(event){
    event.preventDefault();
    event.stopPropagation();
    var year = $('#calendar-form input[name=year]').val();
    year++;
    $('#calendar-form input[name=year]').val(year);
    $('#year-element').html(year);
    redrawMonths(year);
  });

  $('div#calendar .links a').livequery('click', function(event){
    event.preventDefault();
    event.stopPropagation();
    var month = $(this).attr('rel');
    $('#calendar-form input[name=month]').val(month);
    $('#calendar-form').submit();
  });

});

