/*
 * jQuery selectbox plugin
 *
 * Copyright (c) 2007 Sadri Sahraoui (brainfault.com)
 * Licensed under the GPL license:
 *   http://www.gnu.org/licenses/gpl.html
 *
 * The code is inspired from Autocomplete plugin (http://www.dyve.net/jquery/?autocomplete)
 *
  * Version: 0.4
 * 
 * Changelog :
 *  - Fix width when the select is in a hidden div   @Pawel Maziarz
 *  - Add a unique id for generated li to avoid conflict with other selects and empty values @Pawel Maziarz
 */
jQuery.fn.extend({
 selectbox: function(options) {
  return this.each(function() {
   new jQuery.SelectBox(this, options);
  });
 }
});





var jQuerySelectboxIndexArray = new Array();
jQuery.SelectBox = function(selectobj, options) {
         
   var selectedID = selectobj.id;
   for(var m =0 ; m< jQuerySelectboxIndexArray.length; m++){            
        if(jQuerySelectboxIndexArray[m] == selectedID){               
         var xx= document.getElementById(selectedID + '_input')
           if(xx != null)
                return;
        }        
   }
   
    jQuerySelectboxIndexArray.push(selectedID);
   
 var opt = options || {};
 opt.inputClass = opt.inputClass || "selectbox";
 opt.containerClass = opt.containerClass || "selectbox-wrapper";
 opt.hoverClass = opt.hoverClass || "selected";
 opt.debug = opt.debug || false;
 
 var elm_id = selectobj.id;
 
 
 var close = false;
 var active = -1;
 var inFocus = false;
 var hasfocus = 0;
 //jquery object for select element
 var $select = $(selectobj);
 // jquery container object
 var $container = setupContainer(opt);
 //jquery input object 
 var $input = setupInput(opt);
 // hide select and append newly created elements
      var over = false;
 $select.hide().before($input).before($container);
 if(selectobj.disabled == true){
        $input.attr('disabled',true)
        $input.css('color','gray')
 }
 
 
 if(selectobj.onchange != null){
 
     var tx_change = selectobj.onchange.toString();
     
     if(tx_change.indexOf('__doPostBack') != -1 )
     {
  
         
           $input.attr('doPostback',true)
           $input.attr('cid',selectobj.id)
           
           $(selectobj).attr('onchange','');
     }
     
 
 }
 else
 { 
           // alert('no postback');
 }
 
 
 
 
 
 
 init();
 
   
 $input
 .click(function(){
 
 $container.hover(
             function()
             {
                // document.getElementById($container[0].id).style.background = 'red';
                 over = true;
                
                 return;
             },
             function()
             {
                //$container.focus();
              // document.getElementById($container[0].id).style.background = 'blue';
                 over = false
             });
 
 
 
            if (!inFocus) {
            if(selectobj.disabled != true)
        $container.toggle();                       
      }
    
 })
 .focus(function(){
    if(selectobj.disabled != true){
        if ($container.not(':visible')) {
            inFocus = true;
            $container.show();
        }
    }
 })
 .keydown(function(event) {    
  switch(event.keyCode) {
   case 38: // up
    event.preventDefault();
    moveSelect(-1);
    break;
   case 40: // down
    event.preventDefault();
    moveSelect(1);
    break;
   //case 9:  // tab 
   case 13: // return
    event.preventDefault(); // seems not working in mac !\      
    setCurrent($container.find('.selected').attr('id'));
    hideMe();
    break;
  }
 })
 .blur(function() {             
        var isOn = over;
  if ($container.is(':visible') && hasfocus > 0 ) {
   if(opt.debug) console.log('container visible and has focus')
  } else {
      
            if(isOn == false){                         
                setTimeout(hideMe,1000)                 
   }
  }
 }); 
 function hideMe() { 
     
     var x = $container;
     //document.getElementById($container[0].id).style.display = 'none';
  $container.hide(); 
 }
 
 function init() {
  $container.append(getSelectOptions($input.attr('id'))).hide();
  var width = $input.css('width');
  
  var item = $container.find('.selected').attr('id');
  
  var atr = $container.find('li');

  var i;
  for(var i=0; i< atr.length; i++){
      if(atr[i].className.indexOf('selected') != -1)
      break
  }

  active = i;
  
  
  //$container.width(width);
    }
 
 function setupContainer(options) {
  var container = document.createElement("div");
  $container = $(container);
  $container.attr('id', elm_id+'_container');
  $container.addClass(options.containerClass);
  return $container;
 }
 
 function setupInput(options) {
  var input = document.createElement("input");
  var $input = $(input);
  $input.attr("id", elm_id+"_input");
  $input.attr("type", "text");
  $input.addClass(options.inputClass);
  $input.attr("autocomplete", "off");
  $input.attr("readonly", "readonly");
  $input.attr("tabIndex", $select.attr("tabindex")); // "I" capital is important for ie
  
  return $input; 
 }
 
 function moveSelect(step) {
 
  var lis = $("li", $container);
  if (!lis) return;
  active += step;
  if (active < 0) {
   active = 0;
  } else if (active >= lis.size()) {
   active = lis.size() - 1;
  }
  lis.removeClass(opt.hoverClass);
  $(lis[active]).addClass(opt.hoverClass);
 }
 
 function setCurrent() {  
 

 
  var li = $("li."+opt.hoverClass, $container).get(0);
  var ar = (''+li.id).split('_');
  var el = ar[ar.length-1];
  $select.val(el);
        var html =$(li).html();
        html = html.replace('amp;', ''); 
  $input.val(html);
  $select.change();   
  return true;
 }
 
 var close = false;
 function setCurrent(id) { 
        
  var x = document.getElementById(id);
  var li = x;
  var ar = (''+li.id).split('_');
  var el = ar[ar.length-1];
  $select.val(el);
  var html = $(li).html();//replace('&amp', '')
  html = html.replace('amp;', ''); 
  $input.val(html);
  close = true;
     $container.toggle();
  try
        {
         $select.change();
        }
        catch(err)
        {

        }        
          if($input.attr('dopostback') != null)
     {
            
     if($input.attr('dopostback') == 'true'){
         var cid = $input.attr('cid');
         
         cid = cid.replace('_','$');
         cid = cid.replace('_','$');
//         alert(cid)
         __doPostBack(cid, '')
     }
     }
        
  return true;
 }
 // select value
 function getCurrentSelected() {

  return $select.val();
 }
 
 // input value
 function getCurrentValue() {
 
  return $input.val();
 }
 
 function getSelectOptions(parentid) {
  var select_options = new Array();
  var ul = document.createElement('ul');
  $select.children('option').each(function() {
   var li = document.createElement('li');
   li.setAttribute('id', parentid + '_' + $(this).val());
   li.innerHTML = $(this).html();
   if ($(this).is(':selected')) {
       var html = $(this).html()
    $input.val(html.replace('amp;', ''));
    $(li).addClass(opt.hoverClass);
   }
   ul.appendChild(li);
   $(li)
   .mouseover(function(event) {
    hasfocus = 1;
    if (opt.debug) console.log('out on : '+this.id);
    jQuery(event.target, $container).addClass(opt.hoverClass);
   })
   .mouseout(function(event) {
    hasfocus = -1;
    if (opt.debug) console.log('out on : '+this.id);
    jQuery(event.target, $container).removeClass(opt.hoverClass);
   })
   .click(function(event) {
    if (opt.debug) console.log('click on :'+this.id);
    
       
    setCurrent(this.id);
   
    hideMe();
   });
  });
  return ul;
 }
 
};
