/*
Select dropdown control script
(c) 2010, Anton Pleshivtsev
*/
function Select(divid,text,listData,selected, input_name, options){
  this.id=divid;
  this.data=listData; 
  this.text=text;
  this.selected=selected;
  this.input_name=input_name;
  this.opened=false; 
  this.create();
  this.options = {localSearch:false, loadMore: null, addNew: null,hasZero: false};
  if (options) this.options = options;
  this.updateData(selected);
  
}
Select.prototype.open=function(){
  $("#"+this.id+"list").show();
  this.opened=true;
}
Select.prototype.makeWidth=function(){  
  $("#"+this.id+'list').width(parseInt($("#"+this.id).width()));
}
Select.prototype.create=function(){
  var _this=this;
  $("#"+this.id).append("<img src='/tpl/img/dd.gif'><span id='"+this.id+"_text'>"+this.text+"</span><input type='hidden' value='0' id='"+this.id+"_val' name='"+this.input_name+"' >");
  $("#"+this.id).after("<div id='"+this.id+"list' class='selectlist'></div>");
  
  this.makeWidth();
  
  $("#"+this.id).click(function () { 
    //console.log(this);
    //console.log('1');
    
    $("#"+_this.id+"list").css("left",$(this).offset().left);
    $("#"+_this.id+"list").css("top",$(this).offset().top+20);
    
    if(!_this.opened){
      _this.open();
      
      $(document).click(function(e) {
        
        //console.log(e.pageX, ' : ', e.pageY);
      
        //var clicked = $(e.target);
        //alert(clicked.attr('class'));
        //console.log('click: ', clicked.attr('class'));
        var сe = $("#"+_this.id);
        var offset= сe.offset();
        var left_offset_position = offset.left;
        var top_offset_position = offset.top;
        var right_offset_position = offset.left+сe.width();
        var bottom_offset_position = offset.top + сe.height();
        if (e.pageX < left_offset_position || 
            e.pageX > right_offset_position || 
            e.pageY < top_offset_position ||
            e.pageY > bottom_offset_position) {
          $("#"+_this.id+"list").hide(); 
          _this.opened=false;
        }
      });
      /**/
      
    } else {
      $("#"+_this.id+"list").hide();
      _this.opened=false;
    }
  });
}
Select.prototype.putLocalSearch=function(){
  $('#'+this.id+'_text').html('<input onkeyup="'+this.id+'.localSearch();" id="'+this.id+'_searchText" style="width:155px;border:none;font-size:13px">');
  $('#'+this.id+'_searchText').focus();
  this.close();
}
Select.prototype.localSearch=function(){
  var text = $('#'+this.id+'_searchText').val();
  var _this = this;
  var re=new RegExp("("+text+")",'gi');
  var html='';
  
  if (!text) return;
  
  //console.log('serch: ',text);
  
  this.close();
  
  if (this.options.localSearch) {
    html+= "<div class='search' onclick='"+_this.id+".putLocalSearch();'>Поиск по списку</div>";
  }
  $.each(this.data, function(key, value) {
    var str = value['name'];
    if(str.match(re)) {
      str = str.replace(new RegExp("("+text+")",'gi'), "<b>$1</b>");
      html+="<div onclick='"+_this.id+".set("+key+")'>"+str+"</div>";
    }
  });
  $("#"+this.id+"list").html(html);
  this.open();
}
Select.prototype.addNew=function(){
}
Select.prototype.updateData=function(selected){
  var _this=this;
  var html='';
  var first = false;
  //$('#'+_this.id+'_text').html(this.data.pop()['name']);
  
  //console.log(this.data);
  if (this.options.loadMore) {
    html+= "<div class='search' onclick='"+this.options.loadMore+"'>Загрузить все</div>";
  }
  
  if (this.options.localSearch) {
    html+= "<div class='search' onclick='"+_this.id+".putLocalSearch();'>Поиск по списку</div>";
  }
  
  if (this.options.addNew) {
    html+= "<div class='search' onclick='"+_this.id+".addNew();'>Добавить вариант</div>";
  }

  if (this.options.hasZero) {
    //this.data[0] = {"id":"0","name":'Не указано'};
    html+= "<div class='search' onclick='"+_this.id+".set(0);'>Не указано</div>";
  }
  
  if (this.data) {
    $.each(this.data, function(key, value) { 
      
      if(_this.options.hasZero && !first){
        $('#'+_this.id+'_text').html("Ничего не выбрано");
        $('#'+_this.id+'_val').val(0);
        first = true;
      }
      
      if (!first){
        var text = value['name'];
        if (text.length > 17) text = value['name'].substring(0,17)+'...';
        $('#'+_this.id+'_text').html(text);
        $('#'+_this.id+'_val').val(key);
        first = true;
      }
      
      if (key == _this.selected) {
        var text = value['name'];
        if (text.length > 17) text = value['name'].substring(0,17)+'...';
        $('#'+_this.id+'_text').html(text);
        $('#'+_this.id+'_val').val(_this.selected);
      }
      html+="<div onclick='"+_this.id+".set("+key+")'>"+value['name']+"</div>";
    });
  } else {
    $('#'+_this.id+'_text').html('Список пуст');
    $('#'+_this.id+'_val').val(0);
  }
  $("#"+_this.id+"list").html(html);
  
  _this.makeWidth();
}
Select.prototype.set=function(val){
  if(val) {
    $("#"+this.id+"_val").attr("value",val);
    var text = (typeof(this.data[val]) != 'undefined')? this.data[val]['name'] : 'Загрузите все';
    //if (text.length > 17) text = this.data[val]['name'].substring(0,17)+'...';
    if (text.length > 17) text = text.substring(0,17)+'...';
    $("#"+this.id+"_text").html(text);
  } else {
    $("#"+this.id+"_val").attr("value",0);
    $("#"+this.id+"_text").html("Ничего не выбрано");
  }
  this.close();
  this.clbk(val);
}
Select.prototype.close=function(){
  $("#"+this.id+"list").hide();
  this.opened=false;
}
Select.prototype.clbk=function(val){
  //alert(val);
}

