/*
 * uniqlo utils
 */
$.extend({
	log: function(msg){if(location.href.indexOf("file:///")==0 && window.console){console.log(msg)}}
});

/*
 * image rollover plugin
 */
(function($){
	$.fn["rollover"] = function(options){
		var settings = $.extend({
			"suffix" : "_o"
		}, options);
		
		var _imgs = [];
		
		this.each(function(){
			var dsrc  = $(this).attr('src');
			var ftype = dsrc.substring(dsrc.lastIndexOf('.'), dsrc.length);
			var hsrc  = (dsrc.indexOf(settings.suffix+ftype)>0) ? dsrc:dsrc.replace(ftype, settings.suffix+ftype);
			// preload
			_imgs.push(new Image());
			_imgs[_imgs.length-1].src = hsrc;
			
			$(this)
				.attr({"dsrc": dsrc, "hsrc": hsrc})
				.mouseover(function(){$(this).attr("src", $(this).attr("hsrc"));})
				.mouseout( function(){$(this).attr("src", $(this).attr("dsrc"));});
		});
		return this;
	};
})(jQuery);

/*
 * image rollover toggle plugin
 * @require image rollover plugin
 */
(function($){
	$.fn["rolloverToggle"] = function(options){
		var settings = $.extend({
			"current": true,
			"suffix" : "_o"
		}, options);
		
		this.each(function(){
			if(settings.current){
				// default -> hover
				$(this).attr({
					"dsrc": $(this).attr("hsrc"),
					"src" : $(this).attr("hsrc")
				});
			}else{
				// hover -> default
				$(this).attr({
					"dsrc": $(this).attr("hsrc").replace(settings.suffix,""),
					"src" : $(this).attr("hsrc").replace(settings.suffix,"")
				});
			}
		});
		return this;
	};
})(jQuery);

/*
 * set maximum height to $items
 */
(function($){
	$.fn["autoHeight"] = function(options){
		// settings
		var settings = $.extend({
			"column": null
		}, options);

		var $items = $(this);
		var length = $items.length;
		var column = (settings.column ? settings.column : length);
		var $item, i, j, num, maxHeight;
		for(i = 0; i < length;) {
			num = (length - i >= column ? column : length - i);
			maxHeight = 0;
			for(j = 0; j < num; ++ j) {
				$item = $items.eq(i+j);
				maxHeight = ($item.height() > maxHeight ? $item.height() : maxHeight);
			}
			for(j = 0; j < num; ++ j, ++ i) {
				$items.eq(i).height(maxHeight);
			}
		}
		return this;
	};
})(jQuery);

/*
 * uniqlo header plugin
 * @require image rollover plugin
 */
(function($){
	$.fn["header"] = function(options){
		// settings
		var settings = $.extend({
			"imgClass" : ".imgover",
			"mainID"   : "#navHeader",
			"subClass" : "navCategory",
			"cartID"   : "#gnav_cart_trigger",
			"searchID" : "#searchFocus",
			"duration" : 200,
			"animate"  : false
		}, options);

		// main
		this.each(function(){
			// ヘッダ第二階層で遷移しないのはクリックころす
			$(this).find("a").focus(function(){
				$(this).blur();
			});
			$(this).find("ul.navCategory>li>a").click(function(){
				if($(this).attr("href")=="#") return false;
			});
			
			// 検索フォーム
			$(this)
				.find(settings.searchID)
				.focus(function(){
					$(this).parent().parent().addClass("inputFocus");
				})
				.blur(function(){
					$(this).parent().parent().removeClass("inputFocus");
				});
			
			// カンパニー判定
			if($("body#company").length>0){
				$("#header_company")
					.parent()
					.addClass("focus")
					.end()
					.find(">img")
					.rolloverToggle()
					.end()
					.siblings("ul")
					.removeClass("navCategoryHidden");
			}
			
			// ３階層ドロップダウン
			$(settings.mainID).find("li").hover(
				function(){
					if(!settings.animate && $(this).parent().attr("id") == settings.mainID.replace("#","")){
						$(this).find(">ul").show();
					}else{
						$(this).find(">ul:not(:animated)").slideDown(settings.duration);
					}
				},
				function(){
					// カレントカテゴリ第二階層は閉じない
					if($(this).hasClass("focus") && $(this).find(">ul").hasClass(settings.subClass)) return;
					if(!settings.animate && $(this).parent().attr("id") == settings.mainID.replace("#","")){
						$(this)
							.find(".sub")
							.hide()
							.end()
							.find(">ul")
							.hide();
					}else{
						$(this).find(">ul").slideUp(settings.duration, function(){
							// アニメーションのタイミング次第で第三階層が取り残されるので強制的に閉じる
							$(this).find(".sub").hide();
						});
					}
				});
			
			// ショッピングカート
			if(settings.animate){
				$(settings.cartID).parent().hover(
					function(){
						$(this).find(">ul:not(:animated)").slideDown(settings.duration);
					},
					function(){
						$(this).find(">ul").slideUp(settings.duration);
					});
			}else{
				$(settings.cartID).parent().hover(
					function(){
						$(this).find(">ul").show();
					},
					function(){
						$(this).find(">ul").hide();
					});
			}
			
			// ロールオーバー変更
			$(this).find(settings.imgClass)
				.unbind("mouseover")
				.unbind("mouseout")
				.parent()
				.parent()
				.hover(
					function(){
						var $img = $(this).find(">a>img");
						$img.attr("src", $img.attr("hsrc"));
					},
					function(){
						var $img = $(this).find(">a>img");
						$img.attr("src", $img.attr("dsrc"));
					});
		});
		return this;
	};
})(jQuery);

/*
 * L3 size switcher plugin (UNIQLO.Store.ItemSize)
 * @require image rollover plugin
 */
(function($){
	$.fn["sizeSwitcher"] = function(options){
		// settings
		var settings = $.extend({
			"targetID": "#blkMainItemList",
			"smallW": 228,
			"smallH": 228,
//			"smallP":"$12",
			"smallP":"middles",
			"largeW": 472,
			"largeH": 472,
//			"largeP":"$14"
			"largeP":"middlel"
		}, options);
		
		this.each(function(){
			$(this).find(".ctrlDisp02 a").die("click").live("click", function(){
				// サイズ判定
				var size = ($(this).parent().hasClass("size01"))? "small":"large";
				$.log("size switcher: " + size);
				
				// ターゲット切替
				$(settings.targetID)
						.toggleClass("blkUnitSize01")
						.toggleClass("blkUnitSize02")
						.find(".thumb img")
						.each(function(){
							$(this).attr({
//								src   : $(this).attr("src").replace(/(Mode=size)\d/, settings[size+"P"]),
								src   : $(this).attr("src").replace(/(middle)(s|l)/, settings[size+"P"]),
								width : settings[size+"W"],
								height: settings[size+"H"]
							});
						});
				
				// トリガー切替
				var $em = $("#utilMainItemList .ctrlDisp02 em>img");
				$em
					.attr("src", $em.attr("src").replace("_o.gif", ".gif"))
					.parent()
					.replaceWith("<a href='#'>" + $em.parent().html() + "</a>");
				$(this).replaceWith("<em>" + $(this).html() + "</em>");
				$("#utilMainItemList .ctrlDisp02 a>img").rollover();
				
				return false;
			});
		});
		return this;
	};
})(jQuery);

/*
 * L3 size switcher plugin (for noEC only)
 * @require image rollover plugin
 */
