var recalculateItems = 0;
var basketRemoveItemsTime2 = 0;

var availabilityTooltipYes = new Array();
var availabilityTooltipNo = new Array();

function redirect(href) {
  window.location.href = href;
}

$(document).ready( function() {
    $("a.fancybox").fancybox({
      'zoomSpeedIn': 300,
      'zoomSpeedOut': 300,
      'overlayShow' :true
    });
  });
  
// rozbaleni / zabaleni popisu produktu
$(function() {
  var height = $('.catDescriptions .bg').height(); 
  $('.catDescriptions .bg').css({ height: '105px' });

  var str = $('.catDescriptions p span').text();
  var desc = (str.substr(0,160)+"...");
  $(".catDescriptions p span").text(desc);

  $('.drop').click(function () {
    if($(this).hasClass('showMore')) {
      //show desc category
      $('.catDescriptions .bg').animate({ height: height }); 
      $(this).addClass('hideMore');
      $(this).removeClass('showMore');
      $(this).text('Skrýt popis');
      var desc = (str.substr(0));
      $(".catDescriptions p span").text(desc);
    }
    else {
      //hide desc category
      $('.catDescriptions .bg').animate({ height: '105' }); 
      $(this).removeClass('hideMore');
      $(this).addClass('showMore');
      $(this).text('Celý popis');
      var desc = (str.substr(0,160)+"...");
      $(".catDescriptions p span").text(desc);
    }
    return false;
  });
});

  
$(document).ready(function(){
  
  $(window).load(function() {
   $("#cartAnimation .cartToys").animate({top: 10},"normal") 
   $("#cartAnimation p").animate({top: 10},"normal")
    return false;
  });
  
  
  /* Featured Rotation */
  var featuredContainer = $('.imageProduct div.imageBig > div');
  featuredContainer.hide().filter(':first').show();

  $('.imageProduct div.thumb ul.slider a').click(function () {
    featuredContainer.hide();
    featuredContainer.filter(this.hash).show();
    $('.imageProduct div.thumb ul.slider a').removeClass('selected');
    $(this).addClass('selected');
    return false;
  }).filter(':first').click();

  $(".imageProduct div.imageBig .ico-thumb").click(function(){
    href = $(this).attr('href');
    
    $(href).children("a:first").click();

    return false;
  })

  // Tabs detail product
  $('#moreInfo').tabs();

});

