/*  © Copyright 2001 - 2006 Excira Technologies, Inc. All Rights Reserved.
 * -----------------------------------------------------------------------
 *
 */
 
Ext.namespace("Excira");

var DoingAtkins = function() {
	
	var simpleEncoding = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; 


	return {
	
		/**
		 *
		 */
		getContactForm : function() {

			// First get the initial form text
			var statusEl = Ext.get("contactStatus");
			if ( statusEl ) {
			
    			var statusUpdateObj = {
    				url:"/getFormText.ajax",
    				params:{ "formPath": "contact", "status": "initial" }
    			};
    			
				var updateMan = statusEl.getUpdateManager();
				updateMan.showLoadIndicator = false;
				updateMan.update(statusUpdateObj);
			}	
			
			// Now create the form
			// Now setup the form
			Ext.QuickTips.init();
			Ext.QuickTips.enable();
			
			Ext.form.Field.prototype.msgTarget = 'side';
						
			var form = new Ext.FormPanel({
				
				bodyStyle:"padding:10px 10px 10px",	
				buttonAlign:"right",							
				defaults: {width: 230},
				defaultType:"textfield",
				items: [{
							xtype:"textfield",
							allowBlank:false,
					        fieldLabel:"Name",
					        name:"name",
							validationEvent:false
				   		},				   		
				   		{
				   			xtype:"textfield",
				   			allowBlank:false,
					        fieldLabel:"Email Address",
					        name:"emailAddress",
					        regex:/^([\w\d\-\.]+)@{1}(([\w\d\-]{1,67})|([\w\d\-]+\.[\w\d\-]{1,67}))\.(([a-zA-Z]{2,4})(\.[a-zA-Z]{2})?)$/i,
					        regexText:"Invalid email address",
							validationEvent:false
				    	},
						{
				   			xtype:"numberfield",
					        allowBlank:true,
					        allowNegative:false,
					        decimalPrecision:0,
					        fieldLabel:"Telephone Number",
					        name:"telephoneNumber",
					        validationEvent:false
		                },
		                {
							xtype:"textarea",
							allowBlank:false,
					        fieldLabel:"Comments",
					        name:"comments",
							validationEvent:false
		                }],								
				labelWidth: 110, 
				frame:false,
				width: 390	
			});
			
			form.addButton({
						    text:"Submit",
							handler:function() {
							
								// Submit form
								form.getForm().submit({
									url:Momento.generatePostURL("contact"),
									success:function(result, action) {
									
										// Clear contact form
										Momento.removeChildren("*", "contactForm");	
										
										// Clear contact status
										Momento.removeChildren("*", "contactStatus");
									
										var obj = Ext.util.JSON.decode(action.response.responseText);
										Ext.DomHelper.append("contactStatus", {tag:"div", html:obj.successText});
									}							
								});
							}
			});
			
			form.render("contactForm");				
		},
	
		/**
		 *
		 */
		 show : function(path) {
		 
		 	// Get the title and text of request doc
			Ext.Ajax.request({
				url:"/getDocumentText.ajax",
				params:{ "docPath": path },
				success: function(response, action) {
			   				   		
					var obj = Ext.util.JSON.decode(response.responseText);
					
					// Now show the text
					Ext.Msg.alert(obj.title, obj.text);
				}
			});					 	
			
			return false;
		 },
	
		/**
		 *
		 */
		getRegisterForm : function() {
		
			// First get the initial form text
			var statusEl = Ext.get("registerStatus");
			if ( statusEl ) {
			
    			var statusUpdateObj = {
    				url:"/getFormText.ajax",
    				params:{ "formPath": "registerForm", "status": "initial" }
    			};
    			
				var updateMan = statusEl.getUpdateManager();
				updateMan.showLoadIndicator = false;
				updateMan.update(statusUpdateObj);
			}
		
			// Now setup the form
			Ext.QuickTips.init();
			Ext.QuickTips.enable();
			
			Ext.form.Field.prototype.msgTarget = 'side';
						
			var form = new Ext.FormPanel({
				
				bodyStyle:"padding:10px 10px 10px",	
				buttonAlign:"right",							
				defaultType:"textfield",
				items: [{
							xtype:"textfield",
							allowBlank:false,
					        fieldLabel:"Full Name",
					        name:"name",
							validationEvent:false,
							width:230
				   		},
						{
							xtype:"textfield",
							allowBlank:false,
					        fieldLabel:"User Name",
					        name:"userName",
							validationEvent:false,
							width:230
				   		},				   		
				   		{
				   			xtype:"textfield",
				   			allowBlank:false,
					        fieldLabel:"Email Address",
					        name:"emailAddress",
					        regex:/^([\w\d\-\.]+)@{1}(([\w\d\-]{1,67})|([\w\d\-]+\.[\w\d\-]{1,67}))\.(([a-zA-Z]{2,4})(\.[a-zA-Z]{2})?)$/i,
					        regexText:"Invalid email address",
							validationEvent:false,
							width:230
				    	},
				   		{
				   			xtype:"textfield",
				   			allowBlank:false,
					        fieldLabel:"Password",
					        inputType:"password",
					        name:"password",
							validationEvent:false,
					        validator:function(fieldValue) {
					        
					        	var confirmValue = form.getForm().findField("passwordConfirm").getValue();
					        	if ( confirmValue == "" || fieldValue == confirmValue)
					        		return true;

					        	return "Passwords do not match";
					        },
							width:230
				    	},
				   		{
				   			xtype:"textfield",
				   			allowBlank:false,
					        fieldLabel:"Confirm Password",
					        inputType:"password",
					        invalidText:"Passwords do not match",
					        name:"passwordConfirm",
							validationEvent:false,
					        validator:function(fieldValue) {
					        
					        	var passwordValue = form.getForm().findField("password").getValue();
					        	if ( passwordValue == "" || fieldValue == passwordValue)
					        		return true;
					        
					        	return "Passwords do not match";
					        },
							width:230
				    	},				    					    	
				    	{
				    		xtype:"checkbox",
				    		autoHeight:false,
				    		autoWidth:false,
				    		boxLabel:"I have read the <span onclick=\" return DoingAtkins.show('terms')\" class=\"link\">terms</span> & <span onclick=\"return DoingAtkins.show('privacy')\" class=\"link\">privacy policy</span>",
							labelSeparator:"",
				    		name:"terms"
				    	}],								
				labelWidth: 110, 
				frame:false,
				width: 390	
			});
			
			form.addButton({
						    text:"Register",
							handler:function() {
							
								// Confirm form fields are valid
								if ( !form.getForm().isValid() )
									return;
									
								// Confirm user has read terms and privacy policy
								var termsEl = form.getForm().findField("terms");
								if ( termsEl.getValue() == false ) {
									Ext.Msg.alert("Terms & Privacy Policy", "You must read the terms & privacy policy to register.");
									return;
								}									
								
								// Submit form
								form.getForm().submit({
									url:"/register.ajax",
									success:function(result, action) {
									
										// Clear register form
										Momento.removeChildren("*", "registerForm");	
										
										// Clear register status
										Momento.removeChildren("*", "registerStatus");
									
										var obj = Ext.util.JSON.decode(action.response.responseText);
										Ext.DomHelper.append("registerStatus", {tag:"div", html:obj.successText});
									}
								});
							}
			});
			
			form.render("registerForm");		
		},
	
		/**
		 *
		 */
		 getLoginForm : function() {

			Ext.QuickTips.init();
			Ext.QuickTips.enable();
			Ext.form.Field.prototype.msgTarget = 'side';
						
			var form = new Ext.FormPanel({
				
				bodyStyle:"padding:10px 10px 10px",	
				buttonAlign:"right",							
				defaultType:"textfield",
				items: [{
							xtype:"textfield",
							allowBlank:false,
					        fieldLabel:"Email address",
					        invalidText:"Invalid email address or password",
					        name:"emailAddress",
					        validationEvent:false,
							width:230
				   		},
				   		{
				   			xtype:"textfield",
				   			allowBlank:false,
					        fieldLabel:"Password",
					        inputType:"password",
					        invalidText:"Invalid email address or password",
					        name:"password",
					        validationEvent:false,
							width:230
				    	},
				    	{
				    		xtype:"checkbox",
				    		autoHeight:false,
				    		autoWidth:false,
				    		fieldLabel:"Remember Me",
				    		name:"rememberMeCookie"
				}],								
				labelWidth: 85, 
				frame:false,
				width: 360	
			});
			
			form.addButton({
						    text:"Login",
							handler:function() {
								form.getForm().submit({
									url:"/login.ajax",
									success:function() {
										window.location.href = "/memberHome";
									}
								});
							}
			});
			
			form.render("loginForm");
			
			Ext.DomHelper.append("loginForm", {tag:"div", id:"forgot"});
			Ext.DomHelper.append("forgot", {tag:"div", id:"forgotText", html:"Forgot your password?", cls:"link"});
			
			var forgotEl = Ext.get("forgot");
			forgotEl.on("click", function() {
				
				// Only create the form once!
				var forgotFormEl = Ext.get("forgotForm");
				if ( forgotFormEl )
					return;

				var forgotForm = new Ext.FormPanel({
					
					bodyStyle:"padding:10px 10px 10px;margin:10px 0 0 0",	
					buttonAlign:"right",							
					defaults: {width: 230},
					defaultType:"textfield",
					id:"forgotForm",
					items: [{
				   			xtype:"textfield",
				   			allowBlank:false,
					        fieldLabel:"Email Address",
					        name:"emailAddress",
					        regex:/^([\w\d\-\.]+)@{1}(([\w\d\-]{1,67})|([\w\d\-]+\.[\w\d\-]{1,67}))\.(([a-zA-Z]{2,4})(\.[a-zA-Z]{2})?)$/i,
					        regexText:"Invalid email address",
							validationEvent:false
					    	}],								
					labelWidth:85,
					frame:false,
					width: 360	
					
				});
				
				forgotForm.addButton({
							    text:"Remind Me!",
								handler:function() {
									forgotForm.getForm().submit({
										url:"/forgot.ajax",
										success:function(result, action) {

											// Clear contact status
											Momento.removeChildren("*", "forgot");
										
											var obj = Ext.util.JSON.decode(action.response.responseText);
											Ext.DomHelper.append("forgot", {tag:"div", html:obj.successText});

										}
									});
								}
				});				

				forgotForm.render("forgot");



			});
		 },
	
	
		/**
		 * 
		 */
		getProfileForm : function() {
		
		
			// Setup the store
			var store = new Ext.data.JsonStore({
				url:Momento.generateGetURL("profile"),
				root:"profiles",
				fields:[
				    {name: "userName"},    
				    {name: "feet"},
				    {name: "inches"}
				]
			});
			
			// Get the records and execute callback
			store.load({
				callback:function(profiles, options, success) {		
		
					// Get the current profile values
					var userName = "";
					var feet;
					var inches;
					if ( profiles.length == 1 ) {
					
						var profile = profiles[0];
						
						userName = profile.get("userName");
						
						if ( profile.get("feet") != 0 )
							feet = profile.get("feet");
						
						if ( profile.get("inches") != 0 )
							inches = profile.get("inches");
					}
		
					// Now create the form
					Ext.QuickTips.init();
					Ext.form.Field.prototype.msgTarget = 'side';
					
				   var form = new Ext.FormPanel({
				   
						bodyStyle:"padding:10px 10px 10px",
						buttonAlign:"right",							
				        items: [{
				            layout:'column',
				            border:false,
				            items:[{
				            	columnWidth:.25,
				            	border:false,
				            	layout:"form",
				            	frame:false,
				            	items:[{
				            		border:false,
				            		html:"Height:"
				            	}]
				            },
				            {
				                columnWidth:.3,
				            	border:false,		                
				                layout:"form",
				                labelAlign:"top",
				                labelWidth:50,
				                items: [{
						   			xtype:"numberfield",
							        allowBlank:true,
							        allowNegative:false,
							        decimalPrecision:0,
							        fieldLabel:"Feet",
							        name:"feet",					        
							        value:feet,
							        width:50
				                }]
				            },
				            {
				                columnWidth:.3,
				            	border:false,		                
				                layout:"form",
				                labelWidth:50,
				                labelAlign:"top",
				                items: [{
						   			xtype:"numberfield",
							        allowBlank:true,
							        allowNegative:false,
							        decimalPrecision:2,
							        fieldLabel:"Inches",
							        name:"inches",					        
							        value:inches,
							        width:50
				                }]
				            }]
				        }],
				        labelAlign:"left",
				        labelWidth:75,
						width:350		        
				    });
				    
					// Create dialog div for popup if it does
					// not yet exist
					var dialogEl = Ext.get("dialog");
					if ( !dialogEl )
						Ext.DomHelper.append("profile", {tag:"div", id:"dialog"});
				
					// Create window and add form
					var dialog = new Ext.Window({
						autoHeight:true,
						autoScroll:true,
						buttons:[
								{
								    text:"Save",
									handler:function() {
								
										// Confirm user entered a valid height
										var feetEl = form.getForm().findField("feet");
										var inchesEl = form.getForm().findField("inches");
										
										if ( feetEl.getValue() == 0 && inchesEl.getValue() == 0 ) {
											feetEl.markInvalid("Invalid height");
											inchesEl.markInvalid("Invalid height");
											return;
										}	
													
										form.getForm().submit({
											url:Momento.generatePostURL("profile"),
											success:function() {
												dialog.hide();
												dialog.destroy();
												DoingAtkins.viewProfile();
												DoingAtkins.updateWeightVsTimeChartURL();
											}
										});							
									}
								},
								{
								    text:"Cancel",
									handler:function() {
										dialog.hide();
										dialog.destroy();
									}
								}						
						],
						closable:true,
						el:"dialog",
						hideBorder:true,
						keys:[
						{
							key:27,
							fn:function() {
								dialog.hide();
								dialog.destroy();						
							}
						}
						],
						items:form,
						modal:true,
						resizable:false,
						shadow:true,
						title:"Height",
						width:350
					});
		
					// Render form
					dialog.show();
				}
			});		    
		},
		
		/**
		 * 
		 */
		viewProfile : function() {
		
			// First get the initial form text
			var statusEl = Ext.get("profileStatus");
			if ( !statusEl ) {
				Ext.DomHelper.append("profile", {tag:"div", id:"profileStatus"});
				var statusEl = Ext.get("profileStatus");
				var statusUpdateObj = {
					url:"/getFormText.ajax",
					params:{ "formPath": "profileForm", "status": "initial" }
				};
				var updateMan = statusEl.getUpdateManager();
				updateMan.showLoadIndicator = false;
				updateMan.update(statusUpdateObj);
			}
			
			// Setup the store
			var store = new Ext.data.JsonStore({
				url:Momento.generateGetURL("profile"),
				root:"profiles",
				fields:[
				    {name: "feet"},
				    {name: "inches"},
				    {name: "lastWeight"},
				    {name: "lastDate"},
				    {name: "bmi"},
				    {name: "bmiRange"},
				    {name: "bmiMaxNormal"},
				    {name: "bmiOverweight"}
				]
			});
			
			// Get the records and execute callback
			store.load({
				callback:function(profiles, options, success) {
					
					// Clear current profile div and display values			
					Momento.removeChildren("*", "profileDetails");
					
					// Create profileDetails div
					var profileDetailsEl = Ext.get("profileDetails");
					if ( !profileDetailsEl )
						Ext.DomHelper.append("profile", {tag:"div", id:"profileDetails"});
						
					// Do not attempt to proceed if no profile was returned					
					if ( profiles.length < 1 ) 
						return;
					
					// Display the profile details		
					var profile = profiles[0];

					// Add height details					
					var feet = profile.get("feet");
					var inches = profile.get("inches");
					
					if ( feet == 0 && inches == 0 ) 
						Ext.DomHelper.append("profileDetails", {tag:"div", html:"Height: <span onclick=\"DoingAtkins.getProfileForm()\" class=\"link\">Click here</span> to enter you height so we can provide you with BMI information"});
					else 
						Ext.DomHelper.append("profileDetails", {tag:"div", html:"Height: " + feet + "\' " + inches + "\"&nbsp;&nbsp;&nbsp;&nbsp;<span onclick=\"DoingAtkins.getProfileForm()\" class=\"link\">Edit height</span>"});
					
					// Add weight details
					var lastWeight = profile.get("lastWeight");
					if ( lastWeight != 0 )
						Ext.DomHelper.append("profileDetails", {tag:"div", html:"Current Weight: " + lastWeight + " as of " + profile.get("lastDate")});
				
					// Add BMI details
					var bmi = profile.get("bmi");
					if ( bmi != 0 ) {
					
						var bmiText = "<br/>Your BMI is " + bmi + ", which falls within the " + profile.get("bmiRange") + " range." + 
										" Your maximum normal weight is " + profile.get("bmiMaxNormal") + ". "
										
						var overweight = profile.get("bmiOverweight");
						if ( parseFloat(overweight) > 0 )
							bmiText = bmiText + "You are " + overweight + " pounds above the overweight BMI threshold."
						Ext.DomHelper.append("profileDetails", {tag:"div", html:bmiText});
					}
				}
			});
		},
	
		///////////////////////////////////////////////////////////////////////////////////
	
		/**
		 *
		 */
		getBMIColor : function(level) {

			if ( level == "obese" ) 
				return "807059";
				
			if ( level == "overweight" ) 
				return "727EA3";
				
			if ( level == "underweight" ) 
				return "567A7A";
				
			return "000000";		
		},
	
		/**
		 * 
		 */
		getWeightVsTimeForm : function() {
			
			Ext.QuickTips.init();
			Ext.form.Field.prototype.msgTarget = 'side';
						
			var form = new Ext.FormPanel({
				
				bodyStyle:"padding:10px 10px 10px",	
				buttonAlign:"right",
				defaults: {width: 230},
				id:"weightVsTimeForm",
				items: [{
							xtype:"datefield",
							format:"Y-m-d",
					        fieldLabel:"Date",
					        invalidText:"Invalid date format (yyyy-MM-dd)",
					        maxValue:new Date(),
					        name:"date",
					        allowBlank:false,
					        validationEvent:false,
					        value:new Date()
				   		},
				   		{
				   			xtype:"numberfield",
					        fieldLabel:"Weight",
					        name:"weight",
					        allowBlank:true,
					        allowNegative:false,
					        decimalPrecision:2
				    	}],								
				labelWidth: 75,
				frame:false,
				width: 350	
			});
			
			form.addButton({
						    text:"Save",
							handler:function() {
								form.getForm().submit({
									url:"/updateWeightVsTime.ajax",
									success:function() {
										DoingAtkins.updateWeightVsTimeChartURL();
										DoingAtkins.viewProfile();
										form.getForm().reset();
									}
								});							
							}
			});
			
			form.render("weightVsTime");
		},
		
		/**
		 * 
		 */
		 simpleEncodeY : function(values, maxValue) {
		 	
			var chartData = ['s:'];
			
			var value;
			for (var i = 0; i < values.length; i++) {
				
				var currentValue = values[i];
				if ( !isNaN(currentValue) && currentValue >= 0 ) {
								
					value = 	
						Math.round((simpleEncoding.length-1) * currentValue / maxValue);
					chartData.push(simpleEncoding.charAt(value));
				}
				else
					chartData.push("_");
			}
			return chartData.join("");
		 },
		 
		 /**
		  * 
		  */
		  textEncodeXY : function(valuesX, valuesY) {
		  	
		  	var chartData = ['t:'];
			
			// Add the x values
			for (var i = 0; i < valuesX.length; i++) {
				
				chartData.push(valuesX[i]);			
				if ( i < valuesX.length - 1 )
						chartData.push(",");
			}
			
			chartData.push("|");
			
			// Add the y values
			for (var i = 0; i < valuesY.length; i++) {
				
				chartData.push(valuesY[i]);			
				if ( i < valuesY.length - 1 )
						chartData.push(",");
			}			
			return chartData.join("");
		  },
		  
		/**
		 * 
		 */
		updateWeightVsTimeChartURL : function() {
		
			var url = "/getWeightVsTimeValues.ajax";
			
			Ext.Ajax.request({
			   url: url,
			   success: function(result, request) {
			   				   		
			   		// Get the entries for this user and add to corresponding
			   		// date and weight arrays
			   		var entries = result.responseXML.getElementsByTagName("entry");

					// Handle case where there are no entries for this user
			   		if ( entries.length == 0 ) {
			   			
			   			var chartEl = Ext.get("chart");
						if ( chartEl )
							chartEl.remove();

						Ext.DomHelper.append("weightVsTimeChart", {tag:"span", html:"Enter you weight in the form above to chart your progress.", id:"chart"});
						
			   			return;
			   		}
			   		
			   		// Otherwise create chart...
   		
			   		var dates =[];
			   		var weights = [];
			   		for ( var i = 0 ; i < entries.length ; i++ ){
			   			
						dates.push(getElementData(entries[i], "date"));
						weights.push(getElementData(entries[i], "weight"));
					}
		
					// Get the chart data
					var chd = DoingAtkins.textEncodeXY(dates, weights);
					
					// Get the chart labels
					var labels = result.responseXML.getElementsByTagName("labels");
					
					// Get the x labels
					var xValues = getElementData(labels[0], "xValues");
					var chxl = "0:|" + xValues;

					// Get the y labels
					var yValues = getElementData(labels[0], "yValues");
					chxl = chxl + "|1:|" + yValues;

					// Generate basic chart URL - this will be the source of 
					// the chart image
					var src = "http://chart.apis.google.com/chart?" + 
								"chs=560x300" +
								"&chd=" + chd +
								"&chxt=x,y" + 
								"&chxl=" + chxl +
								"&chtt=Weight+vs+Time";
								
					// Add legend to chart
					var cutOffs = result.responseXML.getElementsByTagName("cutOff");
					src = src + DoingAtkinsChart.getLegend(cutOffs);
					
					// Add markers to chart
					src = src + DoingAtkinsChart.getMarkers(cutOffs);
					
					// Get grid lines
					src = src + DoingAtkinsChart.getGridLines(xValues);
										
					// Now determine type of chart and add to chart URL
					src = src + "&cht=lxy";

					// Remove existing chart if necessary			
					var chartEl = Ext.get("chart");
					if ( chartEl )
						chartEl.remove();

					// Add updated chart
					Ext.DomHelper.append("weightVsTimeChart", {tag:"img", src:src, id:"chart"});
			   }
			});				
		}		  
	};
}();


