var $j = jQuery.noConflict();
var preload = Array();
var loaded = 0;

var carouselIndex = 0;
     
$j(document).ready(function(){
	initLanguages();
	initFades("a.scroll", 0.8);
	initFades(".tpl_4 .carousel li", 0.55);
	initNavigation();
	initFadingRollovers("#navigate .navigation a[class!=active], #footlinks a, #lang_relative a");
	initActiveStates("#navigate .navigation a.active");
	initForms();
	initCarousels();
	initRetail();
});

function initStoreCarousels(){
	$j(".carousel_imagery").each(function(){
		var images = $j("img", this);
		$j(images).each(function(i){
			
			if(i > 0){
				$j(this).css('display', 'none');
			} else {
				$j(this).addClass('active');
			}
			
		});
		
		$j(".total", this).text(images.length);
		
		if(images.length <= 1){
			$j(".paginator", this).css('display', 'none');
		}
		
	});
	
		$j(".img_back").click(function(e){
			e.preventDefault();
			var carousel = $j(this).parents('.carousel_imagery');
			var images = $j("img", carousel);
			var selectedIndex = 0;
			$j(images).each(function(i){
				if($j(this).hasClass('active')){
					selectedIndex = i;
				}
			});
			
			nextIndex = selectedIndex - 1;
			
			if(selectedIndex == 0){
				nextIndex = images.length - 1;
			}
			
			$j(images).removeClass('active');
			$j("img:eq(" + selectedIndex + ")", carousel).css('display', 'none');
			$j("img:eq(" + nextIndex + ")", carousel).css('display', 'block').addClass('active');
			
			$j(".current", carousel).text(nextIndex + 1);
		});
		
		$j(".img_forward").click(function(e){
			e.preventDefault();
			
			var carousel = $j(this).parents('.carousel_imagery');
			var images = $j("img", carousel);
			var selectedIndex = 0;
			$j(images).each(function(i){
				if($j(this).hasClass('active')){
					selectedIndex = i;
				}
			});
			
			nextIndex = selectedIndex + 1;
			
			if(selectedIndex == images.length - 1){
				nextIndex = 0;
			}
			
			$j(images).removeClass('active');
			$j("img:eq(" + selectedIndex + ")", carousel).css('display', 'none');
			$j("img:eq(" + nextIndex + ")", carousel).css('display', 'block').addClass('active');
			$j(".current", carousel).text(nextIndex + 1);
			
		});
}

$j(window).load(function(){
	$j(".carousel_imagery").fadeIn();
});

function initLanguages(){
	$j("#language_selector select").change(function(e){
		if($j(this).val() != "--"){
			window.location.href = window.location.href + "?&set_lang=" + $j(this).val();
		}
	});
}

function initRetail(){
	$j('.outlets').each(function(){
	
		$j("li:first", this).addClass('first');
	
		var left = 0.5 * (730 - $j(this).width());
		$j(this).css('left', left);
	
	});
	
}

function initDropcaps(selector){

	$j(selector).each(function(){
		var t = $j(this).text();
		var f = t.substring(0,1).toLowerCase();
		
		var allowed = Array("a", "t");
		if(allowed.inArray(f)){
			var end = "<div class='remaining'>" + t.substring(1) + "</div>";
			t = "<span class='dropcap dropcap_" + f + "'>" + f + "</span>" + end + "";
			$j(this).html(t).addClass('dropCapped');
		}
	});


}

