dojo.require("domino.form.FilteringSelect");
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("domino.data.ViewStore");
dojo.require("dijit.form.Textarea");
dojo.require("dijit.form.Form");
dojo.require("dijit.form.CheckBox");
dojo.require("dijit.Dialog");
dojo.require("dojo.data.ItemFileWriteStore");
dojo.require("dijit.form.SimpleTextarea");
dojo.require("dijit.form.NumberTextBox");

/*
my maxForm inherits from dijit.form. 
*/
dojo.declare("maxForm",dijit.form.Form, {
		
		origValues : null,
		isNewDoc : null,		
		validFlag: null,
		currPage:null,
		prevPage:null,
		nextPage:null,
		formLoaded:false,
		reqId:null,
		reqNo:null,
		JOAStatus:null, 
					
		// This is called from page load and initializes the values of the form
		initializeForm: function(  appId, reqNo, cPage, nPage, pPage, newDoc, JOAStatus ){
			//console.debug("start initializeForm");
			var form = document.forms[0];			
			var pageName = "valid_pg" + cPage ;
			
			this.reqId = appId;
			this.reqNo = reqNo;
			this.currPage = cPage;
			this.nextPage = nPage;
			this.prevPage = pPage;
			this.isNewDoc = (newDoc === "true");
			this.JOAStatus = JOAStatus;
			
			this.formLoaded=true;		
			this.loadItemValues();	// Save a copy of the initial item values
			if (this.isNewDoc) { 
				this.validFlag = ""
			} else {
				this.validFlag = form[ pageName ].value;
				// If we have been to this page before,  and the 
				if ( this.validFlag === "false" ) {
					this.validate();		
				}
			}
		},
								
		loadItemValues:function(){
			//console.debug("entering loadItemValues");
			this.origValues = this.getItemValues();		
		},
		
		// This will get all the values of all form widgets for comparison later.
		getItemValues : function( lDoc /* if lDoc take the item values from the notes document */ ){
			//console.debug("entering getItemValues");
			
			var buttonList = [];
			var values = {};
			
	 		dojo.forEach( this.getDescendants(), function(widget){
				var value = widget.getValue ? widget.getValue() : widget.value;
				var name = widget.name;			
									
				if(widget.setChecked){
				
					if(/Radio/.test(widget.declaredClass)){
						// radio button				
						if (!dojo.getObject(name, false, values)){
							dojo.setObject(name, "", values);
						};
				
						if(widget.checked){
							dojo.setObject(name, value, values);
						}
					}else{
						// checkbox/toggle button
						if (!dojo.getObject(name, false, values)){
							dojo.setObject(name, "", values);
						};
				
						if(widget.checked){
							var curVal = dojo.getObject(name, false, values)
							var newVal = (curVal == "") ? value : curVal += ("/" + value);
							dojo.setObject(name, newVal, values);
						};
					}
				}else{		
					if( /Date/.test(widget.declaredClass)) {									
						if(value){
							value = dojo.date.locale.format(value, {selector:'date', datePattern:'yyyy-MM-dd'}).toLowerCase();
						} else {
							value = ""	
						}
					};
			
					if( /Number/.test(widget.declaredClass)) {									
						if( isNaN( value )  ){					
							value = 0
						}
					};
			
					dojo.setObject(name, value, values);
				}
			});
	
			// Some pages may need to get data not contained in widgets, such as references or education information 
			// if there is a pageGetData function on the form, then call it.
			if( window.pageGetData) { 
				pageGetData( lDoc, values );
			}
			return values;
		},
		
		// Return true if the field values have changed, else false
		isChanged: function() {
			var objA = this.origValues;
			var objB = this.getItemValues();
			
			for (fieldName in objA) {
				if ( objA[fieldName] !== objB[fieldName]) { //different (atom) values				
					//console.debug( "field name:" + fieldName +", orig:" + objA[fieldName] + ", new:" + objB[fieldName] );
					
          			return true
        		};                     
			};		
			
    		return false
		},
		
		isValid: function(){
			var buttonList = [];
			var isValid = true;
			// If the page has it's own validate function, use it!
			if( window.pageValidate ) { 
				isValid = pageValidate();
			} else {				
		 		dojo.forEach( this.getDescendants(), function(widget){
			    	if( /Radio/.test(widget.declaredClass)){ 
				    	/* If the widget is a radio button */
				    	/* check the button list to see if we have already validated this set of buttons */
		   			 	if ( !widget.disabled  ){
		    				if ( dojo.indexOf( buttonList, widget.name)<0 ) {			    
			   					buttonList.push( widget.name );			   							   				
			  					var value = getSelectedRadioValue( dojo.query( "[name='" + widget.name + "']" ));
			  					// var value = widget.groupValue();
			  					if ( value === "" ){				  					
		  							isValid = false;	
		  			 			} 
	  						}	 
						}
					} else {
	    				if ( ! widget.disabled  ) { /* dont worry about disabled widgets */
							if ( widget.isValid && !widget.isValid() ) {		  												
								isValid = false;				  			
		  					}
			  			} 
					}
 				});
			};
			return isValid;
		},
		
		// Return an array of widget information for debugging
		getWidgetStatus: function(){			
			var retArray= [];
		 	dojo.forEach( this.getDescendants(), function(widget){
			 	var oData = {};
			 	dojo.setObject("id", widget.id, oData );				
				dojo.setObject("value", widget.value, oData );						
				dojo.setObject("class", widget.declaredClass, oData );								
				dojo.setObject("disabled", widget.disabled ? "true" : "false", oData );	
				
				var isValid = "valid";
			    if( /Radio/.test(widget.declaredClass)){ 
				    	
		   			if ( !widget.disabled  ){			    
			   			var value = getSelectedRadioValue( dojo.query( "[name='" + widget.name + "']" ));			  				
			  			if ( value == "" ){
				 				isValid = "not valid";		  						
		  		 		}  						 
					}
				} else {
	    			if ( ! widget.disabled  ) { /* dont worry about disabled widgets */
						if ( widget.isValid && !widget.isValid() ) {				
		  					isValid = "not valid";
			  			}
					} 
				}
							
				dojo.setObject("valid", isValid, oData );											
				dojo.setObject("class", widget.declaredClass, oData );												
				retArray.push( oData );				    
 			});
			return retArray;
		},
					
		validate: function(){	
			var buttonList = [];
			var firstwidget;	
		
			// If the page has it's own validate function, use it!
			if( window.pageValidate ) { 
				return pageValidate();
			} else {
			
    			dojo.forEach( this.getDescendants(), function(widget){

			    if( /Radio/.test(widget.declaredClass)){ 
				    /* If the widget is a radio button */
				    /* check the button list to see if we have already validated this set of buttons */
		   			 if ( !widget.disabled  ){
		    			if ( dojo.indexOf( buttonList, widget.name)<0 ) {			    
			   				buttonList.push( widget.name );
			  				var value = getSelectedRadioValue( dojo.query( "[name='" + widget.name + "']" ));
			  				
			  				if ( value == "" ){
				  				//console.debug( widget.name + " is not valid" );	
				  				// alert( "radio group " + widget.name + " is " + ( value == ""?"not valid ":"valid with a value of "+ value  ) )		
		  						dojo.query( "[id='" + widget.name + "']").style({
									backgroundColor:'red',
									color:'white'								
								});
		  					
		  						/* Hang on to the first invalid widget */ 
		    					if ( ! firstwidget ) {firstwidget = widget};
		  			 		} 
	  					}	 
					}
				} else {
	    			if ( ! widget.disabled  ) { /* dont worry about disabled widgets */
						if ( widget.isValid && !widget.isValid() ) {				
		  				
							//console.debug(widget.name + " is enabled and failed validation!"); 
				
				  			/* call the widget's validate function, if there is one! */
				    		if( widget.validate ){ widget.validate(true) };
			    	
				    		/* set focus to the widget */
	    					widget.focus();
	    			
	    					/* Hang on to the first invalid widget */ 
		    				if ( ! firstwidget ) {firstwidget = widget}
		  				}
					} else {
						// if( widget.disabled ){alert( "widget: " + widget.name + " is disabled." )};			
					} 
				}
				// if( widget.disabled ){console.debug( "widget: " + widget.name + " is disabled." )};	
			});
		
			if ( firstwidget ) {
				//dijit.scrollIntoView(firstwidget.containerNode||firstwidget.domNode);
				//firstwidget.focus();
				//alert("Form Validation Failed!");
				//return false;
				return true;
			} else {
				/* This is where we'll submit the form */ 		
				return true;
			};
	 		};			
		},

			
		// This removes disabled Inputs from the DOM, it is called before the form is submitted. 
		stripDisabledWidgets: function(){		
			dojo.forEach(this.getDescendants(), function(widget){    
				if ( widget.disabled  ) {
					//console.debug( "destroying widget:" + widget.name );
					widget.destroy();
				}
			});
		},
		
		onSubmit: function(/*Event?*/e){ 
			//	summary:
			//		Callback before user submits the form.  
			// 		If there is a function on the page called pageSubmit(), it will be called. This function must
			//		return True or False if the page can be submitted. 
			//		If no pageSubmit function is found, just return true.			
			if( window.pageSubmit ) { 
				return pageSubmit();
			} else {	
				return true;
			}	
		},
		
		submit: function(){
			// summary:
			//		programmatically submit form 
			if(!(this.onSubmit() === false)){			
				// If the page has a load data function, execute it!
				if( window.pageLoadData) { 
					pageLoadData();
				}				
				// Remove any disabled widgets from the form
				this.stripDisabledWidgets();
				// and submit the form to Notes
				this.containerNode.submit();	
			}		
		}
})

