function setTimeout_(to,f) {
    return setTimeout(f,to);
}

if( typeof Object.create !== "function" ) {
    Object.create = function( obj ) {
        function F() {}
        F.prototype = obj;
        return new F();
    }
}

function assert(exp, message) {
    if (!exp) 
        throw "ASSERTION FAILURE!! " + message;
}

jQuery.ajaxSetup({ cache: false });

function contains(a, obj) {
    var i = a.length;
    while (i--) {
       if (a[i] === obj) {
           return true;
       }
    }
    return false;
}

function getGlobal() {
    return (function() {
        return this;
    })();
}

function sessionEndCounterStart(maxTime) {
    var logout_count = maxTime;
    jQuery('#sessionWindow').find('.minute').html(normaliseTime(logout_count));
    var sessionExpireIntervalcounter = setInterval(function() {
    	if ($('#sessionWindow').hasClass("hidden")){
    		clearInterval(sessionExpireIntervalcounter);
    	}
        logout_count--;
        jQuery('#sessionWindow').find('.minute').html(normaliseTime(logout_count));
        if (logout_count <= 0) {
            clearInterval(sessionExpireIntervalcounter);
            jQuery('#sessionWindow').find('#endSession')[0].click();
        }
    },1000);
}
function normaliseTime(time) {
	var minutes = time/(60)|0;
	var seconds = time -(minutes*60);
	var prefix ="";
	if (seconds<10){
		prefix = "0";
	}
	return minutes+":"+prefix+seconds;
}


// =====HeartBeat=====================================

function sendHBtoServer() {

    sendHBtoServerWithArgs(function(data) {
        let popuptime = 1*60*1000;

        if ($.isNumeric(data)){

            if (data<popuptime){
                if ($('#sessionWindow').hasClass("hidden")){
                    $('.sessionExpireDialogBackground').css('height', $(document).height()+'px');
                    $('.sessionExpireDialogBackground').css('width', $(document).width()+'px');
                    $('#sessionWindow').removeClass("hidden");
                    sessionEndCounterStart(popuptime/1000|0);
                }
            }
        } else {
            console.error("HB server response is not numeric: " +data);
        }
    }, function(jqXHR, textStatus, errorThrown){
         // console.log("sendHBtoServer error " + textStatus + " " + errorThrown);
         // console.log(jqXHR);
    });
}

function sendHBtoServerWithArgs(onSuccess, onError, queryString = '') {
    jQuery.ajax({
        type: "GET",
        url: 'https://' + document.domain + ':' + location.port + getGlobal()['CTX_PATH'] + '/hb/hb.sl' + queryString,
        success: function(data) {
            onSuccess(data);
        },
        error:  function(jqXHR, textStatus, errorThrown){
            onError(jqXHR, textStatus, errorThrown);
        },
        dataType: "text",
        cache: false
    });
}


var lastHB = undefined;
var cardioFreq_normal = getGlobal()['HB_FREQUENCE'];
var cardioFreq = cardioFreq_normal;

function runAuthorizedCardio() {
		sendHBtoServer();
    
    
    var newLastHB = new Date().getTime();
    var hbDelta = lastHB === undefined ? 0 : newLastHB - lastHB; 
    var maybeSuffocation = hbDelta - cardioFreq;
    
    if(maybeSuffocation > 1000)
        cardioFreq = cardioFreq * 0.5; // Chrome is likely to suppress JS - setTimeout lasts longer
    else if(maybeSuffocation < 300 && cardioFreq < cardioFreq_normal)
        cardioFreq = Math.min(cardioFreq + Math.max((cardioFreq_normal - cardioFreq) * 0.5, 500), cardioFreq_normal); // calming down
    
    if(maybeSuffocation > 10000) {
        // console.log({"maybeSuffocation": maybeSuffocation, "cardioFreq": cardioFreq, "newLastHB" : newLastHB});
        // console.log("Help! IB being suffocated by Chrome! :(");
    }
    
    lastHB = newLastHB;
        
    setTimeout_(cardioFreq, runAuthorizedCardio);
}


if( !(  getGlobal()['isLoginPage'] === true 
     || getGlobal()['isPrintPage'] === true
     ) && getGlobal()['HB_STARTED'] !== true
       && getGlobal()['DISABLE_HB'] !== true ) {
    getGlobal()['HB_STARTED'] = true;
    runAuthorizedCardio();
}    

// =====HeartBeat=[END]===============================   

// has duplicate in ibank.js
function isEnter(event) {
    var keynum;

    if(window.event) {// IE
        keynum = event.keyCode;
    } else if(event.which) { // Netscape/Firefox/Opera
        keynum = event.which;
    }
    
    if( keynum==13 ) {
        return true;
    } else {
        return false;
    }
}

