/* ******************** the net Object/namespace from Dave Crane "Ajax in Action" ****************************************** */

var net=new Object();
net.READY_STATE_UNINITIALIZED=0;
net.READY_STATE_LOADING=1;
net.READY_STATE_LOADED=2;
net.READY_STATE_INTERACTIVE=3;
net.READY_STATE_COMPLETE=4;

net.ContentLoader=function(url,onload,onerror,params,HttpMethod){

	if (!HttpMethod) {
		HttpMethod = "GET";
	}
	if (!params) {
		params = null;
	}
	else {
		if (HttpMethod == 'GET') {
			url += ((url.indexOf('?') > 0) ? '&' : '?') + params;
			params = null;
		}
	}
	this.url = url;
	this.req = null;
	this.params = params;
	this.HttpMethod = HttpMethod;
	this.onload = onload;
	this.onerror = (onerror) ? onerror : this.defaultError;
	this.loadSomeInfo(url, params, HttpMethod);

}
net.ContentLoader.prototype={
    loadSomeInfo:function(url,params,HttpMethod){
		if (typeof jQuery !== 'undefined' && jQuery === $ && typeof $.expando === 'string' && $.expando.substr(0, 6) === 'jQuery') {
			var loader = this;
			$.ajax({
				url: url,
				cache: false,
				type: HttpMethod,
				data: params,
				beforeSend: function(jqXHR, settings) {
					loader.req = jqXHR;
				},
				success: function(data, textStatus, jqXHR){
					loader.onload.call(loader);
				},
				error: function(jqXHR, textStatus, errorThrown){
				    loader.onerror.call(loader);
				}
			});
		}
		else {
			if (window.XMLHttpRequest) {
				this.req = new XMLHttpRequest();
			}
			if (this.req) {
				try {
					var loader = this;
					this.req.open(HttpMethod, url, true);
					this.req.onreadystatechange = function(){
						if (loader.onReadyState.call) {
							loader.onReadyState.call(loader);
						}
						else 
							loader.onReadyState(loader);
					}
					if (HttpMethod == 'POST') {
						this.req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
					}
					this.req.send(params);
				} 
				catch (err) {
					if (this.onerror.call) {
						this.onerror.call(this);
					}
					this.onerror(this);
				}
			}
		}
    },
    onReadyState:function(){
         var req=this.req;
         var ready=req.readyState;
         if (ready==net.READY_STATE_COMPLETE){
             var httpStatus=0;
             try {
                 httpStatus=req.status;
             } catch (err){
                 alert("error fetching data!"
                       +"\n\nreadyState:"+this.req.readyState
                       +"\nheaders: "+this.req.getAllResponseHeaders());
                 return;
             }
             if (httpStatus==200 || httpStatus==0){
                 if (this.onload.call) {
                     this.onload.call(this);
                 }
                 else this.onload(this);
             }else{
                 if (this.onerror.call) {
                     this.onerror.call(this);
                 }
                 this.onerror(this);
             }
         }
    },
    defaultError:function(){
         alert("error fetching data!"
               +"\n\nreadyState:"+this.req.readyState
               +"\nheaders: "+this.req.getAllResponseHeaders());
    }
}

/* *************    L o g i n S u b m i t    *************************/
//Next var's must be initialized globally outside this script
//var loginuserempty = ""; // "user field empty"
//var logincertURL = "";   // full URL for certified login
//var loginuncertURL = ""; // full URL for uncertified login
//var mobLoginStartError = ""; // "cannot start the XMLHTTPRequest"
//var mobLoginStartMessage = ""; // "starting Mobile ID login"
//var mobLoginWaitingMessage = ""; // "waiting for Mobile ID login accept"
//var mobLoginOKMessage = ""; // "waiting for Mobile ID login accept"
//var mobLoginTimeoutMessage=""; // waitung answer from server returned is timed out
//var koodinumbritext = "";        // "the Magical number:"
//var reqtimes=[70,20,10,10,10,10]; // polling policy (seconds between polls)
//var moberroricon = "img ..."; // erroricon element content

var mobLoginStartError = ""; // "cannot start the XMLHTTPRequest"
var mobLoginStartMessage = ""; // "starting Mobile ID login"
var mobLoginWaitingMessage = ""; // "waiting for Mobile ID login accept"
var mobLoginOKMessage = ""; // "waiting for Mobile ID login accept"
var mobLoginTimeoutMessage=""; // waitung answer from server returned is timed out

