/* sbc 2011 specific js */

//ie7 z-index fix
var fixIe7Divs = function() {
  if ($.browser.msie && $.browser.version.substr(0,1) <= 7) {
    var pagePath = window.location.pathname+"";
    if(pagePath.indexOf("SBCEqLander.jsp")        > 0 ||
       pagePath.indexOf("SBCEqSCLander.jsp")      > 0 ||
       pagePath.indexOf("SBCEqSelectSection.jsp") > 0 ||
       pagePath.indexOf("SBCEqProductList.jsp")   > 0) {

      $(function() {
        var zIndexNumber = 1000;
        $('div').each(function() {
          $(this).css('zIndex', zIndexNumber);
          zIndexNumber -= 10;
        });
      });
    }
  }  
}

$(document).ready(function() {
  fixIe7Divs();
	
  $('#coda-slider-1').codaSlider();
  //display arrows only if more than one panel
  if ($('.panel-container .panel').length < 2){
    $('.coda-nav-left').hide();
    $('.coda-nav-right').hide();
  };
  
  // equipment lander rotating header images
  /*
  $('#eq-rotating-nav').nivoSlider({
    effect:'fade',
    slices:1,
    animSpeed:300,
    pauseTime:6000,
    startSlide:0, //Set starting Slide (0 index)
    directionNav:true, //Next  Prev
    directionNavHide:false, //Only show on hover
    controlNav:true, //1,2,3...
    controlNavThumbs:false, //Use thumbnails for Control Nav
    controlNavThumbsSearch: '.jpg', //Replace this with...
    controlNavThumbsReplace: '_thumb.jpg', //...this in thumb Image src
    keyboardNav:false, //Use left & right arrows
    pauseOnHover:false //Stop animation while hovering        
  });
  */
  
  (function() {
    $('#eq-rotating-nav').css("zIndex", 11);

    var zindex = 11;  
    $('#eq-rotating-nav').children().each(function() {
      $(this).css("zIndex", zindex);
      zindex += 1;
    });
  });
  
  // hack to only show the true first image AND text
  $('eq-rotating-link:gt(0)').css('display', 'none');
  
  // increase spacing for more than two rotating images
  if ($('.nivo-control').length > 2) {
	var rightspace = 60+($('.nivo-control').length - 2)*12;
	rightspace+='px';
	$('.nivo-prevNav').css('right', rightspace);
  };
  
  if ($('.eq-rotating-link').length < 2) {
	 $('.nivo-directionNav').hide();
	 $('.nivo-controlNav').hide();
  };
  
  //anchor-fade fades the image bound by an anchor on hover
  //to use, simply add 'anchor-fade' as a class to whatever container you want to fade out/in on hover over/out
  $('.anchor-fade').hover(function(){
	  $(this).fadeTo("slow", .4);
  },function(){
	  $(this).fadeTo("slow", 1);
  });
  
  /* tooltips in hotspot carousel image */
  $('.hs_info').tooltip({
        showURL: false
      });
  
  $('.tooltip').tooltip({
	  showURL: false
  })
      
  /* tabs... homebrewed to work with other js files below */
  //When page loads...
  $(".sbc-cyclopedia-wwh").hide(); //Hide all content
  $("ul.sbc-wwh-tabs li:first").addClass("active").show(); //Activate first tab
  $(".sbc-cyclopedia-wwh:first").show(); //Show first tab content

  //On Click Event
  $("ul.sbc-wwh-tabs li").click(function() {

    $("ul.sbc-wwh-tabs li").removeClass("active"); //Remove any "active" class
    $(this).addClass("active"); //Add "active" class to selected tab
    $(".sbc-cyclopedia-wwh").hide(); //Hide all tab content

    var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
    $(activeTab).fadeIn(); //Fade in the active ID content
    return false;
  });
  
});

