/**
 * Stylife　JavaScript lib.js
 * @author kurihara.masaaki
 * @version $Rev$
 * @requires jquery 1.6.x later
 */

if(!window.Stylife) Stylife ={};

(function(w, d, $) {
	/*@cc_on 
		_d=document;eval('var document=_d')
	@*/
	/**
	 * Stylife Util Class
	 * @author kuriharamasaaki
	 * @version $Rev$
	 * @requires OtherClassName
	 */
	
	Stylife.Util = {
		hashStyle: "#!",
		getUrlVars: function(){
			var vars = {}, hash;
			// URLシリアライズ
			var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

			// hashに詰める
			for(var i = 0; i < hashes.length; i++){
				hash = hashes[i].split('=');

				vars[hash[0]] = hash[1];
				// vars[hash[0]] = hash[1];
			}
			return vars;
		},
		getUrlVar: function(name){
			return this.getUrlVars()[name];
		},
		addUrlHash: function(arg) {
			var myUri = this.hashStyle;
			var myAnchor = arg;
			var myLocation = '';
			myLocation = myUri + myAnchor;
			window.location.href = myLocation;
		}
	};

	/**
	 * Stylife Storege Core
	 * @author kurihara.masaaki
	 * @version $Rev$
	 * @requires jquery 1.6.x later
	 */

	Stylife.Storage = {
		 config:function(id) {
			return function(name, value) {
				name = id + '_' + name;
				var options = {
					expires: +new Date + 2592000000, // 30 days
					path : '/'
				};
				return value === undefined ?
					Stylife.Storage.updateCookie(name, options) :
					Stylife.Storage.cookie(name, value, options);
			};
		},

		cookie: function(name, value, options) {
			if (!'cookie' in d || !name) return;

			switch (value) {
				case undefined:
					var cookie = d.cookie;
					if (cookie && cookie != '') {
						var cookies = cookie.split(';');
						for (var i = 0, l = cookies.length, c; i < l; ++i) {
							c = $.trim(cookies[i]);
							if (c && c.indexOf(name + '=') == 0) {
								return decodeURIComponent(c.slice(name.length + 1));
							}
						}
					}
					break;

				default:
					options = options || {};
					if (value === null) {
						value = '';
						options.expires = -1;
					}

					var params = {
						expires: options.expires ?
							new Date(options.expires).toUTCString() :
							undefined,
						path : options.path,
						domain : options.domain
					};

					var p = [], v;
					for (var k in params) {
						v = params[k];
						v && p.push(k + '=' + v);
					}
					options.secure && p.push('secure');
					p.unshift(encodeURIComponent(value));

					d.cookie = name + '=' + p.join(';');
			}
		},

		updateCookie: function(name, options) {
			var value = Stylife.Storage.cookie(name);
			value !== undefined && Stylife.Storage.cookie(name, value, options);
			return value;
		}
	};

	/**
	 * Brand Page Class
	 * @author kuriharamasaaki
	 * @version $Rev$
	 * @requires OtherClassName
	 */
	Stylife.Brands = {
		inited : false,
		review_base_url: '/asynchronus/tlb-common-review/async-regist-nick-shoptop',
		setup: function(e) {
			// bind Event Lsitener			
			$('a#tlb_regist_nickname').live("click", this.registNickname);
		    $('a#tlb_regist_review').live("click", this.registReview);  
		},
		registReview: function(e) {
	        //$.get("/tlb-common-async/load?tlbcname=tlb-common-review&tlbaname=async-review-shoptop",
	        $.get("/asynchronous/tlb-common-review/async-review-shoptop",{
				headline: $("#tlb_review_comment").val(),
	 			fb		: $('#tlb_fb_chk').is(':checked'),
				tw		: $('#tlb_tw_chk').is(':checked'),
				brand_cd: $("#tlb_review_brand_cd").val(),
				site_cd	: $("#tlb_review_site_cd").val()}, 
	            function(data) {
	                $("#tlb_review").html(data);
					setTimeout(function() {
						if (jQuery('#tlb_staff-recommend_block li').length >= 4) {
							var review = jQuery('#tlb_staff-recommend_block').vTicker({
										   speed: 500,
										   pause: 7500,
										   showItems: 4,
										   animation: 'fade',
										   mousePause: true,
										   height: 385,
										   direction: 'down'
										});
						};
					},0);
	        });
		},
		registNickname:function (argument) {
	        //$.get("/tlb-common-async/load?tlbcname=tlb-common-review&tlbaname=async-regist-nick-shoptop",
	        $.get("/asynchronous/tlb-common-review/async-regist-nick-shoptop",{
					nickname: $("#tlb_nickname").val(),
					brand_cd: $("#tlb_review_brand_cd").val(),
					site_cd: $("#tlb_review_site_cd").val()}, 
	            function(data) {
	                $("#tlb_review").html(data);
					setTimeout(function() {
						if (jQuery('#tlb_staff-recommend_block li').length >= 4) {
						var review = jQuery('#tlb_staff-recommend_block').vTicker({
									   speed: 500,
									   pause: 7500,
									   showItems: 4,
									   animation: 'fade',
									   mousePause: true,
									   height: 385,
									   direction: 'down'
									});
						};
					},0);
	        });
		}
	};

	/**
	 * Seach Conditons Class
	 * @author kurihara.masaaki
	 * @version $Rev$
	 * @requires Stylife.Storage
	 */
	
	Stylife.ImageViewer = {
		inited:false,
		setup: function  () {
			jQuery('#tlb_itemArea').jqm();
			this.inited= true;
		},
		show: function(event,site_cd,item_cd,scd) {
			if (!event) return;
			if (event.preventDefault) {
				event.preventDefault();
			// otherwise set the returnValue property of the original event to false (IE)
			} else {
				event.returnValue = false;
			}
			this.inited || this.setup();

			var param = {
				site_cd: site_cd,
				model_cd: item_cd,
				scd: scd || ""
			};

			var params = $.param(param);

			var url = "/asynchronous/tlb-item-image/async-zoom?"+params+"&callback=?";

			$.getJSON(url,function(data){
				$('#tlb_itemArea').jqmShow(); 

				var template = $("#itemViewerTmpl");
				var view = template.tmpl(data);

				$(view).find('#phVariationField ul li a img').click(function(e) {
					e.preventDefault();
					var photo = $(this).attr('label');
					$('#tlb_itemArea #item-photo img').attr('src',photo);
					$('#tlb_itemArea #phVariationField ul li a img').removeClass('selected');
					$(this).addClass('selected');
					return false;	
				});

				$('#tlb_itemArea').html(view);

				// $('#phVariationField ul li a img').click(Stylife.ImageViewer.photoSlect);

				var viewportOffset = $(w).scrollTop();

				var viewportHeight = window.innerHeight ? window.innerHeight : $(window).height();
				var viewportWidth = window.innerWidth ? window.innerWidth : $(window).width();
				var top  = (viewportHeight/ 2) - ($("#tlb_itemArea").height() / 2) + viewportOffset;
				var left = (viewportWidth/ 2) - ($("#tlb_itemArea").width() / 2);  
 
				$('#tlb_itemArea').css('top',top).css('left',left).css('position','absolute');

			  });
		},
		photoSlect: function(e) {
			e.preventDefault();
			var photo = $(this).attr('label');
			$('#tlb_itemArea #zoom').attr('src',photo);
			$('#tlb_itemArea #phVariationField ul li a img').removeClass('selected');
			$(this).addClass('selected');
		},
		close:function(e) {
			if (!e) return;
			if (e.preventDefault) {
				e.preventDefault();
			// otherwise set the returnValue property of the original event to false (IE)
			} else {
				e.returnValue = false;
			}
			
			$('#tlb_itemArea').jqmHide(); 
			return false;
		}
		
		
	};
	/**
	 * Item Page Class
	 * @author kuriharamasaaki
	 * @version $Rev$
	 * @requires OtherClassName
	 */
	Stylife.Items = {
		inited : false,
		setup: function() {
			// bind Event Lsitener			
			$('a#tlb_regist_nickname').live("click", this.registNickname);
		    $('a#tlb_regist_review').live("click", this.registReview);  
			this.inited = true;

		},
		registReview: function(e) {			
	        //$.get("/tlb-common-async/load?tlbcname=tlb-common-review&tlbaname=async-review-item",
	        $.get("/asynchronous/tlb-common-review/async-review-item",{
				headline: $("#tlb_review_comment").val(),
	 			fb		: $('#tlb_fb_chk').is(':checked'),
				tw		: $('#tlb_tw_chk').is(':checked'),
				model_cd: $("#tlb_review_model_cd").val(),
				site_cd	: $("#tlb_review_site_cd").val()}, 
	            function(data) {
	                $("#tlb_review").html(data);
					setTimeout(function() {
						if (jQuery('.tlb_review .tlb_carousel li').length >= 4) {
		
						var review = $('.tlb_review .tlb_carousel').vTicker({
									   speed: 500,
									   pause: 7500,
									   showItems: 5,
									   animation: 'fade',
									   mousePause: true,
									   height: 360,
									   direction: 'down'
									});
						};
						if (jQuery('.tlb_staff-recommend .tlb_carousel li').length >= 4) {

						var recommend = $('.tlb_staff-recommend .tlb_carousel').vTicker({
									   speed: 500,
									   pause: 7500,
									   showItems: 5,
									   animation: 'fade',
									   mousePause: true,
									   height: 360,
									   direction: 'down'
									});
						};
					},0);
	        });
		
		},
		registNickname:function (e) {
			//$.get("/tlb-common-async/load?tlbcname=tlb-common-review&tlbaname=async-regist-nick-item",
	        $.get("/asynchronous/tlb-common-review/async-regist-nick-item",{
					nickname: $("#tlb_nickname").val(),
					model_cd: $("#tlb_review_model_cd").val(),
					site_cd: $("#tlb_review_site_cd").val()}, 
	            function(data) {
	                $("#tlb_review").html(data);
	
					setTimeout(function() {
						if (jQuery('.tlb_review .tlb_carousel li').length >= 4) {

						var review = $('.tlb_review .tlb_carousel').vTicker({
									   speed: 500,
									   pause: 7500,
									   showItems: 5,
									   animation: 'fade',
									   mousePause: true,
									   height: 360,
									   direction: 'down'
									});
						};
						if (jQuery('.tlb_staff-recommend .tlb_carousel li').length >= 4) {

						var recommend = $('.tlb_staff-recommend .tlb_carousel').vTicker({
									   speed: 500,
									   pause: 7500,
									   showItems: 5,
									   animation: 'fade',
									   mousePause: true,
									   height: 360,
									   direction: 'down'
									});
						};
					},0);
	        });
		}
	};

	/**
	 * Seach Conditons Class
	 * @author kurihara.masaaki
	 * @version $Rev$
	 * @requires Stylife.Storage
	 */
	Stylife.Search ={
		config: null,
		mode : 'search',
		inited: false,
		suggest: null,
		list_base_url: '/asynchronus/tlb-alllists-filter/async-ajax',
		item_base_url: '/asynchronous/tlb-alllists/async-top',
		lists: {
			"site":"#tlb_search_site_ul",
			"shop":"#tlb_search_shop_ul",
			"brand":"#tlb_search_brand_ul",
			"category_l": "#tlb_search_itemcat_ul",
			"category_m": "#tlb_search_itemcat_ul li ul"
		},
		condtion:{
			free_word:"",
			site_cd:[],
			brand_cd:"",
			maker_name:[],
			category_l_cd:"",
			category_m_cd:[],
			fixed_price_lower:"",
			fixed_price_upper:"",
			discount_rate_lower:"",
			disp_from_date:"",
			sort:"",
			sale:"",
			inventory_flg:"1",
			rows:"",
			total_cnt:"",
			page:""
		},
		crumb : {
			site:{
				text: "",
				url:""
			},
			shop:{
				text: "",
				url:""
			},
			brand:{
				text: "",
				url:""
		
			},
			item_l:{
				text: "",
				url:""
			},
			item_m:{
				text: "",
				url:""
			}
		},
		
		/**
		 * Set Up Stylife.Search Class
		 * Add Event Seach Condtion Block
		 * @public
		 */
		// 01="sf" Stylife 
		// 13="nuan"nuan+ 
		// 05="looks"Look!s the NET 
		// 15="chuse"　CHUSE

		setup: function(){

			// set Search Condtion Cookie.
			this.config = Stylife.Storage.config("search");

			// set this.inited = true;
			this.inited = true;

			var siteList= this.lists['site'];
			var shopList = this.lists['shop'];
			var brandList = this.lists['brand'];
			var itemCategoryList = this.lists['category_l'];
			var itemCategoryListM = this.lists['category_m'];

			// Brand List and Shop List Add Event
			// $(siteList+" li a,"+shopList+" li a,"+brandList+" li a,"+itemCategoryList+" li a,"+itemCategoryList + " li ul li a").live("click",this.blockListClick);

			// bind drill down
			$('#tlb_search_rows a,#tlb_search_sale a,#tlb_search_sort a,#tlb_search_inventory_flg a').click(this.blockDrillDownClick);

			// init ShopSuggest and Brand Suggest.
			var shoplistsuggest = this.shopListSuggest();
			var branlistsuggest = this.brandListSuggest();

			// $("input[name=disp_from_date]").datepicker({
			// 	dateFormat: 'yymmdd',
			// 	dayNamesMin: ['日','月', '火', '水', '木', '金', '土'],
			// 	monthNames: ['1月','2月','3','4','5','6','7','8','9','10','11','12']
			// });

			// pageing処理
			$('ul.tlb_paging li a').live('click',this.blockPageingClick);

			$('ul.tlb_paging li.next a').live('click',this.blockPageingNextClick);
			$('ul.tlb_paging li.prev a').live('click',this.blockPageingPrevClick);
			
			// 絞り込みボタンの登録
			// 性別絞り込み
			$('#sex').change(this.changeSex);
			
			// フリーワード絞り込み
			$('#tlb_free_word_submit').click(this.freeWordNarrowDown);

			// 価格絞り込み
			$('#tlb_price_submit').click(this.priceNarrowDown);

			// 割引率で絞り込み
			$('#tlb_off_price_submit').click(this.offPriceNarrowDown);

			// 日付で絞り込み
			$('#tlb_date_submit').click(this.dispFromDateNarrowDown);

			// this.updateTotalCount();
		},
		updateTotalCount:function () {
			// if (!Stylife.Search.condtion['total_cnt']) {
				$('#tlb_maxrows').html('全 '+Stylife.Search.condtion['total_cnt']+' 件').fadeIn();
			// };
		},
		scrollto:function() {
			var top = 0;

			if (Stylife.Search.mode == 'shop') {
				top =  $('.tlb_result-item').offset().top;
			};
			
			$('html,body').animate({ scrollTop: top}, 'slow','swing');
		},
		blockDrillDownClick:function(e) {
			// 遷移しない
			e.preventDefault();
			var parent =  $(this).parent();
			var target = parent.attr("id");
			// 全体class削除をし選択項目に付与

			$("#"+target + " a").removeClass('select');
			// ($(this).hasClass('select'))? $(this).removeClass('select') : $(this).addClass('select');
			$(this).addClass('select');
			
			// modeストリップ
			var mode = parent.attr("id").replace(/tlb_search_/,"");
			var val = $(this).attr("val");

			// sort:"",
			// sale:"",
			// rows:"",
			// page:""
			// inventory_flg:"1"

			Stylife.Search.condtion[mode] = val;

			if (mode == 'rows') Stylife.Search.config('rows',val);
			if (mode == 'sele') Stylife.Search.condtion['page'] = "";

			// page reset
			Stylife.Search.condtion['page'] = "";

			var params = $.param(Stylife.Search.condtion);
			var url = Stylife.Search.item_base_url + "?" + params;
			
			$.cookie(Stylife.Search.mode+'_condition',url.replace(this.item_base_url+"?",""));

			Stylife.Search.updateList(url);
			Stylife.Util.addUrlHash('re');

		},
		blockPageingPrevClick: function(e) {
			// 遷移しない
			e.preventDefault();
			var prev_page_num = Stylife.Search.condtion['page']--;

			if (prev_page_num >= 0) {
				var params = $.param(Stylife.Search.condtion);
				var url = Stylife.Search.item_base_url + "?" + params;

				$.cookie('search_condition',url.replace(this.item_base_url+"?",""));
				Stylife.Search.updateList(url);
			};
			// area0
			Stylife.Search.scrollto();
			Stylife.Util.addUrlHash('re');
		},
		blockPageingNextClick: function(e) {
			// 遷移しない
			e.preventDefault();
			var last_page_num = parseInt($('.tlb_paging li.last a').text());

			var next_page_num = Stylife.Search.condtion['page']++;

			if (next_page_num <= last_page_num) {

				var params = $.param(Stylife.Search.condtion);
				var url = Stylife.Search.item_base_url + "?" + params;

				$.cookie(Stylife.Search.mode+'_condition',url.replace(this.item_base_url+"?",""));

				Stylife.Search.updateList(url);
			};

			Stylife.Search.scrollto();

			Stylife.Util.addUrlHash('re');
		},
		blockPageingClick: function(e) {
			// 遷移しない
			e.preventDefault();

			var page = $(this).text();
			if (!page) return;
			Stylife.Search.condtion['page'] = page;
			
			var params = $.param(Stylife.Search.condtion);
			var url = Stylife.Search.item_base_url + "?" + params;

			$.cookie(Stylife.Search.mode+'_condition',url.replace(this.item_base_url+"?",""));
			
			Stylife.Search.updateList(url);
			Stylife.Search.scrollto();
			
			Stylife.Util.addUrlHash('re');
			
		},
		blockListClick: function(event) {
			if (!event) return;
			if (event.preventDefault) {
				event.preventDefault();
			} else {
				event.returnValue = false;
			}
			
			var target = event.target || event.srcElement;
			var blockid = $(target).attr("block");
			var text = $(target).text();

			var val = $(target).attr("val") || "";

			var selectedListText = $(target).text();
			var list = Stylife.Search.lists[blockid];

			switch (blockid){
				case 'site':{
					($(target).hasClass('select'))? $(target).removeClass('select') : $(target).addClass('select');

					var sites = $('#tlb_search_site_ul li a.select').map(function(){
										return $(this).attr('val');
									}).get();

					var sites_text = $('#tlb_search_site_ul li a.select').map(function(){
										return $(this).text();
									}).get();

					Stylife.Search.condtion['site_cd'] = sites;
					Stylife.Search.condtion['maker_name'] = '';
					Stylife.Search.condtion['brand_cd'] = '';
					Stylife.Search.condtion['maker_name'] = '';
					Stylife.Search.condtion['category_l_cd'] = '';
					Stylife.Search.condtion['category_m_cd'] = '';
					Stylife.Search.condtion['page'] = "";

					// パンクズリセット
					Stylife.Search.clearCrumb();
					var params = $.param(Stylife.Search.condtion);
					var url = "/asynchronous/tlb-alllists-filter/async-ajax?" + params + "&callback=?" ;
					
					$.getJSON(url,function (data) {
						var shops = data.brand;
						var brands = data.maker;
						var categories = data.category_l;

						Stylife.Search.updateShopBlock(shops);
						Stylife.Search.updateBrandBlock(brands);
						Stylife.Search.updateCategoryBlock(categories);
					});

					// pageをリセット
					Stylife.Search.condtion['page'] = "";
					var params = $.param(Stylife.Search.condtion);

					var url = Stylife.Search.item_base_url + "?" + params;

					Stylife.Search.crumb[blockid]['text'] = (sites.length == 1) ? sites_text : "";
					Stylife.Search.crumb[blockid]['val'] = (sites.length == 1) ? val : "";
					Stylife.Search.crumb[blockid]['url'] = (sites.length == 1) ? '/cm/alllists?'+params :"";

// 					Stylife.Search.config('condition',url.replace(this.item_base_url+"?",""));
					$.cookie(Stylife.Search.mode+'_condition',url.replace(this.item_base_url+"?",""));

					Stylife.Search.updateList(url);

				break;
				}
				case 'shop':{

					var num = $(list + " li a").index(target);

					$(list + " li a").each(function(i) {
						if (i!=num) {
							$(this).removeClass('select');
						};
					});

					($(list + " li a").eq(num).hasClass('select'))? $(list + " li a").eq(num).removeClass('select') : $(list + " li a").eq(num).addClass('select');

					if ($(list + " li a.select").length == 0) {
						$(list + " li:first a").addClass('select');
					};

					var shop = $(list + " li a.select").attr('val') || "";
					var shop_text = ($(list + " li a.select").text() != '全て') ? $(list + " li a.select").text():"";

					// condtion update.
					Stylife.Search.condtion['brand_cd'] = shop;
					Stylife.Search.condtion['maker_name'] = '';
					Stylife.Search.condtion['category_l_cd'] = '';
					Stylife.Search.condtion['category_m_cd'] = '';

					// pageをリセット
					Stylife.Search.condtion['page'] = "";

					var params = $.param(Stylife.Search.condtion);

					var url = "/asynchronous/tlb-alllists-filter/async-ajax?" + params + "&callback=?" ;

					$.getJSON(url,function (data) {
						var brands = data.maker;
						var categories = data.category_l;
						Stylife.Search.updateBrandBlock(brands);
						Stylife.Search.updateCategoryBlock(categories);
					});

					var url = Stylife.Search.item_base_url + "?" + params;
					
					Stylife.Search.crumb[blockid]['text'] = shop_text;
					Stylife.Search.crumb[blockid]['val'] = val;
					Stylife.Search.crumb[blockid]['url'] = '/cm/alllists?'+params;

					// Stylife.Search.config('condition',url.replace(this.item_base_url+"?",""));
					$.cookie(Stylife.Search.mode+'_condition',url.replace(this.item_base_url+"?",""));

					Stylife.Search.updateList(url);

				break;
				}
				case 'brand':{
					if (val == "" ){
							$(list + " li a").removeClass('select');
							$(target).addClass('select');

					}else{
						// 他だったら「全て」のClass"select"を削除
						$(list + " li:first a").removeClass('select');
						($(target).hasClass('select'))? $(target).removeClass('select') : $(target).addClass('select');
						if ($(list + " li a.select").length == 0) {
							$(list + " li:first a").addClass('select');
						};
					}

					var brands = $('#tlb_search_brand_ul li a.select').map(function(){
									return $(this).attr('val');
								}).get();

					var brands_text = $('#tlb_search_brand_ul li a.select').map(function(){
									return $(this).text();
								}).get();

					// condtion update.
					Stylife.Search.condtion['maker_name'] = brands;
					Stylife.Search.condtion['category_l_cd'] = '';
					Stylife.Search.condtion['category_m_cd'] = '';
					
					// pageをリセット
					Stylife.Search.condtion['page'] = "";

					var params = $.param(Stylife.Search.condtion);

					var url = "/asynchronous/tlb-alllists-filter/async-ajax?" + params + "&callback=?" ;

					$.getJSON(url,function (data) {
						var categories = data.category_l;
						Stylife.Search.updateCategoryBlock(categories);
					});

					var params = $.param(Stylife.Search.condtion);
					var url = Stylife.Search.item_base_url + "?" + params;
					
					if (brands_text == "全て") {
						brands_text = "";
					};

					Stylife.Search.crumb[blockid]['text'] = (brands.length == 1) ? brands_text : "";
					Stylife.Search.crumb[blockid]['val'] = (brands.length == 1) ? val : "";
					Stylife.Search.crumb[blockid]['url'] = (brands.length == 1) ? '/cm/alllists?'+params : "";;

					// Stylife.Search.config('condition',url.replace(this.item_base_url+"?",""));

					$.cookie(Stylife.Search.mode+'_condition',url.replace(this.item_base_url+"?",""));

					Stylife.Search.updateList(url);

				break;
				}
				case 'category_l':{
					var num = $(list + " li a").index(target);

					$(list + " li a").each(function(i) {
						if (i!=num) {
							$(this).removeClass('select');
							$(this).next("ul").hide();
						};
					});

					($(list + " li a").eq(num).hasClass('select'))? $(list + " li a").eq(num).removeClass('select') : $(list + " li a").eq(num).addClass('select');
					
					if ($(list + " li a").eq(num).hasClass('select')){
						 $(target).next("ul").show();
					}else{
						
					}

					if ($(list + " li a.select").length == 0) {
						$(list + " li:first a").addClass('select');	
					};

					var category_l = $('#tlb_search_itemcat_ul li a.select').attr('val') || "";	
					var category_l_text = $('#tlb_search_itemcat_ul li a.select').text() || "";	

					// condtion update.
					Stylife.Search.condtion['category_l_cd'] = category_l;
					Stylife.Search.condtion['category_m_cd'] = '';
					// pageをリセット
					Stylife.Search.condtion['page'] = "";

					var params = $.param(Stylife.Search.condtion);
					var url = Stylife.Search.item_base_url + "?" + params;
					
					if (category_l_text == "全て") {
						category_l_text = "";
					};

					Stylife.Search.crumb['item_l']['text'] = category_l_text;
					Stylife.Search.crumb['item_l']['val'] = val;
					Stylife.Search.crumb['item_l']['url'] = '/cm/alllists?'+params;
					
					// item_mをクリア
					Stylife.Search.crumb['item_m']['text'] = "";
					Stylife.Search.crumb['item_m']['val'] = "";
					Stylife.Search.crumb['item_m']['url'] = "";
					
					// Stylife.Search.config('condition',url.replace(this.item_base_url+"?",""));
					$.cookie(Stylife.Search.mode+'_condition',url.replace(this.item_base_url+"?",""));

					Stylife.Search.updateList(url);

					// スクロールバーの高さをリロード
					fleXenv.updateScrollBars();

				break;
				}
				case 'category_m':{
					($(target).hasClass('select'))? $(target).removeClass('select') : $(target).addClass('select');
					var category_l = $('#tlb_search_itemcat_ul li a.select').attr('val') || "";	

					// 選択された項目取得
					var category_m = $('#tlb_search_itemcat_ul li ul li a.select').map(function(){
								return $(this).attr('val');
							}).get();

					// 選択された項目テキストを取得
					var category_m_text = $('#tlb_search_itemcat_ul li ul li a.select').map(function(){
								return $(this).text();
							}).get();

					// 検索条件セット
					Stylife.Search.condtion['category_l_cd'] = category_l;
					Stylife.Search.condtion['category_m_cd'] = category_m;
					// pageをリセット
					Stylife.Search.condtion['page'] = "";

					var params = $.param(Stylife.Search.condtion);
					var url = Stylife.Search.item_base_url + "?" + params;

					Stylife.Search.crumb['item_m']['text'] = (category_m.length ==1) ? category_m_text : "";
					Stylife.Search.crumb['item_m']['val'] = (category_m.length == 1) ? val : "";
					Stylife.Search.crumb['item_m']['url'] = (category_m.length == 1) ? '/cm/alllists?'+params : "";;

					// Stylife.Search.config('condition',url.replace(this.item_base_url+"?",""));
					$.cookie(Stylife.Search.mode+'_condition',url.replace(this.item_base_url+"?",""));

					Stylife.Search.updateList(url);

				break;
				}
			}
			
			Stylife.Util.addUrlHash('re');
			
			if (Stylife.Search.mode != 'shop') this.updateCrumb();
			
			return false;
		},
		updateCrumb: function(event) {
			// テンプレート読み込み
			// TODO：都度読み込みやめる
			var template = $("#breadCrumbTmpl");
			$('#breadcrumbsField').html(template.tmpl(Stylife.Search.crumb));
		},
		clearCrumb: function() {
			this.crumb = {
				site:{
					text: "",
					url:""
				},
				shop:{
					text: "",
					url:""
				},
				brand:{
					text: "",
					url:""

				},
				item_l:{
					text: "",
					url:""
				},
				item_m:{
					text: "",
					url:""
				}
			};
		},
		/**
		 * Update Left BrandBlock 
		 * @private
		 * @param {Object} //paramName Describe this parameter
		 * @returns Update HTML node
		 */
		updateSiteBlock: function (site) {
			var list = $(this.lists['site']);
			var template = $("#siteListTmpl");
			list.html('');

			template.tmpl(site).appendTo(list);

			// 文字列が入ってるかもしれないので絞り込み入力を空に
			$('#shop_input').val("");

			// スクロールバーの高さをリロード
			// fleXenv.updateScrollBars();
		},
		updateShopBlock: function (shop) {
			var list = $(this.lists['shop']);
			var template = $("#shopListTmpl");

			list.html('');
			template.tmpl(shop).appendTo(list);

			// 文字列が入ってるかもしれないので絞り込み入力を空に
			$('#shop_input').val("");

			// スクロールバーの高さをリロード
			// fleXenv.updateScrollBars();
		},

		updateBrandBlock: function (brands) {
			var list = $(this.lists['brand']);
			var template = $("#brandListTmpl");

			list.html('');
			template.tmpl(brands).appendTo(list);

			// 文字列が入ってるかもしれないので絞り込み入力を空に
			$('#brand_input').val("");

			// スクロールバーの高さをリロード
			// fleXenv.updateScrollBars();
		},
		
		updateCategoryBlock: function (itemCategories) {
		
			var list = $(this.lists['category_l']);
			var template = $("#itemCategoryListTmpl");
			
			list.html('');
			template.tmpl(itemCategories).appendTo(list);

			// スクロールバーの高さをリロード
			fleXenv.updateScrollBars();
		},
		updateConditionFromCookie: function() {
			var cond = $.cookie(Stylife.Search.mode+'_condition');
			var params = decodeURIComponent(cond);

			var vars = {}, hash;
			// URLシリアライズ
			// var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
			var hashes = params.split('&');

			// hashに詰める
			for(var i = 0; i < hashes.length; i++){
				hash = hashes[i].split('=');
				vars[hash[0]] = hash[1];
			}

			if (Stylife.Search.mode == 'shop' && vars['brand_cd'] != Stylife.Search.condtion['brand_cd']) {
				return;
			};

			// var params = cond.replace('?','');
			var sex = vars['sex'];
			var sort = vars['sort'];
			var sale = vars['sale'];
			var rows = vars['rows'];

			// sort復元
			$('#tlb_search_sort a').each(function() {
				($(this).attr('val') == sort)? $(this).addClass('select'):$(this).removeClass('select');
			});

			// sale復元
			$('#tlb_search_sale a').each(function() {
				($(this).attr('val') == sale)? $(this).addClass('select'):$(this).removeClass('select');
			});

			// tlb_search_rows
			$('#tlb_search_rows a').each(function() {
				($(this).attr('val') == rows)? $(this).addClass('select'):$(this).removeClass('select');
			});

			// freeword復元
			$('input[name=free_word]').val(decodeURIComponent(vars['free_word']));

			// fixed_price_lower復元
			$('input[name=fixed_price_lower]').val(vars['fixed_price_lower']);

			// fixed_price_lower復元
			$('input[name=fixed_price_upper]').val(vars['fixed_price_upper']);

			// discount_rate_lower復元
			$('input[name=discount_rate_lower]').val(vars['discount_rate_lower']);

			// disp_from_date復元
			$('input[name=disp_from_date]').val(vars['disp_from_date']);
			var url = "/asynchronous/tlb-alllists-filter/async-ajax?" + params + "&callback=?" ;

			// discount_rate_lower復元
			$('input[name=discount_rate_lower]').val(vars['discount_rate_lower']);

			// sex
			$('#sex option:selected').val(vars['sex']);

			//　遷移
			// 無限ループ防止でcookie削除
			// location.href = 'http://tl.www.stylife.co.jp/cm/alllists?'+params;
			
			$.getJSON(url,function (data) {
				var site = data.site;
				var shops = data.brand;
				var brands = data.maker;
				var categories = data.category_l;

				if (Stylife.Search.mode != 'shop'){
					Stylife.Search.updateSiteBlock(site);
					Stylife.Search.updateShopBlock(shops);
				}
				Stylife.Search.updateBrandBlock(brands);
				Stylife.Search.updateCategoryBlock(categories);
			});
			
			var url = Stylife.Search.item_base_url + "?" + params;
			this.updateList(url);

			// $.cookie('search_condition','');

		},
		updateList: function (url) {
			var mode = Stylife.Search.mode;
			if (mode == 'shop') {
				$('.tlb_eyecatch,#bodyNewsField').hide();
			};

			$.get(url,function(data) {
				var a = $(data);

				a.find('.tlb_pic a img.image:gt(8)').lazyload({ 
					placeholder : "/library/tlb/images/loading.gif",
					effect      : "fadeIn",
					failurelimit: 10,
					event : "scroll"
			 	});

				a.find('.tlb_pic a img.image:lt(8)').lazyload({ 
					placeholder : "/library/tlb/images/loading.gif",
					effect      : "fadeIn",
					failurelimit: 10,
					event : "load"
			 	});
				
				$('#paragraph').html(a);
			});
			
			// setTimeout(function(){
			// 	$('.tlb_list_item li').flatHeights();
			// 	Stylife.Search.updateTotalCount();
			// },1500);
			
		},
		shopListSuggest: function() {
			var inputID = "#shop_input";
			var TargetElement = "#tlb_search_shop_ul li";
			this._listSuggest(inputID,TargetElement);
		},
		brandListSuggest: function() {
			var inputID = "#brand_input";
			var TargetElement = "#tlb_search_brand_ul li";
			this._listSuggest(inputID,TargetElement);
		},
		changeSex: function (e) {
			var sex = $('#sex option:selected').val() || 0;

			if (!sex) return;
			Stylife.Search.condtion['sex'] = sex;
			
			var params = $.param(Stylife.Search.condtion);
			var url = Stylife.Search.item_base_url + "?" + params;

			$.cookie(Stylife.Search.mode+'_condition',url.replace(this.item_base_url+"?",""));
			Stylife.Search.updateList(url);
		},
		offPriceNarrowDown: function(e) {
			e.preventDefault();
			var discount_rate_lower = $('.form_search input[name=discount_rate_lower]').val();

			Stylife.Search.condtion['discount_rate_lower'] = discount_rate_lower;
			
			var params = $.param(Stylife.Search.condtion);
			var url = Stylife.Search.item_base_url + "?" + params;
			$.cookie(Stylife.Search.mode+'_condition',url.replace(this.item_base_url+"?",""));
			Stylife.Util.addUrlHash('re');
			
			Stylife.Search.updateList(url);
		},
		dispFromDateNarrowDown: function(e) {
			e.preventDefault();
			var disp_from_date = $('.form_search input[name=disp_from_date]').val();

			Stylife.Search.condtion['disp_from_date'] = disp_from_date;
			
			var params = $.param(Stylife.Search.condtion);
			var url = Stylife.Search.item_base_url + "?" + params;

			$.cookie(Stylife.Search.mode+'_condition',url.replace(this.item_base_url+"?",""));
			Stylife.Util.addUrlHash('re');

			Stylife.Search.updateList(url);
		},
		priceNarrowDown: function(e) {
			e.preventDefault();

			var fixed_price_lower = $('input[name=fixed_price_lower]').val();
			var fixed_price_upper = $('input[name=fixed_price_upper]').val();

			// if (!fixed_price_lower && !fixed_price_upper ) return;
			
			Stylife.Search.condtion['fixed_price_lower'] = fixed_price_lower;
			Stylife.Search.condtion['fixed_price_upper'] = fixed_price_upper;

			var params = $.param(Stylife.Search.condtion);
			var url = Stylife.Search.item_base_url + "?" + params;

			$.cookie(Stylife.Search.mode+'_condition',url.replace(this.item_base_url+"?",""));
			Stylife.Util.addUrlHash('re');

			Stylife.Search.updateList(url);
		},
		freeWordNarrowDown: function(e) {
			e.preventDefault();
			var freeword = $('.form_search input[name=free_word]').val();

			Stylife.Search.condtion['free_word'] = freeword;
			
			var params = $.param(Stylife.Search.condtion);
			var url = Stylife.Search.item_base_url + "?" + params;

			$.cookie(Stylife.Search.mode+'_condition',url.replace(this.item_base_url+"?",""));
			Stylife.Util.addUrlHash('re');

			Stylife.Search.updateList(url);
		},
		_listSuggest: function (inputID,TargetElement) {
			var input = $(inputID);
			var timeout_id = null;

			input.keyup(function(){
					timeout_id = null;
					// listがアップデートされてるかもしれないので都度listを参照
					// TODO：見直す
					var target = $(TargetElement);

					try{
						var list_regex = new RegExp(input.val());
						// リストの検索
						target.each(function(){
							var display = ($(this).text().match(list_regex) ? "block" : "none");
							if(this.style.display !== display) this.style.display = display;
						});

					}catch(e){
						alert(e);
					}
			});
		}
	};		
})(this, document, jQuery);

