// load jquery
document.write("<script type='text/javascript' src='/xtenit/jscripts/jquery.js'></script"+">");

var autofill = {
   textfield : "",                     //id of textfield with # prefix
   textfieldval : "",                  //value of the textfield
   autofillul : "",                    //id of ul with # prefix
   autofilllist : new Array(),         //list of li 
   currentselected : -1,               //current selected for the use of up down arrows
   event : "",
   isLoaded : false,
   xhrtimeout : new XMLHttpRequest(),  //xhr request for aborting

   init : function(fieldid) {
      // get textfield id and generate ul id from that id
      this.textfield = "#"+fieldid;
      this.autofillul = "#"+fieldid+"-autofilllist";

      // add ul for autofilling
      document.write("<ul id='"+fieldid+ "-autofilllist' style='border:1px solid #999; float:left; position:absolute; margin:0; padding:0; display:none; z-index:1000;'></ul>");

      // let the window load first, to ensure that the list would be properly loaded
      window.onload = function() {

         // convert s to camel case
         function rzCC(s){
           for(var exp=/-([a-z])/; exp.test(s); s=s.replace(exp,RegExp.$1.toUpperCase()));
           return s;
         };

         // this fixes the problem for the font-size on IE
         function getStyle(e,a){
           var v=null;
           if(document.defaultView && document.defaultView.getComputedStyle){
             var cs=document.defaultView.getComputedStyle(e,null);
             if(cs && cs.getPropertyValue) v=cs.getPropertyValue(a);
           }
           if(!v && e.currentStyle) v=e.currentStyle[rzCC(a)];
           return v;
         };

         // add css
         $(autofill.autofillul).css({ 
            left : $(autofill.textfield).position().left,
            width : $(autofill.textfield).width(),
            top : $(autofill.textfield).position().top + $(autofill.textfield).height() + 8,
            fontFamily : $(autofill.textfield).css("fontFamily"),
            fontSize : getStyle($(autofill.textfield).get(0),'font-size')
         });

         //alert($(autofill.textfield).get(0).style.fontSize);
         //alert(document.defaultView.getComputedStyle($(autofill.textfield).get(0), null).fontSize);

         $(window).resize(function() {
            // add css
            $(autofill.autofillul).css({ 
               left : $(autofill.textfield).position().left,
               top : $(autofill.textfield).position().top + $(autofill.textfield).height() + 8
            });
         });

         // add extra events
         $("*").bind("mousedown", function(event) {
            $(autofill.autofillul).hide();
            autofill.event = "";
            autofill.currentselected = -1;
         });

         // make sure to show list if existing on mousedown or focus on textfield
         $(autofill.textfield).focus(function(event) {
            autofill.showHiddenList();
         });

         autofill.isLoaded = true;
         if(autofill.autofilllist.length > 0) {
            $(autofill.autofillul).show();
            $(autofill.textfield).focus();            
         }
      };
      // setup keyup event
      $(autofill.textfield).keyup(function(event) {

         // if keycode is up, down or enter
         if(event.keyCode == 38 || event.keyCode == 40 || event.keyCode == 13) {
            if(autofill.event == "mouse") {
               try {
                  for(var i=0; i<autofill.autofilllist.length; i++) {
                     $(autofill.autofilllist[i].li).css({ background:"white", color:"black" });
                  }
               } catch(e) { }
            }

            autofill.event = "key";

            // check if list has a value
            if(autofill.autofilllist.length > 0) {

               // if key up
               if(event.keyCode == 38) {
                  autofill.showHiddenList();
                  autofill.currentselected--;
                  
                  // clear previous selection
                  try {
                     $(autofill.autofilllist[autofill.currentselected+1].li).css({ background:"white", color:"black" });
                  } catch(e) {
                  }

                  // select a word
                  if(autofill.currentselected > -1) {
                     autofill.selectWord();
                  }
                  // show default keyword if selection is out of bounds
                  else if(autofill.currentselected == -1) {
                     $(autofill.textfield).val(autofill.textfieldval);
                  }
                  // show from the bottom
                  else {                    
                     autofill.currentselected = autofill.autofilllist.length-1;
                     autofill.selectWord();
                  }
               }
               // if key down
               else if(event.keyCode == 40) {
                  autofill.showHiddenList();
                  autofill.currentselected++;

                  // clear previous selection
                  try {
                     $(autofill.autofilllist[autofill.currentselected-1].li).css({ background:"white", color:"black" });
                  } catch(e) {
                  }
                  // select a word
                  if(autofill.currentselected < autofill.autofilllist.length) {
                     autofill.selectWord();                
                  }
                  // show default keyword if selection is out of bounds
                  else if(autofill.currentselected == autofill.autofilllist.length) {
                     $(autofill.textfield).val(autofill.textfieldval);               
                  }
                  // show from the bottom
                  else {                     
                     autofill.currentselected = 0;                    
                     autofill.selectWord(); 
                  }
               }
               else {
                  autofill.removeAllKeywords();                  

                  // submit form by clicking button, this needs to be done for IEs sake
                  $(autofill.textfield).parents("form").find("input[type='submit']").eq(0).click();
               }               
            }
         
            // always return focus on text field
             $(autofill.textfield).focus();
         }
         else {
            // abort currently called ajax
            try {
               autofill.xhrtimeout.abort();
            } catch(e) {
            }         

            // get the value of the text field
            autofill.textfieldval = $(autofill.textfield).val();

            // remove all keywords
            autofill.removeAllKeywords();
            
            // check if text has value
            if(autofill.textfieldval.replace(" ", "").length > 0) {
               // run ajax
               autofill.searchKeyword();
            }
         }
      });

   },

   selectWord : function() {     
      $(autofill.autofilllist[autofill.currentselected].li).css({ background:"#5598d7", color:"white" });
      $(autofill.textfield).val(autofill.autofilllist[autofill.currentselected].word);
   },

   addKeywordToList : function(keyword) {
      var keywordtemp = document.createElement("li");

      //remove white spaces in front and back
      function trim(str, chars) {
	      return ltrim(rtrim(str, chars), chars);
      }
       
      function ltrim(str, chars) {
	      chars = chars || "\\s";
	      return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
      }
       
      function rtrim(str, chars) {
	      chars = chars || "\\s";
	      return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
      }      

      // add to li
      $(keywordtemp).html(keyword.replace(trim(autofill.textfieldval), "<strong>"+autofill.textfieldval+"</strong>"));

      // add css
      $(keywordtemp).css({ 
            margin:0,
            padding:"3px",
            border: "1px solid white",
            listStyleType:"none",
            background: "white"
      });

      // store li to autofilllist
      var newkeyword = {
         li : keywordtemp,
         word : keyword
      };

      autofill.autofilllist.push(newkeyword);
   },

   showHiddenList : function() {
      // show 
      if($(autofill.autofillul).css("display") == "none" && autofill.autofilllist.length > 0) {
         autofill.currentselected=-1;
         $(autofill.autofillul).show();
      }
   },

   addKeywordsToUL : function() {

      for(var i=0; i<autofill.autofilllist.length; i++) {
         var keywordtemp = autofill.autofilllist[i];

         // add css on mouseover
         $(keywordtemp.li).mouseover(function(event){
            try {
               for(var i=0; i<autofill.autofilllist.length; i++) {
                  $(autofill.autofilllist[i].li).css({ background:"white", color:"black" });
               }

               $(autofill.textfield).val(autofill.textfieldval);
            } catch(e) { }

            $(this).css({ background:"#5598d7", color:"white" });

            //search index
            for(var i=0; i<autofill.autofilllist.length; i++) {
               if(autofill.autofilllist[i].li == this) {
                  autofill.currentselected = i;
               }
            }
         });

         /*
         // add css on mouseout
         $(keywordtemp.li).mouseout(function(event){
            $(this).css({ background:"white", color:"black" });
            autofill.event = "";
            autofill.currentselected = -1;
         });
         */

         $(keywordtemp.li).unbind("mousedown");

         // add event on click
         $(keywordtemp.li).mousedown(function(event) {
            // put selected word on textfield
            $(autofill.textfield).val(autofill.autofilllist[autofill.currentselected].word);

            // hide list
            autofill.removeAllKeywords();

            // submit form
            $(autofill.textfield).focus();
            $(autofill.textfield).parents("form").find("input[type='submit']").eq(0).click();
         });

         // add keyword to list
         $(autofill.autofillul).append(keywordtemp.li);
      }   

      // show keywords
      if(autofill.isLoaded == true) {
         $(autofill.autofillul).show();
         $(autofill.textfield).focus();
      }
   },

   removeAllKeywords : function() {
      // clear values to defaults
      try {
         autofill.autofilllist = new Array();
         autofill.currentselected = -1;

         $(autofill.autofillul).contents().remove();
         $(autofill.autofillul).hide();

      } catch(e) {
        alert(e);
      }
   },

   searchKeyword : function() {

      // run ajax
      autofill.xhrtimeout = $.ajax({
         url: "/xsub/AutoFill",
         cache: true,
         type: "POST",
         data : { keyword : autofill.textfieldval },
         dataType : "xml",
         success: function(xmlDoc) {
            // remove all words again, repeated to ensure no overlapping results
            autofill.removeAllKeywords();

            try {
               // places word results on list
               if($(xmlDoc).find("keyword").length > 0) {

                  for(var i=0; i<$(xmlDoc).find("keyword").length; i++) {
                     var keyword = $(xmlDoc).find("keyword").eq(i).text();
                     autofill.addKeywordToList(keyword);
                  }   
                  
                  autofill.addKeywordsToUL();
                    
               }
            } catch(e) { 
            }
         },
         error : function(XMLHttpRequest, textStatus, errorThrown) {
           // alert(XMLHttpRequest+","+textStatus+","+errorThrown);
         }
      });
   }
};