(function($){
	$.fn["sizeSwitcher2"] = function(options){
		// settings
		var settings = $.extend({
			"targetID": "#blkMainItemList",
			"smallW": 228,
			"smallH": 228,
			"smallP":"_m.jpg",
			"largeW": 472,
			"largeH": 472,
			"largeP":"_l.jpg"
		}, options);
		
		this.each(function(){
			$(this).find(".ctrlDisp02 a").die("click").live("click", function(){
				// サイズ判定
				var size = ($(this).parent().hasClass("size01"))? "small":"large";
				$.log("size switcher2: " + size);
				
				// ターゲット切替
				$(settings.targetID)
						/*
						いったんカラーチップなし
						.toggleClass("blkUnitSizeColor01")
						.toggleClass("blkUnitSizeColor02")
						*/
						.toggleClass("blkUnitSize01")
						.toggleClass("blkUnitSize02")
						.find(".thumb img")
						.each(function(){
							$(this).attr({
								src   : $(this).attr("src").replace(/(_(l|m).jpg$)/, settings[size+"P"]),
								width : settings[size+"W"],
								height: settings[size+"H"]
							});
						})
						.end()
						.find(".colorSelect a")
						.each(function(){
							$(this).attr({
								href  : $(this).attr("href").replace(/(_(l|m).jpg$)/, settings[size+"P"])
							});
						});
				
				// トリガー切替
				var $em = $("#utilMainItemList .ctrlDisp02 em>img");
				$em
					.attr("src", $em.attr("src").replace("_o.gif", ".gif"))
					.parent()
					.replaceWith("<a href='#'>" + $em.parent().html() + "</a>");
				$(this).replaceWith("<em>" + $(this).html() + "</em>");
				$("#utilMainItemList .ctrlDisp02 a>img").rollover();
				
				return false;
			});
		});
		return this;
	};
})(jQuery);

/*
 * L3 size filter
 */
(function($){
	$.fn["sizeFilter"] = function(options){
		// settings
		var settings = $.extend({
			"anchor" : "#utilMainItemTitle",
			"baseURL": "../disp/CSfDispListPage_002.jsp?"
		}, options);
		
		// 遷移先URL指定
		var _filter = function(size){
			
			try{
				var q = {
					dispNo: disp_no
				};
				if (size && size != 'title') {
					$.extend(q, {
						action : "size" + size,
						sizeFilterToggle: size
					});
				}
				return settings.baseURL + $.param(q) + settings.anchor;
			}catch(e){
				// disp_no未定義（デバッグ用
				if(location.hash.length == 0){
					return location.href + settings.anchor;
				}else{
					return location.href.replace(location.hash, settings.anchor);
				}
			}
		};
		
		this.each(function(){
			$(this).change(function(){
				var uri = _filter($(this).val());
				location.href = uri;
			});
		});
		return this;
	};
})(jQuery);

/*
 * L3 list color chips plugin
 */
(function($){
	$.fn["listColorChips"] = function(options){
		var settings = $.extend({
			"selectClass" : "select",
			"preload"     : false
		}, options);
		
		var _imgs = [];
		
		this.each(function(){
			$(this)
				.find(".colorSelect a")
				.click(function(){
					if($(this).parent().hasClass(settings.selectClass)) return false;
					$.log("list color chips: " +  $(this).attr("href"));
					$(this)
						.parent()
						.addClass(settings.selectClass)
						.siblings()
						.removeClass(settings.selectClass)
						.closest(".unit")
						.find(".thumb>a>img")
						.attr("src", $(this).attr("href"));
					return false;
				});
			
			// preload
			if(settings.preload){
				_imgs.push(new Image());
				_imgs[_imgs.length-1].src = $(this).attr("href");
			}
		});
		return this;
	};
})(jQuery);

/*
 * L3 Live Banner Plugin
 * @require image rollover plugin
 */