/*
 * jQuery Tooltip plugin 1.3
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/
 * http://docs.jquery.com/Plugins/Tooltip
 *
 * Copyright (c) 2006 - 2008 Jörn Zaefferer
 *
 * $Id: jquery.tooltip.js 5741 2008-06-21 15:22:16Z joern.zaefferer $
 * 
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
 
;(function($) {
  
    // the tooltip element
  var helper = {},
    // the current tooltipped element
    current,
    // the title of the current element, used for restoring
    title,
    // timeout id for delayed tooltips
    tID,
    // IE 5.5 or 6
    IE = $.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent),
    // flag for mouse tracking
    track = false;
  
  $.tooltip = {
    blocked: false,
    defaults: {
      delay: 200,
      fade: false,
      showURL: true,
      extraClass: "",
      top: 15,
      left: 15,
      id: "tooltip"
    },
    block: function() {
      $.tooltip.blocked = !$.tooltip.blocked;
    }
  };
  
  $.fn.extend({
    tooltip: function(settings) {
      settings = $.extend({}, $.tooltip.defaults, settings);
      createHelper(settings);
      return this.each(function() {
          $.data(this, "tooltip", settings);
          this.tOpacity = helper.parent.css("opacity");
          // copy tooltip into its own expando and remove the title
          this.tooltipText = this.title;
          $(this).removeAttr("title");
          // also remove alt attribute to prevent default tooltip in IE
          this.alt = "";
        })
        .mouseover(save)
        .mouseout(hide)
        .click(hide);
    },
    fixPNG: IE ? function() {
      return this.each(function () {
        var image = $(this).css('backgroundImage');
        if (image.match(/^url\(["']?(.*\.png)["']?\)$/i)) {
          image = RegExp.$1;
          $(this).css({
            'backgroundImage': 'none',
            'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + image + "')"
          }).each(function () {
            var position = $(this).css('position');
            if (position != 'absolute' && position != 'relative')
              $(this).css('position', 'relative');
          });
        }
      });
    } : function() { return this; },
    unfixPNG: IE ? function() {
      return this.each(function () {
        $(this).css({'filter': '', backgroundImage: ''});
      });
    } : function() { return this; },
    hideWhenEmpty: function() {
      return this.each(function() {
        $(this)[ $(this).html() ? "show" : "hide" ]();
      });
    },
    url: function() {
      return this.attr('href') || this.attr('src');
    }
  });
  
  function createHelper(settings) {
    // there can be only one tooltip helper
    if( helper.parent )
      return;
    // create the helper, h3 for title, div for url
    helper.parent = $('<div id="' + settings.id + '"><h3></h3><div class="body"></div><div class="url"></div></div>')
      // add to document
      .appendTo(document.body)
      // hide it at first
      .hide();
      
    // apply bgiframe if available
    if ( $.fn.bgiframe )
      helper.parent.bgiframe();
    
    // save references to title and url elements
    helper.title = $('h3', helper.parent);
    helper.body = $('div.body', helper.parent);
    helper.url = $('div.url', helper.parent);
  }
  
  function settings(element) {
    return $.data(element, "tooltip");
  }
  
  // main event handler to start showing tooltips
  function handle(event) {
    // show helper, either with timeout or on instant
    if( settings(this).delay )
      tID = setTimeout(show, settings(this).delay);
    else
      show();
    
    // if selected, update the helper position when the mouse moves
    track = !!settings(this).track;
    $(document.body).bind('mousemove', update);
      
    // update at least once
    update(event);
  }
  
  // save elements title before the tooltip is displayed
  function save() {
    // if this is the current source, or it has no title (occurs with click event), stop
    if ( $.tooltip.blocked || this == current || (!this.tooltipText && !settings(this).bodyHandler) )
      return;

    // save current
    current = this;
    title = this.tooltipText;
    
    if ( settings(this).bodyHandler ) {
      helper.title.hide();
      var bodyContent = settings(this).bodyHandler.call(this);
      if (bodyContent.nodeType || bodyContent.jquery) {
        helper.body.empty().append(bodyContent)
      } else {
        helper.body.html( bodyContent );
      }
      helper.body.show();
    } else if ( settings(this).showBody ) {
      var parts = title.split(settings(this).showBody);
      helper.title.html(parts.shift()).show();
      helper.body.empty();
      for(var i = 0, part; (part = parts[i]); i++) {
        if(i > 0)
          helper.body.append("<br/>");
        helper.body.append(part);
      }
      helper.body.hideWhenEmpty();
    } else {
      helper.title.html(title).show();
      helper.body.hide();
    }
    
    // if element has href or src, add and show it, otherwise hide it
    if( settings(this).showURL && $(this).url() )
      helper.url.html( $(this).url().replace('http://', '') ).show();
    else 
      helper.url.hide();
    
    // add an optional class for this tip
    helper.parent.addClass(settings(this).extraClass);

    // fix PNG background for IE
    if (settings(this).fixPNG )
      helper.parent.fixPNG();
      
    handle.apply(this, arguments);
  }
  
  // delete timeout and show helper
  function show() {
    tID = null;
    if ((!IE || !$.fn.bgiframe) && settings(current).fade) {
      if (helper.parent.is(":animated"))
        helper.parent.stop().show().fadeTo(settings(current).fade, current.tOpacity);
      else
        helper.parent.is(':visible') ? helper.parent.fadeTo(settings(current).fade, current.tOpacity) : helper.parent.fadeIn(settings(current).fade);
    } else {
      helper.parent.show();
    }
    update();
  }
  
  /**
   * callback for mousemove
   * updates the helper position
   * removes itself when no current element
   */
  function update(event)  {
    if($.tooltip.blocked)
      return;
    
    if (event && event.target.tagName == "OPTION") {
      return;
    }
    
    // stop updating when tracking is disabled and the tooltip is visible
    if ( !track && helper.parent.is(":visible")) {
      $(document.body).unbind('mousemove', update)
    }
    
    // if no current element is available, remove this listener
    if( current == null ) {
      $(document.body).unbind('mousemove', update);
      return; 
    }
    
    // remove position helper classes
    helper.parent.removeClass("viewport-right").removeClass("viewport-bottom");
    
    var left = helper.parent[0].offsetLeft;
    var top = helper.parent[0].offsetTop;
    if (event) {
      // position the helper 15 pixel to bottom right, starting from mouse position
      left = event.pageX + settings(current).left;
      top = event.pageY + settings(current).top;
      var right='auto';
      if (settings(current).positionLeft) {
        right = $(window).width() - left;
        left = 'auto';
      }
      helper.parent.css({
        left: left,
        right: right,
        top: top
      });
    }
    
    var v = viewport(),
      h = helper.parent[0];
    // check horizontal position
    if (v.x + v.cx < h.offsetLeft + h.offsetWidth) {
      left -= h.offsetWidth + 20 + settings(current).left;
      helper.parent.css({left: left + 'px'}).addClass("viewport-right");
    }
    // check vertical position
    if (v.y + v.cy < h.offsetTop + h.offsetHeight) {
      top -= h.offsetHeight + 20 + settings(current).top;
      helper.parent.css({top: top + 'px'}).addClass("viewport-bottom");
    }
  }
  
  function viewport() {
    return {
      x: $(window).scrollLeft(),
      y: $(window).scrollTop(),
      cx: $(window).width(),
      cy: $(window).height()
    };
  }
  
  // hide helper and restore added classes and the title
  function hide(event) {
    if($.tooltip.blocked)
      return;
    // clear timeout if possible
    if(tID)
      clearTimeout(tID);
    // no more current element
    current = null;
    
    var tsettings = settings(this);
    function complete() {
      helper.parent.removeClass( tsettings.extraClass ).hide().css("opacity", "");
    }
    if ((!IE || !$.fn.bgiframe) && tsettings.fade) {
      if (helper.parent.is(':animated'))
        helper.parent.stop().fadeTo(tsettings.fade, 0, complete);
      else
        helper.parent.stop().fadeOut(tsettings.fade, complete);
    } else
      complete();
    
    if( settings(this).fixPNG )
      helper.parent.unfixPNG();
  }
  
})(jQuery);

/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 *
 * Uses the built in easing capabilities added In jQuery 1.1
 * to offer multiple easing options
 *
 * TERMS OF USE - jQuery Easing
 * 
 * Open source under the BSD License. 
 * 
 * Copyright © 2008 George McGinley Smith
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
*/

// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend( jQuery.easing,
{
  def: 'easeOutQuad',
  swing: function (x, t, b, c, d) {
    //alert(jQuery.easing.default);
    return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
  },
  easeInQuad: function (x, t, b, c, d) {
    return c*(t/=d)*t + b;
  },
  easeOutQuad: function (x, t, b, c, d) {
    return -c *(t/=d)*(t-2) + b;
  },
  easeInOutQuad: function (x, t, b, c, d) {
    if ((t/=d/2) < 1) return c/2*t*t + b;
    return -c/2 * ((--t)*(t-2) - 1) + b;
  },
  easeInCubic: function (x, t, b, c, d) {
    return c*(t/=d)*t*t + b;
  },
  easeOutCubic: function (x, t, b, c, d) {
    return c*((t=t/d-1)*t*t + 1) + b;
  },
  easeInOutCubic: function (x, t, b, c, d) {
    if ((t/=d/2) < 1) return c/2*t*t*t + b;
    return c/2*((t-=2)*t*t + 2) + b;
  },
  easeInQuart: function (x, t, b, c, d) {
    return c*(t/=d)*t*t*t + b;
  },
  easeOutQuart: function (x, t, b, c, d) {
    return -c * ((t=t/d-1)*t*t*t - 1) + b;
  },
  easeInOutQuart: function (x, t, b, c, d) {
    if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
    return -c/2 * ((t-=2)*t*t*t - 2) + b;
  },
  easeInQuint: function (x, t, b, c, d) {
    return c*(t/=d)*t*t*t*t + b;
  },
  easeOutQuint: function (x, t, b, c, d) {
    return c*((t=t/d-1)*t*t*t*t + 1) + b;
  },
  easeInOutQuint: function (x, t, b, c, d) {
    if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
    return c/2*((t-=2)*t*t*t*t + 2) + b;
  },
  easeInSine: function (x, t, b, c, d) {
    return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
  },
  easeOutSine: function (x, t, b, c, d) {
    return c * Math.sin(t/d * (Math.PI/2)) + b;
  },
  easeInOutSine: function (x, t, b, c, d) {
    return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
  },
  easeInExpo: function (x, t, b, c, d) {
    return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
  },
  easeOutExpo: function (x, t, b, c, d) {
    return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
  },
  easeInOutExpo: function (x, t, b, c, d) {
    if (t==0) return b;
    if (t==d) return b+c;
    if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
    return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
  },
  easeInCirc: function (x, t, b, c, d) {
    return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
  },
  easeOutCirc: function (x, t, b, c, d) {
    return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
  },
  easeInOutCirc: function (x, t, b, c, d) {
    if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
    return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
  },
  easeInElastic: function (x, t, b, c, d) {
    var s=1.70158;var p=0;var a=c;
    if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
    if (a < Math.abs(c)) { a=c; var s=p/4; }
    else var s = p/(2*Math.PI) * Math.asin (c/a);
    return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
  },
  easeOutElastic: function (x, t, b, c, d) {
    var s=1.70158;var p=0;var a=c;
    if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
    if (a < Math.abs(c)) { a=c; var s=p/4; }
    else var s = p/(2*Math.PI) * Math.asin (c/a);
    return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
  },
  easeInOutElastic: function (x, t, b, c, d) {
    var s=1.70158;var p=0;var a=c;
    if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
    if (a < Math.abs(c)) { a=c; var s=p/4; }
    else var s = p/(2*Math.PI) * Math.asin (c/a);
    if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
    return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
  },
  easeInBack: function (x, t, b, c, d, s) {
    if (s == undefined) s = 1.70158;
    return c*(t/=d)*t*((s+1)*t - s) + b;
  },
  easeOutBack: function (x, t, b, c, d, s) {
    if (s == undefined) s = 1.70158;
    return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
  },
  easeInOutBack: function (x, t, b, c, d, s) {
    if (s == undefined) s = 1.70158; 
    if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
    return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
  },
  easeInBounce: function (x, t, b, c, d) {
    return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
  },
  easeOutBounce: function (x, t, b, c, d) {
    if ((t/=d) < (1/2.75)) {
      return c*(7.5625*t*t) + b;
    } else if (t < (2/2.75)) {
      return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
    } else if (t < (2.5/2.75)) {
      return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
    } else {
      return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
    }
  },
  easeInOutBounce: function (x, t, b, c, d) {
    if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
    return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
  }
});

