/**
 // ***************************************************************************************
 //   INCLUDE:
 //   /js/new_account.js
 //
 //   PURPOSE:
 //   This file provides javascript support for new account registration
 //
 //   teagan [6.20.2010]
 // ***************************************************************************************
 */
Ext.onReady(function() {

	// ------------------------------------
	// declare the "save the form" function
    var saveForm = function(button, event) {
		var form = Ext.getCmp('new_account_main_form');

		// Save the library with the base parameters
		Ext.apply(form.baseParams,{
			 method: 'register'
			,library: this.library
		}); 
		
		form.form.submit({
			 clientValidation: true
			,submitEmptyText: false
            ,waitMsg:'Registering...'
			
			// form successfully saved
            ,success: function (form, action) {
                Ext.MessageBox.alert('Thank You!', 'A welcome email has been sent.  Please follow the directions in it to activate your account');
				newAccountWindow.hide();
            }
			
			// form save failed
            ,failure:function(form, action) {		
                Ext.MessageBox.alert('Message', 'Save failed - ' + action.result.message);
            }
		});
				
    } // eo function saveForm


	// ---------------------------------
	// Create the new account form
	var newAccountForm = new Ext.FormPanel({
		 url: Slush.app.mappings_com + 'slush/users.cfc'
		,baseParams:{
		  returnFormat: 'JSON'
		}
		,border: false
		,id: 'new_account_main_form'
		,width: 570
		,height: 575
		,flex: 1
		,layout: 'form'
		,monitorValid: true
		,defaults: {
			 msgTarget: 'side'
			,xtype: 'textfield'
			,allowBlank: false
			,anchor: '-50' 
		}
        ,items: [{
			 xtype: 'box'
			,anchor: '100%' 
			,html: 	'<div style="text-align: center;">' +
						'<b>Welcome to the community of Teachers and Learners "Source-Links-Under-Shared-Headings".</b><br>' +
						'<span class="small">' +
							'We have the singular goal of aggregating the resources we can all use, to create, understand and share.' +
						'</span>' +
					'</div>'
		},{
			 name:'email'
			,id: 'newAccount_Email'
			,maskRe: /([^<>;'"]+)$/  
			,vtype: 'email'  
			,validationEvent: 'blur'
			,fieldLabel: 'Email address'
			,maxLength: 100			
			,itemCls: 'spacerDbl'
		 },{					
			 name:'emailConfirm'
			,vtype: 'confirm'
			,validationEvent: 'blur'
			,originalField: 'newAccount_Email'  
			,fieldLabel: 'Confirm'
			,emptyText: 'Please enter your Email Address again'
			,maxLength: 100
		},{					
			 name:'password'
			,fieldLabel: 'Password'
			,id: 'newAccount_Password'
			,maskRe: /([^<>;'"]+)$/  
			,inputType: 'password'
			,maxLength: 30			
			,minLength: 6			
			,anchor: '60%' 
			,itemCls: 'spacer'
		},{
			 name:'passwordConfirm'
			,fieldLabel: 'Confirm'
			,inputType: 'password'
			,vtype: 'confirm'
			,originalField: 'newAccount_Password'  
			,maxLength: 30			
			,minLength: 6			
			,anchor: '60%' 
		},{					
			 xtype: 'compositefield'
			,msgTarget: 'side'
			,fieldLabel: 'User name'
			,itemCls: 'spacer'
            ,items: [{
				 name:'username'
				,id: 'newAccount_Username'
				,maskRe: /([^ <>;'"]+)$/  
				,xtype: 'textfield'
				,allowBlank: false
				,maxLength: 9	
				,minLength: 4	
				
			// ----- Check Availability ----
			},{
				 xtype: 'button'
				,text: 'Check Availability'
				,handler: function(btn, evt) {
					var usernameVal = Ext.getCmp('newAccount_Username').getValue().trim();
					if (usernameVal != '' && usernameVal != null) {
					
						Ext.Ajax.request({   
							 waitMsg: 'Checking...'
							,url: Slush.app.mappings_com + 'slush/users.cfc'
							,params: {
								method: 'chkDisplayName',
								returnFormat: 'JSON',
								displayName: Ext.getCmp('newAccount_Username').getValue()
							} 
							,success: function(response){   
								var result=Ext.util.JSON.decode(response.responseText);
								if(result.success){
									Ext.example.msg({title:'Yes!', anchor:'l', pause:3}, "It's Available.");
								} else {
									Ext.example.msg({title:'Sorry', anchor:'l', pause:3}, result.message);
								}
							}
							,failure: function(response){
								var result=response.responseText;
								Ext.MessageBox.alert('Error','Could not connect to the database. Please retry later');    
							}                     
						}); // eo ajax request   
						
					} // eo if value not null
				} // eo handler
				
			}] // eo composite field items
		},{
			 xtype: 'panel'
			,title: 'Registration Agreement'
			,anchor: '-30' 
			,autoScroll: true
			,height: 200
			,margins: '30 0 0 14'
			,contentEl: 'license_text_hidden'
			,cls: 'spacerDbl'
		},{
			 xtype: 'box'
			,anchor: '-20' 
			,cls: 'spacerDbl'
			,html: 	'<div style="text-align: center;">' +
						'<b>Choose a favorite library below to complete your registration</b>' +
					'</div>'
					
		}] // eo config items array

		,buttonAlign: 'center'
        ,buttons: [
			 createLibButton('code',{handler: saveForm})
			,createLibButton('web', {handler: saveForm})
			,createLibButton('tech',{handler: saveForm})
			,createLibButton('art', {handler: saveForm})
			,createLibButton('apps',{handler: saveForm})
			,{
			 	 scale: 'medium'
				,id: 'addSlushButton_close'
				,cls: 'x-hidden'
            	,text: 'close'
				,handler: function() {window.close();}
			}
		]
    });


	// ------------------------------
	// Create the new account window
	var newAccountWindow = new Ext.Window({
		 id: 'newAccountWindow'
		,bodyCssClass: 'windowBg'
		,constrain: true
		,resizable: false
		,closable: true
		,closeAction: 'hide'
		,width: 615
		,height: 716
		,layout: 'vbox'
		,items: [
			{
			 xtype: 'box'
			,width: 570
			,height: 55
			,html: 	'<div id="user_info">' +
						'<div id="user_info_new" class="section">' +
							'<br />' +
							'<span class="new_account_link xlarge"><b>New Account Registration</b></span>' +
						'</div>' +
					'</div>'
			}
		,newAccountForm]
	});

	// ----------------------------------------------------------
	// get all of the elements with the new account class
	var links = Ext.select('.new_account_link');
	links.addClassOnOver('a_hover');
	// show the new account window when the element is clicked
	links.on('click', function(event, el, options) {
		newAccountWindow.show();
	});


    /**
     * Convenience function for creating Library submit buttons
     * @param {Object} config Optional config object
     * @return {Ext.Button} The new Button object
     */
    function createLibButton(library, config) {
		// Create a template for the buttons
		var buttonTpl = new Ext.XTemplate(
			'<span class="page_footer_libs_the" style="margin:0 0 0 3px;">the</span>',
			'<span class="page_footer_libs_lib color{lib}">',
				'{lib}<img src="images/page/tt_lib_{lib}.png">',
			'</span>'
		);
		
		// Create the button
        config = config || {};		
        Ext.applyIf(config, {
			 scale: 'medium'
			,id: 'addSlushButton_' + library
			,formBind: true
            ,text: buttonTpl.apply({lib:library})
			,library: library
        });        
		
		// return out
        return new Ext.Button(config);
    };

	  
}); // Ext.onReady

