/**
 * @file stationsearch.js
 * @brief 株式会社ワクワクプランの提供する駅データ.jpを用いるスクリプトファイル
 *
 * @author kinokorori
 * @date 2008. 7. 30
 */

var stationSearchManager = new function()
{
	this.stationInfoArray = null;
	this.stationNameTagName = "stationName";
	this.stationNameAttr = "value";
	this.forMsgTag = "searchResultMessage";
}

function stationInfo(s_name, l_name, st_g_code, lon, lat)
{
	this.stationName = s_name;
	this.lineName = l_name;
	this.stationGCode = parseInt(st_g_code);
	this.longitude = lon;
	this.latitude = lat;
	this.duplicate = false;
}

stationSearchManager.searchStation = function()
{
	$(this.forMsgTag).innerHTML = "検索中です。";

	var stationName = $(this.stationNameTagName).getValue();
	if (stationName == null) { return; }

	var url = "http://www.ekidata.jp/api/n.php";
	var pars = "w=" + encodeURIComponent(stationName);

/*
	if (navigator.appName == "Netscape") {
		try {
			netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
		} catch(e) {
			alert(e);
			return;
		}
	}
*/
	var proxy = "http://hiyoshisv.blogdns.com/tabesta/cgi-bin/proxy.php";
	var proxy_pars = "proxy_url=" + encodeURIComponent(url + "?" + pars);

	var ajax = new Ajax.Request(proxy,
		{
			method: 'get',
			parameters: proxy_pars,
			onComplete: this.completeGetStationInfo,
			onSuccess: this.succeededAjax,
			onFailure: this.callFail
		});
}

stationSearchManager.succeededAjax = function(req)
{
	var ret = stationSearchManager.getStationInfo(req);
	if (ret) { return; }

	//駅検索に失敗したので地名検索にシフト
	if (geocodingManager != undefined) {
		geocodingManager.search($(stationSearchManager.stationNameTagName).getValue());
	}
}

stationSearchManager.getStationInfo = function(req)
{
	var xmlData = req.responseXML;
	if (!xmlData) { return false; }
	var errorCodeNodes = xmlData.getElementsByTagName("error");
	var errorCode = errorCodeNodes[0].firstChild.nodeValue;
	if (errorCode != 0) {
		this.showErrorInStationSearch(errorCode);
		return false;
	}
	
	var totalNodes = xmlData.getElementsByTagName("total");
	var total = totalNodes[0].firstChild.nodeValue;
	if (total == 0) {
		//$(this.forMsgTag).innerHTML = "候補となる駅名がありません";
		return false;
	}
	
	var stationNodes = xmlData.getElementsByTagName("station");
	this.stationInfoArray = new Array();
	for (var i = 0; i < stationNodes.length; ++i) {
		var stationName = stationNodes[i].getElementsByTagName("station_name")[0].firstChild.nodeValue;
		var lineName = stationNodes[i].getElementsByTagName("line_name")[0].firstChild.nodeValue;
		var stationGCode = stationNodes[i].getElementsByTagName("station_g_cd")[0].firstChild.nodeValue;
		var lon = stationNodes[i].getElementsByTagName("lon")[0].firstChild.nodeValue;
		var lat = stationNodes[i].getElementsByTagName("lat")[0].firstChild.nodeValue;
		this.stationInfoArray[i] = new stationInfo(stationName, lineName, stationGCode, lon, lat);
	}

	this.uniqueStation();
	$(this.forMsgTag).innerHTML = this.stationInfoArray.length + "駅の候補が見つかりました。";

	//1駅ならそのままマップ移動+バー検索
	if (this.stationInfoArray.length == 1) {
		$("candidateStation").style.display = "none";
		this.moveToStation(this.stationInfoArray[0]);
		return true;
	}

	//セレクトエリアに表示
	var addTag = "";
	for (var i = 0; i < this.stationInfoArray.length; ++i) {
		addTag += '<option value="' + i + '"';
		if (!i) { addTag += ' selected="selected"'; }
		addTag += '>' + this.stationInfoArray[i].stationName;
		if (!this.stationInfoArray[i].duplicate) {	
			addTag += "[" + this.stationInfoArray[i].lineName + "]";
		}
		addTag += "</option>\n";
	}

	var candsElem = $("selectCandidate");
	if (candsElem.outerHTML == undefined) {
		candsElem.innerHTML = addTag;
	} else {
		candsElem.outerHTML = '<select name="selectCandidate" id="selectCandidate" size="4">' + addTag + '</select>';
	}
	$("candidateStation").style.display = "block";

	return true;
}

/**
 * @brief 緯度経度が等しい駅を統合します
 * @note 同じGCodeを有する駅同士だけを判断します
 */
stationSearchManager.uniqueStation = function() {
	this.stationInfoArray.sort(compareStationGCode);
	var shiftInfo = new stationInfo(null, null, -1, 0, 0);
	var endLoop = this.stationInfoArray.length;
	for (var i = 0; i < endLoop; ++i) {
		var tempInfo = this.stationInfoArray.shift();
		if (tempInfo.stationGCode == shiftInfo.stationGCode) {
			//var dist = this.calcLatLongToDist(tempInfo.latitude, tempInfo.longitude, 
			//	shiftInfo.latitude, shiftInfo.longitude);
			//alert(tempInfo.stationName + " to " + shiftInfo.stationName + " = " + dist);
			//if (tempInfo.latitude==shiftInfo.latitude && tempInfo.longitude==shiftInfo.longitude) {
				this.stationInfoArray[this.stationInfoArray.length - 1].duplicate = true;
				continue;
			//}
		}
		this.stationInfoArray.push(tempInfo);
		shiftInfo = tempInfo;
	}
}

/**
 * @brief 駅GroupCodeによるソート用関数
 */
function compareStationGCode(lhs, rhs) {
	return lhs.stationGCode - rhs.stationGCode;
}

/**
 * @brief 駅候補決定
 */
stationSearchManager.decideStation = function()
{
	this.moveToStation(this.stationInfoArray[$("selectCandidate").selectedIndex]);
}

/**
 * @brief 駅に移動
 * @param[in] objStationInfo stationInfoオブジェクト
 */
stationSearchManager.moveToStation = function(objStationInfo)
{
	mapCtrl.moveMap(objStationInfo.latitude, objStationInfo.longitude);
	tabelogManager.newSearch(objStationInfo.latitude, objStationInfo.longitude);
}

stationSearchManager.completeGetStationInfo = function()
{
}

stationSearchManager.callFail = function()
{
	$(this.forMsgTag).innerHTML = "検索に失敗しました。";
}

stationSearchManager.showErrorInStationSearch = function(errorCode)
{
	var str = "";
	switch(errorCode) {
	case 1:
		str = "検索文字列に問題があります。";
		break;
		
	default:
		str = "駅名検索時に不明なエラーが発生しました。";
		break;
	}
	$(this.forMsgTag).innerHTML = str;
}

/**
 * @brief 緯度経度から距離を計算する(近似計算)
 * @return 距離
 */
stationSearchManager.calcLatLongToDist = function(lat1, lon1, lat2, lon2)
{
	var dl = lon2 - lon1;
	var dp = lat2 - lat1;
	var R = 6378137;
	var dx = R * dl * Math.cos((lat1 *  Math.PI) / 180);
	var dy = R * dp;
	var L = Math.sqrt(dx*dx + dy*dy);
	return L;
}
