// Add the additional 'advanced' VTypes
Ext.apply(Ext.form.VTypes, {
	daterange: function(val, field) {
		var date = field.parseDate(val);
		
		// We need to force the picker to update values to recaluate the disabled dates display
		var dispUpd = function(picker) {
			var ad = picker.activeDate;
			picker.activeDate = null;
			picker.update(ad);
		};
		
		if (field.startDateField && field.endDateField) {
			var sd = Ext.getCmp(field.startDateField);
			sd.maxValue = date;
			var ed = Ext.getCmp(field.endDateField);
			ed.minValue = date;
			if (sd.menu && sd.menu.picker) {
				sd.menu.picker.maxDate = date;
				dispUpd(sd.menu.picker);
			}
			if (ed.menu && ed.menu.picker) {
				ed.menu.picker.minDate = date;
				dispUpd(ed.menu.picker);
			}

		} else if (field.startDateField && !field.endDateField) {
			var sd = Ext.getCmp(field.startDateField);
			sd.maxValue = date;
			if (sd.menu && sd.menu.picker) {
				sd.menu.picker.maxDate = date;
				dispUpd(sd.menu.picker);
			}

		} else if (field.endDateField && !field.startDateField) {
			var ed = Ext.getCmp(field.endDateField);
			ed.minValue = date;
			if (ed.menu && ed.menu.picker) {
				ed.menu.picker.minDate = date;
				dispUpd(ed.menu.picker);
			}

		}
		/* Always return true since we're only using this vtype
		* to set the min/max allowed values (these are tested
		* for after the vtype test)
		*/
		return true;
	}
});