var ldrMob = null; // object for asynchronous communication to server
var intervalMob=0; // total time in seconds
var countMobind=0; // index to polling policy array (seconds between polls)
var countMob=0;    // current pollintervalMob countMober in seconds
var intervalMobID=0; // timer's ID for clearing it
var stopitMob = false;   // to block entering LoginSubmit twice
var mobSubmitType; 
var isActive = true;

function mobDoServerResponse(){}
/***************************   m o b F o r m M o b D i s a b l e   *******************/
function mobFormMobDisable(ifdisabled){
 stopitMob = ifdisabled;
 if(!ifdisabled){
     document.timeoutvorm.pwd.value="";
     document.timeoutvorm.code.value="";
 }
}

/***************************   m o b S e t M o b M e s s a g e   *******************/
function mobSetMobMessage(messtext,iferror){
 var mdiv;
 if(mobSubmitType=='SMARTID') mdiv=document.getElementById("smartidmessage");
 else mdiv=document.getElementById("mobmessage");
 if(mdiv){
     mdiv.innerHTML=(iferror?("<"+moberroricon+">"):"")+messtext.replace(/#/g,"<br/>");
     if(mdiv.className){mdiv.className=(iferror?"mobh4err":"mobh4");}
 }
}

/***************************   m o b D o S e r v e r E r r o r    **********/
function mobDoServerError(){
if(intervalMobID){window.clearInterval(intervalMobID);}
isActive=false;
intervalMobID=0;
mobFormMobDisable(false);
mobSetMobMessage(LoginStartError,true);
stopitMob=0;
}

/*************************   m o b T e s t R e s p o n s e     ***************/
function mobTestResponse(){
 countMob+=1;
 intervalMob+=1;
 if(countMob>reqtimes[countMobind]&&ldrMob===null&&isActive){
     if(intervalMobID){window.clearInterval(intervalMobID);}
     isActive=false;
     var anurl = document.timeoutvorm.action;
     var parameters = "act=MOBLOGINTEST&sasskey="+document.timeoutvorm.sesskey.value+"&lang="+document.timeoutvorm.lang.value;
     parameters += "&req=" + document.timeoutvorm.code.value;
     countMob=0;
     countMobind++;
     if(countMobind==reqtimes.length){
         mobFormMobDisable(false);
         mobSetMobMessage(LoginTimeoutMessage);
         return;
     }
     ldrMob=new net.ContentLoader(anurl,mobDoServerResponse,mobDoServerError,parameters,"GET");
     if (!ldrMob||!ldrMob.req) {
         mobDoServerError();
         return;
     }
     intervalMobID=window.setInterval(mobTestResponse,1000);
     isActive=true;
 }
 else{
     mobSetMobMessage(LoginWaitingMessage+" "+intervalMob);
 }
}

/***************************   m o b D o S e r v e r R e s p o n s e    **********/
function mobDoServerResponse(){
if(isActive){
 if(intervalMobID){window.clearInterval(intervalMobID);}
 isActive=false;
 intervalMobID=0;
 var mdiv=null;
 var vastus = ldrMob.req.responseText;
 // var mobSubmitType = document.sessionData.cert.value; 

 if(vastus.substr(0,6)=="ERROR:"){
     mobSetMobMessage(vastus.substr(6),true);
     mobFormMobDisable(false);
 }
 else if(vastus.substr(0,3)=="OK:") {
     mobSetMobMessage(LoginOKMessage);
     if(mobSubmitType=='SMARTID') mdiv=document.getElementById("smartidcode");
     else mdiv=document.getElementById("midcode");
     if(mdiv) {mdiv.innerHTML="";}
     document.timeoutvorm.pwd.value=mobSubmitType;
	 
	if(typeof(ajaxTimeoutCallback) =='function' ) 
        ajaxTimeoutCallback(); 
    else { 
        var cTempCallback='ajaxcallback'; 
        var cParams=''; 
        for(var i = 0; i < document.timeoutvorm.length; i++) { 
            if( document.timeoutvorm.elements[i].name !='sesskey' && document.timeoutvorm.elements[i].name !='' && document.timeoutvorm.elements[i].value !='')  
               cParams = cParams + document.timeoutvorm.elements[i].name + '=' + document.timeoutvorm.elements[i].value + '#'; 
            if (document.timeoutvorm.elements[i].name =='act') cTempCallback+='_'+document.timeoutvorm.elements[i].value; 
        } 
        if (typeof(window[cTempCallback])=='function') { 
            Unet_ajaxget('json', window[cTempCallback],  cParams ); 
			window.parent.tb_remove();
            return false; 
        } else if(document.timeoutvorm.ajax_target&&document.timeoutvorm.ajax_target.value.length>0) { 
            Unet_ajaxget(document.timeoutvorm.ajax_target.value, '',  cParams ); 
			window.parent.tb_remove();
            return false; 
        } 
		else {
			document.timeoutvorm.submit();
		}
     } 

     return;
 }
 else if(vastus.substr(0,4)=="REQ:"){
     document.timeoutvorm.code.value=vastus;
     var lastpos = -1;
     var newpos = 0;
     while((newpos=vastus.indexOf(":",lastpos+1))>0){lastpos=newpos;}
     if(mobSubmitType=='SMARTID') mdiv=document.getElementById("smartidcode");
     else mdiv=document.getElementById("midcode");
     if(mdiv){mdiv.innerHTML='<span class="text">' + koodinumbritext + '</span><span class="code">' + vastus.substr(lastpos+1) + '</span>';}
     mobSetMobMessage(LoginWaitingMessage);
     intervalMobID=window.setInterval(mobTestResponse,1000);
     isActive=true;
 }
 else {/* alert("arusaamatu vastus="+vastus+ldrMob+ldrMob.req);*/}
 ldrMob=null;
} 
}

/***************************   T i m e o u t S u b m i t   *******************/
function TimeoutSubmit(){
 if (stopitMob) {
     return false;
 }
 mobSubmitType = document.sessionData.cert.value; 
 setMessages(mobSubmitType);
 var mdiv;
 if(mobSubmitType=='SMARTID') mdiv=document.getElementById("smartidcode");
 else mdiv=document.getElementById("midcode");
 if (mdiv){mdiv.innerHTML = '<span class="label">' + LoginStartMessage + '</span>';}
 if(mobSubmitType=='SMARTID') mdiv=document.getElementById("smartidmessage");
 else mdiv=document.getElementById("mobmessage");
 if (mdiv){mdiv.innerHTML = "";}
 if(mobSubmitType=='SMARTID') mdiv=document.getElementById("smartidkinnitan");
 else mdiv=document.getElementById("mobkinnitan");
 if (mdiv&&mdiv.style&&mdiv.style.display)
     { mdiv.style.display="";}
 mdiv=document.getElementById("kinnitanklahviblokk");
 if (mdiv){mdiv.style.display="none";}
 mdiv=document.getElementById("timeoutpage");
 if (mdiv&&mdiv.style&&mdiv.style.display)
     { mdiv.style.display="none";}
 mobFormMobDisable(true);
 mobSetMobMessage(LoginStartMessage);
 countMobind=0;
 intervalMob=0;
 countMob=0;
 var parameters = "act=MOBLOGINSTART&sasskey="+document.timeoutvorm.sesskey.value+"&lang="+document.timeoutvorm.lang.value+"&mobdevice="+mobSubmitType;
 ldrMob=new net.ContentLoader(document.timeoutvorm.action,mobDoServerResponse,mobDoServerError,parameters,"GET");
 if (!ldrMob||!ldrMob.req) {
     mobDoServerError();
     return;
 }
 intervalMobID=window.setInterval(mobTestResponse,1000);
 isActive=true;
}

/***************************   m o b S t o p M o b W a i t   *******************/
function mobStopMobWait(){
 mobFormMobDisable(false);
 if(intervalMobID){window.clearInterval(intervalMobID);}
 isActive=false;
 var mdiv=document.getElementById("mobkinnitan");
 mdiv.style.display="none";
 mdiv=document.getElementById("smartidkinnitan");
 mdiv.style.display="none";
 mdiv=document.getElementById("kinnitanklahviblokk");
 if (mdiv){mdiv.style.display="";}
 mdiv=document.getElementById("timeoutpage");
 mdiv.style.display="";
// alert(mdiv.style.display);
}
/***************************   s e t M e s s a g e s    **********/

function setMessages(messType) {
	if(messType && messType=="SMARTID") {
		LoginStartError = smartLoginStartError;
		LoginStartMessage = smartLoginStartMessage;
		LoginWaitingMessage = smartLoginWaitingMessage;
		LoginOKMessage = smartLoginOKMessage;
		LoginTimeoutMessage = smartLoginTimeoutMessage;
	}
	else {
		LoginStartError = mobLoginStartError;
		LoginStartMessage = mobLoginStartMessage;
		LoginWaitingMessage = mobLoginWaitingMessage;
		LoginOKMessage = mobLoginOKMessage;
		LoginTimeoutMessage = mobLoginTimeoutMessage;
	}
}
