var tropo;
var audio;
$(function()
{
	if (navigator.appName.indexOf("Microsoft") != -1) audio = new Soundset("/user_data/packages/default/js/asset/SoundUnit.swf");
	else audio = document.getElementById("sound_set");
	
	var effect = new caseinc.effect();
	tropo = new tropopause.products();
	
	effect.animatePriceByClass("price");
	effect.animatePriceByClass("sum_price");
	effect.animatePriceByClass("point");
	effect.opacityFade("op_fade");
	
	//menu
	effect.blinkFadeTextByClass("blink_fade_text");
	$("#menu_products").bind(click, function(){menuLink(this);});
	$("#menu_archive").bind(click, function(){menuLink(this);});
	$("#menu_contact").bind(click, function(){menuLink(this);});
	$("#menu_mypage").bind(click, function(){menuLink(this);});
	function menuLink(jObj){location.href = jObj.children[0].href;}
	
	//URLを判断してメニュー表示する。
	var page = tropo.getPageName();
	$("#menu_"+page).corner("15px");
	$("#menu_"+page).unbind("hover");
	$("#menu_"+page).unbind(click);
	$("#menu_"+page).css({"background-color" : "#000", "cursor" : "default"});
	$("#menu_"+page+" a").css("color", "#FFF");
	if(page !== "products") initMenu("#menu_products");
	if(page !== "archive") initMenu("#menu_archive");
	if(page !== "contact") initMenu("#menu_contact");
	if(page !== "mypage") initMenu("#menu_mypage");
	function initMenu(jObj)
	{
		$(jObj).corner("15px");
		$(jObj).hover(
			function()
			{
				$(this).css({"background-color" : "#000", "cursor" : "pointer"});
				$(this.children).css("color", "#FFF");
			},
			function()
			{
				$(this).css({"background-color" : "#FFF", "cursor" : "default"});
				$(this.children).css("color", "#000");
			}
		);
	}
	
	//INDEX判定
	if(location.pathname === "/" || location.pathname === "/index.php") tropo.dispIndex();
	
	//category menu
	tropo.initCategories();
	
	$(window).resize(function(){setSize();});
});

function setSize(){
	var winW = $(window).width();
	var winH = $(window).height();
	if(winW < 984) $(".thum_wrapper").css("width", "984px");
	else $(".thum_wrapper").css("width", "100%");
}

//商品詳細画面、サブ画像切替
function chgDImg(src_id, tgt_id, large_img)
{
	$("#"+tgt_id).append("<img id=\"l_"+src_id+"\" src=\""+large_img+"\" style=\"position:absolute;\"/>");
	setTimeout(function(){
		$("#l_"+src_id).animate({"opacity": "0"}, 1000, function(){$("#l_"+src_id).remove();});
	}, 2000);
}

