AJX Tools (AJX) : Ajax Library « Ajax Layer « JavaScript DHTML






AJX Tools (AJX)

 

/*******************************************************************************
 *
 * AJX Tools (AJX)
 *
 * Developers: 
 *   - Tales Viglioni (talesviglioni@gmail.com)
 *   - Cristopher Sanches (cristopherms@gmail.com)
 *
 * Version: 1.0
 * Date: 06/26/2006
 * 
 * Copyright (c) 2006 T&C.
 * All rights reserved.
 *
 * AJX Tools is distributable under the terms of an GNU Library or 
 * Lesser General Public License (LGPL).
 *
 * http://ajxtools.sourceforge.net/
 * 
AJXtools
   |
   +- AJXload()
   |
   +- AJXgetHTTPObject()
   |
   +- AJXstatus()
   |
   +- AJXsetWaitMessage()
   |   
   +- AJXgetWaitMessage()
   |   
   +- AJXsetLoadingMessage()
   |   
   +- AJXgetLoadingMessage()

     
AJXapplication
   |
   +- AJXpopulateCombo()
   |
   +- AJXaddTableRow()
   |
   +- AJXupdateTableRow()
   |
   +- AJXremoveTableRow()
   |   
   +- AJXgetResponseText()   
   |
   +- AJXgetResponseXML()   
   |
   +- AJXautoComplete()      
   |
   +- AJXfillDiv()      
   |
   +- AJXcleanDiv()      
   |
   +- AJXautoComplete()
         
         
AJXutil
   |
   +- AJXfindPosX()
   |
   +- AJXfindPosY()
   |
   +- AJXvalidateRequired()
   |   
   +- AJXgetObjectName()
   |   
   +- AJXgetFormValues()
   |
   +- AJXshowMessage()
   |
   +- AJXexistsCssClass()
   |
   +- AJXtokenizer()
   |   
   +- AJXtrim()
   |   
   +- AJXRTrim()
   |   
   +- AJXLTrim()  
 ******************************************************************************/
  
/*******************************************************************************
 * AJXtools()
 * AJX Tools main class
 *
 ******************************************************************************/
