﻿var HideAllSubMenus = function(){};
var DisplaySubMenu = function(){};

// The number of thumbnails to display at any one time in the image gallery
var galleryWindowSize = 3; 
var productWindowSize = 5; 
var thumbOnDisplay;

var productListApi;
var galleryApi;

var doTransition = true;

// Function to swap the product page hero image
var showMe = function(obj){
  
  var src = $(obj).attr('href');
  var title = '';
  
  obj = $(obj).children('img');
  
  if ( obj.attr('id') == thumbOnDisplay ){
    return;
  }

  thumbOnDisplay = obj.attr('id');
  title = obj.attr('alt');
  
  // Fade it out
  $('#productHero img').fadeOut(400, function(){ 
    // When complete, swap the source and bring it back
    $(this)
    .attr('src', src)
    .attr('alt', title)
    .load(function(){
      // loading complete, fadein please
      $(this).fadeIn(400);
    })});
  return false;
}

function toProperCase(s)
{
  return s.toLowerCase().replace(/^(.)|\s(.)/g, 
          function($1) { return $1.toUpperCase(); });
}

$(document).ready(function()
{

  /* --- Navigation --- */
  
  // Highlight functional pages in the menu and footer
  $('#leftCol .unorderedListMenu a, #footer li a').each( function(){
    if ( $(this).attr('href') == $.getUrlBase() || 
         $(this).attr('href') == $.getUrlBase() + "?" + $.getQueryString() ){
      $(this).addClass('MenuItemActive');
    }
    
   });


  // Get all side nav items which aren't active
  var nonActiveLinks = $("#leftCol .unorderedListMenu a").not($('#leftCol li a.MenuItemActive, #leftCol li a.ChildMenuItemActive, #leftCol li li a'));
  
  // Override the css colours to enable transitions on the first mouse over
  nonActiveLinks.attr("style", "border-color: #716F6F; color: #716F6F;");

  // Attach hover listener to manage colour transitions
  nonActiveLinks.hover(
      function() {try{
          $(this).clearQueue();
          $(this).animate({ borderLeftColor: "#f85c00",
                            color: "#f85c00" }, 200);
      }catch(e){}}
    ,
      function() {try{
          $(this).clearQueue();
          $(this).animate({ borderLeftColor: "#716F6F",
                            color: "#716F6F" }, 300);
      }catch(e){}}
    );

  var nonActiveChildLinks = $("#leftCol .unorderedListMenu li li a").not($('#leftCol li li a.MenuItemActive'));
  
  nonActiveChildLinks.attr("style", "color: #716F6F;");
  
  // hover listener for second level li navigation
  nonActiveChildLinks.hover(
      function() {try{
          $(this).clearQueue();
          $(this).animate({ color: "#f85c00" }, 200);
      }catch(e){}}
    ,
      function() {try{
          $(this).clearQueue();
          $(this).animate({ color: "#716F6F" }, 300);
      }catch(e){}}
    );
  
  /* --- Transitions --- */
  
  // Transition in the content
  try{
    
    // Pre-load the corner image before doing the transition
    var bgImage = $("#cornerPipe").css('background-image').replace(/url\(['"]?([^\)'"]+)['"]?\)/, "$1");
    var cornerLoader = $("<img src='" + bgImage + "' />");
    
    // Right the corner image is loaded, run the transition
    cornerLoader.load( function(){
      if( doTransition ){
        $("#leftCol").show("blind", { direction: "vertical", easing: "easeInCubic"}, 500);
        $("#leftCol #horizontalPipe").show("blind", { direction: "horizontal", easing: "easeInCubic" }, 800);
        doTransition = false;
      }
    });

  }catch(e){
    // If the animations fail, show the content
    $("#leftCol, #leftCol #horizontalPipe, #productList ul, #cmsContentInner3").show();
  }  
  //make sure the above ran, if not, force show leftCol again
  if(doTransition)
  {
    $("#leftCol, #leftCol #horizontalPipe, #productList ul, #cmsContentInner3").show();
  }
  
  /* --- Image Gallery --- */
  
  // Work out which image is currently being shown
  thumbOnDisplay = $("#imageGallery .items img").first().attr('id'); 
  
  // Preload all the gallery images
  $('#imageGallery .items a').each(function(index) {
      var imgPreload = $('<img />').attr('src', $(this).attr('href'));
  });
  
  // Fade the gradient in and out
	var gallerySeek = function( seekEvent, index ){
	  try{
	    if ( (!index) || index == 0 ){
	      $('#westGhost').animate({ width: '0px' });
	    }else{
	      $('#westGhost').animate({ width: '45px' });
	    }
  	  
  	  
	    if ( index == galleryApi.getSize() - galleryWindowSize){
	      $("#eastGhost").animate({ width: '0px' });
	    }else{
	      $("#eastGhost").animate({ width: '45px' });
	    }	    
	  }catch(e){
	  }
	}

	// Fade the gradient in and out
	// This gets messy due to trying to manage half indexes ( where only half a product is shown at the end )
	var productSeek = function( seekEvent, index ){	
	  
	  // function is called on page load with no valid arguments
    // when this happens, get the current index from the api
	  
	  try{
	  if ( index == undefined ){
	     if ( seekEvent == undefined ){
	      index = productListApi.getIndex();
	     }
	  }
    
	  
	    // Hide or show north ghost
	    if ( index == 0 ){
	      $('#northGhost').animate({ height: '0px' });
	    }else{
	      $('#northGhost').animate({ height: '45px' });
	     
	     // Set the titles of the ghosts
  	    var topItem = productListApi.getItems()[index - ( Math.ceil( productWindowSize % 1 ) )];
  	    $('#northGhost').attr( 'title', $(topItem).children('a').attr('title') );
	    }
  	  
  	  // Hide or show south ghost
	    if ( index == productListApi.getSize() - Math.floor( productWindowSize ) ){
	      $("#southGhost").animate({ height: '0px' });
	    }else{
	      $("#southGhost").animate({ height: '45px' });
	      
	      // Set the title of the ghost
	      var bottomItem = productListApi.getItems()[index + Math.ceil( productWindowSize ) - 1];
  	    $('#southGhost').attr( 'title', $(bottomItem).children('a').attr('title') );
	    }
	   }catch( e ){
	   }
	}
  
  
  // initialize scrollable gallery
  var galleryCount = $("#imageGallery .items").children().size();
	if ( galleryCount > galleryWindowSize ){
	  $("#gallery .btnLeft").addClass("prev").removeClass("disabled");
	  $("#gallery .btnRight").addClass("next").removeClass("disabled");

	  $("#imageGallery").scrollable();
	  
    // Show the navigation buttons
    $('#gallery a.prev, #gallery a.next').show();
    
    // Set the number of thumbnails to display at any one time
    galleryApi = $("#imageGallery").data("scrollable");
	  galleryApi.getConf().itemCount = galleryWindowSize;
	  galleryApi.onBeforeSeek( gallerySeek );
	}

	// initialize scrollable product list
  var productCount = $("#productList ul").children().size();
	if ( productCount > productWindowSize ){
	  $("#productList .top").addClass("prev").removeClass("disabled");
	  $("#productList .bottom").addClass("next").removeClass("disabled");
	  
	  $("#vertScroller").scrollable({ vertical: true });

    
    // Set the number of thumbnails to display at any one time
    productListApi = $("#vertScroller").data("scrollable");
	  productListApi.getConf().itemCount = productWindowSize;
	  productListApi.onBeforeSeek( productSeek );
	  
	  var currentProduct = $.getUrlVar('p');
    var scrollTo = 0;

    // If a product is selected and we need to scroll to it
	  if ( currentProduct && productCount > productWindowSize ){
	    $("#productList ul").children().each(function(index) {
	      
	      // Find the current product
        if ( $(this).attr("class") == "p_" + currentProduct ){
          
          // Scroll to it ( if required )
          scrollTo = Math.ceil( index - productWindowSize + 1 );
          if ( scrollTo > 0 ){
            productListApi.seekTo( scrollTo, 700 );
          }
        }
      });      
	  }
	}
	
	// Setup event handlers to pass on the click event when
	// the ghosted gradient is clicked
	var horizClick = function( index ){
	  var target = galleryApi.getItems()[index];
	  target = $(target).children('a');
	  target.trigger('click');
	}
	
	var vertClick = function( index ){
		var target = productListApi.getItems()[index];	  
	  target = $(target).children('a');
	  window.location.href = target.attr('href');
    return false;
	}
	
	$('#eastGhost').click(function(){ 
	  horizClick( galleryWindowSize + galleryApi.getIndex() - 1 );
	});
	
	$('#westGhost').click(function(){ 
	  horizClick( galleryApi.getIndex() );
	});
	
	$('#northGhost').click(function(){ 
	  vertClick( productListApi.getIndex() - ( Math.ceil( productWindowSize % 1 ) ) );
	});
	
	$('#southGhost').click(function(){ 
	  vertClick( productListApi.getIndex()  + Math.ceil( productWindowSize ) - 1 );
	});
		
	// ie6 can't handle the png gradients
  if ( !ie6 ){
    // Show the gradients
    $("#northGhost, #southGhost, #eastGhost, #westGhost").show();
    gallerySeek();
    productSeek();
  }
  
  /* --- Tooltips --- */
  
  $('body').append("<div id='tooltip'><div class='start'><!-- // --></div><label id='tooltipContent'></label><div class='end'><!-- // --></div></div>" );
  
  var tooltip = $("#tooltip");
  var tooltipContent = $("#tooltipContent");
  
  if ( ie6 ){
    // PNG Fix
    DD_belatedPNG.fix('#tooltip .start, #tooltipContent, #tooltip .end');
  }
  
	$("#productList ul li a, #northGhost, #southGhost").hover(
		function(){
		  // Get the title then remove it -- this is to disable the builtin browser tooltip
      $this = $(this);
      $.data(this, 'title', $this.attr("title") );
      $.data(this, 'alt', $this.children('img').attr('alt') );
      $this.attr("title","");
      $this.children('img').attr('alt', '');
	    
		  tooltipContent.html( $.data( this, 'title') );
		  tooltip.show();
	  },
		function(){		
		  // Hide the tooltip and restore the title
		  $this = $(this);
		  $this.attr("title", $.data( this, 'title' ) );
		  $this.children('img').attr('alt', $.data(this, 'alt') );
		  tooltipContent.html("");
		  tooltip.hide(); 
		}
	);
	
	// follow the mouse
	$("#productList ul li a, #northGhost, #southGhost").mousemove(function(e) {
		var mousex = e.pageX + 20;
		var mousey = e.pageY - 5;
		$(tooltip).css({  top: mousey, left: mousex });
	});
	
  /* add classes that you want jquery vertical scrollbar to appear on */
  $(function()
  {
      $('.cmsContentCutDown').jScrollPane();
      $('.cmsContentNoImageCutDown').jScrollPane();
      $('.productDetail').jScrollPane();
  });
  
  // Hide 3rd level in nav (yes this is a hack, but i couldn't figure out the logic for solving this server-side with Brochure ...I did try ...for hours ><)
  $('#side_menu .side_item .ms_side_sub_menu').hide();
  
  // Hack to get tertiary menu items still retaining the primary menu item active (bug with brochure menu again, only seems to handle 2 level menus)
  var classes = $(document.body).attr('class').split(" ");
  for (var i=classes.length; i--;) {
      //menu is case sensitive, make first char capital ><
      var element = toProperCase(classes[i]);
      $('.unorderedListMenu ul li .' + element).addClass("ParentMenuItemActive");
  }
  
});
