﻿
function dg_Colum(field,text)
{
    this.field=field;
    this.text=text;
    this.visible=true;
    this.cssClass='';
    this.width=0;
    this.height=0;
    this.isTemplate=false;
    
}


function clsSelectorJs(divCont)
{
//Propiedades
   this.win=null;
   this.criteria=null;
   this.criteriaProperty=null;
   this.Name='';
   this.divFilterSource='';
   this.filterDataSourceResponse;
   this.updateText=null;
   this.updateValue=null;
   this.folderImages=''
   this.headerStyle='dgSizableHeader';
   this.itemStyle='dgSizabledgItem';
   this.itemStyleOver='dgSizabledgItemStyleOver';
   this.itemStyleSelected='dgSizabledgItemSelected';
   this.ItemAlternative='dgSizabledgItemAlternative';
   this.top=0;
   this.left=0;
   this.width=500;
   this.pageSize=4;
   this.pageCount=1;
   this.recordCount=0;
   this.pageNumber=1;
   this.columns=[];
   this.selectedRows=[];
   this.checkRol=false;
   this.columnKey=-1;
//   this.filters=[];
   this.textHeader="";
   this.textLoading="Buscando resultados..."
   this.divSearchBox=null;
   this.showState=true;
   this.showFilter=true;
  
// Campos
   this.divSearchBox=null;  //Caja principal
   this.divResultsPane=null; //Panel de resultados
   this.divLoading=null; //Caja de estado
   this.divFilters=null; //Caja con los criterios de bÃºsqueda
   this.scrollResults=null // caja con los resultados de la llamada asincrona
   this.divCont=null;
   this.Event=null;
   if(divCont)
    this.divCont=divCont;
   else
    this.divCont=document.body;
   this.onLoadFilters=null;

//Delegados
   this.onCheckData=null;
   this.oncallBack=null; //Inicia la llamada asincrona, define la funcion de respuesta
   //function dg_onCallBack(sender) sender=referencia al objeto dgSizable
   // para poder asociarle la funcion de respuesta
   this.onItemCreated=null; // Se lanza cuando se crea una fila
   //function dg_onItemCreated("TR creado","datarow","tipo de fila creado")
   this.callBackResponse=function(sender){return;}; //Evento que se lanza cuando se recibe respuesta del servidor
   
   this.onItemClick=function(obj,data){
   return;}
   
   this.LoadFilters=function(obj)//Funcion para cargar un div con los criterios personalizados
   {
   
    if(typeof(this.onLoadFilters)=='function')
    {
      return this.onLoadFilters(this);
    }
    var objF;
    divF=document.createElement('Div');
    return divF;
   }
   
}



clsSelectorJs.prototype.addColum=function(col)
{
    this.columns[this.columns.length]=col;
};



clsSelectorJs.prototype.goTo=function(page)
{
    if(this.divResultsPane.childNodes.length)
    {
      this.divResultsPane.removeChild(this.divResultsPane.firstChild);
    }
    this.pageNumber=page;    
    this.callBack();
}

clsSelectorJs.prototype.callBack=function()
{

    if(typeof this.oncallBack=="function")
        this.oncallBack(this);
}


clsSelectorJs.prototype.clear=function(){
    try{
    if(this.divSearchBox){this.divCont.removeChild(this.divSearchBox)};
    }
    catch(Exception){}
}

clsSelectorJs.prototype.Init = function (e) {
    if(this.SelectionMode=='Multiple')
    {
      for(i=0;i<this.values.length;i++)
      {
        this.AddSelectedItem(this.values[i].value.split('|@@|')[0]);
      }
    }
    else
    {
      if(this.updateValue.value!='')
        this.AddSelectedItem(this.updateValue.value);
    }

    if(this.divSearchBox){this.divCont.removeChild(this.divSearchBox)};
    this.drawResultBox(e);
    if(this.win)
      win.recalculateIframe();
    return this.divSearchBox;
};

