/* Cannondale custom magento JS */
var $j = jQuery.noConflict(); //MUST DECLARE THIS... to work with prototype 

/*
//==================================================================================
   PAGE LOAD CODE UP HEEEERRREEE
//==================================================================================

  Object: CD
  Object literal to hold code
  
  HOW IT WORKS:  
    Javascript that should run on every page will go under the 'common' object literal
    
    Common has 2 parts-
        init  :  put all code that effects the visuals here.  This runs first
        finalize:  put all code that needs to get run, but does not effect how the page looks here, it will run second. Low priority stuff.
        
    Page specific javascript goes under the body class.
    For example:  Mens apparel has the classes 'catalog-category-view categorypath-apparel-mens category-mens'
    If your code runs on all shopping pages, put it under 'catalog-category-view'  if it just runs on men's apparel, then put it
    under 'categorypath-apparel-mens'
    
    Each body class will work like common with init and finalize functions
        FOO = {
          common : {
            init     : function(){ ... },
            finalize : function(){ ... }
          },
          shopping : {
            init     : function(){ ... },
            cart     : function(){ ... },
            category : function(){ ... }  //category is a body ID  It will run the common code for shopping and it's specific code for that page
          }
        }
    
    Page firing is triggered by the UTIL function at the bottom of the page.
    
    WHY DO THIS? It helps page load and performance to only have relevant code running on the pages it's needed on. :) Also it makes things
    easy to find!
    
*/

