function createList(obj,id) {
   obj.id = id;
   obj.getWrap = function(elem) { 
       
       if (elem == undefined) 
        return jQuery(obj.id); 
       return jQuery(elem);
   };
   obj.Clean = function() { obj.getWrap().html('');};
}
function ControlListSelect(id) {   
    createList(this,id);        
}
ControlListSelect.prototype = {
    Append : function (elem) {              
        this.getWrap().append("<option value=" + elem.getPk() + ">" + elem.getName() + "</option>" );       
    },
    onClickElem : function(callback) {
        this.getWrap().change(callback);
    },
    checkElem : function() {                 
       return parseInt(this.getWrap().val());
    }
}

function ControlListDiv(id, checkall)  {
   createList(this,id);
   this.classActive = 'label_active';
   this.classDisActive = 'label_disactive';
   this.checkall = checkall;
   var self = this;
   this.getWrap(this.checkall).click(function() {        
       if ( self.getWrap(self.checkall).attr('checked') ) {
           self.getWrap().css('opacity','0.1')
           self.onCheckAll();
       } else {
           self.getWrap().css('opacity','1')           
       }
   });
   this.getWrap().click(function() {        
       if ( self.getWrap(self.checkall).attr('checked') ) {
           self.getWrap(self.checkall).attr('checked', false);
           self.getWrap().css('opacity','1');
       }               
   });
}
ControlListDiv.prototype = {
    onCheckAll : function() {},
    getPrefix : function(){ return this.id.substr(1);}, 
    Append : function (elem, isActive) {       
       isActive = (isActive == undefined) || (isActive == false) ? this.classDisActive : this.classActive; 
       return this.getWrap().append("<div id='" + elem.getPk() + this.getPrefix() + "' class='" + isActive + "'><label title='" + elem.name + "' >" + elem.getName() + "</label></div>");          
    },
    onClickElem : function(callback) {
       this.getWrap().children().bind("click",callback);
    },
    getElemPk : function(wrapElem){       
       return parseInt(wrapElem.attr('id'));
    },
    checkElem : function(elem) {                 
       elem = this.getWrap(elem);
       elemLabel = elem;              
       if (elemLabel.hasClass(this.classDisActive)) {
          elemLabel.removeClass(this.classDisActive).addClass(this.classActive);
       } else {
          elemLabel.removeClass(this.classActive).addClass(this.classDisActive);       
       }
       return this.getElemPk(elem);
    }
}

function Manager (arrEntity, control) {
    this._data = arrEntity;
    this._control = control;    
    this.getControl = function(){ return this._control;},
    this.getData = function(){ return this._data;}
    this.Rebuild = function (filter,filterChecked) {
        animLoad(this.getControl(),true);
        this._control.Clean();
        if (filter == undefined) 
            return true;
        var self = this;
        this.Foreach(function(item,elem){                   
            
            if ( (jQuery.inArray(elem.getParentId(),filter) != -1) || (filterChecked && jQuery.inArray(elem.getPk(),filterChecked) != -1)  ) {
                elem.isShow = true;
                self._control.Append( elem,(filterChecked != undefined && jQuery.inArray(elem.getPk(),filterChecked) != -1) );                            
            } else
                elem.isShow = false;
        });
        this.onRebuild();
        animLoad(this.getControl(),false);
    };
    this.AppendAll = function() {
        var self = this;
        this.Foreach(function(item,elem){                   
            if (elem.isShow) 
                self._control.Append(elem);
        });
    };
    this.Foreach = function(callback) {jQuery (this._data).each(callback); },
    this._Visible = function(arrPk,isShow) {        
        this.Foreach(function(item,elem){            
            if (jQuery.inArray(elem.getPk(),arrPk) != -1)
              elem.isShow = isShow;
        });                 
    };
    this.Show = function(arrPk){this._Visible(arrPk,true);},
    this.Hide = function(arrPk){this._Visible(arrPk,false);}
}

