// *********************************************************************
// *********************************************************************
var _request;
var _target;
var _rateid;
var _infoid;
var _primary = new Array("USDJPY", "EURJPY", "GBPJPY");
var _secondary = new Array("AUDJPY", "NZDJPY", "ZARJPY", "TRYJPY");
var _rateboxs = new Array();
var _protocol = "http";

$(function() {
	//_request = getXmlHttpRequest();
	
	_protocol = document.location.protocol;
	if(_protocol.substr(0, _protocol.length - 1) == "https") {
		_protocol = "https";
	} else {
		_protocol = "http";
	}
	
	getRate();
	getInformations();
});

// =====================================================================
// =====================================================================
function getXmlHttpRequest() {
	if (window.XMLHttpRequest) {
		_request = new XMLHttpRequest(); 
		//_request.overrideMimeType('text/xml')	
	} else {
		try {
			_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				_request = new ActiveXObject("Microsoft.XMLHTTP");
			} 
			catch (e) {
				_request = false;
			}
		}
	}
	return _request;
}

function getRate() {
	var url = _protocol + "://www.phillipfinancials.com/apis/get_rateinfo.php";
	
	$.ajax({
		url: url,
		cache: false,
		success: onResultHandler
	});
//	_request.open('POST', url, true);
//	_request.onreadystatechange = onResultHandler;
//	_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//	_request.send();
	
	_rateid = setTimeout(getRate, 100000);
}

function getInformations() {
	var url = _protocol + "://www.phillipfinancials.com/apis/get_information.php";

	$.ajax({
		url: url,
		cache: false,
		success: onResultInfoHandler
	});
	
//	_request.open('POST', url, true);
//	_request.onreadystatechange = onResultInfoHandler;
//	_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//	_request.send();
	
	_infoid = setTimeout(getInformations, 100000);
}

function onResultHandler(res, status, xhr) {
//	if(_request.readyState == 4) {
//		if(_request.status == 200) {
//			if(_request.responseText != "") {
				try
				{
					eval("var data = " + res);
					setRateInfo(data, "primary_rate", _primary);
					setRateInfo(data, "secondary_rate", _secondary);
				}
				catch(e)
				{
					alert(e.message);
				}
//			}
//		}
//	}
}

function onResultInfoHandler(res, status, xhr) {
//	if(_request.readyState == 4) {
//		if(_request.status == 200) {
//			if(_request.responseText != "") {
				try
				{
					//eval("var data = " + _request.responseText);
					eval("var data = " + res);
					setFxInformation(data);
				}
				catch(e)
				{
					alert(e.message);
				}
//			}
//		}
//	}
}

function setRateInfo(data, target, ratetype) {
	var base_tag = $('#Ticker .' + target);
	if(base_tag.length == 0) {
		var box = createRateBox(data, target, ratetype);
		$('#Ticker').append(box);
		return;
	}
	
	// 日付設定
	var up_date = data["rates attr"].date.split(' ')[0].split('/');
	var datetime = up_date[0] + "." + up_date[1] + "." + up_date[2];
	$('span:first', base_tag).html(datetime);
	
	for(val in data.rates.rate) {
		for(var n = 0; n < ratetype.length; n++) {
			var node = data.rates.rate[val];
			if(ratetype[n] == node.pair) {
				var tag_p = $('.' + node.css, base_tag);
				$('.ask', tag_p).html(node.ask);
				$('.bid', tag_p).html(node.bid);
			}
		}
	}
}

function createRateBox(data, target, ratetype) {
	var base_node = $('<li></li>')
			.attr('class', target);
	var icon = $('<img/>')
			.attr('src', 'http://www.phillipfinancials.com/images/ico_Rate.gif')
			.attr('alt', 'FXレート情報')
			.attr('class', 'Ico1')
			.width(40)
			.height(40);
	var title = $('<img/>')
			.attr('src', 'http://www.phillipfinancials.com/images/icon-list_Rate.gif')
			.attr('alt', 'フィリップFXレート情報')
			.attr('class', 'Ico2')
			.width(68)
			.height(16);
	var up_date = data["rates attr"].date.split(' ')[0].split('/');
	var datetime = up_date[0] + "." + up_date[1] + "." + up_date[2];
	var update_p = $('<p></p>')
			.html('<span>' + datetime + '</span>');
	
	base_node.append(icon);
	base_node.append(title);
	base_node.append(update_p);
	
	for(val in data.rates.rate) {
		for(var n = 0; n < ratetype.length; n++) {
			var node = data.rates.rate[val];
			if(ratetype[n] == node.pair) {
				var ask_p = '<span class="ask">' + node.ask + '</span>';
				var bid_p = '<span class="bid">' + node.bid + '</span>';
				var tag_p = $('<p></p>')
						.attr('class', node.css)
						.html(node.jpname + ":<br />" + bid_p + "-" + ask_p);
				base_node.append(tag_p);
			}
		}
	}
	return base_node;
}

