var CURRENCY = '&pound;';

/*
 * Superfish v1.4.1 - jQuery menu widget
 * Copyright (c) 2008 Joel Birch
 * Dual licensed under the MIT and GPL licenses:
 *  http://www.opensource.org/licenses/mit-license.php
 *  http://www.gnu.org/licenses/gpl.html
 * CHANGELOG: http://users.tpg.com.au/j_birch/plugins/superfish/changelog.txt
 */
(function($){
  $.superfish = {};
  $.superfish.o = [];
  $.superfish.op = {};
  $.superfish.defaults = {
    hoverClass : 'sfHover',
    pathClass : 'overideThisToUse',
    delay : 600,
    animation : {opacity:'show',height:'show'},
    speed : 'fast',
    oldJquery : false,
    disableHI : false,
    // callback functions:
    onInit : function(){},
    onBeforeShow : function(){},
    onShow : function(){},
    onHide : function(){}
  };
  $.fn.superfish = function(op){
    var bcClass = 'sfbreadcrumb',
      over = function(){
        var $$ = $(this), menu = getMenu($$);
        getOpts(menu,true);
        clearTimeout(menu.sfTimer);
        $$.showSuperfishUl().siblings().hideSuperfishUl();
      },
      out = function(){
        var $$ = $(this), menu = getMenu($$);
        var o = getOpts(menu,true);
        clearTimeout(menu.sfTimer);
        if ( !$$.is('.'+bcClass) ) {
          menu.sfTimer=setTimeout(function(){
            $$.hideSuperfishUl();
            if (o.$path.length){over.call(o.$path);}
          },o.delay);
        }
      },
      getMenu = function($el){ return $el.parents('ul.superfish:first')[0]; },
      getOpts = function(el,menuFound){ el = menuFound ? el : getMenu(el); return $.superfish.op = $.superfish.o[el.serial]; },
      hasUl = function(){ return $.superfish.op.oldJquery ? 'li[ul]' : 'li:has(ul)'; };

    return this.each(function() {
      var s = this.serial = $.superfish.o.length;
      var o = $.extend({},$.superfish.defaults,op);
      o.$path = $('li.'+o.pathClass,this).each(function(){
        $(this).addClass(o.hoverClass+' '+bcClass)
          .filter(hasUl()).removeClass(o.pathClass);
      });
      $.superfish.o[s] = $.superfish.op = o;
      
      $(hasUl(),this)[($.fn.hoverIntent && !o.disableHI) ? 'hoverIntent' : 'hover'](over,out)
      .not('.'+bcClass)
        .hideSuperfishUl();
      
      var $a = $('a',this);
      $a.each(function(i){
        var $li = $a.eq(i).parents('li');
        $a.eq(i).focus(function(){over.call($li);}).blur(function(){out.call($li);});
      });
      
      o.onInit.call(this);
      
    }).addClass('superfish');
  };

  $.fn.extend({
    hideSuperfishUl : function(){
      var o = $.superfish.op,
        $ul = $('li.'+o.hoverClass,this).add(this).removeClass(o.hoverClass)
          .find('>ul').hide().css('visibility','hidden');
      o.onHide.call($ul);
      return this;
    },
    showSuperfishUl : function(){
      var o = $.superfish.op,
        $ul = this.addClass(o.hoverClass)
          .find('>ul:hidden').css('visibility','visible');
      o.onBeforeShow.call($ul);
      $ul.animate(o.animation,o.speed,function(){ o.onShow.call(this); });
      return this;
    }
  });

  $(window).unload(function(){
    $('ul.superfish').each(function(){
      $('li',this).unbind('mouseover','mouseout','mouseenter','mouseleave');
    });
  });
})(jQuery);

// Overlabel - Accessible Text Input Labels For Space Saving Forms
(function($){
  $.fn.overlabel = function() {
    this.each(function(){
      var label = $(this);
      var id = this.htmlFor || label.attr('for') || 'NO-ID';
      $('#'+id.replace(/\:/,'\\:'))
      .parent().addClass('overlabel-wrapper').end()
      .focus(function(){ label.css('text-indent','-1000px'); })
      .blur(function(){ this.value || label.css('text-indent','0px'); })
      .trigger('focus').trigger('blur')
      .length && 
        label.addClass('overlabel-apply');
    });
  }
})(jQuery);

// DERIVE WEBSITE ROOT PATH
function deriveRoot()
{
  var root = window.location.protocol+'//'+window.location.hostname+'/';
  
  if ( ( pos = window.location.pathname.search('httpdocs') ) != -1 )
  {
    root += window.location.pathname.substring(1,pos+9);
  }
  
  if ( window.location.pathname.search('demo') != -1 )
  {
    root += 'demo/';
  }
  
  return root;
}

// BASKET FUNCTIONS
function animateBasket( action )
{
  switch ( action )
  {
    case 'add':
      colour = '#00BF08';
      break;
    case 'delete':
      colour = '#FF4A4A';
      break;
  }
  
  $('li#updated').highlightFade({colour:colour,iterator:'exponential'});
}