clsSelectorJs.prototype.CreateDivLoading=function()
{
    this.divLoading = document.createElement("div");
    this.divLoading.style.width=this.width  +'px';
    this.divLoading.className='dgSizableState';
    img=document.createElement('img');
    //img.src=this.folderImages+'wait.gif'
    img.style.verticalAlign='middle';
    tabla=document.createElement('table');
    //tabla.className='dgSizableDfltTable';
    tabla.cellPadding=1;
    tabla.cellSpacing=0;
    tabla.style.height='100%';
    tb=document.createElement('Tbody');
    tabla.appendChild(tb);
    tr=document.createElement('tr');
    tb.appendChild(tr);
    td=document.createElement('td');
    td.style.width='5px';
    td.noWrap=true;
    tr.appendChild(td);
    td=document.createElement('td');
    td.appendChild(img)
    tr.appendChild(td);
    td=document.createElement('td');
    td.style.width='100%';
    td.style.paddingLeft='5px';
    td.style.verticalAlign='middle';
    tr.appendChild(td);
    div=document.createElement('div');
    //div.appendChild(document.createTextNode(this.textLoading+'   '));
    td.appendChild(div);
    this.divLoading.appendChild(tabla);
    this.MessageState('Aceptar.png','Sin resultados');
    if(!this.showState)
      this.divLoading.style.display='none';
}

clsSelectorJs.prototype.MessageState=function(img,text)
{
  this.divLoading.childNodes[0].childNodes[0].childNodes[0].childNodes[2].childNodes[0].innerText=text;
  image=this.divLoading.childNodes[0].childNodes[0].childNodes[0].childNodes[1].childNodes[0];
  image.src=this.folderImages+img;
//  if(image='')
//    image.style.display='none';
//  else
//    image.style.display='block';
    
}

clsSelectorJs.prototype.CreateDivFilters=function()
{
  var div;
  div=this.LoadFilters(this);
  div.className='dgSizableFilters';    
  return div;
}

clsSelectorJs.prototype.drawResultBox = function (e) {

  this.Event=e;
  ///Tabla de maquetacion
  tbl=document.createElement("table")
  tbl.cellPadding=0;
  tbl.cellSpacing=0;
  tbl.style.height="100%";
  tbl.style.width = this.width + "px";
  tbody=document.createElement("tbody");
  tbl.appendChild(tbody);
  tr1=document.createElement('tr');
  tbody.appendChild(tr1);
  td1=document.createElement('td')
  td1.style.textAlign='left';
  tr1.appendChild(td1);
  tr2=document.createElement('tr');
  tbody.appendChild(tr2);
  td2=document.createElement('td');
  td2.style.textAlign='left';
  tr2.appendChild(td2);
  if(!this.showState)
      td2.style.display='none';
  
  
  
  
//Caja principal
    this.divSearchBox= document.createElement("div");
    this.divSearchBox.className = "dgSizableBox";
    this.divSearchBox.style.cursor='default';
    this.divSearchBox.style.width = this.width + "px";
    
     //Caja de Estado 
    this.CreateDivLoading();
    td2.appendChild(this.divLoading);
    
  //Caja con los criterios de seleccion
    this.divFilters=this.CreateDivFilters();
    if(!this.showFilter)
      this.divFilters.style.display='none';
    this.divSearchBox.appendChild(this.divFilters);  
  
   
//Panel de resultados    
    this.divResultsPane = document.createElement("div");
    this.divResultsPane.className = "dgSizableResults";
    this.divSearchBox.appendChild(this.divResultsPane); 
    td1.appendChild(this.divSearchBox);
    //this.divSearchBox.appendChild(this.divLoading)
    
//AÃ±adir al contendor y marcar la altura
    this.divCont.appendChild(tbl);
    this.divSearchBox.style.height=this.divCont.parentNode.offsetHeight - 25+ 'px';
    
    
};

clsSelectorJs.prototype.crearTablaIniciaContenido=function ()
{
  tbl=document.createElement("table")
  tbl.style.height="100%";
  tbody=document.createElement("tbody");
  tbl.appendChild(tbody);
  tr=document.createElement('tr');
  tbody.appendChild(tr);
  tr.appendChild(document.createElement('td'));
  this.divResultsPane.appendChild(tbl);
}



clsSelectorJs.prototype.populateResults = function (res) {
    
    
    if(this.divResultsPane.childNodes.length)
    {
      this.divResultsPane.removeChild(this.divResultsPane.firstChild);
    }
//   this.callBackResponse(this);
    if(res!=null)
    {
        this.pageNumber=res.pageNumber;
        this.pageCount=res.pageCount;
        this.recordCount=res.recordCount;
        this.pageSize=res.pageSize;
        result=res;
        this.createGrid(result, this.Event);
     }    
};

clsSelectorJs.prototype.showError=function(res)
{
    var cont=document.createElement("div");
    cont.id="Error";
    cont.className="Error";
//  span=document.createElement('span');
//  span.innerHTML="Error: "+res.error.Message;
////  cont.innerHTML="Error: "+res.error.Message;
    cont.innerHTML="Error: " + res;
    this.divResultsPane.appendChild(cont);
    
}
clsSelectorJs.prototype.CalculateHeightScroll=function()
{
  try{
  this.divScrolable.style.height= this.divSearchBox.offsetHeight-this.divLoading.offsetHeight - this.divFilters.offsetHeight - 24+ 'px'
  }
  catch(Exception){}
}