Ext.onReady(function(){

	Ext.QuickTips.init();
	
	// turn on validation errors beside the field globally
    Ext.form.Field.prototype.msgTarget = 'side';

 	
	/* Define arrays for pull-down menus */
	arr_coupon_frequency = [['annual', 'Annual'],['semiannual', 'Semi-Annual'],['quarterly', 'Quarterly'],['monthly', 'Monthly']];
	arr_day_count_method = [['actual_actual','Act/Act'],['30_360','30/360'],['sia_30_360','NASD/360'],['30e+_360','ISMA/360']];
	arr_end_of_month_adjustment_flag = [['adjust','Adjust'],['dont_adjust','Don\'t Adjust']];
	arr_given_py_flag = [['price_given','Price'],['yield_given','Yield']];
	
	var dt = new Date();
	
	/* Define fields */
	fld_coupon_rate = {fieldLabel: Ext.tipslbl.lbl_coupon_rate, name: 'coupon_rate', xtype: 'numberfield', width: 120, allowBlank:false, tabIndex: 1};
	fld_given_py_flag = new Ext.form.ComboBox({
		fieldLabel: Ext.tipslbl.lbl_given_py_flag,
		hiddenName:'given_py_flag',
		store: new Ext.data.SimpleStore({
			fields: ['dspValue', 'dspDisplay'],
			data : arr_given_py_flag
		}),
		valueField:'dspValue',
		displayField:'dspDisplay',
		typeAhead: true,
		mode: 'local',
		triggerAction: 'all',
		selectOnFocus:true,
		allowBlank:false,
		forceSelection: true,
		value: 'price_given',
		width: 100, 
		tabIndex: 4
		});
	
	fld_maturity_date = new Ext.form.DateField({fieldLabel: Ext.tipslbl.lbl_maturity_date, name: 'maturity_date', id: 'maturity_date', width: 100, allowBlank:false, tabIndex: 2, vtype: 'daterange', startDateField: 'issue_date'});
	fld_given_py ={fieldLabel: Ext.tipslbl.lbl_given_py, name: 'given_py', xtype: 'numberfield', width: 120, allowBlank:false, tabIndex: 5};
	
	fld_redemption_value = {fieldLabel: Ext.tipslbl.lbl_redemption_value , name: 'redemption_value', id: 'redemption_value', width: 120, allowBlank:false, xtype: 'numberfield', value: 100, tabIndex: 3};
	fld_settlement_date = new Ext.form.DateField({fieldLabel: Ext.tipslbl.lbl_settlement_date, name: 'settlement_date', id: 'settlement_date', value: dt.format('m/d/Y'), width: 100, allowBlank:false, tabIndex: 6, vtype: 'daterange', startDateField: 'issue_date', endDateField: 'maturity_date'});

	fld_first_coupon_date = new Ext.form.DateField({fieldLabel: Ext.tipslbl.lbl_first_coupon_date, name: 'first_coupon_date', width: 100, tabIndex: 7});
	fld_issue_date = new Ext.form.DateField({fieldLabel: Ext.tipslbl.lbl_issue_date, name: 'issue_date', id: 'issue_date', width: 100, tabIndex: 8, vtype: 'daterange', endDateField: 'maturity_date'});
	fld_coupon_reinvestment_rate = {fieldLabel: Ext.tipslbl.lbl_coupon_reinvestment_rate, name: 'coupon_reinvestment_rate', width: 120, xtype: 'numberfield', tabIndex: 9};
	
	fld_coupon_frequency = new Ext.form.ComboBox({
		fieldLabel: Ext.tipslbl.lbl_coupon_frequency,
		hiddenName:'coupon_frequency',
		store: new Ext.data.SimpleStore({
			fields: ['dspValue', 'dspDisplay'],
			data : arr_coupon_frequency
		}),
		valueField:'dspValue',
		displayField:'dspDisplay',
		typeAhead: true,
		mode: 'local',
		triggerAction: 'all',
		selectOnFocus:true,
		allowBlank:false,
		forceSelection: true,
		value: 'annual',
		width: 140, 
		tabIndex: 10
		});
		
	fld_day_count_method = new Ext.form.ComboBox({
		fieldLabel: Ext.tipslbl.lbl_day_count_method,
		hiddenName:'day_count_method',
		store: new Ext.data.SimpleStore({
			fields: ['dspValue', 'dspDisplay'],
			data : arr_day_count_method
		}),
		valueField:'dspValue',
		displayField:'dspDisplay',
		typeAhead: true,
		mode: 'local',
		triggerAction: 'all',
		selectOnFocus:true,
		allowBlank:false,
		forceSelection: true,
		value: 'actual_actual',
		width: 140, 
		tabIndex: 11
		});
		
	fld_end_of_month_adjustment_flag = new Ext.form.ComboBox({
		fieldLabel: Ext.tipslbl.lbl_end_of_month_adjustment_flag,
		hiddenName:'end_of_month_adjustment_flag',
		store: new Ext.data.SimpleStore({
			fields: ['dspValue', 'dspDisplay'],
			data : arr_end_of_month_adjustment_flag
		}),
		valueField:'dspValue',
		displayField:'dspDisplay',
		typeAhead: true,
		mode: 'local',
		triggerAction: 'all',
		selectOnFocus:true,
		allowBlank:false,
		forceSelection: true,
		value: 'dont_adjust',
		//emptyText: 'Don\'t Adjust',
		width: 140, 
		tabIndex: 12
		});
	
	sec_required_values = {
		xtype:'fieldset',
		title: Ext.tipslbl.lbl_required_values,
		autoHeight: true,
		width: 490,
		border: true,
		items: [{
			layout:'column',
			defaults: {columnWidth:.33, layout: 'form'},
			items:[{
				items: [fld_coupon_rate, fld_given_py_flag]
			},{
				items: [fld_maturity_date, fld_given_py]
			},{
				items: [fld_redemption_value, fld_settlement_date]
			}]
		}]
	};
	
	sec_optional_values = {
		xtype:'fieldset',
		title: Ext.tipslbl.lbl_optional_values,
		autoHeight: true,
		width: 490,
		border: true,
		items: [{
			layout:'column',
			defaults: {columnWidth:.33, layout: 'form'},
			items:[{
				items: [fld_issue_date]
			},{
				items: [fld_first_coupon_date]
			},{
				items: [fld_coupon_reinvestment_rate]
			}]
		}]
	};
	
	sec_adjust_settings = {
		xtype:'fieldset',
		title: Ext.tipslbl.lbl_adjust_settings,
		autoHeight: true,
		width: 490,
		border: true,
		items: [{
			layout:'column',
			defaults: {columnWidth:.33, layout: 'form'},
			items:[{
				items: [fld_coupon_frequency]
			},{
				items: [fld_day_count_method]
			},{
				items: [fld_end_of_month_adjustment_flag]
			}]
		}]
	};
	
	
	fld_price  = {fieldLabel: Ext.tipslbl.lbl_price, name: 'price', id: 'price', width: 120, xtype: 'numberfield', readOnly: true};
	fld_yield  = {fieldLabel: Ext.tipslbl.lbl_yield, name: 'yield', id: 'yield', width: 120, xtype: 'numberfield', readOnly: true};
	fld_accrued_interest  = {fieldLabel: Ext.tipslbl.lbl_accrued_interest, name: 'accrued_interest', id: 'accrued_interest', width: 120, xtype: 'numberfield', readOnly: true};
	
	sec_price_yield = {
		xtype:'fieldset',
		layout: 'form',
		title: Ext.tipslbl.lbl_price_yield,
		autoHeight: true,
		width: 490,
		border: true,
		items: [{
			layout:'column',
			defaults: {columnWidth:.33, layout: 'form'},
			items:[{
				items: [fld_price]
			},{
				items: [fld_yield]
			},{
				items: [fld_accrued_interest]
			}]
		}]
	};
	
	fld_duration = {fieldLabel: Ext.tipslbl.lbl_duration, name: 'duration', id: 'duration', width: 120, xtype: 'numberfield'};
	fld_modified_duration = {fieldLabel: Ext.tipslbl.lbl_modified_duration, name: 'modified_duration', id: 'modified_duration', width: 120, xtype: 'numberfield'};
	fld_convexity = {fieldLabel: Ext.tipslbl.lbl_convexity, name: 'convexity', id: 'convexity', width: 120, xtype: 'numberfield'};
	fld_price_value_of_01 = {fieldLabel: Ext.tipslbl.lbl_price_value_of_01, name: 'price_value_of_01', id: 'price_value_of_01', width: 120, xtype: 'numberfield'};
	fld_yield_value_of_32nd = {fieldLabel: Ext.tipslbl.lbl_yield_value_of_32nd, name: 'yield_value_of_32nd', id: 'yield_value_of_32nd', width: 120, xtype: 'numberfield'};
	
	sec_duration = {
		xtype:'fieldset',
		layout: 'form',
		title: Ext.tipslbl.lbl_sec_duration,
		autoHeight: true,
		width: 490,
		border: true,
		items: [{
			layout:'column',
			defaults: {columnWidth:.33, layout: 'form'},
			items:[{
				items: [fld_duration, fld_price_value_of_01]
			},{
				items: [fld_modified_duration, fld_yield_value_of_32nd]
			},{
				items: [fld_convexity]
			}]
		}]
	};
	
	fld_annual_yield  = {fieldLabel: Ext.tipslbl.lbl_fld_annual_yield, name: 'annual_yield', id: 'annual_yield', width: 100, xtype: 'numberfield', readOnly: true};

	sec_annual_yield  = {
		xtype:'fieldset',
		layout: 'form',
		title: Ext.tipslbl.lbl_sec_annual_yield ,
		autoHeight: true,
		width: 490,
		border: true,
		items: [{
			layout:'column',
			defaults: {columnWidth:.33, layout: 'form'},
			items:[fld_annual_yield]
		}]
	};
	
	fld_coupon_interest = {fieldLabel: Ext.tipslbl.lbl_coupon_interest, name: 'coupon_interest', id: 'coupon_interest', width: 120, xtype: 'numberfield', readOnly: true};
	fld_interest_on_interest = {fieldLabel: Ext.tipslbl.lbl_interest_on_interest, name: 'interest_on_interest', id: 'interest_on_interest', width: 120, xtype: 'numberfield', readOnly: true};
	fld_total_interest = {fieldLabel: Ext.tipslbl.lbl_total_interest, name: 'total_interest', id: 'total_interest', width: 120, xtype: 'numberfield', readOnly: true};
	fld_cap_gain = {fieldLabel: Ext.tipslbl.lbl_cap_gain, name: 'cap_gain', id: 'cap_gain', width: 120, xtype: 'numberfield', readOnly: true};
	fld_total_dollar_return = {fieldLabel: Ext.tipslbl.lbl_total_dollar_return, name: 'total_dollar_return', id: 'total_dollar_return', width: 120, xtype: 'numberfield', readOnly: true};
	fld_total_future_amount = {fieldLabel: Ext.tipslbl.lbl_total_future_amount, name: 'total_future_amount', id: 'total_future_amount', width: 120, xtype: 'numberfield', readOnly: true};
	
	sec_income = {
		xtype:'fieldset',
		layout: 'form',
		title: Ext.tipslbl.lbl_income,
		autoHeight: true,
		width: 490,
		border: true,
		items: [{
			layout:'column',
			defaults: {columnWidth:.33, layout: 'form'},
			items:[{
				items: [fld_coupon_interest, fld_cap_gain]
			},{
				items: [fld_interest_on_interest, fld_total_dollar_return]
			},{
				items: [fld_total_interest, fld_total_future_amount]
			}]
		}]
	};
	
	fld_previous_coupon_date = new Ext.form.DateField({fieldLabel: Ext.tipslbl.lbl_previous_coupon_date, name: 'previous_coupon_date', id: 'previous_coupon_date', width: 100, readOnly: true});
	fld_next_coupon_date = new Ext.form.DateField({fieldLabel: Ext.tipslbl.lbl_next_coupon_date, name: 'next_coupon_date', id: 'next_coupon_date', width: 100, readOnly: true});
			
	/*fld_previous_coupon_date = {fieldLabel: 'Previous Coupon Date', name: 'previous_coupon_date', id: 'previous_coupon_date', width: 120, xtype: 'numberfield', readOnly: true};
	fld_next_coupon_date = {fieldLabel: 'Next Coupon Date', name: 'next_coupon_date', id: 'next_coupon_date', width: 120, xtype: 'numberfield', readOnly: true};
	*/
	sec_coupon  = {
		xtype:'fieldset',
		layout: 'form',
		title: Ext.tipslbl.lbl_coupon,
		autoHeight: true,
		width: 490,
		border: true,
		items: [{
			layout:'column',
			defaults: {columnWidth:.33, layout: 'form'},
			items:[{
				items: [fld_previous_coupon_date]
			},{
				items: [fld_next_coupon_date]
			}]
		}]
	};
	
	btn_Calculate = { 
		text: Ext.tipslbl.lbl_btn_Calculate,
		formBind: true,	 
		// Function that fires when user clicks the button 
		handler:function(){ 
			inputs.getForm().submit({ 
				waitTitle: Ext.tipslbl.lbl_waitTitle, 
				waitMsg: Ext.tipslbl.lbl_waitMsg,
			
			// Functions that fire (success or failure) when the server responds. 
			// The one that executes is determined by the 
			// response that comes from login.asp as seen below. The server would 
			// actually respond with valid JSON, 
			// something like: response.write "{ success: true}" or 
			// response.write "{ success: false, errors: { reason: 'Login failed. Try again.' }}" 
			// depending on the logic contained within your server script.
			// If a success occurs, the user is notified with an alert messagebox, 
			// and when they click "OK", they are redirected to whatever page
			// you define as redirect. 
			
				success:function(form, action){ 
					obj = Ext.util.JSON.decode(action.response.responseText);
					
					inputs.form.items.get('price').setValue(obj.results.price);
					inputs.form.items.get('yield').setValue(obj.results.yield);
					inputs.form.items.get('accrued_interest').setValue(obj.results.accrued_interest);
					inputs.form.items.get('duration').setValue(obj.results.duration);
					inputs.form.items.get('modified_duration').setValue(obj.results.modified_duration);
					inputs.form.items.get('convexity').setValue(obj.results.convexity);
					inputs.form.items.get('price_value_of_01').setValue(obj.results.price_value_of_01);
					inputs.form.items.get('yield_value_of_32nd').setValue(obj.results.yield_value_of_32nd);
					inputs.form.items.get('annual_yield').setValue(obj.results.annual_yield);
					inputs.form.items.get('coupon_interest').setValue(obj.results.coupon_interest);
					inputs.form.items.get('interest_on_interest').setValue(obj.results.interest_on_interest);
					inputs.form.items.get('total_interest').setValue(obj.results.total_interest);
					inputs.form.items.get('previous_coupon_date').setValue(obj.results.previous_coupon_date);
					inputs.form.items.get('next_coupon_date').setValue(obj.results.next_coupon_date);
					
					val_cap_gain = inputs.form.items.get('redemption_value').getValue() - inputs.form.items.get('price').getValue();
					inputs.form.items.get('cap_gain').setValue(val_cap_gain);
					
					val_total_dollar_return = inputs.form.items.get('total_interest').getValue() + val_cap_gain;
					inputs.form.items.get('total_dollar_return').setValue(val_total_dollar_return);
					
					val_total_future_amount = inputs.form.items.get('redemption_value').getValue() + inputs.form.items.get('total_interest').getValue();
					inputs.form.items.get('total_future_amount').setValue(val_total_future_amount);
					
					Ext.getCmp('tab2').enable();
					Ext.getCmp('alltabs').setActiveTab(1);
					
				},
			
			// Failure function, see comment above re: success and failure. 
			// You can see here, if login fails, it throws a messagebox
			// at the user telling him / her as much.  
			
				failure:function(form, action){
					if (action.failureType == 'client') {
						
					} else {
						obj = Ext.util.JSON.decode(action.response.responseText);
						Ext.Msg.alert('Calculator Error', obj.results.thisErrors);
					}
				} 
			}); 
		}
	}
	
	btn_Reset = {
		text: Ext.tipslbl.lbl_btn_Reset,
		handler:function(){ 
			inputs.getForm().reset(); 
		}
	}
	
	var proxy1 = new Ext.data.ScriptTagProxy({
	    url: 'http://data.investinginbondseurope.org/iibeu-site/actTIPSEngine.cfm',
	    method: 'GET'
    });
    
	/* Define Inputs Form Panel */
	var inputs = new Ext.FormPanel({
		
		url: 'http://data.investinginbondseurope.org/iibeu-site/actTIPSEngine.cfm',
        method:'POST', 
		labelWidth: 75,
		border:false,
		bodyStyle:'padding:15px 5px 0',
		width: 575,
		items: {
			xtype:'tabpanel',
			id: 'alltabs',
			plain:true,
			deferredRender:false,
			activeTab: 0,
			defaults:{layout: 'form', labelAlign: 'top', autoHeight:true}, 
			items:[{
				frame: true,
				id: 'tab1',
				title: Ext.tipslbl.lbl_Title_tab1,
				bodyStyle:'padding:5px 5px 0',
				width: 530,
				items:[sec_required_values, sec_optional_values, sec_adjust_settings],
				buttons: [btn_Calculate, btn_Reset]
			},{
				frame: true,
				id: 'tab2',
				title: Ext.tipslbl.lbl_Title_tab2,
				disabled: true,
				bodyStyle:'padding:5px 5px 0',
				width: 530,
				items:[sec_price_yield, sec_duration, sec_annual_yield, sec_income, sec_coupon]
			}]
		}
	});
	
	inputs.render('gbc_inputs');
	
	/* Calculated fields */
	// cap_gain = redemption_value - price;
	// total_dollar_return = total_interest + cap_gain;
	// total_future_amount = base_price + total_interest;
	
});