function activateRemoveLinks( root )
{
  $('a.del').click(function()
  {
    $.get(root+'basket/',
    {
      removeItem  : $(this).attr('id').substring(10),
      ajax        : 'true'
    },
    function(data)
	{
	  var item_count = 0;
	  $('#basket').html( data );
	  activateRemoveLinks( root );
	  animateBasket( 'delete' );
	  $('#basket').find('h5').each(function()
	  {
	    item_count++;
	  });
	  if(item_count == 1)
	  {
		$('span.mini_basket_items').html(item_count+' item');
	  }
	  else
	  {
		$('span.mini_basket_items').html(item_count+' items');
	  }
	});
    
    return false;
  });
  
  $('a.checkoutDelete').click(function()
  {
    $.get(root+'basket/',
    {
      removeCheckoutItem : $(this).attr('id').substring(10),
      ajax               : 'true'
    },
    function(data){ $('div#ajaxify').html( data ); activateRemoveLinks( root ); });
    
    return false;
  });
}
function activateAddLinks( root )
{
  $('form.add_to_basket').submit(function()
  {
    var containerID = $(this).find('ol[@id^="ajaxify-"]').attr('id');
    
    var notCompleted = false;
    
    $('#'+containerID).find('select').each(function()
    {
      if ( !$(this).attr('value') ) { notCompleted = $(this).prev().text(); return false; }
    });
    
    if ( notCompleted ) // Not all options have been selected as required
    {
      alert('Please make your '+notCompleted+' selection!');
    }
    else // All is gravy...// ONLY PROBLEM BEING THAT ONLY USERS WITH JAVASCRIPT ENABLED WILL SEE AN ERROR
    {
      var quantity = 1;
      
      if ( $(this).find('select[@name=quantity]').length )
      {
        if ( $(this).find('select[@name=quantity]').val() != '' )
        {
          quantity = $(this).find('select[@name=quantity]').val();
        }
      }
      
      $.post(root+'basket/',
      {
        addToBasket  : 'addToBasket',
        ajax         : 'true',
        comboID      : $(this).find('input[@name=comboID]').val(),
        productID    : $(this).find('input[@name=productID]').val(),
        quantity     : quantity
      },
      function(data)
	  {
		var item_count = 0;
		$('#basket').html( data );
		activateRemoveLinks( root );
		animateBasket( 'add' );
		$('#basket').find('h5').each(function()
		{
		  item_count++;
		});
		if(item_count == 1)
		{
			$('span.mini_basket_items').html(item_count+' item');
		}
		else
		{
			$('span.mini_basket_items').html(item_count+' items');
		}
	  });
    }
    
    return false;
  });
}
function activateProductConfigurators( root )
{
  $('form ol[@id^="ajaxify-"] li select').change(function()
  {
    var containerID = $(this).parent().parent().attr('id');
    var productID   = $('#'+containerID).parent().next('fieldset').find('input[@name=productID]').val();
    
    if ( typeof(productID) == 'undefined' ) // Trade Discount Occurence...
    {
      productID = $('#'+containerID).parent().parent().children('fieldset').eq(2).find('input[@name=productID]').val();
    }
    
    var configValues = '';
    
    $('#'+containerID).find('select').each(function()
    {
      configValues += $(this).attr('name')+'===='+$(this).attr('value')+';;;;';
    });
    
    if ( $('select#quantity').length ) // If Multiple Discount Select Is Present, Reset It
    {
      $('select#quantity')[0].selectedIndex = 0;
    }
    
    $.post(root+'reconfigure/',
    {
      reconfigureProduct : 'reconfigureProduct',
      ajax               : 'true',
      configValues       : configValues,
      productID          : productID
    },
    function(data){ $('#'+containerID).html( data ); activateProductConfigurators( root ); checkForPriceUpdate( productID ); });
  });
  
  $('select#quantity').change(function()
  {
    var multiple  = $(this).attr('value');
    var productID = $(this).parent().parent().parent().next('fieldset').find('input[@name=productID]').val();
    
    if ( $('input[@name="updatedPrice-'+productID+'"]').length )
    {
      var price = $('input[@name="updatedPrice-'+productID+'"]').attr('value');
    }
    else
    {
      var price = $(this).parent().parent().parent().next('fieldset').find('input[@name=price]').val();
    }
    
    if ( typeof(multiple) != 'undefined' )
    {
      var discountText  = $(this).find('option:selected').text();
      var discount      = discountText.split(' ');
      
      if ( discount[2].indexOf('%') != -1 ) // Percentage Discount
      {
        discount = discount[2].slice(0,(discount[2].length-1));
        
        if ( discount.length == 1 )
        {
          discount = '0.0'+discount;
        }
        else
        {
          discount = '0.'+discount;
        }
		
        discount = Math.round((price * discount)*100)/100;
		discount = discount * multiple;
      }
      else // Monetary Discount
      {
        discount = discount[2].slice(1);
      }
	  
      var multiplePrice = price * multiple;
      multiplePrice = Math.round((multiplePrice - discount)*100)/100;
      
      $('#Price-'+productID).html(CURRENCY+multiplePrice.toFixed(2));
    }
    else
    {
      $('#Price-'+productID).html(CURRENCY+price);
    }
  });
  
}
function checkForPriceUpdate( id )
{
  if ( $('input[@name="updatedPrice-'+id+'"]').length )
  {
    $('#Price-'+id).html(CURRENCY+$('input[@name="updatedPrice-'+id+'"]').attr('value'));
  }
}

/*
 * Floating Basket
 * Based upon: X Floater Box, Copyright 2001-2007 Michael Foster (Cross-Browser.com)
 * Which is part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL
 * http://www.cross-browser.com/
 */

