//  @import com.hedgehoglab.application.controller.BaseController;

/**
 *
 * @param scope
 */
function SearchContactsController(scope){
    BaseController.call(this,scope);
    scope.view.subscribe_to("on_search_term_changed",on_search_term_changed);
    
    var _old_term=null;
    var tag_index={};
    var _term=null;
    var _tags="";

    function on_search_term_changed(event){
        _term=event.term;
        event.tags=_tags;

        scope.state_machine_model.searching_for_contacts();
        scope.selected_contacts_model.model([]);

        scope.contacts_service.get_contacts_by_search_term(event,function(data){
            if(data!=null){
                data.contact=BaseModel.to_array(data.contact);
				//	Sort the data
				// data.contact=data.contact.sort(function(a,b){
				// 	var a_name=((a.lastName!=null)?a.lastName:"")+((a.firstName!=null)?a.firstName:"")
				// 	var b_name=((b.lastName!=null)?b.lastName:"")+((b.firstName!=null)?b.firstName:"")
				// 	return a_name.toLowerCase()>b_name.toLowerCase();
				// });
            } 
            scope.contacts_model.model(data);
			
        });

        on_update_tags({term:_term,tags:_tags});
    };

    function on_update_tags(event){
       
        
        if(_term != _old_term || event.tags.length==0){
            tag_index={};
            scope.tag_service.get_tags_for_result_search({tags:_tags,term:_term},function(data){
            // Check to see if we should show tag filter or not
            if(!data){
                scope.tag_view.disable();
            } else {
                scope.tag_view.enable();
            }
            scope.tag_view.update({tags:data,indices:tag_index});
            _old_term = _term;
        });
        }
        

    };

    scope.view.subscribe_to("on_search_term_empty",on_search_term_empty);

    function on_search_term_empty(event){
        on_search_term_changed({"term":"","tags":[]});   
    };

    scope.results_view.subscribe_to("on_preresult_clicked",function(event){
        //on_search_term_changed(event);
    });

    scope.tag_view.subscribe_to('on_tag_clicked',function(event){
        scope.message_service.show_message({message:"Filtering by tags...",duration:"750",type:"info"});
        if(tag_index[event.id]==null){
            tag_index[event.id]=event.label;
        }else{
            tag_index[event.id]=null;
        }
        //  rebuild tag list
        var tags=[];

        $.each(tag_index,function(i,n){
            tags.push(n);
        });
        _tags=""+tags;

        on_search_term_changed({term:_term,tags:_tags});
    });

    scope.tag_view.subscribe_to("on_tag_filter_clicked",function(event){
        scope.tag_view.update();
        on_search_term_changed({tags:"",term:_term});
        scope.tag_view.show();
    });

    on_search_term_changed({"term":"","tags":[]});


};