clsSelectorJs.prototype.createGrid=function(dt,e)
{
     var tbl;
     var tr;
     var td;
     var tbody;
     var div;
     
     tbl=document.createElement("Table");
     tbl.cellPadding=0;
     tbl.cellSpacing=0;
     tbl.className='dgSizableDfltTable';
     tbl.border=0;
     tbody=document.createElement("Tbody");
     tbl.appendChild(tbody);
     
     tr=document.createElement("tr");
     tbody.appendChild(tr);
     td=document.createElement("td");
     div=document.createElement('Div');
     td.appendChild(div);
     obj=createHeaderTable(this,dt)
     div.appendChild(obj);
     tr.appendChild(td);     
     tbody.appendChild(tr);
     
     
     tr=document.createElement("tr");
     tbody.appendChild(tr);
     td=document.createElement("td");
     //Crear encabezados del grid
     div=document.createElement('Div');
     td.appendChild(div);
     div.appendChild(CreateTableHeaderResults(this,dt));
     
     //Crear Datos del grid
     div=document.createElement('Div');
     this.divScrolable=div;
     div.className="dgSizableDivScrolable";
     this.CalculateHeightScroll();
     td.appendChild(div);
     div.appendChild(CreateTableResults(this,dt));
     tr.appendChild(td);     
     tbody.appendChild(tr);
     var doc= document.createDocumentFragment();
     doc.appendChild(tbl);

    this.divResultsPane.appendChild(doc);
    
    div.style.height
     
    
    
}




//Crea la tabal que contiene  los botones de navegaciÃ³n
function createHeaderTable(obj,dt)
{
    var tbl;
    var tr;
    var tbody;
    var tr;
    tbl=document.createElement('Table');
    tbl.border=0;
    tbl.cellPadding=0;
    tbl.cellSpacing=0;
    tbl.style.width='100%';
    tbl.className='dgSizableFilterTable';
    tbody=document.createElement('tBody');
    tbl.appendChild(tbody);
    tr=document.createElement('tr');
    tr.className='dgSizableHeaderGridTR';
    tbody.appendChild(tr);
    td=document.createElement('td');
    td.className='dgSizableHeaderGrid';
    td.style.width='200px';
    td.noWrap=true;
    td.appendChild(document.createTextNode('Página '+dt.pageNumber+ ' de '+dt.pageCount));
    tr.appendChild(td);
    td=document.createElement("TD");
    tr.appendChild(td);
    td.className="dgSizableTdSelect";
    
    //Select
    tSelect=document.createElement('table')
    tSelect.style.height='100%';
    tbodySelect=document.createElement('tbody')
    tSelect.appendChild(tbodySelect);
    trSelect=document.createElement('tr');
    tbodySelect.appendChild(trSelect);
    tdSelect=document.createElement('td');
    trSelect.appendChild(tdSelect);
    tdSelect.appendChild(document.createTextNode('Ir a la página'));
    tdSelect.style.verticalAlign='middle';
    tdSelect.style.paddingRight='4px';
    tdSelect.noWrap=true;
    tdSelect=document.createElement('td');
    trSelect.appendChild(tdSelect);
    select=document.createElement("Select");
    select.className='Select';
    select.size=1;
    select.onchange=function(){obj.goTo(select.value);};
    var option
    for(i=1;i<=dt.pageCount;i++)
    {
        option=document.createElement("Option");
        option.text=i;
        option.value=i;
        select.options.add(option)     
    }
    if(select.options.length>0)
      select.options[dt.pageNumber-1].selected=true;
    tdSelect.appendChild(select);
    td.align="center";
    td.appendChild(tSelect);
    
    //Botonera
    td=document.createElement("td");
    td.style.width='200px';
    tr.appendChild(td);
    tr.appendChild(td);
    tbody.appendChild(tr);
    td.noWrap=true;
    td.className='dgSizableHeaderGrid';
    td.style.textAlign='right';
    var num;
    var cont;
    num=obj.pageNumber;
    cont=obj.pageCount;
    taux=document.createElement('table');
    taux.cellPadding=0;
    taux.cellSpacing=0;
    td.appendChild(taux);
    tbaux=document.createElement('tbody');
    taux.appendChild(tbaux);
    tr=document.createElement('tr');
    tbaux.appendChild(tr);
    td=document.createElement('td');
    td.noWrap='true';
    td.className='dgSizableButton';
    img=document.createElement("img");
    img.alt='Ir a la primera pÃ¡gina';
    img.src=obj.folderImages+ 'Primero.png';
    if(num>1)
    {
        img.style.cursor='pointer';
        img.onclick=function(){
          
          obj.goTo(1);  
        }
    }
    else{img.style.cursor='default'}
    td.appendChild(img);
    tr.appendChild(td);
    td=document.createElement("td");
    td.noWrap='true';
    td.className='dgSizableButton';
    img=document.createElement("img");
    img.alt='Ir a la pÃ¡gina anterior';
    img.src=obj.folderImages+ 'Anterior.png';
    if(num>1)
    {
        img.style.cursor='pointer';
        img.onclick=function(){
          
          obj.goTo(obj.pageNumber-1);  
        }
    }
    else{img.style.cursor='default'}
    td.appendChild(img);
    tr.appendChild(td);
    
    td=document.createElement("td");
    td.noWrap='true';
    td.className='dgSizableButton';
    img=document.createElement("img");
    img.alt='Ir a la pÃ¡gina siguiente';
    img.src=obj.folderImages+ 'Siguiente.png';
    if(num<cont)
    {
        img.style.cursor='pointer';
        img.onclick=function(){
          
          obj.goTo(obj.pageNumber+1);  
        }
    }
    else{img.style.cursor='default'}
    td.appendChild(img);
    tr.appendChild(td);
    
    td=document.createElement("td");
    td.noWrap='true';
    td.className='dgSizableButton';
    td.noWrap=true;
    
    img=document.createElement("img");
    img.alt='Ir a la Ãºltima pÃ¡gina';
    img.src=obj.folderImages+ 'Ultimo.png';
    if(num<cont)
    {
        img.style.cursor='pointer';
        img.onclick=function(){   
          obj.goTo(obj.pageCount);  
        }
    }
    else{img.style.cursor='default'}
    td.appendChild(img);
    tr.appendChild(td);

    
    
    return tbl;
}

