/*
function turnMenusOff() {
	var divs, i, j;
	$("#main_menu > li > a").each(function(){
		if ($(this).hasClass("menuOn")) {
			$("div", $(this).parent()).each(function(){
				$(this).addClass = "divOff";
			});
			$(this).addClass = "menuOff";
		}
	});
}

function turnMenuOn(menuItem) {
	$("div", $(menuItem).parent()).each(function(){
		$(this).addClass = "divOn";
	});
	menuItem.addClass = "menuOn";
}

function accessibleMenu() {
	$("#main_menu > li > a").each(function(){
		if ($(this).hasClass("menuOff")) {
			this.onfocus = function() {
				turnMenusOff();
				turnMenuOn(this);
			}
			this.onmouseover = function() {
				turnMenusOff();
				turnMenuOn(this);
			}
			this.onmouseout = function() {
				turnMenusOff();
			}
		}
		
	});
}


// Controls the behavior of the search box in the menu navigation
function controlSearchBox() {
	var searchBox = document.getElementById("search_link");
	var searchTxtField = $("keywords").get(0);
	
	function showSearch() {
		var searchLi = document.getElementById("search_link");
		var searchDiv = document.getElementById("search_link").getElementsByTagName("div")[0];
		
		searchLi.style.background = "#f0f0f0 url('/source/images/search_icon.gif') no-repeat 32px -39px";
		searchDiv.style.display = "block";
	}
	function conditionalHide() {
		if (!searchLocked) {
			hideSearch();
		}
	}
	
	searchBox.onfocus = showSearch;
	searchBox.onmouseover = showSearch;
	searchBox.onmouseout = conditionalHide;
}
function lockSearch() {
	searchLocked = true;
}
function hideSearch() {
	var searchLi = document.getElementById("search_link");
	var searchDiv = document.getElementById("search_link").getElementsByTagName("div")[0];
	
	searchLi.style.background = "transparent url('/source/images/search_icon.gif') no-repeat 32px 2px";
	searchDiv.style.display = "none";
	searchLocked = false;
}

*/

// Function that toggles between the families and categories tabs (for the carousel)
function alterTabClass(tabName) {
	if (tabName.id == "type_tab") {
		tabOn =	document.getElementById("type_tab");
		bgOn = document.getElementById("typeBg");
		carOn = document.getElementById("type_carousel");
		numOn = document.getElementById("typeNumbers");
		
		tabOff = document.getElementById("collection_tab");
		bgOff = document.getElementById("collectionBg");
		carOff = document.getElementById("collection_carousel");
		numOff = document.getElementById("collectionNumbers");
		
		tabOff.className = "tab_off";
		bgOff.className = "tab_off png";
		carOff.className = "car_off";
		numOff.className = "num_off";
		
		tabOn.className = "tab_on"; 
		bgOn.className = "tab_on png";
		carOn.className = "car_on";
		numOn.className = "num_on";
		document.getElementById("type-nav").style.display = "block";
		document.getElementById("collection-nav").style.display = "none";
		
	} else {
		tabOn =	document.getElementById("collection_tab");
		bgOn = document.getElementById("collectionBg");
		carOn = document.getElementById("collection_carousel");
		numOn = document.getElementById("collectionNumbers");
		
		tabOff = document.getElementById("type_tab");
		bgOff = document.getElementById("typeBg");
		carOff = document.getElementById("type_carousel");
		numOff = document.getElementById("typeNumbers");
		
		tabOff.className = "tab_off";
		bgOff.className = "tab_off png";
		carOff.className = "car_off";
		numOff.className = "num_off";
		
		tabOn.className = "tab_on";
		bgOn.className = "tab_on png";
		carOn.className = "car_on";
		numOn.className = "num_on";
		document.getElementById("type-nav").style.display = "none";
		document.getElementById("collection-nav").style.display = "block";
	}
}


