/* Author:

 */

$(function() {

  // Ini the top nav menu
  if (!($.browser.msie && $.browser.version == "6.0")) Nav.init();

  // Homepage javascript
  if ($('.home-page').length)  Homepage.init();

  if ($('form').length) {
    // Validate the forms
    $('form').validate({messages: {emailAddress: "Invalid email address"}});

    if ($('form#sub-categories-filter').length) {
      var $form = $('form#sub-categories-filter'),
          $subCategoriesContainer = $('#sub-categories-container').isotope(),
          guideClass = 'guide',
          $inputs = $form.find('input[type=checkbox]'),
          selector, filters;

      $form.change(function() {
        filters = '';
        $inputs.each(function() {
          var $this = $(this);
          if ($this.parent().hasClass('checked')) {
            filters += '.' + $this.attr('data-filter') + ', ';
          }
        })
        selector = '.' + guideClass + ', ' + filters;
        $subCategoriesContainer.isotope({ filter: selector ,   animationOptions: {
          duration: 750,
          easing: 'easeInOutExpo',
          queue: false
        }});
      });

    }
    // Uniform the checkboxes
    $('form.uniform').find('input[type=checkbox]')
        .uniform()
        .end()
        .css({opacity: 0, visibility: "visible"})
        .animate({opacity: 1}, 200, 'easeOutQuad');

  }
  // Activate the product slider
  if ($('#product-slides').length) $('#product-slides').slides({slideEasing: 'easeOutQuart', slideSpeed: 500});

  // Show Seo text bottom page
  $('#seo-text').find('a.more-lk').live('click', function() {
    $(this).hide()
        .next('.more')
        .fadeIn(400, function() {
          $(this).show();
        });
    return false;
  });

});


var Homepage = {
  init : function() {
    window.log('homepage init');
    this.initSlider();
    if (!($.browser.msie && ($.browser.version == "6.0" || $.browser.version == "7.0"))) this.initNewsScroller();
  },


  initNewsScroller: function() {
    window.log('news scroller init');
    var $scroller = $('#scroller');

    if ($scroller.find('li').length > 1) {
      $scroller.jcarousel(
          {
            vertical: false,
            wrap: 'circular',
            auto:1,
            rtl: false,
            scroll: 1,
            animation: 7000,
            easing: 'linear'

          });
    }
  },

  initSlider: function() {
    window.log('slider init');

    var $slider = $('#homepage-slider'),
        $slides = $slider.find('li'),
        nSlides = $slides.length,
        $prev = $('#btn-prev'),
        $next = $('#btn-next'),
        currentIndex = 0,
        pauseTime = 3000,
        firstFlag = 1,
        autoPlayTimeout;


    var getPrevIndex = function() {
      return (currentIndex === 0) ? (nSlides - 1) : (currentIndex - 1);
    }

    var getNextIndex = function() {
      return (currentIndex === (nSlides - 1)) ? 0 : (currentIndex + 1);
    }

    // timeout function used for the auto rotation (default state)
    var autoPlay = function() {
      autoPlayTimeout = setTimeout(function() {
        showSlide(getNextIndex(), 1);
        autoPlay();
      }, pauseTime)
    };

    // Clear the timeOut
    var stopAutoPlay = function() {
      clearTimeout(autoPlayTimeout);
    }

    // fade Out the current slide and show the new one
    var showSlide = function(index, mutliplier) {
      if (!firstFlag) {
        var leftHide = -30 * mutliplier,
            leftShow = 100 * mutliplier;


        $slides.stop(true, true).eq(currentIndex).css('opacity', 1).animate({'opacity': 0, left: leftHide + 'px'}, 150, 'easeInQuart', function() {
              $slides.eq(index).css({'opacity': 0, 'left' : leftShow + 'px'}).show().animate({'opacity': 1, 'left' : 0}, 700, 'easeOutExpo');
              currentIndex = index;
            });

      } else {
        $slides.eq(index).css({'opacity': 0}).show().animate({'opacity': 1}, 1000, 'easeOutQuad', function() {
              if (nSlides > 1) autoPlay();
            });
        firstFlag = 0;
      }
    }

    // Show the navigation menu
    if ($prev.length && $next.length) {
      $prev.css('opacity', 0).show().animate({'opacity': 1}, 1000, 'easeOutQuad');
      $next.css('opacity', 0).show().animate({'opacity': 1}, 1000, 'easeOutQuad');
      $prev.live('click', function() {
        stopAutoPlay();
        showSlide(getPrevIndex(), -1);
        return false;
      });

      $next.live('click', function() {
        stopAutoPlay();
        showSlide(getNextIndex(), 1);
        return false;
      });
    }

    // Show the first slide
    showSlide(currentIndex);
  }
}