function urlencode( str ) {
                                 
    var histogram = {}, tmp_arr = [];
    var ret = (str+'').toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The histogram is identical to the one in urldecode.
    histogram["'"]   = '%27';
    histogram['(']   = '%28';
    histogram[')']   = '%29';
    histogram['*']   = '%2A';
    histogram['~']   = '%7E';
    histogram['!']   = '%21';
    histogram['%20'] = '+';
    histogram['\u20AC'] = '%80';
    histogram['\u0081'] = '%81';
    histogram['\u201A'] = '%82';
    histogram['\u0192'] = '%83';
    histogram['\u201E'] = '%84';
    histogram['\u2026'] = '%85';
    histogram['\u2020'] = '%86';
    histogram['\u2021'] = '%87';
    histogram['\u02C6'] = '%88';
    histogram['\u2030'] = '%89';
    histogram['\u0160'] = '%8A';
    histogram['\u2039'] = '%8B';
    histogram['\u0152'] = '%8C';
    histogram['\u008D'] = '%8D';
    histogram['\u017D'] = '%8E';
    histogram['\u008F'] = '%8F';
    histogram['\u0090'] = '%90';
    histogram['\u2018'] = '%91';
    histogram['\u2019'] = '%92';
    histogram['\u201C'] = '%93';
    histogram['\u201D'] = '%94';
    histogram['\u2022'] = '%95';
    histogram['\u2013'] = '%96';
    histogram['\u2014'] = '%97';
    histogram['\u02DC'] = '%98';
    histogram['\u2122'] = '%99';
    histogram['\u0161'] = '%9A';
    histogram['\u203A'] = '%9B';
    histogram['\u0153'] = '%9C';
    histogram['\u009D'] = '%9D';
    histogram['\u017E'] = '%9E';
    histogram['\u0178'] = '%9F';
    
    // Begin with encodeURIComponent, which most resembles PHP's encoding functions
    ret = encodeURIComponent(ret);
    
    for (search in histogram) {
        replace = histogram[search];
        ret = replacer(search, replace, ret) // Custom replace. No regexing
    }
    
    // Uppercase for full PHP compatibility
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
        return "%"+m2.toUpperCase();
    });
    
    return ret;
}

function preloadImages(){
	var allImgs = Array();
	var total = preload.length;
	
	var copy = preload;
	
	$j(preload).each(function(i){
		//var image = jQuery("<img>").attr("src", preload[i]);
		allImgs[i] = new Image(); //new img obj
		allImgs[i].src = preload[i].replace(/&amp;/g, "&");
		$j(".thumbnail a:eq(" + i + ")").append(allImgs[i]);
		
		$j(allImgs[i]).load(function(){
			loaded++;
			var percentage = Math.round(100 * (loaded / total));
			$j("#percentage").html(percentage + "%");
			copy[i] = '';
			if(loaded == total){
				
				initPressScroller();
				$j("#loading_progress").fadeOut('slow');
				setTimeout(function(){
					$j('.sc_menu').fadeTo(500, 1);
				}, 400);
			
			}
			
			if(loaded+1 == total){
				//console.log(copy);
				//above helps for debugging.
			}
			
		});
		
	});
	

	//alert(preload.length);

}

function preloadCarouselImages(){
	var allImgs = Array();
	var total = preload.length;
	
	$j(preload).each(function(i){
		//var image = jQuery("<img>").attr("src", preload[i]);
		
		allImgs[i] = new Image(); //new img obj
		allImgs[i].src = preload[i].replace(/&amp;/g, "&");
		$j(".carousel li a:eq(" + i + ")").append(allImgs[i]);
		
		$j(allImgs[i]).load(function(){
			loaded++;
			var percentage = Math.round(100 * (loaded / total));
			$j("#percentage").html(percentage + "%");
			
			if(loaded == total){
			
				$j("#loading_progress").fadeOut('slow');
				setTimeout(function(){
					//$j('.sc_menu').fadeTo(500, 1);
					initCarousel("#products");
					buildCarousels();
				}, 400);
			
			}
			
		});
		
	});
	
	
	//alert(preload.length);
	
}

function initCarousels(){
	var carousels = $j(".tpl_4 .carousel").fadeTo(0, 0);
}

function buildCarousels(){
	
	var targets = $j(".product_target").fadeTo(0, 0);
	
	var carousels = $j(".carousel");
	$j(carousels).each(function(){
	
		var items = $j("li", this);
		var width = 0;
		$j(items).each(function(){
			width += $j(this).outerWidth();
		});
		
		$j(this).width(width);
		
	});
	
	var products = $j(".tpl_4 .carousel li a");
	$j(products).each(function(i){
	
		$j(this).click(function(e){
			e.preventDefault();
			$j('.carousel').fadeTo(400, 0).addClass('hidden');
			setTimeout(showProduct, 800, i);
		});
	
	});
	
	$j(carousels).fadeTo(400, 1);
	initPan();
	
}

function initForms(){

	$j('form').submit(function(e){
		
		
		var errors = 0;
		
		var requireds = $j(".required", this);
		$j(requireds).each(function(i){
		
			if($j(this).val() == "" || $j(this).val() == "--"){
				errors++;
				$j(this).addClass('error');
			} else {
				$j(this).removeClass('error');
			}
		
		});
		
		var emails = $j(".email", this);
		$j(emails).each(function(i){
		
			if(!checkEmail($j(this).val())){
				errors++;
				$j(this).addClass('error');
					//animate it
			} else {
				$j(this).removeClass('error');
			}
			
		});

	
		if(errors == 0){
			
			//let it post
			
		} else {
			$j('.error').animate({backgroundColor: '#ff0000'}, 400).animate({opacity: 1}, 400).animate({backgroundColor: '#2b2a2a'});
			e.preventDefault();
		}
	
		
	
	});
	
	$j("#birthday").focus(function(e){
	
		$j(".dp-choose-date").trigger('click');
	
	});

}

