/**
 * @fileoverview
 * Obsługa serwisu po stronie przeglądarki
 *
 * @author Adam Łyskawa (http://nisza.org)
 * (c)2011 by 100v.pl, all rights reserved
 * @requires jQuery, swfobject
 */
(function() {
  /**
   * Konfiguracja dodatków JS
   */
  Configuration = {
    'serviceIPHash'     : 'dcf76b750922708a374f75791c8984017f83045f',
    'serviceUAHash'     : '23cd85e2f54bee76bf882405525d66dd0ebd2e4e',
    'flashDisable'      : false, // wyłączenie flasha
    'flashWindowsOnly'  : false, // flash tylko pod Windows
    'flashAnimation'    : '100v/layout/gfx/top.swf', // ścieżka do animacji
    'flashSize'         : '1050x490', // wymiary flasha
    'flashParams'       : { // parametry flasha
                          'wmode' : 'gpu', // typ renderowania
                          'scale' : 'noscale', // typ skalowania
                          'menu'  : 'true' // wyświetlanie menu flasha
                        }
  };
  /**
   * Moduł dostępu serwisowego (zależy od Crypto.SH1, pomijane przy braku)
   * Umożliwia serwisowanie działającej aplikacji produkcyjnej
   */
  ServiceAccess = {
    /** @type boolean Tryb serwisowy **/
    enabled : false,
    /** @type string Hasz IP **/
    currentIPHash : '',
    /** @type string Hasz UA **/
    currentUAHash : '',
    /** Autostart **/
    Init : function() { $(function() { ServiceAccess.Start(); }); }(),
    /** Uruchomienie pozyskiwania informacji o trybie serwisowym **/
    Start : function() {
      if (typeof Crypto !== 'undefined' && typeof Crypto.SHA1 === 'function') {
        var metaIP = $('meta[name=X-Remote-Addr]'), ip = '', ip_hash = '';
        if (metaIP.length) {
          ip = metaIP.attr('content');
          if (ip) this.currentIPHash = Crypto.SHA1(ip);
          this.currentUAHash = Crypto.SHA1(navigator.userAgent);
          if (Configuration.serviceIPHash === this.currentIPHash &&
              Configuration.serviceUAHash === this.currentUAHash) {
            this.enabled = true;
          }
        }
      }
    },
    /** Zwrócenie hashów serwisowych dla zapytania serwisowego **/
    Get : function() {
      return [this.currentIPHash, this.currentUAHash];
    }
  };
  /**
   * Moduł rozwijania kategorii
   */
  Categories = {
    /** Autostart **/
    Init : function() { $(function() { Categories.Start(); }); }(),
    /**
     * Start modułu
     */
    Start : function() {
      var current = window.location.toString();
      $('a.category-products').css('display', 'block').hide();
      $('#chcategories span.category-top').click(Categories.Click).each(function() {
        var categoryTop = $(this),
            categoryProducts = categoryTop.nextUntil('span', 'a.category-products');
        categoryProducts.each(function() {
          if (this.href === current) {
            $(this).addClass('active');
            categoryTop.addClass('active');
            categoryProducts.show();
          }
        });
      });
      $('#chcategories a.category-top').each(function() {
        if (this.href === current) $(this).addClass('active');
      });
    },
    /**
     * Obsługa kliku na kategorii
     */
    Click : function() {
      var categoryTop = $(this),
          categoryTopsAll = categoryTop.siblings('span.category-top');
          categoryAllProducts = categoryTop.siblings('a.category-products'),
          categoryProducts = categoryTop.nextUntil('span', 'a.category-products');
      categoryTopsAll.removeClass('active');
      categoryAllProducts.slideUp('fast');
      categoryTop.addClass('active');
      categoryProducts.slideDown('fast');
    }
  };
  /**
   * Moduł osadzania animacji flash
   */
  Flash = {
    /** Autostart **/
    Init : function() { $(function() { Flash.Start(); }); }(),
    /** Osadzenie animacji flash w nagłówku strony **/
    Start : function() {
      if (ServiceAccess.enabled) Configuration.flashDisable = true;
      if (Configuration.flashDisable ||
          (Configuration.flashWindowsOnly &&
           !navigator.platform.match(/win/i))) {
        //$('#flash').addClass('preview'); // wersja statyczna w przypadku wyłączenia flasha
        return;
      }
      var path = Configuration.flashAnimation,
          id = 'flash',
          size = Configuration.flashSize.split(/\D+/, 2),
          width = size[0],
          height = size[1],
          versionReq = '10.0.0',
          params = Configuration.flashParams,
          callback = function(e) {
            // wersja statyczna jeśli wymagana wersja flasha jest niedostępna:
            if (!e.success) $('#flash').addClass('preview');
          },
          embed = function() {
            if (
              navigator.userAgent.match(/chrome/i) ||
              navigator.userAgent.match(/msie/i) ||
              navigator.userAgent.match(/safari/i)
            ) params.wmode = 'opaque';
            swfobject.embedSWF(
              path, id, width, height, versionReq,
              null, null, params, null, callback
            );
          };
      embed();
    }
  };
  /**
   * Moduł zakładek na stronie głównej
   */
  Tabs = {
    /** Autostart **/
    Init : function() { $(function() { Tabs.Start(); }); }(),
    /** Obsługa zakładek na stronie głównej **/
    Start : function() {
      var indexTab = $.cookie.get('indexTab');
      if (typeof indexTab === 'undefined') indexTab = 0;
      var indexContent = $('#indexDefault'),
          indexTabs = $('#indexDefault>h1'),
          indexTabContents = $('#indexDefault>div'),
          moveTabsToTop = function() {
            indexTabs.insertBefore(indexTabContents.eq(0));
            indexTabs = $('#indexDefault>h1');
          },
          switchToIndexTab = function(event) {
            var tab = typeof event === 'undefined'
                  ? indexTabs.eq(indexTab)
                  : $(event.target),
                tabs = tab.parent().find('h1');
            if (typeof event !== 'undefined') indexTab = tabs.index(tab);
            indexTabs.eq(indexTab).addClass('active');
            indexTabs.not(':eq(' + indexTab + ')').removeClass('active');
            indexTabContents.not(':eq(' + indexTab + ')').hide();
            indexTabContents.eq(indexTab).show();
            $.cookie.set('indexTab', indexTab);
          };
      indexTabs.css({
        'display' : 'inline-block',
        'margin-right' : '26px',
        'cursor' : 'pointer'
      });
      moveTabsToTop();
      switchToIndexTab();
      indexTabs.click(switchToIndexTab);
    }
  };
  /**
   * Moduł wyświetlania logotypów klientów
   */
  Clients = {
    /** Autostart **/
    Init : function() { $(function() { Clients.Start(); }); }(),
    /**
     * Start modułu
     * Zmiana logotypów w pseudolosowej sekwencji
     */
    Start : function() {
      var c = $('#boxClients'), l = $('span.logo', c), i, n = 0, r = [];
      for (i = 0; i < l.length; i++) r.push(i);
      r.sort(function() { return 1 - 2 * (Math.random() < 0.5); });
      var s = function() {
        l.fadeOut('slow');
        l.eq(r[n++]).fadeIn('slow');
        if (n >= r.length) n = 0;
      }
      s(); setInterval(s, 2500);
    }
  };
  /**
   * Moduł prawidłowej obsługi paska przewijania
   * Ignorowanie elementów wystających poza szerokość głównej kolumny
   */
  PageSize = {
    /** Autostart **/
    Init : function() { $(function() { PageSize.Start(); }); }(),
    /** Uruchomienie **/
    Start : function() {
      var html = $('html'),
          body = $('body'),
          scroll = 1,
          scrollState = 0,
          pageWidth = $('#mainWrapper').width();
      $(window).resize(function() {
        scrollState = body.css('overflow-x') !== 'hidden';
        var width = $(window).width();
        scroll = 1 * (width < pageWidth);
        if (scroll !== scrollState) {
          if (scroll) body.css('overflow-x', 'auto');
          else body.css('overflow-x', 'hidden');
        }
      }).resize();
    }
  };
  /**
   * Dodatkowe linki (uaktywnienie linków na elementach)
   * (umieszczenie tego w HTML mogłoby być niezgodne ze standardami W3C)
   */
  Links = {
    /** Autostart **/
    Init : function() { $(function() { Links.Start(); }); }(),
    /** Uruchomienie **/
    Start : function() {
      $('#boxWebmaster')
        .css('cursor', 'pointer')
        .click(function(e) {
          if (e.target.nodeName.toLowerCase() !== 'a')
            window.location = '/';
        });
    }
  };
})();
/**
 * Wtyczki jQuery z frameworka MACHINE 5
 * @author Adam Łyskawa
 */
