// JavaScript Document
// DOM関連ユーティリティ

//// イベントハンドラ関連
// リスナーの追加
function addListner(elem, eventType, func, cap) {
	if (elem.addEventListener) {
		elem.addEventListener(eventType, func, cap);
	} else if (elem.attachEvent) {
		elem.attachEvent('on' + eventType, func);
	} else {
		return false;
	}
}

// HTML固有のJavaScript関連初期化メソッドへのランチャー
// windowのload完了時に呼び出される
// HTML側で inithtml() を実装しておく必要がある
function inithtml0() {
	inithtml();
}

// load完了時に初期化メソッドへのランチャーが呼び出されるよう設定しておく
addListner(window, 'load', inithtml0, false);


//// HTTP関連
var httpObj = false;
var http_timerId;
var http_timeout_sec;
var http_timeoutFunc;
var http_finishFunc;

function createHttpObj() {
	if (httpObj) {
		return false;
	}
	try {
		if (window.XMLHttpRequest) {
			httpObj = new XMLHttpRequest();
		} else if (window.ActiveXObject) {
			httpObj = new ActiveXObject('Microsoft.XMLHTTP');
		}
	} catch (e) {
		httpObj = false;
	}
	return true
}

function doGet(url, timeout, finishFunc, timeoutFunc) {
	if (createHttpObj() == false) {
		return;
	}
	http_finishFunc = finishFunc;
	http_timeoutFunc = timeoutFunc;
	http_timeout_sec = timeout;
	http_timerId = setInterval('httpTimeoutCheck()', 1000);
	httpObj.open("GET", url, true);
	httpObj.onreadystatechange = httpStateChange;
	httpObj.send("");
}

function httpStateChange() {
	if (!httpObj) {
		return;
	}
	if (httpObj.readyState == 4) {
		clearInterval(http_timerId);
		http_finishFunc();
		clearHttpProc();
	}
}

function httpTimeoutCheck() {
	http_timeout_sec--;
	if (http_timeout_sec <= 0) {
		// タイマーストップ
		clearInterval(http_timerId);
		// HTTPリクエスト中断
		httpObj.abort();
		// タイムアウトコールバックを呼び出す
		if (http_timeoutFunc) {
			http_timeoutFunc();
		}
		// HTTPオブジェクトの開放
		clearHttpProc();
	}
}

function clearHttpProc() {
	http_timerId = 0;
	http_timeout_sec = 0;
	http_timeoutFunc = false;
	http_finishFunc = false;
	httpObj = false;
}

// Utilities
function getObjById(id) {
	return document.getElementById(id);
}

