// JavaScript Document

var basepath 	= "/resources/fiftynifty"
var scriptspath = basepath + "/scripts"
var extpath 	= scriptspath + "/ext_3_0"
var formwindow;


Ext.form.VTypes["zip"]=/[0-9]/;




Ext.override(Ext.form.Checkbox, {
	//use this code to override and retain original
    // private
	// to fix defect in ext to left align checkbox input fields
    getResizeEl : function(){
        if(!this.resizeEl){
            this.resizeEl = Ext.isSafari||Ext.isIE ? this.wrap : (this.wrap.up('.x-form-element', 5) || this.wrap);
        }
        return this.resizeEl;
    }
});

Ext.ns('Ext.fiftynifty');

(function() {

	ResourcePanel = Ext.extend(Ext.DataView, {
		autoHeight   : true,
		frame        : true,
		border		 :	true,
		cls          : 'resource',
		itemSelector : 'dd',
		overClass    : 'over',
		tpl          : new Ext.XTemplate(
			'<div id="resource-ct">',
				'<tpl for=".">',
				'<div>',

					'<h2><div>',
						'{values.resource_type}',
						
					'</div></h2>',

					'<dl>',
						'<tpl for="resources">',
						
							'<dd>',
							
								'<div>',
									'<h4  ext:url="{resource_url}">{resource_name}</h4>',
									'<div class="resource_description">{resource_description}</div><div><p>&nbsp;</p></div>',
									'<div width="100%">',
									'<tpl for="resource_links">',
										'<div><h6  ext:url="{resource_link_url}" >{resource_link_name}</h6></div>',
									'</tpl>',
									'</div>',
								'</div>',
								
								
							'</dd>',
						'</tpl>',
					'<div style="clear:left"></div></dl>',
				'</div>',
				
				'</tpl>',
			'</div>'),
	
	
		onClick : function(e){
			var group = e.getTarget('h2', 3, true);
			if(group){
				group.up('div').toggleClass('collapsed');
			}else{
				var t = e.getTarget('h6', 10, true);
				
				if(t){
					if(t && !e.getTarget('a', 2)){
						var url = t.getAttributeNS('ext', 'url');
						document.location = url;
						//window.open(url);
					}
				}else{
					var t = e.getTarget('h4', 5, true);
					if(t && !e.getTarget('a', 2)){
						var url = t.getAttributeNS('ext', 'url');
						document.location = url;
						//window.open(url);
					}
					
				}
			}
			return ResourcePanel.superclass.onClick.apply(this, arguments);
		}
	});
	
	Ext.fiftynifty.ResourcePanel = ResourcePanel;
	Ext.reg('resourcepanel', Ext.fiftynifty.ResourcePanel);
	
})();


Ext.onReady(function(){
	
	Ext.QuickTips.init();
	Ext.BLANK_IMAGE_URL = extpath + "/resources/images/default/s.gif";
	// turn on validation errors beside the field globally
	
	Ext.form.Field.prototype.msgTarget = 'side';

    var resource_store = new Ext.data.JsonStore({
        id : 'resource_id',
        fields     : ['resource_id', 'resource_name', 'resources','resource_type'],
		autoLoad   : false,
		url			: 'getActivites.cfm',
		listeners	: {
			//'load' : function(){ Ext.Msg.alert('here','here')}
		}
    });
	

	function buttonHandler(b,e){
	
		resource_store.load({
			params : {
				'resource_type': b.resource_type
			}
		});
	};
	
	resource_store.loadData(Ext.fiftynifty.resources);
	resource_store.load({params : {'resource_type': 1}});
    var panel = new Ext.Panel({
        frame      : false,
        renderTo   : 'all-resources',
        height     : 470,
		width		: 351,
		autoScroll : true,
		border: true,
        items      : new ResourcePanel({
            store : resource_store
        }),
		tbar : [{
			xtype : 'button',
			text: 'Activities',
			width : 60,
			enableToggle : true,
			toggleGroup	: 'sa',
			handler : buttonHandler,
			resource_type : 1,
			pressed : true
		},'-',{
			xtype : 'button',
			text: 'Games',
			width : 60,
			enableToggle : true,
			toggleGroup	: 'sa',
			handler : buttonHandler,
			resource_type : 2
		},'-',{
			xtype : 'button',
			text: 'Puzzles',
			width : 60,
			enableToggle : true,
			toggleGroup	: 'sa',
			handler : buttonHandler,
			resource_type : 4		
		},'-',{
			xtype : 'button',
			text: 'All',
			width : 60,
			enableToggle : true,
			toggleGroup	: 'sa',
			handler : function (){	resource_store.loadData(Ext.fiftynifty.resources); }
			
		}]
    });
});