function checkEmail(email){
	AtPos = email.indexOf("@");
	StopPos = email.lastIndexOf(".");
	Message = true;
	
	if (email == "") {
		Message = false;
	}
	
	if (AtPos == -1 || StopPos == -1) {
		Message = false;
	}
	
	if (StopPos < AtPos) {
		Message = false;
	}
	
	if (StopPos - AtPos == 1) {
		Message = false;
	}
	//alert(Message);
	return Message;
}



function initPressPage(){
	var images = $j("ul.press_menu img");
	$j(images).each(function(){
	
		if($j(this).height() > 340){
			$j(this).css('height', '340px');
		}
	
	});
	

	//Get our elements for faster access and set overlay width
	var div = $j('div.sc_menu'),
	ul = $j('ul.press_menu'),
	ulPadding = 15;
	
	//Get menu width
	var divWidth = div.width();
	
	//Remove scrollbars	
	div.css({overflow: 'hidden'});
	
	//Find last image container
	var lastLi = ul.find('li:last-child');
	
	//When user move mouse over menu
	div.mousemove(function(e){
	    //As images are loaded ul width increases,
	    //so we recalculate it each time
	    var ulWidth = lastLi[0].offsetLeft + lastLi.outerWidth() + ulPadding;	
	    var left = (e.pageX - div.offset().left) * (ulWidth-divWidth) / divWidth;
	    div.scrollLeft(left);
	});

}


function initPressScroller(){
	
	//first gotta do some weirdness..
	
	var thumbs = $j('.thumbnail');
	var row2 = $j('#row_2');
	$j(thumbs).each(function(i){
		if(i%2 == 0){
			$j(row2).append($j(this));
		}	
	});

	//Get our elements for faster access and set overlay width
	var div = $j('div.sc_menu'),
	ul = $j('#row_2'),
	ulPadding = 15;
	
	//Get menu width
	var divWidth = div.width();
	
	//Remove scrollbars	
	div.css({overflow: 'hidden'});
	
	//Find last image container
	var lastLi = $j(ul).find('.thumbnail:last-child');
	
	//When user move mouse over menu
	var ulWidth = lastLi[0].offsetLeft + lastLi.outerWidth() + ulPadding;	
	var multiplier = (ulWidth-divWidth) / divWidth;
	div.mousemove(function(e){
	    //As images are loaded ul width increases,
	    //so we recalculate it each time
	    var left = (e.pageX - div.offset().left) * multiplier;
	    div.scrollLeft(left);
	});
	
	
	$j('.thumbnail a').hoverIntent(
		function(){
			
			$j('span', this).show();
			
			if($j.browser.msie){
				$j('img', this).hide();
			} else {
				$j('img', this).fadeTo(100, 0.3);
			}
			
		},
		function(){
			
			$j('span', this).hide();
			
			if($j.browser.msie){
				$j('img', this).show();
			} else {
				$j('img', this).fadeTo(100, 1);
			}
			
		}
	);

}

function killLinks(){
	
	$j('a.scroll').click(function(e){
		e.preventDefault();
	});
	
}

function showState(state){

	var selector = "#" + state;
	
	var $pane = $j("#stores .scroller").jScrollPane({animateTo:true, showArrows:true});
	$pane[0].scrollTo(selector);
	
}

function showStateNoAnimation(state){
	var selector = "#" + state;
	
	var $pane = $j("#stores .scroller").jScrollPane({animateTo:false, showArrows:true});
	$pane[0].scrollTo(selector);
}



function initPan(){
	var originalSizes = new Array();
	$j('#pane1').jScrollHorizontalPane({showArrows:true});

	/*
var div = $j('#pan'),
	ul = $j('#products'),
	ulPadding = 15;
	
	//Get menu width
	var divWidth = div.width();
	
	//Remove scrollbars	
	div.css({overflow: 'hidden'});
	
	//Find last image container
	var lastLi = ul.find('li:last-child');
	
	//When user move mouse over menu
	var ulWidth = lastLi[0].offsetLeft + lastLi.outerWidth() + ulPadding;
	var multiplier = (ulWidth-divWidth) / divWidth;
	div.mousemove(function(e){
	    //As images are loaded ul width increases,
	    //so we recalculate it each time
	    	
	    var left = (e.pageX - div.offset().left) * multiplier;
	    div.scrollLeft(left);
	});
*/

}