(function($){
	$.fn["l3Banner"] = function(options){
		// settings
		var settings = $.extend({
		}, options);

		//////////////////////////////////////////////////////

		var $l3Banner = $(this);
		var _bannerWidth = $l3Banner.width();
		var _bannerHeight = $l3Banner.height();

		var _maxCoordinateHeight = 0;
		var $lastLayer;
		var _isIE = $.browser.msie;
		var _isSupportOpacity = $.support.opacity;
		var  _isUT = $l3Banner.hasClass("l3banner_ut");

		var _defaultSlideEasing = "easeOutQuart";
		var _defaultSlideDuration = 750;

		//////////////////////////////////////////////////

		
		// ボタンの画像の設定
		var _IMG_NEXT_BUTTON_SRC = "https://www.uniqlo.com/global_images/uk/img/l3/liveban/btn_liveban_right.gif";
		var _IMG_PREV_BUTTON_SRC = "https://www.uniqlo.com/global_images/uk/img/l3/liveban/btn_liveban_left.gif";
		var _IMG_RETURN_BUTTON_SRC = "https://www.uniqlo.com/global_images/uk/img/l3/liveban/btn_liveban_return.gif";
		
		// 右上メニューの表示/非表示
		var _showBannerMenu = function(onComplete) {

			var $bannerMenu = $l3Banner.find(">div.l3banner_banner.current>div.l3banner_menu_container>ul.btnLivebanMenu");

			if($bannerMenu.is(":animated")) { return false; }

			var $container = $bannerMenu.parent(); // .menu_container
			var width = $container.width();
			var height = $container.height();
			$container
			.show();

			if(_isSupportOpacity) {

			$bannerMenu
				.animate({
				opacity: 1.0
				}, 300, "easeOutCubic", onComplete)
				.show();

			} else {
			// IE6, 7, 8はフェードしない
			$bannerMenu
				.show();
			(onComplete ? onComplete() : 0);
			}

			
			_hideMenuButton();

			return true;
		};

		var _hideBannerMenu = function(onComplete) {

			var $bannerMenu = $l3Banner.find(">div.l3banner_banner.current>div.l3banner_menu_container>ul.btnLivebanMenu");

			var $container = $bannerMenu.parent();

			if(_isSupportOpacity) {

			$bannerMenu
				.addClass("hiding")
				.stop(true, false) // cleraQueue and don't gotoEnd
				.animate({
				opacity: 0
				}, 250, function() {
				$(this).removeClass("hiding");
				$container.hide();
				(onComplete ? onComplete() : 0);
				});

			} else {
			// IE6, 7, 8はフェードしない
			$bannerMenu
				.hide();
			$container
				.hide();
			(onComplete ? onComplete() : 0);
			}


			var $img = $bannerMenu.find(">li>a>img.current");
			$img
			.attr("src", $img.attr("hsrc"));
			

			_showMenuButton();
		};

		// メニューボタンの表示/非表示
		var _showMenuButton = function() {

			var $img = $l3Banner.find(">div.l3banner_banner.current>p.btnLivebanMenu")
			.stop(true, true)
			.fadeIn();
		};

		var _hideMenuButton = function() {

			$l3Banner.find(">div.l3banner_banner.current>p.btnLivebanMenu")
			.stop(true, true)
			.fadeOut();
		};

		//////////////////////////////////////////////////

		// #l3_content_bannerのリサイズ
		var _resizeBanner = function(width, height, onComplete, duration) {

			var diff = $("#l3_content_banner").height() - height;
			if(diff == 0) {
			(onComplete ? onComplete() : 0);
			return ;
			}
			duration = (duration ? duration : 1000);
			$("#l3_content_banner")
			.stop(true, false)
			.animate({
				height: height
			}, duration, "easeOutQuint", onComplete);
		};
		
		// 第一階層、第二階層が表示される直前に行われる処理
		// このタイミングではまだ$layerはカレントになっていない
		var _onLayerWillAppear = function($layer) {
			
			if($layer.hasClass("boxCoordinate")) {
				// コーディネートの場合
				_onLayer2CoordinateWillAppear($layer);
			} else if($layer.hasClass("boxVoice")) {
				// ユーザーズボイスの場合
				$layer
					.find("div.scroll")
					.scrollTop(0);
			} else if($layer.hasClass("l3banner_slideshow")) {
				// スライドショーの場合
				_onSlideshowWillAppear($layer);
			}
			_resizeBanner(_bannerWidth, $layer.height());
		};
		
		// 右上メニューの選択
		$("ul.btnLivebanMenu>li>a").click(function() {

			if($l3Banner.find(":animated").length) { return false; }
			
			$(this)
			.children("img")
			.addClass("current")
			.parent() // a
			.parent() // li
			.siblings().find("img.current")
			.removeClass("current")
			.trigger("mouseout", "p");

			var l2Id = $(this).attr("href").replace("#", "");

			var $banner = $l3Banner.find(">div.l3banner_banner.current");
			var $layers = $("div.l3banner_layers", $banner);
			var $layer1 = $layers.children("div.current");
			var $layer2 = $layers.children("#" + l2Id);

			if($layer1.attr("id") == $layer2.attr("id")) {

			// コーディネートが表示されているときにコーディネートを選択したときの処理
			if($layer2.hasClass("boxCoordinate")) {
				_onLayer2CoordinateWillAppear($layer2, true, function() {
				_resizeBanner(_bannerWidth, $layer2.height(), null, 400);
				});
			}

			return false;
			}

			// 商品詳細の第三階層から第二階層への遷移
			if($layer1.hasClass("boxDetail") && $layer1.hasClass("l3banner_layer3") && $layer2.hasClass("boxDetail")) {

				var duration = Math.abs($layer1.height() - $layer2.height()) / 540 * 750;
				_resizeBanner(_bannerWidth, $layer2.height(), null, duration);
			_resetLayer3Detail($layer1, true);

			return false;
			}

			var top1 = parseInt($layer1.css("top"));
			var top2 = parseInt($layer2.css("top"));

			var diff = (top2 - top1 < 0 ? top1 - top2 : top2 - top1);
			var duration = (diff <= 810 ? 550 : diff / 1.5); // 810 = _bannerHeight(540) * 1.5

			$l3Banner.find(">div.l3banner_banner.current>div.l3banner_layers")
			.animate({
				top: -top2
			}, duration, "easeOutQuint", function() {

				// コーディネートと商品詳細は最初のページに戻す
				if($lastLayer.hasClass("boxCoordinate")) {
				_onLayer2CoordinateWillAppear($lastLayer, false);
				} else if($lastLayer.hasClass("boxDetail") && $lastLayer.hasClass("l3banner_layer3")) {
				_resetLayer3Detail($lastLayer);
				}

			});

			// 表示直前の処理
			_onLayerWillAppear($layer2);

			// カレント表示の更新
			$layer1.removeClass("current");
			$layer2.addClass("current");

			if(!$layer2.hasClass("boxCover")) {
			_hideBannerMenu();
			_showMenuButton();
			}

			$lastLayer = $layer1;

			return false;
		});

		// スライドショーのサムネイル（商品詳細の第二階層など）の選択
		$("ul.listDetail>li>a").click(function() {

			if($l3Banner.find(":animated").length) { return false; }

			var $layer2 = $("div.l3banner_banner.current>div.l3banner_layers>div.current")
			.removeClass("current");
			
			var $item = $($(this).attr("href"));
			var index = $item.parent().children().index($item);
			var isLastItem = $item.hasClass("l3banner_last_item");

			var $items = $item
			.addClass("current")	 // 選択したサムネイル
			.siblings()			  // 選択したサムネイル以外
			.removeClass("current")
			.parent()				// .l3banner_container
			.css({
				left: -_bannerWidth * index,
				top: 0
			});
			
			var $layer3 = $items
			.parent() // .l3banner_layer3
			.addClass("current");


			$layer2
			.animate({
				left: -_bannerWidth
			}, _defaultSlideDuration, _defaultSlideEasing, function() {
				$(this)
				.css({
					left: _bannerWidth
				});
			});

			$layer3
			.animate({
				left: 0
			}, _defaultSlideDuration, _defaultSlideEasing, function() {
			});

			var duration = Math.abs($layer2.height() - $layer3.height()) / 540 * 750;
			_resizeBanner(_bannerWidth, $layer3.height(), null, duration);

			_hideBannerMenu();

			// ボタンの表示/非表示の更新
			_adjustControlPosition($layer3.find("div.l3banner_control").show(), $item.width(), $item.height())
			.find("img.next_button").css("display", (isLastItem ? "none" : ($item.next().length == 0 ? "none" : "block"))).end()
			.find("img.prev_button").hide().end()
			.find("img.return_button").css("display", (isLastItem ? "block" : "none"));

			$lastLayer = $layer2
			
			return false;
		});

		// 進む/戻る/リターンボタンの位置調整
		var _adjustControlPosition = function($control, width, height) {
			var $nextButton = $(">img.next_button", $control);
			var $prevButton = $(">img.prev_button", $control);
			var $returnButton = $(">img.return_button", $control);
			
			$nextButton
			.css({
				left: (width - $nextButton.width() - 10),
				top: (((height - $nextButton.height())*0.5)|0)
			});
			$prevButton
			.css({
				left: 10,
				top: (((height - $prevButton.height())*0.5)|0)
			});
			$returnButton
			.css({
				left: $nextButton.css("left"),
				top: $nextButton.css("top")
			});

			return $control;
		};

		//////////////////////////////////////////////////
		// setup
		
		// メニューボタンの初期化処理
		var _setupMenuButton = function() {
			
			var _isBannerAnimated = false;
			var _menuButtonShowingId = -1;
			var _waitForCompleteAnimation = false;

			
			$l3Banner.find(">div.l3banner_banner>p.btnLivebanMenu")
			.find(">a>img")
			.mouseover(function() {

				if(_menuButtonShowingId != -1) {
				clearInterval(_menuButtonShowingId);
				}
				var isSuccessed = _showBannerMenu();
				if(!isSuccessed) {
				_menuButtonShowingId = setInterval(function() {
					if(_showBannerMenu()) { // success ?
					clearInterval(_menuButtonShowingId);
					_menuButtonShowingId = -1;
					}
				}, 50);
				}
				_isBannerAnimated = $l3Banner.find(">div.l3banner_banner.current>div.l3banner_menu_container>ul.btnLivebanMenu").is(":animated");
			})
			.mouseout(function() {
				if(_isBannerAnimated) {
				_isBannerAnimated = false;
				_showBannerMenu();
				}
				$(this).attr("src", $(this).attr("hsrc"));
			})
			.mousemove(function(event) {
				if(_isBannerAnimated) {
				_isBannerAnimated = false;
				_showBannerMenu();
				}
			})
			.click(function() {
				_showBannerMenu();
			});
		};

		// 右上メニューの初期化処理
		var _setupMenu = function() {

			$l3Banner.find(">div.l3banner_banner>ul.btnLivebanMenu").each(function() {

			$(this).parent().show(); // 高さを取得するために一時的に表示
			$(this)
				.wrap("<div class=\"l3banner_menu_container\"></div>")
				.hover(null, function(event, notHide) {

				if(notHide) { return false; }

				var $currentLayer = $("div.l3banner_banner.current>div.l3banner_layers>div.current");
				if($currentLayer.hasClass("l3banner_layer1")) { return false; }

				_hideBannerMenu();
				return false;
				})
				.parent() // .menu_container
				.css({
				position: "absolute",
				right: $(this).css("right"),
				top: $(this).css("top"),
				width: $(this).width(),
				height: $(this).height(),
				overflow: "hidden"
				});
			$(this).parent().hide();

			$(this)
				.css({
				right: 0,
				top: 0
				})
				.find(">li>a")
				.focus(function() {
				// FFでクリックしたときの点線を消す
				$(this).blur();
				return false;
				})
				.find(">img").each(function() { // 各メニューの項目の画像

				// カスタムのロールオーバーの処理に置き換える
				// マウスアウトしてもマウスオーバー時の画像を残す
				$(this)
//					.rollover()
					.unbind("mouseover")
					.unbind("mouseout")
					.mouseover(function() {
					$(this)
						.attr("src", $(this).attr("hsrc"));
					})
					.mouseout(function() {
					if(!$(this).hasClass("current")) {
						$(this)
						.attr("src", $(this).attr("dsrc"));
					}
					});
				})
				.first()
				.addClass("current")
				.trigger("mouseover");
			});
		};

		// マージンを調整する
		// IEだとnth-of-typeが使えないので、JS側で実装した
		var _removeMargin = function($items, itemsPerPage, column) {

			var index = 0;
			var counter = $items.length;
			var pages = (((counter-1) / itemsPerPage)|0) + 1;

			for(var page = 0; page < pages; ++ page) {

			var length = (counter >= itemsPerPage ? itemsPerPage : counter);
			counter -= itemsPerPage;

			var start = (((length-1) / column)|0) * column;

			for(var i = 0; i < length; ++ i, ++ index) {
				// 右端のアイテムの右マージンの削除
				if(_isIE && (index+1) % column == 0) {
				$items.eq(index).css({
					marginRight: "0px"
				});
				}

				// 最下段のアイテムの下マージンの削除
				// コーディネートは一段になったので常に削除
				// ゆくゆくはcssで対応するほうがいい
				$items.eq(index).css({
				marginBottom: "0px"
				});
			}
			}
		};

		// コーディネートの初期化処理
		var _setupCoordinate = function() {

			$l3Banner.find(">div.l3banner_banner>div.l3banner_layers>div.boxCoordinate").each(function() {

			$(this).show();  // 高さを取得するために一時的に表示

			var column = 3;
			var $pages = $(this).find(">div.l3banner_pages");
			var $dls = $pages.find(">dl");
			var length = $dls.length;
			var pageLength = ((length - 1) / column + 1)|0;

			var index = 0;
			for(var i = 0; i < pageLength; ++ i) {
				$dls.slice(index, index += column)
				.wrapAll($("<div />")
					 .addClass("clearfix")
					 .addClass("l3banner_page")
					 .addClass("l3banner_item").get(0));
			}
			
				if( _isUT ) {
					// UTの場合は高さをバナーの高さに合わせる
					$(this).find("div>dl").each(function() {
						var dh = _bannerHeight - $(this).children("dt").height();
						var $dd = $(this).children("dd");
						var pd = parseInt($dd.css("padding-top")) + parseInt($dd.css("padding-bottom"));
						$dd.height(dh-pd);
						});
				} else {
					// UT以外の場合は商品数に応じて高さを一番高いものに合わせる
					$(this).find("div>dl>dd").autoHeight({column: 3});
				}
				
				var $items = $(this).find(".listCoordinate");
				
				if($items.length > 0) {
					_removeMargin($items, 6, 3);
				}

			// レイヤーの大きさを設定
			var firstHeight = -1;
			$(this).find("div.l3banner_pages>div.l3banner_page").each(function() {
				if(firstHeight == -1) {
				firstHeight = $(this).height();
				_maxCoordinateHeight = firstHeight;
				return ;
				}
				_maxCoordinateHeight = ($(this).height() > _maxCoordinateHeight ? $(this).height() : _maxCoordinateHeight);
			});

			$(this).css({
				width: _bannerWidth,
				height: firstHeight,
				display: "none"
			});

			});
		};

		// コーディネートの表示直前に行われる処理
		// 最初のページに戻す
		var _onLayer2CoordinateWillAppear = function($layer2, animate, onComplete) {

			var $items = $(".l3banner_item", $layer2);
			var $item = $items.removeClass("current").first().addClass("current");
			var index = $items.index($item); // always 0
			
			if(animate) {
			var $container = $("div.l3banner_container", $layer2);
			var duration = -parseInt($container.css("left")) / _bannerWidth * 300;
			if(duration > 0) {
				$container
				.animate({
					left: 0
				}, duration, "easeOutQuart", onComplete);
			}
			} else {
			$("div.l3banner_container", $layer2).css("left", "0px");
			(onComplete ? onComplete() : 0);
			}

			var $control = $(".l3banner_control", $layer2);
			_adjustControlPosition($control, _bannerWidth, 440)
			.find("img.next_button").css("display", (index < $items.length-1 ? "block" : "none")).end()
			.find("img.prev_button").css("display", (index > 0 ? "block" : "none")).end()
			.find("img.return_button").hide();

			$layer2.css({
			height: $item.height(),
			overflow: "hidden" 
			});
		};

		// スライドショーの表示直前に行われる処理
		// コントロール用のボタンの配置を行う
		var _onSlideshowWillAppear = function($layer) {
			var $items = $(".l3banner_item", $layer);
			var $item = $items.removeClass("current").first().addClass("current");
			var index = $items.index($item);
			
			var $control = $(".l3banner_control", $layer);
			if($items.length <= 1) {
				$control.hide();
			} else {
				_adjustControlPosition($control, $item.width(), $item.height())
					.find("img.next_button").css("display", (index < $items.length-1 ? "block" : "none")).end()
					.find("img.prev_button").css("display", (index > 0 ? "block" : "none")).end()
					.find("img.return_button").hide();
			}
		};
		
		// 商品詳細の初期化処理
		var _setupDetail = function() {
			
			$l3Banner.find(">div.l3banner_banner>div.l3banner_layers>div.boxDetail.l3banner_layer2").each(function() {
			$(this)
				.find("a")
				.focus(function() {
				$(this).blur();
				return false;
				});
			});
		};

		// 商品詳細の第三階層を隠して、第二階層を表示する
		var _resetLayer3Detail = function($layer3, animate) {

			var $layer2 = $layer3.siblings("div.boxDetail.l3banner_layer2");

			// アニメーションする場合
			if(animate) {

			// ボタンを隠す
			var $container = $layer3
				.find("div.l3banner_control")
				.fadeOut("fast")
				.end()
				.find("div.l3banner_container");

			var $items = $container.find(".l3banner_item");
			var $currentItem = $items.filter(".current").removeClass("current");
			var index = $items.index($currentItem);

			// 現在表示されている商品の最後の説明ページを探す
			var length = $items.length;
			var lastItemIndex = -1;
			for(var i = index; i < length; ++ i) {
				if($items.eq(i).hasClass("l3banner_last_item")) {
				lastItemIndex = i;
				break;
				}
			}
			// 見つからなかった場合は最後の説明ページを指定する
			if(lastItemIndex == -1) {
				lastItemIndex = length-1;
			}
			index = lastItemIndex;

			$items.eq(index+1).css("visibility", "hidden");

			// 移動距離を計算
			var diff = parseInt($container.css("left")) + (index * _bannerWidth);
			
			$container
				.stop(true, false)
				.animate({
				left: -_bannerWidth * (index+1)
				}, _defaultSlideDuration, _defaultSlideEasing, function() {
				$layer3
					.css({
					left: _bannerWidth
					});
				$items.eq(index+1).css("visibility", "visible");
				
				});

			$layer2
				.css({
				left: _bannerWidth + diff
				})
				.stop(true, false)
				.animate({
				left: 0
				}, _defaultSlideDuration, _defaultSlideEasing);

			// カレント表示の更新
			$layer2.addClass("current");
			$layer3.removeClass("current");

			} else {

			$layer2
				.css({
				left: 0
				});
			$layer3
				.css({
				left: _bannerWidth
				});
			}
		};

		// スライドショーの初期化処理
		// 最初と最後のアイテムにクラスを付与する
		var _setupSlideshow = function() {
			
			$l3Banner.find(">div.l3banner_banner>div.l3banner_layers>div.l3banner_slideshow").each(function() {
			    // コーディネートは処理しない
				if($(this).hasClass("boxCoordinate")) { return ; }
				$(this)
					.css({
						overflow: "hidden"
					})
					.find(">div.l3banner_container")
					.children().each(function() { // .l3banner_items
						$(this)
							.find(">div.l3banner_item:first")
							.addClass("l3banner_first_item")
							.end()
							.find(">div.l3banner_item:last")
							.addClass("l3banner_last_item")
							.end()
							.parent()
							.append($(this).children());
					})
					.remove("div.l3banner_items");
				});
				
			var $button = $("<img />")
				.addClass("imgover")
				.css({
					position: "absolute",
					cursor: "pointer"
				});
			var $control = $("<div />")
				.addClass("l3banner_control")
			.append($button.clone().addClass("next_button").attr("src", "https://www.uniqlo.com/global_images/uk/img/l3/liveban/btn_liveban_right.gif"))
			.append($button.clone().addClass("prev_button").attr("src", "https://www.uniqlo.com/global_images/uk/img/l3/liveban/btn_liveban_left.gif"))
			.append($button.clone().addClass("return_button").attr("src", "https://www.uniqlo.com/global_images/uk/img/l3/liveban/btn_liveban_return.gif"));
				
			$l3Banner.find(">div.l3banner_banner>div.l3banner_layers>div.l3banner_slideshow").each(function() {
			$(this)
				.append($control.clone())
				.find("div.l3banner_container")
				.css({
					position: "absolute",
					width: ($(this).find(".l3banner_item").length * _bannerWidth)
				})
				.find(".l3banner_item")
				.css({
					float: "left",
					width: _bannerWidth
				});
			});
			
			// 進むボタンを押したときの処理
			// スライドの移動。ボタンの表示/非表示の設定
			$l3Banner
			.find(">div.l3banner_banner>div.l3banner_layers>div.l3banner_slideshow")
			.find("div.l3banner_control>img.next_button").click(function(event) {
				
				if($(this).is(":animated")) { return; }
				
				var $container = $(this).parent().parent().find("div.l3banner_container");
				var $items = $container.find(".l3banner_item");
				var $currentItem = $items.filter(".current").removeClass("current");
				var index = $items.index($currentItem);
				var $nextItem = $items.eq(index+1);
				var height = $nextItem.addClass("current").height();
				
				var $layer = $("div.l3banner_banner.current>div.l3banner_layers>div.current");
				if($layer.hasClass("boxCoordinate")) {
					$layer.height(height);
				}
					
				if($nextItem.hasClass("l3banner_last_item")) {
						
					// 次に表示するページが最後のアイテムの場合の処理
					$(this)
						.attr("src", $(this).attr("dsrc"))
						.hide();
					var $otherButton = $(this).siblings().filter(".prev_button");
					($otherButton.is(":visible") ? 0 : $otherButton.fadeIn("fast"));
					$(this).siblings().filter(".return_button").show();
				
				} else {
				
					(index+2 >= $items.length ? $(this).fadeOut("fast") : $(this).show());
					var $otherButton = $(this).siblings().filter(".prev_button");
					($otherButton.is(":visible") ? 0 : $otherButton.fadeIn("fast"));
					$(this).siblings().filter(".return_button").hide();
				
				}
				
				// スライドのコンテナ
				$container
					.stop(true, false) // clearQueue and don't gotoEnd
					.animate({
						left: -_bannerWidth * (index+1)
					}, _defaultSlideDuration, _defaultSlideEasing, function() {
						_resizeBanner(_bannerWidth, height, null, 400);
					});
				_hideBannerMenu();
			});
			
			// 戻るボタンを押したときの処理
			// スライドの移動。ボタンの表示/非表示の設定
			$l3Banner
			.find(">div.l3banner_banner>div.l3banner_layers>div.l3banner_slideshow")
			.find("div.l3banner_control>img.prev_button").click(function(event) {
				
				if($(this).is(":animated")) { return; }
				
				var $container = $(this).parent().parent().find("div.l3banner_container");
				var $items = $container.find(".l3banner_item");
				var $currentItem = $items.filter(".current").removeClass("current");
				var index = $items.index($currentItem);
				var $prevItem = $items.eq(index-1); ////
				var height = $prevItem.addClass("current").height();
				
				var $layer = $("div.l3banner_banner.current>div.l3banner_layers>div.current");
				if($layer.hasClass("boxCoordinate")) {
					$layer.height(height);
				}
				
				if($prevItem.hasClass("l3banner_first_item")) {
					
					// 次に表示するページが最初のアイテムの場合の処理
					$(this).fadeOut("fast");
					var $otherButton = $(this).siblings().filter(".next_button");
					($otherButton.is(":visible") ? 0 : $otherButton.fadeIn("fast"));
					
				} else {
				
					(index-2 < 0 ? $(this).fadeOut("fast") : $(this).show());
					var $otherButton = $(this).siblings().filter(".next_button");
					($otherButton.is(":visible") ? 0 : $otherButton.fadeIn("fast"));
				
				}
				
				$returnButton = $(this).siblings().filter(".return_button");
				($returnButton.is(":visible") ? $returnButton.fadeOut("fast") : 0);
				
				// スライドのコンテナ
				$container
					.stop(true, false) // clearQueue and don't gotoEnd
					.animate({
						left: -_bannerWidth * (index-1)
					}, _defaultSlideDuration, _defaultSlideEasing, function() {
						_resizeBanner(_bannerWidth, height);
					});
				_hideBannerMenu();
			});
			
			// リターンボタンを押したときの処理
			// 商品詳細、第二階層への遷移
			$l3Banner
				.find(">div.l3banner_banner>div.l3banner_layers>div.l3banner_slideshow")
				.find("div.l3banner_control>img.return_button").click(function(event) {
					
					if($lastLayer && $lastLayer.is(":animated")) { return false; };
					
					var $currentLayer = $("div.l3banner_banner.current>div.l3banner_layers>div.current");
					var duration = Math.abs($lastLayer.height() - $currentLayer.height()) / 540 * 750;
					var height = ($currentLayer.hasClass("boxDetail") ? $lastLayer.height() : $currentLayer.height());
					
					_resizeBanner(_bannerWidth, height, null, duration);
					
					if($currentLayer.hasClass("boxDetail")) {
						$currentLayer.removeClass("current");
						_resetLayer3Detail($currentLayer, true);
					} else {
						_resetSlideshow($currentLayer, true);
					}
				
			});
		};
		
		// スライドショーをリセットする
		// 一枚目に戻る
		var _resetSlideshow = function($layer, animate) {
			
			// アニメーションする場合
			if(animate) {
				
				// ボタンがフェードアウ中の場合は処理をしない
				var $control = $layer.find("div.l3banner_control");
				if($control.is(":animated")) {
					return ;
				}
				
			
			var $container = $layer.find("div.l3banner_container");
			
			var $items = $container.find(".l3banner_item");
			var lastIndex = $items.length - 1;
			
			// 最初のページの位置を最後に移動する
			$items.last().after($items.first());
			
			// ボタンを隠す
			$control.fadeOut(200);
			
			// スライドさせる
			$container
				.stop(true, false)
				.css({
					left: -((lastIndex-1) * _bannerWidth)
				})
				.animate({
					left: -(lastIndex * _bannerWidth)
				}, _defaultSlideDuration, _defaultSlideEasing, function() {
					
					var $items = $(this)
						.css({
							left: 0
						})
						.children("div.l3banner_item");
						
					//  最後のページの位置を最初に戻す
					var $newItem = $items.last().addClass("current");
					$items.first().before($newItem);
					
					// ボタンを表示する
					$control.stop().fadeIn(200);
					_adjustControlPosition($control, $newItem.width(), $newItem.height())
						.find("img.next_button").show().end()
						.find("img.prev_button").hide().end()
						.find("img.return_button").hide();
				});
				
			} else {
				$layer3
					.css({
						left: 0
					});
			}
		};
		
		// L3動くバナーの初期化処理
		var _setup = function() {

			if($l3Banner.hasClass("initialized")) { return; }

			$l3Banner
			.addClass("initialized");

			_setupCoordinate();
			_setupDetail();
			_setupSlideshow();

			_setupMenuButton();
			_setupMenu();

			
			// 各階層に高さを設定
			$("div.l3banner_layers").children().each(function() {
				if($(this).hasClass("boxVoice")) {
					$(this).height($(this).height() + parseInt($(this).css("paddingBottom")));
				} else if($(this).hasClass("boxCoordinate")) {
				} else if($(this).hasClass("l3banner_slideshow")) {
					$(this).css({
						width: _bannerWidth,
						height: _bannerHeight
					});
				} else {
					$(this).width(_bannerWidth);
				}
			});

			// 縦に並べる
			//		$l3Banner.css("overflow", "visible"); // tmep
			var top = 0;
			$(".l3banner_layers")
			.children().each(function() {

				if($(this).hasClass("boxDetail") && $(this).hasClass("l3banner_layer3")) {

				var $layer2 = $(this).siblings(".boxDetail");
				var thisTop = ($layer2 ? parseInt($layer2.css("top")) : 0);

				$(this)
					.css({
					left: _bannerWidth,
					top: thisTop
					});

				} else {
				$(this)
					.css({
					top: top
					});
				if($(this).hasClass("boxCoordinate")) {
					top += _maxCoordinateHeight;
				} else {
					top += $(this).height() + parseInt($(this).css("paddingBottom"))
				}
				}
				_totalHeight = top;
			});

			$l3Banner.find(">div.l3banner_banner>div.l3banner_layers")
			.css({
				position: "absolute"
			});

			// 初期表示
			$l3Banner
			.find("img.imgover")
			.rollover()
			.end()
			.find("div.l3banner_banner:first")
			.addClass("current")
			.show()
			.children()
			.hide()
			.filter("div.l3banner_layers")
			.show()
			.children()
			.hide()
			.filter("div.boxCover:first")
			.addClass("current")
			.fadeIn(900, function() {
				// Chromeのとき、#l3_content_bannerがoverflow:hidden;になっていると表示がおかしくなったので、
				// いったんカバー以外のレイヤーを隠し、カバーが表示されたら他のレイヤーも表示するように修正
				$l3Banner.find(">div.l3banner_banner>div.l3banner_layers").children().show();
			});

			var _showBannerMenuFirstTime = function() {

			// 右上メニューの表示
			var $bannerMenu = $l3Banner
				.find("div.l3banner_banner:first>div.l3banner_menu_container");
			var top = parseInt($bannerMenu.css("top"));
			var height = $bannerMenu.height();

			if(_isSupportOpacity) {

				$bannerMenu
				.delay(550)
				.css({
					height: (($bannerMenu.height()*0.2)|0),
					opacity: 0
				})
				.animate({
					top: top,
					height: height,
					opacity: 1.0
				}, 500, "easeOutCubic")
				.show()
			} else {
				// IE6,7,8はフェードさせない
				$bannerMenu
				.delay(550)
				.css({
					height: 0
				})
				.animate({
					top: top,
					height: height
				}, 550, "easeOutCubic")
				.show();
			}

			};
			_showBannerMenuFirstTime();

		}
		
		var _init = function() {
			
			// カバー画像以外は表示を隠す
			$("#l3_content_banner>div.l3banner_banner")
				.filter(":first")
				.find("div.l3banner_layers>div.boxCover:first")
				.hide();

			// ロールオーバーを設定
			$l3Banner
				.find("img.imgover")
				.rollover();

			// 右上メニューは imgoverクラスがないので個別に設定
			var $topMenuItem = $l3Banner
				.find("ul.btnLivebanMenu>li>a>img")
				.rollover()
				.filter(":first"); // 「TOPへ」
				
			// 「TOPへ」は初期状態でマウスオーバー時の画像が表示される
			$topMenuItem.attr("src", $topMenuItem.attr("hsrc"));

			// メイン画像、メニュー項目画像、商品詳細のサムネイル用のセレクタ
			// これらの画像の読み込みを待ってからセットアップを開始する
			var mainImgSeleector = "div.boxCover>p>img";
			var menuButtonImgSelector = "ul.btnLivebanMenu>li>a>img";
			var boxDetailImgSelector = "div.boxDetail.l3banner_layer2>ul>li>a>img";
			var imgs = $(mainImgSeleector + "," + menuButtonImgSelector + "," + boxDetailImgSelector);

			var numOfImgs = imgs.length;
			
			if(numOfImgs == 0) {
				_setup();
			} else {
				$(window).bind('load', _setup);
			}
		};
	
		_init();
		

	///////////////////////////////////////////////////////

		return this;
	};
})(jQuery);