Ext.fiftynifty.states = [
	['AL', 'Alabama'],
	['AK', 'Alaska'],
	['AZ', 'Arizona'],
	['AR', 'Arkansas'],
	['CA', 'California'],
	['CO', 'Colorado'],
	['CT', 'Connecticut'],
	['DE', 'Delaware'],
	['DC', 'District of Columbia'],
	['FL', 'Florida'],
	['GA', 'Georgia'],
	['HI', 'Hawaii'],
	['ID', 'Idaho'],
	['IL', 'Illinois'],
	['IN', 'Indiana'],
	['IA', 'Iowa'],
	['KS', 'Kansas'],
	['KY', 'Kentucky'],
	['LA', 'Louisiana'],
	['ME', 'Maine'],
	['MD', 'Maryland'],
	['MA', 'Massachusetts' ],
	['MI', 'Michigan'],
	['MN', 'Minnesota'],
	['MS', 'Mississippi'],
	['MO', 'Missouri'],
	['MT', 'Montana'],
	['NE', 'Nebraska'],
	['NV', 'Nevada'],
	['NH', 'New Hampshire'],
	['NJ', 'New Jersey'],
	['NM', 'New Mexico'],
	['NY', 'New York'],
	['NC', 'North Carolina'],
	['ND', 'North Dakota'],
	['OH', 'Ohio'],
	['OK', 'Oklahoma'],
	['OR', 'Oregon'],
	['PA', 'Pennsylvania'],
	['RI', 'Rhode Island'],
	['SC', 'South Carolina'],
	['SD', 'South Dakota'],
	['TN', 'Tennessee'],
	['TX', 'Texas'],
	['UT', 'Utah'],
	['VT', 'Vermont'],
	['VA', 'Virginia' ],
	['WA', 'Washington'],
	['WV', 'West Virginia'],
	['WI', 'Wisconsin'],
	['WY', 'Wyoming']
];

var store = new Ext.data.SimpleStore({
	fields: ['abbr', 'state'],
	data : Ext.fiftynifty.states // from states.js
});
var statecombo = new Ext.form.ComboBox({
	
	
});



namefieldgroup = new Ext.form.FieldSet({
	title : 'Personal Information',
	defaultType: 'textfield',
	defaults: {
		width			: 250,
		allowBlank		: false
    },
	items:[
		{fieldLabel	: 'First Name', name  : 'firstname'},
		{fieldLabel	: 'Last Name',	name  : 'lastname'},  
		{fieldLabel	: 'School Name',name  : 'schoolname'},  
		{fieldLabel	: 'Email', 		name  : 'email', vtype: 'email'}
	]
									   
});