var CD;
window.CD = {
  //config is a good place to store commonly used configuration objects
  config : {
    menuDialog : {
    			height: 424,
    			width: 1050,
    			draggable: false,
    			resizable: false,
    			position: [156,117],
    			modal: true
    		},
    bikeDialog : {
          		height: 700,
    			width: 1050,
    			draggable: false,
    			resizable: false,
    			position: [156,117],
    			modal: true
    		},
    supportDialog : {
          		height: 350,
    			width: 1033,
    			draggable: false,
    			resizable: false,
    			position: [156,117],
    			modal: true
    		}    		 		
  },

  common : {
    init     : function(){
      WD.countrySwitcher(); // initialize country switcher
      WD.globalSearchHandler(); // initialize search handler

      $j('#navigation-overlay:ui-dialog').dialog("destroy");
	  currentAjaxRequest = null;
      $j('.ui-widget-overlay, .ui-dialog-titlebar-close, .navLink').live("click", function() {
        $j('#navigation-overlay:ui-dialog').dialog("close");
        $j( ".navItem" ).addClass("linkChange");
        $j( ".navItem" ).removeClass("temporary-link");
        $j('.ui-widget-overlay').remove();
        if($j(document.body).hasClass('cms-home-main')) {
          WD.backgroundCarousel.delayTransition();
        }
        if (currentAjaxRequest) currentAjaxRequest.abort();
      });
      
      $j('.overlayMenu').live("click",function(e){
        e.preventDefault();
        if($j(document.body).hasClass('cms-home-main')) {
          WD.backgroundCarousel.pauseTransition();
        }
        //hello ghetto
       $j('.ui-dialog').addClass('wait');
       $j('#navigation-overlay').html('');
       var altURL = $j(this).attr('id');
       var getURL;
       if (altURL){
          getURL = $j('#' + altURL + ' a').attr("href");
       } else {
           getURL = $j(this).find('a').attr("href"); // Product category page
       }
       // var getURL = $j(this).find('a').attr('href');
        var customID = $j(this).attr('id')+'-menu';
        var actualID = "#" + $j(this).attr('id');
        var width = $j(window).width();
        var height = $j(window).height();
        var supportBoo = $j(this).attr('id') =="supportDialog"; 
        if (getURL =="#"){
            $j( ".navItem" ).removeClass("linkChange");
            $j( actualID ).addClass("temporary-link");
            var categoryContent = $j(this).find('ul').clone();
            if ($j('.ui-widget-overlay').length == 0) $j('<div class="ui-widget-overlay" style="z-index: 1001;"></div>').appendTo('#container');
            $j('#navigation-overlay').html(categoryContent).dialog(supportBoo?CD.config.supportDialog:CD.config.menuDialog).dialog('open').addClass('menuCategories').find('.overlay').attr('id', customID);
            $j('.ui-dialog').removeClass('wait');
        }else{
          currentAjaxRequest = $j.ajax({
            url: getURL,
            success: function(data) {    
              if ($j('.ui-widget-overlay').length == 0) $j('<div class="ui-widget-overlay" style="z-index: 1001;"></div>').appendTo('#container');
              $j('.ui-dialog').removeClass('wait');
              $j('#navigation-overlay').html(data).dialog(CD.config.bikeDialog).dialog('open').addClass('menuCategories').find('.overlay').attr('id', customID);
              $j('#category-tab-contents').tabs({ panelTemplate: '<section></section>' });

            }
          });                   
        }
      });
      
		//	Functionality for Breadcrumb Triggers
		//	This opens the overlay menu for breadcrumb items that do not have a page. 
		$j( ".breadcrumbs .support" ).click( function( event ) {
			event.preventDefault();
			$j( "#supportDialog" ).trigger( "click" );
		});	
		
		$j( ".breadcrumbs .apparel-breadcrumb" ).click( function( event ) {
			event.preventDefault();
			$j( "#Apparel" ).trigger( "click" );
		});
		
		$j( ".breadcrumbs .bikes-breadcrumb" ).click( function( event ) {
			event.preventDefault();
			$j( "#Bikes" ).trigger( "click" );
		});
		
		$j( ".breadcrumbs .road-breadcrumb" ).click( function( event ) {
			event.preventDefault();
			$j(".bikes-menu-road a").trigger( "click" );
			$j('.ui-dialog').addClass('wait');
       		$j('#navigation-overlay').html('');
		});
		
		$j( ".breadcrumbs .mountain-breadcrumb" ).click( function( event ) {
			event.preventDefault();
			$j(".bikes-menu-mountain a").trigger( "click" );
			$j('.ui-dialog').addClass('wait');
       		$j('#navigation-overlay').html('');
		});
		
		$j( ".breadcrumbs .urban-breadcrumb" ).click( function( event ) {
			event.preventDefault();
			$j(".bikes-menu-recreation a").trigger( "click" );
			$j('.ui-dialog').addClass('wait');
       		$j('#navigation-overlay').html('');
		});
		
		$j( ".bike-link .breadcrumbs .womens-breadcrumb" ).click( function( event ) {
			event.preventDefault();
			$j(".bikes-menu-womens a").trigger( "click" );
			$j('.ui-dialog').addClass('wait');
       		$j('#navigation-overlay').html('');
		});// End breadcrumb triggers
		
      $j('#icon-twitter').mouseover(function() { WD.twitterModule(); });
      
		$j(window).scroll( function() {
			var x = $j(window).scrollLeft();
			if (x != 0 ) $j( "#footer" ).css( 'left', -x );
			else $j( "#footer" ).css( 'left', 0 );
		});
		
		
    },
    finalize : function(){ 
      }
  }, //end CD.common
  'cms-home' : {
    init : function() {
      WD.twitterModule();
      WD.backgroundCarousel.init(
        {
          'widgetMode':'home',
          'slideTimeout' : 4000
        }
      );
    }
  },
  'cms-home-main' : {
    init : function() {
      WD.twitterModule();
      WD.backgroundCarousel.init(
        {
          'widgetMode':'home',
          'slideTimeout' : 4000
        }
      );
    }
  },
  'cms-page-view': {
    init : function() {
      $j('.country-select').customStyle();
    }
  },
  'bio' : {
    init : function() {
      $j('a.filter').bind('click', function(){
        $j(this).parent('.bio_category_filter').find('.filter').toggleClass('expanded').end().find('ul').toggle('slow');

      });
    var $container = $j('#tileContainer');
    
    $container.masonry({
      itemSelector: '.tile',
      columnWidth: 5,
      isAnimated: !Modernizr.csstransitions
    });    
  	
  	// Gets the height of the padding since this could change at times. 30 is the height of the footer.
	var paddingHeight = parseInt($j('.innovation-post-view #main-content, .bio-post-view #main-content').css("padding-top").replace("px", "")) + parseInt($j('.innovation-post-view #main-content, .bio-post-view #main-content').css("padding-bottom").replace("px", "")) + 30;
	
	// The number is the height total of padding (padding-top + padding-bottom).
	var contentHeight = $j('.innovation-post-view #main-content, .bio-post-view #main-content').height() + paddingHeight;	
		if ( contentHeight < $j('html').height() ) {
		$j('.innovation-post-view #main-content, .bio-post-view #main-content').height($j('html').height() - paddingHeight + "px");
		$j(window).resize( function() {
			if ( contentHeight < $j('html').height() ) {
				$j('.innovation-post-view #main-content, .bio-post-view #main-content').height($j('html').height() - paddingHeight + "px");
			}
		});
	}
  }
  },
  'registerbike-index-index': {
    init : function() {
      $j('.regContent').find('select').customStyle();
      $j('#newsletter').button();
    }    
  },
  'news': {
    init : function() {
      $j('.filterBy').customStyle();
      $j('.filterBy').change(function(){
        window.location = $j(this).find('option:selected').attr('url');
      });
      WD.dotPagination({
        containerID : "#newsSection",
        page: ".page",
        pagination: ".pagination"
      });
    }
  },
  'catalog-category-view' : {
    init : function() {
      var config = {
        widgetMode : 'click',
        showSkip : true,
        showBigNav : true,
        showNextSlideAmt : 150
      };
      if ($j('#background-widget').length){ //only if there are images to display (they're set in the description field on the category)
        WD.backgroundCarousel.init(config);
        WD.backgroundCarousel.setFinalSlideContent('#category-content');
        }
      }
    },
    'catalog-product-view' : {
      init : function() {
        WD.productHandler.init();
      }
    },
    "compare-index-index":{
      init: function(){
       $j(".dropdown").selectmenu();
       $j('b.close').bind('click', function(){$j(this).parents('.specs').addClass("hidden");});
        
      }      
    },
    "apparelPage": {
      init: function(){
        $j('#filterBy, .dropdown, .addToCart select').customStyle();
        $j('#filterBy').change(function(){
          window.location = $j(this).find('option:selected').attr('url');
        });
        WD.simpleTabs();
      
     	// Used to resize the apparel product and grid pages to fit the height of the screen.
		// Gets the height of the padding since this could change at times. 30 is the height of the footer.
		var paddingHeight = parseInt($j('.apparelGrid .apparel, .apparelProduct #main-content').css("padding-top").replace("px", "")) + parseInt($j('.apparelGrid .apparel, .apparelProduct #main-content').css("padding-bottom").replace("px", "")) + 30;
		
		// The number is the height total of padding (padding-top + padding-bottom).
		var apparelGridHeight = $j('.apparelGrid .apparel, .apparelProduct #main-content').height() + paddingHeight;	
			if ( apparelGridHeight < $j('html').height() ) {
			$j('.apparelGrid .apparel, .apparelProduct #main-content').height($j('html').height() - paddingHeight + "px");
			$j(window).resize( function() {
				if ( apparelGridHeight < $j('html').height() ) {
					$j('.apparelGrid .apparel, .apparelProduct #main-content').height($j('html').height() - paddingHeight + "px");
				}
			});
		}	// Ends the height resizing code.
      }
    },

    "apparelProduct": {
    	init: function() {
    		var theseOptions = {
    			zoomType: 'reverse',//Values: standard, reverse
	            zoomWidth: 375,
	            zoomHeight: 350,
	            xOffset: 0,
	            yOffset: 0,
	            imageOpacity: 0.6,
	            title : false
    		};
    		
    		$j(".more-views a").click( function( event ) {
    			event.preventDefault();

    			$j(".more-views a").removeClass("selectedImage");
    			$j(this).addClass("selectedImage");
    			
    			var mainImageUrl = $j(this).children("img").attr("rel");    			
    			var fullSizeUrl = $j(this).attr("href");
    			
    			$j("#main-image img").attr("src", mainImageUrl);
    			$j("#main-image").attr("href", fullSizeUrl);
    			$j("#main-image").unbind();
    			$j("#main-image").jqzoom(theseOptions);
    		});	
    	}
    },
    // Used to resize the contacts pages to fit the height of the screen.
    "contacts-index-index": {
    	init: function() {
    		// Gets the height of the padding since this could change at times. 30 is the height of the footer.
    		var paddingHeight = parseInt($j('.contacts-index-index #main-content').css("padding-top").replace("px", "")) + parseInt($j('.contacts-index-index #main-content').css("padding-bottom").replace("px", "")) + 30;
    		
    		// The number is the height total of padding (padding-top + padding-bottom).
    		var contactsContentHeight = $j('.contacts-index-index #main-content').height() + paddingHeight;	
    			if ( contactsContentHeight < $j('html').height() ) {
    			$j('.contacts-index-index #main-content').height($j('html').height() - paddingHeight + "px");
    			$j(window).resize( function() {
    				if ( contactsContentHeight < $j('html').height() ) {
    					$j('.contacts-index-index #main-content').height($j('html').height() - paddingHeight + "px");
    				}
    			});
    		}	
    	}
    },
    
    // Used to resize the news post pages to fit the height of the screen.
    "news-newspost": {
    	init: function() {
    		// Gets the height of the padding since this could change at times. 30 is the height of the footer.
			var paddingHeight = parseInt($j('.news-newspost #main-content').css("padding-top").replace("px", "")) + parseInt($j('.news-newspost #main-content').css("padding-bottom").replace("px", "")) + 30;
			
			// The number is the height total of padding (padding-top + padding-bottom).
			var contentHeight = $j('.news-newspost #main-content').height() + paddingHeight;	
				if ( contentHeight < $j('html').height() ) {
				$j('.news-newspost #main-content').height($j('html').height() - paddingHeight + "px");
				$j(window).resize( function() {
					if ( contentHeight < $j('html').height() ) {
						$j('.news-newspost #main-content').height($j('html').height() - paddingHeight + "px");
					}
				});
			}	
    	}
    },
    
    "catalogsearch-result-index": {
   		init: function() {
    		// Gets the height of the padding since this could change at times. 30 is the height of the footer.
			var paddingHeight = parseInt($j('.catalogsearch-result-index #main-content').css("padding-top").replace("px", "")) + parseInt($j('.catalogsearch-result-index #main-content').css("padding-bottom").replace("px", "")) + 30;
			
			// The number is the height total of padding (padding-top + padding-bottom).
			var contentHeight = $j('.catalogsearch-result-index #main-content').height() + paddingHeight;	
				if ( contentHeight < $j('html').height() ) {
				$j('.catalogsearch-result-index #main-content').height($j('html').height() - paddingHeight + "px");
				$j(window).resize( function() {
					if ( contentHeight < $j('html').height() ) {
						$j('.catalogsearch-result-index #main-content').height($j('html').height() - paddingHeight + "px");
					}
				});
			}	
    	} 
    },
    
    'archive':{
      init: function(){
        $j('#archiveYear, #archiveCategory, #archiveSubCategory').selectmenu();
      }
    },
    'cms-manuals': {
      init: function(){
        $j('.filterBy').customStyle();
        $j('#manuals').change(function(){
          var filterType = $j(this).find('option:selected').attr('value');
          $j(".manualWrap:visible").addClass('hidden');
          $j("#"+filterType).removeClass('hidden');
        });
      }      
    },
    'cms-dealer-locator' : {
      init : function() {
        $j(window).resize(WD.resizeMapObjects);
        $j(document).ready(WD.resizeMapObjects);
        
        
        $j("select").customStyle();
      }
    }//end apparelPage

  

}  // end window.CD





