/* global $j, __page__ajax_postback */

//=========================================================================
//      A J A X Textbox Timeout
//=========================================================================
__logAjTxtbx=false;
//function that gets called on ajax timeout, or
//on blur if submitted=false
function submitAjax(id) {
    var jro = getJroAttr(id);
	
	if(__logAjTxtbx)console.warn(`AJAX TETX-BOX:${id}:in submitAjax`);
	
    if (! jro.postbackdone) {
		//document.getElementById('status').innerText = "in submitAjax:will submit";
        if (typeof (__page__ajax_postback) === 'function') {
            __page__ajax_postback(id, $j('#' + id).val());
			if(__logAjTxtbx)console.warn(`AJAX TETX-BOX:${id}:called __page__ajax_postback`);
			jro.postbackdone = true; // set flag so that we do not submit again
			
		} else if (typeof (jro.ajaxPostbackHandler) === 'function') {
			if(__logAjTxtbx)console.warn(`AJAX TETX-BOX:${id}:called ajaxPostbackHandler`);
			jro.ajaxPostbackHandler();
			jro.postbackdone = true; // set flag so that we do not submit again
        
		} else {
           throw new Error('You must define a function called __page__ajax_postback(id,value) on your page \nOR assign a function reference to the jsp textbox control via property ajaxPostbackHandler to handle Textbox :'+ id +': requests!');
        }
        
        
    } else {
        //already submitted, nothing to do
		if(__logAjTxtbx)console.warn(`AJAX TETX-BOX:${id}: already submitted, nothing to do`);
    }
	
	if(__logAjTxtbx)console.warn(`AJAX TETX-BOX:${id}:clearing timeout`);
    if (jro.timerVar) clearTimeout(jro.timerVar);

}

// called on textbox keypress, it clears timeout and restarts a new one
function startAjaxTimeout(id, timeoutTime) {
    var jro = getJroAttr(id);
    if (jro.timerVar) clearTimeout(jro.timerVar);
    jro.timerVar = setTimeout('submitAjax(\'' + id + '\')', timeoutTime);
	jro.postbackdone = false;
    //document.getElementById('status').innerText = "Ajax Timeout started!!!";
}


function ajaxTextboxBlur(id) {

    var jro = getJroAttr(id);
    if (jro.timerVar) clearTimeout(jro.timerVar);
    const val =  $j('#' + id).val();
    if (jro.onentervalue === val) {
		if(__logAjTxtbx)console.warn(`AJAX TETX-BOX:${id}: Same value: not executing submitAjax`);
    } else {
		if(__logAjTxtbx)console.warn(`AJAX TETX-BOX:${id}: calling submitAjax: new value:${val}`);
        submitAjax(id);
    }
}

function ajaxTextboxFocus(id) {
    var jro = getJroAttr(id); 
    jro.onentervalue = $j('#' + id).val();
    jro.postbackdone = false;
	if(__logAjTxtbx)console.warn(`AJAX TETX-BOX:${id}: Focus value: ${jro.onentervalue}`);
}