/*
 * L4 image switch plugin
 * @require jQuery UI Draggable
 */
(function($){
	$.fn["imageSwitcher"] = function(options){
		// settings
		var settings = $.extend({
			"$thumbs"  : null,
			"triggerID": "#prodImgDefault a",
			"targetID" : "#prodImgZOOMInner",
			"tooltipID": "#prodImgZOOMTooltip",
			"backID"   : "#prodImgZOOMBack",
			"cursorID" : "#prodImgZOOMCursorClose"
		}, options);
		
		var _imgs = [];
		
		// ドラッガブル拡大画像表示
		var _zoom = function(href){
			$.log("zoom: " + href);
			$(settings.targetID)
				.html(
					$("<img />")
						.attr("src", href)
						.addClass("draggable")
						.draggable({
							containment: "parent",
							drag: _dragging
						})
				)
				.parent()
				.fadeIn(200);
			
			// ツールチップ
			if(!$.support.opacity){
				// IE6,7,8はフェードさせない
				if($(settings.tooltipID).length>0){
					setTimeout(function(){
						$(settings.tooltipID).show();
					}, 200);
					setTimeout(function(){
						$(settings.tooltipID).remove();
					}, 10000);
				}
			}else{
				// IE6,7,8以外はフェードさせる
				$(settings.tooltipID)
					.delay(200)
					.fadeIn(300)
					.delay(10000)
					.fadeOut(300, function(){
						// 初回しか表示しないのでremove
						$(this).remove()
					});
			}
		};
		
		// 左カラムのサムネイル選択状態をリセット
		var _reset = function(){
			settings.$thumbs
				.removeClass("selected")
				.removeClass("current");
		};
		
		// ドラッグ中ハンドラ
		var _dragging = function(e, obj){
			// ドラッグしたままスクロールすると範囲外まで移動できちゃうので
			// ドラッグ終了時にposition判定して位置を補正してみる
			if(obj.position.left<0)   obj.position.left = 0;
			if(obj.position.left>430) obj.position.left = 430;
			if(obj.position.top <0)   obj.position.top  = 0;
			if(obj.position.top >430) obj.position.top  = 430;
		};
		
		// main
		this.each(function(){
			settings.$thumbs = $(this).find("li");
			
			// 左カラムのサムネイルクリックで画像拡大
			$(this)
				.find("li")
				.mouseover(function(){
					if(!$(this).hasClass("current")){
						$(this).addClass("selected");
					}
				})
				.mouseout(function(){
					if(!$(this).hasClass("current")){
						$(this).removeClass("selected");
					}
				})
				.find("a")
				.each(function(){
					// preload
					_imgs.push(new Image());
					_imgs[_imgs.length-1].src = $(this).attr("href");
				})
				.click(function(){
					// 選択状態なら処理しない
					if($(this).parent().hasClass("current")) return false;
					// サムネイル部のカレント表示切替
					$(this)
						.parent()
						.addClass("current")
						.addClass("selected")
						.siblings()
						.removeClass("current")
						.removeClass("selected");
					// 拡大表示
					_zoom($(this).attr("href"));
					return false;
				});
				
			// もどる
			$(settings.backID).click(function(){
				$(settings.targetID)
					.parent()
					.fadeOut(200);
				_reset();
				return false;
			});
			
			// 中央カラムの画像クリック
			$(settings.triggerID).live("click", function(){
				//$(this).blur();
				_zoom($(this).attr("href"));
				_reset();
				return false;
			});
		});
		return this;
	};
})(jQuery);

