//
// $Id: aws.js,v 1.37 2010/04/18 15:12:37 zetaka Exp $
// 
var BaseURL="http://www.netaro.info/";
//var BaseURL='http://localhost/';
var cgiURL=BaseURL+'~zetaka/cgi-bin/xaws/';
var initURL=cgiURL+"sendawsdata.cgi";
var verifyURL=cgiURL+"verify.cgi";

// --- global variables
var imgSet=null;
var stageNo=-1;
var sessionId=-1;
var ansAry=null;
var usrName=null;

// --- variables for XMLHttpRequest
var timeout_sec=6;
var timerID;
var httpReq=null;

// ----
// 認証結果を受け取り，画面に表示する関数
function showResult() {
	var resStr='';

	if (4==httpReq.readyState) {
		clearInterval(timerID);
		if (200==httpReq.status) {
			// CGIの結果をXMLとして受け取る
			var resdat=httpReq.responseXML;

			// 認証結果の取得 (サーバから受け取る)
			var res=resdat.documentElement.getElementsByTagName('RESULT');
			if (1!=res.length) alert("wrong response!");
			var authResult=res[0].firstChild.nodeValue; // RESULTタグにて返される

			// 値はtrue or falseのはず
			resStr='<div class="resblock">';
			if ('true' == authResult) {
				resStr+='<div class="authresstr">Authentication succeeds.</div>';
				resStr+='<div class="resimg"><img src="./maru.png" /></div>';
			} else {
				resStr+='<div class="authresstr">Authentication failed.</div>';
				resStr+='<div class="resimg"><img src="./batu.png" /></div>';
			}
			resStr+='</div>';

			resStr+='<div>';
			resStr+='Push button if you try authentication again.<div>';
			resStr+='<div class="btns"><input type="button" value="Retry" onclick="location.reload(true)" /></div>';
			resStr+='</div>';
		} else {
			alert(httpReq.status+' '+httpReq.statusText);
			resStr="Verifying your answer...";
		}
	}

	document.getElementById('authblock').innerHTML=resStr;
}

// ----
// 認証結果を問い合わせる関数
function getResultOfAuth() {
	// make POST data
	var pdat='sid='+encodeURIComponent(sessionId);
	pdat+='&uas='+encodeURIComponent(ansAry.join(','));

	ajaxPostReq(verifyURL, showResult, pdat) ;
}

// ----
// 入力状況を示すinput field用HTMLを生成する関数
function htmlForInputStateFeedback(numofstg) {
	var resHTML='';

	resHTML+='<div>';
	resHTML+='<input type="password" value="';
	for (var x=0; x<numofstg; ++x) {
		resHTML+='*';
	}
	resHTML+='" size="4" maxlength="4" />';
	resHTML+='</div>';

	return resHTML;
}

// ----
// 回答を変数に格納する関数
function storeAns(uchoice) {
	ansAry[stageNo-1]=uchoice;
	document.getElementById('stg'+stageNo).style.display='none';
	++stageNo;
	if (stageNo < 5) {
		document.getElementById('stg'+stageNo).style.display='block';
	} else {
		// 回答終了時の処理
		// document.getElementById('authblock').innerHTML=ansAry.join(',')+' <='+ansAry.length;
		getResultOfAuth();
	}
}

// ----
// 認証画面のHTMLを生成する関数
function constructHTMLforAuth() {
	var html='';

	for (var stg=0; stg < imgSet.length; ++stg) {
		var stgImgs=imgSet[stg];

		html+='<div class="stage" id="stg'+(1+stg)+'">';
		html+=htmlForInputStateFeedback(stg);
		for (var nimg=0; nimg < stgImgs.length-1; ++nimg) {
			if (0==(nimg%3)) { html+='<br/>'; }
			html+='<img class="authimg" src="'+stgImgs[nimg]+'" onclick="storeAns('+(1+nimg)+')" />';
		}

		// no pass-image回答用のHTML
		html+='<div>';
		html+='<img class="nopassimg" src="'+stgImgs[stgImgs.length-1]+'" onclick="storeAns(0)" />';
		html+='</div>';

		html+='</div>';
	}

	document.getElementById('authblock').innerHTML=html;
}

// ----
// ユーザ名がなく，ステージ情報がなかった場合のHTML出力
function htmlForNoUser() {
	var htmlstr='';

	htmlstr+='<div id="no-usr-alert1">';
	htmlstr+='No such user.';
	htmlstr+='<div id="no-usr-alert2">';
	htmlstr+='<input type="button" value="Retry" onclick="location.reload(true);" />';
	htmlstr+='</div>';
	htmlstr+='</div>';

	document.getElementById('unblock').style.display='none';
	document.getElementById('authblock').innerHTML=htmlstr;
}

// ----
function initAwaseE() {
	stageNo=1;
	ansAry=new Array(4);

	var unblock=document.getElementById('unblock');
	unblock.style.display='none';
}

