/*
 * Requires: jquery, profile.js, phones.js, section.js, profile_brokerage.js
 */
var Representatives = {};

function Representative(id, name, edit) {
	this.name = name;
	this.id = id;
	this.edit = edit;
}
Representative.prototype = {
	tags: null,
	
	info: function() {
		var self = this;
		if (this.edit) {
			if (Profiles[this.getId()] && Profiles[this.getId()].setUpdate) {}
			else Profiles[this.getId()] = this;
			
			Phones[this.getId()] = new Contact('phone', this.getId());
		}
		else Profiles[this.getId()] = this;
		
		Sections[this.getId() + 'contact'] = new Section('contact', this.getId());
		Emails[this.getId()] = new Email(this.getId());
	},
	
	setBrokerages: function(brokerages, brokerage_id) {
		var self = this;
		if ($('#brokerages' + this.getId()).length > 0) {
			this.tags = new Tags('brokerages' + this.getId(), this.name + '[' + this.id + ']' + '[brokerage_id]');
			this.tags.setLimit(1);
			this.tags.tagsOnClick(function(id, name) {
				new Profiles(id, 'Brokerage').get();
			});
			
			this.tags.addQuickSearch(function(name) {
				// second argument gets called after the ajax callback to gain access to the current profile object
				new Profiles('new', 'Brokerage').get(name, function(id, profile, tab){
				
					//Function called by Profile.update
					Profiles['Brokerage' + id].setUpdate(function(data){
					
						// update tags and its quicksearch
						self.tags.getQuickSearch().addOption(data.brokerage_id, data.company_name, QuickSearchTemplate(data.company_name));
						self.tags.addTag(data.brokerage_id, data.company_name);
						tab.remove();
						self.selectTab();
						
						//Update mainSearch
						MAINSEARCH.get().addOption(data.brokerage_id, data.company_name, QuickSearchTemplate(data.company_name, 'Brokerage'), 'Brokerage');
					});
				});
			});
			
			var search = this.tags.getQuickSearch();
			jQuery.each(brokerages, function(){
				search.addOption(this.brokerage_id, this.company_name, QuickSearchTemplate(this.company_name));
				if (this.brokerage_id == brokerage_id)
					self.tags.addTag(this.brokerage_id, this.company_name);
			});
		}
	}
};
Representative.prototype = jQuery.extend(Representative.prototype, Profile.prototype);