$(document).ready(function(){
  
  // register form, order form
  if($('#company_data').is(':checked')) {
    $('#companyForm').slideDown();
  }
  
  $('#company_data').click(function() {
    if($(this).is(':checked')) {
      $('#companyForm').slideDown('normal');
    } else {
      $('#companyForm').slideUp('normal');
    }
  });
  
  if($('#delivery_address').is(':checked')) {
    $('#addressForm').slideDown();
  }
  
  $('#delivery_address').click(function() {
    if($(this).is(':checked')) {
      $('#addressForm').slideDown('normal');
    } else {
      $('#addressForm').slideUp('normal');
    }
  });
  
  $("#userLoginSubmit").click(function(){
    submit('userLoginForm');
    return false;
  });
  
  // nastaveni overlay pro PPL
  $("#overlay_ppl").click(function(){
    showOverlayContent('Lokality pro večerní doručení PPL', BreezyCMS_URL + 'overlays/ppl_evening_delivery', 780, 'max');
    return false;
  });

    
  $("input.digit").keyup(function (e) {

    val = $(this).attr('value');
    
    var key = window.event ? e.keyCode : e.which;
    //var keychar = String.fromCharCode(key);
    //reg = /\d/;
    
    //if (true || reg.test(keychar) || (key >= 96 && key <=105) || key == 46 || key == 8 || key == 61 || key == 282 || key == 352 || key == 268 || key == 344 || key == 381 || key == 221 || key == 193 || key == 205 || key == 201)
    //{
      val = $(this).attr('value');
      if (val == '')
        val = 0;
      
      d = new Date();
      ms = recalculateItems = d.getTime();
      
        
      href = $(this).parent().parent().find("a.basketChangeCount:first").attr('href');
      href += val + '/' + ms + '/';
      data = '';
        
      $.post(
        href,
        data,
        function(data) {
          if (data)
          {
            if (data['time'] == recalculateItems) {
              $("#cart p").remove();
              $("#cart").prepend(data['basket']);
              $("#price_" + data['id']).text(num2money(data['item_price']));
              $("#total_price").text(num2money(data['total_price']));
              setFreeShipping(data['free_shipping']);
              $("#availability_" + data['id']).children().hide();
              $("#availability_" + data['id']).append(data['availability']);
              setTooltips();
            }
          }
        },
        'json'
      );
    //}
  
  });

  $('#adressShow').click(function() {
    if($(this).is(':checked')) {
      $('#adressForm').show('normal');
    } else {
      $('#adressForm').hide('normal');
    }
  });

  // zobrazeni zpusobu platby v zavislosti na metode platby
  if ($("#delivery_and_payment_methods_form").length)
  {
    checked = 0;
    
    $("input[name='delivery_method_id']").each(function(){
      if ($(this).attr('checked'))
        checked = $(this).attr("value");
    });
    
    setDependPayments(checked);
  }
  
  $("input[name='delivery_method_id']").click(function(){
    setDependPayments($(this).attr("value"));
  });
  
  // update boxu s obsahem kosiku po zmene zpusobu doruceni
  $("input[name='delivery_method_id'], input[name='payment_method_id']").click(function(){
    
    var data = $("input[name='delivery_method_id']").serialize() + '&' + $("input[name='payment_method_id']").serialize();
    
    $.post
    (
      BreezyCMS_URL + 'nakup/box_basket/',
      data,
      function(data)
      {
        $("#boxBasket").replaceWith(data);
      }
    )
    
  });
  
  /*
  // zobrazeni vyrobcu pri filtrovani
  $("a.show-brand").toggle(function(){    
      $(this).addClass("up");
      $(".filter-cols").slideDown("normal");
    }, function() {
      $(this).removeClass("up");
      $(".filter-cols").slideUp("normal");
    } 
  ); 
*/
  
  // tooltip
  setTooltips();
});

function setTooltips() {
  $(".order-state.ok").each(function(i){
    id = $(this).parent().attr('id').substr(13);
    //alert(availabilityTooltipYes["a_" + id]);
    $(this).simpletip({content: availabilityTooltipYes["a_" + id], fixed: true, position: [0,30]});
  });
  
  $(".order-state.error").each(function(i){
    id = $(this).parent().attr('id').substr(13);
    $(this).simpletip({content: availabilityTooltipNo["a_" + id], fixed: true, position: [0,30]});
  });
}

function setDependPayments(delivery)
{
  $("input[name='payment_method_id']").removeAttr('disabled');
  
  for (key in depend_payments[delivery])
  {
    $('#payment_method_' + depend_payments[delivery][key]).attr('disabled', 'disabled');
  }

  /*  
  $("input[name='payment_method_id'][disabled!='true']").each(function(){
    alert($(this).attr('disabled'));
  });
  */
  $("input[name='payment_method_id'][disabled]").each(function(){
    if ($(this).attr('checked'))
      $("input[name='payment_method_id'][disabled!='true']:first").attr('checked', 'checked');
  });
}

function setFreeShipping(bal)
{
  if (bal > 0)
  {
    $("#free_shipping_1 strong:first").text(num2money(bal) + ' Kč');
    $("#free_shipping_2").addClass('none');
    $("#free_shipping_1").removeClass('none');
  }
  else
  {
    $("#free_shipping_1").addClass('none');
    $("#free_shipping_2").removeClass('none');
  }
}
  
function submit(form)
{
  $("form#"+form).submit();  
}

$(function(){
	// Tabs homepage
	$('#tabPanel').tabs();	

	// Tabs detail product
	$('#moreInfo').tabs();	
});

// Vymazani hodnoty value u inputu
function swip (elementInput, swipFrom, swipTo)  {
	if (elementInput.value == swipFrom) elementInput.value = swipTo;
}