/*
 *
 * TERMS OF USE - EASING EQUATIONS
 * 
 * Open source under the BSD License. 
 * 
 * Copyright © 2001 Robert Penner
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
 */
 
/*
  jQuery Coda-Slider v2.0 - http://www.ndoherty.biz/coda-slider
  Copyright (c) 2009 Niall Doherty
  This plugin available for use in all personal or commercial projects under both MIT and GPL licenses.
*/

$(function(){
  // Remove the coda-slider-no-js class from the body
  $("body").removeClass("coda-slider-no-js");
  // Preloader
  //$(".coda-slider").children('.panel').hide().end().prepend('<p class="loading">Loading...<br /><img src="images/ajax-loader.gif" alt="loading..." /></p>');
});

var sliderCount = 1;

$.fn.codaSlider = function(settings) {

  settings = $.extend({
    autoHeight: true,
    autoHeightEaseDuration: 1000,
    autoHeightEaseFunction: "easeInOutExpo",
    autoSlide: false,
    autoSlideInterval: 7000,
    autoSlideStopWhenClicked: true,
    crossLinking: true,
    dynamicArrows: true,
    dynamicArrowLeftText: "&#171; left",
    dynamicArrowRightText: "right &#187;",
    dynamicTabs: true,
    dynamicTabsAlign: "center",
    dynamicTabsPosition: "top",
    externalTriggerSelector: "a.xtrig",
    firstPanelToLoad: 1,
    panelTitleSelector: "h2.title",
    slideEaseDuration: 1000,
    slideEaseFunction: "easeInOutExpo"
  }, settings);
  
  return this.each(function(){
    
    // Uncomment the line below to test your preloader
    // alert("Testing preloader");
    
    var slider = $(this);
    
    // If we need arrows
    if (settings.dynamicArrows) {
      slider.parent().addClass("arrows");
      slider.parent().before('<div class="coda-nav-left" id="coda-nav-left-' + sliderCount + '"><a class="sbc-prev-arrow arrow" href="#"></a></div>');
      slider.parent().after('<div class="coda-nav-right" id="coda-nav-right-' + sliderCount + '"><a class="sbc-next-arrow arrow" href="#"></a></div>');
    };
    
    var panelWidth = slider.find(".panel").width();
    var panelCount = slider.find(".panel").size();
    var panelContainerWidth = panelWidth*panelCount;
    var navClicks = 0; // Used if autoSlideStopWhenClicked = true
    
    // Surround the collection of panel divs with a container div (wide enough for all panels to be lined up end-to-end)
    $('.panel', slider).wrapAll('<div class="panel-container"></div>');
    // Specify the width of the container div (wide enough for all panels to be lined up end-to-end)
    $(".panel-container", slider).css({ width: panelContainerWidth });
    
    // Specify the current panel.
    // If the loaded URL has a hash (cross-linking), we're going to use that hash to give the slider a specific starting position...
    if (settings.crossLinking && location.hash && parseInt(location.hash.slice(1)) <= panelCount) {
      var currentPanel = parseInt(location.hash.slice(1));
      var offset = - (panelWidth*(currentPanel - 1));
      $('.panel-container', slider).css({ marginLeft: offset });
    // If that's not the case, check to see if we're supposed to load a panel other than Panel 1 initially...
    } else if (settings.firstPanelToLoad != 1 && settings.firstPanelToLoad <= panelCount) { 
      var currentPanel = settings.firstPanelToLoad;
      var offset = - (panelWidth*(currentPanel - 1));
      $('.panel-container', slider).css({ marginLeft: offset });
    // Otherwise, we'll just set the current panel to 1...
    } else { 
      var currentPanel = 1;
    };
      
    // Left arrow click
    $("#coda-nav-left-" + sliderCount + " a").click(function(){
      navClicks++;
      if (currentPanel == 1) {
        offset = - (panelWidth*(panelCount - 1));
        alterPanelHeight(panelCount - 1);
        currentPanel = panelCount;
        slider.siblings('.coda-nav').find('a.current').removeClass('current').parents('ul').find('li:last a').addClass('current');
      } else {
        currentPanel -= 1;
        alterPanelHeight(currentPanel - 1);
        offset = - (panelWidth*(currentPanel - 1));
        slider.siblings('.coda-nav').find('a.current').removeClass('current').parent().prev().find('a').addClass('current');
      };
      $('.panel-container', slider).animate({ marginLeft: offset }, settings.slideEaseDuration, settings.slideEaseFunction);
      if (settings.crossLinking) { location.hash = currentPanel }; // Change the URL hash (cross-linking)
      return false;
    });
      
    // Right arrow click
    $('#coda-nav-right-' + sliderCount + ' a').click(function(){
      navClicks++;
      if (currentPanel == panelCount) {
        offset = 0;
        currentPanel = 1;
        alterPanelHeight(0);
        slider.siblings('.coda-nav').find('a.current').removeClass('current').parents('ul').find('a:eq(0)').addClass('current');
      } else {
        offset = - (panelWidth*currentPanel);
        alterPanelHeight(currentPanel);
        currentPanel += 1;
        slider.siblings('.coda-nav').find('a.current').removeClass('current').parent().next().find('a').addClass('current');
      };
      $('.panel-container', slider).animate({ marginLeft: offset }, settings.slideEaseDuration, settings.slideEaseFunction);
      if (settings.crossLinking) { location.hash = currentPanel }; // Change the URL hash (cross-linking)
      return false;
    });
    
    // If we need a dynamic menu
    if (settings.dynamicTabs) {
      var dynamicTabs = '<div class="coda-nav" id="coda-nav-' + sliderCount + '"><ul></ul></div>';
      switch (settings.dynamicTabsPosition) {
        case "bottom":
          slider.parent().append(dynamicTabs);
          break;
        default:
          slider.parent().prepend(dynamicTabs);
          break;
      };
      ul = $('#coda-nav-' + sliderCount + ' ul');
      // Create the nav items
      $('.panel', slider).each(function(n) {
        ul.append('<li class="tab' + (n+1) + '"><a href="#' + (n+1) + '">' + $(this).find(settings.panelTitleSelector).text() + '</a></li>');                       
      });
      navContainerWidth = slider.width() + slider.siblings('.coda-nav-left').width() + slider.siblings('.coda-nav-right').width();
      ul.parent().css({ width: navContainerWidth });
      switch (settings.dynamicTabsAlign) {
        case "center":
          ul.css({ width: ($("li", ul).width() + 2) * panelCount });
          break;
        case "right":
          //ul.css({ float: 'right' });
          ul.addClass('right');
          break;
      };
    };
      
    // If we need a tabbed nav
    $('#coda-nav-' + sliderCount + ' a').each(function(z) {
      // What happens when a nav link is clicked
      $(this).bind("click", function() {
        navClicks++;
        $(this).addClass('current').parents('ul').find('a').not($(this)).removeClass('current');
        offset = - (panelWidth*z);
        alterPanelHeight(z);
        currentPanel = z + 1;
        $('.panel-container', slider).animate({ marginLeft: offset }, settings.slideEaseDuration, settings.slideEaseFunction);
        if (!settings.crossLinking) { return false }; // Don't change the URL hash unless cross-linking is specified
      });
    });
    
    // External triggers (anywhere on the page)
    $(settings.externalTriggerSelector).each(function() {
      // Make sure this only affects the targeted slider
      if (sliderCount == parseInt($(this).attr("rel").slice(12))) {
        $(this).bind("click", function() {
          navClicks++;
          targetPanel = parseInt($(this).attr("href").slice(1));
          offset = - (panelWidth*(targetPanel - 1));
          alterPanelHeight(targetPanel - 1);
          currentPanel = targetPanel;
          // Switch the current tab:
          slider.siblings('.coda-nav').find('a').removeClass('current').parents('ul').find('li:eq(' + (targetPanel - 1) + ') a').addClass('current');
          // Slide
          $('.panel-container', slider).animate({ marginLeft: offset }, settings.slideEaseDuration, settings.slideEaseFunction);
          if (!settings.crossLinking) { return false }; // Don't change the URL hash unless cross-linking is specified
        });
      };
    });
      
    // Specify which tab is initially set to "current". Depends on if the loaded URL had a hash or not (cross-linking).
    if (settings.crossLinking && location.hash && parseInt(location.hash.slice(1)) <= panelCount) {
      $("#coda-nav-" + sliderCount + " a:eq(" + (location.hash.slice(1) - 1) + ")").addClass("current");
    // If there's no cross-linking, check to see if we're supposed to load a panel other than Panel 1 initially...
    } else if (settings.firstPanelToLoad != 1 && settings.firstPanelToLoad <= panelCount) {
      $("#coda-nav-" + sliderCount + " a:eq(" + (settings.firstPanelToLoad - 1) + ")").addClass("current");
    // Otherwise we must be loading Panel 1, so make the first tab the current one.
    } else {
      $("#coda-nav-" + sliderCount + " a:eq(0)").addClass("current");
    };
    
    // Set the height of the first panel
    if (settings.autoHeight) {
      panelHeight = $('.panel:eq(' + (currentPanel - 1) + ')', slider).height();
      // hack fix, does not get the proper height of the panel
      slider.css({ height: panelHeight });
    };
    
    // Trigger autoSlide
    if (settings.autoSlide) {
      slider.ready(function() {
        setTimeout(autoSlide,settings.autoSlideInterval);
      });
    };
    
    function alterPanelHeight(x) {
      if (settings.autoHeight) {
        panelHeight = $('.panel:eq(' + x + ')', slider).height()
        slider.animate({ height: panelHeight }, settings.autoHeightEaseDuration, settings.autoHeightEaseFunction);
      };
    };
    
    function autoSlide() {
      if (navClicks == 0 || !settings.autoSlideStopWhenClicked) {
        if (currentPanel == panelCount) {
          var offset = 0;
          currentPanel = 1;
        } else {
          var offset = - (panelWidth*currentPanel);
          currentPanel += 1;
        };
        alterPanelHeight(currentPanel - 1);
        // Switch the current tab:
        slider.siblings('.coda-nav').find('a').removeClass('current').parents('ul').find('li:eq(' + (currentPanel - 1) + ') a').addClass('current');
        // Slide:
        $('.panel-container', slider).animate({ marginLeft: offset }, settings.slideEaseDuration, settings.slideEaseFunction);
        setTimeout(autoSlide,settings.autoSlideInterval);
      };
    };
    
    // Kill the preloader
    $('.panel', slider).show().end().find("p.loading").remove();
    slider.removeClass("preload");
    
    sliderCount++;
    
  });
};﻿
/**
* hoverIntent is similar to jQuery's built-in "hover" function except that
* instead of firing the onMouseOver event immediately, hoverIntent checks
* to see if the user's mouse has slowed down (beneath the sensitivity
* threshold) before firing the onMouseOver event.
* 
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* hoverIntent is currently available for use in all personal or commercial 
* projects under both MIT and GPL licenses. This means that you can choose 
* the license that best suits your project, and use it accordingly.
* 
* // basic usage (just like .hover) receives onMouseOver and onMouseOut functions
* $("ul li").hoverIntent( showNav , hideNav );
* 
* // advanced usage receives configuration object only
* $("ul li").hoverIntent({
*	sensitivity: 7, // number = sensitivity threshold (must be 1 or higher)
*	interval: 100,   // number = milliseconds of polling interval
*	over: showNav,  // function = onMouseOver callback (required)
*	timeout: 0,   // number = milliseconds delay before onMouseOut function call
*	out: hideNav    // function = onMouseOut callback (required)
* });
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne <brian@cherne.net>
*/
(function($) {
	$.fn.hoverIntent = function(f,g) {
		// default configuration options
		var cfg = {
			sensitivity: 7,
			interval: 100,
			timeout: 0
		};
		// override configuration options with user supplied object
		cfg = $.extend(cfg, g ? { over: f, out: g } : f );

		// instantiate variables
		// cX, cY = current X and Y position of mouse, updated by mousemove event
		// pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
		var cX, cY, pX, pY;

		// A private function for getting mouse position
		var track = function(ev) {
			cX = ev.pageX;
			cY = ev.pageY;
		};

		// A private function for comparing current and previous mouse position
		var compare = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			// compare mouse positions to see if they've crossed the threshold
			if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
				$(ob).unbind("mousemove",track);
				// set hoverIntent state to true (so mouseOut can be called)
				ob.hoverIntent_s = 1;
				return cfg.over.apply(ob,[ev]);
			} else {
				// set previous coordinates for next time
				pX = cX; pY = cY;
				// use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
				ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
			}
		};

		// A private function for delaying the mouseOut function
		var delay = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			ob.hoverIntent_s = 0;
			return cfg.out.apply(ob,[ev]);
		};

		// A private function for handling mouse 'hovering'
		var handleHover = function(e) {
			// next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut
			var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
			while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } }
			if ( p == this ) { return false; }

			// copy objects to be passed into t (required for event object to be passed in IE)
			var ev = jQuery.extend({},e);
			var ob = this;

			// cancel hoverIntent timer if it exists
			if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

			// else e.type == "onmouseover"
			if (e.type == "mouseover") {
				// set "previous" X and Y position based on initial entry point
				pX = ev.pageX; pY = ev.pageY;
				// update "current" X and Y position based on mousemove
				$(ob).bind("mousemove",track);
				// start polling interval (self-calling timeout) to compare mouse coordinates over time
				if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}

			// else e.type == "onmouseout"
			} else {
				// unbind expensive mousemove event
				$(ob).unbind("mousemove",track);
				// if hoverIntent state is true, then call the mouseOut function after the specified delay
				if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
			}
		};

		// bind the function to the two event listeners
		return this.mouseover(handleHover).mouseout(handleHover);
	};
})(jQuery);