//==================================================================================
//  WIDGETS!!!!
//  put all your super awesome regular code below
//==================================================================================

WD = {

  dotPagination: function(options){
    var containerID = options.containerID,
        page = options.page,
        paginationContainer = options.pagination,
        pageIndex = $j(containerID).find(options.page).length,
        paginationDots ="";
        
        for (i=0; i<pageIndex; i++){
          paginationDots += "<li class='dot pageItem'>&bull;</li>";
        }
        
        $j(options.page).not(":first").addClass('hidden');
        $j(containerID).find(paginationContainer).append('<ul class="paginationList clearfix">'+paginationDots+'</ul>');
        
        $j('.dot').live ('click', function(){ 
          var getIndex = $j('.dot').index(this);
          $j('.dot.selected').removeClass('selected');
          $j(this).addClass('selected');
          $j('.page:visible').addClass('hidden');
          $j('.page:eq('+getIndex+')').removeClass('hidden');
        });

  }, //end WD.dotPagination();
  simpleTabs: function(){
      //tabs for the accordion. Not using jQuery UI, too much overkill            
      $j('.tabs a').live('click', function(event){ 

          event.preventDefault();
          var tabContent = $j(this).attr('href');

          $j(this).parents('.tabs').find('li.selected').removeClass('selected');
          $j(this).parents('li').addClass('selected');            

          $j(this).parents('.tabContainer').find('.tabContent').not('.hidden').addClass('hidden').hide();
          $j(tabContent).removeClass('hidden').show();   
      });

  }, //end WD.simpleTabs
  globalSearchHandler : function() {
    var searchForm      = '#site-search',
        searchFormText  = '#search',
        searchSubmit    = '#site-search-submit';
    $j(searchForm).mouseenter(
      function() {
        $j(this).animate({ 'width' : 110 + 'px'}, 500, function(){
          $j(searchFormText).focus();
          $j(searchSubmit).click(function(event) { 
          	event.preventDefault();
          	$j(searchFormText).focus(); 
          	if( $j( searchFormText ).val() != "" ) $j(searchForm).submit(); 
          });
        });
      }
    );
    
   $j(searchForm).mouseleave(function() {
   	$j(searchFormText).blur();
  	if( !$j( searchFormText ).val() ) $j(this).animate({ 'width' : 28 + 'px'}, 500);
   }); 
  },
  resizeMapObjects : function() {
    var caWidth = $j('#main-content').width(),
        caHeight = $j('#main-content').height(),
        footerHeight = $j('#footer').height();
    caHeight = caHeight - footerHeight;
    $j('#map').height(caHeight);
    $j('#map').width((caWidth-$j('.locator #sidebar').width())-68);
    $j('#sidebar').height(caHeight-$j('#storelocator-header').height()-$j('#footer').height()-12);
  },
  twitterModule : function(){
    var timeout = setTimeout(function() {
      $j('.tweeter').css({'display':'none'});
    }, 3000);
    $j('.tweeter').css({'display':'block'});
    $j('.tweeter').mouseover(function() {
    clearTimeout(timeout);
    $j(this).mouseleave(function() {
      $j(this).css({'display':'none'});
    });
    return false;
    });
  },
  backgroundCarousel : (function() {
    var slides = [],
    parentContainer = '#main-content',
    slidesContainer = '#background-widget > ul',
    slideItems = '#background-widget > ul > li',
    slideNav = '#bg-widget-nav',
    slideNavItems = '#bg-widget-nav > li',
    finalSlideClass = 'finalSlide',
    activeClass = 'active',
    slideCount = -1,
    currSlide = 0,
    nextSlide = 1,
    overlayOpen = false,
    slideOffset = 0,
    slideSpeed = 1000,
    slideTimeout = 5000,
    slideTransition = null,
    widgetMode = 'auto', // other options will be 'click' and ... ?
    showSkip = false, // true/false for skip button in slideNav
    showBigNav = false,
    showNextSlide = false, // show peek of next slide in view
    showNextSlideAmt = 0,
    footerHeight = 0; // this is to offset the height of the footer -- probably don't need this in a variable...

    var _self = {
      config : function(config) {
        activeClass = config.activeClass || activeClass;
        finalSlideClass = config.finalSlideClass || finalSlideClass;
        showSkip = config.showSkip || showSkip;
        showBigNav = config.showBigNav || showBigNav;
        parentContainer = config.parentContainer || parentContainer;
        slidesContainer = config.slidesContainer || slidesContainer;
        slideItems = config.slideItems || slideItems;
        slideNav = config.slideNav || slideNav;
        slideNavItems = config.slideNavItems || slideNavItems;
        slideTimeout = config.slideTimeout || slideTimeout;
        showNextSlide = config.showNextSlide || showNextSlide;
        showNextSlideAmt = config.showNextSlideAmt || showNextSlideAmt;
        widgetMode = config.widgetMode || widgetMode;
      },
      init: function(config) {
        if( config ) {_self.config(config); }

        _self.setImgSize();
        slideCount = $j(slideItems).length;

        $j(slideItems).each(function(i) {
          slides.push(this);
          $j(this)
          .css({ 'position' : 'absolute', 'top' : 0, 'left' : - showNextSlideAmt + 'px', 'z-index' : ( slideCount - i ) })
          .animate({'left' : (( slideOffset * i ) - showNextSlideAmt) + 'px' }, slideSpeed);
        });

        $j(window).resize(function() {
          _self.setImgSize();
          _self.setNavPosition();
        });

        $j(slideNavItems).live('click',_self.slideNavClick);
        if(showBigNav) {
          _self.initBigNav();
          _self.positionLargeNav();
        }

        footerHeight = $j('#footer').height();
        _self.initSlideNav();


        switch(widgetMode) {
          //case 'home' : _self.delayTransition(); break; // don't need this unless more initialization than default behavior is needed.
          case 'click' : break;
          default : _self.delayTransition(); break;
        }
      },
      initBigNav : function() {
        var bigNavLinkLeft = document.createElement('a'),
        bigNavLinkRight = document.createElement('a');

        bigNavLinkLeft.className = 'bigNavLink';
        bigNavLinkLeft.href = 'javascript:void(0);';
        bigNavLinkLeft.id = 'large-nav-prev';
        bigNavLinkRight.className = 'bigNavLink';
        bigNavLinkRight.href = 'javascript:void(0);';
        bigNavLinkRight.id = 'large-nav-next';

        $j(parentContainer).append(bigNavLinkLeft);
        $j(parentContainer).append(bigNavLinkRight);

        $j('#large-nav-prev,#large-nav-next').live('click',_self.largeNavListener);
      },
      initSlideNav : function() {
        var navItem = null,
        navLink = null;

        $j(slides).each(function(i) {
          navItem = document.createElement('li');
          navLink = document.createElement('a');
          navLink.setAttribute('href','javascript:void(0);');
          if(i == currSlide) {
            navItem.className = activeClass;
          }
          navItem.appendChild(navLink);
          $j(slideNav).append(navItem);
        });

        if(showSkip) {
          navItem = document.createElement('li');
          navLink = document.createElement('a');
          navLink.setAttribute('href','javascript:void(0);');
          navLink.innerHTML = 'Skip &rarr;';
          navItem.className = 'skip';
          navItem.appendChild(navLink);
          $j(slideNav).append(navItem);
        }

        _self.setNavPosition();
      },
      arrangeSlides : function() {
        $j(slides).each(function(i){
          if(showNextSlideAmt == 0) {
            if(i != currSlide) {
              $j(this).css({ 'left' : ( slideOffset ) + 'px' });
            }
          } else {
            $j(this).css({ 'left' : (( slideOffset * i ) - showNextSlideAmt)  + 'px' });
            $j(slidesContainer).css({ 'left' : - (nextSlide * slideOffset) + ( $j(slides[currSlide]).hasClass(finalSlideClass) ? showNextSlideAmt : 0 ) + 'px' });
          }
        });
      },
      clickNext : function() {
        $j(slides[currSlide])
        .css({ 'display' : 'block' })
        .animate(
          { 'left' : '-' + ( slideOffset + showNextSlideAmt ) + 'px'},
          slideSpeed
        );
        $j(slides[nextSlide])
        .css({ 'display' : 'block', 'left' : (slideOffset - showNextSlideAmt) + 'px' })
        .animate(
          {'left' : (0 - showNextSlideAmt) + 'px' },
          slideSpeed
        );
      },
      clickPrev : function() {
        $j(slides[currSlide])
        .css({ 'display' : 'block' })
        .animate(
          { 'left' : ( slideOffset - showNextSlideAmt ) + 'px'},
          slideSpeed
        );
        $j(slides[nextSlide])
        .css({ 'display' : 'block', 'left' : - (slideOffset) + 'px' })
        .animate(
          {'left' : ( 0 - showNextSlideAmt ) + 'px' },
          slideSpeed
        );
      },
      delayTransition : function() {
        overlayOpen = false;
        slideTransition = setTimeout(_self.loop,slideTimeout);
      },
      pauseTransition : function() {
        overlayOpen = true;
        clearTimeout(slideTransition);
      },
      loop : function() {
        $j(slideNavItems + ':nth-child(' + (currSlide + 1) +')').removeClass(activeClass);
        $j(slideNavItems + ':nth-child(' + (nextSlide + 1) +')').addClass(activeClass);

        $j(slides[currSlide])
        .css({ 'display' : 'block' })
        .animate(
          { 'left' : '-' + slideOffset + 'px'},
          slideSpeed,
          _self.slideComplete
        );
        $j(slides[nextSlide])
        .css({ 'display' : 'block', 'left' : slideOffset + 'px' })
        .animate(
          {'left' : '0'},
          slideSpeed
        );
      },
      largeNavListener : function() {
        switch(this.id) {
          case 'large-nav-prev' :
            if(currSlide > 0) {
              _self.slideTo(currSlide-1);
              nextSlide = currSlide - 1;
              currSlide--;
            }
          break;
          case 'large-nav-next' :
            if(currSlide < slideCount - 1 ) {
              _self.slideTo(currSlide+1);
              nextSlide = currSlide + 1;
              currSlide++;
            }
          break;
        }
        _self.setActiveNav();
      },
      positionLargeNav : function() {
        $j('#large-nav-prev,#large-nav-next').css('top', ($j(parentContainer).height()/2)-$j('#large-nav-prev').height()+'px');
      },
      setActiveNav : function(click) {
        $j(slideNavItems).each(function() {
          if($j(this).hasClass(activeClass)) {
            $j(this).removeClass(activeClass);
          }
        });
        if(click) {
          $j(click).addClass(activeClass);
        } else {
          $j(slideNavItems + ':nth-child(' + (nextSlide + 1) +')').addClass(activeClass);
        }
      },
      setImgSize : function() {
        slideOffset = $j(parentContainer).width();
        $j(slideItems).css({ 'width' : slideOffset + 'px', 'height' : ( $j(parentContainer).height() - footerHeight) + 'px' });
        $j(slideItems + ' > img').css({ 'width' : slideOffset + 'px' });
        if(showBigNav) { _self.positionLargeNav(); }
        _self.arrangeSlides();
      },
      setFinalSlideContent : function(content) {
        var c = $j(content).html();
        $j('.'+finalSlideClass).html(c);
      },
      setNavPosition : function() {
        $j(slideNav).css({ 'left' : ((slideOffset/2) - $j(slideNav).width()) + 'px' });
      },
      slideComplete : function() {
        $j(this).css({ 'display' : 'none' });

        currSlide = currSlide >= nextSlide ? nextSlide : currSlide + 1;
        nextSlide = nextSlide + 1 == slideCount ? 0 : currSlide + 1;

        if(!overlayOpen) {
          _self.delayTransition();
        }
      },
      slideNavClick : function() {
        _self.setImgSize();
        var currIndex = $j(this).index();

        nextSlide = currIndex;

        if(showSkip && $j(this).hasClass('skip')) {
          nextSlide = currIndex-1;
          _self.slideTo(currIndex-1);
          _self.setActiveNav(this-1);
          currSlide = currIndex - 1;
          return;
        }

        _self.setActiveNav(this);
        if(showNextSlideAmt == 0) {

          if(slideTransition) { clearTimeout(slideTransition); }

          if(currIndex > currSlide) {
            _self.clickNext();
          } else
          if(currIndex < currSlide) {
            _self.clickPrev();
          }

        } else {
          _self.slideTo(currIndex);
        }

        currSlide = currIndex;
      },
      bigNavDisplay : function(show) {
        if(show) {
          $j('#large-nav-prev, #large-nav-next').fadeIn(slideSpeed);
        } else {
          $j('#large-nav-prev, #large-nav-next').fadeOut(slideSpeed);
        }
      },
      slideTo : function(i) {
        $j(slidesContainer)
        .css({ 'position':'absolute','top':0 })
        .animate({'left': - ( i * slideOffset ) + (i == slideCount - 1 ? showNextSlideAmt : 0) + 'px'}, slideSpeed );
        if(showBigNav && (i == slideCount-1)) { _self.bigNavDisplay(false); } else { _self.bigNavDisplay(true); }
      }
    };
    return _self;
  }()),
  productHandler : (function() {
    var currentPanel = '#bike-detail',
        zoomContainer = '#bike-zoom',
        footerHeight = $j('#footer').height()+50;
    var _self = {
      init : function() {
        $j('#bike-menu li a').click(function() {
          var navLoc = $j(this).attr('navloc'),
              clickHash = navLoc.substr(navLoc.lastIndexOf('#'),navLoc.length);
          _self.subNavClickHandler(clickHash);
        });
        _self.setContainerSize(zoomContainer);
        $j(window).resize(function() {
          _self.setContainerSize(zoomContainer);
        });
        $j('#bike-detail img').click(function() {
          $j("html, body, #container, #main-content").css("height", "100%");
          _self.setContainerSize(zoomContainer);
          $j(currentPanel).hide();
          $j("#bike-menu").hide();
          $j("#close-bike-zoom").css("top", 115 + $j("#bike-nav").height() + "px");
          _self.subNavClickHandler("#bike-detail");
          $j(zoomContainer).show();
          $j("#right-detail").hide();
          WD.productSlider.init(zoomContainer,350,'#main-content','#footer');
        });
        $j('#close-bike-zoom').click(function() {
          $j(zoomContainer).hide();
          $j("#bike-menu").show();
          $j("#right-detail").show();
          $j("html, body, #container, #main-content").css("height", "auto");
          $j(currentPanel).show();
        });
        $j('#color-availability li a').click(_self.setBikeImageDisplay);
      },
      setContainerSize : function(c) {
        var mcW = (($j(window).width()-$j('#left-content').width())-20),
            mcH = $j('#main-content').height()-footerHeight;
        $j(c).css({ 'width' : mcW+'px', 'height' : mcH+'px' });
        $j('#main-content').css('width',mcW+'px');
      },
      setBikeImageDisplay : function() {
        var clicked = $j(this).attr('data-color');
        $j('#bike-detail img, #zoom-img-container img').addClass('hideBikeImg');
        $j('#detail-image-'+clicked+', #zoom-image-'+clicked).removeClass('hideBikeImg');
      },
      subNavClickHandler : function(c) {
        if(c !== currentPanel) {
          $j(currentPanel).hide();
        }
        currentPanel = c;
        if(c === '#bike-geo' || c === '#bike-specs' || c === '#bike-features' ) {
          $j("#right-detail").hide();
        } else {
          $j("#right-detail").show();
        }
        $j(c).show();
      }
    };
    return _self;
  }()),
  productSlider : (function() {

    var cX = null,
        cY = null,
        tX = null,
        tY = null,
        parent = null,
        scroll = null,
        speed = null,
        parentWidth = null,
        parentHeight = null,
        scrollWidth = null,
        scrollHeight = null,
        offsetX = null,
        offsetY = null,
        last = null;


    function slidePos(p,s,c) { // parent(width|height), scroll(width|height), coordinate(x|y)
      return ((c/p)*s)-c;
    }
    var _self = {
      init : function(v,d,oL,oT) {

        last = new Array(); // array to store previous x/y values
        parent = v; // parent container identifier
        scroll = parent + " img"; // interior container MUST have this class
        speed = d; // speed of animation

        offsetX = $j(oL).width();
        offsetY = $j(oT).height();
        _self.resizeDomElements();

        $j(scroll).css({'position':'absolute','white-space':'no-wrap'});
        $j(window).resize(_self.resizeDomElements);
        $j(parent).live("mousemove",_self.slideListener);
      },
      resizeDomElements : function() {
        parentWidth = $j(parent).width();
        scrollWidth = $j(scroll).width();
        parentHeight = $j(parent).height();
        scrollHeight = $j(scroll).height();
      },
      slideListener : function(e) {
        cX = (e.clientX-this.offsetLeft)-$j('#left-content').width();
        cY = (e.clientY-this.offsetTop)-$j('#footer').height();

        if(cX != last["x"]) {
          _self.slideLeft(cX);
        }
        if(cY != last["y"]) {
          _self.slideTop(cY);
        }

        last["x"] = (last["x"] == null) ? 0 : cX;
        last["y"] = (last["y"] == null) ? 0 : cY;
      },
      slideLeft : function(x) {
        tX = slidePos(parentWidth,scrollWidth,x);
        $j(scroll).animate({"left": "-"+(tX)+"px"},{duration:speed,queue:false,easing:"linear" });
      },
      slideTop : function(y) {
        tY = slidePos(parentHeight,scrollHeight,y);
        $j(scroll).animate({"top": "-"+(tY)+"px"},{duration:speed,queue:false,easing:"linear" });
      }
    };

    return _self;

  }()),
  countrySwitcher : function() {
    var localeData = {},
    countryList = document.createElement('ul'),
    flagSpan = null,
    listItem = null,
    listItemText = null;

    $j('#available-locales .locale').each(function(){
      localeData[this.value] = this.innerHTML;
    });

    $j.each(localeData, function(i,data) {
      flagSpan = document.createElement('span');
      listItem = document.createElement('li');
      listItemText = document.createTextNode(data);
      flagSpan.className = 'flag ' + i;
      listItem.appendChild(flagSpan);
      listItem.appendChild(listItemText);
      listItem.className = 'countryListItem';
      listItem.setAttribute('data-country',i);
      countryList.appendChild(listItem);
    });

    countryList.id = 'country-list';
    countryList.className = 'countryList';
    $j('#footer-nav .changeRegion').append(countryList);

    $j('#change-locale').click(
      function() {
        $j(this).css({'visibility':'hidden'});
        $j('#country-list').css({'display':'block'});
      }
    ).mouseenter(
      function() {
        $j(this).addClass('over');
      }
    ).mouseleave(
      function() {
        $j(this).removeClass('over');
      }
     );

    $j('#country-list').mouseleave(function() {
      $j(this).css({'display':'none'});
      $j('#change-locale').css({'visibility':'visible'});
    });

    $j('#country-list .countryListItem').live({
      'mouseenter' : function() {
        $j(this).addClass('over');
      },
      'mouseleave' : function() {
        $j(this).removeClass('over');
      },
      'click': function(e) {
        var path = window.location.pathname,
        clickCountry = $j(this).attr('data-country') == 'usa' ? '' : '/' + $j(this).attr('data-country'),
        pathPieces = [],
        shifted = null;

        pathPieces = path.split('/');
        pathPieces.shift(); // lose the domain piece; we don't need it
        shifted = pathPieces.shift();

        if($j.inArray(shifted,localeData) > -1) {
          path = clickCountry + '/' + pathPieces.join('/');
        } else {
          path = clickCountry + '/' + (shifted != '' && typeof(localeData[shifted]) === 'undefined' ? shifted + '/' : '') + pathPieces.join('/');
        }

        $j('#country-list').css({'display':'none'});
        $j('#change-locale').css({'visibility':'visible'});

        window.location = path;
      }
    });
  }//,another???
  
}; //end WD



//==================================================================================
//  FIRE IT UP: Execute that code
// http://paulirish.com/2009/markup-based-unobtrusive-comprehensive-dom-ready-execution/
//==================================================================================

UTIL = {
 
  fire : function(func,funcname, args){
    var namespace = CD;  // obj literal namespace
 
    funcname = (funcname === undefined) ? 'init' : funcname;
    if (func !== '' && namespace[func] && typeof namespace[func][funcname] == 'function'){
      namespace[func][funcname](args);
    } 
  }, 
 
  loadEvents : function(){ 
    var bodyId = document.body.id;
    // hit up common first.
    UTIL.fire('common');
 
    // do all the classes too.
    $j.each(document.body.className.split(/\s+/),function(i,classnm){
      UTIL.fire(classnm);
      UTIL.fire(classnm,bodyId);
    });
 
    UTIL.fire('common','finalize'); 
  } 
 
}; 
 
// kick it all off here 
$j(document).ready(UTIL.loadEvents);

