
var CashFlowRiskCalculator = function() {

	Ext.QuickTips.init();

	var dataStore;
	
	var pricingTable = [
		[  1,  25, 45.00],
		[ 26,  50, 65.00],
		[ 51, 100, 90.00],
		[101, 250, 165.00],
		[251, 500, 275.00],
		[501, 100000, 500.00]
	];
		
	var calculatedData = [
		['Single', 0.0, 0.0, 0.0],
		['Employee/Spouse', 0.0, 0.0, 0.0],
		['Employee/Child(ren)', 0.0, 0.0, 0.0],
		['Family', 0.0, 0.0, 0.0]
	];

	var fs;
	var colPercent;
	var colDollars;
	var messageElement;
	var colModel;
	var basedOnPercent = true;
	
	function calcExposure(premium, contribution_percentage) {
		return (premium * (100 - contribution_percentage)) / 100;
	}
	
	function calculatePerEmployeeCost(numEmployees) {
		
		var priceTier = 0.0;
		
		for (i = 0; i < pricingTable.length; i++) {
			var tier = pricingTable[i];
			if (numEmployees >= tier[0] && numEmployees <= tier[1]) {
				priceTier = tier[2];
				break;
			}
			
		}
		return (priceTier / numEmployees);
	}
	
	function calculate() {
		var values = fs.getValues(false);
		
		
		if (basedOnPercent) {
			
			calculatedData[0][1] = 
				calcExposure(parseFloat(values['prem_single']), parseInt(values['cont_single']));
			var referenceExposure = calculatedData[0][1];
			var referencePremium = parseFloat(values['prem_single']);
			
			calculatedData[1][1] = referenceExposure +
				calcExposure(parseFloat(values['prem_emp_spouse']) - referencePremium, parseInt(values['cont_emp_spouse']));
			calculatedData[2][1] = referenceExposure +
				calcExposure(parseFloat(values['prem_emp_child']) - referencePremium, parseInt(values['cont_emp_child']));
			calculatedData[3][1] = referenceExposure +
				calcExposure(parseFloat(values['prem_family']) - referencePremium, parseInt(values['cont_family']));
		} else {
			// column 2 - column 1
			calculatedData[0][1] = parseFloat(values['prem_single']) - parseFloat(values['cont_dollar_single']);
			calculatedData[1][1] = parseFloat(values['prem_emp_spouse']) - parseFloat(values['cont_dollar_emp_spouse']);
			calculatedData[2][1] = parseFloat(values['prem_emp_child']) - parseFloat(values['cont_dollar_emp_child']);
			calculatedData[3][1] = parseFloat(values['prem_family']) - parseFloat(values['cont_dollar_family']);
		}

		var perEmployee = calculatePerEmployeeCost(parseFloat(values['num_employees']));
		
		calculatedData[0][2] = perEmployee;
		calculatedData[1][2] = perEmployee;
		calculatedData[2][2] = perEmployee;
		calculatedData[3][2] = perEmployee;
	
		calculatedData[0][3] = calculatedData[0][1] + perEmployee;
		calculatedData[1][3] = calculatedData[1][1] + perEmployee;
		calculatedData[2][3] = calculatedData[2][1] + perEmployee;
		calculatedData[3][3] = calculatedData[3][1] + perEmployee;
		
		dataStore.load();
	}
	
	function setContributionEntryInDollars(v) {
		basedOnPercent = !v;
		if (v) {
			colPercent.hide();
			colDollars.show();
			messageElement.show();
		} else {
			messageElement.hide();
			colDollars.hide();
			colPercent.show();
		}
		if (fs.isValid()) {
			calculate();
		}
	}

	// Class Public Interface
	return {
		init : function() {
			Ext.form.Field.prototype.msgTarget = 'qtip';

			Ext.form.VTypes["integerMask"] = /[\d-]/;
			Ext.form.VTypes["integerText"] = 'Not a valid number.';
			Ext.form.VTypes["integer"] = function(v) { return (v > 0 && !isNaN(parseInt(v))); }
			
			Ext.form.VTypes["percentMask"] = /[\d-]/;
			Ext.form.VTypes["percentText"] = 'Not a valid percent. Value must be between 0 and 100.';
			Ext.form.VTypes["percent"] = function(v) { return (v <= 100 && v >= 0); }
			
			Ext.form.VTypes["dollarVal"] = /^[\$]?[\d]*(.[\d]{2})?$/;
			Ext.form.VTypes["dollarMask"] = /[\d\$.]/;
			Ext.form.VTypes["dollarText"] = 'Not a valid dollar amount.  Must be in the format "$123.45" ($ symbol and cents optional).';
			Ext.form.VTypes["dollar"] = function(v) { return Ext.form.VTypes["dollarVal"].test(v); }
			
			fs = new Ext.form.Form({
			        labelAlign: 'right',
			        labelWidth: 140,
//			        waitMsgTarget: 'box-bd',
					monitorValid: true
			    });

				// Enter Total dollar contribuation for each Level of Coverage
				
				fs.fieldset({legend:'Calculator Options', hideLabels : true});


				fs.column({width:320, hideLabels : true});
				var cb = new Ext.form.Checkbox(
					{
						boxLabel: 'Enter contributions as fixed dollar amounts<br/>&nbsp;&nbsp;&nbsp;<i>(Default is as a percentage of premium)</i>',
						name: 'dollaramount_entry',
						width: 'auto'
					});
				
				fs.add(cb);
				
				cb.on({check : function(checkbox, checked) { setContributionEntryInDollars(checked); } });
				
				cb = new Ext.form.Checkbox(
					{
						boxLabel: 'Display subscription fee added to monthly premium',
						name: 'display_premium_change',
						width: 'auto'
					})
				fs.add(cb);
				cb.on({check : function(checkbox, checked) { 
						colModel.setHidden(colModel.getIndexById('employee_premium'), !checked);
					}
				});
				fs.end();
				
				fs.column({id: 'messages', width:240, align: 'right'});
				fs.end();
				
				fs.end();
				
				fs.add(new Ext.form.TextField(
					{
			            fieldLabel: 'Number of Employees',
			            name: 'num_employees',
						allowBlank: false,
			            width: 80,
						vtype: 'integer'
			        })
				);
				
				
				fs.fieldset({legend:'Company Contributions/Premiums'});
				
					
				colPercent = fs.column({width:282});
				
				fs.add(
				        new Ext.form.TextField({
				            fieldLabel: 'Single (%)',
				            name: 'cont_single',
							allowBlank: false,
				            width: 120,
							value: 0,
							vtype: 'percent'
				        }),
				        new Ext.form.TextField({
				            fieldLabel: 'Employee/Spouse (%)',
				            name: 'cont_emp_spouse',
							allowBlank: false,
				            width: 120,
							value: 0,
							vtype: 'percent'
				        }),
						new Ext.form.TextField({
				            fieldLabel: 'Employee/Children (%)',
				            name: 'cont_emp_child',
							allowBlank: false,
				            width: 120,
							value: 0,
							vtype: 'percent'
				        }),
						new Ext.form.TextField({
				            fieldLabel: 'Family (%)',
				            name: 'cont_family',
							allowBlank: false,
				            width: 120,
							value: 0,
							vtype: 'percent'
				        })
				);
				
				fs.end();
				
				
				colDollars = fs.column({width:282});
				colDollars.hide();
				
				fs.add(
				        new Ext.form.TextField({
				            fieldLabel: 'Single',
				            name: 'cont_dollar_single',
							allowBlank: false,
				            width: 120,
							value: 0,
							vtype: 'dollar'
				        }),
				        new Ext.form.TextField({
				            fieldLabel: 'Employee/Spouse',
				            name: 'cont_dollar_emp_spouse',
							allowBlank: false,
				            width: 120,
							value: 0,
							vtype: 'dollar'
				        }),
						new Ext.form.TextField({
				            fieldLabel: 'Employee/Children',
				            name: 'cont_dollar_emp_child',
							allowBlank: false,
				            width: 120,
							value: 0,
							vtype: 'dollar'
				        }),
						new Ext.form.TextField({
				            fieldLabel: 'Family',
				            name: 'cont_dollar_family',
							allowBlank: false,
				            width: 120,
							value: 0,
							vtype: 'dollar'
				        })
				);
				
				fs.end();				
				
				
				fs.column({width:282});
				fs.add(
					new Ext.form.TextField({
				            fieldLabel: 'Monthly Premium',
				            name: 'prem_single',
							allowBlank: false,
				            width: 120,
							vtype: 'dollar'
				    }),
					new Ext.form.TextField({
				            fieldLabel: 'Monthly Premium',
				            name: 'prem_emp_spouse',
							allowBlank: false,
				            width: 120,
							vtype: 'dollar'
				    }),
					new Ext.form.TextField({
				            fieldLabel: 'Monthly Premium',
				            name: 'prem_emp_child',
							allowBlank: false,
				            width: 120,
							vtype: 'dollar'
				    }),
					new Ext.form.TextField({
				            fieldLabel: 'Monthly Premium',
				            name: 'prem_family',
							allowBlank: false,
				            width: 120,
							vtype: 'dollar'
				    })
				);				
				
				fs.end();
				fs.end();
				
				
				var calcButton = fs.addButton({ text :'Calculate!', handler: calculate, disabled: true});
				fs.on({
					clientvalidation : function(form, isValid) {
						if (isValid) {
							calcButton.enable();
						} else {
							calcButton.disable();
						}
					}
				});
				
				fs.render('form-ct');
				
				var messages = Ext.get('messages');
				messageElement = messages.createChild({
					html: '<span style="color:red;">Enter total dollar contribution for each level of coverage.</span>' });
				messageElement.hide();
				
				dataStore = new Ext.data.Store({
					proxy: new Ext.data.MemoryProxy(calculatedData),
					reader: new Ext.data.ArrayReader({}, [
							{name: 'type'},
							{name: 'premium', type: 'float'},
							{name: 'cost', type: 'float'},
							{name: 'employee_premium', type: 'float'}
						]
					)
				});
				//dataStore.load();
				
				// create the column model
				colModel = new Ext.grid.ColumnModel([
					{id:'type', header: "Type", width: 120, sortable: true, locked:false, dataIndex: 'type'},
					{header: "Monthly Cash Flow Exposure", align: 'right', width: 160, sortable: true, renderer: Ext.util.Format.usMoney, dataIndex: 'premium'},
					{header: "Subscription Cost/Employee", align: 'right', width: 160, sortable: true, renderer: Ext.util.Format.usMoney, dataIndex: 'cost'},
					{id:'employee_premium', header: "New Employee Premium", align: 'right', width: 160, sortable: true, renderer: Ext.util.Format.usMoney, dataIndex: 'employee_premium',  hidden: true}
					
				]);
			
				 // create the Grid
		        var grid = new Ext.grid.Grid('based_on_percent_grid', {
		            ds: dataStore,
		            cm: colModel,
		            autoExpandColumn: 'type'
		        });
		        
		        grid.render();

		}
	};
	
}();


Ext.onReady(CashFlowRiskCalculator.init, CashFlowRiskCalculator, true);
