/**
 * @requires: jquery, profile.js, section.js, tags.js
 * @requires: NOREPRESENTATIVEID
 */
function Investment(id, name, edit) {
	this.name = name;
	this.id = id;
	this.edit = edit;
	
	this.noRepSelected = false;
	
	this.commP = 0;
	this.mrktP = 0;
	this.orgP = 0;
	
}
Investment.prototype = {
	tags: null,
	
	noRepSelected: null,
	
	commP: null,
	mrktP: null,
	orgP: null,
	
	info: function() {
		var self = this;
		if (this.edit) {
			$(document).ready(function(){
				self.date = self.getElt('investdate').datepicker();
			});
		}
		
		Profiles[this.getId()] = this;
		return this;
	},
	
	initInvestor: function(ids, investors) {
		var self = this;
		if ($('#investors' + this.getId()).length > 0 && this.edit) {
			this.investorTags = new Tags('investors' + this.getId(), this.name + '[' + this.id + ']' + '[investor_id][]');
			this.investorTags.tagsOnClick(function(id, name) {
				new Profiles(id, 'Investor').get();
			});
			
			this.investorTags.addQuickSearch(function(name){
				// second argument gets called after the ajax callback to gain access to the current profile object
				new Profiles('new', 'Investor').get(name, function(id, profile, tab){
				
					//Function called by Profile.update
					Profiles['Investor' + id].setUpdate(function(data){
					
						// update tags and its quicksearch
						self.investorTags.getQuickSearch().addOption(data.investor_id, data.name, QuickSearchTemplate(data.name));
						self.investorTags.addTag(data.investor_id, data.name);
						tab.remove();
						self.selectTab();
						
						//Update mainSearch
						MAINSEARCH.get().addOption(data.investor_id, data.name, QuickSearchTemplate(data.name, 'Investor'), 'Investor');
					});
				});
			});

			var search = this.investorTags.getQuickSearch();
			jQuery.each(investors, function(){
				search.addOption(this.investor_id, this.name, QuickSearchTemplate(this.name));
				if (ids[this.investor_id])
					self.investorTags.addTag(this.investor_id, this.name);
			});
		}
	},
	
	initSeries: function(id, series){
		var self = this;
		if ($('#series' + this.getId()).length > 0 && this.edit) {
			this.seriesTags = new Tags('series' + this.getId(), this.name + '[' + this.id + ']' + '[series_id]');
			this.seriesTags.setLimit(1);
			this.seriesTags.tagsOnClick(function(id, name){
				new Profiles(id, 'Series').get();
			});
			
			this.seriesTags.tagsOnClose(function(id, name){
				self.updateInvestments(0, 0, 0);
			});
			
			this.seriesTags.addQuickSearch(function(name){
				// second argument gets called after the ajax callback to gain access to the current profile object				
				new Profiles('new', 'Series').get(name, function(id, profile, tab){
				
					//Function called by Profile.update
					Profiles['Series' + id].setUpdate(function(data){
						
						// error checking
						if (!data.commissionp)	data.commissionp = 0;
						if (!data.marketfeep)	data.marketfeep = 0;
						if (!data.orgfeep)		data.orgfeep = 0;

						// update tags and its quicksearch
						self.seriesTags.getQuickSearch().addOption(data.series_id, data.seriesname, QuickSearchTemplate(data.seriesname), {commP:data.commissionp, mrktP:data.marketfeep, orgP:data.orgfeep});
						self.seriesTags.addTag(data.series_id, data.seriesname);
						tab.remove();
						self.selectTab();
						
						//update default percentages
						self.updateInvestments(data.commissionp, data.marketfeep, data.orgfeep);
						
						//Update mainSearch
						MAINSEARCH.get().addOption(data.series_id, data.seriesname, QuickSearchTemplate(data.seriesname, 'Series'), 'Series');
					});
				});
			});
			
			var search = this.seriesTags.getQuickSearch();
			search.setApproveFunction(function(id, name, data) {
				self.seriesTags.addTag(id, name);
					self.updateInvestments(data.commP, data.mrktP, data.orgP);
			});
			jQuery.each(series, function(){
				search.addOption(this.series_id, this.seriesname, QuickSearchTemplate(this.seriesname), {commP:this.commissionp, mrktP:this.marketfeep, orgP:this.orgfeep});
				if (id == this.series_id) 
					search.approveFunction(this.series_id, this.seriesname, {commP:this.commissionp, mrktP:this.marketfeep, orgP:this.orgfeep});
			});
		}
	},
	
	initRepresentative: function(id, representatives){
		var self = this;
		if ($('#representatives' + this.getId()).length > 0 && this.edit) {
			this.representativeTags = new Tags('representatives' + this.getId(), this.name + '[' + this.id + ']' + '[representative_id]');
			this.representativeTags.setLimit(1);
			this.representativeTags.tagsOnClick(function(id, name) {
				new Profiles(id, 'Representative').get();
			});
			
			this.representativeTags.tagsOnClose(function(id, name){
				self.noRepSelected = false;
				self.updateInvestments(self.commP, self.mrktP, self.orgP);
			});
			
			this.representativeTags.addQuickSearch(function(name) {
				// second argument gets called after the ajax callback to gain access to the current profile object
				new Profiles('new', 'Representative').get(name, function(id, profile, tab){
				
					//Function called by Profile.update
					Profiles['Representative' + id].setUpdate(function(data){
					
						// update tags and its quicksearch
						self.representativeTags.getQuickSearch().addOption(data.representative_id, data.name, QuickSearchTemplate(data.name));
						self.representativeTags.addTag(data.representative_id, data.name);
						tab.remove();
						self.selectTab();
						
						//Update mainSearch
						MAINSEARCH.get().addOption(data.representative_id, data.name, QuickSearchTemplate(data.name, 'Representative'), 'Representative');
					});
				});
			});

			var search = this.representativeTags.getQuickSearch();
			search.setApproveFunction(function(id, name, data) {
				self.representativeTags.addTag(id, name);
					if (id == NOREPRESENTATIVEID) {
						self.noRepSelected = true;
						self.updateInvestments(self.commP, self.mrktP, self.orgP);
					}
					self.updateInvestments(self.commP, self.mrktP, self.orgP);
			});
			jQuery.each(representatives, function(){
				search.addOption(this.representative_id, this.name, QuickSearchTemplate(this.name));
				if (id == this.representative_id)
					search.approveFunction(this.representative_id, this.name);
			});
		}
	},
	
	initInstitution: function(id, institutions) {
		var self = this;
		if ($('#institutions' + this.getId()).length > 0 && this.edit) {
			this.institutionTags = new Tags('institutions' + this.getId(), this.name + '[' + this.id + ']' + '[institution_id]');
			this.institutionTags.setLimit(1);
			this.institutionTags.setLabelLimit(30);
			this.institutionTags.tagsOnClick(function(id, name) {
				self.institutionProfile = new Profiles(id, 'Institution');
				self.institutionProfile.get();
			});
			
			this.institutionTags.addQuickSearch(function(name) {
				// second argument gets called after the ajax callback to gain access to the current profile object
				new Profiles('new', 'Institution').get(name, function(id, profile, tab){
				
					//Function called by Profile.update
					Profiles['Institution' + id].setUpdate(function(data){
					
						// update tags and its quicksearch
						self.institutionTags.getQuickSearch().addOption(data.institution_id, data.name, QuickSearchTemplate(data.name));
						self.institutionTags.addTag(data.institution_id, data.name);
						tab.remove();
						self.selectTab();
						
						//Update mainSearch
						MAINSEARCH.get().addOption(data.institution_id, data.name, QuickSearchTemplate(data.name, 'Institution'), 'Institution');
					});
				});
			});

			var search = this.institutionTags.getQuickSearch();
			jQuery.each(institutions, function(){
				search.addOption(this.institution_id, this.name, QuickSearchTemplate(this.name));
				if (id == this.institution_id)
					self.institutionTags.addTag(this.institution_id, this.name);
			});
		}
	},
	
	initTypes: function(qualifiedclient, accreditedinvestor, erisa, planType) {
		var self = this;
		var qualified, clientInvestor, erisaYes, erisaNo, other;

		// accrediation
		var qualified = new INTRIGO.Tag('Qualified Purchaser').setName('Investment[' + this.id + '][qualifiedclient]').checkbox(['yes', 'no'], qualifiedclient);
		var clientInvestor = new INTRIGO.Tag('Client/Investor').setName('Investment[' + this.id + '][accreditedinvestor]').onDeselect(function(tag) {
			$('#ERISARow' + self.getId()).css('display', 'none');
			$('#planTypeRow' + self.getId()).css('display', 'none');
			$('#planTypeRowOther' + self.getId()).css('display', 'none');
		}).onSelect(function(tag) {
			$('#ERISARow' + self.getId()).css('display', '');
		}).checkbox(['yes', 'no'], accreditedinvestor);
		
		var container = $('#accrediation' + this.getId());
		container.append(qualified.getContainer());
		container.append(clientInvestor.getContainer());
		
		// erisa
		var container = document.getElementById('ERISA' + this.getId());
		var tags = new INTRIGO.Tags(container, 'Investment[' + this.id + '][erisa]').radio();
		var erisaYes = tags.addTag('yes').onSelect(function(tag) {
			$('#planTypeRow' + self.getId()).css('display', '');
		}).onDeselect(function(tag) {
			$('#planTypeRow' + self.getId()).css('display', 'none');
			$('#planTypeRowOther' + self.getId()).css('display', 'none');
		});
		var erisaNo = tags.addTag('no');
		var selected = tags.findByValue(erisa);
		if (selected) {
			selected.select();
		}
		else erisaNo.select();
		
		// plan type
		var plans = ['IRA', '401K', 'Profile Sharing', 'Pension', 'KEOGH'];
		var container = document.getElementById('planType' + this.getId());
		var planTypeFunc = function(tag){
			var elt = self.getElt('plantype');
			if (tag.getValue() == 'Other') {
				$('#planTypeRowOther' + self.getId()).css('display', '');
				if (planType && jQuery.inArray(planType, plans) == -1) {
					elt.val(planType);
				}
				else {
					elt.val('');
					elt.get(0).focus();
				}
			}
			else {
				elt.val(tag.getValue());
			}
		}
		tags = new INTRIGO.Tags(container, '').onSelect(planTypeFunc).disableRemove();
		for (var i = 0; i < plans.length; i++) {
			tags.addTag(plans[i]);
		}
		var other = tags.addTag('Other').onDeselect(function(tag) {
			$('#planTypeRowOther' + self.getId()).css('display', 'none');
		});
		
		var selected = tags.findByValue(planType);
		if (selected) {
			selected.select();
		}
		else if (planType) {
			other.select();
		}
	},
	
	initPercentages: function(commP, mrktP, orgP){
		var self = this;
		
		this.gross = this.getElt('grossinvest');
		this.comm = this.getElt('commission');
		this.mrkt = this.getElt('marketingfee');
		this.org = this.getElt('orgfee');
		this.net = this.getElt('netinvest');
		
		this.commP = commP;
		this.mrktP = mrktP;
		this.orgP = orgP;

		this.gross.keyup(function() {
			if (self.noRepSelected)
				self.updateInvestments(0, 0, self.orgP, true);
			else self.updateInvestments(self.commP, self.mrktP, self.orgP, true);
		});
	},
	
	updateNetInvest: function(){
		this.net.val((this.gross.val() - this.comm.val() - this.mrkt.val() - this.org.val()).toFixed(2));
	},
	
	updateInvestments: function(commP, mrktP, orgP, dontOverwrite){
		if (!dontOverwrite) {
			this.commP = commP;
			this.mrktP = mrktP;
			this.orgP = orgP;
		}
		// if no representative is selected do not overwrite the values stored in the object
		if (this.noRepSelected) {
			commP = 0;
			mrktP = 0;
		}
		
		//update html
		this.getElt('commissionPercentage').html((commP * 1).toFixed(2) + ' %');
		this.getElt('marketingPercentage').html((mrktP * 1).toFixed(2) + ' %');
		this.getElt('orgfeePercentage').html((orgP * 1).toFixed(2) + ' %');
		
		//update totals
		this.comm.val((this.gross.val() * (commP * 0.01)).toFixed(2));
		this.mrkt.val((this.gross.val() * (mrktP * 0.01)).toFixed(2));
		this.org.val((this.gross.val() * (orgP * 0.01)).toFixed(2));
		
		this.updateNetInvest();
	}
};
Investment.prototype = jQuery.extend(Investment.prototype, Profile.prototype);