Manager.prototype = {
    onRebuild : function() {}
}
function Filter(params) 
{
   this._params = params;
   this.getParams = function() { return this._params; }
}
function createEntity(obj, id, name, isShow) 
{
   obj.id = id;
   obj.name = name;
   obj.getName = function() { return this.name; }
   obj.getPk = function() { return this.id; }
   obj.isShow = (isShow != undefined) ? isShow : false; 
}
function Country(id,name,isShow) 
{
   createEntity(this,id,name,isShow);
}
function Resort(id,name,countryId,isShow) 
{
   createEntity(this,id,name,isShow);
   this.countryId = countryId; 
   this.getParentId = function() { return this.countryId; }
   this.getName = function() { 
        var self = this;
       if (self.country_name == undefined) {
          jQuery(arrCountry).each (function(item,elem){
            if (self.countryId == elem.getPk())
                self.country_name = elem.name;
          }); 
       }
       return self.country_name + "<span class='raquo'>»</span>" + this.name; 
   }
}
function Hotel(id,name,resortId,isShow,nameRU) 
{
   createEntity(this,id,name,isShow);
   this.resortId = resortId;
   this.getParentId = function() { return this.resortId; }
   this.nameRU = nameRU;   
   this.getName = function() {        
       var self = this;
       if (self.resort_name == undefined) {
          jQuery(arrResort).each (function(item,elem){
            if (self.resortId == elem.getPk())
                self.resort_name = elem.name;
          }); 
       }
       return self.resort_name + "<span class='raquo'>»</span>" + this.name; 
   }
   this.getFormatItem = function() {        
       var self = this;
       if (self.resort_name == undefined) {
          jQuery(arrResort).each (function(item,elem){
            if (self.resortId == elem.getPk())
                self.resort_name = elem.name;
          }); 
       }
       return this.name + '<p style="margin:0; padding:0; color:#26A908; font-size:10px; float:right;">' + self.resort_name + '</p>';
   }
   this.getCountryId = function() {
       var self = this;
       if (self.countryId == undefined) {
          jQuery(arrResort).each (function(item,elem){
            if (self.resortId == elem.getPk())
                self.countryId = elem.countryId;
          }); 
       }
       return self.countryId;
   }
} 
function animLoad(elem,isShow) 
{
        if (isShow) {
            jQuery(elem).attr('style','background:url(/img/mwait.gif) 50% 0% no-repeat #FFFFFF ;');
        } else {
            jQuery(elem).attr('style','background: #FFFFFF;');
        }

}
function clone(o) {
    if(!o || "object" !== typeof o)  {
        return o;
    }
    varc = "function" === typeof o.pop ? [] : {};
    var p, v;
    for(p in o) {
        if(o.hasOwnProperty(p)) {
            v = o[p];
            if(v && "object" === typeof v) {
                cloneObj[p] = clone(v);
            }
        else cloneObj[p] = v;
        }
    }
    return cloneObj;
}
function TourSearch (arrHotel,arrResort,arrCountry,params) 
{    
    var self = this;
    // данные
    newArrHotel = new Array();
    var cntItem = 0;
    jQuery(arrHotel).each(function(item,elem){                      
                      cloneObj = new Object();  
                      elemRU = clone(elem);
                      elemRU.name = elemRU.nameRU
                      newArrHotel[cntItem++] = elem;
                      newArrHotel[cntItem++] = elemRU;
    });

    this.Hotel = new Manager(arrHotel,new ControlListDiv(params.control.list.hotel,params.control.checkall.hotel));    
    this.Resort = new Manager(arrResort,new ControlListDiv(params.control.list.resort,params.control.checkall.resort));
    this.Country = new Manager(arrCountry,new ControlListSelect(params.control.list.country));
    // фильтр
    this.filter = new Filter({country_id : [], resort_id: [], hotel_id : [], resort_name : []});        
    this.filter.toggleCountryId = function (id) {
        this.getParams().country_id = new Array();
        this.getParams().country_id.push(id);         
    }
    this.filter.toggleResortId = function (id) {         
        if (jQuery.inArray(id,this.getParams().resort_id) != -1) {
            var newArr = Array();
            jQuery(this.getParams().resort_id).each(function(item,elem){
                if (elem != id) newArr.push(elem);
            });
            this.getParams().resort_id = newArr;
        } else
            this.getParams().resort_id.push(id); 
    }
    this.filter.toggleHotelId = function (id) {
        if (jQuery.inArray(id,this.getParams().hotel_id) != -1) {
            var newArr = Array();
            jQuery(this.getParams().hotel_id).each(function(item,elem){
                if (elem != id) newArr.push(elem);
            });
            this.getParams().hotel_id = newArr;            
        } else
            this.getParams().hotel_id.push(id); 
    }
    // обработчики событий
    this.Hotel.getControl().onCheckAll = function() {
        self.filter.getParams().hotel_id = new Array();
        self.Hotel.Rebuild(self.filter.getParams().resort_id);
        self.HotelHandler();
    }
    this.Resort.getControl().onCheckAll = function() {
        self.filter.getParams().resort_id = new Array();
        self.Resort.Rebuild(self.filter.getParams().country_id);
        self.ResortHandler();
        self.Hotel.Rebuild(self.filter.getParams().resort_id);
        self.HotelHandler();
    }
    this.Hotel.onRebuild = function() {
        jQuery(params.control.search.hotel).setOptions({ data: newArrHotel });
    };
    this.CountryHandler = function() {
         var self = this;
         this.Country.getControl().onClickElem(function(){
            id = self.Country.getControl().checkElem();                                                
            self.filter.toggleCountryId(id);                                 
            self.filter.getParams().resort_id = new Array();
            self.filter.getParams().hotel_id = new Array();
            self.Resort.Rebuild(self.filter.getParams().country_id);                        
            self.ResortHandler(); 
            self.Resort.getControl().getWrap().click();            
            self.Hotel.Rebuild();
            self.Hotel.getControl().getWrap().click();
        }); 
     }    
    this.ResortHandler = function() {
         var self = this;
         this.Resort.getControl().onClickElem(function(){
            id = self.Resort.getControl().checkElem(this);                                                
            self.filter.toggleResortId(id);                       
            self.Hotel.Rebuild(self.filter.getParams().resort_id,self.filter.getParams().hotel_id);            
            self.HotelHandler();
        });
     }
    this.HotelHandler = function() {
         var self = this;
         this.Hotel.getControl().onClickElem(function(){                               
            id = self.Resort.getControl().checkElem(this);
            self.filter.toggleHotelId(id);
        });         
    }
    // поиск отелей
    jQuery(params.control.search.hotel).autocomplete(newArrHotel,{
        formatItem: function(item) {                                     
            if (jQuery.inArray(item.getCountryId(),self.filter.getParams().country_id) != -1) 
                return item.getFormatItem();
            return false;
        }
    }).result(function(event, item) {                                                                               
        self.filter.getParams().hotel_id.push(item.getPk());
        self.Hotel.Rebuild(self.filter.getParams().resort_id,self.filter.getParams().hotel_id);
        self.HotelHandler();
        self.Hotel.getControl().getWrap().click();        
        jQuery(params.control.search.hotel).val("");
    }); 
    
}
function doSearchResult(current,no_reset_page)
{
    if(!no_reset_page) jQuery("#m_page").val(0);           
    param = new Array();
    jQuery(pspo.filter.getParams().resort_id).each(function(iter,item){
        param.push("m[resort_id][]=" + item)
    });
    jQuery(pspo.filter.getParams().hotel_id).each(
    function(iter,item){
        param.push("m[hotel_id][]=" + item)
    });    
    jQuery("#hide_search_form").css('display','block');
    lockResult(); 
    if(!current) current='';           
        checkTourDate("#date_from_field_show","#date_from_field");
    jQuery.ajax({ url: "/tour_search/search",cache: false,type: "POST",
                  data: jQuery("#search_form").serialize()+ current + '&' + param.join('&'),
                  async: true,success: function(html) {                      
                        if(current) {
                            document.getElementById("search_result").innerHTML = html;                            
                        }
                        else {
                            document.getElementById("search_result").innerHTML = html;                            
                        }
                        jQuery('#link_short_form').attr('onClick','javascript: hideForm();').css('color','#0084c9');
                        jQuery("#hide_search_form").css('display','none');
                    }
    });
}    

