$.extend({

  getUrlVars: function(){
    var vars = [], hash;
    var url = window.location.href;
    if (window.location.hash) url = url.substr(0, url.indexOf('#'));
    var hashes = url.slice(url.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },

  getUrlVar: function(name){
    return $.getUrlVars()[name];
  },

  priceFormat: function(number, decimalLimit, thousandSeparator, decimalSeparator){
    var number = Math.round(number * Math.pow(10,decimalLimit));
    if (number >= 0) n1 = n2 = '';
    var y = (''+ Math.abs(number)).split('');
    var z = y.length - decimalLimit;
    if (z<0) z--;
    for (var i = z; i < 0; i++) y.unshift('0');
    if (z<0) z = 1;
    y.splice(z, 0, decimalSeparator);
    if (y[0] == decimalSeparator) y.unshift('0');
    while (z > 3) { z-=3; y.splice(z,0,thousandSeparator); }
    return y.join('');
  }

});

(function($){
  $.fn.fakeXFBML = function(fb_tag, params){
    var container = $(this);
    params = params || {};
    fb_tag = $('<fb:' + fb_tag + '></fb:' + fb_tag + '>');
    $.each(params, function( key , value ) {
      fb_tag.attr( key , value );
    });
    fb_tag.appendTo(container);
  };
})(jQuery);

$(document).ready(function() {

  // external links
  $(function() {
    $('div.banners a:not([href*="nako.cz"]), div.card.links a:not([href*="nako.cz"])').click(function(){
      window.open(this.href);
      return false;
    }).attr('title', this.title + ' [externí odkaz]');
  });

  $('li.print-product-detail a').click(function() {
    window.print();
    return false;
  });

  // Facebook "like box"
  $('div#facebook-like-box').fakeXFBML('like-box', {
    href: 'http://www.facebook.com/Naradi.Nako.Pardubice',
    width: 212,
    height: 313,
    colorscheme: 'light',
    stream: false,
    show_faces: true,
    header: false,
    border_color: '000000'
  });

  // Facebook "like" button
  $('div#facebook-like-button').fakeXFBML('like', {
    width: 275,
    action: 'like',
    show_faces: true
  });

  // categories
	$('div.category').hover(function(){
    $(this).toggleClass('active');
	});

  // search form
  $('#searching-form').submit(function(){
    if ($('#searching-search-text').val() == '') {
      alert('Zadejte prosím hledaný výraz');
      return false;
    }
    if ($('#searching-search-text').val().length < 3) {
      alert('Hledaný výraz musí obsahovat alespoň tři znaky');
      return false
    }
  });

  // autocomplete
  var selectResult = function(value, data) {
    window.location = 'http://www.nako.cz/' + data + '.html';
  }

  $('#searching-search-text').autocomplete({
    serviceUrl: '/index.php?p=actions&action=searching/autocomplete',
    minChars: 3,
    delimiter: /(,|;)\s*/,
    zIndex: 9999,
    deferRequestBy: 0,
    onSelect: selectResult,
    noCache: false
  });

  // changes layout type
  $('div.sorting select').change(function(){
    $('div.sorting select').attr('readonly', 'readonly');
    $('form#settings').submit();
  });

  // checks all producers
  var checked_status = false;
  $('input#producer-0').click(function(){
    $('input[name*="producer"]').each(function(){
      this.checked = !checked_status;
    });
    checked_status = !checked_status;
    this.checked = false;
  });

  // top items
  $('div#top-items ul').anythingSlider({
    height: 252,
    width: 571,
    delay: 5000,
    forwardText: '&rarr;',
    backText: '&larr;',
    pauseOnHover: false,
    infiniteSlides: false,
    stopAtEnd: false,
    autoPlay: true,
    hashTags: false,
    startPanel: 1,
    buildNavigation: true,
    buildArrows: false
  });

  // price range
  if ($('div#price-range').length > 0) {
    var minPrice = $('input#price-range-from').val() * 1;
    var maxPrice = $('input#price-range-to').val() * 1;
    var currentMinPrice = typeof($.getUrlVar('filter[price][from]')) == 'undefined' ? minPrice : $.getUrlVar('filter[price][from]');
    var currentMaxPrice = typeof($.getUrlVar('filter[price][to]')) == 'undefined' ? maxPrice : $.getUrlVar('filter[price][to]');
    $('<p id="price-range-legend" class="legend"></p>').insertBefore('div#price-range');
    $('<input type="hidden" id="price-amount-min" name="filter[price][from]" value="0" /><input type="hidden" id="price-amount-max" name="filter[price][to]" value="0" />').insertAfter('div#price-range');
    $('div#price-range').slider({
      range: true,
      step: 100,
      min: minPrice,
      max: maxPrice,
      values: [currentMinPrice, currentMaxPrice],
      slide: function(event, ui) {
        $('p#price-range-legend').html('od <strong>' + $.priceFormat(ui.values[0], 0, '.') + ' Kč</strong> do <strong>' + $.priceFormat(ui.values[1], 0, '.') + ' Kč</strong>');
      },
      stop: function(event, ui){
        $('input#price-amount-min').val(ui.values[0]);
        $('input#price-amount-max').val(ui.values[1]);
      }
    });
    $('input#price-amount-min').val(currentMinPrice);
    $('input#price-amount-max').val(currentMaxPrice);
    $('p#price-range-legend').html('od <strong>' + $.priceFormat($('div#price-range').slider('values', 0), 0, '.') + ' Kč</strong> do <strong>' + $.priceFormat($('div#price-range').slider('values', 1), 0, '.') + ' Kč</strong>');
  }

  // advanced filtering
  $('fieldset.basic-filters p.expand a').click(function() {
    $('fieldset.advanced-filters').toggleClass('active');
    return false;
  })
  $('fieldset.advanced-filters p.close a').click(function() {
    $('fieldset.advanced-filters').removeClass('active');
    return false;
  })

  // lightbox
  $('a[rel^="gallery"]').prettyPhoto({
    theme: 'facebook',
    deeplinking: false,
    overlay_gallery: false,
    social_tools: false,
    show_title: false,
    slideshow: false
  });

  // popup: inline content
  $('a[rel="inline-content"]').fancybox({
    ajax: {
      type: 'GET',
      data: 'ajax=true'
    },
    centerOnScroll: true,
    titleShow: false
  });

  // popup: iframes
  $('a[rel="iframe"]').fancybox({
    centerOnScroll: true,
    height: 541,
    titleShow: false,
    type: 'iframe',
    width: 660
  });

});

