/* 
          class: JAutoComplete
         author: rock.z.luo
        version: 1.0
           date: 2009-08-01
           
        summary: 基于jQuery的自动完成提示
     
      use class: jQuery, JAutoComplete_Hotels
 use global ver: none
  
        updated: ver, name, date, summary.
*/

function JAutoComplete(class_s)
{
  switch(class_s)
  {
    case 'Hotels': return new JAutoComplete_Flights();
          default: return new JAutoComplete_Flights();
  }
}/* function JAutoComplete(class_s) */

/* 转参数为Unicode编码 */
function strEncode(str){
	var unicode="";
	var len=str.length;
	for(var i=0;i<len;i++)
    {
		unicode+=str.charCodeAt(i);
		if(i<len-1)
			unicode+="_";
    }
    return unicode;
}

//---------------------------------------------------------------------------------------

/* 
          class: JAutoComplete_Flights
         author: rock.z.luo
        version: 1.0
           date: 2009-08-01
           
        summary: 基于jQuery的自动完成提示
     
      use class: jQuery
 use global ver: none
  
        updated: ver, name, date, summary.
        updated: ver, name, date, summary.
*/

JAutoComplete_Flights.prototype.main = JAutoComplete_Flights_main;

function JAutoComplete_Flights()
{  
  var this_ = this;
  
  //required
  this_.request_path  = ''; //files.ext?path=<value>
  
  this_.ele_o         = {};
  this_.ele_o.tbx_e   = undefined;
  
  //optional
  this_.ele_o.popup_e     = undefined;
  this_.var_name          = 'autocomplete_vacations';
  this_.popup_class_name  = 'JAutoComplete_Flights_popup_'; 
  this_.popup_width       = 0;
  this_.offset_o          = { left:0, top:0 };
  
  this_.submit_callback_f = undefined; 
  
  this_.x_o = {};
  this_.x_o.temp_result   = [];
  this_.x_o.dom_items_s   = [];
  this_.x_o.dom_tbx_e     = [];
  this_.x_o.current_index = -1; 
  
  this_.x_o.prev_data     = [];
  
}/* function JAutoComplete_Flights() */