/*
my maxRadioButton
*/
dojo.declare("maxRadioButton", dijit.form.RadioButton, {
	labelId:"",
	
	groupValue: function(){
		var retVal = "";
		dojo.forEach(this._groups[this.name], function(widget){
				if( widget.checked ){
					retVal  = widget.value;					
				}
		}, this);
		return retVal;	
	},
		
	isValid: function() { /* if any widget in the group is checked, return true */
		var lValid = false;
		dojo.forEach(this._groups[this.name], function(widget){
				if( widget.checked ){
					lValid = true;					
				}
		}, this);
		
		if (!lValid ){			
			//dojo.query( "[id='" + this.name + "']").style({
			//					backgroundColor:'red',
			//					color:'white'								
			//			});
		} ;
		
		return lValid
	},
	
	validate: function(/*Boolean*/ isFocused){
			// summary:
			//		Called by oninit, onblur, and onkeypress.
			// description:
			//		Show missing or invalid messages if appropriate, and highlight textbox field.
			var isValid = this.isValid();			
			return isValid;
	},
		
	_clicked: function(/*Event*/ e){
			this.inherited(arguments);
			
			if( this.labelId =="" ){ this.labelId = this.name };	
			dojo.query( "[id='" + this.labelId + "']").style({			
							backgroundColor:'transparent',
							color:'black'								
						});					
			// console.debug(this.name + ": value=" + this.value + "." );			
				
		return true;
		}
	
})
		