function dispatcher (path, func) {
    dispatcher.path_func = dispatcher.path_func || [];
    if (func) return dispatcher.path_func.push([path, func]);
    for(var i = 0, l = dispatcher.path_func.length; i < l; ++i) { // >
        var func = dispatcher.path_func[i];
        var match = path.match(func[0]);
        match && func[1](match);
    };
};

dispatcher('.', function () {
    jQuery(function () {
        // 全URLで使う内容 
		jQuery('input[name=free_word]').ajaxSuggest('/asynchronous/tlb-suggest/async-top');
    });
});

dispatcher('^/nuan/$|/nuan$', function () {
    jQuery(function () {
		jQuery('.clothImage img').lazyload({ 
			placeholder : "/library/tlb/images/loading.gif",
			effect      : "fadeIn"
		});
    });
});

dispatcher('^/$|/sf/$|/sf$|/chuse/$|/chuse$',function() {
		var site = location.pathname;

	    jQuery(function () {
			// TOP　Ticker
			jQuery('#tlb_staff-recommend_block').vTicker({
			   speed: 500,
			   pause: 7500,
			   showItems: 10,
			   animation: 'fade',
			   mousePause: false,
			   height: 385,
			   direction: 'down'
			});
	 	});

		jQuery(document).ready(function() {
			jQuery(window).scroll(function() { return false;});
			var tlb_recommend = jQuery(".tlb_recommend .carouselField").jcarousel({
									visible:3,
									scroll:3,
									itemVisibleInCallback: {
							            onAfterAnimation:  function() {
											jQuery(window).trigger("scroll");
							            }
							        }
								});
			var tlb_snapshot = jQuery(".tlb_snapshot .carouselField").jcarousel({
									visible:(site == '/chuse/')?3:5,
									scroll:(site == '/chuse/')?3:5,
									itemVisibleInCallback: {
							            onAfterAnimation:  function() {
											jQuery(window).trigger("scroll");
							            }
							        }
									});

		   	var tlb_check = jQuery(".tlb_check-item .carouselField").jcarousel({
									visible:7,
									scroll:7,
									itemVisibleInCallback: {
							            onAfterAnimation:  function() {
											jQuery(window).trigger("scroll");
							            }
							        }
									});

			jQuery('.tlb_pic a img.image:lt(8)').lazyload({ 
				placeholder : "/library/tlb/images/loading.gif",
				effect      : "fadeIn",
				failurelimit: 4,
				event : "load"
		 	});

			jQuery('.tlb_pic a img.image:gt(8)').lazyload({ 
				placeholder : "/library/tlb/images/loading.gif",
				effect      : "fadeIn",
				failurelimit: 4,
				event : "scroll"
		 	});
		});
});