/*  
    版本：2009-10-09
    作用：类的入口函数
必填参数：none
*/
function JAutoComplete_Flights_main()
{
  var this_ = this;
  
  this_.offset_o.left = this_.offset_o.left || 0;
  this_.offset_o.top  = this_.offset_o.top || 0;
  
  this_.ele_o.popup_e = $('<dl class="'+this_.popup_class_name+'"></dl>')
                        .appendTo('body')
                        .css({display:'none', position:'absolute'});
  
  this_.x_o.dom_tbx_e = this_.ele_o.tbx_e.get(0);
  
  var script_e    = document.createElement('script');
      script_e.id = this_.x_o.dom_tbx_e.id+'_cross_domain_e';
      document.body.appendChild(script_e);
      
  this_.ele_o.tbx_e.attr('autocomplete', 'off');
      
  $(window).resize
  (
    function()
    {
      var left_top_o = this_.ele_o.tbx_e.offset();
      this_.ele_o.popup_e.css
      (
        {
          left: left_top_o.left+this_.offset_o.left+'px'
          , top: left_top_o.top+this_.offset_o.top+this_.ele_o.tbx_e.height()+'px'
        }
      );
    }
  );
  
  //捕捉全局的点击事件
  $(document).click
  (
    function(evt)
    {
      var evt_e = evt.target||evt.srcElement;
      if(evt_e.id==this_.ele_o.tbx_e.id){ return true; }
        
      this_.ele_o.popup_e.css('display', 'none');      
      JAutoComplete_Flights_reset(this_);
          
    }
  );
  
  //捕捉全局的上下键
  $(document).keydown
  (
    function(evt)
    {
      if
      (
        (
          evt.keyCode===37
          ||evt.keyCode===38
          ||evt.keyCode===39
          ||evt.keyCode===40
        )&&this_.ele_o.popup_e.css('display')=='block'
      )
      {        
        //this_.x_o.dom_tbx_e.blur();
        this_.ele_o.popup_e.find('dd').removeClass('current_');
        var total_i = this_.x_o.dom_items_s.length;
        
        //向上移动
        if(evt.keyCode===37||evt.keyCode===38)
        {
          if(this_.x_o.current_index>0)
          { 
            this_.x_o.current_index--; 
          }
          else
          { 
            this_.x_o.current_index = total_i-1; 
          }
        }//向下移动
        else
        {
          if(this_.x_o.current_index>=(total_i-1))
          { 
            this_.x_o.current_index = 0; 
          }
          else
          { 
            this_.x_o.current_index++; 
          } 
        }/* if(evt.keyCode===37||evt.keyCode===38) */
        curr_i =  this_.x_o.current_index; 
        var current_e = this_.x_o.dom_items_s[this_.x_o.current_index];
        if(current_e)
        {
          current_e.onmouseover();
        }
        
         this_.ele_o.popup_e.find('dd.current_').each
        (
          function()
          {
        	  if('keywords'==this_.ele_o.tbx_e.attr("id")){
              o_areaID=this.getAttribute('id'); //attrr('value',o_areaID);
               $('#keywords_id').attr('value',o_areaID);//界面上在隐藏域中赋id
              }else if('city_to'==this_.ele_o.tbx_e.attr("id")){
            	//  r_areaID=this.getAttribute('id');
            	//   $('#city_to_va').attr('value',r_areaID);
              }else if('hotKeyStr'==this_.ele_o.tbx_e.attr("id")){
            	//  r_areaID=this.getAttribute('id');
              }
        	  this_.ele_o.tbx_e.val( this.getAttribute('value') );
          }
        );
        
      }/* end if */
      

      
      
      if(evt.keyCode===13&&this_.ele_o.popup_e.css('display')=='block')
      {
        this_.ele_o.popup_e.find('dd.current_').each
        (
          function()
          {
        	  if('keywords'==this_.ele_o.tbx_e.attr("id")){
            	 o_areaID=this.getAttribute('id'); //attrr('value',o_areaID);
            	 $('#keywords_id').attr('value',o_areaID);//界面上在隐藏域中赋id
              }else if('city_to'==this_.ele_o.tbx_e.attr("id")){
            	//  r_areaID=this.getAttribute('id');
            	//   $('#city_to_va').attr('value',r_areaID);
              }else if('hotKeyStr'==this_.ele_o.tbx_e.attr("id")){
            	//  r_areaID=this.getAttribute('id');
              }
              
        	  this_.ele_o.tbx_e.val( this.getAttribute('value') );
        	  this_.ele_o.popup_e.css( {display:'none'} );
        	  JAutoComplete_Flights_reset(this_);
          }
        );
      }
      
      return true;
    }
  );
  //响应文本框的回车事件
  this_.ele_o.tbx_e.keydown
  (
    function(evt)
    {
      if(evt.keyCode===13)
      {
        if(this_.ele_o.popup_e.css('display')=='block')
        {
          evt.preventDefault();
          
          return true;
        }
        else if(this_.ele_o.popup_e.css('display')=='none')
        {
          if( $.isFunction(this_.submit_callback_f) )
          {
            return this_.submit_callback_f(this_.x_o.dom_tbx_e, this_.ele_o.popup_e);
          }
        }
      }

    }
  );
  
  //响应用户输入
  this_.ele_o.tbx_e.keyup
  (
    inner_f
  );
  
  this_.ele_o.tbx_e.click
  (
    inner_f
  );
  curr_i=0;
  function inner_f(evt)
  {
    if(evt.keyCode===13)
    {
      return true;
    }
    
    if
    (
      (
        evt.keyCode===37
        ||evt.keyCode===38
        ||evt.keyCode===39
        ||evt.keyCode===40
      )
    ){ return true; }
          
    var tbx_value = this.value.replace(/^\s*|\s*$/g, '');
    var flag = (this.id=="keywords" || this.id=="city_to")?true:false;
    var is_chinese_b = /[\u4e00-\u9fa5]/.test(tbx_value);
    var request_value = strEncode(tbx_value);//$.browser.msie?encodeURIComponent(tbx_value):tbx_value;
    if( tbx_value.length===0 )
    {
      this_.ele_o.popup_e.css('display', 'none');
      JAutoComplete_Flights_reset(this_);
      return true;
    }
    
    script_cross_domain_f
    (
      false
      , flag?this_.request_path.replace(/<value>/gi, request_value+'&sq_x='+Math.random() ):this_.request_path.replace(/<value>/gi, $("#hotKeyStr").val()+'&sq_x='+Math.random() )
      , function(evt)
        {        
          if(typeof window[this_.var_name]=='undefined')
          {
            this_.ele_o.popup_e.css('display', 'none');
            
            JAutoComplete_Flights_reset(this_);
            
            return true; 
          }
          
          var left_top_o = this_.ele_o.tbx_e.offset();
          this_.ele_o.popup_e.html('');
          this_.ele_o.popup_e.css
          (
            {
              display:'block'
              , left: left_top_o.left+this_.offset_o.left+'px'
              , top: left_top_o.top+this_.offset_o.top+this_.ele_o.tbx_e.height()+5+'px'
            }
          );
            
          this_.ele_o.popup_e.html('');
          this_.ele_o.popup_e.append
          (
            format_f
            (
            //  "<dd class='title_ is_not_item_'>输入中文|拼音或↑↓选择</dd>"
            )
          );
          //update 0831
          all_j = window[this_.var_name];
          //没有返回数据
          if(window[this_.var_name].dest.length<=0)
          {
            this_.ele_o.popup_e.css('display', 'block');
            JAutoComplete_Flights_reset( this_ );
            if(this_.ele_o.tbx_e.val()!=""){
            
	            this_.ele_o.popup_e.append
	            (
	              format_f
	              (
	                  // "<dd class='no_items_'>输入错误,没有此出发城市</dd>"
	              )
	            );
            }
            return true; 
          }
          //for(var i=0, j=window[this_.var_name].dest.length; i<j; i++)
          if(window[this_.var_name].dest.length>10){
	          for(var i=0, j=10; i<j; i++)
	          {
	            var items_ = window[this_.var_name].dest[i];
	            this_.x_o.temp_result = items_.id;
	            var external_airport_s = 'no_class_';//items_.ischina?'no_class_':'external_';
	              this_.ele_o.popup_e.append
	              (
	                //<dd class="no_class_ cursor_" value="兴义" style="width: 180px;">
	                format_f
	                (
	                  "<dd id='{0}' class='{1}' value='{2}'><span>{3}{4}</span></dd>"
	                  , items_.id
	                  , external_airport_s
	                  , (items_.nm.indexOf('(')==-1)?items_.nm:items_.nm.substring(0,items_.nm.indexOf('('))
	                  , JAutoComplete_Flights_make_highlight_alphabet(items_, tbx_value)
	                  , JAutoComplete_Flights_make_highlight(items_.nm, is_chinese_b, false, items_, tbx_value)
	                )
	              );
	          }
          }else{         
            	var _keyReLeng ;
            	if(this_.ele_o.tbx_e.attr("id") == 'hotKeyStr'){
            		_keyReLeng  = window[this_.var_name].dest.length -1;
            	}else{
            		_keyReLeng  = window[this_.var_name].dest.length;
            	}
               
              for(var i=0, j=_keyReLeng; i<j; i++)
	          {
	            var items_ = window[this_.var_name].dest[i];
	           	this_.x_o.temp_result = items_.id;
	            var external_airport_s = 'no_class_';//items_.ischina?'no_class_':'external_';
	              this_.ele_o.popup_e.append
	              (
	                //<dd class="no_class_ cursor_" value="兴义" style="width: 180px;">
	                format_f
	                (
	                  "<dd id='{0}' class='{1}' value='{2}'><span>{3}{4}</span></dd>"
	                  , items_.id
	                  , external_airport_s
	                  , (items_.nm.indexOf('(')==-1)?items_.nm:items_.nm.substring(0,items_.nm.indexOf('('))
	                  , JAutoComplete_Flights_make_highlight_alphabet(items_, tbx_value)
	                  , JAutoComplete_Flights_make_highlight(items_.nm, is_chinese_b, false, items_, tbx_value)
	                )
	              );
	          }
	          
          }
          // 默认值

          
          var index_count = 0;
          this_.x_o.dom_items_s = [];
          
          var new_a = this_.ele_o.popup_e.find("dd").not('.is_not_item_')
          .each
          (
            function()
            { 
              var this__ = this;
                  this__.index_count = index_count++;                    
                  this_.x_o.dom_items_s.push(this__);
                  
              $(this).addClass('cursor_');
                                
              this.onmouseover = 
              function()
              {
                this_.ele_o.popup_e.find('dd').removeClass('current_');
                $(this).addClass('current_');
                this_.x_o.current_index = this.index_count; 
                curr_i = this.index_count; 
              };
              
              this.onmouseout = 
              function()
              {
                //$(this).removeClass('current_');
              };
              
              this.onclick =
              function(evt, arg_e)
              {
                var this__ = arg_e||this;
                this_.ele_o.popup_e.css('display', 'none');
				if('keywords'==this_.ele_o.tbx_e.attr("id")){
					o_areaID=this.getAttribute('id');
					$('#keywords_id').attr('value',o_areaID);//鼠标点击出发城市的时候把id值付给keywords_id
				}else if('city_to'==this_.ele_o.tbx_e.attr("id")){
					r_areaID=this.getAttribute('id');
					//$('#city_to_va').attr('value',r_areaID);
				}else if('hotKeyStr'==this_.ele_o.tbx_e.attr("id")){
					//k_areaID=this.getAttribute('id');
				}
                this_.ele_o.tbx_e.val( this.getAttribute('value') );
                JAutoComplete_Flights_reset( this_ );                  
              };
            }
          );
                  
          if( this_.popup_width )
          {
            this_.ele_o.popup_e.find("dd").each
            (
              function()
              {
                this.style.width = this_.popup_width+'px';
              }
            );
          }/* if( this_.popup_width ) */
          
          if(this_.x_o.dom_items_s[0])
          {
            this_.ele_o.popup_e.find('dd').removeClass('current_');
            this_.x_o.dom_items_s[0].onmouseover();
          }
          
          this_.x_o.prev_data = window[this_.var_name];
          window[this_.var_name] = undefined;            
          return true;
        }/* function() */
    );/* script_cross_domain_f */
    
  }/* function inner_f(evt) */
  
  return;
}/* function JAutoComplete_Flights_main() */

