/*

TAG Heuer Web Magazine

*/



/* --------------------------------
	base URL
-------------------------------- */

var baseURL = 'http://'+location.hostname+'';



/* --------------------------------
	site root
-------------------------------- */

var siteRoot = getSiteRoot('common/js/base.js');

function getSiteRoot(path) {
	var elms = document.getElementsByTagName('script');
	for (var i = elms.length - 1; i >= 0; i--) {
		var src = elms[i].src;
		if (new RegExp(path + '([\?].*)*$').test(src)) return src.split(path)[0];
	}
	return false;
}



/* --------------------------------
	DOM
-------------------------------- */

$(function() {
	$('li:first-child').addClass('first');
})



/* --------------------------------
	UX
-------------------------------- */

var ux = {
	// 初期化
	init: function() {
		var self = this;
		if (this.isIE6) this.pngfix.load();
		$(function() {
			self.rollover('.rollover', '_ov', '_on');
			if (self.isIE6) self.pngfix.fix();
			self.discrimination.init();
			if((self.discrimination.ua=='ipad')||(self.discrimination.ua=='iphone')||(window.location.href.indexOf('product_print',0)!=-1)) {// iPhone/iPad/印刷ページの時はスムーススクロールを有効化
				$('p.pagetop a').attr('href','#container');
				self.scroller.init();
			}
		});
	},

	// ロールオーバー
	rollover: function(selector, over, on, onOver) {
		$(selector).each(function() {
			var src = this.src;
			var ext = new RegExp('\.(gif|jpg|png)([\?].*)*$').exec(src)[0];
			var hasOn = on && new RegExp(on + ext).test(src);
			if (hasOn && !onOver) return;
			var search = (hasOn && onOver) ? on + ext : ext;
			var replace = (hasOn && onOver) ? onOver + ext : over + ext;
			var overSrc = src.replace(search, replace);
			new Image().src = overSrc;
			$(this).mouseout(function() {
				this.src = src;
			}).mouseover(function() {
				this.src = overSrc;
			});
		});
	},

	// PNG Fix
	pngfix: {
		// 読み込み
		load: function() {
			var d = document;
			var src = [
				'<script type="text/javascript" src="' + siteRoot + 'common/lib/DD_belatedPNG/DD_belatedPNG.js"></script>',
				'<script type="text/javascript" src="' + siteRoot + 'common/lib/ifixpng/jquery.ifixpng.js"></script>'
			].join('');
			d.open();
			d.write(src);
			d.close();
		},

		// 実行
		fix: function() {
			DD_belatedPNG.fix('.belatedpng');
			$.ifixpng(siteRoot + 'common/lib/ifixpng/pixel.gif');
			$('img[src$=.png]:not(.noifixpng)').ifixpng().filter('.rollover').mouseout(function() {
				$(this).ifixpng();
			}).mouseover(function() {
				$(this).ifixpng();
			});
		}
	},

	// スクローラー
	scroller: {
		// 設定
		conf: {
			pitch: 10,
			interval: 10
		},

		// 初期化
		init: function(conf) {
			var self = this;
			var temp = this.conf;
			for (var key in conf) temp[key] = conf[key];
			this.conf = temp;
			$('a[href^="#"]:not(.noscroll)').each(function() {
				if (!this.hash || this.hash == '#') return;
				$(this).click(function(e) {
					e.preventDefault();
					this.blur();
					self.scroll(this.hash);
				});
			});
		},

		// スクロール
		scroll: function(id) {
			if (this.timer) clearInterval(this.timer);
			var self = this;
			var pitch = this.conf.pitch;
			var interval = this.conf.interval;
			var top = $(id + ', a[name="' + id.replace(/^#/, '') + '"]').eq(0).offset().top;
			var win = window;
			var $win = $(win);
			var scrollLeft = $win.scrollLeft();
			var limit = $(document).height() - $win.height();
			if (limit < 0) limit = 0;
			if (top > limit) top = limit;
			if (top < 0) top = 0;
			var dir = (top > $win.scrollTop()) ? 1 : -1;
			var math = (dir > 0) ? Math.ceil : Math.floor;
			top = math(top);
			this.timer = setInterval(function() {
				var scrollTop = $win.scrollTop();
				if (scrollTop == top || scrollTop == self.scrollTop) {
					clearInterval(self.timer);
					return;
				}
				self.scrollTop = scrollTop;
				scrollTop += math((top - scrollTop) / pitch);
				if (dir > 0 && scrollTop > top || dir < 0 && scrollTop < top) scrollTop = top;
				win.scrollTo(scrollLeft, scrollTop);
			}, interval);
		}
	},

	// IE6判定フラグ
	isIE6: /msie ([0-9]+)/.test(navigator.userAgent.toLowerCase()) && RegExp.$1 == 6,


	// iPhone/iPadを判別しbodyにclassを付ける
	discrimination: {
		
		// 設定
		element: 'body', // classを追加するエレメント
		iphone: 'iphone', // iPhoneの場合の追加class
		ipad: 'ipad', // iPadの場合の追加class
		ua: '',
		
		init: function() {
			if(navigator.userAgent.indexOf('iPhone',0)!=-1){ $(this.element).addClass(this.iphone); this.ua='iphone' }
			if(navigator.userAgent.indexOf('iPad',0)!=-1){ $(this.element).addClass(this.ipad); this.ua='ipad' }
		}
		
	}


}

ux.init();



/* --------------------------------
	MM_Behavior
-------------------------------- */

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}



/* --------------------------------
	Fix Height
-------------------------------- */

/*
 * fixHeight - jQuery Plugin
 * http://www.starryworks.co.jp/blog/tips/javascript/fixheightjs.html
 *
 * Author Koji Kimura @ STARRYWORKS inc.
 * http://www.starryworks.co.jp/
 * 
 * Licensed under the MIT License
 *
 */


(function($){
	
	var isInitialized = false;
	var parents = [];
	var textHeight = 0;
	var $fontSizeDiv;
	
	$.fn.fixHeight = function() {
		this.each(function(){
			var childrenGroups = getChildren( this );
			
			$.each( childrenGroups, function(){
				
				var $children = $(this);
				if ( !$children.filter(":visible").length ) return;
				
				var row = [];
				var top = 0;
				$children.each(function(){
					if ( top != $(this).position().top ) {
						$(row).sameHeight();
						row = [];
						top = $(this).position().top;
					}
					row.push(this);
				});
				if ( row.length ) $(row).sameHeight();
			});
			
			
		});
		init();
		return this;
	}
	
	$.checkFixHeight = function( i_force ) {
		if ( $fontSizeDiv.height() == textHeight && i_force !== true ) return;
		textHeight = $fontSizeDiv.height();
		$(parents).fixHeight();
	}
	
	$.fn.sameHeight = function() {
		var maxHeight = 0;
		this.css("height","auto");
		this.each(function(){
			if ( $(this).height() > maxHeight ) maxHeight = $(this).height();
		});
		return this.height(maxHeight);
	}
	
	function getChildren( i_parent ) {
		var $parent = $( i_parent );
		
		if ( $parent.data("fixHeightChildrenGroups") ) return $parent.data("fixHeightChildrenGroups");
		var childrenGroups = [];
		
		var $children = $parent.find(".fixHeightChild");
		if ( $children.length ) childrenGroups.push( $children );
		
		var $groupedChildren = $parent.find("*[class*='fixHeightChild']:not(.fixHeightChild)");
		if ( $groupedChildren.length ) {
			var classNames = {};
			$groupedChildren.each(function(){
				var a = $(this).attr("class").split(" ");
				var i;
				var l = a.length;
				var c;
				for ( i=0; i<l; i++ ) {
					c = a[i].match(/fixHeightChild[a-z0-9_-]+/i);
					if ( !c ) continue;
					c = c.toString();
					if ( c ) classNames[c] = c;
				}
			});
			for ( var c in classNames ) childrenGroups.push( $parent.find("."+c) );
		}
		
		if ( !childrenGroups.length ) {
			$children = $parent.children();
			if ( $children.length ) childrenGroups.push( $children );
		}
		
		$parent.data("fixHeightChildrenGroups", childrenGroups );
		parents.push( $parent );
		
		return childrenGroups;
	}
	
	
	function init() {
		if ( isInitialized ) return;
		isInitialized = true;
		$fontSizeDiv = $(document).append('<div style="position:absolute;left:-9999px;top:-9999px;">s</div>');
		setInterval($.checkFixHeight,1000);
		$(window).resize($.checkFixHeight);
		$.checkFixHeight();
		$(window).load( function(){ $.checkFixHeight(true); } );
	}
	
})(jQuery);



$(function(){
	$("ul.items, .shopWrap").fixHeight();
});



/* --------------------------------
	Tiny Carousel
-------------------------------- */

/*!
 * Tiny Carousel 1.8
 * http://www.baijs.nl/tinycarousel
 *
 * Copyright 2010, Maarten Baijs
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.opensource.org/licenses/gpl-2.0.php
 *
 * Date: 10 / 11 / 2010
 * Depends on library: jQuery
 */
(function($){
	$.fn.tinycarousel = function(options){
		var defaults = { 
			start: 1, // where should the carousel start?
			display: 1, // how many blocks do you want to move at 1 time?
			axis: 'x', // vertical or horizontal scroller? ( x || y ).
			controls: true, // show left and right navigation buttons.
			pager: false, // is there a page number navigation present?
			interval: false, // move to another block on intervals.
			intervaltime: 7000, // interval time in milliseconds.
			rewind: false, // If interval is true and rewind is true it will play in reverse if the last slide is reached.
			animation: true, // false is instant, true is animate.
			duration: 500, // how fast must the animation move in ms?
			callback: null // function that executes after every move
		};
		var options = $.extend(defaults, options);  

		var oSlider = $(this);
		var oViewport = $('.viewport:first', oSlider);
		var oContent = $('.overview:first', oSlider);
		var oPages = oContent.children();
		var oBtnNext = $('.next:first', oSlider);
		var oBtnPrev = $('.prev:first', oSlider);
		var oPager = $('.pager:first', oSlider);
		var iPageSize, iSteps, iCurrent, oTimer, bPause, bForward = true, bAxis = options.axis == 'x';

		return this.each(function(){
			initialize();
		});
		function initialize(){
			iPageSize = bAxis ? $(oPages[0]).outerWidth(true) : $(oPages[0]).outerHeight(true);
			var iLeftover = Math.ceil(((bAxis ? oViewport.outerWidth() : oViewport.outerHeight()) / (iPageSize * options.display)) -1);
			iSteps = Math.max(1, Math.ceil(oPages.length / options.display) - iLeftover);
			iCurrent = Math.min(iSteps, Math.max(1, options.start)) -2;
			oContent.css(bAxis ? 'width' : 'height', (iPageSize * oPages.length));
			move(1);
			setEvents();
		}
		function setEvents(){
			if(options.controls && oBtnPrev.length > 0 && oBtnNext.length > 0){
				oBtnPrev.click(function(){move(-1); return false;});
				oBtnNext.click(function(){move( 1); return false;});
			}
			if(options.interval){
				oSlider.hover(function(){clearTimeout(oTimer); bPause = true},function(){bPause = false; setTimer();});
			}
			if(options.pager && oPager.length > 0){
				$('a',oPager).click(setPager);
			}
		}
		function setButtons(){
			if(options.controls){
				oBtnPrev.toggleClass('disable', !(iCurrent > 0));
				oBtnNext.toggleClass('disable', !(iCurrent +1 < iSteps));
			}
			if(options.pager){
				var oNumbers = $('.pagenum', oPager);
				oNumbers.removeClass('active');
				$(oNumbers[iCurrent]).addClass('active');
			}			
		}		
		function setPager(oEvent){
			if($(this).hasClass('pagenum')){
				iCurrent = parseInt(this.rel) -2;
				//iCurrent = parseInt(this.rel) -1; /*default*/
				move(1);
			}
			return false;
		}
		function setTimer(){
			if(options.interval && !bPause){
				clearTimeout(oTimer);
				oTimer = setTimeout(function(){
					iCurrent = !options.rewind && (iCurrent +1 == iSteps) ? -1 : iCurrent;
					bForward = iCurrent +1 == iSteps ? false : iCurrent == 0 ? true : bForward;
					move((options.rewind ? (bForward ? 1 : -1) : 1));
				}, options.intervaltime);
			}
		}
		function move(iDirection){
			if(iCurrent + iDirection > -1 && iCurrent + iDirection < iSteps){
				iCurrent += iDirection;
				var oPosition = {};
				oPosition[bAxis ? 'left' : 'top'] = -(iCurrent * (iPageSize * options.display));	
				oContent.animate(oPosition,{
					queue: false,
					duration: options.animation ? options.duration : 0,
					complete: function(){
						if(typeof options.callback == 'function')
						options.callback.call(this, oPages[iCurrent], iCurrent);
					}
				});
				setButtons();
				setTimer();
			}
		}
	};
})(jQuery);

function createPager(){
	var entryNum = $('#slider .entry').length;
	if(entryNum>1){
	  $('#slider').append('<ul class="pager"></ul>');
	  for(i=1; i<entryNum+1; i++){
		  $('.entry').eq(i-1).attr('id','entry'+i+'');
		  $('ul.pager').append('<li><a rel="'+i+'" class="pagenum entry'+i+'" href="#entry'+i+'">●</a></li>');
	  }
	  $('ul.pager').css('paddingLeft',''+383 - 19*entryNum +'px')
	}
}

$(function(){				
	createPager();
	if(ux.discrimination.ua!='ipad'){//iPadでは実行しない
		$('#slider').tinycarousel({ pager: true, interval: true });
	}
});



/*****************************************************************************
 jQuery flickGal 1.0.1
 
 Copyright (c) 2011 Soichi Takamura (http://stakamura.me/jquery/flickgal/demo.html)
 
 Dual licensed under the MIT and GPL licenses:
 http://www.opensource.org/licenses/mit-license.php
 http://www.gnu.org/licenses/gpl.html
 
 **************************************************************************** */
(function (jQuery) {

    jQuery.fn.flickGal = function (options) {

        var options = jQuery.extend({
            infinitCarousel: false,
            lockScroll: true
        }, options);

        return this.each(function () {

            // initializing
            var $flickBox = $(this),
                $container = $(".viewport", $flickBox).css({
                    overflow: "hidden"
                }),
                $box = $(".overview", $container).css({
                    position: "relative",
                    overflow: "hidden",
                    top: 0,
                    left: 0
                }),
                $items = $(".entry", $box).css({
                    float: "left"
                }),
                item_length = $items.length,
                item_width = $items.outerWidth(true),
                box_width = item_width * item_length,
                box_height = $items.outerHeight(true),
                minLeft = 0,
                maxLeft = ((item_width * item_length) - item_width) * -1,
                eventIndex = 0,
                cd = 0,
                // currently displayed
                containerOffsetLeft = $container.offset().left,
                containerBaseX = 0; // left offset (needed to orientationing)
            $container.height(box_height).scroll(function () {
                $(this).scrollLeft(0);
            });
            $box.height(box_height).width(box_width).css({
                "-webkit-transform": "translate3d(" + getTranslateX() + "px,0,0)"
            });

            // events occur on eigher iphone or pc
            var eventStr = [{
                s: "mousedown",
                e: "mouseup",
                m: "mousemove"
            }, {
                s: "touchstart",
                e: "touchend",
                m: "touchmove"
            }];
            var userAgent = navigator.userAgent.toLowerCase();
            if (/*userAgent.search(/iphone/) >= 0 || */userAgent.search(/ipad/) >= 0) eventIndex = 1;

            // **** define left offset ****

            function redefineLeftOffset(e) {
                containerBaseX = ($container.innerWidth() - item_width) / 2;
                moveToIndex(cd);
            }
            window.addEventListener("orientationchange", redefineLeftOffset, false);
            redefineLeftOffset();

            // **** navigation behavior ****
            var $nav = $(".pager", $flickBox),
                $nav_a = $nav.find("a[href^=#]"),
                $nav_children = $nav_a.parent();
            var ifNavExists = ($nav.length && $nav_a.length && $nav_children.length) ? true : false;
            if (ifNavExists) {
				//$nav_a.eq(0).addClass("active");
                $nav_children.eq(0).addClass("active");
                $nav_a.bind(eventStr[eventIndex]["s"], function (e) {
                    var i = $nav_a.index(this);
                    moveToIndex(i);
                    return false;
                }).bind("click", function () {
                    return false;
                });
            }

            // **** box behavior **** 
            var box = $box[0];
            box.addEventListener(eventStr[eventIndex]["m"], touchHandler, false);
            box.addEventListener(eventStr[eventIndex]["s"], touchHandler, false);
            box.addEventListener(eventStr[eventIndex]["e"], touchHandler, false);
            box.addEventListener("webkitTransitionEnd", finishAnimation, false);

            // **** back and forth arrows behavior (optional) ****
            var $prev = $(".prev", $flickBox),
                $next = $(".next", $flickBox);
            var ifArrowsExists = ($prev.length && $next.length) ? true : false;
            if (ifArrowsExists) {
                function prevTappedHandler() {
                    cd = (cd > 0) ? cd - 1 : (options.infinitCarousel) ? item_length - 1 : cd;
                    moveToIndex(cd);
                }

                function nextTappedHandler() {
                    cd = (cd < item_length - 1) ? cd + 1 : (options.infinitCarousel) ? 0 : cd;
                    moveToIndex(cd);
                }

                function attatchOfftoArrows() {
                    $prev.add($next).removeClass("off");

                    if (cd === 0) {
                        $prev.addClass("off");
                    } else if (cd === item_length - 1) {
                        $next.addClass("off");
                    }
                }
                
                $prev.bind(eventStr[eventIndex]["s"], prevTappedHandler);
                $next.bind(eventStr[eventIndex]["s"], nextTappedHandler);
                attatchOfftoArrows();
            }

            // ==== function - touch event handler ====
            var startX = 0,
                endX = 0,
                startTime = 0,
                startLeft = 0,
                ifMouseDown = 0,
                ifDefaultPrevented = 0;

            function touchHandler(e) {

                var touch = (eventIndex) ? e.touches[0] : e;

                // ############# touchMove
                if (e.type === eventStr[eventIndex]["m"]) {
                    if (ifDefaultPrevented === 0 && options.lockScroll) e.preventDefault();
                    if (ifMouseDown) {
                        var diffX = containerBaseX + touch.pageX - startX;
                        $box.css({
                            "-webkit-transform": ["translate3d(", startLeft + diffX, "px,0,0)"].join("")
                        });
                    }

                // ############# touchStart
                } else if (e.type === eventStr[eventIndex]["s"]) {
                    ifMouseDown = 1;

                    startTime = (new Date()).getTime();
                    startX = (eventIndex) ? touch.pageX : e.clientX;
                    startLeft = getTranslateX() - containerOffsetLeft - containerBaseX;

                    if ($box.hasClass('moving')) {
                        $box.removeClass('moving').css({
                            "-webkit-transform": ["translate3d(", containerBaseX + startLeft, "px,0,0)"].join("")
                        });
                    }

                // ############# touchEnd
                } else if (e.type === eventStr[eventIndex]["e"]) {
                    startLeft = ifMouseDown = ifDefaultPrevented = 0;
                    endX = (eventIndex) ? e.changedTouches[0].pageX : e.clientX;
                    moveToIndex();
                }
            }

            // ==== function - when the animation finished ====

            function finishAnimation() {
                $box.removeClass("moving");
            }

            // ==== function - scrolling box to fit to grid ====

            function moveToIndex(_cd) {

                $box.addClass("moving");

                var l = getTranslateX(); //parseInt($box.css("left"));
                if (typeof(_cd) == "number") cd = _cd;
                else {
                    var endTime = (new Date()).getTime();
                    var timeDiff = endTime - startTime;
                    var distanceX = endX - startX;

                    if (timeDiff < 300 && Math.abs(distanceX) > 30) {
                        if (distanceX > 0) cd--;
                        else cd++;
                    } else {
                        var d = Math.abs((minLeft + l) - containerBaseX - item_width / 2);
                        cd = Math.floor(d / item_width);
                    }
                }

                if (cd > item_length - 1) cd = item_length - 1;

                else if (cd < 0) cd = 0;

                // detect right position to fit
                $box.css({
                    "-webkit-transform": ["translate3d(", containerBaseX + item_width * cd * -1, "px,0,0)"].join("")
                });

                //if (ifNavExists) $nav_a.removeClass("active").eq(cd).addClass("active");
                if (ifNavExists) $nav_children.removeClass("active").eq(cd).addClass("active");
                if (ifArrowsExists) attatchOfftoArrows();
            }

            // ==== function - getTranslateX ====

            function getTranslateX() {
                return $box.offset().left;
            }
        });

    };
})(jQuery);

$(function(){
	if(ux.discrimination.ua=='ipad'){
		$("#slider").flickGal();
	}
});



/* --------------------------------
	Custum Scrollbar
-------------------------------- */

/* 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);



/**
 * @projectDescription Monitor Font Size Changes with jQuery
 *
 * @version 1.0
 * @author Dave Cardwell
 *
 * jQuery-Em - $Revision: 24 $ ($Date: 2007-08-19 11:24:56 +0100 (Sun, 19 Aug 2007) $)
 * http://davecardwell.co.uk/javascript/jquery/plugins/jquery-em/
 *
 * Copyright ©2007 Dave Cardwell <http://davecardwell.co.uk/>
 *
 * Released under the MIT licence:
 * http://www.opensource.org/licenses/mit-license.php
 */

// Upon $(document).ready()…
jQuery(function($) {
    // Configuration…
    var eventName = 'emchange';
    
    
    // Set up default options.
    $.em = $.extend({
        /**
         * The jQuery-Em version string.
         *
         * @example $.em.version;
         * @desc '1.0a'
         *
         * @property
         * @name version
         * @type String
         * @cat Plugins/Em
         */
        version: '1.0',
        
        /**
         * The number of milliseconds to wait when polling for changes to the
         * font size.
         *
         * @example $.em.delay = 400;
         * @desc Defaults to 200.
         *
         * @property
         * @name delay
         * @type Number
         * @cat Plugins/Em
         */
        delay: 200,
        
        /**
         * The element used to detect changes to the font size.
         *
         * @example $.em.element = $('<div />')[0];
         * @desc Default is an empty, absolutely positioned, 100em-wide <div>.
         *
         * @private
         * @property
         * @name element
         * @type Element
         * @cat Plugins/Em
         */
        element: $('<div />').css({ left:     '-100em',
                                    position: 'absolute',
                                    width:    '100em' })
                             .prependTo('body')[0],
        
        /**
         * The action to perform when a change in the font size is detected.
         *
         * @example $.em.action = function() { ... }
         * @desc The default action is to trigger a global “emchange” event.
         * You probably shouldn’t change this behaviour as other plugins may
         * rely on it, but the option is here for completion.
         *
         * @example $(document).bind('emchange', function(e, cur, prev) {...})
         * @desc Any functions triggered on this event are passed the current
         * font size, and last known font size as additional parameters.
         *
         * @private
         * @property
         * @name action
         * @type Function
         * @cat Plugins/Em
         * @see current
         * @see previous
         */
        action: function() {
            var currentWidth = $.em.element.offsetWidth / 100;
            
            // If the font size has changed since we last checked…
            if ( currentWidth != $.em.current ) {
                /**
                 * The previous pixel value of the user agent’s font size. See
                 * $.em.current for caveats. Will initially be undefined until
                 * the “emchange” event is triggered.
                 *
                 * @example $.em.previous;
                 * @result 16
                 *
                 * @property
                 * @name previous
                 * @type Number
                 * @cat Plugins/Em
                 * @see current
                 */
                $.em.previous = $.em.current;
                
                /**
                 * The current pixel value of the user agent’s font size. As
                 * with $.em.previous, this value *may* be subject to minor
                 * browser rounding errors that mean you might not want to
                 * rely upon it as an absolute value.
                 *
                 * @example $.em.current;
                 * @result 14
                 *
                 * @property
                 * @name current
                 * @type Number
                 * @cat Plugins/Em
                 * @see previous
                 */
                $.em.current = currentWidth;
                
                $.event.trigger(eventName, [$.em.current, $.em.previous]);
            }
        }
    }, $.em );
    
    
    /**
     * Bind a function to the emchange event of each matched element.
     *
     * @example $("p").emchange( function() { alert("Hello"); } );
     *
     * @name emchange
     * @type jQuery
     * @param Function fn A function to bind to the emchange event.
     * @cat Plugins/Em
     */

    /**
     * Trigger the emchange event of each matched element.
     *
     * @example $("p").emchange()
     *
     * @name emchange
     * @type jQuery
     * @cat Plugins/Em
     */
    $.fn[eventName] = function(fn) { return fn ? this.bind(eventName, fn)
                                               : this.trigger(eventName); };
    
    
    // Store the initial pixel value of the user agent’s font size.
    $.em.current = $.em.element.offsetWidth / 100;
    
    /**
     * While polling for font-size changes, $.em.iid stores the intervalID in
     * case you should want to cancel with clearInterval().
     *
     * @example window.clearInterval( $.em.iid );
     * 
     * @property
     * @name iid
     * @type Number
     * @cat Plugins/Em
     */
    $.em.iid = setInterval( $.em.action, $.em.delay );
});



/* 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 78 2009-07-03 19:16:36Z kelvin.luck@gmail.com $
 */

/**
 * 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)
 *								tabIndex		-	The tabindex for this jScrollPane to control when it is tabbed to when navigating via keyboard (default 0)
 *								enableKeyboardNavigation - Whether to allow keyboard scrolling of this jScrollPane when it is focused (default true)
 *								animateToInternalLinks - Whether the move to an internal link (e.g. when it's focused by tabbing or by a hash change in the URL) should be animated or instant (default false)
 *								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 (default false)
 * @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);
			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 {
				$this.data('originalStyleTag', $this.attr('style'));
				// 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 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;
				var $container = $('<div></div>')
					.attr({'className':'jScrollPaneContainer'})
					.css(
						{
							'height':paneHeight+'px', 
							'width':paneWidth+'px'
						}
					);
				if (settings.enableKeyboardNavigation) {
					$container.attr(
						'tabindex', 
						settings.tabIndex
					);
				}
				//$this.wrap($container);
				// 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) {
						delta = delta || (event.wheelDelta ? event.wheelDelta / 120 : (event.detail) ? -event.detail/3 : 0);
						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) == '#' && h.length > 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
					}
				);
				$this[0].scrollTo = $this[0].scrollBy = function() {};
				// 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':''
				}
			);
			$this.attr('style', $this.data('originalStyleTag'));
			$c.after($this).remove();
		}
	});
}

$.fn.jScrollPane.defaults = {
	scrollbarWidth : 10,
	scrollbarMargin : 0,
	wheelSpeed : 18,
	showArrows : false,
	arrowSize : 0,
	animateTo : false,
	dragMinHeight : 40,
	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(){
	var $scrollContainer = $('.viewport .container');
//	if((ux.discrimination.ua!='iphone')||(ux.discrimination.ua!='ipad')){// iPhone/iPadの時は実行しない
	if(ux.discrimination.ua!='ipad'){// iPadの時は実行しない
		$(window).load(function(){
			$scrollContainer.jScrollPane({scrollbarWidth:9});
		});
		$('a.pageAnchor').bind(
			'click',
			function() {
				var targetElementSelectorString = $(this).attr('href');
				$scrollContainer[0].scrollTo(targetElementSelectorString);
				return false;
			}
		);
		$('.pagetop a').bind(
			'click',
			function() {
				$scrollContainer[0].scrollTo(0,0);
				return false;
			}
		);
	}
});



/* --------------------------------
	Spec Sheet Flash
-------------------------------- */

$(function(){
	itemChange.init();
})

var itemChange = {

	init: function(){
		var self = this;
		self.flashEmbed();
		$('#itemZoomArea .item').hide();
		$('#itemZoomArea .item:first').show();
		$('#variationArea ul.thumb li:first a').addClass('current');
		$('#variationArea ul.thumb a').each(function(i){
			$(this).click(function(){
				var hasClass = $(this).attr('class');
				if(hasClass != 'current'){
				  $('#variationArea ul.thumb li a').removeClass('current');
				  $(this).addClass('current');
				  $('#itemZoomArea .item').fadeOut(200);
				  $('#itemZoomArea .item:eq('+i+')').fadeIn(500);
				}
			})
		})
	},
	
	// Flash読み込み
	flashEmbed: function(){
		var isMens = location.href.indexOf('/mens/',0)!=-1;
		var imgDir = isMens? '006':'007';
		$('#itemZoomArea .item .flash').each(function(i){
			var itemId = $(this).attr('id').slice(6);
			var flashvars = {
				imgURL:''+baseURL+'/archives/'+ imgDir +'/item_'+itemId+'.jpg'
			};
			var params = {
				bgcolor:'#ffffff',
				wmode:'transparent'
			};
			var attributes = {
				id: 'flash_'+itemId+'',
				name: 'flash_'+itemId+''
			};
			swfobject.embedSWF('../../swf/variation.swf', 'flash_'+itemId+'', '254', '350', '9.0.0.0', false, flashvars, params, attributes);
		})
	}
};



/* --------------------------------
	Image Gallery
-------------------------------- */

var cg = new Object();
cg.currentData = '';
cg.currentNum = 0;
cg.currentMax = 0;
cg.fadeSpeed = 300; //フェードの初期値

cg.dataList = new Object();

$(document).ready(function(){
	$('#overlayContainer').hide();
	jQuery.each($('#overlayContainer').children(), function(){
		if($(this).attr('id') != 'overlayInner' && $(this).attr('id') != 'overlayBg') $(this).hide();
	});
	$('#overlayContainer').remove().appendTo('body');
});

cg.open = function(data, num){
	
	if( cg.dataList[data] == undefined ){
		cg.dataList[data] = $('#'+data);
	}
	//cg.currentData = $('#'+data);
	cg.currentData = cg.dataList[data].clone();
	//cg.currentList = $('#'+data).children();
	cg.currentList = cg.currentData.children();
	cg.currentNum = (num) ? num : 1;
	
	cg.currentMax = cg.currentData.children().length;
	
	$('#overlayContent').empty();
	cg.currentList.eq(cg.currentNum-1).children().first().clone().appendTo('#overlayContent');
	$('#overlayContent').find('.currentNum').text(cg.currentNum);
	$('#overlayContent').find('.maxNum').text(cg.currentMax);
	$('#overlayContainer').fadeIn(cg.fadeSpeed);
}

cg.close = function(){
	$('#overlayContainer').fadeOut(cg.fadeSpeed);
}

cg.next = function(){
	cg.currentNum = (cg.currentNum == cg.currentMax) ? 1 : cg.currentNum+1;
	cg.changeContent();
}

cg.prev = function(){
	cg.currentNum = (cg.currentNum == 1) ? cg.currentMax : cg.currentNum-1;
	cg.changeContent();
}

cg.goto = function(num){
	cg.currentNum = num;
	cg.changeContent();
}

cg.changeContent = function(){
	$('#overlayContent').fadeOut(cg.fadeSpeed);
	$('#overlayContent').queue(function(){
		$(this).empty();
		$(this).append(cg.currentList.eq(cg.currentNum-1));
		$(this).find('.currentNum').text(cg.currentNum);
		$(this).find('.maxNum').text(cg.currentMax);
		$(this).dequeue();
	});
	$('#overlayContent').fadeIn(cg.fadeSpeed);
};