function showProduct(index){
	
	$j(".product_target:eq(" + index + ")").css('display', 'block').fadeTo(400, 1);
	var targets = $j(".product_target:eq(" + index + ") img");
	$j(".jScrollArrowLeft, .jScrollArrowRight, .jScrollPaneTrack").fadeTo(400, 0);
	
	
	/*
$j(targets).each(function(){
	
		
		var paddingLeft = 730 - $j(this).width();
		if(paddingLeft > 100){
		    paddingLeft = 100;
		}
		if(paddingLeft < 0){
		    paddingLeft = 0;
		}
		$j(this).css('margin-left', paddingLeft + 'px');
		
	
	});

*/	
	carouselIndex = index;
}

function hideProducts(){
	$j(".product_target").fadeTo(400, 0);
	$j(".jScrollArrowLeft, .jScrollArrowRight, .jScrollPaneTrack").fadeTo(400, 1);
	setTimeout(showCarousel, 400);
}

function showCarousel(){
	$j(".product_target").css('display', 'none');
	$j("#products").fadeTo(400, 1);
	
}

function initCarousel(selector){

	$j("#right, #left, .back").click(function(e){
		e.preventDefault();
		hideProducts();
	});

}

function initNavigation(){

	$j("#navigate .navigation > li").each(function(i){
	
		
	
		$j(this).hoverIntent(
        	function(){ 
        		//$j(this).find('.subnavigation').slideDown();
        		if($j.browser.msie){
        			$j('.subnavigation:gt(' + i + '), .subnavigation:lt(' + i + ')').fadeOut('slow');
        			$j(this).find('.subnavigation').fadeIn('slow');
        		} else {
        			$j('.subnavigation:gt(' + i + '), .subnavigation:lt(' + i + ')').hide('slow');
        			$j(this).find('.subnavigation').show('slow');
        		}
       		}, 
       		function() { 
        		//nothing, the nav should remain
        	} 
    	);
		
	});
	
	$j('#navigate a.active').parents('.subnavigation').show();
	$j('li.open').find('.subnavigation').show();
	
}

function initActiveStates(selectors){

	$j(selectors).each(function(){
     	var fade = "<div class='fader'><div class='fader_opacity'></div></div>";
    	$j(this).append(fade);
    	
    	if($j.browser.msie){
    		$j(this).find('.fader').show();
    	} else {
    		$j(this).find('.fader').fadeTo(0, 1);
    	}
    	
    });

}

function initFadingRollovers(selectors){

	$j(selectors).each(function(){
     	var fade = "<div class='fader'><div class='fader_opacity'></div></div>";
    	$j(this).append(fade);
    });
    
    if($j.browser.msie){
    	
    	$j(".fader").hide();
    	
    	$j(selectors).hoverIntent(
   		 		
   			function(){
   				$j(this).find('.fader').show();
   			},
   			function(){
   				$j(this).find('.fader').hide();
   			}
   		
   		);
    	
    } else {
    
   		$j(".fader").fadeTo(0, 0);
   		 
   		$j(selectors).hoverIntent(
   		 		
   			function(){
   				$j(this).find('.fader').fadeTo(300, 1);
   			},
   			function(){
   				$j(this).find('.fader').fadeTo(300, 0);
   			}
   		
   		);
	}

}

function initFades(selectors, amount){

	$j(selectors).fadeTo(0, amount);
	$j(selectors).hover(
		function(e){
			$j(this).fadeTo(200, 1);
		},
		function(f){
			$j(this).fadeTo(200, amount);
		}
	);
	
}


/* HOVER INTENT */
/**
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne <brian@cherne.net>
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);


/* Copyright (c) 2006 Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 *
 * $LastChangedDate: 2007-12-20 09:02:08 -0600 (Thu, 20 Dec 2007) $
 * $Rev: 4265 $
 *
 * Version: 3.0
 * 
 * Requires: $ 1.2.2+
 */