var Nav = {
  init: function() {
    window.log('nav init');

    var $productNavLink = $('#product-nav-lk'),
        $productNavLi = $productNavLink.parent(),
        productNavLiSelected = $productNavLi.hasClass('selected'),
        $productNavBox = $('#product-navigation'),
        $productNavBoxInner = $productNavBox.find('#product-navigation-inner'),
        productNavBoxInnerHeight = $productNavBoxInner.outerHeight() + 10,
        $productNavCategoryLis = $productNavBox.find('li'),
        $productNavShadow = $('#product-navigation-shadow'),
        $productNavImgWrapper = $productNavBox.find('#img-wrapper'),
        $imgFake = $productNavBox.find('#img-fake'),
        productNavLinkc = productNavBoxc = {},
        mouse = {'x': 0, 'y':0},
        status = 'hidden';

    // Init the position of the product nav box
    var resetPosition = function() {
      productNavLinkOffset = $productNavLink.offset();
      $productNavBox.css({'left' : (productNavLinkOffset.left + 5)})
      $productNavShadow.css({'left' : (productNavLinkOffset.left + 5)})

      // Set the elements positions
      productNavLinkc = getElementPosition($productNavLink);
      productNavBoxc = getElementPosition($productNavBox);
    }

    // Get element positon and create an object
    var getElementPosition = function($e) {
      var offset = $e.offset();
      return ({'x' : offset.left, 'y' : offset.top, 'w' : $e.width(), 'h' : $e.height()});
    }

    // set the drop down menu status
    // hidden | hiding | showing | visible
    var setStatus = function(_status) {
      status = _status;
    }

    // get the drop down position
    var getStatus = function() {
      return status;
    }


    // Check if the mouse is the drop down or the menu item
    var isMouseIn = function() {
      var mouseIn = false;
      if (
          (
              ((productNavLinkc.x <= mouse.x) && (mouse.x <= (productNavLinkc.x + productNavLinkc.w)))
                  &&
                  ((productNavLinkc.y <= mouse.y) && mouse.y < (productNavLinkc.y + productNavLinkc.h))
              )
              ||
              (
                  ((productNavBoxc.x <= mouse.x) && (mouse.x <= (productNavBoxc.x + productNavBoxc.w)))
                      &&
                      ((productNavBoxc.y <= mouse.y) && mouse.y <= (productNavBoxc.y + productNavBoxc.h))
                  )
          )
        mouseIn = true;

      return mouseIn;
    }

    // Show the product drop down
    var showProductNavBox = function() {
      if (getStatus() === 'hidden') {

        // add selected class to product nav li
        if (!productNavLiSelected) $productNavLi.addClass('selected');

        // update status
        setStatus('showing');

        // Monitor the mousemoves
        $('body').mousemove(function(e) {
          if (getStatus() === 'visible') {
            mouse.x = e.pageX;
            mouse.y = e.pageY;
            productNavBoxc = getElementPosition($productNavBox);
            if (!isMouseIn()) hideProductNavBox();
          }
        });

        // Reset content css
        $productNavBoxInner.children().css({'opacity': 0, 'visibility': 'visible'});

        // Show the shadow
        $productNavShadow.show();

        // Set the box height
        $productNavBox.height(productNavBoxInnerHeight);

        // Show the box
        $productNavBoxInner.stop(true, true).animate({'top': 0}, '250', 'easeOutExpo');

        // Display item in cascade

        // Show nav content
        setTimeout(function() {
          $productNavBoxInner.children()
              .animate({'opacity':1}, 600, function() {
                setStatus('visible');
              });
        }, 150)

      }
    }

    // Hide the drop down
    var hideProductNavBox = function() {
      if (getStatus() === 'visible' || getStatus() === 'showing') {

        // add selected class to product nav li
        if (!productNavLiSelected) $productNavLi.removeClass('selected');

        setStatus('hiding');

        // Stop monitoring the mouse moves
        $('body').unbind('mousemove');
        $productNavBoxInner.stop(true, true).animate({'top': '-' + productNavBoxInnerHeight + 'px'}, 200, 'easeOutQuart', function() {
              $productNavShadow.hide();
              $productNavBox.height(0);
              setStatus('hidden');
            });
      }
    }

    // Set the box position and its related elements
    resetPosition();
    $productNavBoxInner.css({'top': '-' + productNavBoxInnerHeight + 'px'});
    $(window).resize(resetPosition);

    // Show the panel
    $productNavLink.live('mouseover', function() {
      showProductNavBox();
    });

    // Handle the drop down menu
    $productNavCategoryLis.live('mouseover',
        function() {
          var $li = $(this),
              $link = $li.find('a').first(),
              data = $link.data(),
              $img;

          // add hover class
          $li.addClass('hover');

          // remove images
          $productNavImgWrapper.find('img').remove();

          // Show the image
          if (!$.isEmptyObject(data)) {
            $img = $('<img/>', {'title': data.imageTitle, 'src': data.imageSrc}).css('opacity', 1).show().appendTo($productNavImgWrapper);
          }

        }).live('mouseleave', function() {
          $productNavImgWrapper.find('img')
              .first()
              .remove();

          // Remove the hover class
          $(this).removeClass('hover');
        });
  }


}
