
$(document).ready(function(){
  /** =nav dropdowns
  ************************************************************/
  $('div.header > ul.nav-main:first').superfish({
    autoArrows:  false,
    dropShadows: false,
    closeAnimation: {height: 'hide'},
    closeSpeed: 120,
    animation: {height: 'show'},
    speed: 200
  });


  /** =style tweaks
  ************************************************************/
  /** =last class **/
  $('div.section').children().last().addClass('last').add('li:last-child').addClass('last');

  /** =wrap title entities in superscript tags **/
  $('div.content-header h1, ul.products-list h3').each(function() {
    $(this).html($(this).html().replace(/®/, '<sup>&reg;</sup>').replace(/™/, '<sup>&trade;</sup>'));
  });

  /** =custom ols **/
  $('ol.custom > li, ol.custom ol > li').prepend(function() {
    var index = $(this).index() + 1;
    return '<span class="bullet">' + index + '</span>';
  });

  /** =content header height **/
  var heightInner = 0;
  $('div.content-header-1, div.content-header-2').each(function(index) {
    var thisEl = $(this);
    thisEl.height(thisEl.height()).css('position', 'absolute').css('marginTop', '-' + thisEl.height() / 2 + 'px');
    if(thisEl.height() > heightInner) {
      heightInner = thisEl.height();
    }
  });

  if (heightInner > 60) {
    $('div.content-header').height(heightInner);
  }

  if ($('body.p-side-nav div.content-2 div.chest-of-drawers').length) {
    $('div.content-header-2').css('marginTop', function(index, val) {
      return (parseFloat(val) - 10) + 'px';
    });
  }

  /** =home logo bug
  ************************************************************/
  var $logo = $('div.header').children('.logo');
  $logo.append('<a href="/" class="go-home">Go to the homepage</a>');
  $logo.hover(function() {
    $(this).find('.go-home').stop(true, false).animate({top: '-30px'}, 100);
  }, function() {
    $(this).find('.go-home').stop(true, false).animate({top: '0'}, 100);
  });
});




