Array.prototype.indexOf = function(el) {
  var rval = -1;
  for (var i = 0; i < this.length && rval == -1; i++) {
    if (this[i] == el) {
      rval = i;
    }
  }
  return rval;
}


/* Wykonywane po zbudowaniu drzewa DOM, ale przed onload
 * (onload czekaloby na zaladowanie obrazkow)
 */
$(function() {
  var HOVER_SELECTOR = ['#nav li>span',
                        '.poll li'
                       ].join(', '); // join nas ochroni przed zapomnieniem przecinkow w CSS
  var HOVER_CLASS = 'hover';
  var STR_SEARCH_QUERY_LABEL = 'wpisz szukane słowo lub frazę...';
  var STR_HOME = 'Przejdź do strony głównej';

  function getNextSiblingOfType(elem, type) {
    var rval = null;
    var arr = type.indexOf ? true : false;
    if (arr) {
      for (var i = 0; i < type.length; i++) {
        type[i] = type[i].toLowerCase();
      }
    }
    for (; elem && !rval; elem = elem.nextSibling) {
      var matched = arr
        ? elem.tagName && type.indexOf(elem.tagName.toLowerCase()) != -1
        : elem.tagName == type;
      if (matched) {
        rval = elem;
      }
    }
    return rval;
  }
  
  /**
   * Ustawia na input[type=text] etykiete, ktora opisuje pole tekstowe. Etykieta znika,
   * gdy kliknie sie na pole lub gdy zawartosc pola nie jest pusta.
   */ 
  function setDynamicLabel(input, labelText) {
    $(input).each(function(index, el) {
      var $el = $(el);
      var $label = null;
      var label = null;
      var fetchedLabelText = labelText;
      if (!labelText) {
        $label = $('label[for=' + $el.attr('id') + ']');
        fetchedLabelText = $label.text();
        label = $label.get(0);
        label.parentNode.removeChild(label);
      }

      el.labelText = fetchedLabelText;

      $el.focus(function() {
        if (this.labelVisible) {
          this.labelVisible = false;
          this.value = '';
        }
      });
      $el.blur(function() {
        if (this.value == '') {
          this.labelVisible = true;
          this.value = this.labelText;
        }
      });
      
      $el.attr('value', '');
      $el.blur();
    });
  }

  function setCollapsible(panels, options) {
    var i;
    var defaults = {
      panel: '> li',
      trigger: '> h2, > img',
      hoverClass: 'hover',
      content: '> ul, > div',
      openClass: 'open',
      closedClass: 'closed',
      openSpeed: 'fast',
      closeSpeed: 'fast'
    }

    options = options || {};
    if (typeof panels == 'string') {
      options.panel = panels;
    }

    for (i in defaults) {
      if (options[i] === undefined) {
        options[i] = defaults[i];
      }
    }

    var $panels = $(options.panel);
    var openPanel = null;

    $panels.each(function(index, panel) {
      var $panel = $(panel);
      var $trigger = $(options.trigger, panel);
      var $content = $(options.content, panel);
      if (!($trigger.length && $content.length)) {
        return;
      }

      panel.open = function(speed) {
        if (openPanel && openPanel != this) {
          openPanel.close();
        }
        $content.show(speed || options.openSpeed);
        openPanel = this;
        this.opened = true;
        $(this).removeClass(options.closedClass).addClass(options.openClass);
      }

      panel.close = function(speed) {
        if (openPanel == this) {
          openPanel = null;
        }
        this.opened = false;
        $content.hide(speed || options.closeSpeed);
        $(this).removeClass(options.openClass).addClass(options.closedClass);
      }

      panel.close();

      $panel.hover(
        function() { $panel.addClass('hover'); },
        function() { $panel.removeClass('hover'); }
      );
      $trigger.click(function() {
        if (panel.opened) {
          panel.close();
        } else {
          panel.open();
        }
      });
    });
  }

  try {

  // z powodu SEO czynimy to niedostepne dla robotow
  // mozemy sobie na to pozwolic -- dla uzytkownikow
  // nie jest to az tak wazne
  $('a#logo').attr('title', STR_HOME);


  // robi z jednej kolumny dwie
  // 
  // struktura przed uzyciem:
  //  ul.collapsible
  //    li
  //    li
  //    ...
  //  po uzyciu:
  //  div.collapsible
  //    ul
  //      li
  //      li
  //      ...
  //    ul
  //      li
  //      li
  //      ...
  //  Jedna kolumna ma sens gdy sa wylaczone skrypty, no i znacznie ulatwia
  //  napisanie szablonow. Ale skrypty zle dzialaja na jednej liscie
  //  symulujacej dwie kolumny, bo elementy przeplywaja z jednej
  //  pseudokolumny na druga w momencie klikania
  $('ul.collapsible').each(function(listIndex, ul) {
    var $ul = $(ul);
    var $wrapper = $('<div class="' + $ul.attr('class') + '"></div>');
    $('> li:even', ul).appendTo($('<ul></ul>').appendTo($wrapper));
    $('> li', ul).appendTo($('<ul></ul>').appendTo($wrapper));
    $ul.replaceWith($wrapper);
  });


  setCollapsible('.collapsible > li, .collapsible > ul > li');

  // dodaj klase .hover gdzie trzeba
  $(HOVER_SELECTOR).hover(function() { $(this).addClass(HOVER_CLASS); }, function() { $(this).removeClass(HOVER_CLASS); })

  setDynamicLabel('.newsletter input[type=text]');
  setDynamicLabel('#search input[type=text]', STR_SEARCH_QUERY_LABEL);

  // dzieki temu mozna kliknac w dowolnym miejscu li w ankiecie
  $('.poll li').click(function() {
    $('input[type=radio]', this).attr('checked', 'checked');
  });

  // nawigacja - chowanie/pokazywanie podmenu
  $('#nav li>span').each(function(i, trigger) {
    var $trigger = $(trigger);
    

    var content = getNextSiblingOfType(this, ['ul', 'ol']);
    if (!content) {
      return;
    }

    this.$content = $(content);

    this.open = function(speed) {
      var speed = speed || 'fast';
      this.$content.show(speed);
      $([this, this.parentNode]).removeClass('closed').addClass('open');
      this.opened = true;
    }

    this.close= function(speed) {
      var speed = speed || 'fast';
      this.$content.hide(speed);
      $([this, this.parentNode]).removeClass('open').addClass('closed');
      this.opened = false;
    }

    $trigger.click(function() {
      if (this.opened) {
        this.close();
      } else {
        this.open();
      }
      return false;
    });

    this.close(0);
  });
  $('#nav li:has(.current) > span, .open > span').each(function(index, el) {
    if (el.open) {
      el.open(0);
    }
  });



  /* IE FIX
   * Klikanie w obrazek w linku nie powodowalo podazenia za linkiem
   */
  if (jQuery.browser.msie) {
    $('.news h3 a').click(function() {
      // try, bo czesto nie ma uprawnien do zmiany window.location
      try {
        window.location = $(this).attr('href');
      } catch (e) {
      }
     });
  }

  } catch (e) {
    // To oznacza awarie w skrypcie. Skoro skrypty moga nie dzialac,
    // anulujemy wlaczenie JavaScriptu na body. Te skrypty, ktore
    // daly rade odpalic, juz tego w tym momencie nie potrzebuja,
    // a awaria innych polaczona z klasa js na body blokowalaby interfejs
    $('body').removeClass('js');

    // Dla celow developerskich mozna to odkomentowac:
    // alert("Wystąpił błąd:\n" + e.message);
  }

});

/* IE FIX
 * Dzieki niemu najechanie na linki z obrazkami w tle nie powoduje
 * dziwnego przeskoku zwiazanego z ladowaniem obrazka
 */
if (jQuery.browser.msie) {
  try {
    document.execCommand('BackgroundImageCache', false, true);
  } catch(e) {
    // nie udalo sie -- trudno
  }
}