function AJXtools()
{
   var waitMessage = "";
   var loadingMessage = "";
   var _this = this;
  var util = new AJXutil();
  
  this.AJXresponseXML=null;
  this.AJXresponseText=null;  
  this.AJXload = AJXload;
  this.AJXsetWaitMessage = AJXsetWaitMessage;
  this.AJXgetWaitMessage = AJXgetWaitMessage;
  this.AJXsetLoadingMessage = AJXsetLoadingMessage;
  this.AJXgetLoadingMessage = AJXgetLoadingMessage;

  /**
   * AJXload()
   * Method to load page thru GET or POST form methods.
   *
   * Parameters:
   *   - url: url to submition. (required)
   *   - objAJXapplication: instance of a object to execute the 
   *                        method "nextMethod". (required)
   *   - nextMethod: method of "objAJXapplication" called after 
   *                 send data. (required)
   *   - form: form submited. Case form exists, open method uses POST. 
   *           Otherwise, open method uses GET. (optional)
   *   - isAsync: configure if the call method will execute synchronous (false)
   *              or asynchronous (true). The default value is true. (optional)
   *   - returnXML: configure if the return will load AJXresponseXML (true) or 
   *                AJXresponseText (false). The default value is true. (optional)
   *
   */
  function AJXload(url, objAJXapplication, nextMethod, form, isAsync, returnXML)
  {
     var AJXhttp = AJXgetHTTPObject();  
    var data = null;
    var returnType = null;
    
    if (returnXML==false)
    {
      returnType = "text";
    }
    else
    {
      returnType = "xml";
    }

    if (isAsync != false)
    {
      isAsync = true;
    }
    
    if(form)
    {
      data = util.AJXgetFormValues(form);      
      AJXhttp.open("POST",url,isAsync);
    }
    else
    {
      AJXhttp.open("GET",url,isAsync);
    }  
    
    AJXhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    util.AJXshowMessage(AJXgetWaitMessage());    
    AJXhttp.send(data);
  
    if (isAsync)
    {
      AJXhttp.onreadystatechange = function() 
        {AJXstatus(AJXhttp, objAJXapplication, nextMethod, isAsync, returnType);};    
    }
    else
    {
      AJXstatus(AJXhttp, objAJXapplication, nextMethod, isAsync, returnType);
    }
  }   

  /**
   * AJXstatus()
   * Verifies the status of the request. 
   *
   * Parameters:
   *   - http: instance of XMLHttpRequest object. (required)
   *   - objExec: instance of a object to execute the 
   *              method "nextMethod". (required)
   *   - methodExec: method of "objExec" called after responseXML. (required)
   *   - isAsync: inform if the call was synchronous (false) or 
   *              asynchronous(true). (required)
   *   - returnType: configure the return to responseText or 
   *                 responseXML. (required)
   *
   */
  function AJXstatus(http, objExec, methodExec, isAsync, returnType)
  {  
    if(http.readyState <= 3)
    {
      util.AJXshowMessage(AJXgetLoadingMessage());
    }      
    
    if(http.readyState == 4)
    {
      if (http.status == 200)
      {
        util.AJXshowMessage("");

        if (returnType=="text")
        {
          _this.AJXresponseText = http.responseText;
        }
        else
        {
          _this.AJXresponseXML = http.responseXML;
        }

        if (isAsync)
        {
          if ((objExec!=null)&&(methodExec!=null))        
          {
            eval("objExec."+methodExec);
          }
          _this.AJXresponseXML = null;
          _this.AJXresponseText = null;
        }
      }
      else
      {
        util.AJXshowMessage("Error code: " + http.status);
      }
    }
  }  

  /**
   * AJXgetHTTPObject() 
   * Create the XMLHttpRequest object.
   * 
   */
  function AJXgetHTTPObject() 
  {
    var xmlhttp;

    // If the user is using Mozilla/Firefox/Safari
    if (window.XMLHttpRequest) 
    {
      xmlhttp = new XMLHttpRequest();    
      xmlhttp.overrideMimeType('text/xml');
    }  
    // If the user is using IE    
    else if (window.ActiveXObject) 
    {
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    return xmlhttp;
  }  

  /**
   * AJXgetWaitMessage() 
   * Gets the value of waitMessage attribute.
   * 
   */
    function AJXgetWaitMessage()
    {
        if (waitMessage == "")
        {
          AJXsetWaitMessage("Wait...");
        }
        return waitMessage;
    }

  /**
   * AJXsetWaitMessage() 
   * Sets the value of waitMessage attribute.
   * 
   */
    function AJXsetWaitMessage(waitMsg) 
    {
        waitMessage = waitMsg;
    }  

  /**
   * AJXgetLoadingMessage() 
   * Gets the value of loadingMessage attribute.
   * 
   */
    function AJXgetLoadingMessage()
    {
        if (loadingMessage == "")
        {
          AJXsetLoadingMessage("Loading...");
        }
        return loadingMessage;
    }

  /**
   * AJXsetLoadingMessage() 
   * Sets the value of loadingMessage attribute.
   * 
   */
    function AJXsetLoadingMessage(loadingMsg) 
    {
        loadingMessage = loadingMsg;
    }  
}

/*******************************************************************************
 * AJXapplication()
 * AJX Tools application class.
 *
 ******************************************************************************/
function AJXapplication()
{
  var AJXexecuting = false;
  var util = new AJXutil();
  var ajx = new AJXtools();

  this.AJXpopulateCombo = AJXpopulateCombo;
  this.AJXaddTableRow = AJXaddTableRow;
  this.AJXupdateTableRow = AJXupdateTableRow;
  this.AJXgetResponseText = AJXgetResponseText;
  this.AJXgetResponseXML = AJXgetResponseXML;
  this.AJXremoveTableRow = AJXremoveTableRow;
  this.AJXfillDiv = AJXfillDiv;
  this.AJXcleanDiv = AJXcleanDiv;
  this.AJXautoComplete = AJXautoComplete;

  /**
   * AJXpopulateCombo()
   * Populate a combo box with the values from a xml element.
   * 
   * Parameters:
   *  - url: url to submition. (required)
   *  - form: submited form if html form method is "post". (optional)
   *   - repeatedElement: xml repeated tag (required)
   *  - comboName: name of combo to populate (required)
   *   - valueTag: xml tag containing the "value" parameter of html
   *          "option" tag (required)
   *   - textTag: xml tag containing the text to combo (required)repeatedElement
   *  - functionAfterExecution: function called after the execution 
   *                of AJXpopulateCombo function (optional)
   *
   * Expected XML element in AJXresponseXML:
   *
   *  <root (repeatedElement*)>
   *    <repeatedElement(valueTag, textTag)>
   *    ...
   *  </root>
   *
   */
  function AJXpopulateCombo(url, form, repeatedElement, comboName, valueTag, textTag, functionAfterExecution)
  {
    if (!util.AJXvalidateRequired(url,repeatedElement, comboName, valueTag, textTag))
    {
      return false;
    }

    if (!AJXexecuting && ajx.AJXresponseXML==null)
    {
      AJXexecuting = true;
      executeMethod = "AJXpopulateCombo(\""+url+"\",\""+form+"\",\""+repeatedElement+"\",\""+comboName+"\",\""+valueTag+"\",\""+textTag+"\",\""+functionAfterExecution+"\");";
      ajx.AJXload(url,this,executeMethod,form);
      AJXexecuting = false;
      executeMethod = "";
    }
    
    if (!AJXexecuting && ajx.AJXresponseXML!=null)
    {
      var opt;
      var XMLelement = ajx.AJXresponseXML.getElementsByTagName(repeatedElement); 
      var cmb = document.getElementsByName(comboName)[0]

      for(j=cmb.length; j >= 0 ; j--) 
      {
        cmb.remove(j);
      }    
      
      for(i=0 ; i < XMLelement.length ; i++) 
      {
        opt = document.createElement("option");
        opt.text = XMLelement[i].getElementsByTagName(textTag)[0].firstChild.data; 
        opt.value = XMLelement[i].getElementsByTagName(valueTag)[0].firstChild.data; 
      
        try 
        {
          cmb.add(opt, null); // standards compliant; doesn't work in IE
        }
        catch(ex) 
        {
          cmb.add(opt); // IE only
        }    
      }  
      eval(functionAfterExecution);
    }
  }
  
  /**
   * AJXaddTableRow()
   * Add rows in a table with values from a xml element. Each repeated child 
   * represents a table row, and each child in repeated element, represents a 
   * table cell.
   * 
   * Parameters:
   *  - url: url to submition. (required)
   *  - form: submited form if html form method is "post". (optional)
   *   - repeatedElement: xml repeated tag. (required)
   *  - idTable: id of HTML table tag to add row. (required)
   *   - rowsPosition: first position after table headers. (required)
   *  - message: message showed if not found any "repeatedElement" tag. (optional)
   *  - clearTable: case "Y", remove all table rows begining in "rowPosition". (optional)
   *  - functionAfterExecution: function called after execution of AJXaddTableRow() method, if exists some "repeatedElement" tag. (optional)
   *  - functionAlwaysExecuted: function always called after execution of AJXaddTableRow() method. (optional)
   *
   * Expected XML element in AJXresponseXML:
   *
   *  <root (repeatedElement*)>
   *    <repeatedElement(child1, child2, ... ,childN)>
   *    ...
   *  </root>
   *
   */
  function AJXaddTableRow(url, form, repeatedElement, idTable, rowsPosition, message, clearTable, functionAfterExecution, functionAlwaysExecuted)
  {
    if (!util.AJXvalidateRequired(url, repeatedElement, idTable, rowsPosition))
    {
      return false;
    }
    
    if (!AJXexecuting && ajx.AJXresponseXML==null)
    {
      AJXexecuting = true;
      executeMethod = "AJXaddTableRow(\""+url+"\",\""+form+"\",\""+repeatedElement+"\",\""+idTable+"\",\""+rowsPosition+"\",\""+message+"\",\""+clearTable+"\",\""+functionAfterExecution+"\",\""+functionAlwaysExecuted+"\")";
      ajx.AJXload(url,this,executeMethod,form);
      AJXexecuting = false;
      executeMethod = "";
    }
    
    if (!AJXexecuting && ajx.AJXresponseXML!=null)
    {  
      var aTable;
      var aRow;
      var aCell;
      var childXMLelement;
      var XMLelement = ajx.AJXresponseXML.getElementsByTagName(repeatedElement);
      var aTable = document.getElementById(idTable);
      
      if (clearTable == "Y")
      {      
        if (aTable.rows.length > posrowsPosition)
        {
          var aLength = aTable.rows.length
          for(i=rowsPosition ; i < aLength; i++) 
          {          
            aTable.deleteRow(rowsPosition);
          }
        }
      }
  
      if (XMLelement.length == 0)
      {
        if (message != "")
        {
          alert(message);
        }
      }
      else
      {      
        for(i=0 ; i < XMLelement.length ; i++) 
        {
          childXMLelement = XMLelement[i].childNodes;        
          aRow = aTable.insertRow(aTable.rows.length);
          var k = 0;
          for(j=0 ; j < childXMLelement.length ; j++) 
          {
            if (childXMLelement[j].nodeType==1)
            {
              aCell = aRow.insertCell(k);            
              if (childXMLelement[j].firstChild!=null)
              {
                aCell.innerHTML = childXMLelement[j].firstChild.nodeValue;
              }
              else
              {
                aCell.innerHTML = "&nbsp;";
              }
              k++;
            }
          }
        }
        eval(functionAfterExecution);
      }
      eval(functionAlwaysExecuted);
    }
  }  

  /**
   * AJXupdateTableRow()
   * Update rows in a table with values from a xml element. Each repeated child 
   * represents a table row, and each child in repeated element, represents a 
   * table cell.
   * 
   * Parameters:
   *  - url: url to submition. (required)
   *  - form: submited form if html form method is "post". (optional)
   *   - repeatedElement: xml repeated tag. (required)
   *  - idTable: id of HTML table tag to update row. (required)
   *  - rowKey: table column(s) index(es) used as a unique identifier(s) of a table row.
   *        Case the "key" have more then one column, the values must be separated by commas.
   *        For example: rowKey="2" or rowKey="1,3,5".  
   *  - message: message showed if not found any "repeatedElement" tag. (optional)
   *  - functionAfterExecution: function called after execution of AJXaddTableRow() method, if exists some "repeatedElement" tag. (optional)
   *  - functionAlwaysExecuted: function always called after execution of AJXaddTableRow() method. (optional)
   *
   * Expected XML element in AJXresponseXML:
   *
   *  <root (repeatedElement*)>
   *    <repeatedElement(child1old, child2old, ... ,childNold)>
   *    <repeatedElement(child1new, child2new, ... ,childNnew)>   
   *    ...
   *  </root>
   *
   */   
  function AJXupdateTableRow(url, form, repeatedElement, idTable, rowKey, message, functionAfterExecution, functionAlwaysExecuted)
  {
    if (!util.AJXvalidateRequired(url, repeatedElement, idTable, rowKey))
    {
      return false;
    }
    
    if (!AJXexecuting && ajx.AJXresponseXML==null)
    {
      AJXexecuting = true;
      executeMethod = "AJXupdateTableRow(\""+url+"\",\""+form+"\",\""+repeatedElement+"\",\""+idTable+"\",\""+rowKey+"\",\""+message+"\",\""+functionAfterExecution+"\",\""+functionAlwaysExecuted+"\")";
      ajx.AJXload(url,this,executeMethod,form);
      AJXexecuting = false;
      executeMethod = "";
    }
    
    if (!AJXexecuting && ajx.AJXresponseXML!=null)
    {  
      var aTable;
      var childXMLelement;
      var XMLelement = ajx.AJXresponseXML.getElementsByTagName(repeatedElement);    
      var aTable = document.getElementById(idTable);
      var aIndex;
      var aExecute;
      var aHtml;
      
      if (XMLelement.length == 0)
      {
        if((message!= "undefined") && (message != ""))
        {
          alert(message);
        }
      }
      else
      {    
        aKeys = util.AJXtokenizer(rowKey,',');
        aBiggerKey = 0;
        for(k=0 ; k < aKeys.length ; k++) 
        {  
          if (aKeys[k] > aBiggerKey) 
          {
            aBiggerKey = aKeys[k];
          }
        }
        
        for(i=0 ; i < XMLelement.length ; i+=2) 
        {
          childXMLelement = XMLelement[i].childNodes;
          
          for(j=0 ; j < aTable.rows.length ; j++) 
          {  
            aExecute = false;        
            var k = new Number(0);
            
            if (navigator.appName == "Netscape")
            {
              k=1;
            }
  
            for(y=0 ; y < aKeys.length ; y++) 
            {    
              if (aTable.rows[j].cells.length - 1 >= aBiggerKey)
              {
                if (childXMLelement[(parseInt(aKeys[y],10)+k)].nodeType==1)
                {
                    aHtml = aTable.rows[j].cells[aKeys[y]].innerHTML;
                  aHtml = aHtml.replace(/\n/gi, "");

                  if (util.AJXtrim(aHtml) == childXMLelement[(parseInt(aKeys[y],10)+k)].firstChild.nodeValue)
                  {        
                    aExecute = true;
                    aIndex = j;
                  }
                  else
                  {
                    aExecute = false;
                    aIndex = null;
                  }                
                }
                else
                {
                  k++;
                  y--;
                }
              }
            }

            if (aExecute) 
            {
              childXMLelement = XMLelement[i+1].childNodes;
              var k = new Number(0);
              
              for (x=0 ; x < aTable.rows[aIndex].cells.length; x++)
              {
                if (childXMLelement[x+k].nodeType==1)
                {  
                  
                  aTable.rows[aIndex].cells[x].innerHTML = childXMLelement[x+k].firstChild.nodeValue;
                }
                else
                {
                  k++;
                  x--;
                }
              }            
              aIndex=null;
            }
          }
        }
        eval(functionAfterExecution);
      }
      eval(functionAlwaysExecuted);
    }
  }
  
  /**
   * AJXremoveTableRow()
   * Remove rows from a table with values from a xml element. Each repeated child 
   * represents a table row, and each child in repeated element, represents a 
   * table cell.
   * 
   * Parameters:
   *  - url: url to submition. (required)
   *  - form: submited form if html form method is "post". (optional)
   *   - repeatedElement: xml repeated tag. (required)
   *  - idTable: id of HTML table tag to remove row. (required)
   *  - rowKey: table column(s) index(es) used as a unique identifier(s) of a table row.
   *        Case the "key" have more then one column, the values must be separated by commas.
   *        For example: rowKey="2" or rowKey="1,3,5".  
   *  - message: message showed if not found any "repeatedElement" tag. (optional)
   *  - functionAfterExecution: function called after execution of AJXaddTableRow() method, if exists some "repeatedElement" tag. (optional)
   *  - functionAlwaysExecuted: function always called after execution of AJXaddTableRow() method. (optional)
   *
   * Expected XML element in AJXresponseXML:
   *
   *  <root (repeatedElement*)>
   *    <repeatedElement(child1, child2, ... ,childN)>   
   *    ...
   *  </root>
   *
   */   
  function AJXremoveTableRow(url, form, repeatedElement, idTable, rowKey, message, functionAfterExecution, functionAlwaysExecuted)
  {
    if (!util.AJXvalidateRequired(url, repeatedElement, idTable, rowKey))
    {
      return false;
    }
    
    if (!AJXexecuting && ajx.AJXresponseXML==null)
    {
      AJXexecuting = true;
      executeMethod = "AJXremoveTableRow(\""+url+"\",\""+form+"\",\""+repeatedElement+"\",\""+idTable+"\",\""+rowKey+"\",\""+message+"\",\""+functionAfterExecution+"\",\""+functionAlwaysExecuted+"\")";
      ajx.AJXload(url,this,executeMethod,form);
      AJXexecuting = false;
      executeMethod = "";
    }
    
    if (!AJXexecuting && ajx.AJXresponseXML!=null)
    {
      var aTable;
      var childXMLelement;
      var XMLelement = ajx.AJXresponseXML.getElementsByTagName(repeatedElement);
      var aTable = document.getElementById(idTable);
      var aIndex;
      var aExecute;
      var aHtml;
      
      if (XMLelement.length == 0)
      {
        if((message!= "undefined") && (message != ""))
        {
          alert(message);
        }
      }
      else
      {  
        aKeys = util.AJXtokenizer(rowKey,',');
        aBiggerKey = 0;
        
        for(k=0 ; k < aKeys.length ; k++) 
        {  
          if (aKeys[k] > aBiggerKey) 
          {
            aBiggerKey = aKeys[k];
          }
        }
        
        for(i=0 ; i < XMLelement.length ; i++) 
        {
          childXMLelement = XMLelement[i].childNodes;
  
          for(j=0 ; j < aTable.rows.length ; j++) 
          {
            aExecute = false;
            var k = new Number(0);
            
            if (navigator.appName == "Netscape")
            {
              k=1;
            }
  
            for(y=0 ; y < aKeys.length ; y++) 
            {    
              if (aTable.rows[j].cells.length - 1 >= aBiggerKey)
              {
                if (childXMLelement[(parseInt(aKeys[y],10)+k)].nodeType==1)
                {                
                    aHtml = aTable.rows[j].cells[aKeys[y]].innerHTML;
                  aHtml = aHtml.replace(/\n/gi, "");
                                  
                  if (util.AJXtrim(aHtml) == childXMLelement[(parseInt(aKeys[y],10)+k)].firstChild.nodeValue)
                  {        
                    aExecute = true;
                    aIndex = j;
                  }
                  else
                  {
                    aExecute = false;
                    aIndex = null;
                  }                
                }
                else
                {
                  k++;
                  y--;
                }
              }
            }
  
            if (aExecute) 
            {    
              aTable.deleteRow(aIndex);
              aIndex=null;
            }
          }
        }      
        eval(functionAfterExecution);
      }
      eval(functionAlwaysExecuted);
    }
  }  
  
  /**
   * AJXgetResponseText()
   * Returns the responseText from XMLHttpRequest object
   * 
   * Parameters:
   *  - url: url to submition. (required)
   *  - form: submited form if html form method is "post". (optional)
   *
   */
  function AJXgetResponseText(url, form)
  {
    if (!util.AJXvalidateRequired(url))
    {
      return false;
    }
    
    executeMethod = "";
    ajx.AJXload(url,this,executeMethod,form,false,false);

    return ajx.AJXresponseText;
  }      

  /**
   * AJXgetResponseXML()
   * Returns the responseXML from XMLHttpRequest object
   * 
   * Parameters:
   *  - url: url to submition. (required)
   *  - form: submited form if html form method is "post". (optional)
   *
   */
  function AJXgetResponseXML(url, form)
  {
    if (!util.AJXvalidateRequired(url))
    {
      return false;
    }
    
    executeMethod = "";
    ajx.AJXload(url,this,executeMethod,form,false);

    return ajx.AJXresponseXML;
  }      
  
  /**
   * AJXfillDiv()
   * Fills a DIV tag with responseText from XMLHttpRequest object
   * 
   * Parameters:
   *  - url: url to submition. (required)
   *  - form: submited form if html form method is "post". (optional)
   *  - idDiv: id of tag DIV to fill. (required)   
   *  - appendDiv: if true, append the responseText in DIV tag. Otherwise, 
   *               overwrite the DIV tag with responseText. (optional)
   *
   */
  function AJXfillDiv(url, form, idDiv, appendDiv)
  {
    if (!util.AJXvalidateRequired(url, idDiv))
    {
      return false;
    }
    
    executeMethod = "";
    ajx.AJXload(url,this,executeMethod,form,false,false);
    
    var aDiv = document.getElementById(idDiv);
    
    if (aDiv != null)
    {    
      if (appendDiv!=true)
      {
        aDiv.innerHTML = ajx.AJXresponseText;
      }
      else
      {
        aDiv.innerHTML += ajx.AJXresponseText;
      }        
    }
    else
    {
      alert("AJX Tools: DIV tag not found!");
    }
  }      

  /**
   * AJXcleanDiv()
   * Clean the DIV tag
   * 
   * Parameters:
   *  - idDiv: id of tag DIV to clean. (required)   
   *
   */
  function AJXcleanDiv(idDiv)
  {
    if (!util.AJXvalidateRequired(idDiv))
    {
      return false;
    }    
    
    var aDiv = document.getElementById(idDiv);
    
    if (aDiv != null)
    {    
      aDiv.innerHTML = "";
    }
    else
    {
      alert("AJX Tools: DIV tag not found!");
    }
  }        
  
  /**
   * AJXautoComplete()
   * Fills a DIV tag with responseText from XMLHttpRequest object
   * 
   * Parameters:  
   *  - url: url to submition. (required)
   *  - form: submited form if html form method is "post". (optional)
   *  - fieldName: name of the HTML input text tag. (required)   
   *   - repeatedElement: xml repeated tag. (required)
   *   - textTag: xml tag containing the text to select. (required) 
   *  - evt: reference to the keyboard event.(required)
   *  - userStyle: css style user defined. Cannot be defined the follow 
   *               properties: position, left, width, top, overflow. (optional)
   *         i.e.: userStyle = "border: 1px solid #000000;background:red;"
   *
   */
  function AJXautoComplete(url, form, fieldName, repeatedElement, textTag, evt, userStyle)
  {    
    if (!util.AJXvalidateRequired(url, repeatedElement, fieldName, textTag, evt))
    {
      return false;
    }

      var objName = document.getElementsByName(fieldName)[0];
    var txt = objName.value;
    var T = util.AJXfindPosY(objName) + objName.offsetHeight -1; //top
    var L = util.AJXfindPosX(objName); //left
    var W = objName.offsetWidth -1; //width
    var defaultCss = "position:absolute;left:"+L+";width:"+W+";top:"+T+";border: 1px solid #000000;display:block";  
    var cmb = document.getElementById("AJXselect");
    var childXMLelement;
    var XMLelement;
            
    executeMethod = "";
    ajx.AJXload(url,this,executeMethod,form,false);
    XMLelement = ajx.AJXresponseXML.getElementsByTagName(repeatedElement);
    
    objName = null
      objName = document.getElementsByName(fieldName)[0];
    objName.value = txt;  
    objName.focus();      
    
    if (XMLelement.length!=0)
    {
      if (cmb==null)
      {        
        var objParent = objName.parentNode;
        cmb = document.createElement("select");
        objParent.appendChild(cmb);
        cmb.setAttribute("id", "AJXselect");
        cmb.setAttribute("size", "5");
        cmb.style.cssText=defaultCss;
        cmb.onblur = function()
          {
            destroyCmb();
            objName.focus();
          }
        cmb.onclick = function()
          {
            selection();
            objName.focus();
          }
        cmb.onkeyup = function()
          {
            if (evt.keyCode==13)
            {
              selection();
              objName.focus();
            }      
            if (evt.keyCode==27)
            {
              destroyCmb();
              objName.focus();
            }          
          }
      }
            
      for(j=cmb.length; j >= 0 ; j--) 
      {
        cmb.remove(j);
      }    
            
      for(i=0 ; i < XMLelement.length ; i++) 
      {
        opt = document.createElement("option");
        opt.text = XMLelement[i].getElementsByTagName(textTag)[0].firstChild.data; 
        opt.value = XMLelement[i].getElementsByTagName(textTag)[0].firstChild.data; 
  
        try 
        {
          cmb.add(opt, null); // standards compliant; doesn't work in IE
        }
        catch(ex) 
        {
          cmb.options.add(opt); // IE only
        }    
      }
    
      if (cmb.style.display == "none")
      {        
        cmb.style.display="block";
      }
      
      cmb.value = "";
  
      if (evt.keyCode==27)
      {
        destroyCmb();
      }
  
      if (evt.keyCode==40)
      {
        cmb.focus();
        cmb.options[0].selected=true;
      }
    }
    else
    {
      destroyCmb();
    }
    
    function selection()
    {      
      var txt = cmb.options[cmb.selectedIndex].value;
      objName.value = txt;
      destroyCmb();
    }    
    
    function destroyCmb()
    {      
        var objName = document.getElementById("AJXselect");
        
      for(j=objName.length; j >= 0 ; j--) 
      {
        objName.remove(j);
      }  
      objName.style.display="none";
    }    
  }          
}

/*******************************************************************************
 * AJXutil()
 * AJX Tools util class.
 *
 ******************************************************************************/
function AJXutil()
{
  this.AJXvalidateRequired = AJXvalidateRequired;
  this.AJXgetObjectName = AJXgetObjectName;
  this.AJXgetFormValues = AJXgetFormValues;
  this.AJXshowMessage = AJXshowMessage;
  this.AJXexistsCssClass = AJXexistsCssClass;
  this.AJXtokenizer = AJXtokenizer;
  this.AJXtrim = AJXtrim;
  this.AJXRTrim = AJXRTrim;
  this.AJXLTrim = AJXLTrim;
  this.AJXfindPosX = AJXfindPosX;
  this.AJXfindPosY = AJXfindPosY;
  
  /**
   * AJXfindPosX()
   * Find the horizontal position of a HTML object in relation to the left edge 
   * of the screen.
   *
   * Parameters:
   *   - obj: reference to the object. (required)
   *
   * Return:
   *   - a numeric value with the horizontal position of a HTML object.
   *
   */     
  function AJXfindPosX(obj)
  {      
     var curleft = 0;
     if (obj.offsetParent)
     {
         while (obj.offsetParent)
         {
             curleft += obj.offsetLeft;
             obj = obj.offsetParent;
         }
     }
     return curleft;
  }
  
  /**
   * AJXfindPosY()
   * Find the vertical position of a HTML object in relation to the top edge 
   * of the screen.
   *
   * Parameters:
   *   - obj: reference to the object. (required)
   *
   * Return:
   *   - a numeric value with the vertical position of a HTML object.
   *
   */       
  function AJXfindPosY(obj)
  {
     var curtop = 0;
     if (obj.offsetParent)
     {
         while (obj.offsetParent)
         {
             curtop += obj.offsetTop;
             obj = obj.offsetParent;
         }
     }
     return curtop;
  }    

  /**
   * AJXvalidateRequired()
   * Verifies if the fields are not null or not empty.
   *
   * Parameters:
   *   - arguments: all required arguments separated by commas. (required)
   *
   * Return:
   *   - true: all required fields are not null and not empty.
   *   - false: exist a required field null or empty.
   *
   */   
  function AJXvalidateRequired()
  {
    for (i=0; i<arguments.length; i++)
    {    
      if ((arguments[i]==null) || 
        ((typeof(arguments[i])!="object")&&(AJXtrim(arguments[i])=="")))
      {
        alert("AJX Tools: Argument required in function " + AJXgetObjectName(AJXvalidateRequired.caller));
        return false;
      }
    }
    return true;
  }

  /**
   * AJXgetObjectName()
   * Returns a object ou function name.
   *
   * Parameters:
   *   - obj: objetct or function to get name. (required)
   *
   * Return:
   *   - String with the name of the function or object.
   *
   */   
  function AJXgetObjectName(obj)
  {
    var name = null;
    var func = null
    
    if (typeof(obj) == 'object')
    {
      func = obj.constructor.toString();
    }
    else if (typeof(obj) == 'function')
    {
      func = obj;
    }
    
    if (func != null)
    {
      var rule = new RegExp(/function\s+(\w+).*/g);
      var resp = rule.exec(func);
      name = resp[1];
    }    
    return name;
  }

  /**
   * AJXgetFormValues()
   * Transform all values of a form to "QueryString".
   * 
   * Parameters:
   *   - form: name of the submited form.
   *
   * Return:
   *   - string containing a "QueryString" value.
   *
   */
  function AJXgetFormValues(form)
  { 
    var str = ""; 

    for(var i = 0;i < document.forms[form].elements.length;i++)
    { 
      if (document.forms[form].elements[i].type == "checkbox") 
      {
        if (document.forms[form].elements[i].checked)
        {
          str += document.forms[form].elements[i].name + '=' + escape(document.forms[form].elements[i].value) + '&'; 
        }
      }
      else if (document.forms[form].elements[i].type == "select-multiple")
      {
        for(j=0; j < document.forms[form].elements[i].length; j++)
        {
          if (document.forms[form].elements[i].options[j].selected)
          {
            str += document.forms[form].elements[i].name + '=' + escape(document.forms[form].elements[i].options[j].value) + '&'; 
          }
        }      
      }      
      else
      {
        str += document.forms[form].elements[i].name + '=' + escape(document.forms[form].elements[i].value) + '&'; 
      }
    } 
    str = str.substr(0,(str.length - 1)); 
    return str;
  }
  
  /**
   * AJXshowMessage()
   * Create a DIV tag and shows a message. 
   * The DIV tag style can be defined in CSS class named "div.AJXstyleMsg".
   * The default style is: 
   *    div.AJXstyleMsg { 
   *      position:absolute;
   *      right:0px;
   *      top:0px;
   *      color:white;
   *      background-color:red;
   *      font-family:verdana;
   *      font-weight:bold
   *    }
   *
   * Parameters:
   *   - msg: Message to show in DIV tag. (required)
   *
   * Return:
   *   - void
   *
   */
  function AJXshowMessage(msg)
  {
    var defaultCss = "";

    if (AJXexistsCssClass("AJXstyleMsg"))
    {  
      defaultCss = "class=AJXstyleMsg";        
    }
    else
    {
      defaultCss = "style='position:absolute;right:0px;top:0px;color:white;background-color:red;font-family:verdana;font-weight:bold'";
    }

    if (document.getElementById("AJXmessage")==null)
    {
      document.getElementsByTagName("body")[0].innerHTML += "<div id=AJXmessage "+defaultCss+"></div>";
    }

    document.getElementById("AJXmessage").innerHTML = msg;
  }  
  
  /**
   * AJXexistsCssClass()
   * Look for a css class in the stylesheets used in the current page.
   *
   * Parameters:
   *   - nameCssClass: name of the css class to find in stylesheets. (required)
   *
   * Return:
   *   - true: the class was found
   *   - false: the class wasn't found
   *
   */
  function AJXexistsCssClass(nameCssClass)
  {
    var classFound = false;

    if (document.styleSheets.length > 0)
    {
      for (j=0; j < document.styleSheets.length; j++)
      {
        if (navigator.appName == "Netscape")
        {
          objCssRules = document.styleSheets[j].cssRules;        
        }
        else
        {
          objCssRules = document.styleSheets[j].rules;
        }

        for (i=0; i < objCssRules.length; i++)
        {
          if (objCssRules[i].selectorText == nameCssClass)
          {
            classFound = true;
          }
        }          
      }        
    }
    return classFound;
  }  
  
  /**
   * AJXtokenizer()
   * Tokenize a string with the given separator.
   *
   * Parameters:
   *   - str: string to be tokenized (required)
   *   - saparator: string that separate the tokens into str. 
   *                Maximum size of separator is 1. (required)
   *
   * Return:
   *   - Array() containig the tokens
   *
   */  
  function AJXtokenizer(str,separator)
  {
    var tokens = new Array();
    indiceTokens = 0;
    pos = 0;
    fimStr = str.length;
    temToken = false

    for (i=0; i < fimStr; i++)
    {
      if(str.charAt(i) == separator)
      {
        temToken = true;
        tokens[indiceTokens] = str.substring(pos,i);
        pos = i + 1;
        indiceTokens++;
      }
    }

    if (temToken)
    {

      tokens[indiceTokens]=str.substring(pos,fimStr);
    }
    else
    {
      tokens[0] = str.substring(pos,i);
    }
    return tokens;
  }  
  
  /**
   * AJXtrim() 
   * Remove the white spaces before and after a string.
   *
   * Parameters:
   *   - str: string to remove the white spaces. (required)
   *
   * Return:
   *   - string without white spaces in the begining and in the end.
   *
   */
  function AJXtrim(str)
  {
    if(str.length < 1)
    {
      return"";
    }  
    str = AJXRTrim(str);
    str = AJXLTrim(str);

    if(str=="")
    {
      return "";
    }
    else
    {
      return str;
    }
  } 

  /**
   * AJXRTrim()
   * Remove the white spaces after a string.
   *
   * Parameters:
   *   - str: string to remove the white spaces. (required)
   *
   * Return:
   *   - string without white spaces in the end.
   *
   */   
  function AJXRTrim(str)
  {
    var w_space = String.fromCharCode(32);
    var w_space1 = String.fromCharCode(9);
    var v_length = str.length;
    var strTemp = "";

    if(v_length < 0)
    {
      return"";
    }
    var iTemp = v_length -1;

    while(iTemp > -1)
    {
      if((str.charAt(iTemp) != w_space)&&(str.charAt(iTemp) != w_space1))
      {
        strTemp = str.substring(0,iTemp +1);
        break;
      }
      iTemp = iTemp-1;
    } 
    return strTemp;
  } 

  /**
   * AJXLTrim()
   * Remove the white spaces before a string.
   *
   * Parameters:
   *   - str: string to remove the white spaces. (required)
   *
   * Return:
   *   - string without white spaces in the begining.
   *
   */   
  function AJXLTrim(str)
  {
    var w_space = String.fromCharCode(32);
    var w_space1 = String.fromCharCode(9);
    var v_length = str.length;
    var strTemp = "";
    var iTemp = 0;

    if(v_length < 1)
    {
      return "";
    }

    while(iTemp < v_length)
    {
      if((str.charAt(iTemp) != w_space)&&(str.charAt(iTemp) != w_space1))
      {
        strTemp = str.substring(iTemp,v_length);
        break;
      }
      iTemp = iTemp + 1;
    } 
    return strTemp;
  }   
  
}
           
         
  








Related examples in the same category

1.Ajax toolkits
2.Library for development
3.Development library
4.ajax dynamic content
5.ajax dynamic pages