// Bazaar voice functions
function toggle(){
	var revCont = document.getElementById('fekkaibvframe');
	var BVwrap = document.getElementById('bv-wrapper');
	var BVtab = document.getElementById('bv-tab');
	if (revCont.style.display == 'none') {
		revCont.style.display = 'block';
		BVwrap.style.display = 'none';
		BVtab.style.backgroundImage = 'url(/source/images/bazaarvoice/review-open.gif)';
	} else {
		revCont.style.display = 'none';
		BVwrap.style.display = 'block';
		BVtab.style.backgroundImage = 'url(/source/images/bazaarvoice/review-closed.gif)';
	}
}
function bvOpenReview(url) {
	var frm = document.getElementById("iframe");
	var revCont = document.getElementById('fekkaibvframe');

	if (oBVFrameURL == "") oBVFrameURL = frm.src;
	if (url.substr(url.length - 8, 8) == "#reviews") {
		url = oBVFrameURL; 
	} 

	if (revCont.style.display != "block") toggle();

	frm.src = url;
	frm.focus();
	return false;
}
function ratingsDisplayed(totalReviewsCount, avgRating, ratingsOnlyReviewCount, recommendPercentage, productID)
{
    if (totalReviewsCount > 0) {
        var bvRevCntr = document.getElementById("BVReviewsContainer");
        if (bvRevCntr) { bvRevCntr.style.display = "block"; }
    }
    // Other custom items leveraging these values.
    // TODO: insert Web Analytics tracking here
}
function pageChanged(pageName, pageStatus) {		
	// TODO: place web analytics tagging code here to track submission process
}


// Apply alphaImageLoader filter to specific PNG images
function applyImageFilter() {
	if (!/MSIE (5\.5|6)/.test(navigator.userAgent))		// If the browser is not IE6 or below, then return  
		return;
	var images = document.getElementsByTagName('img');
	for (var i=0; i < images.length; i++) {
		var imgClass = images[i].className;
		if (imgClass.indexOf("prodPng") >= 0 || imgClass.indexOf("bulletPng") >= 0) {
			if (imgClass.indexOf("prodPng") >= 0) {
				var realSrc = images[i].src;
				images[i].src = "/source/images/blank.gif";
				images[i].style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src=" + realSrc + ", sizingMethod='scale')";
			} else {	
				var realSrc = images[i].src;
				images[i].src = "/source/images/blank.gif";
				images[i].style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/source/images/footer_bullet.png', sizingMethod='image')";
			}
		}
	}
}

/**************************************
		BEGIN CODE FOR POPUP BOX
***************************************/

function setAction(formObj) {
	formObj.action = "https://shop.fekkai.com/addtocart.aspx?productid=" + formObj.elements[0].value + "&variantid=" + formObj.elements[1].value + "&quantity=" + formObj.elements[2].value;
}

function showCheckOutButtons() {
	if (parent.parent.document.getElementById('GB_btndiv_right'))
		parent.parent.document.getElementById('GB_btndiv_right').className = "GB_btndiv on";
	else if (parent.parent.document.getElementById('GB_btndiv_left'))
		parent.parent.document.getElementById('GB_btndiv_left').className = "GB_btndiv on";
	else if (parent.parent.document.getElementById('GB_btndiv_center'))
		parent.parent.document.getElementById('GB_btndiv_center').className = "GB_btndiv on";
	else
		; 
	/* If the overlay window was closed, then the element referenced will not exist anymore */
}
function showErrorMsg() {
	if (parent.parent.document.getElementById('GB_errordiv_right'))
		parent.parent.document.getElementById('GB_errordiv_right').className = "GB_errordiv error-on";
	else if (parent.parent.document.getElementById('GB_errordiv_left'))
		parent.parent.document.getElementById('GB_errordiv_left').className = "GB_errordiv error-on";
	else if (parent.parent.document.getElementById('GB_errordiv_center'))
		parent.parent.document.getElementById('GB_errordiv_center').className = "GB_errordiv error-on";
	else
		alert('Error Message container not found');
}

function hideErrorMsg() {
	if ((parent.parent.document.getElementById('GB_errordiv_right')) && 
		parent.parent.document.getElementById('GB_errordiv_right').className == "GB_errordiv error-on" )
		parent.parent.document.getElementById('GB_errordiv_right').className = "GB_errordiv error-off";
	else if ((parent.parent.document.getElementById('GB_errordiv_left')) && 
		parent.parent.document.getElementById('GB_errordiv_left').className == "GB_errordiv error-on" )
		parent.parent.document.getElementById('GB_errordiv_left').className = "GB_errordiv error-off";
	else if ((parent.parent.document.getElementById('GB_errordiv_center')) && 
		parent.parent.document.getElementById('GB_errordiv_center').className == "GB_errordiv error-on" )
		parent.parent.document.getElementById('GB_errordiv_center').className = "GB_errordiv error-off";
	else 
		return true;
}