// popups.js -----------------------------------------------------------

var specWindow = null
var specWindowConfig = null
var specWindowWidth = null

function techPopup(pId, pWidth, pHeight) {
  var windowCfg = "scrollbars,resizable,height=" + pHeight + ",width=" + pWidth
  var techWindow = window.open('SBCTechPopup.jsp?pid=' + pId, '', windowCfg)
}

function bullet(bulletCode) {
  if (bulletCode.substring(0, 4) == 'size') sizeChart(bulletCode)
  else {
    if (bulletCode.substring(0, 4) == '3dsm') threedsm(bulletCode)
    else specPopup(bulletCode)
  }
}

function threedsm(threedsmCode) {
  specWindowWidth = 500
  if (threedsmCode.substring(0, 8) == '3dsmsole') specWindowWidth = 700
  pOpen(500, specWindowWidth, 'http://www.specialized.com/specialized/' + threedsmCode + '.htm')
}

function specPopup(specCode) {
  specWindowWidth = 450
  if (specCode == 'bodygeometryshoes') specWindowWidth = 750
  var tableWidth = specWindowWidth - 50
  var cellWidth = specWindowWidth - 100
  pOpen(300, specWindowWidth, '/specs/spec.jsp?speccode=' + specCode + '&tablewidth=' + tableWidth + '&cellwidth=' + cellWidth)
}