xLibrary={version:'4.07',license:'GNU LGPL',url:'http://cross-browser.com/'};
function xAddEventListener(e,eT,eL,cap){if(!(e=xGetElementById(e)))return;eT=eT.toLowerCase();if(e.addEventListener)e.addEventListener(eT,eL,cap||false);else if(e.attachEvent)e.attachEvent('on'+eT,eL);else e['on'+eT]=eL;}function xClientHeight(){var v=0,d=document,w=window;if(d.compatMode=='CSS1Compat'&&!w.opera&&d.documentElement&&d.documentElement.clientHeight){v=d.documentElement.clientHeight;}else if(d.body&&d.body.clientHeight){v=d.body.clientHeight;}else if(xDef(w.innerWidth,w.innerHeight,d.width)){v=w.innerHeight;if(d.width>w.innerWidth)v-=16;}return v;}function xDef(){for(var i=0;i<arguments.length;++i){if(typeof(arguments[i])=='undefined')return false;}return true;}function xGetComputedStyle(oEle,sProp,bInt){var s,p='undefined';var dv=document.defaultView;if(dv&&dv.getComputedStyle){s=dv.getComputedStyle(oEle,'');if(s)p=s.getPropertyValue(sProp);}else if(oEle.currentStyle){var i,c,a=sProp.split('-');sProp=a[0];for(i=1;i<a.length;++i){c=a[i].charAt(0);sProp+=a[i].replace(c,c.toUpperCase());}p=oEle.currentStyle[sProp];}else return null;return bInt?(parseInt(p)||0):p;}function xGetElementById(e){if(typeof(e)=='string'){if(document.getElementById)e=document.getElementById(e);else if(document.all)e=document.all[e];else e=null;}return e;}function xHeight(e,h){if(!(e=xGetElementById(e)))return 0;if(xNum(h)){if(h<0)h=0;else h=Math.round(h);}else h=-1;var css=xDef(e.style);if(e==document||e.tagName.toLowerCase()=='html'||e.tagName.toLowerCase()=='body'){h=xClientHeight();}else if(css&&xDef(e.offsetHeight)&&xStr(e.style.height)){if(h>=0){var pt=0,pb=0,bt=0,bb=0;if(document.compatMode=='CSS1Compat'){var gcs=xGetComputedStyle;pt=gcs(e,'padding-top',1);if(pt!==null){pb=gcs(e,'padding-bottom',1);bt=gcs(e,'border-top-width',1);bb=gcs(e,'border-bottom-width',1);}else if(xDef(e.offsetHeight,e.style.height)){e.style.height=h+'px';pt=e.offsetHeight-h;}}h-=(pt+pb+bt+bb);if(isNaN(h)||h<0)return;else e.style.height=h+'px';}h=e.offsetHeight;}else if(css&&xDef(e.style.pixelHeight)){if(h>=0)e.style.pixelHeight=h;h=e.style.pixelHeight;}return h;}function xLeft(e,iX){if(!(e=xGetElementById(e)))return 0;var css=xDef(e.style);if(css&&xStr(e.style.left)){if(xNum(iX))e.style.left=iX+'px';else{iX=parseInt(e.style.left);if(isNaN(iX))iX=xGetComputedStyle(e,'left',1);if(isNaN(iX))iX=0;}}else if(css&&xDef(e.style.pixelLeft)){if(xNum(iX))e.style.pixelLeft=iX;else iX=e.style.pixelLeft;}return iX;}function xMoveTo(e,x,y){xLeft(e,x);xTop(e,y);}function xNum(){for(var i=0;i<arguments.length;++i){if(isNaN(arguments[i])||typeof(arguments[i])!='number')return false;}return true;}function xScrollTop(e,bWin){var offset=0;if(!xDef(e)||bWin||e==document||e.tagName.toLowerCase()=='html'||e.tagName.toLowerCase()=='body'){var w=window;if(bWin&&e)w=e;if(w.document.documentElement&&w.document.documentElement.scrollTop)offset=w.document.documentElement.scrollTop;else if(w.document.body&&xDef(w.document.body.scrollTop))offset=w.document.body.scrollTop;}else{e=xGetElementById(e);if(e&&xNum(e.scrollTop))offset=e.scrollTop;}return offset;}function xSlideTo(e,x,y,uTime){if(!(e=xGetElementById(e)))return;if(!e.timeout)e.timeout=25;e.xTarget=x;e.yTarget=y;e.slideTime=uTime;e.stop=false;e.yA=e.yTarget-xTop(e);e.xA=e.xTarget-xLeft(e);if(e.slideLinear)e.B=1/e.slideTime;else e.B=Math.PI/(2*e.slideTime);e.yD=xTop(e);e.xD=xLeft(e);var d=new Date();e.C=d.getTime();if(!e.moving)_xSlideTo(e);}function _xSlideTo(e){if(!(e=xGetElementById(e)))return;var now,s,t,newY,newX;now=new Date();t=now.getTime()-e.C;if(e.stop){e.moving=false;}else if(t<e.slideTime){setTimeout("_xSlideTo('"+e.id+"')",e.timeout);s=e.B*t;if(!e.slideLinear)s=Math.sin(s);newX=Math.round(e.xA*s+e.xD);newY=Math.round(e.yA*s+e.yD);xMoveTo(e,newX,newY);e.moving=true;}else{xMoveTo(e,e.xTarget,e.yTarget);e.moving=false;if(e.onslideend)e.onslideend();}}function xStr(s){for(var i=0;i<arguments.length;++i){if(typeof(arguments[i])!='string')return false;}return true;}function xTop(e,iY){if(!(e=xGetElementById(e)))return 0;var css=xDef(e.style);if(css&&xStr(e.style.top)){if(xNum(iY))e.style.top=iY+'px';else{iY=parseInt(e.style.top);if(isNaN(iY))iY=xGetComputedStyle(e,'top',1);if(isNaN(iY))iY=0;}}else if(css&&xDef(e.style.pixelTop)){if(xNum(iY))e.style.pixelTop=iY;else iY=e.style.pixelTop;}return iY;}function xHeight(e,h){if(!(e=xGetElementById(e)))return 0;if(xNum(h)){if(h<0)h=0;else h=Math.round(h);}else h=-1;var css=xDef(e.style);if(e==document||e.tagName.toLowerCase()=='html'||e.tagName.toLowerCase()=='body'){h=xClientHeight();}else if(css&&xDef(e.offsetHeight)&&xStr(e.style.height)){if(h>=0){var pt=0,pb=0,bt=0,bb=0;if(document.compatMode=='CSS1Compat'){var gcs=xGetComputedStyle;pt=gcs(e,'padding-top',1);if(pt!==null){pb=gcs(e,'padding-bottom',1);bt=gcs(e,'border-top-width',1);bb=gcs(e,'border-bottom-width',1);}else if(xDef(e.offsetHeight,e.style.height)){e.style.height=h+'px';pt=e.offsetHeight-h;}}h-=(pt+pb+bt+bb);if(isNaN(h)||h<0)return;else e.style.height=h+'px';}h=e.offsetHeight;}else if(css&&xDef(e.style.pixelHeight)){if(h>=0)e.style.pixelHeight=h;h=e.style.pixelHeight;}return h;}function xDocSize(){var b=document.body,e=document.documentElement;var esw=0,eow=0,bsw=0,bow=0,esh=0,eoh=0,bsh=0,boh=0;if(e){esw=e.scrollWidth;eow=e.offsetWidth;esh=e.scrollHeight;eoh=e.offsetHeight;}if(b){bsw=b.scrollWidth;bow=b.offsetWidth;bsh=b.scrollHeight;boh=b.offsetHeight;}return{w:Math.max(esw,eow,bsw,bow),h:Math.max(esh,eoh,bsh,boh)};}