// Allow User to scroll item quantity up and Down(Limited to 15)
function scrollValue(formObj, dir) {
	var curValue = formObj.elements[2].value;
	if(curValue != 15){
		if(dir == "up"){
			curValue++;
		}
	}
	if(curValue != 1){
		if(dir == "down"){
			curValue--;
		}
	}
	
	formObj.elements[2].value = curValue;
}

// Check scroll limits(0-15)
function checkLimits(formObj) {
	var val = formObj.elements[2].value;
	if(isNaN(val)){
		formObj.elements[2].value = 1;
	}
	
	if(val < 1 || val == ""){
		formObj.elements[2].value = 1;
	}
	
	if(val > 15){
		formObj.elements[2].value = 15;
	}
}
/**************************************
		END CODE FOR POPUP BOX
***************************************/

/**************************************
		BEGIN CODE FOR CAROUSEL
***************************************/
$(document).ready(function(){

	var increment = 882;	// Move this amount with each click
	var duration = 1000;	// Duration of the scroll animation
	
	//Current Page
	var colCurrent = $("#pgCollAct").html();
	var typeCurrent = $("#pgTypeAct").html();
	
	//Max Pages Allowed
	var colMax = 3;		// Collection pages
	var typeMax = 2;	// Type pages
	
	//Button Handlers
    $("#typeLeft").click(function(){
    	killButtons('t');
    	typeCurrent--;
     	 $("#typeSlide").animate({"left": ("+=" + increment + "px")}, duration,
     	 	function(){
     	 		$('#pgTypeAct').html(typeCurrent);
     	 		if(typeCurrent == 1){
     	 			$("#typeLeft").get(0).disabled = true;
     	 			$("#typeRight").get(0).disabled = false;
     	 		}else{
     	 			$("#typeLeft").get(0).disabled = false;
     	 		}
     	 	}
     	 ); 
 	});
    $("#typeRight").click(function(){
    	killButtons('t');
    	typeCurrent++;
     	 $("#typeSlide").animate({"left": ("-=" + increment + "px")}, duration,
     	 	function(){	
     	 		$('#pgTypeAct').html(typeCurrent);
     	 	    if(typeCurrent == typeMax){
     	 			$("#typeRight").get(0).disabled = true;
     	 			$("#typeLeft").get(0).disabled = false;
     	 		}else{
     	 			$("#typeRight").get(0).disabled = false;
     	 		}
     	 	}
     	 ); 	
    });
    
    
    $("#colLeft").click(function(){
    	killButtons('c');
    	colCurrent--;
      $("#collectionSlide").animate({"left": ("+=" + increment + "px")}, duration,
     	 	function(){	
     	 		$('#pgCollAct').html(colCurrent);
     	 	 	if(colCurrent == 1){
     	 			$("#colLeft").get(0).disabled = true;
     	 			$("#colRight").get(0).disabled = false;
     	 		}else{
     	 			$("#colLeft").get(0).disabled = false;
     	 			$("#colRight").get(0).disabled = false;
     	 		}
     	 	}
  		);
    });

    $("#colRight").click(function(){
    	killButtons('c');
    	colCurrent++;
      $("#collectionSlide").animate({"left": ("-=" + increment + "px")}, duration,
           	 function(){	
     	 		$('#pgCollAct').html(colCurrent);
     	 		if(colCurrent == colMax){
     	 			$("#colRight").get(0).disabled = true;
     	 			$("#colLeft").get(0).disabled = false;
     	 		}else{
     	 			$("#colRight").get(0).disabled = false;
     	 			$("#colLeft").get(0).disabled = false;
     	 		}
     	 	}
  		);
    });
    
	//Disables Buttons while scrolling    
	function killButtons(val){
		switch(val){
		case 'c':
			$("#colLeft").get(0).disabled = true;
			$("#colRight").get(0).disabled = true;
		break;
		
		case 't':
			$("#typeLeft").get(0).disabled = true;
			$("#typeRight").get(0).disabled = true;
		break;
		}
	}
	
	//Check if this Page has a Carousel    
	if($("#scroll_pane").html() !== null) {
		
		//By default, disable the Left (Previous) buttons / Enable the Right (Next) buttons 
		$("#typeRight").get(0).disabled = false;
		$("#colRight").get(0).disabled = false;
		$("#typeLeft").get(0).disabled = true;
		$("#colLeft").get(0).disabled = true;

		// If the collection tab is selected then, scroll to the appropriate page if necessary
		if ($("#collection_tab.tab_on").length) {
			var actPage = colCurrent - 1; 
			if ( actPage > 0) {
				$("#collectionSlide").animate({"left": ("-=" + (increment * actPage) + "px")}, 1,
					function(){	
						if(colCurrent == colMax){
							$("#colRight").get(0).disabled = true;
							$("#colLeft").get(0).disabled = false;
						}else{
							$("#colRight").get(0).disabled = false;
							$("#colLeft").get(0).disabled = false;
						}
					}
				);
			}
		}
	
		// If the type tab is selected then, scroll to the appropriate page if necessary
		if ($("#type_tab.tab_on").length) {
			var actPage = typeCurrent - 1; 
			if ( actPage > 0) {
				$("#typeSlide").animate({"left": ("-=" + (increment * actPage) + "px")}, 1,
					function(){	
					if(typeCurrent == typeMax){
							$("#typeRight").get(0).disabled = true;
							$("#typeLeft").get(0).disabled = false;
						}else{
							$("#typeRight").get(0).disabled = false;
							$("#typeLeft").get(0).disabled = false;
						}
					}
				);
			}
		}
		
	}
	$("#print-offer").click(function(e){
		window.print();
		e.preventDefault();
	});

});