(function($) {

$.event.special.mousewheel = {
	setup: function() {
		var handler = $.event.special.mousewheel.handler;
		
		// Fix pageX, pageY, clientX and clientY for mozilla
		if ( $.browser.mozilla )
			$(this).bind('mousemove.mousewheel', function(event) {
				$.data(this, 'mwcursorposdata', {
					pageX: event.pageX,
					pageY: event.pageY,
					clientX: event.clientX,
					clientY: event.clientY
				});
			});
	
		if ( this.addEventListener )
			this.addEventListener( ($.browser.mozilla ? 'DOMMouseScroll' : 'mousewheel'), handler, false);
		else
			this.onmousewheel = handler;
	},
	
	teardown: function() {
		var handler = $.event.special.mousewheel.handler;
		
		$(this).unbind('mousemove.mousewheel');
		
		if ( this.removeEventListener )
			this.removeEventListener( ($.browser.mozilla ? 'DOMMouseScroll' : 'mousewheel'), handler, false);
		else
			this.onmousewheel = function(){};
		
		$.removeData(this, 'mwcursorposdata');
	},
	
	handler: function(event) {
		var args = Array.prototype.slice.call( arguments, 1 );
		
		event = $.event.fix(event || window.event);
		// Get correct pageX, pageY, clientX and clientY for mozilla
		$.extend( event, $.data(this, 'mwcursorposdata') || {} );
		var delta = 0, returnValue = true;
		
		if ( event.wheelDelta ) delta = event.wheelDelta/120;
		if ( event.detail     ) delta = -event.detail/3;
//		if ( $.browser.opera  ) delta = -event.wheelDelta;
		
		event.data  = event.data || {};
		event.type  = "mousewheel";
		
		// Add delta to the front of the arguments
		args.unshift(delta);
		// Add event to the front of the arguments
		args.unshift(event);

		return $.event.handle.apply(this, args);
	}
};

$.fn.extend({
	mousewheel: function(fn) {
		return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
	},
	
	unmousewheel: function(fn) {
		return this.unbind("mousewheel", fn);
	}
});

})(jQuery);


/* Copyright (c) 2006 Kelvin Luck (kelvin AT kelvinluck DOT com || http://www.kelvinluck.com)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * 
 * See http://kelvinluck.com/assets/jquery/jScrollPane/
 * $Id: jScrollPane.js 66 2009-03-15 01:18:07Z kelvin.luck $
 */

/**
 * Replace the vertical scroll bars on any matched elements with a fancy
 * styleable (via CSS) version. With JS disabled the elements will
 * gracefully degrade to the browsers own implementation of overflow:auto.
 * If the mousewheel plugin has been included on the page then the scrollable areas will also
 * respond to the mouse wheel.
 *
 * @example jQuery(".scroll-pane").jScrollPane();
 *
 * @name jScrollPane
 * @type jQuery
 * @param Object	settings	hash with options, described below.
 *								scrollbarWidth	-	The width of the generated scrollbar in pixels
 *								scrollbarMargin	-	The amount of space to leave on the side of the scrollbar in pixels
 *								wheelSpeed		-	The speed the pane will scroll in response to the mouse wheel in pixels
 *								showArrows		-	Whether to display arrows for the user to scroll with
 *								arrowSize		-	The height of the arrow buttons if showArrows=true
 *								animateTo		-	Whether to animate when calling scrollTo and scrollBy
 *								dragMinHeight	-	The minimum height to allow the drag bar to be
 *								dragMaxHeight	-	The maximum height to allow the drag bar to be
 *								animateInterval	-	The interval in milliseconds to update an animating scrollPane (default 100)
 *								animateStep		-	The amount to divide the remaining scroll distance by when animating (default 3)
 *								maintainPosition-	Whether you want the contents of the scroll pane to maintain it's position when you re-initialise it - so it doesn't scroll as you add more content (default true)
 *								scrollbarOnLeft	-	Display the scrollbar on the left side?  (needs stylesheet changes, see examples.html)
 *								reinitialiseOnImageLoad - Whether the jScrollPane should automatically re-initialise itself when any contained images are loaded
 * @return jQuery
 * @cat Plugins/jScrollPane
 * @author Kelvin Luck (kelvin AT kelvinluck DOT com || http://www.kelvinluck.com)
 */

(function($) {

$.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':paneWidth+'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'})
						)
					)
				);
				
				/*
$container.append(
				
					($('<div></div>').attr({'className': 'scrollTop'}))
				
				).append(
				
					($('<div></div>').attr({'className': 'scrollBottom'}))
				
				);
*/
				
				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);

