
//ENUM
var Status=
{
     BEGIN:1
     ,SEARCHING:2
     ,NO_RESULTS:3
     ,SELECTED:4
     ,SEARCH_COMPLETED:5
     ,TOO_MUCH_RESULTS:5
}

controls.BusquedaSemantica = function(id, parametros, nuevoVisible, parentElement) {
    //    //ATRIBUTOS
    //    this.id=id;
    //    this.textBox=null;
    //    this.tablaResultados=null
    //    this.attachTextBox(textBox);
    //    this.resultados=new Array();
    //    this.imageStatus=imageStatus;
    //    this.selectedPersona=null;
    //    this.hiddenPost=hiddenPost;
    //    this.status=Status.BEGIN;
    //    this.personaNueva=null;
    //    this.tiposPersona=tiposPersona;
    //    this.nuevoVisible=nuevoVisible;
    this.id = id;
    this.tablaPrincipal = document.getElementById(this.id + '_tablaPrincipal');
    if (this.tablaPrincipal != null) {
        parentElement.removeChild(this.tablaPrincipal);
        this.tablaResultados = this.tablaPrincipal.tablaResultados;
        this.hideSearchResults();
    }
    //this.tablaPrincipal=document.createElement('<table id="'+this.id+'_tablaPrincipal" cellpadding="1" cellspacing="0" style="border-right: gainsboro 1px solid;border-top: gainsboro 1px solid; border-left: gainsboro 1px solid; border-bottom: gainsboro 1px solid; background-color: white;">');
    this.tablaPrincipal = document.createElement('table');
    this.tablaPrincipal.setAttribute('id', this.id + '_tablaPrincipal');
    parentElement.ctrlBusquedaSemantica = this;

    var tbody = document.createElement('tbody');
    var row = document.createElement('tr');
    this.tablaPrincipal.appendChild(tbody);
    tbody.appendChild(row);
    var cell1 = document.createElement('td');
    var cell2 = document.createElement('td');
    row.appendChild(cell1);
    row.appendChild(cell2);
    this.imageStatus = document.createElement('img');
    this.imageStatus.setAttribute('src', '/./img/lupa_contacto.gif');
    cell1.appendChild(this.imageStatus);

    this.textBox = document.createElement('input');
    this.textBox.setAttribute('type', 'text');
    this.textBox.setAttribute('id', this.id + '_textBox');
    cell2.appendChild(this.textBox);
    //    this.textBox2=document.createElement('<input type="text" id="'+this.id+'_textBox2">');
    //    this.tablaPrincipal.appendChild(this.textBox2);
    this.attachTextBox(this.textBox);

    parentElement.appendChild(this.tablaPrincipal);

    this.resultados = new Array();
    this.tablaResultados = document.getElementById(this.id + '_tablaResultados');
    if (this.tablaResultados != null)
        this.hideSearchResults();
    this.selectedElementoUnico = null;
    this.status = Status.BEGIN;
    this.elementoUnicoNuevo = null;
    this.parametros = parametros;
    this.hiddenPost = document.getElementById(this.id + '_hidden');
    this.nuevoVisible = nuevoVisible;
    this.idBusqueda = 0;
    this.keysPiled = 0;
    this.autoPostBackFunction = null;

    if (this.hiddenPost.value > 0) {
        var thisInstance = this;
        Controls.BusquedaSemantica.BusquedaSemantica.Buscar(this.id, 'ID:' + this.hiddenPost.value, this.parametros,
            function(context) {
                var id = context.value[0];
                thisInstance.drawSearchResults([id]);
                thisInstance.hideSearchResults();
                //thisInstance.setSelectedElementoUnico(context.value[0]); 
                var f = function() {

                    var r = thisInstance.getResultadoByElementoUnico(id);
                    if (r != null && r.response != null) {
                        var tmp = thisInstance.autoPostBackFunction;
                        thisInstance.autoPostBackFunction = null;
                        thisInstance.setSelectedElementoUnico(id);
                        thisInstance.autoPostBackFunction = tmp;

                    }
                    else
                        setTimeout(f, 10);

                }
                setTimeout(f, 10);
            }
        );
    }
}
controls.BusquedaSemantica.getBusquedaSemantica=function(id) 
{
    var tabla=document.getElementById(id);
    if (tabla!=null)
        return tabla.ctrlBusquedaSemantica;
    return null;
}