/**************************************
		END CODE FOR CAROUSEL
***************************************/
/*******************************
		   SCROLL BAR
*******************************/
(function($) {
var fixedWidth = 840;
$.jScrollPane = {
	active : []
};
$.fn.jScrollPane = function(settings)
{
	settings = $.extend({}, $.fn.jScrollPane.defaults, settings);

	var rf = function() { return false; };
	
	return this.each(
		function()
		{
			var $this = $(this);
			// Switch the element's overflow to hidden to ensure we get the size of the element without the scrollbars [http://plugins.jquery.com/node/1208]
			$this.css('overflow', 'hidden');
			var paneEle = this;
			
			if ($(this).parent().is('.jScrollPaneContainer')) {
				var currentScrollPosition = settings.maintainPosition ? $this.position().top : 0;
				var $c = $(this).parent();
				var paneWidth = $c.innerWidth();
				var paneHeight = $c.outerHeight();
				var trackHeight = paneHeight;
				$('>.jScrollPaneTrack, >.jScrollArrowUp, >.jScrollArrowDown', $c).remove();
				$this.css({'top':0});
			} else {
				var currentScrollPosition = 0;
				this.originalPadding = $this.css('paddingTop') + ' ' + $this.css('paddingRight') + ' ' + $this.css('paddingBottom') + ' ' + $this.css('paddingLeft');
				this.originalSidePaddingTotal = (parseInt($this.css('paddingLeft')) || 0) + (parseInt($this.css('paddingRight')) || 0);
				var paneWidth = $this.innerWidth();
				var paneHeight = $this.innerHeight();
				var trackHeight = paneHeight;
				$this.wrap(
					$('<div></div>').attr(
						{'className':'jScrollPaneContainer'}
					).css(
						{
							'height':paneHeight+'px', 
							'width': fixedWidth+'px'
						}
					).attr(
						'tabindex', 
						settings.tabIndex
					)
				);
				// deal with text size changes (if the jquery.em plugin is included)
				// and re-initialise the scrollPane so the track maintains the
				// correct size
				$(document).bind(
					'emchange', 
					function(e, cur, prev)
					{
						$this.jScrollPane(settings);
					}
				);
				
			}
			
			if (settings.reinitialiseOnImageLoad) {
				// code inspired by jquery.onImagesLoad: http://plugins.jquery.com/project/onImagesLoad
				// except we re-initialise the scroll pane when each image loads so that the scroll pane is always up to size...
				// TODO: Do I even need to store it in $.data? Is a local variable here the same since I don't pass the reinitialiseOnImageLoad when I re-initialise?
				var $imagesToLoad = $.data(paneEle, 'jScrollPaneImagesToLoad') || $('img', $this);
				var loadedImages = [];
				
				if ($imagesToLoad.length) {
					$imagesToLoad.each(function(i, val)	{
						$(this).bind('load readystatechange', function() {
							if($.inArray(i, loadedImages) == -1){ //don't double count images
								loadedImages.push(val); //keep a record of images we've seen
								$imagesToLoad = $.grep($imagesToLoad, function(n, i) {
									return n != val;
								});
								$.data(paneEle, 'jScrollPaneImagesToLoad', $imagesToLoad);
								var s2 = $.extend(settings, {reinitialiseOnImageLoad:false});
								$this.jScrollPane(s2); // re-initialise
							}
						}).each(function(i, val) {
							if(this.complete || this.complete===undefined) { 
								//needed for potential cached images
								this.src = this.src; 
							} 
						});
					});
				};
			}

			var p = this.originalSidePaddingTotal;
			var realPaneWidth = paneWidth - settings.scrollbarWidth - settings.scrollbarMargin - p;

			var cssToApply = {
				'height':'auto',
				'width': realPaneWidth + 'px'
			}

			if(settings.scrollbarOnLeft) {
				cssToApply.paddingLeft = settings.scrollbarMargin + settings.scrollbarWidth + 'px';
			} else {
				cssToApply.paddingRight = settings.scrollbarMargin + 'px';
			}

			$this.css(cssToApply);

			var contentHeight = $this.outerHeight();
			var percentInView = paneHeight / contentHeight;

			if (percentInView < .99) {
				var $container = $this.parent();
				$container.append(
					$('<div></div>').attr({'className':'jScrollPaneTrack'}).css({'width':settings.scrollbarWidth+'px'}).append(
						$('<div></div>').attr({'className':'jScrollPaneDrag'}).css({'width':settings.scrollbarWidth+'px'}).append(
							$('<div></div>').attr({'className':'jScrollPaneDragTop'}).css({'width':settings.scrollbarWidth+'px'}),
							$('<div></div>').attr({'className':'jScrollPaneDragBottom'}).css({'width':settings.scrollbarWidth+'px'})
						)
					)
				);
				
				var $track = $('>.jScrollPaneTrack', $container);
				var $drag = $('>.jScrollPaneTrack .jScrollPaneDrag', $container);
				
				
				var currentArrowDirection;
				var currentArrowTimerArr = [];// Array is used to store timers since they can stack up when dealing with keyboard events. This ensures all timers are cleaned up in the end, preventing an acceleration bug.
				var currentArrowInc;
				var whileArrowButtonDown = function() 
				{
					if (currentArrowInc > 4 || currentArrowInc % 4 == 0) {
						positionDrag(dragPosition + currentArrowDirection * mouseWheelMultiplier);
					}
					currentArrowInc++;
				};

				if (settings.enableKeyboardNavigation) {
					$container.bind(
						'keydown.jscrollpane',
						function(e) 
						{
							switch (e.keyCode) {
								case 38: //up
									currentArrowDirection = -1;
									currentArrowInc = 0;
									whileArrowButtonDown();
									currentArrowTimerArr[currentArrowTimerArr.length] = setInterval(whileArrowButtonDown, 100);
									return false;
								case 40: //down
									currentArrowDirection = 1;
									currentArrowInc = 0;
									whileArrowButtonDown();
									currentArrowTimerArr[currentArrowTimerArr.length] = setInterval(whileArrowButtonDown, 100);
									return false;
								case 33: // page up
								case 34: // page down
									// TODO
									return false;
								default:
							}
						}
					).bind(
						'keyup.jscrollpane',
						function(e) 
						{
							if (e.keyCode == 38 || e.keyCode == 40) {
								for (var i = 0; i < currentArrowTimerArr.length; i++) {
									clearInterval(currentArrowTimerArr[i]);
								}
								return false;
							}
						}
					);
				}

				if (settings.showArrows) {
					
					var currentArrowButton;
					var currentArrowInterval;

					var onArrowMouseUp = function(event)
					{
						$('html').unbind('mouseup', onArrowMouseUp);
						currentArrowButton.removeClass('jScrollActiveArrowButton');
						clearInterval(currentArrowInterval);
					};
					var onArrowMouseDown = function() {
						$('html').bind('mouseup', onArrowMouseUp);
						currentArrowButton.addClass('jScrollActiveArrowButton');
						currentArrowInc = 0;
						whileArrowButtonDown();
						currentArrowInterval = setInterval(whileArrowButtonDown, 100);
					};
					$container
						.append(
							$('<a></a>')
								.attr({'href':'javascript:;', 'className':'jScrollArrowUp', 'tabindex':-1})
								.css({'width':settings.scrollbarWidth+'px'})
								.html('Scroll up')
								.bind('mousedown', function()
								{
									currentArrowButton = $(this);
									currentArrowDirection = -1;
									onArrowMouseDown();
									this.blur();
									return false;
								})
								.bind('click', rf),
							$('<a></a>')
								.attr({'href':'javascript:;', 'className':'jScrollArrowDown', 'tabindex':-1})
								.css({'width':settings.scrollbarWidth+'px'})
								.html('Scroll down')
								.bind('mousedown', function()
								{
									currentArrowButton = $(this);
									currentArrowDirection = 1;
									onArrowMouseDown();
									this.blur();
									return false;
								})
								.bind('click', rf)
						);
					var $upArrow = $('>.jScrollArrowUp', $container);
					var $downArrow = $('>.jScrollArrowDown', $container);
					if (settings.arrowSize) {
						trackHeight = paneHeight - settings.arrowSize - settings.arrowSize;
						$track
							.css({'height': trackHeight+'px', top:settings.arrowSize+'px'})
					} else {
						var topArrowHeight = $upArrow.height();
						settings.arrowSize = topArrowHeight;
						trackHeight = paneHeight - topArrowHeight - $downArrow.height();
						$track
							.css({'height': trackHeight+'px', top:topArrowHeight+'px'})
					}
				}
				
				var $pane = $(this).css({'position':'absolute', 'overflow':'visible'});
				
				var currentOffset;
				var maxY;
				var mouseWheelMultiplier;
				// store this in a seperate variable so we can keep track more accurately than just updating the css property..
				var dragPosition = 0;
				var dragMiddle = percentInView*paneHeight/2;
				
				// pos function borrowed from tooltip plugin and adapted...
				var getPos = function (event, c) {
					var p = c == 'X' ? 'Left' : 'Top';
					return event['page' + c] || (event['client' + c] + (document.documentElement['scroll' + p] || document.body['scroll' + p])) || 0;
				};
				
				var ignoreNativeDrag = function() {	return false; };
				
				var initDrag = function()
				{
					ceaseAnimation();
					currentOffset = $drag.offset(false);
					currentOffset.top -= dragPosition;
					maxY = trackHeight - $drag[0].offsetHeight;
					mouseWheelMultiplier = 2 * settings.wheelSpeed * maxY / contentHeight;
				};
				
				var onStartDrag = function(event)
				{
					initDrag();
					dragMiddle = getPos(event, 'Y') - dragPosition - currentOffset.top;
					$('html').bind('mouseup', onStopDrag).bind('mousemove', updateScroll);
					if ($.browser.msie) {
						$('html').bind('dragstart', ignoreNativeDrag).bind('selectstart', ignoreNativeDrag);
					}
					return false;
				};
				var onStopDrag = function()
				{
					$('html').unbind('mouseup', onStopDrag).unbind('mousemove', updateScroll);
					dragMiddle = percentInView*paneHeight/2;
					if ($.browser.msie) {
						$('html').unbind('dragstart', ignoreNativeDrag).unbind('selectstart', ignoreNativeDrag);
					}
				};
				var positionDrag = function(destY)
				{
					destY = destY < 0 ? 0 : (destY > maxY ? maxY : destY);
					dragPosition = destY;
					$drag.css({'top':destY+'px'});
					var p = destY / maxY;
					$this.data('jScrollPanePosition', (paneHeight-contentHeight)*-p);
					$pane.css({'top':((paneHeight-contentHeight)*p) + 'px'});
					$this.trigger('scroll');
					if (settings.showArrows) {
						$upArrow[destY == 0 ? 'addClass' : 'removeClass']('disabled');
						$downArrow[destY == maxY ? 'addClass' : 'removeClass']('disabled');
					}
				};
				var updateScroll = function(e)
				{
					positionDrag(getPos(e, 'Y') - currentOffset.top - dragMiddle);
				};
				
				var dragH = Math.max(Math.min(percentInView*(paneHeight-settings.arrowSize*2), settings.dragMaxHeight), settings.dragMinHeight);
				
				$drag.css(
					{'height':dragH+'px'}
				).bind('mousedown', onStartDrag);
				
				var trackScrollInterval;
				var trackScrollInc;
				var trackScrollMousePos;
				var doTrackScroll = function()
				{
					if (trackScrollInc > 8 || trackScrollInc%4==0) {
						positionDrag((dragPosition - ((dragPosition - trackScrollMousePos) / 2)));
					}
					trackScrollInc ++;
				};
				var onStopTrackClick = function()
				{
					clearInterval(trackScrollInterval);
					$('html').unbind('mouseup', onStopTrackClick).unbind('mousemove', onTrackMouseMove);
				};
				var onTrackMouseMove = function(event)
				{
					trackScrollMousePos = getPos(event, 'Y') - currentOffset.top - dragMiddle;
				};
				var onTrackClick = function(event)
				{
					initDrag();
					onTrackMouseMove(event);
					trackScrollInc = 0;
					$('html').bind('mouseup', onStopTrackClick).bind('mousemove', onTrackMouseMove);
					trackScrollInterval = setInterval(doTrackScroll, 100);
					doTrackScroll();
					return false;
				};
				
				$track.bind('mousedown', onTrackClick);
				
				$container.bind(
					'mousewheel',
					function (event, delta) {
						initDrag();
						ceaseAnimation();
						var d = dragPosition;
						positionDrag(dragPosition - delta * mouseWheelMultiplier);
						var dragOccured = d != dragPosition;
						return !dragOccured;
					}
				);

				var _animateToPosition;
				var _animateToInterval;
				function animateToPosition()
				{
					var diff = (_animateToPosition - dragPosition) / settings.animateStep;
					if (diff > 1 || diff < -1) {
						positionDrag(dragPosition + diff);
					} else {
						positionDrag(_animateToPosition);
						ceaseAnimation();
					}
				}
				var ceaseAnimation = function()
				{
					if (_animateToInterval) {
						clearInterval(_animateToInterval);
						delete _animateToPosition;
					}
				};
				var scrollTo = function(pos, preventAni)
				{
					if (typeof pos == "string") {
						$e = $(pos, $this);
						if (!$e.length) return;
						pos = $e.offset().top - $this.offset().top;
					}
					$container.scrollTop(0);
					ceaseAnimation();
					var maxScroll = contentHeight - paneHeight;
					pos = pos > maxScroll ? maxScroll : pos;
					$this.data('jScrollPaneMaxScroll', maxScroll);
					var destDragPosition = pos/maxScroll * maxY;
					if (preventAni || !settings.animateTo) {
						positionDrag(destDragPosition);
					} else {
						_animateToPosition = destDragPosition;
						_animateToInterval = setInterval(animateToPosition, settings.animateInterval);
					}
				};
				$this[0].scrollTo = scrollTo;
				
				$this[0].scrollBy = function(delta)
				{
					var currentPos = -parseInt($pane.css('top')) || 0;
					scrollTo(currentPos + delta);
				};
				
				initDrag();
				
				scrollTo(-currentScrollPosition, true);
			
				// Deal with it when the user tabs to a link or form element within this scrollpane
				$('*', this).bind(
					'focus',
					function(event)
					{
						var $e = $(this);
						
						// loop through parents adding the offset top of any elements that are relatively positioned between
						// the focused element and the jScrollPaneContainer so we can get the true distance from the top
						// of the focused element to the top of the scrollpane...
						var eleTop = 0;
						
						while ($e[0] != $this[0]) {
							eleTop += $e.position().top;
							$e = $e.offsetParent();
						}
						
						var viewportTop = -parseInt($pane.css('top')) || 0;
						var maxVisibleEleTop = viewportTop + paneHeight;
						var eleInView = eleTop > viewportTop && eleTop < maxVisibleEleTop;
						if (!eleInView) {
							var destPos = eleTop - settings.scrollbarMargin;
							if (eleTop > viewportTop) { // element is below viewport - scroll so it is at bottom.
								destPos += $(this).height() + 15 + settings.scrollbarMargin - paneHeight;
							}
							scrollTo(destPos);
						}
					}
				)
				
				
				if (location.hash) {
					setTimeout(function() {scrollTo(location.hash);}, $.browser.safari ? 100 : 0);
				}
				
				// use event delegation to listen for all clicks on links and hijack them if they are links to
				// anchors within our content...
				$(document).bind(
					'click',
					function(e)
					{
						$target = $(e.target);
						if ($target.is('a')) {
							var h = $target.attr('href');
							if (h && h.substr(0, 1) == '#') {
								setTimeout(function() {scrollTo(h, !settings.animateToInternalLinks);}, $.browser.safari ? 100 : 0);
							}
						}
					}
				); 
				
				// Deal with dragging and selecting text to make the scrollpane scroll...
				function onSelectScrollMouseDown(e)
				{
				   $(document).bind('mousemove.jScrollPaneDragging', onTextSelectionScrollMouseMove);
				   $(document).bind('mouseup.jScrollPaneDragging',   onSelectScrollMouseUp);
				  
				}
				
				var textDragDistanceAway;
				var textSelectionInterval;
				
				function onTextSelectionInterval()
				{
					direction = textDragDistanceAway < 0 ? -1 : 1;
					$this[0].scrollBy(textDragDistanceAway / 2);
				}

				function clearTextSelectionInterval()
				{
					if (textSelectionInterval) {
						clearInterval(textSelectionInterval);
						textSelectionInterval = undefined;
					}
				}
				
				function onTextSelectionScrollMouseMove(e)
				{
					var offset = $this.parent().offset().top;
					var maxOffset = offset + paneHeight;
					var mouseOffset = getPos(e, 'Y');
					textDragDistanceAway = mouseOffset < offset ? mouseOffset - offset : (mouseOffset > maxOffset ? mouseOffset - maxOffset : 0);
					if (textDragDistanceAway == 0) {
						clearTextSelectionInterval();
					} else {
						if (!textSelectionInterval) {
							textSelectionInterval  = setInterval(onTextSelectionInterval, 100);
						}
					}
				}

				function onSelectScrollMouseUp(e)
				{
				   $(document)
					  .unbind('mousemove.jScrollPaneDragging')
					  .unbind('mouseup.jScrollPaneDragging');
				   clearTextSelectionInterval();
				}

				$container.bind('mousedown.jScrollPane', onSelectScrollMouseDown);

				
				$.jScrollPane.active.push($this[0]);
				
			} else {
				$this.css(
					{
						'height':paneHeight+'px',
						'width':paneWidth-this.originalSidePaddingTotal+'px',
						'padding':this.originalPadding
					}
				);
				// clean up listeners
				$this.parent().unbind('mousewheel').unbind('mousedown.jScrollPane').unbind('keydown.jscrollpane').unbind('keyup.jscrollpane');
			}
			
		}
	)
};

$.fn.jScrollPaneRemove = function()
{
	$(this).each(function()
	{
		$this = $(this);
		var $c = $this.parent();
		if ($c.is('.jScrollPaneContainer')) {
			$this.css(
				{
					'top':'',
					'height':'',
					'width':'',
					'padding':'',
					'overflow':'',
					'position':''
				}
			);
			$c.after($this).remove();
		}
	});
}

$.fn.jScrollPane.defaults = {
	scrollbarWidth : 10,
	scrollbarMargin : 5,
	wheelSpeed : 18,
	showArrows : false,
	arrowSize : 0,
	animateTo : false,
	dragMinHeight : 1,
	dragMaxHeight : 99999,
	animateInterval : 100,
	animateStep: 3,
	maintainPosition: true,
	scrollbarOnLeft: false,
	reinitialiseOnImageLoad: false,
	tabIndex : 0,
	enableKeyboardNavigation: true,
	animateToInternalLinks: false
};

// clean up the scrollTo expandos
$(window)
	.bind('unload', function() {
		var els = $.jScrollPane.active; 
		for (var i=0; i<els.length; i++) {
			els[i].scrollTo = els[i].scrollBy = null;
		}
	}
);

})(jQuery);




$(function()
{
	//Check if this Page has a Carousel    
	if($(".makeScroll").html() !== null) {
		//$('.makeScroll').jScrollPane({scrollbarWidth:8});
	}
	
	//Apply sIFR
	//if (typeof sIFR !== 'function') sIFRreplace();
	
	// Image Filter
	applyImageFilter();
	
	// Primary Navigation
	//accessibleMenu();
	//controlSearchBox();
});