function experience(experienceCode, sectURL) {
  pOpen(290, 660, '/experience/experience.jsp?expcode=' + experienceCode + '&secturl=' + sectURL)
}

function sizeChart(chartCode) {
  pOpen(400, 480, '/sizecharts/sizechart.jsp?chartcode=' + chartCode)
}

function newfor2002(new2002Code) {
  pOpen(250, 480, '/sections/new2002.jsp?new2002code=' + new2002Code)
}

function newfor2003(new2003Code) {
  pOpen(250, 480, '/sections/new2003.jsp?new2003code=' + new2003Code)
}

function newfor2004(new2004Code) {
  pOpen(250, 480, '/sections/new2004.jsp?new2004code=' + new2004Code)
}

function comparisonChart(chartCode) {
  pOpen(400, 725, '/sizecharts/comparisonchart.jsp?chartcode=' + chartCode)
}

function reviewPopup(reviewURL) {
  pOpen(450, 725, reviewURL)
}

function equipPopup(equipImage, equipModel) {
  pOpen(575, 695, 'SBCEquipPopup.jsp?equipimage=' + equipImage + '&equipmodel=' + equipModel)
}

function bikePopup(bikeImage, bikeModel) {
  pOpen(768, 1024, 'SBCBikePopup.jsp?bikeimage=' + bikeImage + '&bikemodel=' + bikeModel)
}

function bikePopup(equipImage, equipModel) {
  pOpen(768, 1024, 'SBCEquipPopup.jsp?equipimage=' + equipImage + '&equipmodel=' + equipModel)
}

function geometryPopup(spid) {
  pOpen(350, 750, 'SBCGeometryPopup.jsp?spid=' + spid)
}

function concept(conceptCode) {
  pOpen(600, 625, '/concepts/concepts.jsp?conceptcode=' + conceptCode)
}

function conceptStore(conceptStoreCode) {
  pOpen(600, 625, '/conceptstore/conceptstore.jsp?conceptstorecode=' + conceptStoreCode)
}


function bmx(bmxCode) {
  pOpen(600, 625, '/bmx/bmxs.jsp?bmxcode=' + bmxCode)
}

function buckley(buckleyCode) {
  pOpen(600, 625, '/buckley/buckleys.jsp?buckleycode=' + buckleyCode)
}


function history(historyCode) {
  pOpen(600, 625, '/history/historys.jsp?historycode=' + historyCode)
}

function faq(xsrcCode) {
  pOpen2(620, 720, 'SBCFAQPop.jsp?xsrc=' + xsrcCode)
}

function bFree(url) {
  pOpen(600, 625, url)
}

function pOpen(pHeight, pWidth, pLoc) {
  var scrollBars = 'yes'
  if (pOpen.arguments.length == 4) scrollBars = pOpen.arguments[4]
  specWindowConfig="toolbar=no,location=no,scrollbars=" + scrollBars + ",menubar=no,resizable=yes,status=no,height=" + pHeight + ",width=" + pWidth
  if (specWindow && !specWindow.closed) specWindow.close()
  specWindow = window.open(pLoc, '', specWindowConfig)
  //clearInterval(track)
}

function pOpen2(pHeight, pWidth, pLoc) {
  specWindowConfig="toolbar=yes,location=no,scrollbars=yes,menubar=no,resizable=yes,status=no,height=" + pHeight + ",width=" + pWidth
  if (specWindow && !specWindow.closed) specWindow.close()
  specWindow = window.open(pLoc, '', specWindowConfig)
  //clearInterval(track)
}

/*	******************************

	PLUGIN - Specialized Menu
	Author: Jack Lukic - KNI 
	Notes: Dynamic menu system for specialized.com
		
	// Settings	
		
	setting: default value - explanation
	 
	collapse: true - whether to use accordion style menus
	hideTimer: 1500 - time between mousing off menu and the menu closing
	showSpeed: 600 - time in milliseconds for showing a menu
	showEasing: easeOutExpo - type of easing to use for showing an item
	hideSpeed: 300 - time in milliseconds for showing a menu
	hideEasing: easeOutQuad - type of easing to use for showing an item
	
	levelSelector: ul - selector for a grouping of items (any jQuery/xpath selector)
	elementSelector: li - selector for a single item (any jQuery/xpath selector)
	
	menuSelector - .list - class name given to entire menu container
	blockerSelector - .disable - adding this class name to any link inside menu disables the link from being followed
	
	// initialize using jQuery object
	
	var options = {
		// custom options	
		collapse: false,
		hideTimer: 1500,
		levelSelector: '.group',
		menuSelector: '.page'
	}
	$('#thingy').menu(options);
		
********************************/