function CreateTableHeaderResults(obj)
{
    tb=document.createElement('Table');
    tb.width='100%'
    tby=document.createElement('Tbody');
    tb.appendChild(tby);
    tb.border=0;
    tb.cellPadding=0;
    tb.cellSpacing=0;
    tr2=document.createElement('tr');
    tr2.className=obj.headerStyle;
    
    for(i=0;i<obj.columns.length;i++)
    {
        td2=document.createElement("td");
        td2.className='dgSizableHeaderResults';
        td2.appendChild(document.createTextNode(obj.columns[i].text));
        if(obj.columns[i].visible==false)
            td2.style.display='none';
        if(obj.columns[i].width)
            td2.style.width=obj.columns[i].width + 'px';
        if(obj.columns[i].height)
            td2.style.height=obj.columns[i].height + 'px';
        tr2.appendChild(td2);
    }
    td2=document.createElement("td");
    td2.noWrap="true";
    td2.style.width='13px';
    td2.appendChild(document.createTextNode(' '));
    td2.className='dgSizableHeaderResults';
    tr2.appendChild(td2);
    
    if(typeof(obj.onItemCreated)=='function')
        obj.onItemCreated(tr2,null,1);
    tby.appendChild(tr2);
    return tb;
}

function CreateTableResults(obj,dt)
{
    data=dt.lista;
    tb=document.createElement('Table');
    tby=document.createElement('Tbody');
    tb.appendChild(tby);
    tb.border=0;
    tb.cellPadding=0;
    tb.cellSpacing=0;
    tb.className='dgSizableDfltTable'
    tb.style.width=obj.width-20 +'px'
    //tb.style.width='100%';
    for(j=0;j<data.length;j++)
    {
      tr2=document.createElement("tr");
      tr2.style.cursor='pointer';
      tr2.selected=false;
      if(obj.columnKey!=-1)
      {
        dato=eval('data['+j+'].'+obj.columns[obj.columnKey].field);
        if(obj.ExistSelectedItem(dato)!=-1)
        {
          tr2.selected=true;
          tr2.className=obj.itemStyleSelected;
        }
      }
      if((j+1) % 2==0)
       {
        if(obj.ItemAlternative!='')
        {
          if(!tr2.selected)
            tr2.className=obj.ItemAlternative
          if(obj.itemStyleOver!='')
          {
            tr2.onmouseover=function(){ 
              if(!this.selected) this.className=obj.itemStyleOver;}
            tr2.onmouseout=function(){
            if(!this.selected)
              this.className=obj.ItemAlternative;} 
          }
         }
        }
       else
        if(obj.itemStyle!='')
        {
          if(!tr2.selected)
          tr2.className=obj.itemStyle
          if(obj.itemStyleOver!='')
          {
            tr2.onmouseover=function(){ 
            if(!this.selected)
            this.className=obj.itemStyleOver;}
            tr2.onmouseout=function(){
            if(!this.selected)
            this.className=obj.itemStyle;} 
          }
         }
      for(i=0;i<obj.columns.length;i++)
      {
          td2=document.createElement("td");
          td2.className='dgSizableHeaderResultsColumns';
          if(!obj.columns[i].isTemplate)
          td2.appendChild(document.createTextNode(eval('data['+j+'].'+obj.columns[i].field)));
          if(obj.columns[i].visible==false)
              td2.style.display='none';
          if(obj.columns[i].width)
              td2.style.width=obj.columns[i].width + 'px';
          if(obj.columns[i].height)
              td2.style.height=obj.columns[i].height + 'px';
          tr2.appendChild(td2);    
         
              
      }
        if(typeof(obj.onItemCreated)=='function')
            obj.onItemCreated(tr2,data[j],2);
      var posistion=j;
      tr2.position=j;
      tr2.onclick=function()
      {
        this.selected=!this.selected;
        obj.Action=this.selected?"Select":"Delete";
        retval=obj.onItemClick(obj,data[this.position],this);
        if(this.selected)
        {
          this.className=obj.itemStyleSelected;
          obj.AddSelectedItem(retval);
        }
        else
        {
          if((this.j + 1) % 2==0)
            this.className=obj.ItemAlternative;
          else
            this.className=obj.itemStyle;
        }
        
      }
      tby.appendChild(tr2);
    }
    
    return tb;
}