// ----
// 
function getAuthData() {
	if (4==httpReq.readyState) {
		//
		clearInterval(timerID);
		if (200==httpReq.status) {
			// CGIの結果をXMLとして受け取る
			var awsdat=httpReq.responseXML;

			// STAGEタグを取得し，その数を確認する
			var stgs=awsdat.documentElement.getElementsByTagName('STAGE');
			if (stgs.length < 4) {
				htmlForNoUser();
				return;
			} 

			if (4!=stgs.length) alert("# of stages is wrong=> "+stgs.length);
			imgSet=new Array(stgs.length); // データ保存用の配列を確保

			// 各ステージについて処理
			for (var i=0; i<stgs.length; ++i) {
				var imgs=stgs[i].getElementsByTagName('IMAGE');
				if (10!=imgs.length) alert("# of images is wrong=> "+imgs.length);
				imgSet[i]=new Array(imgs.length);

				// 各ステージ内の画像について処理
				for (var j=0; j<imgs.length; ++j) {
					imgSet[i][j]=imgs[j].childNodes[0].nodeValue;
					// if (j==0) alert(imgSet[i][j]);
				}
			}

			// Session IDの取得
			var ssnid=awsdat.documentElement.getElementsByTagName('SESSIONID');
			if (1!=ssnid.length) alert("wrong session ID=> "+ssnid.length);
			sessionId=ssnid[0].childNodes[0].nodeValue;

			// HTMLの生成
			constructHTMLforAuth();
			initAwaseE();
		}
	} else {
		document.getElementById('authblock').innerHTML="Wait a moment...";
	}
}

// ---
// 認証開始処理
// ユーザ名をサーバに送り，認証に必要な画面データとSession IDを受け取る
//
function startAuth() {
	// 入力されたユーザ名を取得する
	var unfd=document.getElementById('unm');
	if (!unfd) { alert('Error: Wrong html document.'); return; }
	usrName=unfd.value;
	if (!usrName || usrName.length < 1) { 
		alert('Error: You must enter user name.'); 
		return true;
	}

	// サーバに認証画面生成に必要なデータを要求
	// ajaxGetReq(initURL, getAuthData);
	var pdat='unm='+encodeURIComponent(usrName);
	ajaxPostReq(initURL, getAuthData, pdat);

	return false;
}

// ----
// set initial listeners...
function setInitListener() {
	var tfd=document.getElementById('unm');
	tfd.value='';
	tfd.onfocus=function(){ this.style.backgroundColor='#ffff99'; };
	tfd.onblur=function(){ this.style.backgroundColor='white'; };
	tfd.focus();

	var iptform=document.forms[0];
	if (!iptform) { alert('No input form!'); return; }
	iptform.onsubmit=startAuth;
}

// -------------------------------------------------------------------------
// ---- Common function ----------------------------------------------------
// -------------------------------------------------------------------------
function addListener(elem, eventType, func, cap) {
	if (elem.addEventListener)  {
		elem.addEventListener(eventType, func, cap);
	} else {
		alert('Your web browser does not support necesarry functions.');
		return false;
	}
}

// ----
function timeoutCheck() {
	timeout_sec--;
	if (timeout_sec < 0) {
		document.getElementById('authblock').innerHTML="timeout your request!";
		// stop timer
		clearInterval(timerID);
		// abort HTTP request
		httpReq.abort();
		// show status
		alert('Timeout your request.');
		timeout_sec=6;
		return false;
	}
}

// ----
function genHttpReq() {
	try {
		if (window.XMLHttpRequest) {
			httpReq=new XMLHttpRequest();
		} else if (window.ActiveXObject) {
			httpReq=new ActiveXObject("Microsoft.XMLHTTP");
		} else {
			httpReq=false;
		}
	} catch (e) {
		httpReq=null;
	}
}

// ----
function ajaxPostReq(url, funcref, postdata) {
	genHttpReq();

	if (httpReq) {
		// postdataはURIencodeされていると仮定する
		timerID=setInterval('timeoutCheck()', 1000);
		httpReq.open("POST", url, true); // Asynchronous communication
		httpReq.setRequestHeader("content-type", "application/x-www-form-urlencoded;charset=UTF-8");
		httpReq.onreadystatechange=funcref;
		httpReq.send(postdata);
	} else {
		alert('failed to get xmlhttprequest');
	}
}

// ----
function ajaxGetReq(url, funcref) {
	genHttpReq();

	if (httpReq) {
		timerID=setInterval('timeoutCheck()', 1000);
		httpReq.open("GET", url, true);
		httpReq.onreadystatechange=funcref;
		httpReq.send('');
	} else {
		alert('failed to get xmlhttprequest');
	}
}

// -------------------------------------------------------------------------
// start function.
addListener(window, 'load', setInitListener, false);

//
// ends here 
//