// 第一引数はURLのパス部分にマッチする正規表現 
dispatcher('^/cm/alllists', function () {
    jQuery(function () {
		Stylife.Search.setup();

		// restore　
		if (window.location.hash == '#!re') {
			Stylife.Search.updateConditionFromCookie();
		};
    });

	jQuery(document).ready(function() {
		jQuery('.tlb_pic a img.image:lt(8)').lazyload({ 
			placeholder : "/library/tlb/images/loading.gif",
			effect      : "fadeIn",
			failurelimit: 8,
			event : "load"
	 	});
	
		jQuery('.tlb_pic a img.image:gt(8)').lazyload({ 
			placeholder : "/library/tlb/images/loading.gif",
			effect      : "fadeIn",
			failurelimit: 8,
			event : "scroll"
	 	});
    });
});

// 第一引数はURLのパス部分にマッチする正規表現 
dispatcher('^/chuse/item|^/nuan/item|^/sf/item|^/looks/item',function() {	
	Stylife.Items.setup();

	jQuery(document).ready(function() {
		jQuery(window).scroll(function() { return false;});
		var tlb_snapshot = jQuery(".tlb_snapshot .carouselField").jcarousel({
							visible:5,
							scroll:5,
							initCallback:function() {
								jQuery("#anotherItemContainer .carouselField img.image").lazyload({ 
									placeholder : "/library/tlb/images/loading.gif",
									effect      : "fadeIn",
									failurelimit: 5,
									event : "scroll"
							 	});
							},
							itemVisibleInCallback: {
					            onAfterAnimation:  function() {
									jQuery(window).trigger("scroll");
					            }
					        }
							});

				
		var tlb_snapshot = jQuery(".tlb_snapshot-item .carouselField").jcarousel({
							visible:12,
							scroll:12,
							initCallback:function() {
								jQuery("#anotherItemContainer .carouselField img.image").lazyload({ 
									placeholder : "/library/tlb/images/loading.gif",
									effect      : "fadeIn",
									failurelimit: 12,
									event : "scroll"
							 	});
							},
							itemVisibleInCallback: {
					            onAfterAnimation:  function() {
									jQuery(window).trigger("scroll");
					            }
					        }
							});

		var anotherItemContainer = jQuery("#anotherItemContainer .carouselField").jcarousel({
									visible:5,
									scroll:5,
									initCallback:function() {
										jQuery("#anotherItemContainer .carouselField img.image").lazyload({ 
											placeholder : "/library/tlb/images/loading.gif",
											effect      : "fadeIn",
											failurelimit: 5,
											event : "scroll"
									 	});
									},
									itemVisibleInCallback: {
							            onAfterAnimation:  function() {
											jQuery(window).trigger("scroll");
							            }
							        }
									});

		var otherSaleContainer = jQuery("#otherSaleContainer .carouselField").jcarousel({
									visible:5,
									scroll:5,
									initCallback:function() {
										jQuery("#otherSaleContainer .carouselField img.image").lazyload({ 
											placeholder : "/library/tlb/images/loading.gif",
											effect      : "fadeIn",
											failurelimit: 5,
											event : "scroll"
									 	});
									},
									itemVisibleInCallback: {
							            onAfterAnimation:  function() {
											jQuery(window).trigger("scroll");
							            }
							        }
									});

		var tlb_check = jQuery(".tlb_check-item .carouselField").jcarousel({
						visible:12,
						scroll:12,
						initCallback:function() {
							jQuery(".tlb_check-item .carouselField img.image").lazyload({ 
								placeholder : "/library/tlb/images/loading.gif",
								effect      : "fadeIn",
								failurelimit: 12,
								event : "scroll"
						 	});
						},
						itemVisibleInCallback: {
				            onAfterAnimation:  function() {
								jQuery(window).trigger("scroll");
				            }
				        }
						});

		jQuery('.thumb_color').lazyload({ 
						placeholder : "/library/tlb/images/loading.gif",
						effect      : "fadeIn",
						failurelimit: 7,
						event : "scroll"
			 	});
	
		var vtik_opt = 	{
						   speed: 500,
						   pause: 7500,
						   showItems: 5,
						   animation: 'fade',
						   mousePause: true,
						   height: 360,
						   direction: 'down'
						};


		if (jQuery('.tlb_review .tlb_carousel li').length >= 4) {		
			var review = jQuery('.tlb_review .tlb_carousel').vTicker(vtik_opt);
		};

		if (jQuery('.tlb_staff-recommend .tlb_carousel li').length >= 4) {
			var recommend = jQuery('.tlb_staff-recommend .tlb_carousel').vTicker(vtik_opt);
		};
    });
});