(function($) {
	
	jQuery.fn.extend({
		menu: function(params) {
			
			// iterate over each el passed in
			$(this).each(function() {
				
				// define default settings
				var settings = {					
					collapse: true,
					hideTimer: 500,
					showSpeed: 500,
					showEasing: 'easeOutExpo',
					hideSpeed: 300,
					hideEasing: 'easeOutQuad',					
					levelSelector: 'ul',
					elementSelector: 'li',					
					menuSelector: '.list',
					blockerSelector: '.disable',
					hideAfter: '0'
				};				
				jQuery.extend(settings, params);
				
				// cache jQuery objects
				var $menu = $(this);
				var $pulldownMenu = $menu.find(settings.menuSelector);
				// if menu is set to show & hide
				if(settings.hideAfter != 0 && parseInt(settings.hideAfter) > 0) {
					// show menu
					$menu
						.addClass('active')
						.find(settings.menuSelector)
							.slideDown(settings.showSpeed, settings.showEasing)
							.children(settings.levelSelector)
								.animate({opacity: 1}, settings.showSpeed);
					// set hide event
					var hideAfterTimer = setTimeout(function() {
						$menu
							.removeClass('active')
							.find(settings.menuSelector)
								.slideUp(settings.hideSpeed, settings.hideEasing);
					}, settings.hideAfter);
				}
								
				// attach launcher button handler for showing menu
				$menu
					.hover(function() {
                        
                        // Stop the menu from running over the win-counter on the home page in IE
                        if($.browser.msie && $(".winTicker").length > 0) {
                          var currentZIndex = $(this).css("zIndex");
                          $(this).css("zIndex", currentZIndex+1);
                          $(".winTicker").css("zIndex", currentZIndex-1);
                        }
                    
						// Unset timer on interaction  if hideAfter settings was set
						if(typeof(hideAfterTimer) != 'undefined') {
							clearTimeout(hideAfterTimer);
						}
						// reset normal timer if set
						var timer = $menu.data('timer');
						if(typeof(timer) != 'undefined') {
							clearTimeout(timer);
							$menu.removeData('timer');
						}                        
						// generate content to instant on
						$menu
							.addClass('active')
							.find(settings.menuSelector)
								.slideDown(settings.showSpeed, settings.showEasing)
							.children(settings.levelSelector)
								.animate({opacity: 1}, settings.showSpeed);
					},function() {
						// create timer for delay closing of menu
						var timer = setTimeout(function() {
							$menu
								.removeClass('active')
								.removeData('timer')
								.find(settings.menuSelector)
									.slideUp(settings.hideSpeed, settings.hideEasing);											
						}, settings.hideTimer);
						// store timer in menu private data
						$menu.data('timer', timer);
					}
				);
				 
				$pulldownMenu.find(settings.levelSelector).each(function() {
					
					$menuLink = $(this).children(settings.elementSelector).children('a');
					
					// attach event handlers
					$menuLink
						.hover(function() {
							$(this).parent().addClass('hover');
						},function() {
							$(this).parent().removeClass('hover');
						})
						.click(function() {							
							var $subMenu = $(this).siblings(settings.levelSelector);
							// dont follow link if blocker selector exists or menu has another level 
							if( $(this).filter(settings.blockerSelector).exists() || $subMenu.exists() ) {
								
								// collapse other menus if settings dictate
								if(settings.collapse) {
									var $otherMenu = $(this).parent().siblings().children(settings.levelSelector);
									// if other menus are visible close and make inactive
									if( $otherMenu.exists() && $otherMenu.visible() && !$otherMenu.animated() ) {
										$otherMenu
											.siblings('a')
												.removeClass('active');
										$otherMenu
											.animate({opacity: 0}, {queue: false, speed: settings.hideSpeed} )
											.slideUp({queue: false, speed: settings.showSpeed} , settings.showEasing);
									}
								}
								
								// toggle show hide of menu
								if(!$subMenu.animated() ) {
									if( !$subMenu.visible() ) {
										$(this).addClass('active');
										$subMenu								
											.animate({opacity: 1}, {queue: false, speed: settings.showSpeed} )
											.slideDown({queue: false, speed: settings.showSpeed} , settings.showEasing);
									}
									else {
										$(this).removeClass('active');
										$subMenu
											.animate({opacity: 0}, {queue: false, speed: settings.hideSpeed} )
											.slideUp({queue: false, speed: settings.hideSpeed} , settings.hideEasing);
									}
                                                                        
								}
								return false;			
							}
						}
					);
					
				});
				
			});
			// return this for chaining
			return this;
			
			
		}
	});


	/*	******************************
			PLUGIN - Supplemental Conditionals
			Author: Jack Lukic - KNI (all plugins)
			Notes: Selector shortcuts used to simplify code 
		******************************	*/
	jQuery.fn.extend({
		// test if el is animated
    openTo: function(menuItemId) {    
    
			var settings = {					
			  collapse: true,
			  hideTimer: 500,
			  showSpeed: 500,
			  showEasing: 'easeOutExpo',
			  hideSpeed: 300,
			  hideEasing: 'easeOutQuad',					
			  levelSelector: 'ul',
			  elementSelector: 'li',					
			  menuSelector: '.list',
			  blockerSelector: '.disable',
			  hideAfter: '0'
			};    
 
      var parent = $('#nav_href_'+menuItemId).parent();
      while(parent.length > 0) {      
        /* If we hit the top of the menu then break out
        of the loop. */
        if(parent.attr("class") == "list") {
          break;
        }
        
        /* Change the CSS class for the parent
        elements children (a's) to active. */
        parent.children().removeClass();
        parent.children().addClass('active');
                                   
        /* Hide the subMenu. */
        parent
          .animate({opacity: 1}, {queue: false, speed: settings.showSpeed} )
	  		  .slideDown({queue: false, speed: settings.showSpeed} , settings.showEasing);
        
        /* Move up the menu to the next parent. */
        parent = parent.parent();         
      }     
    },
		animated: function() {
			if(this.filter(':animated').size() > 0) {
				return true;
			}
			else {
				return false;	
			}
		},
		// test if el is visible
		visible: function() {
			if(this.filter(':visible').size() > 0) {
				return true;
			}
			else {
				return false;	
			}
		},
		// test if el exists
		exists: function() {
			if(this.size() > 0) {
				return true;
			}
			else {
				return false;	
			}
		}
	});

})(jQuery);

/*
 * jQuery Nivo Slider v2.1
 * http://nivo.dev7studios.com
 *
 * Copyright 2010, Gilbert Pellegrom
 * Free to use and abuse under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
 * 
 * May 2010 - Pick random effect from specified set of effects by toronegro
 * May 2010 - controlNavThumbsFromRel option added by nerd-sh
 * May 2010 - Do not start nivoRun timer if there is only 1 slide by msielski
 * April 2010 - controlNavThumbs option added by Jamie Thompson (http://jamiethompson.co.uk)
 * March 2010 - manualAdvance option added by HelloPablo (http://hellopablo.co.uk)
 */