addressfieldgroup = new Ext.form.FieldSet({
	title : 'Mailing Information',
	defaults: {
		width			: 250,
		allowBlank		: false
    },
	defaultType: 'textfield',
	items:[
		{fieldLabel	: 'Address', 	name  :	'address1'},  
		{fieldLabel	: '', 			name  : 'address2',allowBlank : true},  
		{fieldLabel	: 'City', 		name  : 'city'}, 
		{xtype:'combo',
			
			width:130,
			store: store,
			displayField:'state',
			typeAhead: true,
			mode: 'local',
			forceSelection: true,
			triggerAction: 'all',
			emptyText:'Select a state...',
			selectOnFocus:true,
			fieldLabel : 'State',
			name:'cbstate',
			valueField : 'abbr',
			hiddenName : 'state'
		},{
			fieldLabel	: 'Zip', 		
			name  : 'zip', 
			xtype:'numberfield', 
			maxLength:5, 
			minLength:5, 
			width:130,
			getValue : function(){ 
			   if(!this.rendered) {
					return this.value;
				}
				var v = this.el.getValue();
				if(v === this.emptyText || v === undefined){
					v = '';
				}
				return v;
			},
			setValue : function(v){
				this.value = v;
				if(this.rendered){
					this.el.dom.value = (Ext.isEmpty(v) ? '' : v);
					this.validate();
				}
				return this;
			},
			// private    
			parseValue : function(value){return value;   },
			// private    
			fixPrecision : function(value){return value;    }
			
		}
	]								   
});

var ckboxtext = "I'd like to receive more information about economic and personal finance education."

additionalfieldgroup = new Ext.form.FieldSet({
	title 		: 'Additional Information',
	items:[{
			xtype		: 'checkbox',
			boxLabel	: ckboxtext, 
			hideLabel	: true,	 
			name  		: 'additionalinfo', 
			width 		: 600,
			style		: {
				paddingLeft: '30px'
			}
		}
	]								   
});


orderform = new Ext.FormPanel({
	id				:	'orderform',
	autoScroll		:	true, 
	autoWidth		:	true, 
	bodyStyle		:	"padding: 20px;",
	labelWidth		:	100,
	items			:	[
		namefieldgroup,addressfieldgroup,additionalfieldgroup
		
	]
});
formwindow = new Ext.Window({
	y		:	50,
	title 	: 'Fifty Nifty Order Form',
	id 		: 'formwindow',
	layout 	: 'fit',
	modal	: true,
	closeAction : 'hide',
	width	: 650,
	height	: 500,
	items	: orderform,
	draggable : false,
	bbar	: [
		{
			xtype : 'tbfill'
		},		
		{
			text : 'Save',
			handler : submitForm
		},
		{	xtype : 'tbseparator'},
		{
			text : 'Cancel',
			handler : function(){
				formwindow.hide();
			}
		}
	]
});

function submitForm(){
	//validates the title field on the form
	
	var ofrm = Ext.getCmp('orderform').getForm();
	
	if(!ofrm.findField('firstname').validate())
	{
		return false;
	}
	if(!ofrm.findField('lastname').validate())
	{
		return false;
	}
	if(!ofrm.findField('schoolname').validate())
	{
		return false;
	}
	if(!ofrm.findField('email').validate())
	{
		return false;
	}
	
	if(!ofrm.findField('address1').validate())
	{
		return false;
	}
	if(!ofrm.findField('address2').validate())
	{
		return false;
	}
	if(!ofrm.findField('city').validate())
	{
		return false;
	}
	if(!ofrm.findField('state').validate())
	{
		return false;
	}
	
	if(!ofrm.findField('zip').validate())
	{
		return false;
	}
	
	
	 ofrm.submit({
		url: 'saveOrder.cfm',  
		params:{action:'add'},
		
		success:function(form, action) {
			Ext.Msg.show({
			   title:'Order confirmation',
			   msg: '<div style="padding:10"><br/>Thank you for ordering the Fifty Nifty cards and the Teacher Resource Guide. Your request will be processed soon.<br /><br />Until that time, view <a href="http://www.FederalReserveEducation.org/resources/fiftynifty/">www.FederalReserveEducation.org/resources/fiftynifty/</a> <br/> to download assessments, activities and games.<br /></div>',
			   buttons: Ext.Msg.OK,
			   icon: Ext.MessageBox.INFO,
			   width: 550
			});
			formwindow.hide();
		},
		
		failure: function(form, action) {
			Ext.MessageBox.alert('Save Error','The order was not process.');
		}
	}); 
}

function showForm(){
	orderform.getForm().reset();
	formwindow.show();
};