function setFxInformation(data) {
	var node;
	var ul = $('ul#Ticker');
	var lis = $('li', ul);
	var count = 0;
	
	for(var n = 0; n < lis.length; n++) {
		var obj = $(lis[n]);
		var classes = obj.attr('class');
		if(classes != "primary_rate" && classes != "secondary_rate") {
			obj.remove();
		}
	}
	
	for(val in data.informations.info) {
		var tmp = data.informations.info[val];
		if(tmp == undefined) continue;
		if(tmp.css != undefined) {
			node = data.informations.info[val];
		} else {
			if(node == undefined) continue;
//			var li = $('.' + node.css, ul);
			var tag = createInformationBox(tmp, node);
			//var num = Math.floor( Math.random() * 5 );
			if(count == 0) {
				$('.primary_rate', ul).after(tag);
			} else if(count == 1) {
				$('.secondary_rate', ul).after(tag);
			} else {
				ul.append(tag);
			}
//			if(li.length == 0) {
//				if(lis > 8) $('li:last', ul).remove();
//				var tag = createInformationBox(tmp, node);
//				ul.append(tag);
//			} else {
//				replaceInformationBox(tmp, node);
//			}
			count++;
		}
	}
}

function createInformationBox(data, node) {
	var li_base = $('<li></li>')
				.attr('css', node.css);
//	var a_tag = $('<a></a>')
//		.attr('href', data.link);
	var icon = $('<img />')
		.attr('css', 'Ico1')
		.width(40)
		.height(40);
	var title = $('<img />')
		.attr('css', 'Ico2')
		.width(68)
		.height(16);

	if(node.css == "iconRelease") {
		icon.attr('src', 'http://www.phillipfinancials.com/images/ico_Release.gif')
			.attr('alt', 'ニュースリリース');
		title.attr('src', 'http://www.phillipfinancials.com/images/icon-list_Release.gif')
			.attr('alt', 'フィリップFXニュース');
	} else if(node.css == "iconInfo") {
		icon.attr('src', 'http://www.phillipfinancials.com/images/ico_Info.gif')
			.attr('alt', 'フィリップFXのお知らせ');
		title.attr('src', 'http://www.phillipfinancials.com/images/icon-list_Info.gif')
			.attr('alt', 'お知らせ');
	} else if(node.css == "iconOther") {
		icon.attr('src', 'http://www.phillipfinancials.com/images/ico_Info.gif')
			.attr('alt', 'フィリップFXからのセミナーのお知らせ・その他');
		title.attr('src', 'http://www.phillipfinancials.com/images/icon-list_Other.gif')
			.attr('alt', 'セミナーのお知らせ・その他');
	} else if(node.css == "iconCampaign") {
		icon.attr('src', 'http://www.phillipfinancials.com/images/ico_Campaign.gif')
			.attr('alt', 'フィリップFXのキャンペーン');
		title.attr('src', 'http://www.phillipfinancials.com/images/icon-list_Campaign.gif')
			.attr('alt', 'FXキャンペーン');
	} else if(node.css == "iconSeminar") {
		icon.attr('src', 'http://www.phillipfinancials.com/images/ico_Seminar.gif')
			.attr('alt', 'フィリップFXからのセミナーのお知らせ');
		title.attr('src', 'http://www.phillipfinancials.com/images/icon-list_Seminar.gif')
			.attr('alt', 'セミナーのお知らせ');
	} else if(node.css == "iconSystem") {
		icon.attr('src', 'http://www.phillipfinancials.com/images/ico_System.gif')
			.attr('alt', 'フィリップFXからウェブサイト及び取引システムに関するお知らせ');
		title.attr('src', 'http://www.phillipfinancials.com/images/icon-list_System.gif')
			.attr('alt', 'システムに関するお知らせ');
	} else if(node.css == "iconNotice") {
		icon.attr('src', 'http://www.phillipfinancials.com/images/ico_Notice.gif')
			.attr('alt', 'フィリップFXからの緊急のお知らせ');
		title.attr('src', 'http://www.phillipfinancials.com/images/icon-list_Notice.gif')
			.attr('alt', '緊急のお知らせ');
	}
	
	var up_date = data.update.split(' ')[0].split('/');
	var datetime = up_date[0] + "." + up_date[1] + "." + up_date[2];
	
	var tag_p = $('<p></p>')
			.html('<span><a href="' + data.link + '">' + datetime + '</a></span><br/>' + data.description);
	
	li_base.append(icon);
	li_base.append(title);
	li_base.append(tag_p);
//	li_base.append(a_tag);
	
	return li_base;
}

function replaceInformationBox(data, node) {
	var li_tag = $('#Ticker .' + node.css);
	var up_date = data.update.split(' ')[0].split('/');
	var p_tag = $('p', li_tag);
	
	var datetime = up_date[0] + "." + up_date[1] + "." + up_date[2];
	p_tag.html('<span>' + datetime + '</span><br/>' + data.description);
	
	if(data.link != undefined) {
		var url = data.link['url'];
		var title = data.link['linktext'];
		p_tag.html(p_tag.html() + "<br/><a href=\"" + url + "\">" + title + "</a>");
	}
}
