var goPopUp = {
    iInitTime: 0,
    iPopUpStartTime: 300000,
    iSessTimeLeft: 0,
    iShowStartTime: 300000,
    iTextTimeInterval: 1000,
    oBackGround: null,
    osetInterval: null,
    oPopUp1: null,
    oPopUp2: null,
    oPopUp3: null,
    oPopupTimer: null,
    sDataXml: "",
    sOpacity: 0.0,
    sTmpContent: null,
    sWinTitle: "",
    sAuthType: "",
    sTimeOutMsg: "",
    iDelay: 12,
    iTimeout: 80,
    iInterval: 2,
    sImgPath: "",
    sLang: "",
    lAppletDeactivate: false,
    iAppletDeactivateTime: 10000,
    lShowEnd: false,
    lShowTimer: false,
    lPopupAvailable: false,
    oSign: null,
    smartIdPinger: null,
    lWindowActive: true,
    iPingerPingFactor: 1.1,
    iPingerPingInitialInterval: 2000,
    iPingerPingTimeout: 120000,
    iPingerPingDelay: 0,
    selfUrl: "",
    
    init: function() {
        try {
            
            this.iInitTime = new Date().getTime();
            this.set_InitTime(this.iInitTime);
            this.sessTimeSync();
            if (this.iSessTimeLeft == "?") return;
            this.oPopupTimer = document.getElementById("popup_top1_timer");
            this.oBackGround = document.getElementById("popup_back");
            this.oPopUp1 = document.getElementById("popup_top1");
            this.oPopUp2 = document.getElementById("popup_top2");
            this.oPopUp3 = document.getElementById("popup_top3");
            this.osetInterval = setInterval("goPopUp.rotate_objects();", this.iTextTimeInterval);
            this.lShowEnd = false;
            this.lShowTimer = false;
            this.lPopupAvailable = false;
            this.clearErrors();
        } catch(e) {
            try {
                this.disable();
            } catch(err) {
            }
        }
    },
    clearErrors: function(){
    	$jq("#popup_top2_error").html("");
        $jq("#popup_top2_error_hold").hide();
        $jq("#popup_top3_error").html("");
        $jq("#popup_top3_error_hold").hide();
    },
    sessTimeSync: function() {
        var iTimeLeft;
        var iInitTime;
        iTimeLeft = $jq.IbCookie("SEBVBTimeLeft");
        iInitTime = $jq.IbCookie("SEBVBInitTime");
        this.iSessTimeLeft = "?";
        if (iTimeLeft == null || isNaN(iTimeLeft) || Number(iTimeLeft) < 0 || iInitTime == null || isNaN(iInitTime) || Number(iInitTime) < 0) {
            if (this.osetInterval) clearInterval(this.osetInterval);
            return;
        }
        this.iSessTimeLeft = iTimeLeft;
        this.iInitTime = iInitTime;
    },

    set_SessTimeLeft: function(iTimeLeft) {
        $jq.IbCookie("SEBVBTimeLeft", iTimeLeft);
    },

    set_InitTime: function(iInitTime) {
        $jq.IbCookie("SEBVBInitTime", iInitTime);
    },

    rotate_objects: function() {
        try {
            
        	this.sessTimeSync();
            if (this.iSessTimeLeft == "?") {
                this.disable();
                return;
            }

            var iTimeLeft = this.iSessTimeLeft - (new Date().getTime() - this.iInitTime);

            if (iTimeLeft <= 0) {
                //clearInterval(this.osetInterval); this may be dangerous
                iTimeLeft = 0;
                if (iTimeLeft != this.iSessTimeLeft) {
                    this.iSessTimeLeft = 0;
                    this.set_SessTimeLeft(this.iSessTimeLeft);
                }
            }

            var sTimeShow = this.rotate_time(iTimeLeft);

            
            this.rotate_title(iTimeLeft, sTimeShow);

            //rotate popuptext
            this.oPopupTimer.innerHTML = sTimeShow;

            //rotate popup
            this.rotate_toggle(iTimeLeft);
        } catch(e) {
            try {
                this.disable();
            } catch(err) {
            }
        }
    },

    rotate_time: function(iTimeLeft) {
        var sTimeShow;
        var dDate = new Date(0, 0, 1, 0, 0, 0, iTimeLeft);
        var dMinutes = dDate.getMinutes();
        var dSeconds = dDate.getSeconds();
        if (dMinutes <= 9) {
            sTimeShow = "0";
        } else {
            sTimeShow = "";
        }
        sTimeShow += dMinutes + ":";
        if (dSeconds <= 9) {
            sTimeShow += "0" + dSeconds;
        } else {
            sTimeShow += dSeconds;
        }
        return sTimeShow;
    },

    rotate_title: function(iTimeLeft, sTimeShow) {
        var sTitle;
        if (iTimeLeft < this.iShowStartTime) {
            sTitle = sTimeShow + " | " + this.sWinTitle;
        } else {
            sTitle = this.sWinTitle;
        }
        if (document.title != sTitle) document.title = sTitle;
        try {
            if (top.document.title != sTitle) top.document.title = sTitle;
        } catch(e) {
        }
    },

    rotate_toggle: function(iTimeLeft) {

    	if ( iTimeLeft == 0) { /* session ended */
    		if (this.lShowEnd == false){
    			this.lShowEnd = true;
    			this.sessman("&act=SESSREFRESH&task=force_end"); /* post to BE */
    		}
    	} else if (iTimeLeft <= this.iPopUpStartTime) {
    		if (this.lShowTimer == false){
    			this.lShowTimer = true;
    			this.show_timer();
    		}
    	} else {
    		if (this.lPopupAvailable == true){
    			this.hide();
    			this.lShowEnd = false;
    			this.lShowTimer = false;
    		}
    	}
    	
    },
    
    toggle: function(lshow, sta) {
        if (lshow == "yes") {
            if (this.oPopUp3.style.display == "none") {
                if (this.iSessTimeLeft == 0) {
                    if (sta == 0 || sta == 99999) {
                    	this.show_end();
                    } else {
                        this.show_login();
                    }
                } else {
                    this.show_timer();
                }
            }
        } else {
            this.hide();
        }
    },

    show_login: function() {
    	tb_show('', '#TB_inline?width=600&amp;inlineId=popup_top3&amp;modal=true&amp;autoscale=1');
    	tb_scale();
    	this.lPopupAvailable = true;
    },

    show_end: function() {
    	if(this.lPopupAvailable) {
    		this.hide();
    	}    	
    	tb_show('', '#TB_inline?width=600&amp;inlineId=popup_top2&amp;modal=true&amp;autoscale=1');
    	tb_scale();
    	this.lPopupAvailable = true;
    },

    show_timer: function() {
    	tb_show('', '#TB_inline?height=150&amp;width=600&amp;inlineId=popup_top1&amp;modal=true&amp;autoscale=0');
    	this.lPopupAvailable = true;
    },

    hide: function() {
	    tb_remove();
	    this.lPopupAvailable = false;
    },

    toggle_wait: function(phase) {
        if (phase == "show") {
            showLoader("", 1);
            this.lPopupAvailable = true;
        } else if (phase == "hide") {
            hideLoader();
            this.lPopupAvailable = false;
        }
    	
    },

    get_visible_popup: function() {
        var popup_array = new Array(this.oPopUp1, this.oPopUp2, this.oPopUp3);
        var iCnt;

        for (iCnt = 0; iCnt <= popup_array.length - 1; iCnt++) {
            if (popup_array[iCnt] && popup_array[iCnt].style.display == "block") {
                return popup_array[iCnt];
            }
        }
        return null;
    },

    sessman: function(act1) {
        try {
            var firstpar = "sesskey=" + encodeURIComponent(document.popupform.sesskey.value);
            var authtype = "&auth_type=" + this.sAuthType;
            var fromact = "";
            if (typeof(document.popupform.fromact) != "undefined") {
                fromact = "&from_act=" + document.popupform.fromact.value;
            }
            var allpars = firstpar + act1 + this.get_login_params() + authtype + fromact;
            goPopUp.sessman2(allpars);
            
        } catch(e) {
            try {
                this.disable();
            } catch(err) {
        }
        }
    },

    sessman2: function(params) {
    	if (this.lWindowActive) {
    		showLoader("", 1);
    		this.lPopupAvailable = true;
    	}
        var ths = this;
        $jq.ajax({
            type: 'POST',
            url: this.selfUrl,
            data: params,
            success: function(data, status, xhr){ths.sess_procresponse(data, status, xhr);},
            async:true
        });
        
    },

    sess_procresponse: function(data, status, xhr) {
    	
    	var ReqSta;
    	var contentType = xhr.getResponseHeader("content-type") || "";
    	
    	try {
    		
    		if(contentType.indexOf('html') > -1) {    			
    			this.cbErr("", "Server error");	
    		} else {    		
	    		sDataXML = data;
	    		ReqSta = data.sta;
	    		if (ReqSta == 0) {
					this.restart();
				} else if (ReqSta == 99999) {
					this.show_end();
				} else if (ReqSta == 9999) {
					this.cbErr("", data.error_message);
				} else if (ReqSta > 0) {
					this.clear_login_params();
					this.draw_popup3();
					if (this.iSessTimeLeft != 0)
						this.set_SessTimeLeft(0);
				} else {
					throw "Got " + ReqSta + " reqsta";
				}
    		}
    	}
    	catch (e){
    		try {
    			//TODO
    		}
    		catch (err){
    		}
    	}
        sDataXML = "";
    },
    restart: function() {
        this.sessTimeSync();
        this.disable();
        if (this.iSessTimeLeft == "?") return;
        this.init();
    },

    get_login_params: function() {
        var paramlist = ["popup3_user", "popup3_code", "popup3_pwd", "popup3_action"];
        var iCnt;
        var sTmpEl;
        var paramline = "";
        for (iCnt=0; iCnt<=paramlist.length - 1; iCnt++) {
            sTmpEl = document.getElementById(paramlist[iCnt]);
            if (sTmpEl) {
                paramline = paramline + "&" + sTmpEl.name + "=" + encodeURIComponent(sTmpEl.value);
            }
        }
        return paramline;
    },

    clear_login_params: function() {
        var paramlist = ["popup3_code", "popup3_pwd"];
        var iCnt;
        var sTmpEl;
        var paramline = "";
        for (iCnt=0; iCnt<=paramlist.length - 1; iCnt++) {
            sTmpEl = document.getElementById(paramlist[iCnt]);
            if (sTmpEl) {
                sTmpEl.value = '';
            }
        }
    },

    draw_popup3: function() {
        
        switch(this.sAuthType){
            case 'IDMOB':
//                this.draw_popup3_msign();
                this.draw_popup3_smartid();
            break;
            case 'SMARTID':
                this.draw_popup3_smartid();
            break;
            case 'MOBILESCA':
                this.draw_popup3_smartid();
            break;
            default:
                this.draw_popup3_default();
            break;
        }
    },
    
    draw_popup3_smartid: function() {
        var LoginTable = document.getElementById("popup_top3_login");
        var ErrorTr = document.getElementById("popup_top3_error");
        var CodeField = document.getElementById("popup3_code");
        var PswField = document.getElementById("popup3_pwd");
        var ReqSta = this.get_xml_el_val("STA");
        
        var device_status;
        var device_challenge;

        if (this.sAuthType === 'IDMOB') {
        	device_status = "idmob_status";
        	device_challenge = "idmob_chall";
        	PswField.value = "IDMOB";
        } 
        else if (this.sAuthType === 'MOBILESCA') {
        	device_status = "mobilesca_status";
        	device_challenge = "mobilesca_chall";
        	PswField.value = "MOBILESCA";
        }
        else {
        	device_status = "smartid_status";
        	device_challenge = "smartid_chall";
        	PswField.value = "SMARTID";
        }
        var thisobj = this;
        
        if (ReqSta != 404 && ReqSta != 403 && ReqSta != 7036 && ReqSta != 409) {
            
            LoginTable.style.display = "";
            $jq("#pwaittim").html(""); /*reset timer*/
            $jq("#pwaitinfo").show();
            
            
            this.show_login();
            
            function createPinger(selfUrl, req, cb) {
              var chall_received = false;
              
              var pinger = new Pinger({
            	"pingUrl": selfUrl,
                "pingData": {"act":"SESSREFRESH", "task": device_status, "sesskey": document.popupform.sesskey.value, "req": req, "user": document.popupform.user.value },
                "cbError": function(data){
                    console.log("override cbError");
                    if (typeof processError == 'function') { processError(data);} else {alert('Function processError does not exist!')}
                 },
                "cbSuccess": function(data){
                    console.log("override cbSuccess");
                    if (typeof processSuccess == 'function') { processSuccess(data);} else {alert('Function processSuccess does not exist!')}
                },
                "pingFactor": thisobj.iPingerPingFactor,
                "pingInitialInterval": thisobj.iPingerPingInitialInterval,
                "pingTimeout": thisobj.iPingerPingTimeout,
                "pingDelay": thisobj.iPingerPingDelay,
                "autoStart": false
              });
              
              pinger.getStatus = function(data) {
                if (typeof data === "undefined" || typeof data.is_chall_received === "undefined")
                    return "undefined";
                if (data.is_chall_received && !chall_received) {
                    
                    if (data.chall != '') {
                        hideWaiting();
                    	chall_received = true;
                    } 
                	showChallenge(data.chall);
                }
                if ((data.is_chall_received && data.is_confirmed) || data.is_rejected) {
                	if(data.is_rejected) {
                		return "rejected";
                	} else {
                		return "done";
                	}
                } else {
                    return "wait";
                }
              };
              
              return pinger;
            }
            
            function getChallenge() {
            	
            	var requestData = {
            						"act":"SESSREFRESH", 
            						"task": device_challenge, 
            						"sesskey": document.popupform.sesskey.value, 
            						"user": document.popupform.user.value,
            						"auth_type": thisobj.sAuthType
            						};            	
           	
                $.ajax({
                    url: thisobj.selfUrl,
                    type: 'GET',
                    dataType: 'json',
                    data: requestData,
                    success: function success(data, textStatus, jqXhr){
                    	try {
	                    	if(data.sta == 9999) {
	                    		processError(data);
	                    	} else {
	                        	CodeField.value = data.req_str;
//	                        	PswField.value = "SMARTID";
	                            thisobj.smartIdPinger = createPinger(thisobj.selfUrl, data.req);
	                            thisobj.smartIdPinger.startPinger();
	                    	}
                    	} catch (e){ 
                    		processError({"error_message": "Server error"});
                    	}
                    },
                    error: function error(jqXhr, textStatus, String){
                    	processError({"error_message": "Server error"});
                    }
              });
            }
            
            function hideWaiting() {
              $jq(".show-when-waitingchallenge").addClass("hidden");
            }
            function showChallenge(challenge) {
              if (challenge != "")  {
              	$jq(".show-when-waitingconfirmation").removeClass("hidden");
            	$jq("#pchlgn").text(challenge);
              }
              else { 
                  $jq(".show-when-waitingchallenge").removeClass("hidden");
                  $jq(".show-when-waitingconfirmation").addClass("hidden");
              }
              tb_scale();   // repaint popup, to calculate proper popup height   
            }
            
            function processError(data) {
              data.error_message = data.error_message || "";
              if(data.error_message == "timeout") {
            	  thisobj.cbTm();
              } else {
            	  thisobj.cbErr("", data.error_message); 
              }  
            }
            
            function processSuccess(data) {
              if (data.is_confirmed) {
                thisobj.cbOk();
              } else {
                processError(data);
              }
            }
            
            getChallenge();
            
        } else {
            this.show_end();
        }   
    },
    
    draw_popup3_msign: function(){
        var LoginTable = document.getElementById("popup_top3_login");
        var ErrorTr = document.getElementById("popup_top3_error");
        var CodeField = document.getElementById("popup3_code");
        var PswField = document.getElementById("popup3_pwd");
        var ReqSta = this.get_xml_el_val("STA");
        var Chall = this.get_xml_el_val("CHALL");
        var AuthReq = this.get_xml_el_val("req");
        var req_str = this.get_xml_el_val("req_str");
        	
        CodeField.value = req_str;
    	PswField.value = "IDMOB";
        
        var thisobj = this;
        
        if (ReqSta != 404 && ReqSta != 403 && ReqSta != 7036 && ReqSta != 409) {
            
            LoginTable.style.display = "";
            $jq("#pchlgn").html(Chall);
            $jq("#pwaittim").html(""); /*reset timer*/
            $jq("#pwaitinfo").show();
            
            
            this.show_login();
            
            $jq(document).ready(function (){                
            	thisobj.oSign = new Sign({
            		"url"   	: thisobj.selfUrl,
            		"act"   	: "SESSREFRESH",
            		"task"  	: "idmob_status",
            		"sesskey"	: document.popupform.sesskey.value,
                    "req"   	: AuthReq,
                    "cbOk"  	: thisobj.cbOk,
                    "cbTm"  	: thisobj.cbTm,
                    "cbErr" 	: thisobj.cbErr,
                    "par" 		: thisobj,
                    "delay" 	: thisobj.iDelay,
                    "timeout" 	: thisobj.iTimeout,
                    "interval" 	: thisobj.iInterval,
                    "timer" 	: $jq("#pwaittim_mid")
                });
            });
            
        } else {            
            this.show_end();
        }   
        
    },

    cbOk: function(){
        this.sessman("&act=TIME_SESSREFRESH&task=new");
    },
    
    cbErr: function(msg, msgtxt){
        if (msgtxt != '') {
        	$jq("#popup_top2_error").html(msgtxt);
        	$jq("#popup_top2_error_hold").show();
        }
        this.show_end();
    },
    
    cbTm: function(){
        this.cbErr("", this.sTimeOutMsg);
    },
    
    draw_popup3_default: function(){
        var LoginTable = document.getElementById("popup_top3_login");
        var ErrorTr = document.getElementById("popup_top3_error");
        var GeneratorTr = document.getElementById("popup_top3_gen");
        var GeneratorCodeTd = document.getElementById("popup_top3_gen_val");
        var CodeSpan = document.getElementById("popup3_code_holder");
        var CodeInputDes = document.getElementById("popup3_code_des");
        var PwdInput = document.getElementById("popup3_pwd");
        var CodeNo = this.get_xml_el_val("CODENO");
        var GenType = this.get_xml_el_val("GENTYPE");
        var ReqSta = this.get_xml_el_val("STA");
        var Err = this.get_xml_el_val("error_message"); //show error message
        
        if (Err != "" ){
        	$("#popup_top3_error").html(Err);
        	$("#popup_top3_error_hold").show();
        }
        
        if (ReqSta != 404 && ReqSta != 403 && ReqSta != 7036 && ReqSta != 409) {
            LoginTable.style.display = "";
            GeneratorTr.style.display = "none";            
            if (CodeNo.substring(0,1) == "-") {	
                if (GenType == "LT0") {
                    GeneratorTr.style.display = "";
                    CodeInputDes.style.display = "";
                    GeneratorCodeTd.innerHTML = CodeNo.substring(1);
                    CodeSpan.innerHTML = this.draw_popup3_code("password", 8, 8);
                    CodeInputDes.width = "30%";
                } else {
                    CodeSpan.innerHTML = this.draw_popup3_code("password", 6, 6);
                }                
            } else {
                CodeInputDes.verticalAlign = "middle";
                CodeInputDes.style.whiteSpace = "nowrap";
                CodeSpan.innerHTML = this.draw_popup3_code("password", 6, 6);
            }
            CodeInputDes.innerHTML = this.get_xml_el_val("CODENODES");
            
            this.show_login();
            try {
            	if(this.sAuthType == "TAN") {
            		document.getElementById("popup3_pwd").focus();
            	} else if(this.sAuthType == "GEN") {
            		document.getElementById("popup3_code").focus();
            	}                
            } catch(e) {
            }
        } else {
            LoginTable.style.display = "none";
            this.show_login();
        }
    },

    draw_popup3_code: function(stype, isize, ilen) {
        var onkeypressvalue = 'goPopUp.LoginFormSubmitByKey("&amp;act=TIME_SESSREFRESH&amp;task=new",document.popupform,event);void(0)';
        if ((stype == "text" || stype == "tel" || stype == "password") && isize > 0 && ilen > 0) {
            return "<input class='small' type='" + stype + "' id='popup3_code' name='code' size='" + isize + "' maxlength='" + ilen + "' value='' onkeypress='" + onkeypressvalue + "'/>";
        } else {
            return "";
        }
    },

    get_xml_el_val: function(el) {
        var sVal;
        try {
        	sVal = sDataXML[el.toLowerCase()];
        } catch(e) {
            sVal = "";
        }
        return sVal;
    },
    disable: function() {
        try {
            if (this.osetInterval) clearInterval(this.osetInterval);
            if (this.oSign) this.oSign.finish();
            if (this.smartIdPinger) {
            	this.smartIdPinger.stopTimer();
            	this.smartIdPinger = null;
            }
            this.rotate_title("?", "");
            this.toggle("no", 0);
        } catch(e) {
        	//TODO
        }
    },

    LoginFormSubmitByKey: function(act1, frm, evt) {
        if (this.FrmSbmByKey(evt) && this.LoginFormValidate(frm)) {
            this.LoginFormSubmit(act1, frm);
        } 
        
        return 0;
    },

    LoginFormSubmit: function(act1, frm) {
        if (frm && this.LoginFormValidate(frm)) {
            this.sessman(act1);
        } else {
        	var pwdField = document.getElementById("popup3_pwd");
        	var codeField = document.getElementById("popup3_code");
        	if(pwdField != null) {
        		pwdField.focus();
        	} else if(codeField != null) {
        		codeField.focus();
        	}            
        }
        return 0;
    },

    LoginFormValidate: function(frm) {
        try {
            if (frm) {
                if (this.LoginFieldValidate(document.getElementById("popup3_code")) && this.LoginFieldValidate(document.getElementById("popup3_pwd"))) {
                    return true;
                }
                return false;
            }
        } catch(e) {
        }
        return true;
    },

    LoginFieldValidate: function(fld) {
        try {
            if (fld) {
                if (fld.type) {
                    switch(fld.type) {
                        case "text":
                        case "password":
                        case "tel":
                            if (fld.value == "")
                                return false;
                            break;
                    }
                }
            }
        } catch (e) {
        }
        return true;
    },
    FrmSbmByKey: function(evnt) {
       var keycode;
       if (window.event){
           keycode = window.event.keyCode;
       }
       else{
           if (evnt){
               keycode = evnt.which;
           } else {
               return false;
           }
       }
       if (keycode == 13){
           return true;
       } else {
           return false;
       }
    },
    getUrlParameterByName: function (name, url) {
        if (!url) url = window.location.href;
        name = name.replace(/[\[\]]/g, "\\$&");
        var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
            results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, " "));
    }
}