function filterProducts()
{

  $('#traced > img').removeClass('hidden');
  
  if ($('#sex-boy').attr('checked'))
    sex = $('#sex-boy').attr('value');
  else if ($('#sex-girl').attr('checked'))
    sex = $('#sex-girl').attr('value');
  else
    sex = $('#sex-unisex').attr('value');
 
  // pokud je disabled, je vzdy zatrhnuto
  
  discount = ($("#discount").attr('disabled')) ? 1 : $("#discount").serialize();
  action = ($("#action").attr('disabled')) ? 1 : $("#action").serialize();
  award = ($("#award").attr('disabled')) ? 1 : $("#award").serialize();
  
  var data = $("#category_id").serialize() + '&' + $("#subcategory_id").serialize() + '&' + $("#price_from").serialize() + '&' + $("#price_to").serialize() + '&' +
             $("#age_from").serialize() + '&' + $("#sorting").serialize() + '&action=' + action + '&' + $("#news").serialize() + '&award=' + award + '&' + 
             $("#stock").serialize() + '&discount=' + discount + '&' + '&sex=' + sex + '&' + $("#base_url").serialize() + '&' + $("#list_type").serialize();
    
  // prida vyrobce         
  for (key in producers_ids) {
    if ($("#producer_" + producers_ids[key]).is(":checked")) {
      data += '&producers[]=' + producers_ids[key];
    }
  }
  
  $.ajax({
    type: 'POST',
    url: BreezyCMS_URL+ 'kategorie/filter',
    data: data,
    dataType: 'html',
    success: function (msg) {
      $('#productListContainer').html(msg);
    }
  });
}

function setItemsPerPage(count)
{
  var data = 'count=' + count;
  
  $.ajax({
    type: 'POST',
    url: BreezyCMS_URL+ 'kategorie/items_per_page',
    data: data,
    success: function(msg) {
      filterProducts();
    }
  });
  
  return false;
}

function fbs_click() {
  u=location.href;
  t=document.title;
  
  window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width= 626,height=436');
  return false;
}

function showPurrContainer(name, count)
{
  if (count == 1)
    content = count + " kus";
  else if (count >=2 && count <= 4)
    content = count +  " kusy";
  else
    content = count +  " kusů";
    
  
  content += " byla vložena do košíku";
  head = 'Hračka ' + name + ',';
  
  $("#purr-container h3:first").text(head);
  $("#purr-container p:first").text(content);
  $("#purr-container").show('fast');
  
  setTimeout("$('#purr-container').hide('slow')", 5000);
  
  return false;
}

function addToBasket(id, name, price, count)
{
  action = BreezyCMS_URL + 'basket/add_item';
  data = 'product_id=' + id + '&' + 'product_name=' + name + '&' + 'product_price=' + price + '&' + 'product_count=' + count;
      
  $.post(
    action,
    data,
    function(response) {
      $("#cart p").remove();
      $("#cart").prepend(response);
      showPurrContainer(name, count);
    }
  );

  return false;
}

// Otevreni v odkazu v novem okne
function aktualizujOdkazy() {
  if(!document.getElementsByTagName) return false;
  var links = document.getElementsByTagName("a");
  for (var i=0; i < links.length; i++) {
    if(links[i].className.match("ext")) {
      links[i].onclick = function () {
        return !window.open(this.href);
      }
    }
  }
}

window.onload=aktualizujOdkazy;

// formatovani cen
function num2money(n_value) {
  // validate input
  if (isNaN(Number(n_value)))
    return 'ERROR';
  
  minus = (n_value < 0) ? true : false;
  
  // save the sign
  var b_negative = Boolean(n_value < 0);
  n_value = Math.abs(n_value);
  
  var s_result = '';
  
  // separate all orders
  var b_first = true;
  var s_subresult;
  while (n_value >= 1) 
  {
    s_subresult = (n_value >= 1e3 ? '00' : '') + Math.floor(n_value % 1e3);
    s_result = s_subresult.slice(-3) + ((b_first) ? '' : ' ') + s_result;
    b_first = false;
    n_value = n_value / 1e3;
  }
  
  if (s_result == '')
    s_result = 0;
  else if (minus)
    s_result = '-' + s_result;
  
  // apply formatting and return
  return s_result + ',-';
}
