
// インジケーター用画像ファイルのパス
var INDICATOR_GIF = "/common/img/indicator.gif";

var jewelryXmlFilePath = "/jewelry/xml/jewelry.xml";
var xmlData;

var DISP_MAX = 18;
// サムネイルサイズ
var IMAGE_SIZE = 143;
var SLIDE_ITEM_MAX = 14;
var pageNo = 1;

var condition = {};
condition['items'] = "reset";
condition['material'] = "reset";
condition['price'] = "reset";
condition['scene'] = "reset";

var getQueryDataAry = new Array();

getQueryDataAry = fdc_util_getQueryData();

var notReady = 2; // 非同期動作未完了カウンタ

//-- 分割XML読み込み用のフラグ -------------
// 初回表示フラグ
var firstDispFlg = true;
// 商品情報XMLを全部取得したか管理するフラグ
var xmlReadAllFlg = false;
//------------------------------------------

$(function(){
	// History
	// 上部メニュー
	$("ul.sub_menu li")
		.click(
		    function() {
		    	pageNo = 1;
				var selectedItemId = $(this).attr("id");
				updateCondition(selectedItemId);

				var hash = makeHistoryHashStr();
				$.historyLoad(hash);
			}
		);

	// IE対策
//	if ($.historyNeedIframe) {
		var intervalId = setInterval(function() {
			if($("#fmenu1_menu_parent ul li").length) {
	 			setHistoryFromMenu();
				clearInterval(intervalId);
			}
		}, 100);
//	}

	// インジケーター表示
	dispSearchIndicator();
	checkReady();
});

// インジケーター表示
function dispSearchIndicator() {
	// 商品表示クリア
	$("#productsSearchBox").empty();
	// ページナビクリア
	$(".pageNavBox").empty();
	// インジケータを表示
	$(".pageNavBox").html("<div class=\"jewelryNaBox02\" align=\"center\"><img src=\"" + INDICATOR_GIF + "\"/></div>");
}


$.event.add(window, "load",
	function() {
		// 商品情報XMLの読み込み
		// 非同期化
//		fdc_util_readJewelryXML(jewelryXmlFilePath,
//			function(xml) {
//				xmlData = xml;
//				checkReady();
//			}
//		);

		checkReady();

	}
);


function checkReady(){
	if(--notReady == 0) {
		finalInitialize();
	}
}