dojo.declare("maxCIARadioButton", maxRadioButton, {
	_clicked: function(/*Event*/ e){
			this.inherited(arguments);
			showError( "<p style='font-weight:bold;color:red;text-align:center'>** WARNING **</p><p style='font-weight:bold;text-align:center'>If yes, you are not eligible to work for MAXIMUS.</p>" )		
			//console.debug("CIA Radio Button: " + this.name + ": value=" + this.value + "." );			
				
		return true;
		}
	
})
	
dojo.declare("maxTextArea",dijit.form.Textarea, {
	//		Can be true or false, default is false.
	required: false,
	labelId:"",
	_onKeyPress: function(e){		
		this.inherited(arguments);
		if( this.labelId =="" ){ this.labelId = this.name };	
		dojo.query( "[id='" + this.labelId + "']").style({			
							backgroundColor:'transparent',
							color:'black'								
						});			
		return true;
	},
	isValid: function() {					
		var myValue = trimAll( this.getValue());
		var imEmpty = isEmpty( myValue );	
		return ( this.required && imEmpty )? false: true;
		
		//if ( !this.disabled ){
		//	console.debug( "maxTextArea name:" + this.name + ", is Valid" );
		//	return true;
		//}else {
		//	console.debug( "maxTextArea name:" + this.name + ", is NOT Valid" );
		//	return ( this.required && imEmpty )? false: true;
		//}
	},
	
	validate: function() {					
		// summary:
		//		Called by oninit, onblur, and onkeypress.
		// description:
		//		Show missing or invalid messages if appropriate, and highlight textbox field.
		var isValid = this.isValid();
		if( this.labelId =="" ){ this.labelId = this.name };
		if (!isValid){						
			dojo.query( "[id='" + this.labelId + "']").style({	
				backgroundColor:'yellow',
				color:'black'								
			});		
		}
		return isValid;
			
	}
})


