﻿var _timerID;
var _category;
var _nodeID;
var _keyword;
var _page;
var _safeSearch;
var _runBtn;

var _initWord;

function loadAmazon() {
	ButtonSet("Starting");

	// アマゾンへのリクエストURLを作成するPHPを呼び出し、#ReqUrlエリアに挿入
	var phpURL="get_url.php";
	phpURL += "?idx=" + _category;
	phpURL += "&nid=" + _nodeID;
	phpURL += "&pag=" + _page;
	phpURL += "&kwd=" + encodeURIComponent(_keyword);
	
	$("#ReqUrl").load(
		phpURL,
		function(html, status){
			if (status == "success") {
				// なんか変なのが入るので取る
				var originalURL = encodeURIComponent(html).replace(/[\%EF\%BB\%BF]+/i, "");

				// XMLは、、ドメインを越えて通信できない(クロスドメイン)のでダミーのPHPを噛ませる
				var phpURL="get_xml.php?url=" + originalURL;

				// XMLデータを取得し、パース
				var http = new JKL.ParseXML( phpURL );          	// JKL.ParseXMLオブジェクトを生成
				var data = http.parse();                    		// ダウンロード～解析する

				try {
					// 商品HTML作成
					var goodsHtml = dataToHtml(data.ItemSearchResponse.Items.Item);
					if (goodsHtml != "") {
						listAreaH = "200px";
					} else {
						goodsHtml = "商品は、セーフサーチ機能によりにブロックされました。次の商品を検索しています。";
						listAreaH = "30px";
					}
					// 親パネルをリストの先頭に追加
					var elem = $("<div/>").attr("style", "clear:both; height:0px;");
					$("#ListArea").prepend(
						elem.animate({height: listAreaH}, 2000)	// 親パネルアニメーション
					);
					// もう1つパネル(子パネル)を作り、その中に商品パネルを作成
					var panel = $("<div/>").html(goodsHtml);
					// 親パネルの中に子パネルを追加
					elem.append(panel.fadeIn(2500));				// 子パネルフェードイン
				} catch(e) {
					//status = "エラーが発生しました。" + e;
					status = "すべてのデータを表示しました。";
				}
				_page++;

			} else {
				//status = "リクエストURLの取得に失敗しました。";
				status = "エラーが発生しました。しばらく経ってから、実行してみてください。";
			}

			// errorなら終了
			if (status != "success") {
				clearInterval(_timerID);	// タイマー解除
				$("#ListArea").prepend(
					$("<div/>").html(status + "<br />").attr("style", "clear:both; color:red; font-weight:bold; height:30px; text-align:center;")
				);
				ButtonSet("");				// ボタン初期化
			} else {
				ButtonSet("Start");			// スタート(検索)待ち
			}
		}
	);
}

function loadInitStart() {
	if (_timerID != 0) loadStop();							// タイマー停止
	$("#ListArea").empty();								// 商品リストクリア
	$("#RelationWordList").animate({height: "0px"}, 1500);// 関連語クリア

	var ddlCategory = $("#ddlCategory option:selected");
	_category = ddlCategory.val();
	_keyword = $("#txtKeyword").val();
	if (_keyword == '') {
		_nodeID = ddlCategory.attr("name");
	}
	_page = 1;
	_safeSearch = $("#chkAdult").attr("checked");
	
	// タイトル
	var title = '';
	var subTitle = '';
	if (_category == 'All' && _keyword == '') {
		title = 'カテゴリーを指定しない場合は、キーワードを入力する必要があります。';
	} else {
		// データ取得開始
		loadStart();
		// タイトル
		title = _keyword;
		title += ' [' + ddlCategory.text() + ']';
		if (_safeSearch) {
			subTitle = 'セーフサーチ：ON';
		} else {
			subTitle = 'セーフサーチ：OFF';
		}
	}
	// 関連語表示
	loadRelatioWord(_keyword);
	// タイトル
	$("#SearchTitle").html('<h2>' + HtmlSpecialChars(title) + '</h2>' + subTitle);
}

function loadStart() {
	if (_timerID == 0) {
		loadAmazon();
		_timerID = setInterval(loadAmazon, 6000);
	}
}

function loadStop() {
	clearInterval(_timerID);	// タイマー解除
	_timerID = 0;
}

function dataToHtml(item) {

	var html = "";
	var imageSize = 120;
	
	for (i = 0; i < item.length; i++) {
		if (!item[i].ItemAttributes.IsAdultProduct) {
			adult = false;							// 非アダルト
		} else {
			adult = true;							// アダルト
		}
		if (!item[i].ItemAttributes.Title) {
			title = "No Title";
		} else {
			title = item[i].ItemAttributes.Title;
		}
		try {
			if (!item[i].OfferSummary.LowestNewPrice.FormattedPrice) {
				price = " - ";
			} else {
				price = item[i].OfferSummary.LowestNewPrice.FormattedPrice;
			}
		} catch(e) {
			price = " - ";
		}
		if (!item[i].DetailPageURL) {
			url = "";
		} else {
			url = item[i].DetailPageURL;
		}
		
		if (!(_safeSearch && adult)) {
			html += "<div class=\"goodsPanel\">";
			html += "<a class=\"title\" href=\"" + url + "\" target=\"_blank\" onClick=\"GoodsClick();\">";
			html += title;
			html += "</a>";
			html += "<a class=\"image\" href=\"" + url + "\" target=\"_blank\" title=\"" + title + "\" onClick=\"GoodsClick();\">";
			html += dataToImageHtml(item, imageSize, title);
			html += "</a>";
			html += price
			html += "</div>";
		}
	}

	return html;
}

