$.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('');
  },

  wizardRefreshModels: function(attributeId, valueId){
    $.ajax({
      url: '/index.php?p=actions&action=filters/load_models',
      data: 'attribute_id=' + attributeId + '&value_id=' + valueId,
      cache: false,
      beforeSend: function(){
        $('fieldset.wizard select').attr('disabled', true);
        $('select#models').html('<option>načítám...</option>');
      },
      success: function(html){
        $('select#models').html(html);
        $('fieldset.wizard select').attr('disabled', false);
      }
    });
  },

  wizardRefreshTires: function(type, attributeId, valueId, subValueId, subSubValueId){
    $.ajax({
      url: '/index.php?p=actions&action=filters/load_tires_' + type,
      data: 'attribute_id=' + attributeId + '&value_id=' + valueId + '&tire_rim=' + (typeof(subValueId) == 'undefined' ? 0 : subValueId) + '&tire_width=' + (typeof(subSubValueId) == 'undefined' ? 0 : subSubValueId),
      cache: false,
      beforeSend: function(){
        $('fieldset.wizard select').attr('disabled', true);
        $('select#tires-' + type).html('<option>načítám...</option>');
      },
      success: function(html){
        $('select#tires-' + type).html(html);
        $('fieldset.wizard select').each(function(){
          if ($(this).children('option').length > 1) $(this).attr('disabled', false);
        });
      }
    });
  }

});

$(document).ready(function(){

  // external links
  var domainName = window.location.host.toLowerCase();
  $('a:not([href*="' + domainName + '"])').not('[href^="#"]').not('[href^="mailto"]').each(function(){
    $(this).attr('target', '_blank');
  });

  // categories
  $('ul.mainitems li.has-subitems a.category span').click(function(){
    var elm = $(this).parent().parent();
    if (elm.hasClass('contracted')) {
      elm.removeClass('contracted');
      elm.addClass('expanded');
    } else if (elm.hasClass('expanded')) {
      elm.removeClass('expanded');
      elm.addClass('contracted');
    }
    return false;
  });

  // 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.omnipuls.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
  });
  $('#searching-form button').mouseover(function() {
    $(this).find('img').attr('src','/_layout/_e-shop/search-hover.png');
  });
  $('#searching-form button').mouseout(function() {
    $(this).find('img').attr('src','/_layout/_e-shop/search.png');
  });

  // 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.slider').bxSlider({
    moveSlideQty: 1,
    auto: true,
    pause: 7500,
    pager: true,
    pagerLocation: 'top',
    pagerType: 'full',
    pagerActiveClass: 'active',
    autoControls: false,
    controls: false,
    prevText: '&bull;',
    nextText: '&bull;',
    hideControlOnEnd: true,
    displaySlideQty: 1
  });

  // wizard
  var attributeId = $('input#attribute_id').val();
  $('select#producers').change(function(){
    $.wizardRefreshModels(attributeId, $(this).val());
  });
  $('select#tires-types').change(function(){
    $.wizardRefreshTires('rims', attributeId, $(this).val());
    $.wizardRefreshTires('width', attributeId, 0);
    $.wizardRefreshTires('profiles', attributeId, 0);
  });
  $('select#tires-rims').change(function(){
    $.wizardRefreshTires('width', attributeId, $('select#tires-types').val(), $(this).val());
    $.wizardRefreshTires('profiles', attributeId, 0);
  });
  $('select#tires-width').change(function(){
    $.wizardRefreshTires('profiles', attributeId, $('select#tires-types').val(), $('select#tires-rims').val(), $(this).val());
  });

/*
  // 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"]').fancybox({
    centerOnScroll: true,
    hideOnContentClick: true,
    overlayColor: '#000000',
    overlayOpacity: 0.7,
    titlePosition: 'inside',
    transitionIn: 'fade',
    transitionOut: 'fade',
    speedIn: 300,
    speedOut: 100
  });

  // 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
  });

});