// This var contain an JSON array of divs that are hidden or show on the various pages
// This JSON object is used by showDiv and HideDiv
// Each entry contains the name of the widgets in the div which must be enabled or disabled
var divList = { 
				"US_city": 		{ fields :  ["City","State","Zip"] },
				"non_US_city": 	{ fields :  ["ForeignCity","Province","ForeignZip"] },
				"Agency": 		{ fields :  ["EmpAgency" ] },
				"Website": 		{ fields :  ["WebsiteName"] },
				"MAXEmp": 		{ fields :  ["MAXEmpName" ] },
				"Other": 		{ fields :  ["OtherDesc" ] },		
				"q1_exp": 		{ fields :  ["FormerEmpLoc" ] },		
				"q2_exp":		{ fields :  ["WorkPaperY","WorkPaperN"] },											
				"q4_exp":		{ fields :  ["WorkStatusExp"] },
				"q6_exp":		{ fields :  ["CriminalOffenseExplaination"] },
				"q7_table":		{ fields :  ["EmpRelativeName_1","EmpRelativeRel_1","EmpRelativePos_1","EmpRelativeName_2","EmpRelativeRel_2","EmpRelativePos_2","EmpRelativeName_3","EmpRelativeRel_3","EmpRelativePos_3"] },
				"q16_table": 	{ fields :  ["ConflictsOfInterest_Name","ConflictsOfInterest_GovAgency","ConflictsOfInterest_Invol"] },
				"q18_exp":	 	{ fields :  ["GovAgencyDesc"] },
				"education_details":{ fields :  ["HSName","HSLoc" ]}				
				}

/***************************************************************************************************/

function createNewDoc(){
	window.location.href = session.currentDatabase.WebFilePath +"frmJobApp?readForm&page=1";
}

function goNextPage(){
	moveToPage(gForm.nextPage);		
}

function goPrevPage(){
	moveToPage(gForm.prevPage);
}
				
// This function actually submits the appication and takes the user to the 
// Thank you page.
function submitForm(){
	//console.debug("I'm in Submit Form.")
	var form = document.forms[0];
	var oForm = dijit.byId("frmMain");		
	var errStr = "";
	var certCheck = dijit.byId("CertCheck_1").checked;
	var page1 = (form.valid_pg1.value === "true");
	var page2 = (form.valid_pg2.value === "true");
	var page3 = (form.valid_pg3.value === "true");
	var page4 = (form.valid_pg4.value === "true");
	var page5 = (form.valid_pg5.value === "true");
	var page6 = (form.valid_pg6.value === "true");
	var page7 = (form.valid_pg7.value === "true");
	var sign  = (!(form.sign.value === ""));
	//console.debug( certCheck );
	// If all is valid, then submit the application
	if ( certCheck && page1 && page2 && page3 && page4 && page5 && page6 && page7 && sign ){
		document.forms[0].doc_nextpage.value = "ThankYou";
		document.forms[0].doc_submitted.value = "Yes";	
		oForm.submit();
	} else {
		if(!( certCheck )) {
			errStr += "<p style='font-weight:bold;text-align:center'>You must check the Certification Box to submit this application.</p>";
			//alert( "You must check the Certification Box to submit this application.");
		}
		
		if (!( page1 && page2 && page3 && page4 && page5 && page6 && page7 )){
			errStr += "<p style='font-weight:bold;text-align:center'>Any application section marked with a Red X must be completed.</p>";
			//alert( "Any application section marked with a Red X must be completed!");
		}
		
		if(!( sign )) {
			errStr += "<p style='font-weight:bold;text-align:center'>You must sign the application before submission.</p>";
			// alert( "You must sign the application before submission.");
		}
		
		if (!(errStr==="")) {
			errStr = "<p style='font-weight:bold;color:red;text-align:center'>** ERROR **</p>" + errStr;
			showError( errStr );
			}
				
	}	
}