function winOnResize(){
  xMoveTo('basket',xLeft('rail'),0);
  winOnScroll();
}
function winOnScroll(){
  var topLimit = 519;    // #rail y pos
  //var bottomLimit = 519 + xHeight('brandCloud') + 297 + 35; // top limit + brandCloud + footerBase + content bottom padding
  var bottomLimit = 519 + 197 + 35; // top limit + footer + content bottom padding
  var ds = xDocSize();
  var y  = xScrollTop() - topLimit;
  if(y>0){
    if(y<(ds.h-(bottomLimit+xHeight('basket')))){
      xSlideTo('basket',xLeft('rail'),y,700);
    }
  }else{
    xSlideTo('basket',xLeft('rail'),0,700);
  }
}

/*
 * jQuery lightBox plugin
 * This jQuery plugin was inspired by and based upon Lightbox 2 by Lokesh Dhakar (http://www.huddletogether.com/projects/lightbox2/)
 * (c) 2008 Leandro Vieira Pinho (leandrovieira.com)
 */
(function($){$.fn.lightBox=function(settings){var root = deriveRoot(); settings=jQuery.extend({overlayBgColor:'#000',overlayOpacity:0.8,fixedNavigation:false,imageLoading:root+'media/img/lightbox-ico-loading.gif',imageBtnPrev:root+'media/img/lightbox-btn-prev.gif',imageBtnNext:root+'media/img/lightbox-btn-next.gif',imageBtnClose:root+'media/img/lightbox-btn-close.gif',imageBlank:root+'media/img/lightbox-blank.gif',containerBorderSize:10,containerResizeSpeed:400,txtImage:'Image',txtOf:'of',keyToClose:'c',keyToPrev:'p',keyToNext:'n',imageArray:[],activeImage:0},settings);var jQueryMatchedObj=this;function _initialize(){_start(this,jQueryMatchedObj);return false;}
function _start(objClicked,jQueryMatchedObj){$('embed, object, select').css({'visibility':'hidden'});_set_interface();settings.imageArray.length=0;settings.activeImage=0;if(jQueryMatchedObj.length==1){settings.imageArray.push(new Array(objClicked.getAttribute('href'),objClicked.getAttribute('title')));}else{for(var i=0;i<(jQueryMatchedObj.length)-1;i++){settings.imageArray.push(new Array(jQueryMatchedObj[i].getAttribute('href'),jQueryMatchedObj[i].getAttribute('title')));}}
while(settings.imageArray[settings.activeImage][0]!=objClicked.getAttribute('href')){settings.activeImage++;}
_set_image_to_view();}
function _set_interface(){$('body').append('<div id="jquery-overlay"></div><div id="jquery-lightbox"><div id="lightbox-container-image-box"><div id="lightbox-container-image"><img id="lightbox-image"><div style="" id="lightbox-nav"><a href="#" id="lightbox-nav-btnPrev"></a><a href="#" id="lightbox-nav-btnNext"></a></div><div id="lightbox-loading"><a href="#" id="lightbox-loading-link"><img src="'+settings.imageLoading+'"></a></div></div></div><div id="lightbox-container-image-data-box"><div id="lightbox-container-image-data"><div id="lightbox-image-details"><span id="lightbox-image-details-caption"></span><span id="lightbox-image-details-currentNumber"></span></div><div id="lightbox-secNav"><a href="#" id="lightbox-secNav-btnClose"><img src="'+settings.imageBtnClose+'"></a></div></div></div></div>');var arrPageSizes=___getPageSize();$('#jquery-overlay').css({backgroundColor:settings.overlayBgColor,opacity:settings.overlayOpacity,width:arrPageSizes[0],height:arrPageSizes[1]}).fadeIn();var arrPageScroll=___getPageScroll();$('#jquery-lightbox').css({top:arrPageScroll[1]+(arrPageSizes[3]/10),left:arrPageScroll[0]}).show();$('#jquery-overlay,#jquery-lightbox').click(function(){_finish();});$('#lightbox-loading-link,#lightbox-secNav-btnClose').click(function(){_finish();return false;});$(window).resize(function(){var arrPageSizes=___getPageSize();$('#jquery-overlay').css({width:arrPageSizes[0],height:arrPageSizes[1]});var arrPageScroll=___getPageScroll();$('#jquery-lightbox').css({top:arrPageScroll[1]+(arrPageSizes[3]/10),left:arrPageScroll[0]});});}
function _set_image_to_view(){$('#lightbox-loading').show();if(settings.fixedNavigation){$('#lightbox-image,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide();}else{$('#lightbox-image,#lightbox-nav,#lightbox-nav-btnPrev,#lightbox-nav-btnNext,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide();}
var objImagePreloader=new Image();objImagePreloader.onload=function(){$('#lightbox-image').attr('src',settings.imageArray[settings.activeImage][0]);_resize_container_image_box(objImagePreloader.width,objImagePreloader.height);objImagePreloader.onload=function(){};};objImagePreloader.src=settings.imageArray[settings.activeImage][0];};function _resize_container_image_box(intImageWidth,intImageHeight){var intCurrentWidth=$('#lightbox-container-image-box').width();var intCurrentHeight=$('#lightbox-container-image-box').height();var intWidth=(intImageWidth+(settings.containerBorderSize*2));var intHeight=(intImageHeight+(settings.containerBorderSize*2));var intDiffW=intCurrentWidth-intWidth;var intDiffH=intCurrentHeight-intHeight;$('#lightbox-container-image-box').animate({width:intWidth,height:intHeight},settings.containerResizeSpeed,function(){_show_image();});if((intDiffW==0)&&(intDiffH==0)){if($.browser.msie){___pause(250);}else{___pause(100);}}
$('#lightbox-container-image-data-box').css({width:intImageWidth});$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({height:intImageHeight+(settings.containerBorderSize*2)});};function _show_image(){$('#lightbox-loading').hide();$('#lightbox-image').fadeIn(function(){_show_image_data();_set_navigation();});_preload_neighbor_images();};function _show_image_data(){$('#lightbox-container-image-data-box').slideDown('fast');$('#lightbox-image-details-caption').hide();if(settings.imageArray[settings.activeImage][1]){$('#lightbox-image-details-caption').html(settings.imageArray[settings.activeImage][1]).show();}
if(settings.imageArray.length>1){$('#lightbox-image-details-currentNumber').html(settings.txtImage+' '+(settings.activeImage+1)+' '+settings.txtOf+' '+settings.imageArray.length).show();}}
function _set_navigation(){$('#lightbox-nav').show();$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({'background':'transparent url('+settings.imageBlank+') no-repeat'});if(settings.activeImage!=0){if(settings.fixedNavigation){$('#lightbox-nav-btnPrev').css({'background':'url('+settings.imageBtnPrev+') left 15% no-repeat'}).unbind().bind('click',function(){settings.activeImage=settings.activeImage-1;_set_image_to_view();return false;});}else{$('#lightbox-nav-btnPrev').unbind().hover(function(){$(this).css({'background':'url('+settings.imageBtnPrev+') left 15% no-repeat'});},function(){$(this).css({'background':'transparent url('+settings.imageBlank+') no-repeat'});}).show().bind('click',function(){settings.activeImage=settings.activeImage-1;_set_image_to_view();return false;});}}
if(settings.activeImage!=(settings.imageArray.length-1)){if(settings.fixedNavigation){$('#lightbox-nav-btnNext').css({'background':'url('+settings.imageBtnNext+') right 15% no-repeat'}).unbind().bind('click',function(){settings.activeImage=settings.activeImage+1;_set_image_to_view();return false;});}else{$('#lightbox-nav-btnNext').unbind().hover(function(){$(this).css({'background':'url('+settings.imageBtnNext+') right 15% no-repeat'});},function(){$(this).css({'background':'transparent url('+settings.imageBlank+') no-repeat'});}).show().bind('click',function(){settings.activeImage=settings.activeImage+1;_set_image_to_view();return false;});}}
_enable_keyboard_navigation();}
function _enable_keyboard_navigation(){$(document).keydown(function(objEvent){_keyboard_action(objEvent);});}
function _disable_keyboard_navigation(){$(document).unbind();}
function _keyboard_action(objEvent){if(objEvent==null){keycode=event.keyCode;escapeKey=27;}else{keycode=objEvent.keyCode;escapeKey=objEvent.DOM_VK_ESCAPE;}
key=String.fromCharCode(keycode).toLowerCase();if((key==settings.keyToClose)||(key=='x')||(keycode==escapeKey)){_finish();}
if((key==settings.keyToPrev)||(keycode==37)){if(settings.activeImage!=0){settings.activeImage=settings.activeImage-1;_set_image_to_view();_disable_keyboard_navigation();}}
if((key==settings.keyToNext)||(keycode==39)){if(settings.activeImage!=(settings.imageArray.length-1)){settings.activeImage=settings.activeImage+1;_set_image_to_view();_disable_keyboard_navigation();}}}
function _preload_neighbor_images(){if((settings.imageArray.length-1)>settings.activeImage){objNext=new Image();objNext.src=settings.imageArray[settings.activeImage+1][0];}
if(settings.activeImage>0){objPrev=new Image();objPrev.src=settings.imageArray[settings.activeImage-1][0];}}
function _finish(){$('#jquery-lightbox').remove();$('#jquery-overlay').fadeOut(function(){$('#jquery-overlay').remove();});$('embed, object, select').css({'visibility':'visible'});}
function ___getPageSize(){var xScroll,yScroll;if(window.innerHeight&&window.scrollMaxY){xScroll=window.innerWidth+window.scrollMaxX;yScroll=window.innerHeight+window.scrollMaxY;}else if(document.body.scrollHeight>document.body.offsetHeight){xScroll=document.body.scrollWidth;yScroll=document.body.scrollHeight;}else{xScroll=document.body.offsetWidth;yScroll=document.body.offsetHeight;}
var windowWidth,windowHeight;if(self.innerHeight){if(document.documentElement.clientWidth){windowWidth=document.documentElement.clientWidth;}else{windowWidth=self.innerWidth;}
windowHeight=self.innerHeight;}else if(document.documentElement&&document.documentElement.clientHeight){windowWidth=document.documentElement.clientWidth;windowHeight=document.documentElement.clientHeight;}else if(document.body){windowWidth=document.body.clientWidth;windowHeight=document.body.clientHeight;}
if(yScroll<windowHeight){pageHeight=windowHeight;}else{pageHeight=yScroll;}
if(xScroll<windowWidth){pageWidth=xScroll;}else{pageWidth=windowWidth;}
arrayPageSize=new Array(pageWidth,pageHeight,windowWidth,windowHeight);return arrayPageSize;};function ___getPageScroll(){var xScroll,yScroll;if(self.pageYOffset){yScroll=self.pageYOffset;xScroll=self.pageXOffset;}else if(document.documentElement&&document.documentElement.scrollTop){yScroll=document.documentElement.scrollTop;xScroll=document.documentElement.scrollLeft;}else if(document.body){yScroll=document.body.scrollTop;xScroll=document.body.scrollLeft;}
arrayPageScroll=new Array(xScroll,yScroll);return arrayPageScroll;};function ___pause(ms){var date=new Date();curDate=null;do{var curDate=new Date();}
while(curDate-date<ms);};return this.unbind('click').click(_initialize);};})(jQuery);

/*
 * jQuery Plugin highlightFade (jquery.offput.ca/highlightFade)
 * (c) 2006 Blair Mitchelmore (offput.ca) blair@offput.ca
 */
eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('6.1D.f=q(B){k o=(B&&B.C==1E)?{u:B}:B||{};k d=6.f.N;k i=o[\'z\']||d[\'z\'];k a=o[\'A\']||d[\'A\'];k H={\'18\':q(s,e,t,c){5 p(s+(c/t)*(e-s))},\'1Q\':q(s,e,t,c){5 p(s+P.1R(((c/t)*1T)*(P.1M/1L))*(e-s))},\'1K\':q(s,e,t,c){5 p(s+(P.1U(c/t,2))*(e-s))}};k t=(o[\'v\']&&o[\'v\'].C==W)?o[\'v\']:H[o[\'v\']]||H[d[\'v\']]||H[\'18\'];h(d[\'v\']&&d[\'v\'].C==W)t=d[\'v\'];5 l.1a(q(){h(!l.4)l.4={};k e=(l.4[a])?l.4[a].n:6.f.Z(l,a)||[7,7,7];k c=6.f.J(o[\'u\']||o[\'1I\']||o[\'1k\']||d[\'u\']||[7,7,m]);k s=6.I(o[\'I\']||d[\'I\']);k r=o[\'Q\']||(l.4[a]&&l.4[a].L)?l.4[a].L:6.1e(l,a);h(o[\'n\']||d[\'n\'])r=6.f.T(e=6.f.J(o[\'n\']||d[\'n\']));h(1d o[\'Q\']!=\'16\')r=o[\'Q\'];h(l.4[a]&&l.4[a].K)X.17(l.4[a].K);l.4[a]={E:((s.1c)/i),z:i,D:0,u:c,n:e,L:r,A:a};6.f(l,a,o[\'1b\'],t)})};6.f=q(e,a,o,t){e.4[a].K=X.1f(q(){k 15=t(e.4[a].u[0],e.4[a].n[0],e.4[a].E,e.4[a].D);k 14=t(e.4[a].u[1],e.4[a].n[1],e.4[a].E,e.4[a].D);k 13=t(e.4[a].u[2],e.4[a].n[2],e.4[a].E,e.4[a].D);6(e).M(a,6.f.T([15,14,13]));h(e.4[a].D++>=e.4[a].E){6(e).M(a,e.4[a].L||\'\');X.17(e.4[a].K);e.4[a]=V;h(o&&o.C==W)o.1l(e)}},e.4[a].z)};6.f.N={u:[7,7,m],z:1j,I:1h,A:\'Y\'};6.f.J=q(c,d){k 8;h(c&&c.C==1g&&c.1i==3)5 c;h(8=/O\\(\\s*([0-9]{1,3})\\s*,\\s*([0-9]{1,3})\\s*,\\s*([0-9]{1,3})\\s*\\)/.F(c))5[p(8[1]),p(8[2]),p(8[3])];G h(8=/O\\(\\s*([0-9]+(?:\\.[0-9]+)?)\\%\\s*,\\s*([0-9]+(?:\\.[0-9]+)?)\\%\\s*,\\s*([0-9]+(?:\\.[0-9]+)?)\\%\\s*\\)/.F(c))5[U(8[1])*2.S,U(8[2])*2.S,U(8[3])*2.S];G h(8=/#([a-x-w-9]{2})([a-x-w-9]{2})([a-x-w-9]{2})/.F(c))5[p("y"+8[1]),p("y"+8[2]),p("y"+8[3])];G h(8=/#([a-x-w-9])([a-x-w-9])([a-x-w-9])/.F(c))5[p("y"+8[1]+8[1]),p("y"+8[2]+8[2]),p("y"+8[3]+8[3])];G 5 6.f.12(c)||d||V};6.f.T=q(a){5"O("+a.1J(",")+")"};6.f.Z=q(e,a,b){k s,t;b=b||19;t=a=a||6.f.N[\'A\'];1m{s=6(e).M(t||\'Y\');h((s!=\'\'&&s!=\'10\')||(e.1F.11()=="1G")||(!b&&e.4&&e.4[a]&&e.4[a].n))1H;t=19}1N(e=e.1S);h(!b&&e.4&&e.4[a]&&e.4[a].n)s=e.4[a].n;h(s==16||s==\'\'||s==\'10\')s=[7,7,7];5 6.f.J(s)};6.f.12=q(c){h(!c)5 V;1O(c.1P(/^\\s*|\\s*$/g,\'\').11()){j\'1s\':5[0,7,7];j\'1t\':5[0,0,0];j\'1r\':5[0,0,7];j\'1q\':5[7,0,7];j\'1n\':5[m,m,m];j\'1o\':5[0,m,0];j\'1p\':5[0,7,0];j\'1u\':5[m,0,0];j\'1v\':5[0,0,m];j\'1B\':5[m,m,0];j\'1C\':5[m,0,m];j\'1A\':5[7,0,0];j\'1z\':5[R,R,R];j\'1w\':5[0,m,m];j\'1x\':5[7,7,7];j\'1y\':5[7,7,0]}};',62,119,'||||highlighting|return|jQuery|255|result|||||||highlightFade||if||case|var|this|128|end||parseInt|function||||start|iterator|F0|fA|0x|interval|attr|settings|constructor|currentStep|steps|exec|else|ts|speed|getRGB|timer|orig|css|defaults|rgb|Math|final|192|55|asRGBString|parseFloat|null|Function|window|backgroundColor|getBaseValue|transparent|toLowerCase|checkColorName|newB|newG|newR|undefined|clearInterval|linear|false|each|complete|duration|typeof|curCSS|setInterval|Array|400|length|50|color|call|do|gray|green|lime|fuchsia|blue|aqua|black|maroon|navy|teal|white|yellow|silver|red|olive|purple|fn|String|tagName|body|break|colour|join|exponential|180|PI|while|switch|replace|sinusoidal|sin|parentNode|90|pow'.split('|'),0,{}))

function enableLightboxes( root )
{
  $('a[@rel*=lightbox]').lightBox();
  
  addMagnifyingGlass( root );
}

function addMagnifyingGlass( root )
{
  $('dl.productImages dt a img').after('<img class="superimpose" src="'+root+'media/img/magnifying-glass.gif" alt="Enlarge Image" />');
}
function removeMagnifyingGlass()
{
  $('img.superimpose').remove();
}

function createHelpTips()
{
  $('div.helpTip').each(function()
  {
    $(this).before('<span class="helpTipReveal">?</span>');
  });
}

function activateHelpTips()
{
  $('span.helpTipReveal').bind(
    'mouseover',function(){
      $('div#'+$(this).next().attr("id")).show();
    }
  ).bind(
    'mouseout',function(){
      $('div#'+$(this).next().attr("id")).hide();
    }
  );
}

function activateQuickFind( root )
{
  $('form[@id="filter"] select').change(function()
  {
    if($(this).attr('name') != 'orderBy') // Ignore change of order by select
    {
      var postValue = '';
      
      $('div[id="quickFind_container"]').find('select').each(function()
      {
        postValue += $(this).attr('name')+'='+$(this).attr('value')+';';
      });
      
      $.post(root+'quickfind/',
      {
        quickFind   : 'quickFind',
        postValue   : postValue
      },
      function(data) { $('div[@id="quickFind_container"]').html( data ); activateQuickFind( root ) });
    }
  });
}

$(document).ready(function()
{
  $('#nav').superfish({});
  
  $('input#keywords').focus(function()
  {
    if(this.value == 'Search')
	{
		this.value = '';
	}
  });
  
  $('input#keywords').blur(function()
  {
	if(this.value == '')
	{
		this.value = 'Search';
	}
  });
  
  // Carousel
  if($('#carousel').length)
  {
	$('div#carousel').carousel();
  }
  
  $('label.overlabel').overlabel();
  
  var root = deriveRoot();
  
  // Basket Functionality
  activateRemoveLinks( root );
  activateAddLinks( root );
  activateProductConfigurators( root );
  
  // Quick Find Functionality
  activateQuickFind( root );
  
  enableLightboxes( root );
  
  // Image Changer
  $('dl.productImages li a').hover(function(){
    removeMagnifyingGlass();
    var href = $(this).attr('href');
    var src  = $(this).find('img').attr('src');
    src = src.replace(/_thumb/,'');
    $('dl.productImages dt a').attr('href',href);
    $('dl.productImages dt img').attr('src',src);
    addMagnifyingGlass( root );
  },function(){});
  
  winOnResize(); // set initial position
  xAddEventListener(window,'resize',winOnResize,false);
  xAddEventListener(window,'scroll',winOnScroll,false);
  
  // Checkout
  if ( !$.browser.msie ) // IE won't play nice...
  {
    // Welcome Sign In
    if ( $('input#registeredN').is(':checked') )
    {
      $('form#checkoutWelcome span#hide').hide();
      $('form#checkoutWelcome input#password').hide();
      $('a#forgottenPass').hide();
    }
    $('input[@name="registered"]').change(function()
    {
      if ( $('input#registeredY').is(':checked') )
      {
        $('form#checkoutWelcome span#hide').show();
        $('form#checkoutWelcome input#password').show();
        $('form#checkoutWelcome li#passParent span.warning').show();
        $('a#forgottenPass').show();
      }
      else
      {
        $('form#checkoutWelcome span#hide').hide();
        $('form#checkoutWelcome input#password').hide();
        $('form#checkoutWelcome li#passParent span.warning').hide();
        $('a#forgottenPass').hide();
      }
    });
    
    // Payment Billing Address
    if ( $('input#billingSame').is(':checked') )
    {
      $('fieldset#newBilling').hide();
    }
    
    $('input[@name="billingAddr"]').change(function()
    {
      if ( $('input#billingSame').is(':checked') )
      {
        $('fieldset#newBilling').hide();
      }
      else
      {
        $('fieldset#newBilling').show();
      }
    });
  }
  
  // Form Help Tips
  createHelpTips();
  activateHelpTips();
  
  // Make Product Boxes Equal Height...
  $('ul.products').each(function()
  {
    var line_height = 0;
	
	$(this).find('div.desc').each(function()
    {
      if($(this).height() > line_height)
      {
        line_height = $(this).height();
      }
    });
    
    $(this).find('div.desc').each(function()
    {
	  if($(this).next()[0].tagName == 'H6' && line_height > $(this).height())
	  {
		$(this).next().css('marginTop',(line_height - $(this).height())+'px');
	  }
      $(this).css('height',line_height+'px');
    });
    
    var line_height = 0;
    
    $(this).find('form.add_to_basket').each(function()
    {
      if($(this).height() > line_height)
      {
        line_height = $(this).height();
      }
    });
    
    $(this).find('form.add_to_basket').each(function()
    {
      $(this).css('height',line_height+'px');
    });
  });
  
  if($.browser.msie) // Cannot vertically align images so add margin as required
  {
	$('ul.products div.image span img').each(function()
	{
		if(this.load && this.height < 150)
		{
			var margin_top = ((150 - this.height) / 2);
			$(this).css('marginTop',margin_top);
		}
	});
  }
});

function changeNav(id,src)
{
  var root = deriveRoot();
  $('img#'+id).attr("src",root+"media/img/nav/"+src);
}

/* 
 * CAROUSEL
 * 
 * Based upon:
 * jQuery Coda-Slider v1.1 - http://www.ndoherty.com/coda-slider
 * Copyright (c) 2007 Niall Doherty
 */
$.fn.carousel = function(settings)
{
  
  return this.each(function()
  {
    var container = $(this);
    
    //var slideHeight		= container.find("ul.carousel li").height();
    //var slideCount 		= container.find("ul.carousel li").size();
	
    //var carouselHeight	= slideHeight*slideCount;
	
    //container.find("div.carousel").css("height",carouselHeight);
    
	var cslide = 1;
    
    container.each(function(i)
    {
		$("li#feature1 a").click(function(){skipTo('1','true');return false;});
		$("li#feature2 a").click(function(){skipTo('2','true');return false;});
		$("li#feature3 a").click(function(){skipTo('3','true');return false;});
		$("li#feature4 a").click(function(){skipTo('4','true');return false;});
		
		function auto_slide()
		{
			if(!$('div#carousel').find('ul.control li a').hasClass('clicked'))
			{
				if($('li#feature1 a').hasClass('active') && $('li#feature2').length)
				{
					var next_slide = '2';
				}
				else if($('li#feature2 a').hasClass('active') && $('li#feature3').length)
				{
					var next_slide = '3';
				}
				else if($('li#feature3 a').hasClass('active') && $('li#feature4').length)
				{
					var next_slide = '4';
				}
				else
				{
					var next_slide = '1';
				}
				setTimeout(function()
				{
					skipTo(next_slide,'false');
					auto_slide();
				},4500);
			}
		}
		
		if($('li#feature2').length)
		{
			auto_slide();
		}
		else
		{
			$('ul.control').css('display','none');
		}
		
		function skipTo(slide,click)
		{
			if(click == 'true' || !$('div#carousel').find('ul.control li a').hasClass('clicked'))
			{
				//var cnt = -(slideHeight*(slide-1));
		        
				//$("ul.carousel").animate({ marginTop: cnt+"px" }, 750);
				
				$('li#feature1 a').removeClass('active');
		        $('li#feature2 a').removeClass('active');
		        $('li#feature3 a').removeClass('active');
		        $('li#feature4 a').removeClass('active');
		        
		        switch(slide)
		        {
		          case '1':
		            $('li#feature1 a').addClass('active');
					$('li.feature1').addClass('current');
					
					if($('li.feature2').hasClass('current'))
					{
						$('li.feature1').fadeIn('fast', function() { $('li.feature2').fadeOut('slow'); });
					}
					else if($('li.feature3').hasClass('current'))
					{
						$('li.feature1').fadeIn('fast', function() { $('li.feature3').fadeOut('slow'); });
					}
					else if($('li.feature4').hasClass('current'))
					{
						$('li.feature1').fadeIn('fast', function() { $('li.feature4').fadeOut('slow'); });
					}
					
					$('li.feature2').removeClass('current');
					$('li.feature3').removeClass('current');
					$('li.feature4').removeClass('current');
					
					if(click == 'true')
					{
						$('li#feature1 a').addClass('clicked');
					}
					
		            break;
					
		          case '2':
					
					if($('li.feature1').hasClass('current'))
					{
						$('li.feature2').fadeIn('slow', function() { $('li.feature1').fadeOut('slow'); });
					}
					else if($('li.feature3').hasClass('current'))
					{
						$('li.feature2').fadeIn('fast', function() { $('li.feature3').fadeOut('slow'); });
					}
					else if($('li.feature4').hasClass('current'))
					{
						$('li.feature2').fadeIn('fast', function() { $('li.feature4').fadeOut('slow'); });
					}
					
		            $('li#feature2 a').addClass('active');
					$('li.feature2').addClass('current');
					
					$('li.feature1').removeClass('current');
					$('li.feature3').removeClass('current');
					$('li.feature4').removeClass('current');
					
					if(click == 'true')
					{
						$('li#feature2 a').addClass('clicked');
					}
					
		            break;
					
		          case '3':
					
					if($('li.feature1').hasClass('current'))
					{
						$('li.feature3').fadeIn('slow', function() { $('li.feature1').fadeOut('slow'); });
					}
					else if($('li.feature2').hasClass('current'))
					{
						$('li.feature3').fadeIn('slow', function() { $('li.feature2').fadeOut('slow'); });
					}
					else if($('li.feature4').hasClass('current'))
					{
						$('li.feature3').fadeIn('fast', function() { $('li.feature4').fadeOut('slow'); });
					}
					
		            $('li#feature3 a').addClass('active');
					$('li.feature3').addClass('current');
					
					$('li.feature1').removeClass('current');
					$('li.feature2').removeClass('current');
					$('li.feature4').removeClass('current');
					
					if(click == 'true')
					{
						$('li#feature3 a').addClass('clicked');
					}
		            break;
					
		          case '4':
					
					if($('li.feature1').hasClass('current'))
					{
						$('li.feature4').fadeIn('slow', function() { $('li.feature1').fadeOut('slow'); });
					}
					else if($('li.feature2').hasClass('current'))
					{
						$('li.feature4').fadeIn('slow', function() { $('li.feature2').fadeOut('slow'); });
					}
					else if($('li.feature3').hasClass('current'))
					{
						$('li.feature4').fadeIn('fast', function() { $('li.feature3').fadeOut('slow'); });
					}
					
		            $('li#feature4 a').addClass('active');
					$('li.feature4').addClass('current');
					
					$('li.feature1').removeClass('current');
					$('li.feature2').removeClass('current');
					$('li.feature3').removeClass('current');
					
					if(click == 'true')
					{
						$('li#feature4 a').addClass('clicked');
					}
		            break;
		        }
			}
		}
    });
  });
};