clsSelectorJs.prototype.AddSelectedItem=function(itemSel)
{
  esta=false;
  if(typeof(itemSel)=='string')
  {
    if(this.ExistSelectedItem(itemSel)==-1)
      this.selectedRows[this.selectedRows.length]=itemSel;
  }
}

clsSelectorJs.prototype.DeleteSelectedItem=function(itemSel)
{
  esta=false;
  if(typeof(itemSel)=='string')
  {
    i=this.ExistSelectedItem(itemSel)
    if(i!=-1)
      this.selectedRows[i]=null;
  }
}

clsSelectorJs.prototype.ExistSelectedItem=function(itemSel)
{
  for(i=0;i<this.selectedRows.length;i++)
    if(itemSel==this.selectedRows[i])
      return i;
  return -1;
}

clsSelectorJs.prototype.GetdivSearchBox=function()
{
    return this.divSearchBox
}

clsSelectorJs.prototype.GetdivFilters=function()
{
  return this.divFilters;
}

clsSelectorJs.prototype.close = function () {
    var divbox = this.parentNode.parentNode;
    document.body.removeChild(divbox);
    return false;    
};

clsSelectorJs.prototype.AddOption=function(text,value)
{
  if(typeof(this.values)=='object')
  {
    opt=document.createElement('option');
    opt.text=text;
    opt.value=value+ '|@@|' + text
    if(__ExisteOption(opt,this.values)==-1)
      this.values[this.values.length]=opt;
  }
}

clsSelectorJs.prototype.DeleteOption=function(text,value)
{
  if(typeof(this.values)=='object') //Multiselect
  {
    opt=document.createElement('option');
    opt.text=text;
    opt.value=value+ '|@@|' + text
    i=__ExisteOption(opt,this.values);
    if(i!=-1)
    {
      this.values.options[i]=null;
      this.DeleteSelectedItem(value);
    }
  }
  else
  {
    this.updateText.value='';
    this.updateValue.value='';
  }
}






function __ExisteOption(option,options)
{
  for(i=0;i<options.length;i++)
    if(option.value.split('|@@|')[0]==options[i].value.split('|@@|')[0])
      return i;
  return -1;
}



function  __clsSelectorJsDelete(obj,SelectionMode)
{
  if(SelectionMode=='Simple')
  {
    $get(obj+'_Text').value='';
    $get(obj+'_Value').value='';
  }
  else
  { 
    var _deleted=[];
    _options=$get(obj + '_Values').options
    for(i=_options.length-1;i>=0;i--)
      if(_options[i].selected)
       _options[i]=null;
  
  }
}