controls.BusquedaSemantica.prototype.attachTextBox=function(textBox)
{
    JScriptPage.attachJSEvent(this,textBox,'onkeyup',this.textBoxChanged);
    JScriptPage.attachJSEvent(this,textBox,'onkeydown',this.textBoxKeyDown);
    JScriptPage.attachJSEvent(this,textBox,'onfocus',this.textBoxFocus);
    
    JScriptPage.attachJSEvent(this,document,'onkeydown',
        function(e)
        {
            if (e.keyCode==27)
            {
                this.hideSearchResults();
            }
        }
    );
    //JScriptPage.attachJSEvent(this,textBox,'onblur',function(){alert('blur');});
    this.textBox=textBox;
    this.textBox.style.borderWidth='0px';
    this.textBox.style.borderSyle='none';
    Common.setInmoParentObject(this.textBox,this);
}
controls.BusquedaSemantica.prototype.createTablaResultados=function()
{
     if(this.tablaResultados==null){
        this.tablaResultados=document.createElement('<table id="'+this.id+'_tablaResultados">');
        this.tablaResultados.style.position='absolute';
        this.tablaResultados.style.zIndex='5';
        this.tablaResultados.style.backgroundColor='white';
        this.tablaResultados.style.borderColor='black';
        this.tablaResultados.style.borderStyle='solid';
        this.tablaResultados.style.borderWidth='1px';
        this.tablaResultados.style.fontFamily='arial';
        this.tablaResultados.style.fontSize='11px';
        document.body.insertBefore(this.tablaResultados,document.body.firstChild); 
        //JScriptPage.attachJSEvent(this,this.tablaResultados,'onmouseup',function(){alert('focus');});
        JScriptPage.attachJSEvent(this,window,'onresize',this.positionTablaResultados);
        
        var iFrame=document.createElement('iframe');
        var fnResize=function()
        {
            iFrame.style.width=this.tablaResultados.offsetWidth+'px';
            iFrame.style.height=this.tablaResultados.offsetHeight+'px';
            iFrame.style.left=this.tablaResultados.offsetLeft+'px';
            iFrame.style.top=this.tablaResultados.offsetTop+'px';
            iFrame.style.zIndex='4';
            iFrame.style.position='absolute';
            document.body.insertBefore(iFrame,this.tablaResultados); 
            this.tablaResultados.iFrame=iFrame;
        }
        JScriptPage.attachJSEvent(this,this.tablaResultados,'onresize',fnResize);
        
        this.tablaPrincipal.tablaResultados=this.tablaResultados;
    }
}
controls.BusquedaSemantica.prototype.positionTablaResultados=function()
{
    var tabla=this.imageStatus.offsetParent.offsetParent;
    if (this.tablaResultados!=null)
    {
        this.tablaResultados.style.left=Common.getAbsolutePosition( tabla).left+'px';
        this.tablaResultados.style.top=Common.getAbsolutePosition(tabla).top+tabla.offsetHeight+'px';
    }
}
controls.BusquedaSemantica.prototype.textBoxFocus=function(e)
{
    if (this.getStatus()==Status.SELECTED && this.getSelectedElementoUnico()!=null)
        this.buscarElementoUnico("ID:"+this.getSelectedElementoUnico());
}
controls.BusquedaSemantica.prototype.textBoxChanged=function(e)
{
    if (e.keyCode!=13 && e.keyCode!=9) //Verificamos que no se presiono ni TAB ni ENTER
    { 
        var texto=
            e.keyCode==40 && this.getStatus()==Status.SELECTED?"ID:"+this.getSelectedElementoUnico()
            :this.textBox.value;
        if (!texto.startsWith("ID"))
            this.setSelectedElementoUnico(null);
            

        if (this.textBox.value.length>3 
            && (this.textBox.value!=this.textBox.oldValue || (e.keyCode==40 && this.getStatus()==Status.SELECTED)))
        {              
    //            this.createTablaResultados();
    //            Common.deleteAllRows(this.tablaResultados);
    //            var cell=this.tablaResultados.insertRow().insertCell();
    //            cell.style.fontFamily='arial';
    //            cell.style.fontSize='11px';
    //            cell.innerText='Por favor espere...';
            
            
            thisTmp=this;
            
            if (!texto.startsWith("ID"))
                this.setStatus(Status.SEARCHING);
            
            this.keysPiled++;
            var thisTmp=this;
            this.setSelectedResultadoIndex(-1);
            setTimeout(function(){thisTmp.procesarKeysPiled.call(thisTmp,texto);},500);
        }
        else if (this.textBox.value.length<=3 && this.tablaResultados!=null)
        {
            this.hideSearchResults();
        }
    }
    
}
controls.BusquedaSemantica.prototype.procesarKeysPiled=function(texto)
{
    this.keysPiled--;
    if (this.keysPiled==0)
        this.buscarElementoUnico(texto);
}
controls.BusquedaSemantica.prototype.buscarElementoUnico=function(texto)
{
    this.idBusqueda++;
    thisTmp=this;
    //AjaxPro.queue.abort();  
    Controls.BusquedaSemantica.BusquedaSemantica.Buscar(this.id,texto,this.parametros,function(context){thisTmp.searchResult.call(thisTmp,context)}, this.idBusqueda);
}
controls.BusquedaSemantica.prototype.searchResult=function(r)
{
    if (this.idBusqueda==r.context)
    {
    //        if(this.tablaResultados!=null)
    //        {
    //             document.body.removeChild(this.tablaResultados);
    //             this.tablaResultados=null;
    //        }
        
        if (r.error==null)
        {
            this.drawSearchResults(r.value);
        }
        else
        {
            this.createTablaResultados();
            this.positionTablaResultados();
            Common.deleteAllRows(this.tablaResultados);
            var cell=this.tablaResultados.insertRow().insertCell();
            if (r.error.Message=="TOO_MUCH_RESULTS")
            {
                
               
                cell.innerHTML='Por favor especifique mejor su b&uacute;squeda,<br />hay muchas coincidencias con el texto introducido.';
                this.setStatus(Status.TOO_MUCH_RESULTS);
                this.drawCellNuevo();
            }
            else
            {
                cell.innerHTML=r.error.Message;
                this.setStatus(Status.BEGIN);
            }
        }
    }
    
}
controls.BusquedaSemantica.prototype.drawSearchResults=function(elementosUnicos)
{
     this.createTablaResultados();
     this.positionTablaResultados();
     Common.deleteAllRows(this.tablaResultados);
         
    if (elementosUnicos.length>0)
    {
       
        this.resultados.length=0;
        var tabla=document.createElement('table');
        var row=this.tablaResultados.insertRow();
        var cell=row.insertCell();
        cell.appendChild(tabla);
        cell=row.insertCell();
        this.drawCloseButton(cell);
        for (var i=0;i<elementosUnicos.length;i++)
        {
            row=tabla.insertRow();
            cell=row.insertCell();
            //cell.innerText=personas[i].Nombre1y2Apellido1y2;
            this.resultados[i]=new controls.BusquedaSemanticaSearchResult();
            this.resultados[i].cell=cell;
            this.resultados[i].elementoUnico=elementosUnicos[i];
            this.resultados[i].selected=i==0;
            cell.resultado=this.resultados[i];
            
             this.drawElementoUnicoCell(this.resultados[i]);
            
            JScriptPage.attachJSEvent(this,cell,'onmousemove',this.cellResultadoMouseOver,cell);
            JScriptPage.attachJSEvent(this,cell,'onclick',this.cellResultadoSelected,cell);
            
            
        }
       
        this.applySelected(this.resultados);
        if (this.getStatus()!=Status.SELECTED)
            this.setStatus(Status.SEARCH_COMPLETED);
    }
    else
    {
        var cell=this.tablaResultados.insertRow().insertCell();
        cell.innerHTML='No hay resultados para su b&uacute;squeda';
        this.setStatus(Status.NO_RESULTS);
    }
    this.drawCellNuevo();
    
}
controls.BusquedaSemantica.prototype.drawCellNuevo=function()
{
    if (this.nuevoVisible)
    {
        var cellNuevo=this.tablaResultados.insertRow().insertCell();
        cellNuevo.padding='2px';
        var linkNuevo=document.createElement('a');
        linkNuevo.innerText='Crear nuevo';
        linkNuevo.href='javascript:void(0);';
        linkNuevo.style.color='blue';
        cellNuevo.appendChild(linkNuevo);
        cellNuevo.align='center';
        JScriptPage.attachJSEvent(this,linkNuevo,'onclick',this.drawCellNuevoElementoUnico);
    }
    
}
controls.BusquedaSemantica.prototype.applySelected=function(resultados)
{
    for (var i=0;i<resultados.length;i++)
    {
        var r=resultados[i];
        if (r.selected)
        {
            r.cell.style.backgroundColor='lightblue';
        }
        else
        {
            r.cell.style.backgroundColor='white';
        }
    }
}
controls.BusquedaSemantica.prototype.selectResultado=function(index)
{
    var resultados=this.resultados;
    if ((typeof index=="number" && index>0 && index<resultados.length-1)|| typeof index=="object")
    {
        for (var i=0;i<resultados.length;i++)
        {
            resultados[i].selected=(i==index || resultados[i]==index);
        }
    }
}
controls.BusquedaSemantica.prototype.setSelectedResultadoIndex=function(index)
{
    for (var i=0;i<this.resultados.length;i++)
    {
        this.resultados[i].selected=i==index;
    }
    return null;
}
controls.BusquedaSemantica.prototype.setSelectedResultado=function(resultado)
{
    for (var i=0;i<this.resultados.length;i++)
    {
        this.resultados[i].selected=this.resultados[i]==resultado;
    }
    return null;
}
controls.BusquedaSemantica.prototype.getSelectedResultado=function()
{
    for (var i=0;i<this.resultados.length;i++)
    {
        if(this.resultados[i].selected)
        return this.resultados[i];
    }
    return null;
}
controls.BusquedaSemantica.prototype.getSelectedResultadoIndex=function()
{
    for (var i=0;i<this.resultados.length;i++)
    {
        if(this.resultados[i].selected)
        return i;
    }
    return -1;
}
controls.BusquedaSemantica.prototype.getResultadoByElementoUnico=function(elementoUnico)
{
    for (var i=0;i<this.resultados.length;i++)
    {
        if(this.resultados[i].elementoUnico==elementoUnico)
        return this.resultados[i];
    }
    return null;
}
controls.BusquedaSemantica.prototype.setSelectedElementoUnico=function(elementoUnico)
{
    this.elementoUnico=elementoUnico;
    if (elementoUnico!=null)
    {
        var resultado=this.getResultadoByElementoUnico(elementoUnico);
        this.textBox.value=resultado.response.TextoSeleccionado;
        this.hideSearchResults();
        this.setStatus(Status.SELECTED);
        this.hiddenPost.value=elementoUnico;
        if (this.autoPostBackFunction!=null)
            this.autoPostBackFunction();
    }
    else
    {
        this.hiddenPost.value="-1";
        this.setStatus(Status.BEGIN);
    }
    
}
controls.BusquedaSemantica.prototype.getSelectedElementoUnico=function()
{
    return this.elementoUnico;
}
controls.BusquedaSemantica.prototype.hideSearchResults=function()
{
    if (this.tablaResultados!=null)
    {
        if (this.tablaResultados.iFrame!=null && this.tablaResultados.iFrame.parentElement!=null)
            document.body.removeChild(this.tablaResultados.iFrame);
        if (this.tablaResultados.parentElement!=null)
            document.body.removeChild(this.tablaResultados);
        this.tablaResultados=null;
        if (this.getStatus()!=Status.SELECTED)
            this.setStatus(Status.BEGIN);
    }
}
controls.BusquedaSemantica.prototype.changeImageStatus=function(retard)
{
    var thisInstance=this;
    var fun=function()
    {
        
        var img;
        if (thisInstance.status==Status.BEGIN)
        {
            img='/./img/lupa_contacto.gif';
        }
        else if (thisInstance.status==Status.SEARCHING)
        {
            img='/./img/lupa_contacto_ani.gif';
        }
        else if(thisInstance.status==Status.NO_RESULTS)
        {
            img='/./img/lupa_contacto.gif';
        }
        else if(thisInstance.status==Status.SELECTED)
        {
            img='/./img/check_contacto.gif';
        }  
        else if(thisInstance.status==Status.TOO_MUCH_RESULTS)
        {
            img='/./img/lupa_contacto.gif';
        } 
        else if(thisInstance.status==Status.SEARCH_COMPLETED)
        {
            img='/./img/lupa_contacto.gif';
        } 
        if (thisInstance.imageStatus!=null && thisInstance.imageStatus.src.indexOf(img)==-1)
            thisInstance.imageStatus.src=img;
    };
    if (retard)
        setTimeout(fun,400);
    else
        fun();
}
controls.BusquedaSemantica.prototype.setStatus=function(status)
{
    this.status=status;
    this.changeImageStatus(status!=Status.SEARCHING && status!=Status.SELECTED);
}
controls.BusquedaSemantica.prototype.getStatus=function()
{
    return this.status;
}
controls.BusquedaSemantica.prototype.textBoxKeyDown=function(e)
{
    this.textBox.oldValue=this.textBox.value;
    var index=-1;
    for (var i=0;i<this.resultados.length;i++)
    {
        if(this.resultados[i].selected)
        {
            index=i;
            break;
        }
    }
    if (e.keyCode==38 && index>0)
    {
        this.resultados[index].selected=false;
        this.resultados[index-1].selected=true;
    }
    else if (e.keyCode==40 && index<this.resultados.length-1)
    {
        this.resultados[index].selected=false;
        this.resultados[index+1].selected=true;
    }
//    else if (e.keyCode==27)
//    {
//        this.hideSearchResults();
//        e.returnValue=false;
//    }
    else if (e.keyCode==13 || e.keyCode==9)
    {
        if (this.getSelectedResultado()!=null)
            this.setSelectedElementoUnico(this.getSelectedResultado().elementoUnico);
        e.returnValue=false;
    }
    this.applySelected(this.resultados);         
}
controls.BusquedaSemantica.prototype.drawElementoUnicoCell=function(resultado)
{  
    Common.removeAllElements(resultado.cell);
    var thisTmp=this;
    var f=function(r)
    {
        resultado.cell.innerHTML=r.value.Html;
        resultado.response=r.value;
        var linkDetalles=document.getElementById(r.value.ClientIDControlRaiseDetalles);
        var linkModificar=document.getElementById(r.value.ClientIDControlRaiseModificar);
        if (linkDetalles!=null){
            var f2=function()
            {
                window.event.cancelBubble=true;
                this.drawCellDetalleElementoUnico(resultado.elementoUnico);
            }
            JScriptPage.attachJSEvent(thisTmp,linkDetalles,'onclick',f2);
        }
        if (linkModificar!=null){
            var f2=function()
            {
                window.event.cancelBubble=true;
                this.drawCellModificarElementoUnico(resultado.elementoUnico);
            }
            JScriptPage.attachJSEvent(thisTmp,linkModificar,'onclick',f2);
        }
    }
    Controls.BusquedaSemantica.BusquedaSemantica.GetResponseListado(this.id,resultado.elementoUnico,f);
   
}
controls.BusquedaSemantica.prototype.linkDetallesClicked=function(e,elementoUnico)
{
    e.cancelBubble=true;
    this.drawCellDetalleElementoUnico(elementoUnico);
}
controls.BusquedaSemantica.prototype.linkModificarClicked=function(e,elementoUnico)
{
    e.cancelBubble=true;
    this.drawCellModificarElementoUnico(elementoUnico);
}
controls.BusquedaSemantica.prototype.drawCellDetalleElementoUnico=function(elementoUnico)
{
  //Common.removeAllElements(resultado.cell);
   var tabla=this.tablaResultados;
  
   Common.hideAllRows(tabla);
   var row=tabla.insertRow();
   var cellBack=row.insertCell();
   var cell=row.insertCell();
   var cellClose=row.insertCell();
   var thisTmp=this;
    var f=function(r)
    {
        cell.innerHTML=r.value.Html;   
        thisTmp.drawBackButton(cellBack); 
        thisTmp.drawCloseButton(cellClose);   
    }
    Controls.BusquedaSemantica.BusquedaSemantica.GetResponseDetalle(this.id,elementoUnico,f);  
}
controls.BusquedaSemantica.prototype.hideCellDetalleElementoUnico=function()
{
    var tabla=this.tablaResultados;
    tabla.deleteRow(tabla.rows.length-1);
    Common.showAllRows(tabla);
     this.tablaResultados.style.padding='0px';
}
controls.BusquedaSemantica.prototype.hideCellNuevoElementoUnico=function()
{
    this.hideCellDetalleElementoUnico();
}
controls.BusquedaSemantica.prototype.drawCloseButton=function(parentElement)
{
    var img=document.createElement('<img src="/./img/close_small.gif">');
    parentElement.appendChild(img);
    parentElement.vAlign='top';
    JScriptPage.attachJSEvent(this,img,'onclick',this.hideSearchResults);
    this.tablaResultados.cellSpacing=0;
    this.tablaResultados.cellPadding=0;
    parentElement.style.paddingRight='2px';
    parentElement.style.paddingTop='2px';
    img.style.cursor='pointer';
}
controls.BusquedaSemantica.prototype.drawBackButton=function(parentElement)
{
    var img=document.createElement('img');
    img.src='/./img/back.gif';
    parentElement.appendChild(img);
    parentElement.vAlign='top';
    parentElement.style.paddingLeft='2px';
    parentElement.style.paddingTop='2px';
    img.style.cursor='pointer';
    JScriptPage.attachJSEvent(this,img,'onclick',this.hideCellDetalleElementoUnico);
}    
controls.BusquedaSemantica.prototype.drawCellModificarElementoUnico=function(elementoUnico)
{
    //Common.removeAllElements(resultado.cell);
   var tabla=this.tablaResultados;
  
   Common.hideAllRows(tabla);
   var row=tabla.insertRow();
   var cellBack=row.insertCell();
   var cell=row.insertCell();
   var cellClose=row.insertCell();
   var thisTmp=this;
    var f=function(r)
    {
        cell.innerHTML=r.value.Html;   
        var btnGuardar=document.getElementById(r.value.ClientIDControlRaiseGuardar)
        if (btnGuardar!=null)
        {
            var f2=function()
            {
                var resultado=thisTmp.getSelectedResultado();
                var id=resultado!=null?resultado.elementoUnico:-1;
                thisTmp.guardarElementoUnico(id);
            }
            JScriptPage.attachJSEvent(this,btnGuardar,'onclick',f2);
        }
        thisTmp.drawBackButton(cellBack); 
        thisTmp.drawCloseButton(cellClose);   
    }
    Controls.BusquedaSemantica.BusquedaSemantica.GetResponseModificar(this.id,elementoUnico,f);  
}
controls.BusquedaSemantica.prototype.drawCellNuevoElementoUnico=function()
{
    this.setSelectedResultado(null);
    this.drawCellModificarElementoUnico();
}
controls.BusquedaSemantica.prototype.cellResultadoMouseOver=function(e,cell)
{
    this.selectResultado(cell.resultado);
    this.applySelected(this.resultados);
}
controls.BusquedaSemantica.prototype.cellResultadoSelected=function()
{
    var resultado=this.getSelectedResultado();
    this.setSelectedElementoUnico(resultado.elementoUnico);
}
controls.BusquedaSemantica.prototype.guardarElementoUnico=function(id)
{
    var thisTmp=this;
    var campos={values:new Array(),keys:new Array()};
    var cell=this.tablaResultados.rows[this.tablaResultados.rows.length-1].cells[1];
    for (var i=0;i<cell.children.length;i++)
    {
        if (cell.children[i]['BusquedaSemanticaGuardarKey']!=null)
        {
            campos.values[campos.values.length]=cell.children[i].value;
            campos.keys[campos.keys.length]=cell.children[i]['BusquedaSemanticaGuardarKey'];
        }
    }
    var r=Controls.BusquedaSemantica.BusquedaSemantica.GuardarElementoUnico(this.id,id,campos);
    id=r.value;
    this.hideCellNuevoElementoUnico();
    
    
    this.drawSearchResults([id]);
    this.hideSearchResults();
//    this.drawElementoUnicoCell(this.getResultadoByElementoUnico(id));
//    
   // this.drawCellDetalleElementoUnico(id);
//    
    var thisTmp=this;
    var f=function()
    {
        var r=thisTmp.getResultadoByElementoUnico(id);
        if (r!=null && r.response!=null)
            thisTmp.setSelectedElementoUnico(id);
        else
            setTimeout(f,10);
            
    }
    setTimeout(f,10);
}
    

//-------------