function JAutoComplete_Flights_reset( this_ )
{
  this_.x_o.temp_result = [];
  this_.x_o.dom_items_s = [];
  this_.x_o.current_index = -1;
}

function JAutoComplete_Flights_make_highlight(city_s, is_chinese_b, no_airport_b, items_, tbx_value)
{
  if(is_chinese_b)
  {  		  
  	city_s = city_s.replace( tbx_value,  '<label class="highlight_">'+tbx_value+'</label>');
    return city_s;
  }else{
	  return '';
  }
}

function JAutoComplete_Flights_make_highlight_alphabet(items_, tbx_value_s)
{
  var result_s = [];
  
  if( (!/[\u4e00-\u9fa5]/.test(tbx_value_s))&&items_.nm )
  {  		      
    var temp_re = new RegExp( '('+tbx_value_s+')', 'i' );
     
    result_s.push( items_.nm.replace(temp_re,  '<label class="highlight_">$1</label>') );    
  }
  
  return result_s.join('');
}

/*  
    版本: 2009-08-01
    作用: 脚本跨域函数
必填参数: script_e, path_s, callback_f
*/
function script_cross_domain_f(script_e, path_s, callback_f)
{/* rock.z.luo，void return，func:none */
  var remove_tag_b = false;
  if(typeof script_e==='string'){ script_e = document.getElementById(script_e); }
  if(!script_e){ document.body.appendChild( script_e = document.createElement('script') ); remove_tag_b = true; }
  if(!callback_f){ callback_f = function(){} };  
  script_e.onload = function(){ callback_f(); if(remove_tag_b){ script_e.parentNode.removeChild(script_e); } };  
  script_e.onreadystatechange = function(){ if(script_e.readyState=='loaded'){ callback_f(); if(remove_tag_b){ script_e.parentNode.removeChild(script_e); }} };
  script_e.src = path_s;
}/* function script_cross_domain_f(script_e, path_s, callback_f) */

function format_f(str_)
{/* rock.z.luo code, return string, func:none */
  var len_ = arguments.length, re_ = null, arg_o = arguments;  
  switch(len_)
  {
    case 0: return "";
    case 1: return str_;
  }
  for(var i=1, j=0; i<len_; i++, j++)
  {
    re_ = new RegExp(["\\{", j, "(\\:[a-zA-Z]|)}"].join(""), "g");
    str_ = str_
    .replace
    (
      re_, 
      function($0, $1)
      {
        var result_a = [arg_o[i]];
        
        switch($1)
        {
          case ":C":
          case ":c":
            result_a.unshift('¥');
            break;
        }
        
        return result_a.join('');
      }
    );
  }/* for(var i=1, j=0; i<len_; i++, j++) */ 
  return str_;
}/* function format_f(str_) */