/*
 * L4 image switch
 * @require L4 image switch plugin
 */
$.extend({
	L4ImageSwitch: function(isrc, asrc){
		// 中央カラムの画像入れ替え
		var img = $("#prodImgDefault").html().replace(/(^\s+)|(\s+$)/g, "");
		img = img.replace(/(\shref=\")([^\"]*)/im, "$1"+asrc);
		img = img.replace(/(\ssrc=\")([^\"]*)/im,  "$1"+isrc);
		$("#prodImgDefault").html(img);
		// 左カラムのサムネイルのカレント解除
		$("#prodImgZOOMBack").trigger("click");
	}
});

/*
 * L4 color chips plugin
 * @require L4 image switch
 */
(function($){
	$.fn["colorChips"] = function(options){
		var settings = $.extend({
			"colorNameId"     : "#chipColorName>.colorName"
		}, options);
		
		var _imgs = [];
		
		this.each(function(){
			$(this)
				.mouseover(function(){
					if($(this).parent().hasClass("selected")) return;
					$.L4ImageSwitch($(this).attr("href"), $(this).attr("rel"));
					$(settings.colorNameId).text($(this).attr("title"));
				})
				.mouseout(function(){
					if($(this).parent().hasClass("selected")) return;
					var $c = $(this).parent().parent().find(".selected>a");
					$.L4ImageSwitch($c.attr("href"), $c.attr("rel"));
					$(settings.colorNameId).text($c.attr("title"));
				})
				.click(function(){
					if($(this).parent().hasClass("selected")) return;
					$(this).parent().addClass("selected").siblings().removeClass("selected");
					return false;
				});
			
			// preload
			_imgs.push(new Image());
			_imgs[_imgs.length-1].src = $(this).attr("href");
			_imgs.push(new Image());
			_imgs[_imgs.length-1].src = $(this).attr("rel");
		});
		return this;
	};
})(jQuery);

/*
 * UT Top Page Plugin
 */
(function($) {
	$.fn["utTop"] = function(options){
	
	// settings
	var settings = $.extend({
		column:3
	}, options);
	
	//------- CONST ------------------------------------------------------
	var _CURRENT_TAG   = "uttop_current";
	var _HIDE_TAG      = "uttop_hide";
	var _OVER_TAG      = "uttop_over";
	var _DUMMY_TAG     = "uttop_dummy";
	
	var _DEFAULT_TAG   = "uttop_item_default";
	var _ROLLOVER_TAG  = "uttop_item_rollover";
	var _DETAIL_TAG    = "uttop_item_detail";
	var _THUMB_TAG     = "uttop_item_thumb";
	var _CONTAINER_TAG = "uttop_item_container";
	var _ITEMS_TAG     = "uttop_items";
	
	var _DEFAULT_HEIGHT          = 425; // アニメーションの時間を決める基準となる高さ（ピクセル）
	var _SHOW_CONTAINER_DURATION = 500;
	var _SHOW_CONTAINER_EASING   = "easeOutQuart";
	var _HIDE_CONTAINER_DURATION = 500;
	var _HIDE_CONTAINER_EASING   = "easeOutQuart";
	var _SHOW_DETAIL_DURATION    = 500;
	var _SHOW_DETAIL_EASING      = "easeOutExpo";
	var _HIDE_DETAIL_DURATION    = 500;
	var _HIDE_DETAIL_EASING      = "easeOutExpo";
	
	var MOUSE_OUT_TIMEOUT = 400;
	
	//------- MEMBERS -----------------------------------------------------
	var $root = $(this);
	var _rootWidth = $root.width();
	
	// 横列の数
	var _cols = settings.column;
	
	var i, j;
	var $utItems = $root.find(">div." + _ITEMS_TAG);
	var $utDetails;
	var $utThumbs;
	var $utContainers;
	
	var _detailHeights = [];
	var _containerHeiths = [];
	
	var _mouseOutTimeoutID = -1;
	
	//-------------------------------------------------------
	// container
	//-------------------------------------------------------
	
	// コンテナの初期状態の高さを取得する
	var _getContainerHeight = function($container) {
		return _containerHeiths[$utContainers.index($container)];
	};
	
	// コンテナを表示する
	var _showContainer = function($container, height, onComplete) {
		
		var fireOnComplete = function() {
			if(onComplete != null) {
				onComplete($container);
			}
		};
	
		// 表示後の高さ
		height = (height == null ? _getContainerHeight($container) : height);
		var currentHeight;
		var willShow = false;
		
		if($container.is(":visible")) {
			currentHeight = $container.height();
			willShow = (currentHeight != height);　// 変更後の高さが今と異なる場合表示する
		} else {
			currentHeight = 0;
			willShow = (height > 0); // 変更後の高さが0の場合表示する
		}
		
		if(!willShow) {
			fireOnComplete();
			return;
		}
		
		// アニメーション時間の計算
		var r = Math.abs(height - currentHeight) / _DEFAULT_HEIGHT;
		var duration = _SHOW_CONTAINER_DURATION * r;
		
		$container
			.removeClass(_HIDE_TAG)
			.show()
			.stop()
			.css({
			    height:currentHeight
			})
			.animate({
				height:height
			}, duration, _SHOW_CONTAINER_EASING, fireOnComplete);
	};
	
	// コンテナを非表示にする
	var _hideContainer = function($container, onComplete) {
		
		if(!$container.is(":visible")) {
			return;
		}
		
		// アニメーション時間の計算
		var height = _getContainerHeight($container);
		var r = $container.height() / height;
		var duration = _HIDE_CONTAINER_DURATION * r;
		
		$container
			.addClass(_HIDE_TAG)
			.show()
			.stop()
			.animate({
				height:0
			}, duration, _HIDE_CONTAINER_EASING, function() {
				var height = _getContainerHeight($(this));
				$(this)
					.removeClass(_HIDE_TAG)
					.hide();
				if(onComplete != null) {
					onComplete($(this));
				}
			});
	};
	
	//-------------------------------------------------------
	// detail
	//-------------------------------------------------------
	
	// 詳細の初期状態の高さを取得する
	var _getDetailHeight = function($detail) {
		return _detailHeights[$utDetails.index($detail)];
	};
	
	// 詳細を表示する
	var _showDetail = function($detail, animated, onComplete) {
		
		$detail
			.removeClass(_HIDE_TAG)
			.show();
		
		if(animated) {
			
			// アニメーション中でなければ透明度を初期値に設定する
			if(!$detail.is(":animated")) {
				$detail
					.css({
						opacity:0.90
					});
			}
			
			// 上から下にスライドさせる
			var height = _getDetailHeight($detail);
			$detail
				.css({
					top:-height
				})
				.stop()
				.animate({
					top:0,
					opacity:1.0
				}, _SHOW_DETAIL_DURATION, _SHOW_DETAIL_EASING, function() {
					if(onComplete != null) {
						onComplete($(this));
					}
				});
		} else {
			$detail
				.show()
				.css({
					top:0,
					opacity:1.0
				})
			if(onComplete != null) {
				onComplete($detail);
			}
		}
	};
	
	// 詳細を非表示にする
	var _hideDetail = function($detail, animated, onComplete) {
	};
	
	//-------------------------------------------------------
	// timeout
	//-------------------------------------------------------
	
	// マウスアウトして一定時間経過した際の処理を設定する
	var _setMouseOutTimeout = function(onTimeout) {
		_clearMouseOutTimeout();
		_mouseOutTimeoutID = setTimeout(onTimeout, MOUSE_OUT_TIMEOUT);
	};
	
	// マウスアウトして一定時間経過した際の処理をクリアする
	var _clearMouseOutTimeout = function() {
		if(_mouseOutTimeoutID != -1) {
			clearTimeout(_mouseOutTimeoutID);
			_mouseOutTimeoutID = -1;
		}
	}
	
	//-------------------------------------------------------
	// setup
	//-------------------------------------------------------
	
	// 行ごとに詳細要素をまとめ、コンテナに格納する
	var _groupItemDetails = function() {
		
		var row = 0;
		// コンテナを生成し、指定した要素をコンテナに追加する
		var appendToContainer = function(items) {
			var length = items.length;
			if(length == 0) {
				return ;
			}
			var contentWidth = _rootWidth;
			var contentHeight = items[0].height();
			for(j = 1; j < length; ++ j) {
				if(items[j].height() > contentHeight) {
					contentHeight = items[j].height();
				}
			}
			
			_containerHeiths[row] = contentHeight;
			
			var $container = $("<div/>")
				.addClass(_CONTAINER_TAG)
				.hide()
				.css({
					position:"relative",
					height:contentHeight,
					overflow:"hidden",
					width:contentWidth,
					float:"left"
				});
			
			var length = items.length;
			for(i = 0; i < length; ++ i) {
				items
					.pop()
					.css({
						position:"absolute",
						width:contentWidth
					})
					.appendTo($container);
			}
			row ++;
			return $container;
		};
		
		var insertContainerAt = function(index, items) {
			$utThumbs
				.filter(":eq(" + index + ")")
				.after(appendToContainer(array));
		};
		
		var array = [];
		var count = 0;
		$utDetails
			.each(function() {
				
				_detailHeights[count] = $(this).height();
				
				array.push($(this));
				
				if(++count % _cols == 0) {
					insertContainerAt(count-1, array);
				}
			
			});
			
		if(array.length > 0) {
			insertContainerAt(count-1, array);
		}
	
	};
	
	// サムネイルのロールオーバーのオン/オフを切り替える
	var _toggleThumbAt = function($thumb) {
		var $default = $thumb.children(":first");
		var $rollover = $thumb.children(":last");
		
		if($default.is(":visible")) {
			$default
				.hide();
			$rollover
				.show();
		} else {
			$default
				.show();
			$rollover
				.hide();
		}
	};
	
	// コンテナを閉じる
	var _closeContainer = function() {
		var $container = $utContainers
			.filter("." + _CURRENT_TAG)
			.removeClass(_CURRENT_TAG);
		
		_hideContainer($container, function($target) {
			$target
				.children()
				.removeClass(_CURRENT_TAG);
		});
	};
	
	// サムネイルを初期化する
	var _setupThumbs = function() {
		
		// uttop_item_default と uttop_item_rollover を
		// ひとつのdivにまとめる（ロールオーバーをするため）
		$utItems
			.find(">div." + _DEFAULT_TAG + ",div." + _ROLLOVER_TAG)
			.each(function() {
				if($(this).hasClass(_DEFAULT_TAG)) {
					var $next = $(this).next();
					
					var $thumb = $("<div/>")
						.addClass(_THUMB_TAG)
						.css({
							float:"left",
							/* uttop_item_defaultに設定されているマージンをサムネイルに適用する */
							marginTop:$(this).css("marginTop"),
							marginRight:$(this).css("marginRight"),
							marginBottom:$(this).css("marginBottom"),
							marginLeft:$(this).css("marginLeft")
						});
					
					$(this)
						.css({
							margin:0
						})
						.before($thumb)
						.appendTo($thumb);
					
					if($next.hasClass(_ROLLOVER_TAG)) {
						$next
							.hide()
							.css({
								margin:0
							})
							.appendTo($thumb);
					}
				}
			});
			
		// マウスオーバー/マウスアウト時の処理
		$utThumbs = $utItems
			.find(">div." + _THUMB_TAG)
			.hover(
				// Mouse Over
				function() {
					_clearMouseOutTimeout();
					
					$(this)
						.addClass(_CURRENT_TAG);
					
					_toggleThumbAt($(this));
					
					var index;
					
					/** コンテナの表示 */
					index = $utThumbs
						.index($(this));
					var row = (index / _cols)|0;
					
					var $container = $utContainers
						.filter(":eq(" + row + ")");
						
					$utContainers
						.filter("." + _CURRENT_TAG)
						.each(function() {
						
							// 2つのjQueryオブジェクトが同じオブジェクトかどうか
							var isEquals =
								$(this) != null &&
								$container != null &&
								$(this).get(0) == $container.get(0);
							
							if(!isEquals) {
								_closeContainer();
							}
						});
					
					var isContainerVisible = $container
						.addClass(_CURRENT_TAG)
						.is(":visible");
			
			var $detail = $utDetails
				.filter(":eq(" + index + ")");
			
			// コンテナの表示
			var detailHeight = _getDetailHeight($detail);
			_showContainer($container, detailHeight, function($target) {
				var $thumb = $utThumbs
					.filter("." + _CURRENT_TAG);
				var $currentContainer = $utContainers
					.filter("." + _OVER_TAG);
				// マウスオーバーしている要素がなければコンテナを閉じる
				if($thumb.length == 0 &&
				   $currentContainer.length == 0) {
					_setMouseOutTimeout(_closeContainer);
				}
			});
			
			// 詳細要素が空の場合は何もしない
			if($detail.hasClass(_DUMMY_TAG)) {
				return ;
			}
					
					/** 詳細の表示 */
					var $details = $container
						.children("div." + _DETAIL_TAG);
					if(!isContainerVisible) {
						$details
							.each(function() {
								$(this)
									.hide()
									.css({
										opacity:1.0
									});
							});
					}
					
					// 表示する詳細を最前面に配置
					if($detail.siblings().length > 0) {
						$detail
							.siblings(":last")
							.after($detail);
							
					}
					
					if(!$detail.hasClass(_CURRENT_TAG)) {
						$detail
							.addClass(_CURRENT_TAG)
							.siblings("." + _CURRENT_TAG)
							.removeClass(_CURRENT_TAG);
						
						_showDetail($detail, isContainerVisible);
						
						// 表示されている詳細がすべてアニメーション中の場合
						// 一番後ろの詳細のアニメーションを停止し、下端に隙間ができないようにする
						var visibleLength = $detail.siblings(":visible").length;
						if($detail.siblings(":animated").length == visibleLength) {
							$detail
								.siblings(":visible:first")
								.stop()
								.css({
									top:0
								});
						}
					}
				},
				// Mouse Out
				function() {
					
					_clearMouseOutTimeout();
					
					$(this)
						.removeClass(_CURRENT_TAG);
					
					_toggleThumbAt($(this));
					
					/** コンテナの非表示 */
					var $container = $utContainers
						.filter("." + _CURRENT_TAG);
					
					// 表示アニメーション中かどうか
					if(!$container.is(":visible") ||
					   !$container.is(":animated") ||
						$container.hasClass(_HIDE_TAG)) {
						
						_setMouseOutTimeout(_closeContainer);
					}
				});
	};
	
	// 詳細要素の初期化処理
	var _setupDetails = function() {
		
		// uttop_item_detail が存在しない場合は空のdivを追加する
		$utItems
			.find(">div." + _THUMB_TAG + ",div." + _DETAIL_TAG)
			.each(function() {
				if( $(this).hasClass(_THUMB_TAG) &&
					!$(this).next().hasClass(_DETAIL_TAG)) {
					$(this)
						.after($("<div/>")
							   .addClass(_DETAIL_TAG)
							   .addClass(_DUMMY_TAG));
				}
			});
		
		$utDetails = $utItems.find(">div." + _DETAIL_TAG);
		
		// 詳細を列ごとにまとめてコンテナに格納する
		_groupItemDetails();
		
		// マウスオーバー/マウスアウト時の処理
		$utContainers = $root
			.find(">div.uttop_items>div." + _CONTAINER_TAG)
			.hide()
			.hover(
				// Mouse Over
				function() {
					
					_clearMouseOutTimeout();
					
					$(this)
						.addClass(_CURRENT_TAG)
						.addClass(_OVER_TAG);
					
					// 非表示アニメーション中の場合
					if($(this).is(":animated") &&
					   $(this).hasClass(_HIDE_TAG)) {
						_showContainer($(this), function($target) {
							var $thumb = $utThumbs
								.filter("." + _CURRENT_TAG);
							var $currentContainer = $utContainers
								.filter("." + _OVER_TAG);
							if($thumb.length == 0 && $currentContainer.length == 0) {
								_setMouseOutTimeout(_closeContainer);
							}
						});
					}
				},
				// Mouse Out
				function() {
					
					$(this)
						.removeClass(_OVER_TAG);
					
					if(!$(this).is(":animated")) {
						_setMouseOutTimeout(_closeContainer);
					}
				});
	
	};
	
	// uttop_item_default, uttop_item_rollover, uttop_item_detail 以外の要素を取り除く
	var _removeInvalidElements = function() {
		$utItems
			.children(":not(div." + _DEFAULT_TAG + ",div." + _ROLLOVER_TAG + ",div." + _DETAIL_TAG + ")")
			.remove()
	};
	
	// UTトップを初期化する
	var _setup = function() {
		_removeInvalidElements();
		_setupThumbs();
		_setupDetails();
	};
	_setup();
	
	return this;
	};
})(jQuery);

// initialize
$(function(){
	$(".imgover").rollover();
	$("#header").header();
	$("#utilMainItemList").sizeSwitcher();
	$("#selectedSizeCombo").sizeFilter();
	$("#prodThumbImgs").imageSwitcher();
	$(function() {
		var cache = [];
		$.preLoadImages = function() {
			var args_len = arguments.length;
			for (var i = args_len; i--;) {
				var cacheImage = document.createElement('img');
				cacheImage.src = arguments[i];
				cache.push(cacheImage);
			}
		}
		getPath = $("#l3_content_banner img").attr("src");
		$.preLoadImages(getPath, getPath);
		$("#l3_content_banner").l3Banner();
	});
	
	// for company only.
	$("body#company #boxCompanyCont>.listCompanyCont").autoHeight({column: 2});
	$("body#company .btn2p>.listCompanyCont").autoHeight({column: 2});
	$("body#company #boxCompanyCont02>.listCompanyCont").autoHeight({column: 4});
	$("body#company #boxCompanyCont03>.container>.listCompanyCont").autoHeight({column: 4});
	
	// for noEC only.
	$("body#noEC #listChipColor a").colorChips();
	$("body#noEC #utilMainItemList").sizeSwitcher2();
	$("body#noEC #blkMainItemList>.unit").listColorChips();

	// for UT
	$("div#uttop_content").utTop({column:3});
});