var DoingAtkinsChart = function() {

	return {
	
		/**
		 *
		 */
		getGridLines : function(xValues) {
		
			// Get the number of x markers
			var numberOfMarkers = 4;
			if ( xValues ) {
			
				numberOfMarkers = xValues.split("|").length;
			
				// Remove one marker for the y axis
				numberOfMarkers--;
			}
			
			// Find spacing for vertical grid lines
			var spacing = 100 / numberOfMarkers;
		
			return "&chg=" + spacing + ",5,1,1";
		},
		
		/**
		 *
		 */
		getLegend : function(legendItems) {
				
			// Start with legend item for weight
			// Create blank legend item after weight - we
			// want space between weight legen item and 
			// BMI legend items
			var chdl = "weight";
			var chco = "ff9900";						
		
			// Now iterate over legend items and add
			// to corresponding strings
			var name;
			var color;

			for ( var i = 0 ; i < legendItems.length ; i++ ) {

				name = getElementData(legendItems[i], "name");
				color = DoingAtkins.getBMIColor(name);
				
	   			// Create chart legend labels for BMI markers
	   			chdl = chdl + "|BMI: " + name;
	   			
	   			// Create chart legend colors for BMI markers
	   			chco = chco + "," + color;
			}
			
			return "&chdl=" + chdl + "&chco=" + chco;
		},
		
		/**
		 *
		 */
		getMarkers : function(cutOffs) {
		
			// Do not proceed if there are no cutoffs
			if ( cutOffs.length == 0 )
				return;

			var chm = "&chm=";
			
			// Now add markers for any cutoffs
			var value;
			var name;
			var color;
			for ( var i = 0 ; i < cutOffs.length ; i++ ) {

				name = getElementData(cutOffs[i], "name");
				value = getElementData(cutOffs[i], "value");
				color = DoingAtkins.getBMIColor(name);
				
				// Create BMI markers
	   			chm = chm + 
	   				"h," + color + ",0," + value + ",1";

	   			if ( i < cutOffs.length - 1 ) {
	   				chm = chm + "|";
	   			}
			}

			return chm;		
		}
	}; 
}();