/* IMAGE FIT */

(function($j) {
	$j.fn.imagefit = function(options) {
		var fit = {
			all : function(imgs){
				imgs.each(function(){
					fit.one(this);
					})
				},
			one : function(img){
				$j(img)
					.width('100%').each(function()
					{
						$j(this).height(Math.round(
							$j(this).attr('startheight')*($j(this).width()/$j(this).attr('startwidth')))
						);
					})
				}
		};
		
		this.each(function(){
				var container = this;
				
				// store list of contained images (excluding those in tables)
				var imgs = $j('img', container).not($j("table img"));
				
				// store initial dimensions on each image 
				imgs.each(function(){
					$j(this).attr('startwidth', $j(this).width())
						.attr('startheight', $j(this).height())
						.css('max-width', $j(this).attr('startwidth')+"px");
				
					fit.one(this);
				});
				// Re-adjust when window width is changed
				$j(window).bind('resize', function(){
					fit.all(imgs);
				});
			});
		return this;
	};
})(jQuery);

/*
 * jQuery Color Animations
 * Copyright 2007 John Resig
 * Released under the MIT and GPL licenses.
 */

(function(jQuery){

	// We override the animation for all of these color styles
	jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
		jQuery.fx.step[attr] = function(fx){
			if ( fx.state == 0 ) {
				fx.start = getColor( fx.elem, attr );
				fx.end = getRGB( fx.end );
			}

			fx.elem.style[attr] = "rgb(" + [
				Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
			].join(",") + ")";
		}
	});

	// Color Conversion functions from highlightFade
	// By Blair Mitchelmore
	// http://jquery.offput.ca/highlightFade/

	// Parse strings looking for color tuples [255,255,255]
	function getRGB(color) {
		var result;

		// Check if we're already dealing with an array of colors
		if ( color && color.constructor == Array && color.length == 3 )
			return color;

		// Look for rgb(num,num,num)
		if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
			return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

		// Look for rgb(num%,num%,num%)
		if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
			return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

		// Look for #a0b1c2
		if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
			return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

		// Look for #fff
		if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
			return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

		// Otherwise, we're most likely dealing with a named color
		return colors[jQuery.trim(color).toLowerCase()];
	}
	
	function getColor(elem, attr) {
		var color;

		do {
			color = jQuery.curCSS(elem, attr);

			// Keep going until we find an element that has color, or we hit the body
			if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
				break; 

			attr = "backgroundColor";
		} while ( elem = elem.parentNode );

		return getRGB(color);
	};
	
	// Some named colors to work with
	// From Interface by Stefan Petre
	// http://interface.eyecon.ro/

	var colors = {
		aqua:[0,255,255],
		azure:[240,255,255],
		beige:[245,245,220],
		black:[0,0,0],
		blue:[0,0,255],
		brown:[165,42,42],
		cyan:[0,255,255],
		darkblue:[0,0,139],
		darkcyan:[0,139,139],
		darkgrey:[169,169,169],
		darkgreen:[0,100,0],
		darkkhaki:[189,183,107],
		darkmagenta:[139,0,139],
		darkolivegreen:[85,107,47],
		darkorange:[255,140,0],
		darkorchid:[153,50,204],
		darkred:[139,0,0],
		darksalmon:[233,150,122],
		darkviolet:[148,0,211],
		fuchsia:[255,0,255],
		gold:[255,215,0],
		green:[0,128,0],
		indigo:[75,0,130],
		khaki:[240,230,140],
		lightblue:[173,216,230],
		lightcyan:[224,255,255],
		lightgreen:[144,238,144],
		lightgrey:[211,211,211],
		lightpink:[255,182,193],
		lightyellow:[255,255,224],
		lime:[0,255,0],
		magenta:[255,0,255],
		maroon:[128,0,0],
		navy:[0,0,128],
		olive:[128,128,0],
		orange:[255,165,0],
		pink:[255,192,203],
		purple:[128,0,128],
		violet:[128,0,128],
		red:[255,0,0],
		silver:[192,192,192],
		white:[255,255,255],
		yellow:[255,255,0]
	};
	
})(jQuery);

Array.prototype.inArray = function (value)
// Returns true if the passed value is found in the
// array. Returns false if it is not.
{
var i;
for (i=0; i < this.length; i++) {
// Matches identical (===), not just similar (==).
if (this[i] === value) {
return true;
}
}
return false;
};
