/* ＵＴＦー８ */

/*
usage sample 1:
	var json = new Json('http://www.venusrecord.com/v2/json/35416.json',
			function (obj) {alert('price: ' + obj.price);},
			function () {alert('HttpRequest error:' + this.url);});
	json.send();

usage sample 2:
	Json.send('http://www.venusrecord.com/v2/json/35416.json',
			function (obj) {alert('price: ' + obj.price);},
			function () {alert('HttpRequest error:' + this.url);});

 */

/*
 * Json constructor
 */
function Json(url, onreceive, onerror) {
	this.url = url;
	Json[this.url] = this;
	if (onreceive) {
		this.onreceive = onreceive;
	}
	if (onerror) {
		this.onerror = onerror;
	}
}

/*
 * initialize Json class
 */
_Json();
function _Json() {

	Json.prototype.onreceive = doNothing;
	Json.prototype.onerror = doNothing;
	Json.prototype.send = send;
	Json.onreadystatechange = onreadystatechange;
	Json.callback = callback;

	Json.send = function (url, onreceive, onerror) {
		(new Json(url, onreceive, onerror)).send();
	};

	function callback(object) {
		return object;
	}

	function doNothing() {
	}

	//
	function send() {
		this.http_request = createHttpRequest();
		this.http_request.onreadystatechange = new Function('Json.onreadystatechange(\''  + this.url + '\');');
		this.http_request.open("GET", this.url, true);
		this.http_request.send(null);
	}

	//
	function onreadystatechange(key) {
		var json = Json[key];
		if (json && json.http_request && json.http_request.readyState == 4) {
			if (json.http_request.status == 200) {
				json.onreceive(eval("(" + json.http_request.responseText + ")"));
			} else {
				json.onerror();
			}
			delete json.http_request;
			delete Json[key];
		}
	}

	// XMLHttpRequestオブジェクト生成
	function createHttpRequest() {

		// Win IE用
		if(window.ActiveXObject) {

			// MSXML2以降
			try {
				return new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {}

			// 旧MSXML
			try {
				return new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}

		} 

		// XMLHttpRequestオブジェクト実装ブラウザ
		if(window.XMLHttpRequest){
			return new XMLHttpRequest();
		}

		return null;
	}

}