(function($) {

	$.fn.nivoSlider = function(options) {

		//Defaults are below
		var settings = $.extend({}, $.fn.nivoSlider.defaults, options);

		return this.each(function() {
			//Useful variables. Play carefully.
			var vars = {
				currentSlide: 0,
				currentImage: '',
				totalSlides: 0,
				randAnim: '',
				running: false,
				paused: false,
				stop:false
			};
		
			//Get this slider
			var slider = $(this);
			slider.data('nivo:vars', vars);
			slider.css('position','relative');
			slider.addClass('nivoSlider');
			
			//Find our slider children
			var kids = slider.children();
			kids.each(function() {
				var child = $(this);
				var link = '';
				if(!child.is('img')){
					if(child.is('a')){
						child.addClass('nivo-imageLink');
						link = child;
					}
					child = child.find('img:first');
				}
				//Get img width & height
                var childWidth = child.width();
                if(childWidth == 0) childWidth = child.attr('width');
                var childHeight = child.height();
                if(childHeight == 0) childHeight = child.attr('height');
                //Resize the slider
                if(childWidth > slider.width()){
                    slider.width(childWidth);
                }
                if(childHeight > slider.height()){
                    slider.height(childHeight);
                }
                if(link != ''){
                    link.css('display','none');
                }
                child.css('display','none');
                vars.totalSlides++;
			});
			
			//Set startSlide
			if(settings.startSlide > 0){
				if(settings.startSlide >= vars.totalSlides) settings.startSlide = vars.totalSlides - 1;
				vars.currentSlide = settings.startSlide;
			}
			
			//Get initial image
			if($(kids[vars.currentSlide]).is('img')){
				vars.currentImage = $(kids[vars.currentSlide]);
			} else {
				vars.currentImage = $(kids[vars.currentSlide]).find('img:first');
			}
			
			//Show initial link
			if($(kids[vars.currentSlide]).is('a')){
				$(kids[vars.currentSlide]).css('display','block');
			}
			
			//Set first background
			slider.css('background','url('+ vars.currentImage.attr('src') +') no-repeat');
			
			//Add initial slices
			for(var i = 0; i < settings.slices; i++){
				var sliceWidth = Math.round(slider.width()/settings.slices);
				if(i == settings.slices-1){
					slider.append(
						$('<div class="nivo-slice"></div>').css({ left:(sliceWidth*i)+'px', width:(slider.width()-(sliceWidth*i))+'px' })
					);
				} else {
					slider.append(
						$('<div class="nivo-slice"></div>').css({ left:(sliceWidth*i)+'px', width:sliceWidth+'px' })
					);
				}
			}
			
			//Create caption
			slider.append(
				$('<div class="nivo-caption"><p></p></div>').css({ display:'none', opacity:settings.captionOpacity })
			);			
			//Process initial  caption
			if(vars.currentImage.attr('title') != ''){
                var title = vars.currentImage.attr('title');
                //if(title.substr(0,1) == '#') title = $(title).html();
                $('.nivo-caption p', slider).html(title);					
				$('.nivo-caption', slider).fadeIn(settings.animSpeed);
			}
			
			//In the words of Super Mario "let's a go!"
			var timer = 0;
			if(!settings.manualAdvance && kids.length > 1){
				timer = setInterval(function(){ nivoRun(slider, kids, settings, false); }, settings.pauseTime);
			}

			//Add Direction nav
			if(settings.directionNav){
				slider.append('<div class="nivo-directionNav"><a class="nivo-prevNav">&nbsp;</a><a class="nivo-nextNav">&nbsp</a></div>');
				
				//Hide Direction nav
				if(settings.directionNavHide){
					$('.nivo-directionNav', slider).hide();
					slider.hover(function(){
						$('.nivo-directionNav', slider).show();
					}, function(){
						$('.nivo-directionNav', slider).hide();
					});
				}
				
				$('a.nivo-prevNav', slider).live('click', function(){
					if(vars.running) return false;
					clearInterval(timer);
					timer = '';
					vars.currentSlide-=2;
					nivoRun(slider, kids, settings, 'prev');
				});
				
				$('a.nivo-nextNav', slider).live('click', function(){
					if(vars.running) return false;
					clearInterval(timer);
					timer = '';
					nivoRun(slider, kids, settings, 'next');
				});
			}
			
			//Add Control nav
			if(settings.controlNav){
				var nivoControl = $('<div class="nivo-controlNav"></div>');
				slider.append(nivoControl);
				for(var i = 0; i < kids.length; i++){
					if(settings.controlNavThumbs){
						var child = kids.eq(i);
						if(!child.is('img')){
							child = child.find('img:first');
						}
                        if (settings.controlNavThumbsFromRel) {
                            nivoControl.append('<a class="nivo-control" rel="'+ i +'"><img src="'+ child.attr('rel') + '" alt="" /></a>');
                        } else {
                            nivoControl.append('<a class="nivo-control" rel="'+ i +'"><img src="'+ child.attr('src').replace(settings.controlNavThumbsSearch, settings.controlNavThumbsReplace) +'" alt="" /></a>');
                        }
					} else {
						nivoControl.append('<a class="nivo-control" rel="'+ i +'">'+ (i + 1) +'</a>');
					}
					
				}
				//Set initial active link
				$('.nivo-controlNav a:eq('+ vars.currentSlide +')', slider).addClass('active');
				
				$('.nivo-controlNav a', slider).live('click', function(){
					if(vars.running) return false;
					if($(this).hasClass('active')) return false;
					clearInterval(timer);
					timer = '';
					slider.css('background','url('+ vars.currentImage.attr('src') +') no-repeat');
					vars.currentSlide = $(this).attr('rel') - 1;
					nivoRun(slider, kids, settings, 'control');
				});
			}
			
			//Keyboard Navigation
			if(settings.keyboardNav){
				$(window).keypress(function(event){
					//Left
					if(event.keyCode == '37'){
						if(vars.running) return false;
						clearInterval(timer);
						timer = '';
						vars.currentSlide-=2;
						nivoRun(slider, kids, settings, 'prev');
					}
					//Right
					if(event.keyCode == '39'){
						if(vars.running) return false;
						clearInterval(timer);
						timer = '';
						nivoRun(slider, kids, settings, 'next');
					}
				});
			}
			
			//For pauseOnHover setting
			if(settings.pauseOnHover){
				slider.hover(function(){
					vars.paused = true;
					clearInterval(timer);
					timer = '';
				}, function(){
					vars.paused = false;
					//Restart the timer
					if(timer == '' && !settings.manualAdvance){
						timer = setInterval(function(){ nivoRun(slider, kids, settings, false); }, settings.pauseTime);
					}
				});
			}
			
			//Event when Animation finishes
			slider.bind('nivo:animFinished', function(){ 
				vars.running = false; 
				//Hide child links
				$(kids).each(function(){
					if($(this).is('a')){
						$(this).css('display','none');
					}
				});
				//Show current link
				if($(kids[vars.currentSlide]).is('a')){
					$(kids[vars.currentSlide]).css('display','block');
				}
				//Restart the timer
				if(timer == '' && !vars.paused && !settings.manualAdvance){
					timer = setInterval(function(){ nivoRun(slider, kids, settings, false); }, settings.pauseTime);
				}
				//Trigger the afterChange callback
				settings.afterChange.call(this);
			});
		});
		
		function nivoRun(slider, kids, settings, nudge){
			//Get our vars
			var vars = slider.data('nivo:vars');
			if((!vars || vars.stop) && !nudge) return false;
			
			//Trigger the beforeChange callback
			settings.beforeChange.call(this);
					
			//Set current background before change
			if(!nudge){
				slider.css('background','url('+ vars.currentImage.attr('src') +') no-repeat');
			} else {
				if(nudge == 'prev'){
					slider.css('background','url('+ vars.currentImage.attr('src') +') no-repeat');
				}
				if(nudge == 'next'){
					slider.css('background','url('+ vars.currentImage.attr('src') +') no-repeat');
				}
			}
			vars.currentSlide++;
			if(vars.currentSlide == vars.totalSlides){ 
				vars.currentSlide = 0;
				//Trigger the slideshowEnd callback
				settings.slideshowEnd.call(this);
			}
			if(vars.currentSlide < 0) vars.currentSlide = (vars.totalSlides - 1);
			//Set vars.currentImage
			if($(kids[vars.currentSlide]).is('img')){
				vars.currentImage = $(kids[vars.currentSlide]);
			} else {
				vars.currentImage = $(kids[vars.currentSlide]).find('img:first');
			}
			
			//Set acitve links
			if(settings.controlNav){
				$('.nivo-controlNav a', slider).removeClass('active');
				$('.nivo-controlNav a:eq('+ vars.currentSlide +')', slider).addClass('active');
			}
			
			//Process caption
			if(vars.currentImage.attr('title') != ''){
                var title = vars.currentImage.attr('title');
                if(title.substr(0,1) == '#') title = $(title).html();	
                    
				if($('.nivo-caption', slider).css('display') == 'block'){
					$('.nivo-caption p', slider).fadeOut(settings.animSpeed, function(){
						$(this).html(title);
						$(this).fadeIn(settings.animSpeed);
					});
				} else {
					$('.nivo-caption p', slider).html(title);
				}					
				$('.nivo-caption', slider).fadeIn(settings.animSpeed);
			} else {
				$('.nivo-caption', slider).fadeOut(settings.animSpeed);
			}
			
			//Set new slice backgrounds
			var  i = 0;
			$('.nivo-slice', slider).each(function(){
				var sliceWidth = Math.round(slider.width()/settings.slices);
				$(this).css({ height:'0px', opacity:'0', 
					background: 'url('+ vars.currentImage.attr('src') +') no-repeat -'+ ((sliceWidth + (i * sliceWidth)) - sliceWidth) +'px 0%' });
				i++;
			});
			
			if(settings.effect == 'random'){
				var anims = new Array("sliceDownRight","sliceDownLeft","sliceUpRight","sliceUpLeft","sliceUpDown","sliceUpDownLeft","fold","fade");
				vars.randAnim = anims[Math.floor(Math.random()*(anims.length + 1))];
				if(vars.randAnim == undefined) vars.randAnim = 'fade';
			}
            
            //Run random effect from specified set (eg: effect:'fold,fade')
            if(settings.effect.indexOf(',') != -1){
                var anims = settings.effect.split(',');
                vars.randAnim = $.trim(anims[Math.floor(Math.random()*anims.length)]);
            }
		
			//Run effects
			vars.running = true;
			if(settings.effect == 'sliceDown' || settings.effect == 'sliceDownRight' || vars.randAnim == 'sliceDownRight' ||
				settings.effect == 'sliceDownLeft' || vars.randAnim == 'sliceDownLeft'){
				var timeBuff = 0;
				var i = 0;
				var slices = $('.nivo-slice', slider);
				if(settings.effect == 'sliceDownLeft' || vars.randAnim == 'sliceDownLeft') slices = $('.nivo-slice', slider)._reverse();
				slices.each(function(){
					var slice = $(this);
					slice.css('top','0px');
					if(i == settings.slices-1){
						setTimeout(function(){
							slice.animate({ height:'100%', opacity:'1.0' }, settings.animSpeed, '', function(){ slider.trigger('nivo:animFinished'); });
						}, (100 + timeBuff));
					} else {
						setTimeout(function(){
							slice.animate({ height:'100%', opacity:'1.0' }, settings.animSpeed);
						}, (100 + timeBuff));
					}
					timeBuff += 50;
					i++;
				});
			} 
			else if(settings.effect == 'sliceUp' || settings.effect == 'sliceUpRight' || vars.randAnim == 'sliceUpRight' ||
					settings.effect == 'sliceUpLeft' || vars.randAnim == 'sliceUpLeft'){
				var timeBuff = 0;
				var i = 0;
				var slices = $('.nivo-slice', slider);
				if(settings.effect == 'sliceUpLeft' || vars.randAnim == 'sliceUpLeft') slices = $('.nivo-slice', slider)._reverse();
				slices.each(function(){
					var slice = $(this);
					slice.css('bottom','0px');
					if(i == settings.slices-1){
						setTimeout(function(){
							slice.animate({ height:'100%', opacity:'1.0' }, settings.animSpeed, '', function(){ slider.trigger('nivo:animFinished'); });
						}, (100 + timeBuff));
					} else {
						setTimeout(function(){
							slice.animate({ height:'100%', opacity:'1.0' }, settings.animSpeed);
						}, (100 + timeBuff));
					}
					timeBuff += 50;
					i++;
				});
			} 
			else if(settings.effect == 'sliceUpDown' || settings.effect == 'sliceUpDownRight' || vars.randAnim == 'sliceUpDown' || 
					settings.effect == 'sliceUpDownLeft' || vars.randAnim == 'sliceUpDownLeft'){
				var timeBuff = 0;
				var i = 0;
				var v = 0;
				var slices = $('.nivo-slice', slider);
				if(settings.effect == 'sliceUpDownLeft' || vars.randAnim == 'sliceUpDownLeft') slices = $('.nivo-slice', slider)._reverse();
				slices.each(function(){
					var slice = $(this);
					if(i == 0){
						slice.css('top','0px');
						i++;
					} else {
						slice.css('bottom','0px');
						i = 0;
					}
					
					if(v == settings.slices-1){
						setTimeout(function(){
							slice.animate({ height:'100%', opacity:'1.0' }, settings.animSpeed, '', function(){ slider.trigger('nivo:animFinished'); });
						}, (100 + timeBuff));
					} else {
						setTimeout(function(){
							slice.animate({ height:'100%', opacity:'1.0' }, settings.animSpeed);
						}, (100 + timeBuff));
					}
					timeBuff += 50;
					v++;
				});
			} 
			else if(settings.effect == 'fold' || vars.randAnim == 'fold'){
				var timeBuff = 0;
				var i = 0;
				$('.nivo-slice', slider).each(function(){
					var slice = $(this);
					var origWidth = slice.width();
					slice.css({ top:'0px', height:'100%', width:'0px' });
					if(i == settings.slices-1){
						setTimeout(function(){
							slice.animate({ width:origWidth, opacity:'1.0' }, settings.animSpeed, '', function(){ slider.trigger('nivo:animFinished'); });
						}, (100 + timeBuff));
					} else {
						setTimeout(function(){
							slice.animate({ width:origWidth, opacity:'1.0' }, settings.animSpeed);
						}, (100 + timeBuff));
					}
					timeBuff += 50;
					i++;
				});
			}  
			else if(settings.effect == 'fade' || vars.randAnim == 'fade'){
				var i = 0;
				$('.nivo-slice', slider).each(function(){
					$(this).css('height','100%');
					if(i == settings.slices-1){
						$(this).animate({ opacity:'1.0' }, (settings.animSpeed*2), '', function(){ slider.trigger('nivo:animFinished'); });
					} else {
						$(this).animate({ opacity:'1.0' }, (settings.animSpeed*2));
					}
					i++;
				});
			}
		}
	};
	
	//Default settings
	$.fn.nivoSlider.defaults = {
		effect:'random',
		slices:15,
		animSpeed:500,
		pauseTime:3000,
		startSlide:0,
		directionNav:true,
		directionNavHide:true,
		controlNav:true,
		controlNavThumbs:false,
        controlNavThumbsFromRel:false,
		controlNavThumbsSearch:'.jpg',
		controlNavThumbsReplace:'_thumb.jpg',
		keyboardNav:true,
		pauseOnHover:true,
		manualAdvance:false,
		captionOpacity:0.8,
		beforeChange: function(){},
		afterChange: function(){},
		slideshowEnd: function(){}
	};
	
	$.fn._reverse = [].reverse;
	
})(jQuery);

jQuery.logThis = function( text ){
    if( (window['console'] !== undefined) ){
        console.log( text );
    }
};