// 第一引数はURLのパス部分にマッチする正規表現 
dispatcher('^/chuse/brand|^/nuan/brand|^/sf/brand|^/looks/brand',function() {
	jQuery(document).ready(function() {
		// var order_car = jQuery(".tlb_order .carouselField").jcarousel({visible:4,scroll:4,wrap:'circular'});
		// var snap_car = jQuery(".tlb_snapshot .carouselField").jcarousel({visible:4,scroll:4,wrap:'circular'});
		// var staff_recommend_car =  jQuery(".tlb_staff-recommend .carouselField").jcarousel({vertical:true});
		// var check_item_car = jQuery(".tlb_check-item .carouselField").jcarousel({visible:9,scroll:9,wrap:'circular'});
		jQuery(window).scroll(function() { return false;});
		var order_car = jQuery(".tlb_order .carouselField").jcarousel({
							visible:4,
							scroll:4,
							itemVisibleInCallback: {
					            onAfterAnimation:  function() {
									jQuery(window).scroll(function() { return false;});
									jQuery(window).trigger("scroll");
									return false;
					            }
					        }
						});

		var snap_car = jQuery(".tlb_snapshot .carouselField").jcarousel({
							visible:4,
							scroll:4,
							itemVisibleInCallback: {
					            onAfterAnimation:  function() {
									jQuery(window).trigger("scroll");
					            }
					        }
						});

		var staff_recommend_car =  jQuery(".tlb_staff-recommend .carouselField").jcarousel({vertical:true});

		var check_item_car = jQuery(".tlb_check-item .carouselField").jcarousel({
							visible:9,
							scroll:9,
							itemVisibleInCallback: {
					            onAfterAnimation:  function() {
									jQuery(window).trigger("scroll");
					            }
					        }
						});
						
		jQuery('.tlb_pic a img.image:gt(8)').lazyload({ 
			placeholder : "/library/tlb/images/loading.gif",
			effect      : "fadeIn",
			failurelimit: 8,
			event : "scroll"
	 	});

		jQuery('.tlb_pic a img.image:lt(8)').lazyload({ 
			placeholder : "/library/tlb/images/loading.gif",
			effect      : "fadeIn",
			failurelimit: 8,
			event : "load"
	 	});

        Stylife.Brands.setup();
		Stylife.Search.setup();
		
		if (jQuery('#tlb_staff-recommend_block li').length >= 4) {
		var review = jQuery('#tlb_staff-recommend_block').vTicker({
					   speed: 500,
					   pause: 7500,
					   showItems: 4,
					   animation: 'fade',
					   mousePause: true,
					   height: 385,
					   direction: 'down'
					});
		};
	});
	
	jQuery(function () {
		Stylife.Search['mode'] = 'shop';

		// restore　
		if (window.location.hash == '#!re') {
			Stylife.Search.updateConditionFromCookie();
		};
		
    });
});
dispatcher('^/cm/styling',function() {
    jQuery(function () {
		jQuery(window).scroll(function() { return false;});
		jQuery('.tlb_pic a img.image:lt(8)').lazyload({ 
			placeholder : "/library/tlb/images/loading.gif",
			effect      : "fadeIn",
			failurelimit: 8,
			event : "load"
	 	});

		jQuery('.tlb_pic a img.image:gt(8)').lazyload({ 
			placeholder : "/library/tlb/images/loading.gif",
			effect      : "fadeIn",
			failurelimit: 8,
			event : "scroll"
	 	});

		jQuery(".tlb_snapshot .carouselField").jcarousel({
			visible:5,
			scroll:5,
			itemVisibleInCallback: {
	            onAfterAnimation:  function() {
					jQuery(window).trigger("scroll");
	            }
	        }
			});
		

	});
	
});

// ライブラリ等を読み込む 
dispatcher(location.pathname);

