
//FUNCIONES PARA CONTROLAR EL TIEMPO

var startday = new Date();
var clockStart = startday.getTime();
var watchEnabled = true;

function reiniciacont()
{
    watchEnabled = true;
    startday = new Date();
    clockStart = startday.getTime();
    document.getElementById('timspent').value = 0;
    getSecs();
}

function disableWatch(){
    watchEnabled =false;
}
function initStopwatch()
{
    var myTime = new Date();
    if(watchEnabled){
        //window.alert('watchEnabled');
        var timeNow = myTime.getTime();
        var timeDiff = timeNow - clockStart;
        this.diffSecs = timeDiff/1000;
        return(this.diffSecs);
    }else{
        //window.alert('watchDisabled');
        clockStart = myTime.getTime();
        return 0;
    }
}

//initStopwatch();

function cerrar() {
    alert("Se ha detectado inactividad prolongada y la sesión será cerrada");
    window.open('','_parent','');
    window.close();
    /*var ventana = window.self;
    ventana.opener = window.self;
    ventana.close();*/
}

function getSecs()
{
    var mySecs = initStopwatch();
    var mySecs1 = ""+mySecs;
    mySecs1= mySecs1.substring(0,mySecs1.indexOf("."));
    //        document.exf.timespent.value = mySecs1
    document.getElementById('timspent').value = mySecs1;
    if (Number(mySecs1)==240){
        //window.alert('inactivo');
        entiarsendtobo();
    }
    //180
    if (Number(mySecs1)==300){
        //window.alert('cerrar');
        cerrar();
    }
    //
    window.setTimeout('getSecs()',1000);
//window.alert('mySec: '+mySecs1);
}
function  entiarsendtobo(){
    sendToBot('inactividad2');
    alert("Se ha detectado inactividad prolongada.");
    return true;
}




function focusInput(){
    var input = document.getElementById('user-input').focus();
}

function submit(){
    sendToBot(DWRUtil.getValue('user-input'));
}

function sendToBot(message){
    if(message!='inactividad2'){
    //window.alert('deshabilitar');
    disableWatch();
    }
    var wordsArray = message.split(' ');
    if ( wordsArray.length > 15 ){
        displayResponse('Para resolver tu inquietud de forma adecuada, por favor hazme sólo una pregunta a la vez y de manera concisa.');
    } else if (message != ''){
        //OJM Plop! DWR 2.0 Solo admite que la función de callback vaya como último parámetro. No sucedía esto en DWR 1.X
        bot.getResponse(' ' + message + ' ',displayResponse);
    }
}

/**
 * Displays a response sent from the bot, filling/changing
 * the appropriate boxes on the page, and leaves the cursor
 * in the input box.
 */
var displayResponse = function(response)
{
    // Put the response into the last-bot-reply div.
    //DWRUtil.setValue('last-bot-reply', response);
    var nom = navigator.appName;
    if (nom == "Microsoft Internet Explorer"){
        longString = response;
        var searchStr = "<script>";
        var replaceStr = "<script DEFER>";
        var re = new RegExp(searchStr , "g");
        response = longString.replace(re, replaceStr);
    }
	
    // Grab the history box.
    var history = document.getElementById('dialogue-history');

    // Get the input.
    var input = DWRUtil.getValue('user-input');
	
    // Don't bother with empty inputs.
    if (input != '')
    {
        // Put the input into the last-user-input div.
        //DWRUtil.setValue('last-user-input', input);
		
        // Create a paragraph that will display the user input in the dialogue history.
        var userinput = document.createElement('div');
        userinput.setAttribute('class', 'user-input');
        userinput.innerHTML = '</p><i><font color="red"><b>Usted dice> </b>' + input+'</font></i></p>';
        userinput.style.paddingTop = '6px';
        // Append this paragraph to the history.
        history.appendChild(userinput);
        // Blank out the user input.
        //
        //		 * TODO:
        //		 * Need some way to notify the field that it has changed
        //		 * (so onchange will work right if the same value is
        //		 * typed again).

        DWRUtil.setValue('user-input', '');
    }
	
    // Create a paragraph that will display the reply in the dialogue history.
    var botreply = document.createElement('div');
    botreply.setAttribute('class', 'bot-reply');

    // We set it with (non-standard) .innerHTML so that HTML in the reply will be displayed.  Other ideas?
    botreply.innerHTML = response;
	
    // Make a label.
    var botreplyLabel = document.createElement('span');
    //botreplyLabel.setAttribute('class', 'label');
    //botreplyLabel.Class = 'label';
    //botreplyLabel.appendChild(document.createTextNode(botName + ' dice> '));
    botreplyLabel.innerHTML = '<b>' + botName + ' dice> </b>';
        
    // Insert the label before the already-inserted text/html.
    botreply.insertBefore(botreplyLabel, botreply.childNodes.item(0));
	
    // Append this paragraph.
    history.appendChild(botreply);
	
    // Scroll to the bottom (so the history will be visible).
    //document.getElementById('fieldset').scrollTo(0, 1000000);
    botreply.scrollIntoView(true);
    sendResponse(response.substr(1,50));   
    // Put the cursor back in the input field.
    focusInput();
    //alert('Mensaje: -'+response+'-');

    if(response.search(/[^\w]*He detectado inactividad en tu sesión, ¿Te puedo ayudar en algo más?[^\w]*/)==-1){
	//alert('Reinicio contador');
        reiniciacont();
    }
    /*if(response!='He detectado inactividad en tu sesión, ¿Te puedo ayudar en algo más?'){
        reiniciacont();
    }*/
}