function dataToImageHtml(item, imageSize, title) {
	var imageSet;
	if (!imageSet) {
		try { imageSet = (!!item[i].MediumImage.URL) ? item[i].MediumImage : '';	}catch(e) {}
	}
	if (!imageSet) {
		try { imageSet = (!!item[i].LargeImage.URL) ? item[i].LargeImage : '';	}catch(e) {}
	}
	if (!imageSet) {
		try { imageSet = (!!item[i].SmallImage.URL) ? item[i].SmallImage : '';	}catch(e) {}
	}

	// 画像サイズ調整
	if(!!imageSet) {
		src = imageSet.URL;
		h = imageSize;
		w = imageSize;
		if (!!imageSet.Height['#text']) {
			h = imageSet.Height['#text'];
		}
		if (!!imageSet.Width['#text']) {
			w = imageSet.Width['#text'];
		}
		//if ($w >= $this->ImageSize) {		// 基準サイズを最大として、縦横比を合わせる（幅）
			h = imageSize * h / w;
			w = imageSize;
		//}
		if (h >= imageSize) { 				// 基準サイズを最大として、縦横比を合わせる（高さ）
			w = imageSize * w / h;
			h = imageSize;
		}
	} else {
		src= "img/NoImage100x100.png";
		h = imageSize;
		w = imageSize;
	}
	// IMGタグ作成
	html = "<img src=\"" + src + "\"";
	html += " style=\"";
	html += "height:" + h + "px;";
	html += "width:" + w + "px;";
	html += "\"";
	html += " alt=\"" + title + "\"";
	html += " />";
	return html;
}

function ButtonSet(runBtn) {
	if (runBtn == "") {
		$("#btnSearch").attr("src", "img/btnStart.gif");
		$("#btnStop").attr("src", "img/btnStop.gif");
		$("#btnRestart").attr("src", "img/btnRestart.gif");
	} else if (runBtn == "Starting"){
		$("#btnSearch").attr("src", "img/btnStarting.gif");
		$("#btnStop").attr("src", "img/btnStop.gif");
		$("#btnRestart").attr("src", "img/btnRestart.gif");
	} else if (runBtn == "Start"){
		$("#btnSearch").attr("src", "img/btnStart_On.gif");
		$("#btnStop").attr("src", "img/btnStop.gif");
		$("#btnRestart").attr("src", "img/btnRestart.gif");
	} else if (runBtn == "Stop"){
		$("#btnSearch").attr("src", "img/btnStart.gif");
		$("#btnStop").attr("src", "img/btnStop_On.gif");
		$("#btnRestart").attr("src", "img/btnRestart.gif");
	} else if (runBtn == "Restart"){
		$("#btnSearch").attr("src", "img/btnStart.gif");
		$("#btnStop").attr("src", "img/btnStop.gif");
		$("#btnRestart").attr("src", "img/btnRestart_On.gif");
	}
	_runBtn = runBtn;
}
/*
	Yahoo!の急上昇検索ワードを取得
*/
function loadWord() {
	try {
		var url = 'http://shopping.yahooapis.jp/ShoppingWebService/V1/json/queryRanking?appid=aifxudaxg65Lnw6xV8bGOoMfOXKXF0LIV8wCLTYXpLAagXTNrUTFQp_xWUBkPw--&type=up';
		url += '&callback=?';

		$.getJSON(url, function(data) {
			_initWord = data.ResultSet['0'].Result['0'].Query;
			$("#txtKeyword").val(_initWord);
		});
	} catch(e) {
		_initWord = '';
	}
}
/*
	関連語取得
*/
function loadRelatioWord(baseWord) {
	try {
		$("#RelationWordList").height(0);
		$("#RelationWordList").load(
			'relation_word.php?kwd=' + encodeURIComponent(baseWord),
			function(html, status){
				if (status == "success") {
					$("#RelationWordList").animate({height: "15px"}, 1500);
				}
			});
	} catch(e) {
	}
}
/*
	商品クリック
*/
function GoodsClick() {
	loadStop();
	ButtonSet("Stop");
}
/*
	関連語クリック
*/
function RelWordClick(word) {
	$("#txtKeyword").val(word);
	loadInitStart();
	ButtonSet("Starting");
}

$(document).ready(function(){
	_timerID = 0;
	_nodeID = '';
	_keyword = '';
	_page = 1;
	_safeSearch = 0;
	$("#chkAdult").attr("checked", true);

	// 検索ボタン
	$("#btnSearch")
		.click(function(){
			loadInitStart();
			ButtonSet("Starting");
		return false;
		})
		.hover(
			function(){ $(this).attr("src", "img/btnStart_On.gif"); },
			function(){ if (_runBtn != "Start") $(this).attr("src", "img/btnStart.gif"); }
	);
	
	// 一時停止ボタン
	$("#btnStop")
		.click(function(){
			loadStop();
			ButtonSet("Stop");
			return false;
		})
		.hover(
			function(){ $(this).attr("src", "img/btnStop_On.gif"); },
			function(){ if (_runBtn != "Stop") $(this).attr("src", "img/btnStop.gif"); }
	);
	
	// 再開ボタン
	$("#btnRestart")
		.click(function(){
			loadStart();
			ButtonSet("Starting");
			return false;
		})
		.hover(
			function(){ $(this).attr("src", "img/btnRestart_On.gif"); },
			function(){ $(this).attr("src", "img/btnRestart.gif"); }
	);
	
	// キーワード入力テキストボックス
	$("#txtKeyword").click(function(){
		if ($(this).val() == _initWord) {
			$(this).val("");
		}
	})

	// キーワードを初期入力
	//loadWord();
});