/**
 * Script: products.js
 * Class: tropopause.products
 * Copyright (c) 2011 [CASE Inc. (http://caseinc.jp/)]
*/
if(typeof tropopause === "undefined") tropopause = {};
tropopause.products = function()
{
	var _scope = this;

	this.categories = new Array();
	this.categories[ "s_menu_mens"] = "2";
	this.categories[ "s_menu_mens_shirts"] = "6";
	this.categories[ "s_menu_mens_others"] = "7";
	this.categories[ "s_menu_ladies"] = "1";
	this.categories[ "s_menu_ladies_shirts"] = "3";
	this.categories[ "s_menu_ladies_others"] = "4";
	
	this.categoryTitle = new Array();
	this.categoryTitle[ "s_menu_mens_shirts"] = "Men's<br />SHIRTS";
	this.categoryTitle[ "s_menu_mens_others"] = "Men's<br />OTHERS";
	this.categoryTitle[ "s_menu_ladies_shirts"] = "Ladies'<br />SHIRTS";
	this.categoryTitle[ "s_menu_ladies_others"] = "Ladies'<br />OTHERS";
	
	
	this.itemNum = 0;
	this.arr_thumb_images = new Array();
	this.arr_main_images = new Array();
	this.arr_sub_images_1 = new Array();
	this.arr_sub_images_2 = new Array();
	this.arr_sub_images_3 = new Array();
	this.is_loaded = new Array();
	this.is_thumb_loaded = new Array();
	
	//URLからページ名を取得
	this.getPageName = function()
	{
		var page = location.pathname.match(/^\/.*\//);
		if(page == null) page = "";
		else page = page[0].replace(/\//g, "");
		return page;
	};
	
	//TOP画面用読み込み
	this.dispIndex = function()
	{
		//指定カテゴリの読み込み
		var cats = ["s_menu_mens_shirts", "s_menu_mens_others", "s_menu_ladies_shirts", "s_menu_ladies_others"];
		$(".recomend_inner").get(0).innerHTML = "";
		
		for(var key in cats)
		{
			var cat_id = _scope.categories[cats[key]];
			_scope.isTopAnm["r_"+cat_id] = true;
			_scope.arrCatProducts[cat_id] = new Array();
			var htm = "<a id=\"r_"+cat_id+"\" class=\"recomendimg_wrapper\" href=\"/products/list.php#"+cats[key].replace("s_menu_", "")+"\">";
			htm += "<img class='top_menus' src='/user_data/packages/default/img/tropopause/"+cats[key]+".png'>";
			htm += "<div id=\"r_"+cat_id+"_d_elem\" class=\"d_elem\"></div></a>";
			$(".recomend_inner").append(htm);
			
			$("#r_"+cat_id).hover(
				function()
				{
					$(this.children).css(
					{
						"cursor"					: "pointer",
						"z-index"					: "101"
					});
					$(this).children("img").fadeOut("fast");
					_scope.isTopAnm[this.id] = false;
				},
				function()
				{
					$(this.children).css(
					{
						"cursor"					: "default",
						"z-index"					: "100"
					});
					$(this).children("img").fadeIn("fast");
					_scope.isTopAnm[this.id] = true;
				}
			);
			
			ajax.handleSuccess = function(json_data, dataType)
			{
				var data = json_data.response.items;
				var req = json_data.response.request;
				if(data.length > 0)
				{
					for (var i in data)
					{
						//サムネイル読み込み
						_scope.arrCatProducts[req.category_id].push(data[i].product_id);
					}
					_scope.sequenceTopImage(req.category_id);
				}
			};
			ajax.sendData("http://"+hostName+"/api/?action=itemsearch&format=json&page_max=50&category_id="+cat_id, null, "GET");
			_scope.loadImagesByCategory(cat_id, false);
		}
	};
	
	this.isTopAnm = new Array();
	this.arrCatProducts = new Array();
	
	//top用画像切替アニメーション
	this.sequenceTopImage = function(cat_id)
	{
		if (parseInt(cat_id, 10) % 2 == 0) _scope.arrCatProducts[cat_id].reverse();
		
		//ロード中
		var top_st = setInterval(function()
		{
			if(_scope.loaded_cat_thumb(cat_id))
			{
				clearInterval(this);
			}
		}, 100);
		
		var counter = 0;
		var top_img_st = setInterval(function()
		{
			if(_scope.isTopAnm["r_"+cat_id])
			{
				if(counter >= _scope.arrCatProducts[cat_id].length) counter = 0;
				//$("#r_"+cat_id+" img").remove();
				//$("#r_"+cat_id).append("<img src=\""+_scope.arr_thumb_images["p_"+_scope.arrCatProducts[cat_id][counter]]+"\" />");
				$("#r_"+cat_id).css("background", "url('"+_scope.arr_thumb_images["p_"+_scope.arrCatProducts[cat_id][counter]]+"')");
				counter++;
			}
		}, Math.floor(Math.random() * 200) +100);
	};
	
	//TOP用サムネイル画像が読み込まれているか判定
	this.loaded_cat_thumb = function(cat_id)
	{
		for(var key in _scope.arrCatProducts[cat_id])
		{
			if(_scope.is_thumb_loaded["p_"+_scope.arrCatProducts[cat_id][key]] !== true)
			{
				return false;
			}
		}
		return true;
	};
	
	//カテゴリメニューの初期化
	this.initCategories = function()
	{
		//URL hashを判断してカテゴリ表示する。
		var page = _scope.getPageName();
		var anchor = location.hash.replace("#", "");
		
		if(page === "products")
		{
			for (var key in _scope.categories)
			{
				_scope.hoverCategories(key);
				$("#"+key).bind(click, function(){_scope.selectCategoryMenu(this);});
			}
			
			if(anchor === "")
			{
				_scope.loadImagesByCategory("", true);
				_scope.getItemByCategoryId(".thum_wrapper", "");
			}
			else
			{
				var cat_id = "s_menu_"+anchor;
				
				//メニュー切り替え
				$("#"+cat_id).unbind();			//初期化
				$("#"+cat_id).css({"background-color" : "#000", "cursor" : "default"});
				$("#"+cat_id+" p").css("color", "#FFF");
				
				//画像読み込み
				_scope.loadImagesByCategory(this.categories[cat_id], true);
				_scope.getItemByCategoryId(".thum_wrapper", this.categories[cat_id]);
			}
		}
	};
	
	//カテゴリ選択時
	this.selectCategoryMenu = function(j_obj)
	{
		var cat_id = _scope.categories[j_obj.id];
		//URLリダイレクト
		location.href = "/products/list.php"+"#"+j_obj.id.replace("s_menu_", "");
		
		//メニュー表示を切り替え（not hover）
		$(j_obj).corner("15px");
		$(j_obj).unbind();			//初期化
		$(j_obj).css({"background-color" : "#000", "cursor" : "default"});
		$(j_obj.children).css("color", "#FFF");
		
		//他メニューを再バインド
		for (var key in _scope.categories)
		{
			$("#"+key).unbind();			//初期化
			if(key !== j_obj.id)
			{
				_scope.hoverCategories(key);
				$("#"+key).bind(click, function(){_scope.selectCategoryMenu(this);});
			}
		}
		
		//画像読み込み
		_scope.loadImagesByCategory(cat_id, true);
		_scope.getItemByCategoryId(".thum_wrapper", cat_id);
	};
	
	//カテゴリマウスオーバー時
	this.hoverCategories = function(idName)
	{
		$("#"+idName).corner("15px");
		$("#"+idName).hover(
			function()
			{
				$(this).css({"background-color" : "#000", "cursor" : "pointer"});
				$(this.children).css("color", "#FFF");
			},
			function()
			{
				$(this).css({"background-color" : "#FFF", "cursor" : "default"});
				$(this.children).css("color", "#000");
			}
		);
		$("#"+idName).css({"background-color" : "#FFF", "cursor" : "pointer"});
		$("#"+idName+" p").css("color", "#000");
	};
	
	var graphics = new caseinc.graphics();
	var ajax = new caseinc.ajax();
	var hostName = location.hostname;
	this.arr_bar = new Array();
	
	//全てのアニメーションを停止します。（初期化）
	this.clearTimeLine = function()
	{
		clearInterval(_scope.createT);
		for(var i in _scope.st_loading){clearInterval(_scope.st_loading[i])};
		for(var i in _scope.st_disp){clearInterval(_scope.st_disp[i])};
		for(var i in _scope.isAnimated){_scope.isAnimated[i] = false};
	};
	
	//指定カテゴリの商品サムネイルを全て読み込み、HTML表示
	this.createT;
	this.getItemByCategoryId = function(id, cat_id)
	{
		_scope.clearTimeLine();
		
		var arr_htm = new Array();
		var htm = "";
		ajax.handleSuccess = function(json_data, dataType)
		{
			$(id).get(0).innerHTML = "";
			var p_id = new Array();
			var product_id = new Array();
			var data = json_data.response.items;
			
			_scope.itemNum = data.length;
			if(data.length > 0)
			{
				//6列の枠をデータ数分生成
				var frame_htm = "";
				var frame_num = Math.floor(data.length/6);
				_scope.arr_bar = new Array();
				for(var i=0; i<=frame_num; i++)
				{
					frame_htm += "<div id=\"thumb_frame_"+i+"\" class=\"thumb_inline\"></div><div id=\"p_bar_"+i+"\" class=\"p_bar\"></div>";
					_scope.arr_bar.push("p_bar_"+i);
				}
				$(id).append(frame_htm);
				
				//商品毎にHTML生成
				var dataNum = 0;
				_scope.createT = setInterval(function()
				{
					if(dataNum >= data.length - 1) clearInterval(_scope.createT);
					var htm = "";
					p_id[dataNum] = data[dataNum].product_code_max;
					product_id[dataNum] = data[dataNum].product_id;
					htm += "<script>";
					htm += "$(\"#p_"+product_id[dataNum]+"\").bind(click, function(){";
					htm += "audio.play();";
					htm += "tropo.dispItemDetail(\"p_bar_"+(Math.floor(dataNum/6))+"\", \""+product_id[dataNum]+"\" );";
					htm += "});";
					htm += "</script>";
					htm += "<div id=\"listphoto_"+product_id[dataNum]+"\" class=\"listphoto\">";
					htm += "<div id=\"p_"+product_id[dataNum]+"\"></div>";
					htm += "<p id=\"product_thumb_name"+product_id[dataNum]+"\"  class=\"product_thumb_name\">"+data[dataNum].name+"</p>";
					htm += "</div>";
					$("#thumb_frame_"+(Math.floor(dataNum/6))).append(htm);
					
					$("#listphoto_"+product_id[dataNum]).hover(
						function()
						{
							$(this).css("cursor", "pointer");
							$(this).children("p").css("display", "block");
						},
						function()
						{
							$(this).css("cursor", "default");
							$(this).children("p").css("display", "none");
						}
					);
					_scope.sequenceBackground("p_"+product_id[dataNum], true);
					dataNum++;
				}, 300);
			}
			else
			{
				$(id).append("<p>Not Sales.　現在販売商品はありません。</p>");
			}
		};
		ajax.sendData("http://"+hostName+"/api/?action=itemsearch&format=json&page_max=99&category_id="+cat_id, null, "GET");
	};
	
	//サムネイルカテゴリ単位で読み込み
	var thumb_img = new Array();
	var main_img = new Array();
	this.loadImagesByCategory = function(cat_id, readMain)
	{
		ajax.handleSuccess = function(json_data, dataType)
		{
			var data = json_data.response.items;
			if(data.length > 0)
			{
				for (var i in data)
				{
					var code = "p_"+data[i].product_id;
					
					_scope.is_loaded[code] = false;
					thumb_img[code] = new Image();
					thumb_img[code].title = code;		//仮でtitleプロパティ使っとく
					
					thumb_img[code].onload = function(){
						_scope.is_thumb_loaded[this.title] = true;
					}
					
					thumb_img[code].src = data[i].main_list_image;
					_scope.arr_thumb_images[code] = thumb_img[code].src;
					
					if(readMain)
					{
						main_img[code] = new Image();
						main_img[code].title = code;
						
						//メイン画像読み込み完了時
						main_img[code].onload = function(){
							_scope.is_loaded[this.title] = true;
						}
						
						main_img[code].src = data[i].main_image;
						_scope.arr_main_images[code] = main_img[code].src;
					}
				}
			}
		};
		ajax.sendData("http://"+hostName+"/api/?action=itemsearch&format=json&page_max=99"+"&category_id="+cat_id, null, "GET");
	};
	
	//サムネイル画像が全て読み込まれているか判定
	this.loaded_all_thumb = function()
	{
		var counter = 0;
		for(var key in _scope.arr_thumb_images)
		{
			if(_scope.is_thumb_loaded[key] === true) counter++;
		}
		if(counter >= _scope.itemNum) return true;
		return false;
	};
	
	this.isAnimated = new Array();
	
	//背景ベタシーケンスアニメーション（画像ローディング中のみ）
	this.st_loading = new Array();
	this.sequenceBackground = function(idName, readMain)
	{
		_scope.st_loading[idName] = setInterval(function()
		{
			_scope.isAnimated[idName] = true;
			//$("#"+idName).css("background-color", graphics.random_rgb());
			
			var thunbFlg = _scope.is_loaded[idName];
			if(!readMain) thunbFlg = true;
			if(thunbFlg && _scope.loaded_all_thumb())
			{
				clearInterval(_scope.st_loading[idName]);
				_scope.sequenceProductImage(idName);
				_scope.isAnimated[idName] = false;
			}
		}, 100);
	};
	
	//商品画像シーケンスアニメーション（表示時）
	this.st_disp = new Array();
	this.sequenceProductImage = function(idName, speed, num)
	{
		if(!isFinite(speed)) speed = 150;
		if(!isFinite(num)) num = 5;
		var tmpImages = shiftArray(_scope.arr_thumb_images);
		
		function shiftArray(list){
			var _list = new Array()
			for(var key in list)
			{
				_list.push(list[key]);
			}
			return _list;
		}
		
		var imgNum = 0;
		_scope.st_disp[idName] = setInterval(function()
		{
			_scope.isAnimated[idName] = true;
			if(imgNum > tmpImages.length) imgNum = 0;
			var rnd = Math.floor(Math.random() * tmpImages.length);
			$("#"+idName).html("<img src='"+tmpImages[rnd]+"' width=150px height=150px>");
			if(imgNum > num)
			{
				clearInterval(_scope.st_disp[idName]);
				$("#"+idName+" img").attr("src", _scope.arr_thumb_images[idName]);
				_scope.isAnimated[idName] = false;
			}
			imgNum++;
		}, speed);
	};
	
	//商品詳細領域の表示
	this.dispItemDetail = function(id, product_id)
	{
		$("#"+id).html("");
		$(".product_thumb_name").css("display", "none");
		$(".product_arrow").remove();
		$.get("http://"+hostName+"/product_detail.php", {"product_id" : product_id}, function(data)
		{
			_scope.hideItemDetail();
			$("#"+id).get(0).innerHTML = data;
			$(".close_product_detail").bind(click, function(){_scope.hideItemDetail();});
			$("html, body").animate({ scrollTop: $("#"+id).offset().top+200 }, "fast");
			setSize();
			_scope.loadSubImages(product_id)
			
			//サムネイル矢印
			$("#p_"+product_id).append("<div class='product_arrow'></div>");
		});
	};
	
	//sub imageをキャッシュに読み込む
	var sub_img_1 = new Array();
	var sub_img_2 = new Array();
	var sub_img_3 = new Array();
	this.loadSubImages = function(p_id)
	{
		ajax.handleSuccess = function(json_data, dataType)
		{
			var data = json_data.response.items[0];
			
			var code = data.product_id;
			sub_img_1[code] = new Image();
			sub_img_2[code] = new Image();
			sub_img_3[code] = new Image();
			var url = location.protocol+"//"+hostName+"/upload/save_image/";
			if(data.sub_large_image1 != null)
			{
				sub_img_1[code].src = url+data.sub_large_image1;
				_scope.arr_sub_images_1[code] = sub_img_1[code].src;
			}
			if(data.sub_large_image2 != null)
			{
				sub_img_2[code].src = url+data.sub_large_image2;
				_scope.arr_sub_images_2[code] = sub_img_2[code].src;
			}
			if(data.sub_large_image3 != null)
			{
				sub_img_3[code].src = url+data.sub_large_image3;
				_scope.arr_sub_images_3[code] = sub_img_3[code].src;
			}
		};
		ajax.sendData("http://"+hostName+"/api/?action=itemsearch&format=json&product_id="+p_id, null, "GET");
	};
	
	//商品詳細領域の非表示
	this.hideItemDetail = function()
	{
		$(".product_arrow").remove();
		for(var i in _scope.arr_bar)
		{
			$("#"+_scope.arr_bar[i]).get(0).innerHTML = "";
		}
	};
};