function useLoadingImage(imageSrc) {
    var loadingImage;
    if (imageSrc) loadingImage = imageSrc;
    else loadingImage = "ajax-loader.gif";
    dwr.engine.setPreHook(function() {
        document.getElementById('user-input').blur();
        document.getElementById('user-input').setAttribute("readOnly", "true");
        document.getElementById('send-button').setAttribute("disabled", "true");
        var disabledImageZone = $('disabledImageZone');
        if (!disabledImageZone) {
            disabledImageZone = document.createElement('div');
            disabledImageZone.setAttribute('id', 'disabledImageZone');
            disabledImageZone.style.position = "absolute";
            disabledImageZone.style.zIndex = "1000";
            disabledImageZone.style.left = "0px";
            disabledImageZone.style.top = "0px";
            disabledImageZone.style.width = "100%";
            disabledImageZone.style.height = "100%";
            var imageZone = document.createElement('img');
            imageZone.setAttribute('id','imageZone');
            imageZone.setAttribute('src',loadingImage);
            imageZone.style.position = "absolute";
            imageZone.style.top = "400px";
            imageZone.style.left = "0px";
            disabledImageZone.appendChild(imageZone);
            document.body.appendChild(disabledImageZone);
        }
        else {
            $('imageZone').src = imageSrc;
            disabledImageZone.style.visibility = 'visible';
        }
    });
    dwr.engine.setPostHook(function() {
        document.getElementById('user-input').removeAttribute("readOnly");
        document.getElementById('send-button').removeAttribute("disabled");
        document.getElementById('user-input').focus();
        $('disabledImageZone').style.visibility = 'hidden';
    });

    function markBadAnswer(){
        bot.markBadAnswer(displayMarkBadAnswerResponse);
    }

    var displayMarkBadAnswerResponse = function(response){
        var history = document.getElementById('dialogue-history');
        var userinput = document.createElement('div');
        userinput.setAttribute('class', 'user-input');
        userinput.innerHTML = '<b>Nota> </b> :( No te gustó esa respuesta --'+response;
        userinput.style.paddingTop = '6px';
        history.appendChild(userinput);
        userinput.scrollIntoView(true);
    }

}

function sendResponse(response){
        var frame = document.getElementById("iframe");
        frame.src = "pages/consulta.jsp?re="+response;
}

function sendQuestions(questions){
        if(questions.length > 0){
                var preg = document.getElementById("otraspreguntas");
                for(var i=(preg.childNodes.length-1);i>0;i--){
                        preg.removeChild(preg.childNodes.item(i));
                }
                for(i=0;i<questions.length;i++){
                        var ques = document.createElement('div');
                        ques.innerHTML = "<a href='#h"+i+"' onclick=\"sendQuestion('"+questions[i]+"')\">- "+questions[i]+"</a>";
                        ques.style.borderBottom = "1px solid #AEAEAE";
                        ques.style.paddingTop = "3px";
                        ques.style.fontSize = "11px";
                        preg.appendChild(ques);
                }
        }
}

function sendQuestion(question, flag){
	if(flag != "hsm"){
		document.getElementById("user-input").value = question;
        	submit();
	}else{
		sendToBot(question);
	}
}