(function($) {
  /**
   * Cookie module
   * @requires JSON - from JSON2.js for data cookies
   */
  $.cookie = {
    /**
     * Gets a cookie
     * @param {string} name
     * @returns {string}
     */
    get : function(name) {
      if (name && document.cookie.length) {
        var crx = new RegExp('(?:^|;\\s*)' + name + '=(.*?)(?:;|$)'),
            dcm = document.cookie.match(crx),
            cookie = dcm ? unescape(dcm[1]) : undefined;
        if (cookie &&
            (cookie.substr(0, 1) === '{' || cookie.substr(0, 1) === '['))
          cookie = JSON.parse(cookie);
        return cookie;
      } else return undefined;
    },
    /**
     * Sets a cookie
     * @param {string} name
     * @param {string} value
     * @param {string} expire (optional, with unit like ms|s|m|h|d, default in seconds)
     */
    set : function(name, value, expire) {
      if (typeof(expire) == 'string') {
        var m = expire.match(/^(\d*)(|ms|s|m|h|d)$/);
        expire = parseInt(m[1]);
        switch (m[2]) {
          case '':
          case 's': expire*= 1000; break;
          case 'ms': break;
          case 'm': expire*= 60000; break;
          case 'h': expire*= 3600000; break;
          case 'd': expire*= 86400000; break;
        }
      }
      if (typeof value === 'object') value = JSON.stringify(value);
      var x = new Date();
      x.setTime(x.getTime() + expire);
      document.cookie = escape(name) + '=' + escape(value) +
        ((typeof(expire) === 'undefined') ? "" : ';expires=' + x.toUTCString()) + ';path=/';
    }
  };
})(jQuery);