// Move to the next Page
// This is the AJAX version
function moveToPage( strPageNumber ){
	//console.debug("moving to page " + strPageNumber )
	
	var oForm = dijit.byId("frmMain");	
	var form = document.forms[0];	
	
	if ( oForm ){	
		
		// Set the isChanged value of the form to send to the query save. isChanged defaults to "false"
		if ( oForm.isChanged() ) { form.isChanged.value = "true"; } else  { form.isChanged.value = "false"; }
		
		// Set the page requested to move to
		form.doc_nextpage.value = strPageNumber;
		
		// Set the current page	
		form.doc_curpage.value = gForm.currPage;
				
		// Submit the form using AJAX	
		dojo.xhrPost({        		
			load: function(responseObject, ioArgs){
			        	if(responseObject.result === "error" ){
				        	if ( gForm.currPage === "8"  ){ 					        	
								showError( responseObject.errMsg );	
					        } else {
				        		var answer = confirm("Missing Required Field(s):\n\n" + responseObject.errMsg +"\n\nContinue anyway?\n(your information will be saved) " )
								if (answer){window.location.href = session.currentDatabase.WebFilePath + responseObject.nextURL;}
							}				        	
				        } else {					        
					        //console.debug( session.currentDatabase.WebFilePath + responseObject.nextURL );
							window.location.href = session.currentDatabase.WebFilePath + responseObject.nextURL;
					    }
			        	
			        	
        	    	    //console.dir( responseObject );        	    	    
        				},
        	error: function(data){
                		console.dir( data );
        				},
        	timeout: 2000,
        	handleAs: "json",
        	form: "frmMain" 
        	}			
		);
	};
}


// This is the AJAX version without submit
function moveToPage_v1( strPageNumber ){
	//console.debug("moving to page " + strPageNumber )
	
	var oForm = dijit.byId("frmMain");	
	var form = document.forms[0];	
	
	if ( oForm ){	
						
		// If anything changed, then validate the form		
		if ( oForm.currPage!="8" && oForm.isChanged() ){		
			
			form.doc_nextpage.value = strPageNumber;	
			form.doc_curpage.value = gForm.currPage;	
			
			dojo.xhrPost({        		
		        load: function(responseObject, ioArgs){
			        	if(responseObject.result === "error" ){
				        	var answer = confirm("Missing Required Field(s):\n\n" + responseObject.errMsg +"\n\nContinue anyway?" )
							if (answer){
								window.location.href = session.currentDatabase.WebFilePath + responseObject.nextURL;	
							}				        	
				        } else {					        
					        //console.debug( session.currentDatabase.WebFilePath + responseObject.nextURL );
							window.location.href = session.currentDatabase.WebFilePath + responseObject.nextURL;
					    }
			        	
			        	
        	    	    //console.dir( responseObject );        	    	    
        				},
        		error: function(data){
                		console.dir( data );
        				},
        		timeout: 2000,
        		handleAs: "json",
        		form: "frmMain" 
        		}			
			);	
			 		
		} else {
			// No data on the form changed, or we are on the summary page, so just go to the specified page.
			if (gForm.reqId=="new"){
				window.location.href = session.currentDatabase.WebFilePath +"frmJobApp?readForm&page=" + strPageNumber+ "&ReqID=" + gForm.reqNo;	
			} else {
				window.location.href = session.currentDatabase.WebFilePath +"vwAllWebApps/" + gForm.reqId + "?openDocument&page=" + strPageNumber + "&ReqID=" + form.jobCode.value;		
			}
		};
	};
}


function moveToPage_old( strPageNumber ){
	//console.debug("moving to page " + strPageNumber )
	var oForm = dijit.byId("frmMain");	
	var form = document.forms[0];	
	
	if ( oForm ){
					
		// If anything changed, then validate the form		
		if ( oForm.currPage!="8" && oForm.isChanged() ){		
			//alert("form data has changed.")	
			var isValid = oForm.isValid();
			
			//if (isValid) {
			//	alert("form data is valid." );
			//}else{
			//	alert("form data is NOT valid." );	
			//}
			
			form["valid_pg" + gForm.currPage ].value = isValid;
			form.doc_nextpage.value = strPageNumber;	
			form.doc_curpage.value = gForm.currPage;	
			//alert( "submitting the page");
	 		oForm.submit();			
		} else {
			// No data on the form changed, or we are on the summary page, so just go to the specified page.
			if (gForm.reqId=="new"){
				window.location.href = session.currentDatabase.WebFilePath +"frmJobApp?readForm&page=" + strPageNumber+ "&ReqID=" + gForm.reqNo;	
			} else {
				window.location.href = session.currentDatabase.WebFilePath +"vwAllWebApps/" + gForm.reqId + "?openDocument&page=" + strPageNumber + "&ReqID=" + form.jobCode.value;		
			}
		};
	
	};
}	