/** =product and planning ideas and faq filters
************************************************************/
$(document).ready(function() {

  var $inlineFilter = $('form.inline-filter'),
      $allFilters = $inlineFilter.add('form.ajax-filter'),
      $checkbox = $allFilters.find('input:checkbox'),
      $select = $allFilters.find('select'),
      $filterWrapper = $('div.filter-wrapper'),
      products = !!$('body.site-details ul.products-list').length,
      $itemList = products ? $('ul.products-list') : $filterWrapper,
      comb = $inlineFilter.is('.product-filter') ? '.' : '#';

  /* =custom checkboxes */
  if ( $checkbox.length ) {
    $checkbox.customInput();
  }

  /* =custom selects */
  if ( $select.length ) {
    $select.selectmenu({
      style: 'dropdown',
      width: $select.is('#dealer-product-category') ? 200 : 300
    });

  }

  // ajax product filter
  if ( $('form.ajax-filter').length ) {


    $select.change(function(index) {
      var cat = $select.val(),
          sid = 'select' + (this.id || index);

      $.cookie(sid, cat, {
        expires: 7,
        path: '/' + location.pathname.replace(/^\//,'')
      });

      $filterWrapper.append('<div class="loading"></div>')
        .children('.loading')
        .css({
          height: $filterWrapper.height() + 'px',
          width: $filterWrapper.width() + 'px',
          opacity: 0.8
        });


      $.get(window.location.pathname, { category: cat },
        function(data) {
          data = data.replace(/^\s+/m,'');
          var $data = $('<div/>').html(data);
          $filterWrapper.html($data.find('.products-list'));
          $itemList = $filterWrapper.children();

          $('div.downloads-wrapper').html($data.find('.downloads-list'));

          setProductHeights($itemList);
          $itemList.children('li:nth-child(5n+1)').addClass('clear');
          if (typeof $.fn.biglinks !== 'undefined'){
            $itemList.find('div.main').biglinks();
          }
      });

      return false;
    });

    $select.each(function(index) {
      var $thisSelect = $(this),
          sid = sid = 'select' + (this.id || index),
          cat = $.cookie(sid);

      if (cat) {
        var catIndex = $thisSelect.find('option').filter(function() {
          return this.value == cat;
        }).index();
        $thisSelect.selectmenu('value', catIndex);
        $thisSelect.val(cat).trigger('change');
      }

    });

  }
  // set product heights
  // if ( products ) {
    setProductHeights($itemList);
  // }


  function setProductHeights($prods) {

    $prods.each(function(index) {

      var $theseItems = $(this).find('li.product');
      if ($('div.ie6').length) {
        $theseItems.sameHeight({adjustment: 60});
      } else {
        $theseItems.sameHeight();
      }

    });
  }


  function getSelector() {
    var output = '';

    $els.each(function(index) {
      if ( ( $(this).is('select') && $(this).val() )
        || $(this).is(':checked') ) {
        output += comb + $(this).val();
      }
    });
    return output;
  }

  var $nothing = $filterWrapper.first().before('<div class="filter-empty js-hide"><h3>You filtered too hard!</h3><p>Please broaden your search.</p>')
    .prev('.filter-empty');

  // inline filters
  if ( $inlineFilter.length ) {
    var $firstItem = $itemList.first();
    var $items = $firstItem.is('.filter-wrapper') && !$firstItem.is('.faq-list') ? $itemList : $itemList.children();

    var $els = $inlineFilter.find('input, select');
    $els.bind('click change', function(event) {
      if (event.type == 'change' && $(this).is(':checkbox')) {
        return;
      }

      var selector = getSelector();

      $itemList[selector ? 'addClass' : 'removeClass']('filtered');

      if (selector) {
        $items.filter('.active').removeClass('active');
        $items.filter(selector).addClass('active');
      } else {
        $items.addClass('active');
      }

      if ( !$items.filter('.active').length) {
        $nothing.removeClass('js-hide').parent('.filter-wrapper').addClass('empty');
      } else {
        $nothing.addClass('js-hide').parent('.filter-wrapper').removeClass('empty');
      }

      /** = filter products and hide associated tab when filtered **/
      $itemList.each(function() {
        var $thisList = $(this),
            $vis = $thisList.children('.active');

        if ( $itemList.parent('.tabs-panel').length ) {
          var tabId = $thisList.parent('div').attr('id'),
              $parentTab = $('a[href="#"' + tabId + ']').parent('li');

          if ($vis.length) {
            $parentTab.show();

          } else {
            $parentTab.hide();
            if ($parentTab.is('.ui-state-active')) {
              $parentTab.closest('.tabs').tabs('select', 0);
            }
          }
        }
      });

    }).triggerHandler('change');

  }
});

/** =cycle
************************************************************/
$(document).ready(function() {

  var cycles = {
    promos: function() {
      var c = $('div.promos');
      setTimeout(function() {
        c.hide().removeClass('js-hide-alt').slideDown('slow');
      }, 1000);

      return {
        collection: c,
        length: c.length,
        options: {
          fx: 'scrollDown',
          sync:   1,
          pause: 1,
          delay: 2000,
          speed: 400
        }
      };
    },
    ticker: function() {
      var c = $('div.news-ticker ul');
      return {
        collection: c,
        length: c.length,
        options: {
          fx: 'fade',
          sync:   1,
          pause: 1,
          delay: -2000,
          speed: 400
        }
      };
    },
    slideshow: function() {
      var c = $('div.slideshow .slides');
      return {
        collection: c,
        length: !!c.length && c.children().length > 1,
        options: {
          fx:    'scrollLeft',
          sync:   1,
          pause: 1,
          timeout: 5000,
          speed: 800,
          pager: '.pager',
          activePagerClass: 'active'
        }
      };
    },
    bqSlideshow: function() {
      var c = $('div.bq-slideshow').children();
      var $bq = $(this);
      if (!$bq.prev('.controls').length && c.children('.slide').length > 1) {
        $bq.before(FM.prevNext);
      }
      return {
        collection: c,
        length: c.length,
        options: {
          fx: 'fade',
          pause: 1,
          timeout: 10000,
          speed: 800,
          next: $bq.prev().find('.next'),
          prev: $bq.prev().find('.prev')
        }
      };
    },
    featureGallery: function() {
      var c = $('div.feature-gallery'),
          ini = true;

       return {
         collection: c,
         length: c.length,
         options: {
           fx: 'fade',
           pause: 0,
           timeout: 7000,
           speed: 800,
           after: function() {
             if (!ini) {
               $('div.content-1').toggleClass('laptop');
             }
             ini = false;
           }
         }
       };
    }
  };

  FM.cyclesPresent = function() {
    for (var k in cycles) {
      if (cycles[k]().length) {
        return true;
      }
    }
    return false;
  };

  if ( FM.cyclesPresent() ) {

    $.getScript(FM.scriptDir + 'jquery.cycle.min.js', function() {

      $.fn.cycle.transitions.scrollDown = function($cont, $slides, opts) {
        $cont.css('overflow','hidden');
        opts.before.push($.fn.cycle.commonReset);
        var h = $cont.height();
        opts.cssFirst = { top: 0 };
        opts.cssBefore= { top: -h, left: 0 };
        opts.animIn   = { top: 0 };
        opts.animOut  = { top: h };
      };

      $.fn.cycle.transitions.scrollLeft = function($cont, $slides, opts) {
        $cont.css('overflow','hidden');
        opts.before.push($.fn.cycle.commonReset);
        var w = $cont.width();
        opts.cssFirst = { left: 0 };
        opts.cssBefore= { left: w, top: 0 };
        opts.animIn   = { left: 0 };
        opts.animOut  = { left: 0-w };
      };

      $.fn.cycle.transitions.scrollHorz = function($cont, $slides, opts) {
        $cont.css('overflow','hidden').width();
        opts.before.push(function(curr, next, opts, fwd) {
          $.fn.cycle.commonReset(curr,next,opts);
          opts.cssBefore.left = fwd ? (next.cycleW-1) : (1-next.cycleW);
          opts.animOut.left = fwd ? -curr.cycleW : curr.cycleW;
        });
        opts.cssFirst = { left: 0 };
        opts.cssBefore= { top: 0 };
        opts.animIn   = { left: 0 };
        opts.animOut  = { top: 0 };
      };

      $.each(cycles, function(key, val) {
        var thisShow = val();
        if (thisShow.length) {
          thisShow.collection.each(function(index) {
            var thisInstance = val.call(this);
            $(this).cycle(thisInstance.options);
          });
        }
      });
    });
  }
});

$(document).ready(function() {

/** =tabs
************************************************************/
  var index = $.cookie('activeTab') || 0;
  $('div.tabs').tabs({
    selected: index,
    show: function(event, ui) {
      $.cookie('activeTab', ui.index);
    }
  });

/** =faq toggles
************************************************************/
  if ($('body.p-faqs').length) {
    $('body.p-faqs .filter-wrapper a.question').live('click', function(event) {
      $(this).closest('.q-a').toggleClass('collapsed').find('.answer').slideToggle(200);
      return false;
    });
  }
/** =biglinks
************************************************************/
  $('.products-list div.main, body.p-products-home .content-header .nav li, div.featured-products div, .biglink').biglinks();

  $('div.carousel > ul > li, div.video-block').biglinks({
    preventDefault: true
  });
  // $('div.drawer:not(".videos") div.drawer-body > ul > li:has("a"):has("img")').biglinks();
  $('div.video-block > a, div.drawer.videos li > a.img, div.tabs-panel#videos li > a.img, #videos li > a.img').append('<span class="play-btn"></span>');

/** =image gallery
************************************************************/
  var $gallery = $('div.gallery');
  var $carousel = $('div.gallery > div.gallery-carousel');
  var $items = $('div.gallery > div.gallery-carousel > ul > li');

  if ( $gallery.length ) {

    /** =number of thumbnail images to be visible  **/
    var visibleThumbs = 5;

    /** =controls **/
    if ( $items.length > visibleThumbs) {
      $gallery.append(FM.prevNext).find('.prev').addClass('disabled');
    }
    $carousel.each(function(index) {

    });
    /** =start up the carousel **/
    $carousel.jCarouselLite({
         btnNext: '.next',
         btnPrev: '.prev',
         visible: $items.length < visibleThumbs ? $items.length : visibleThumbs,
         circular: false
    });

    $('div.gallery-carousel li:first').addClass('active');

    $('div.gallery-carousel a').live('click', function(event) {
      $('div.gallery-carousel li').removeClass('active');

      var newsrc = this.href;
      var $newImg = $('<img />').attr('src', newsrc);

      if ($newImg[0].complete) {
        switchImage(newsrc);

      } else {
        $newImg.bind('load', function(event) {
          switchImage(newsrc);
        });
      }
      return false;
    });

    function switchImage(src) {
      $carousel.prev('.viewer').find('img').fadeOut(300, function() {
        $(this).attr({'src': src}).fadeIn(300);
        $('a').filter(function() {
          return src.indexOf(this.href) > -1;
        }).closest('li').addClass('active');
      });
    }
  } // $gallery.length
});

/** =standard carousel
************************************************************/
$(document).ready(function() {
  var $carousel = $('div.carousel');

  if ( !$carousel.length) { return; }
  $.getScript(FM.scriptDir + 'jcarousellite.js', function(){
    $carousel.each(function(index) {
      var $thisCarousel = $(this);
      var $theseItems = $thisCarousel.find('ul > li');

      /** =controls **/
      var numVis = $thisCarousel.is('.adstock-carousel') ? 4 : 5;

      if ( $theseItems.length > numVis) {
        $thisCarousel.append('<div class="controls"><span class="prev"><a href="#" class="disabled">Previous</a></span><span class="next"><a href="#">Next</a></span></div>');

        /** =start up the carousel **/
        $thisCarousel.jCarouselLite({
           btnNext: $thisCarousel.find('.next a'),
           btnPrev: $thisCarousel.find('.prev a'),
           visible: numVis,
           circular: false
        });

      }
    });
  });
});

/** =collapsing drawers
************************************************************/
$(document).ready(function() {
  if ($('div.drawer').length) {

    $('body.p-product-detail div.drawer-body')
      .slice(0,2)
      .removeClass('js-hide')
        .parent()
        .removeClass('collapsed');

    $('div.drawer-header').prepend('<a href="#" class="toggle">Collapse/Expand</a>');

    $('div.drawer a.toggle', $('div.chest-of-drawers')[0]).live('click', function(event) {
     var $thisDrawer = $(this).closest('.drawer');
     $thisDrawer.addClass($thisDrawer.is('.collapsed') ? 'expanding' : 'collapsing');
     var $thisBody = $thisDrawer.find('.drawer-body');
      $thisBody.slideToggle('800', function() {
       $thisDrawer.removeClass('expanding collapsing');
       $thisDrawer.toggleClass('collapsed');
     });
      return false;
    });

  }
});

/** =links
************************************************************/
// $(window).bind('load', function() {
//   setTimeout(function() {
//     $('.body').addSizes({
//      insertionType: 'after',
//      exclude: '.btn, .img, a:has("img"), .no-size',
//      excludeContainer: '.products-list, .chest-of-drawers, .variant-panel .main, .p-home, .column-feature, body.site-dealer .body'
//    });
//    $('.products-list .docs').addSizes({
//      exclude: '.btn, .img, a:has("img"), .no-size',
//      insertionType: 'after',
//      content: ['length']
//    });
//    $('body.site-dealer .body').addSizes({
//      insertionType: 'after',
//      exclude: '.btn, .img, a:has("img"), .no-size',
//      content: ['alt'],
//      contentBefore: ' (',
//       contentAfter: ')'
//    });
//
//   }, 1000);
// });

$(document).ready(function() {

  $('div.zoom-content').removeClass('js-hide').wrap('<div class="js-hide"></div>');

  $('a.new-window').click( function() {
      window.open( $(this).attr('href') );
      return false;
  });

  $('a[href^=http]').filter(function() {
    return this.hostname && this.hostname !== location.hostname;
  }).not('.btn, .store-link, a:has(img), .nav-util a, .footer .nav a').addClass('external');
});

/** =fancybox
************************************************************/
$.fancyvids = function(context) {
  context = context || 'body';
  // swf movies
  var swfOptions = {
    padding     : 0,
    autoScale     : false,
    transitionIn    : 'none',
    transitionOut   : 'none',
    href: '/assets/flash/jwplayer/player.swf',
    autoplay: true,
    flashvars: {
      stretching: 'exactfit',
      autostart: 'true',
      bufferlength: '3',
      skin: '/assets/flash/jwplayer/skins/simple.swf',
      lightcolor: 'FFFFFF',
      file: this.href
    }
  };

  // inline
  var inlineOptions = {
   'padding': 40,
   'autoScale': false,
   'titlePosition'  : 'inside'
  };

  $(context).find('a[href^="#"].zoom').each(function(index) {

    var $vid = $(this.hash),
        $obj = $vid.children('object,embed');
    if ($obj.length) {
      var dims = {
        width: parseInt($obj.attr('width'),10),
        height: parseInt($obj.attr('height'),10)
      },
      embeddedOptions = $.extend({}, inlineOptions, dims, {
        transitionIn: 'none',
        transitionOut: 'none',
        padding: 20,
        scrolling: 'no',
        autoDimensions: false,
        onStart: function() {
          $vid.removeClass('js-hide');
        },
        onClosed: function() {
          $vid.addClass('js-hide');
        }
      });

      // $vid.removeClass('js-hide');
      $vid.width(dims.width);
      $vid.height(dims.height);

      $(this).fancybox(embeddedOptions);

    } else {
      $(this).fancybox(inlineOptions);
    }

  });



  $(context).find('a:movieLink(.flv)').each(function(index) {

    swfOptions.flashvars.file = this.href;

    if (this.rel) {
      var wh = this.rel.match(/width=([^;]+);height=(\d+)/),
          thisWidth = wh[1]*1,
          thisHeight = wh[2]*1 + 20;
      swfOptions.width = thisWidth;
      swfOptions.height = thisHeight;
      this.rel = this.rel.replace(wh[0], '');
    }

    $(this).fancybox(swfOptions);
  });

};

$(window).bind('load', function(event) {

  $.fancyvids();
  // img links
  $('a:imgLink.zoom').fancybox({
    'transitionIn' : 'elastic',
    'transitionOut' : 'elastic',
    'titlePosition'  : 'inside'
  });


});

/** =placeholders
************************************************************/
$(document).ready(function() {
 $('input[placeholder]').defaulttext({
   defaultClass: 'placeholder',
   text: 'placeholder'
 });
});

/** =new selectors!
************************************************************/
(function($) {
  $.extend($.expr[':'], {
    imgLink: function(element, index, matches, set) {
      return !!element.href && (/\.(jpe?g|gif|png)$/).test(element.href);
    },
    movieLink: function(element, index, matches, set) {
      var re = /\.(mov|flv|ogg|ogv|swf|wmv|avi)$/;
      if (matches[3] != undefined) {
        re = new RegExp(matches[3] + '$');
      }
      return !!element.href && re.test(element.href);
    }
  });
})(jQuery);

/** =product index hovers
************************************************************/
$(document).ready(function() {
  $('body.p-products-home .content-header-a .nav li a, body.p-home-dealer div.product-cats ul.nav a').hover(
    function(){
      $(this).stop(false, true).animate({top:"-10px"}, 100);
    },
    function(){
      $(this).stop(false, false).animate({top:"0"}, 500);
    });
});

/** =forms
************************************************************/
$(document).ready(function() {

  if( $('form.validate').length ) {
    $.getScript('/tools/min/index.php?g=validation');
  }

});

/** =library vids
************************************************************/
$(document).ready(function() {
  var $vids = $('.p-library #videos');
  if ($vids.length) {

    $(window).bind('load', function() {

      $vids.addClass('loading').load('/includes/videos/', function() {
        $vids.removeClass('loading');
        if (typeof $.fn.columns !== 'undefined') {
          $vids.children('ul').columns({columns: 3});
        }

        $.fancyvids('#videos');

      });

    });
  }
});

/** =columns
************************************************************/
$(document).ready(function() {
  var $listClass = $('ul, ol').filter('[class^=columnize-]');
  if (!$listClass.length || typeof $.fn.columns === 'undefined') { return; }

  $.extend($.fn.columns.defaults, {
    containerWidth: 940,
    autoWidth: true,
    gutter: 20,
    columnClass: 'col'
  });

  $('.columnize-2').columns({ columns: 2 });
  $('.columnize-3').columns({ columns: 3 });
  $('.columnize-4').columns({ columns: 4 });
  $('.columnize-5').columns({ columns: 5 });
  $('.columnize-6').columns({ columns: 6 });

});

/** =ecard
************************************************************/
$(document).ready(function() {
  if ( $('div.ecard-step-1').length ) {
    var $template = $('div.template'),
        $form = $template.closest('form'),
        $button = $form.find('button:submit');

    $template.find('input:radio').bind('click', function() {
      $(this).closest('.checkbox').append($button);
    });
  }
});


$(document).ready(function() {

/** =equal heights
************************************************************/

  $('div.column-feature > div').each(function(index) {
    $(this).children().not(':last')
      .wrapAll('<div class="main"></div>');
  });
  $('div.column-feature .main').sameHeight();

  $('div.finishes-list ul.finishes').each(function(index) {
    $(this).find('li').sameHeight();
  });

  $('div.callouts').each(function(index) {
    $(this).find('div').sameHeight();
  });



/** =tooltips
************************************************************/

  if (typeof $.fn.simpletip !== 'undefined') {
    $(document.body).simpletip('a.adstock-order');
  }

});

/**
* in2 log page
* --------------------------------------------------
*/

$(document).ready(function() {
  if (typeof $.fn.tablesorter !== 'undefined') {
    $('table.tablesorter').tablesorter({
      cssHeader: 'sort-header'
    });
  }
  if (typeof $.fn.datepicker !== 'undefined') {
    $('#in2-date').datepicker({
      dateFormat: 'yy-mm-dd'
    });
  }

});

