/**
 * 共通スクリプト
 * 
 * @author	George Mitsumoto
 * @version	2006-09-14
 * @version	2006-10-21
 * @version	2006-11-01
 * @version	2007-02-08
 * @version	2007-02-11
 * @version 2007-02-12
 * @version 2007-02-14
 */

// ログイン情報を保持していなければログイン画面へリダイレクトする
var sig;
var reloadFlg;
var winName;
var tmpRealPath;
var tmpSelfPath;

tmpRealPath    = getRealPath();
tmpSelfPath    = window.location.pathname;
tmpVirtualPath = tmpSelfPath.replace(tmpRealPath, '');

if (tmpVirtualPath.match(/\//) == '/') {
	sig = getCookie('signature');
	reloadFlg = getCookie('RELOAD');
	winName = window.name;

	if (sig.length < 10 && reloadFlg != 't') {
	//	location.href = getRealPath() + 'logout.php';
		setCookie('RELOAD', 't');
	}
}

// onLoadが2回以上実行されないようにするためのフラグ
onLoded_flg1  = 0;
onLoded_flg2  = 0;
selfName      = '';
newWindowFlag = 'f';

/**
 * ブラウザ識別
 */
window.navigator.isWinIE   = null;
window.navigator.isMacIE   = null;
window.navigator.isMozilla = null;
window.navigator.isOpera   = null;
window.navigator.isSafari  = null;
window.navigator.isUnknown = null;

//  Safari
if (navigator.userAgent.indexOf("Safari") > -1) {
	window.navigator.isSafari = true;
}
//  Opera
else if (window.opera) {
	window.navigator.isOpera = true;
}
//  MacIE
else if (navigator.userAgent.indexOf("MSIE") > -1 && navigator.platform.indexOf("Mac") > -1) {
	window.navigator.isMacIE = true;
}
//  WinIE
else if (document.all && document.selection) {
	window.navigator.isWinIE = true;
}
//  Mozilla
else if (window.controllers) {
	window.navigator.isMozilla = true;
}
//  Unknown
else {
	window.navigator.isUnknown = true;
}

/**
 * window.onScroll ハンドラを割り当てる
 */
if (window.navigator.isWinIE == true) {
	window.onscroll = function msgScroll() {
        var canvas = document[ 'CSS1Compat' == document.compatMode ? 'documentElement' : 'body'];
		y = canvas.scrollTop;
		if (document.getElementById("loadingBox") != null) {
			document.getElementById("loadingBox").style.top = y;
		}
	};
}

/**
 * window.onload ハンドラを割り当てる
 * 
 * @example		window.addOnLoadHandler(hoge:Function);
 */
window.onLoadHandlers = new Array();
window.addOnLoadHandler = function(handler) {
	window.onLoadHandlers.push(handler);
};

window.onLoadHandler = function() {
	for (var i=0; i<window.onLoadHandlers.length; i++) {
		window.onLoadHandlers[i]();
	}
};

if (window.addEventListener) {
	window.addEventListener("load", onLoadHandler, true);
}
else {
	window.attachEvent("onload", onLoadHandler);
}

/**
 * window.unload ハンドラを割り当てる
 */
if (window.navigator.isWinIE || window.navigator.isMozilla) {
	window.onbeforeunload = setSessionId;
}
else {
	window.onunload = setSessionId;
}

/**
 * Cookieへの書き込み
 * セッションと同等の扱いをするため有効期限は指定していない
 * 
 * @param	_key	キー
 * @param	_value	値
 */
function setCookie(_key, _value) {
	document.cookie = _key + "=" + escape(_value) + "; path=/;";
}

/**
 * Cookieからの読み込み
 * 
 * @param	_key	キー
 * @return	値
 */
function getCookie(_key) {
	var tmp = document.cookie + ";";
	var tmp1 = tmp.indexOf(_key, 0);
	if (tmp1 != -1) {
		tmp = tmp.substring(tmp1, tmp.length);
		start = tmp.indexOf("=", 0) + 1;
		end = tmp.indexOf(";", start);
		return(unescape(tmp.substring(start, end)));
	}
	else {
		return('');
	}
}

/**
 * 2回目以降の送信を無効にする
 */
function enableSubmitOnce() {
	
	/**
	 * 二重送信の抑止
	 *
	 * @param	_nextPage	2回目以降の送信がされようとした場合の遷移先URL
	 */
	document.canSubmit = function(_nextPage) {
		
		if (getCookie("submitted") == 1) {
			
			tracer.print("連続送信はできません。", 1);
			
			if (_nextPage != undefined) {
				//alert("連続送信しようとしたため、" + _nextPage + " へ飛ばします。", 1);
				location.href = _nextPage;
			}
			return false;
		}
		else {
			setCookie("submitted", 1);	//  送信済みフラグ
			return true;
		}
	}
	
	//tracer.print("enableSubmitOnce : " + typeof document.canSubmit);
	//tracer.print("Cookieを使用した連打抑止処理の実験中", 1);
}

/**
 * 送信済みフラグをクリアする
 */
function initSubmitOnce() {
	setCookie("submitted", 0);
	//tracer.print("送信済みフラグをクリア : " + getCookie("submitted"));
}


/**
 * 開発用簡易トレース
 */
window.tracer = new Object();
function enableTracer() {
	tracer = document.createElement("DIV");
	with (tracer) {
		style.position   = "absolute";
		style.top        = "600px";
		style.right      = "10px";
		style.lineHeight = "1.2";
		style.textAlign  = "right";
		style.fontSize   = "9pt";
		style.color      = "#666";
		// innerHTML        = "/* JavaScript Trace */<br />";
	}
	
	tracer.print = function(_exp, _strong) {
		try {
			if (_strong != undefined) {
				// tracer.innerHTML += "<span style='color:#f00; font-weight:bold;'>" + _exp + "</span><br />";
			}
			else {
				// tracer.innerHTML += _exp + "<br />";
			}
		}
		catch (_error) {
			alert(_error.message);
		}
	}
	document.body.appendChild(tracer);
}


/**
 * SHA1形式のハッシュ処理を行う
 * 
 * @param 	_str	処理対象文字列
 * @return			ハッシュ化した文字列
 * @example	sha1Encode("hoge");
 */
/*** 2007.02.14 K.Takashima Delete ***************
function sha1Encode(_str) {
	var mod    = function(_val)       { return _val % 4294967296 };
	var rotl   = function(_val, _n)   { return (_val << _n) | (_val >>> (32 - _n)) };
	var ch     = function(_b, _c, _d) { return (_b & _c) ^ (~_b & _d) };
	var maj    = function(_b, _c, _d) { return (_b & _c) ^ (_b & _d) ^ (_c & _d) };
	var parity = function(_b, _c, _d) { return _b ^ _c ^ _d };

	var tohex = function(_n) {
		_n = ""+ _n.toString(16);
		if (_n.length==1) _n = "0"+ _n;
		return _n;
	};

	var shafinal = function() {
		var hash = "";
		for (var i=0; i<state.length; i++) {
			hash += tohex((state[i] >>> 24) & 0xff) +
			tohex((state[i] >>> 16) & 0xff) + 
			tohex((state[i] >>>  8) & 0xff) +
			tohex(state[i] & 0xff)
		}
		return hash;
	};

	var sharound = function(_block) {
		var i, j, tmp, x = [];
		var tmpState = [state[0], state[1], state[2], state[3], state[4]];

		for (j=i=0; i<16; i++, j+=4) {
			x[i] = (_block[j+0]<<24) ^ (_block[j+1]<<16) ^ (_block[j+2]<<8) ^ _block[j+3];
		}
		for (i=16; i<80; i++) {
			x[i] = rotl(x[i-3] ^ x[i-8] ^ x[i-14] ^ x[i-16], 1);
		}
        for (i=0; i<80; i++) {
			if (i < 20) {
				tmp = ch(state[1], state[2], state[3], state[4]) + k[0];
			}
			else if (i < 40) {
				tmp = parity(state[1], state[2], state[3], state[4]) + k[1];
			}
			else if (i < 60) {
				tmp = maj(state[1], state[2], state[3], state[4]) + k[2];
			}
			else {
				tmp = parity(state[1], state[2], state[3], state[4]) + k[3];
			}
			tmp = mod(tmp + rotl(state[0], 5) + x[i] + state[4]);
			state[4] = state[3];
			state[3] = state[2];
			state[2] = rotl(state[1], 30);
			state[1] = state[0];
			state[0] = tmp;
		}

		for (i=0; i<state.length; i++) {
			state[i] = mod(state[i]+ tmpState[i]);
		}
    };

	var shaupdata = function(_data) {
		// unpack
		var i, c, tmp=[];
		for (i=0; i<_data.length; i++) {
			c = _data.charCodeAt(i);
			tmp[tmp.length] = c & 0xff;
			while (c > 0xff) {
				tmp[tmp.length] = (c >>>= 8) & 0xff;
			}
		}
		// padding
		var datLen = tmp.length;
		tmp[tmp.length] = 0x80;
		var md = (56 > datLen % 64? 56: 56+ 64)- (datLen % 64);

		while (--md) {
			tmp[tmp.length] = 0;
		}
		// updata
		datLen *= 8;
		return tmp.concat(0, 0, 0, 0,
							(datLen >>> 24) & 0xff,
							(datLen >>> 16) & 0xff,
							(datLen >>>  8) & 0xff,
							datLen & 0xff
						 );
	};
    
	var state = new Array(0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0);
    var k = new Array(0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6);

	var dataz = shaupdata(_str);
	for (var i=0; i<dataz.length/64; i++) {
		sharound(dataz.slice(i*64, ((i+1)*64)));
	}
	return shafinal();
}
*** 2007.02.14 K.Takashima Delete End ************/


/**
 * httpObjectを利用してサーバとバックグラウンド通信を行う
 * 
 * @param	_cbFunc	コールバック関数
 * @return	サーバからの応答
 */
function createXMLHttpRequest(_cbFunc) {
	var XMLhttpObject = null;
	try {
		XMLhttpObject = new XMLHttpRequest();
	}
	catch(e) {
		try	{
			XMLhttpObject = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch(e) {
			try {
				XMLhttpObject = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch(e) {
				return null;
			}
		}
	}
	if (XMLhttpObject) XMLhttpObject.onreadystatechange = _cbFunc;
	return XMLhttpObject;
}

/**
 * WindowNameを取得して各種処理を行う
 */
function checkWindowName() {

	// 2回目の実行であれば何もせずに終了
	if (onLoded_flg1 > 0) {
		return;
	}
	else {
		onLoded_flg1 = 1;
	}

	var key;
	var windowName;
	var phpSessId;
	var ret;
	var httpObj1;
	var httpObj2;
	var httpObj3;
	var postData;
	var realPath;

	// 正確な絶対パスを取得
	realPath = getRealPath();

	// バックグラウンド用のオブジェクトを生成
	httpObj1 = createXMLHttpRequest(dummyFunction);
	httpObj2 = createXMLHttpRequest(dummyFunction);
	httpObj3 = createXMLHttpRequest(dummyFunction);

	// 現在のPHPSESSIDを調査
	phpSessId = getCookie('PHPSESSID');

	// 現在のWindowNameを調査
	windowName = window.name;
	ret = windowName.match(/^OPTIMASID/);
	// オリジナルのNameでなければ初回表示と判断
	if (ret != 'OPTIMASID') {


		/****  2007.02.14 K.Takashima Delete ***************
		// WindowNameを生成してセットする
		key = sha1Encode(String(Math.random() * 10000));
		if (key.match(/[^a-zA-Z0-9]/)) {
			key = sha1Encode(String(Math.random() * 10000));
		}
		window.name = "OPTIMASID" + key;
		****  2007.02.14 K.Takashima Delete End ***********/


		/****  2007.02.14 K.Takashima START  **************/
		// WindowNameを生成してセットする
		var date = new Date();
		var timestamp = date.getTime();

		var requestObj = createXMLHttpRequest(dummyFunction);
		if (requestObj == null) {
			alert('ActiveXObjectが取得できません。\nパソコンのリソースが不足しています!!\n\n他のアプリケーションを終了するか\n又は、パソコンを再起動して下さい。');
			location.href = realPath + 'logout.php';
		}

		requestObj.open('GET', realPath + 'common/init_new_window.php?OLD_ID=' + phpSessId + '&token=' + timestamp, false);
		requestObj.send(null);

		if (requestObj.status < 200 || requestObj.status >= 300) {
			throw new Error(requestObj.status, requestObj.statusText);
		}
		var responseText = requestObj.responseText;

		eval('tmpWindowName=' + responseText);
		windowName = tmpWindowName;
		window.name = windowName;
		/****  2007.02.14 K.Takashima END  **************/


		// 現在使用しているデータを新セッションの領域にコピーする
		postData = 'MODE=new' + '&' + 'NEW_ID=' + window.name  + '&' + 'OLD_ID=' + phpSessId;
		httpObj1.open('GET', realPath + 'common/copy_session_data.php?' + postData, false);
		httpObj1.send(null);

		// PHPSESSIDがオリジナルのSIDであれば他ウィンドウのデータを上書きしたと判断
		ret = phpSessId.match(/^OPTIMASID/);
		if (ret == 'OPTIMASID') {
			// 上書きしたデータをリカバリするプログラムを起動する
			postData = 'TARGET_ID=' + phpSessId;
			httpObj2.open('GET', realPath + 'common/recovery_session_data.php?' + postData, false);
			httpObj2.send(null);
		}
		newWindowFlag = 't';
	}

	/* 2006.12.28 通常遷移時のセッション情報退避を解除 *****
	// 通常遷移の場合
	else {
		// 現在使用しているデータを退避するプログラムを起動する
		postData = 'MODE=normal' + '&' + 'CRR_ID=' + phpSessId;
		httpObj3.open('GET', realPath + 'common/copy_session_data.php?' + postData, false);
		httpObj3.send(null);
	}
	*******************************************************/

	httpObj1 = null;
	httpObj2 = null;
	httpObj3 = null;

	// 現在のスクリプト名をクッキーにセットする
	selfName = document.selfName.self.value;
	setCookie('SELF_NAME', selfName);

	// ラッピングを外す
	if (document.getElementById("loadingBox") != null) {
		document.getElementById("loadingBox").style.display = "none";
	}
}

/**
 * WindowNameをPHPSESSIDに上書きする
 */
function setSessionId() {

    if (window.navigator.isWinIE == true) {
        var tmp = location.href;
        var ret = tmp.match(/investigation_search_result\.php$|monthly_analysis\.php$|cust_search_result\.php$|order_search_result\.php$/);
        if (ret != 'investigation_search_result.php' && ret != 'monthly_analysis.php' && ret != 'cust_search_result.php' && ret != 'order_search_result.php') {
        	if (document.getElementById("loadingBox") != null) {
        		document.getElementById("loadingBox").style.display = "block";
        	}
        }
    }

	var realPath = getRealPath();

	setCookie('PHPSESSID', window.name);
	setCookie('SELF_NAME', selfName);
	setCookie('NEW_WINDOW', newWindowFlag);
	setCookie('RELOAD', '');

    sig = null;
    reloadFlg = null;
    winName = null;
    tmpRealPath = null;
    tmpSelfPath = null;
    tmpRealPath = null;
    tmpSelfPath = null;
    onLoded_flg1 = null;
    onLoded_flg2 = null;
    selfName = null;
    newWindowFlag = null;
    window.navigator.isWinIE   = null;
    window.navigator.isMacIE   = null;
    window.navigator.isMozilla = null;
    window.navigator.isOpera   = null;
    window.navigator.isSafari  = null;
    window.navigator.isUnknown = null;
}

/**
 * XMLhttpRequest用のコールバック関数
 */
function dummyFunction() {
	return;
}

/**
 * 正確な絶対パスを取得する
 */
function getRealPath() {
  return getCookie('REAL_ROOT');
}

/**
 * ドキュメント初期化
 */
window.addOnLoadHandler(enableTracer);	//  開発用簡易トレース

window.addOnLoadHandler(checkWindowName);
window.addOnLoadHandler(enableSubmitOnce);