// Show a div and enable it's widgets
function showDiv( divName ){
	if (gForm.formLoaded) {	
		var oDiv = dojo.byId( divName );
		if (oDiv) {
			//console.debug("show div: " + divName );
			if( oDiv.style.display == 'none' ) {
				 oDiv.style.display = 'block';
				
				 if ( divList[ divName ] ){ 			
					for (var x in divList[ divName ].fields ) {
						var oWidget = dijit.byId(divList[ divName ].fields[x]);
						if( oWidget ) {
							oWidget.setAttribute("disabled",false);
						} else {
							console.debug( "could not find widget:" + divList[ divName ].fields[x] + " to disable.")	
						};
					};					
				};
			}
		} else { 
			console.debug( "showDiv():" + divName + " could not be found." )
		}
	}
}

// Hide a div and disable it's widgets
function hideDiv( divName ){
	if (gForm.formLoaded) {
		var oDiv = dojo.byId( divName );
		if (oDiv) {	 
			//console.debug("hide div: " + divName );
			if( oDiv.style.display == 'block' ) {
				oDiv.style.display = 'none';			
				
		 		if ( divList[ divName ] ){ 			
					for (var x in divList[ divName ].fields ) {
						dijit.byId(divList[ divName ].fields[x]).setAttribute("disabled",true)																								
					};					
				};
			};	
		} else { 
			console.debug( "hideDiv():" + divName + " could not be found." )
		}
	}
}

// Makes a dojo input field read-Only
function makeReadOnlyById(fieldId) {	
    var field = dojo.byId(fieldId);
    field.readOnly = true;
    field.style.cursor = 'default';
    dojo.connect(field, 'onfocus', function () { field.blur(); });
}

// Show or hide the city state info based on country code.
function showCityState( widget ){		
	var countryCode = widget.getValue ? widget.getValue() : widget.value;		
	if (countryCode == "US") {	
			showDiv("US_city");			
			hideDiv("non_US_city");						
		} else {		
			showDiv("non_US_city");			
			hideDiv("US_city"); 
	};
}

// This is the on change for the Source Type input
function showSource() {
	var sourceName = this.getValue();	
	var options = { 
		"Employment Agency": 			{ div : "Agency"},
		"Other":						{ div : "Other" },		
		"Internet Job Posting Site":	{ div : "Website"},
		"Referred by MAXIMUS Employee":	{ div : "MAXEmp" }
		};		
	
	// First hide all the divs	
	for (var x in options) { 	
		hideDiv( options[x].div );
	}	
	
	// Show the hidden input if avalable	
	if ( options[ sourceName] ) {
				showDiv( options[ sourceName ].div  );
	}
				
}		

// OnChange function for Radio Buttons
function rb_Click( widget, divName, showVal ){	
	var rb_name = widget.name
	var value = getSelectedRadioValue( dojo.query( "[name='"+ rb_name +"']" ));
	//console.debug( "divName=" + divName + " radioGroup=" + rb_name + " value=" + value +".");
	
	
	// This hi-lites the radio button text when invalid
	if (!(value =="")) {
		dojo.query("[id='" + rb_name + "']")
						.style({
							backgroundColor:'transparent',
							color:'black'								
						});		
	}
		
	// This is a special case for question 18
	if(divName){
		if (divName=="q18_exp"){
			var q17val = getSelectedRadioValue( dojo.query( "[name='GovAgency']" ));			
			//console.debug("q17="+q17val);
			var q18val = getSelectedRadioValue( dojo.query( "[name='GovProcurement']" ));
			//console.debug("q18="+q18val);
			if( q17val=="No" && q18val=="No" ){ hideDiv(divName) }
			else if(( q17val=="Yes" || q18val=="Yes" )) {showDiv(divName) };	
		} else {
			if (value === showVal ) { showDiv(divName) } else {hideDiv(divName)};	
		};
	};
}		