function finalInitialize(){

	// 初期化
	pageNo = 1;
	condition['items'] = "reset";
	condition['material'] = "reset";
	condition['price'] = "reset";
	condition['scene'] = "reset";

	$.historyInit(setParamFromHistory);

	var hash = location.hash.replace(/^.*#/, '');
	if ( hash == '' ) {
		// 初回表示処理
		firstDispProcess();
	}

    $("ul.sub_menu li")
    	.click(
    		function(event) {
				event.stopPropagation();
				$("ul.dropdown ul").css('visibility', 'hidden');
			}
		);
}


// 指定したページに切り替える
function changePage(no) {
	pageNo = no;
	var hash = makeHistoryHashStr();
	$.historyLoad(hash);
}


function onclickSearchResItem(listNo, pageURL) {

	var data = new Array();

	if (!xmlReadAllFlg) {
		return;
	}

	var startId = (pageNo - 1) * DISP_MAX + listNo - 1;

	if (searchRes.length < SLIDE_ITEM_MAX) {
		$.each(searchRes, function() {
			data.push(this.id);
		});
	} else if(searchRes.length - startId < SLIDE_ITEM_MAX) {
		for(i=startId; i< searchRes.length; i++) {
			data.push(searchRes[i].id);
		}
		
		var restNum = SLIDE_ITEM_MAX - (searchRes.length - startId);
		for(i=0; i<restNum; i++) {
			data.push(searchRes[i].id);
		}
	} else {
		for(i=startId; i<startId + SLIDE_ITEM_MAX; i++) {
			data.push(searchRes[i].id);
		}
	}
	
	var cookieData = data.join(';');

	// 商品詳細ページのスライダー表示する商品IDをクッキーに保存
	$.cookie('sliderItemInfo', cookieData, {expires:FDC_COOKIE_EXP, path:FDC_COOKIE_PATH});

	// 商品詳細ページへ
	document.location.href = pageURL + "?slider=1";
}

//
// 「戻る」対策
//

function setHistoryFromMenu() {

	$('#fmenu1_menu_parent > ul > li').each(
		function(){
			$(this).children("a").click(
				function () {
					var hash = $(this).attr("href");
					hash = hash.replace(/^.*#/, '');
					$.historyLoad(hash);

					// close top Jewerly menu (dropdown)
					$("#fmenu1_menu_parent").css('display', 'none');

					return false;
				}
			);
		}
	);

}

// 履歴用文字列を作成する
function makeHistoryHashStr() {
	var rec_sep  = "--";
	var data_sep = "__";

	var str = "pageNo" + data_sep + pageNo;
	for (var i in condition) {
		str = str + rec_sep +  i + data_sep + condition[i];
	}
	
	// 一覧表示位置用
	str = str + rec_sep +  "p" + data_sep + "1";
	
	return str;
}

// 履歴からパラメータを取得し復帰させる
function setParamFromHistory(hash) {
	var rec_sep  = "--";
	var data_sep = "__";
	var p = 0;

	// 初期化
	pageNo = 1;
	condition['items'] = "reset";
	condition['material'] = "reset";
	condition['price'] = "reset";
	condition['scene'] = "reset";

//	alert("setParamFromHistory(" + hash + ")");

	var hash = hash.replace(/^.*#/, '');
	var ary1 = hash.split(rec_sep);
	for ( var i=0; i<ary1.length; i++) {
		// alert(i + "/" + ary1[i]);
		var ary2 = ary1[i].split(data_sep);
		switch(ary2[0]) {
			case 'items':
			case 'material':
			case 'price':
			case 'scene':
				condition[ary2[0]] = ary2[1];
				break;
			case 'pageNo':
				pageNo = Number(ary2[1]);
				break;
			
			case 'p':
				p = Number(ary2[1]);
				break;
		}
	}


	changeTabMenu();

	// 初回表示？
	if (firstDispFlg) {
		// 検索条件に合致した現ページ分だけのXML情報をサーバから受け取とって表示する
		// 表示後に、残りの商品データを非同期で受け取る
		// 残りのデータを受け取ったかどうかは、フラグxmlReadAllFlgで管理する
		firstDispProcess();
	} else {
		// 残りのXML読み込み中？
		if (!xmlReadAllFlg) {
			// インジケーター表示
			dispSearchIndicator();
			// 監視スタート
			var intervalId = setInterval(function() {
				// 残りXML読み込み完了フラグを監視
				if(xmlReadAllFlg) {
					//alert("xml read");
					clearInterval(intervalId);
					// 検索と検索結果表示
					searchAndDispProcess();
				}
			}, 100);
		} else {
			// javascript内に格納済みの商品全データから検索を行う
			// 検索と検索結果表示
			searchAndDispProcess();
		}
	}

}

// 検索と検索結果表示
function searchAndDispProcess() {
	searchData();
	if (searchRes.length == 0) {
		dispNothingSearchRes();
	} else {
		dispSearchRes();
		dispPageNavi(searchRes.length);
	}
}


//----------------------------------------------------
// 初回表示処理
//----------------------------------------------------
function firstDispProcess() {

	cgiPath = "/jewelry/xml/getPageXml.php?";
	cgiPath += "item=" + condition['items'];
	cgiPath += "&material=" + condition['material'];
	cgiPath += "&price=" + condition['price'];
	cgiPath += "&scene=" + condition['scene'];
	cgiPath += "&page=" + pageNo;
//alert(cgiPath);

	var http = new JKL.ParseXML(cgiPath);
	http.setOutputArrayAll();
	xmlData = http.parse();

	searchNum = xmlData.jewelryList[0].num[0];
	searchData_firstDisp();
	if (searchRes.length == 0) {
		dispNothingSearchRes();
	} else {
		dispSearchRes();
		dispPageNavi(searchNum);
	}

	firstDispFlg = false;

	// 商品情報XMLの読み込み
	// 非同期化
	fdc_util_readJewelryXML(jewelryXmlFilePath,
		function(xml) {
			xmlData = xml;
			// 商品クリックで検索結果から関連情報を設定するため、全商品情報での検索結果を設定しておく
			searchData();
			xmlReadAllFlg = true;
		}
	);

}


function updateCondition(selectedItemId) {
	var temp = selectedItemId.match(/^pdown_([^_]*)_(.*)$/i);
	if (temp.length < 2) return ;

		switch(temp[1]) {
		case 'items':
			condition['items'] = temp[2];
			break;
		case 'material':
			condition['material'] = temp[2];
			break;
		case 'price':
			condition['price'] = temp[2];
			break;
		case 'scene':
			condition['scene'] = temp[2];
			break;
	}
}


function changeTabMenu() {

	$("#tab_items > img").attr("src" ,tabItemImageInfo['items'][condition['items']]['tab']);
	$("#tab_material > img").attr("src" ,tabItemImageInfo['material'][condition['material']]['tab']);
	$("#tab_price > img").attr("src" ,tabItemImageInfo['price'][condition['price']]['tab']);
	$("#tab_scene > img").attr("src" ,tabItemImageInfo['scene'][condition['scene']]['tab']);

}


function searchData() {
	searchRes = new Array();

	if (xmlData.jewelryList == null) {
		return;
	}
	
	$.each(xmlData.jewelryList[0].jewelry,

		function() {
			var item = "";
			if (this.item != null) {
				item = this.item[0];
			}
			
			
			if (condition['items'] != "" && condition['items'] != "reset" && condition['items'] != item) {
				var itemSearchData = new RegExp(condition['items'], "i");
				if (item.search(itemSearchData) == -1) {
					return;
				}
			}
			
			// 価格
			var price = parseInt(this.price[0]);
			// 価格の検索条件が設定されている？
			if (condition['price'] != "" && condition['price'] != "reset") {
				var priceMin = "";
				var priceMax = "";
				if(condition['price'] == 'over15000') {
					priceMin = 0;
					priceMax = 15000;
				} else if(condition['price'] == 'over100000') {
					priceMin = 100000;
				} else {
					var priceSpan =condition['price'].match(/^(\d*)_(\d*)$/);
					priceMin = parseInt(priceSpan[1]);
					priceMax = parseInt(priceSpan[2]);
				}
				//alert(priceMin + "<" + priceMax);
				if (priceMin != "" && price < priceMin) {
					return;
				}
				if (priceMax != "" && priceMax < price) {
					return;
				}
			}
			
			// 素材
			var materialList = new Array();
			if (this.materialList != null && this.materialList[0].material != null) {
				$.each(this.materialList[0].material, function() {
					materialList.push(this);
				});
			} else {
				materialList[0] = "";
			}
			
			// 素材の検索条件が設定されている？
			if (condition['material'] != "" && condition['material'] != "reset") {
				// 素材検索
				var materialHit = false;
				var materialSearchData = new RegExp(condition['material'], "i");
				$.each(materialList, function(i, val) {
					if (val.search(materialSearchData) != -1) {
						materialHit = true;
					}
				});
				
				if (!materialHit) {
					return;
				}
			}

			// シーン
			var sceneList = new Array();
			if (this.sceneList != null && this.sceneList[0].scene != null) {
				$.each(this.sceneList[0].scene, function() {
					sceneList.push(this);
				});
			} else {
				sceneList[0] = "";
			}
			
			// シーンの検索条件が設定されている？
			if (condition['scene'] != "" && condition['scene'] != "reset") {
				// シーン検索
				var sceneHit = false;
				var sceneSearchData = new RegExp(condition['scene'], "i");
				$.each(sceneList, function(i, val) {
					if (val.search(sceneSearchData) != -1) {
						sceneHit = true;
					}
				});
				
				if (!sceneHit) {
					return;
				}
			}

			var temp = new Array();
			temp.item = item;
			temp.price = price;
			temp.materialList = materialList;
			temp.sceneList = sceneList;
			temp.id = this.id[0];
			temp.name = this.name[0];
			temp.entrylink = "";
			if (this.entrylink != null) {
				temp.entrylink = this.entrylink[0];
			}
			
			temp.explanation = "";
			if (this.explanation != null) {
				temp.explanation = this.explanation[0];
			}

			temp.thumbImageURL = "";
			if (this.thumbnail != null) {
				temp.thumbImageURL = this.thumbnail[0];
			} else {
				var thumbId = 1;
				if (this.imageList[0].thumbnail != null) {
					thumbId = this.imageList[0].thumbnail[0];
					if (this.imageList[0].imageURL.length < thumbId) {
						thumbId = 1;
					}
				}
				temp.thumbImageURL = this.imageList[0].imageURL[thumbId - 1];
			}

			var overImageURL = "";
			if (this.overImageURL != null) {
				overImageURL = this.overImageURL[0];
			}
			temp.overImageURL = overImageURL;
			
			searchRes.push(temp);
		}

	);
}


//-----------------------------------
// 初回表示のときの検索
//-----------------------------------
function searchData_firstDisp() {
	searchRes = new Array();
	
	if (xmlData.jewelryList == null) {
		return;
	}
	
	$.each(xmlData.jewelryList[0].jewelry,

		function() {
			var item = "";
			if (this.item != null) {
				item = this.item[0];
			}
			
			// 価格
			var price = parseInt(this.price[0]);

			// 素材
			var materialList = new Array();
			if (this.materialList != null && this.materialList[0].material != null) {
				$.each(this.materialList[0].material, function() {
					materialList.push(this);
				});
			} else {
				materialList[0] = "";
			}
			
			// シーン
			var sceneList = new Array();
			if (this.sceneList != null && this.sceneList[0].scene != null) {
				$.each(this.sceneList[0].scene, function() {
					sceneList.push(this);
				});
			} else {
				sceneList[0] = "";
			}
			
			var temp = new Array();
			temp.item = item;
			temp.price = price;
			temp.materialList = materialList;
			temp.sceneList = sceneList;
			temp.id = this.id[0];
			temp.name = this.name[0];
			temp.entrylink = "";
			if (this.entrylink != null) {
				temp.entrylink = this.entrylink[0];
			}

			temp.explanation = "";
			if (this.explanation != null) {
				temp.explanation = this.explanation[0];
			}

			temp.thumbImageURL = "";
			if (this.thumbnail != null) {
				temp.thumbImageURL = this.thumbnail[0];
			} else {
				var thumbId = 1;
				if (this.imageList[0].thumbnail != null) {
					thumbId = this.imageList[0].thumbnail[0];
					if (this.imageList[0].imageURL.length < thumbId) {
						thumbId = 1;
					}
				}
				temp.thumbImageURL = this.imageList[0].imageURL[thumbId - 1];
			}

			var overImageURL = "";
			if (this.overImageURL != null) {
				overImageURL = this.overImageURL[0];
			}
			temp.overImageURL = overImageURL;

			searchRes.push(temp);
		}
	);
}


function dispNothingSearchRes() {
	$("#productsSearchBox").empty();
	$(".pageNavBox").empty();
	$(".pageNavBox").html('<div class="jewelryNaBox02"><img src="/common/img/jewelry/search_out.gif" width="360" height="104" alt="ジュエリー検索結果 お選び頂いた条件では該当する商品がございません。条件を変更し、再度商品をお探しください。" /></div>');

}

// 検索条件該当の商品表示
function dispSearchRes() {

	// 商品表示クリア
	$("#productsSearchBox").empty();

	$("#productsSearchBox").append($("<ul/>").addClass("jewelryList02"));
	
	var listNo = 1;

	var createOnclickSearchResItem = function (no, entrylink) {
		return function() {
			onclickSearchResItem(no, entrylink);
			return false;
		}
	}

	$.each(searchRes, function(i,val) {

		if (!firstDispFlg) {
			if (i < (pageNo - 1) * DISP_MAX
				|| pageNo * DISP_MAX - 1 < i)
			{
				return;
			}
		}

		// サムネイル画像
		var thumbURL = val.thumbImageURL;

		// ロールオーバー画像
		var thumbOverURL = val.overImageURL;
		
		// liタグのID属性
		var liIdNo = "0" + listNo;
		liIdNo = liIdNo.substr(liIdNo.length - 2);
		$("#productsSearchBox > ul")
			.append($("<li/>")
				.attr("id", "jewelry" + liIdNo)
				.append($("<a/>")
					.click(
						createOnclickSearchResItem(listNo, val.entrylink)
					)
					
					.attr("href", "#")

					.append($("<img/>")
						.attr("src",thumbURL)
						.attr("width", IMAGE_SIZE)
						.attr("height", IMAGE_SIZE)
						.attr("alt" ,val.id)
						.hover(
							function(){
								$(this).attr("src",thumbOverURL);
								// ToolTip表示
								var liElemId = $(this).parent().parent().attr("id");
								var jewelryId =$(this).attr("alt");
								dataSetAndDispToolTip(searchRes, liElemId, jewelryId);

							},
							function(){
								$(this).attr("src",thumbURL);
								// ToolTip非表示
								hideToolTip();
							}
						)
					)
				)
			);
		
		listNo = listNo + 1;
	});

	createJewelryToolTipTempl("productsSearchBox");
}



function dispPageNavi(searchNum) {
	var lastPageNo = Math.ceil(searchNum / DISP_MAX);

	$(".pageNavBox").empty();
	$(".pageNavBox").append($("<p/>").addClass("txtCenter"));

	if (pageNo >=2) {
		$(".pageNavBox").children("p")
			.append($("<a/>")
				.click(
					function() {
						changePage(pageNo-1);
						return false;
					}
				)
				.addClass("prev")
				
				.attr("href", "#")
				.append($("<img/>").attr("src", "/common/img/jewelry/pnav_products_prev.gif")
					.attr("width", "65")
					.attr("height", "16")
					.attr("alt", "前の商品")
				)
			);
	}

	var startNo;
	var endNo;
	if (lastPageNo < 10) {
		startNo = 1;
		endNo = lastPageNo;
	} else {
		if (pageNo <= 6) {
			startNo = 1;
			endNo = 10;
		} else {
			if ( pageNo + 4 <= lastPageNo) {
				startNo = pageNo - 5;
				endNo = pageNo + 4;
			} else {
				startNo = pageNo -5 - ((pageNo + 4) - lastPageNo);
				endNo = lastPageNo;
			}
		}
	}

	// クロージャ
    var createChangePage = function(index) {
    	return function() {
    		changePage(index);
    		return false;
    	}
    }

	for (var i = startNo; i <= endNo; i++) {
		if (i == pageNo) {
			$(".pageNavBox").children("p")
				.append($("<span/>")
					.text(i)
				);
		} else {
			$(".pageNavBox").children("p")
				.append($("<a/>")
					.click(
						createChangePage(i)
					)
					
					.attr("href", "#")
					.text(i)
				);
		}
	}

	if (pageNo < lastPageNo) {
		$(".pageNavBox").children("p")
			.append($("<a/>")
				.click(
					function() {
						// changePage(pageNo+1);
						changePage(pageNo+Number(1));
						return false;
					}
				)
				.addClass("next")

				.attr("href", "#")
				.append($("<img/>").attr("src", "/common/img/jewelry/pnav_products_next.gif")
					.attr("width", "67")
					.attr("height", "16")
					.attr("alt", "次の商品")
				)
			);
	}
}