// Retun True of False if the fields on a dialog box are valid
function validateDialog( oNode ){
	var isOk = true;
	var values = {};	
			
	dojo.forEach(oNode.getDescendants(), function(widget){
			var value = widget.getValue ? widget.getValue() : widget.value;
			var name = widget.name;
			if(!( widget.type=="hidden")){
				
				if(widget.setChecked){
					if(/Radio/.test(widget.declaredClass)){
						// radio button
						if(widget.checked){
							dojo.setObject(name, value, values );
						}
					}else{
						// checkbox/toggle button
						var ary=dojo.getObject(name, false, values);
						if(!ary){
							ary=[];
							dojo.setObject(name, ary, values);
						}
						if(widget.checked){
							ary.push(value);
						}
					}
				}else{
					// plain input				
					if(widget.required && value==""){
						widget.focus()
						isOk = false;
					}else if(value!="" && widget.state=="Error"){
						widget.focus()
						isOk = false;
					}					
					if  (!( isEmpty(value) )) { 							

							if( typeof value == 'string' ) {																						
								value = value.replace(/['"]/g, "");								
							}							
							
							dojo.setObject(name, value, values )
						};
				}
			}	
	});	
	if (isOk){ return values }else {return false };
}

// Delete an item from a store based on the items rowIndex, used by all the table builder functions
function deleteItem( store, rowIndex ){
	//Define a simple error handler.
	var gotError = function(error, request){
    	console.debug("The request to the store failed. " +  error);
	};
	
	// Define a call back to actually delete the passed item.
	var gotItem = function( item ){	store.deleteItem( item )	}
		
	// Query the store to get the item to delete
	store.fetchItemByIdentity({		
  		identity: rowIndex, 
  		onItem: gotItem,
  		onError: gotError
		});	
}

// Retun the number of items in a store.
function storeCount( store ){
	var retNum = 0;
	
	var gotItems = function(items, request){
    	retNum = items.length;
    	//alert("The store count = " +  retNum );
	};
	
	var gotError = function(error, request){
    	alert("The request to the store failed. " +  error);
	}
		
	store.fetch({
		onComplete: gotItems,
		onError: gotError
		});
		
	return retNum;
}


// Called from the summary page to "Sign" the application
function signApplication(){
	var form = document.forms[0];
	var today_date= new Date()
	var month=today_date.getMonth()+1
	var today=today_date.getDate()
	var year=today_date.getFullYear()
	
	var page1 = (form.valid_pg1.value === "true");
	var page2 = (form.valid_pg2.value === "true");
	var page3 = (form.valid_pg3.value === "true");
	var page4 = (form.valid_pg4.value === "true");
	var page5 = (form.valid_pg5.value === "true");
	var page6 = (form.valid_pg6.value === "true");
	var page7 = (form.valid_pg7.value === "true");
	
	// If all is valid, then submit the application
	if ( page1 && page2 && page3 && page4 && page5 && page6 && page7 ){
		var signature = getSignature();
		var submittedDate = month+"/"+today+"/"+year;
				
		form.sign.value = signature;
		form.submittedDate.value = submittedDate;
		
		var strHTML = "<table CELLPADDING=5>"
		strHTML += "<tr><td><strong>Signature:</strong></td><td>" +  signature + "</td></tr>";
		strHTML += "<tr><td><strong>Date Submitted:</strong></td><td>" +  submittedDate + "</td></tr>";
		strHTML += "</table>";				
		dojo.byId("appSignature").innerHTML = strHTML;		
		
	} else {	
		alert("All application pages must be valid before you can sign the application!");
	}	
};

// Calling Method for the Error Dialog
function showError( errMsg ){
	oDialog = dijit.byId( "dialogError");
	oDiv = dojo.byId("errorContainer");
	oDiv.innerHTML = errMsg;
	oDialog.show();	
}

// Calling Method for the Error Dialog
function showPrivacyDialog(){	
	var oDialog = dijit.byId('privacy');
	oDialog.setHref( session.currentDatabase.WebFilePath + "privacy.html?OpenPage" )     
	oDialog.show();	
}

function showWidgetStatus(){
	var oForm = dijit.byId("frmMain");
	var aWidgets = oForm.getWidgetStatus();
	var isValid = oForm.isValid();
	
	var sHTML = "<table><tr><td>id:</td><td>value</td><td>disabled</td><td>valid</td></tr>"
	dojo.forEach( aWidgets, function (item) {
		sHTML += "<tr>"
  		sHTML += "<td>" + item.id + "</td>"
  		sHTML += "<td>" + item.value + "</td>"
  		sHTML += "<td>" + item.disabled + "</td>"
  		sHTML += "<td>" + item.valid + "</td>"  		
  		sHTML += "</tr>"
	});
	
	sHTML += "</table>";
	
	if (isValid) {
		sHTML += "<p>The form is valid!</p>";
	} else {
		sHTML += "<p>The form is NOT valid!</p>";
	}
	showError( sHTML );	
}

