

dojo.addOnLoad(function()
{
	dojo.require("dijit.Dialog");
});

submitContactForm = function()
{
	dojo.byId('idContactForm').submit();
};


/*** Dialog Box ***/

showDialog = function(href)
{
	var dialog = dijit.byId('idDialog');
	
	if (dialog != null)
	{
		dialog.destroyRecursive();
	}
	dialog = new dijit.Dialog({id:"idDialog"}, document.createElement("DIV"));

	dojo.connect(dialog, "onLoad", function()
	{
		dojo.query(".dialogTitle", dialog.containerNode).forEach(function(n){dialog.titleNode.innerHTML = n.innerHTML; n.innerHTML = ""; });
		dojo.query("#idQuit", dialog.containerNode).forEach(function(n){dojo.connect(n, "onclick", dialog, "hide");});
		dojo.query("script", dialog.containerNode).forEach(function(n){eval(n.innerHTML); });
	});
	dialog.show();
	dialog.setHref(href);
	dialog._position();

};


/*** Expandable Table ***/

toggleTableBody = function(tbody, action)
{
	var style = "";
	var imageSrc = "";
	
	if (dojo.isString(tbody)) {tbody = dojo.byId(tbody);}
	
	var table = tbody.parentNode;
	var cookie = table.getAttribute("cookie");
	
	if (action == null)
	{
		if (tbody.rows.length > 1)
		{
			if (tbody.rows[1].style.display == "none")
			{
				action = "expand";
			}
			else
			{
				action = "collapse";
			}
		}
		else
		{
			action = "collapse";
		}
	}

	if (action == "expand")
	{
		style = "";
		imageSrc = "minus.png";
	}
	else
	{
		style = "none";
		imageSrc = "plus.png";
	}	

	dojo.forEach(tbody.rows, function(tr)
	{
		if (dojo.hasClass(tr, "group"))
		{
			dojo.query("IMG", tr).forEach(function(img)
			{
				img.src = "../images/" + imageSrc;
			});
		}
		else
		{
			tr.style.display = style;
		}
	});
	
	if (cookie != null)
	{
		if ((action == "expand") && (!table.state[tbody.id]))
		{
			table.state[tbody.id] = true;
			dojo.cookie(cookie, dojo.toJson(table.state));
		}
		else if ((action == "collapse") && (table.state[tbody.id]))
		{
			table.state[tbody.id] = undefined;
			dojo.cookie(cookie, dojo.toJson(table.state));
		}
	}
}

/*** Expandable Table specifically for expenses 
   -- stupid kludge ***/

toggleTableBodyE = function(tbody, action)
{
	var style = "";
	var imageSrc = "";
	
	if (dojo.isString(tbody)) {tbody = dojo.byId(tbody);}
	
	var table = tbody.parentNode;
	var cookie = table.getAttribute("cookie");
	
	if (action == null)
	{
		if (tbody.rows.length > 1)
		{
			if (tbody.rows[1].style.display == "none")
			{
				action = "expand";
			}
			else
			{
				action = "collapse";
			}
		}
		else
		{
			action = "collapse";
		}
	}

	if (action == "expand")
	{
		style = "";
		imageSrc = "minus.png";
    tbody.rows[0].cells[3].innerHTML = 'Add:';
	}
	else
	{
		style = "none";
		imageSrc = "plus.png";
    tbody.rows[0].cells[3].innerHTML = '';
	}	

	dojo.forEach(tbody.rows, function(tr)
	{
		if (dojo.hasClass(tr, "group"))
		{
			dojo.query("IMG", tr).forEach(function(img)
			{
				img.src = "../images/" + imageSrc;
			});
		}
		else
		{
			tr.style.display = style;
		}
	});
	
	if (cookie != null)
	{
		if ((action == "expand") && (!table.state[tbody.id]))
		{
			table.state[tbody.id] = true;
			dojo.cookie(cookie, dojo.toJson(table.state));
		}
		else if ((action == "collapse") && (table.state[tbody.id]))
		{
			table.state[tbody.id] = undefined;
			dojo.cookie(cookie, dojo.toJson(table.state));
		}
	}
}



toggleAllTableBodies = function(table, action)
{
	dojo.query("TBODY", table).forEach(function(tbody)
	{
		toggleTableBody(tbody, action);
	});
}

toggleAllTableBodiesE = function(table, action)
{
	dojo.query("TBODY", table).forEach(function(tbody)
	{
		toggleTableBodyE(tbody, action);
	});
}


initExpandableTable = function(table, cookieName)
{
	if (dojo.isString(table)) {table = dojo.byId(table);}
	
	table.state = {};

	if (cookieName != null)
	{
		dojo.require("dojo.cookie");
		var state = dojo.cookie(cookieName);
		if (typeof state == "string")
		{
			state = dojo.fromJson(state);
			if (typeof state != "undefined")
			{
				table.state = state;
			}
		}
		table.setAttribute("cookie", cookieName);
	}

	dojo.query("TBODY", table).forEach(function(tbody)
	{
		if (table.state[tbody.id])
		{
			toggleTableBody(tbody, 'expand');
		}
		else
		{
			toggleTableBody(tbody, 'collapse');
		}
	});
};

/*** stupid kludge for expense table to keep the
   add column in there ***/
initExpandableTableE = function(table, cookieName)
{
	if (dojo.isString(table)) {table = dojo.byId(table);}
	
	table.state = {};

	if (cookieName != null)
	{
		dojo.require("dojo.cookie");
		var state = dojo.cookie(cookieName);
		if (typeof state == "string")
		{
			state = dojo.fromJson(state);
			if (typeof state != "undefined")
			{
				table.state = state;
			}
		}
		table.setAttribute("cookie", cookieName);
	}

	dojo.query("TBODY", table).forEach(function(tbody)
	{
		if (table.state[tbody.id])
		{
			toggleTableBodyE(tbody, 'expand');
		}
		else
		{
			toggleTableBodyE(tbody, 'collapse');
		}
	});
};

/*** Javascript Validation ***/

getValue = function(node)
{
	switch (node.type)
	{
		case "text":
		case "textarea":
		case "hidden":
		{
			return node.value;
		}
		case "select":
		case "select-one":
		{
			return node.options[node.selectedIndex].value;
		}
	}
	return "";
}

getDateRegex = function(requireYear)
{
	var feb   = "0?[1-9]|[1-2][0-9]";
	var d30   = feb + "|30";
	var d31   = d30 + "|31";
	var year  = ",? (19[0-9]{2}|20[0-9]{2})";
	var regex = "";
	
	feb = "(" + feb + ")";
	d30= "(" + d30 + ")";
	d31 = "(" + d31 + ")";
	
	if (requireYear == true)
	{
		feb += year;
		d30 += year;
		d31 += year;
	}
	
	regex += "Jan(uary)? " + d31;
	regex += "|Feb(ruary)? "  + feb;
	regex += "|Mar(ch)? " + d31;
	regex += "|Apr(il)? " + d30;
	regex += "|May " + d31;
	regex += "|June? " + d30;
	regex += "|July? " + d31;
	regex += "|Aug(ust)? " + d31;
	regex += "|Sep(t(ember)?)? " + d30;
	regex += "|Oct(ober)? " + d31;
	regex += "|Nov(ember)? " + d30;
	regex += "|Dec(ember)? " + d31;
	
	regex = "^(" + regex + ")$";
	
	return new RegExp(regex, "gi");
}


validateInput = function(node, errorMsg)
{
  var description;
	var value = getValue(node);
	value=trim(value);
	
	params = node.validatorSettings;
	
	if (typeof params == "undefined") {return true;}

	if ( typeof params.required != "undefined")
	if (((dojo.isFunction(params.required)) && (params.required() == true)) || 
	  ((dojo.isString(params.required)) && (dojo.eval(params.required) == true)))

	{
//	  alert(params.label + "+" + value);
		if (value == "" || value == "[choose one]" || value == "[Choose One]" || value == 'NULL')
		{
			dojo.addClass(node, "validatorInputError");
			if (errorMsg != null)
			{
				errorMsg.innerHTML = errorMsg.innerHTML + "<DIV>&quot;" + params.label + "&quot; is required.</DIV>";
			}
			return false;
		}
	}

	switch (params.format)
	{
		case "mm/dd/yyyy":
		{
			dojo.require("dojo.date.locale");
			value = value.replace(/-/g, "/");
			value = value.replace(/^([0-9])\//, "0$1/");
			value = value.replace(/\/([0-9])\//, "/0$1/");

			var dateObj = dojo.date.locale.parse(value, {selector:"date"});

			node.maxLength = 10;
			
			if ((dateObj != null) && (value.length == 10))  // if valid then spoof the regex system with something that always matches
			{
				regex = /./gi;
			}
			else // if not valid then spoof the regex system with something that never matches
			{
				regex = /^THISSHOULDNEVERMATCHNOREALLYNEVER$/gi;
			}
			description = "[" + value + "] must be a date ( formatted like '2/28/2007')."
			break;
		}
		case "currency":
		{
			regex = /^\$?[0-9]{1,3}(,?[0-9]{3})*(\.[0-9]{0,2})?$/gi;
			description = "must be a valid dollar amount.";
			break;
		}
		case "monthday":
		{
			regex = getDateRegex();
			description = "must be a date (formatted like Feb 29).";
			break;
		}
		case "date":
		{
			regex = getDateRegex(true);
			description = "must be a date (formatted like Feb 28).";
			break;
		}
		case "email":
		{
			regex = new RegExp("^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|gov|biz|info|name|aero|biz|info|jobs|museum)$", "gi");
			description = "must be a valid email address.";
			break;
		}
		case "integer":
		{
			regex = /^[0-9]+$/gi;
			description = "must be a whole number.";
			break;
		}
		case "number":
		{
			regex = /^[0-9\.]+\%?$/gi;
			description = "must be a number.";
			break;
		}
		case "alphanum":
		{
			regex = /^[a-z0-9\ ]+$/gi;
			description = "must be letter and numbers only.";
			break;
		}
		case "readonly":
		  break;
		default:
		{
			regex = /^.*$/gi;
			description = "";
		}
	}
	
	
	if ((value.length > 0) && (value.search(regex) == -1))
	{
		dojo.addClass(node, "validatorInputError");

		if (errorMsg != null)
		{
			errorMsg.innerHTML = errorMsg.innerHTML + "<DIV>&quot;" + params.label + "&quot; " + description + "</DIV>";
		}

		return false;
	}
	
	dojo.removeClass(node, "validatorInputError");
	return true;
};

reformatInput = function(node)
{
	var params = node.validatorSettings;
	if (!dojo.hasClass(node, "validatorInputError"))
	{
		switch (params.format)
		{
			case 'mm/dd/yyyy':
			{
				dojo.require("dojo.date.locale");
				node.value = node.value.replace(/-/g, "/");
				node.value = node.value.replace(/^([0-9])\//, "0$1/");
				node.value = node.value.replace(/\/([0-9])\//, "/0$1/");
				
				var dateObj = dojo.date.locale.parse(node.value, {selector:"date"});
				node.value = dojo.date.locale.format(dateObj, {datePattern:"MM/dd/y"}).substring(0,10);
			}
			case 'currency':
			{
				node.value = node.value.replace(/\$/g, "");
				node.value = node.value.replace(/\,/g, "");
			}
		}
	}
};


validateForm = function(event)
{
	var form = event.targetNode;
	var errorMessage = "";
	var isValid = true;
		
	dojo.query(".validatorErrorMessage", form).forEach(function(node){errorMessage = node});

	errorMessage.innerHTML = "";

	dojo.query("input,select", form).forEach(function(node)
	{
		if (!validateInput(node, errorMessage))
		{
			if (isValid) {node.focus();}
			isValid = false;
		}
	});
	
	if (isValid == false)
	{
    document.getElementById('idValidatorErrorMessage').scrollIntoView();
		dojo.stopEvent(event);
		errorMessage.style.display = 'block';
	}

//	  reformatInput(node);

};

validateAllInputs = function(event)
{
	var form = event.targetNode;
	var errorMessage = "";
	var isValid = true;
		
	dojo.query(".validatorErrorMessage", form).forEach(function(node){errorMessage = node});

	errorMessage.innerHTML = "";

	dojo.query("input,select", form).forEach(function(node)
	{
		if (!validateInput(node, errorMessage))
		{
			if (isValid) {node.focus();}
			isValid = false;
		}
	});
	
	  reformatInput(node);
};



addValidator = function(params)
{
	if (dojo.isString(params.id))
	{
		var node = dojo.byId(params.id);
		if (node != null)
		{
			var form = node.form;
			node.validatorSettings = params;
			
			switch(node.type)
			{
				case "text":
				case "area":
					dojo.connect(node, "onkeyup", function(){validateInput(node)});
					dojo.connect(node, "onblur", function(){validateInput(node); reformatInput(node)});
					break;
				case "select":
				case "readonly":
				case "select-one":
					dojo.connect(node, "onchange", function(){validateInput(node)});
					break;
			}
	
			if (dojo.isString(params.hint))
			{
			  helpId=params.id + "Help";
				dojo.require("dijit.Tooltip");
				dojo.byId(helpId).style.display="";
	      var t = new dijit.Tooltip({label:params.hint, connectId:[helpId]}, document.createElement("span"));			
			}

			if (dojo.isString(params.listen))
			{
				params.listen = params.listen.split(",");
				for (var i = 0 ; i < params.listen.length ; i++)
				{
					dojo.connect(dojo.byId(params.listen[i]), "onkeyup" , function(){validateInput(node);});
					dojo.connect(dojo.byId(params.listen[i]), "onchange", function(){validateInput(node);});
				}
			}
      if (form)
      {
			 if (typeof form.validatorSettings == "undefined")
			 {
			 	 form.validatorSettings = true;
				 dojo.connect(form, "onsubmit", validateForm);
			 }
			} 
			validateInput(node);
		}
		else
		{
//			alert('VALIDATOR ERROR: ' + params.id + ' does not exist.');
		}
	}
};

function confirmCancel()
{
    var agree=confirm("Are you sure you wish to cancel and lose your changes?");
    if (agree)
    {
				thePage=unescape(location.href)
				if(thePage.indexOf('?')!==-1)
				thePage=thePage.substring(0,thePage.indexOf('?'))
				thePage=thePage.substr(thePage.lastIndexOf('/')+1)
				thePage=thePage.substr(0,thePage.lastIndexOf('.'))
				location.href="../myprofile/flow.php?from=myprofile/" + thePage + ".php" ;
        return true;
     }   
    else
    {
        return false;
    }    
};

function confirmCancelDialog()
{
    var agree=confirm("Are you sure you wish to cancel and lose your changes?");
    if (agree)
    {
        dijit.byId('idDialog').hide(); 
        return true;
     }   
    else
    {
        return false;
    }    
};


function confirmBudgetCopy()
{
    var agree=confirm("Are you sure you wish to use your expenses from last month as your budget?  Any budget entries will be lost.");
    if (agree)
    {
        return true;
     }   
    else
    {
        return false;
    }    
};


		function setSelectOptions (select, options, optionids, blank)
		{
		    if (! dojo.isArray(options)) {options = options.split(",");}
		    if (! dojo.isArray(optionids)) {optionids = optionids.split(",");}
		
		    select.options.length = 0;
		    if (blank == true)
		    {
		        select.options[select.options.length] = new Option("", "");
		    }
		    for (var i = 0 ; i < options.length ; i++)
		    {
		        select.options[select.options.length] = new Option(options[i], optionids[i]);
		    }
		};

  function retT()
  {
	  return true;
  } ;	

/*** the following 3 functions control a checkbox paired
     with an input box -- if checkbox checked, then 
     use the value "default_value", otherwise
     use whatever is in inputbox
     only need to call connectCheckboxInputPair
     ***/
	defaultcheckbox_OnChange = function(checkbox,inputbox,usevalue)
	{
		var checkbox = dojo.byId(checkbox);
		var inputbox  = dojo.byId(inputbox);
		if (checkbox!=null)
		{
		 if (checkbox.checked==true)
		 {
		    inputbox.value=usevalue;
		 }
		}   
	
	}
	defaultinput_OnChange = function(checkbox)
	{
		var checkbox = dojo.byId(checkbox);
		if (checkbox!=null)
		{
  		checkbox.checked=false;
  	}	
	}

	connectCheckboxInputPair = function(inputId,checkboxId,default_value)
	{
			dojo.connect(dojo.byId(checkboxId), "onchange", document,function(){defaultcheckbox_OnChange(checkboxId,inputId,default_value);});
			dojo.connect(dojo.byId(inputId), "onkeyup", document,function(){defaultinput_OnChange(checkboxId);});
	    defaultcheckbox_OnChange(checkboxId,inputId,default_value);		
	}	
		
		
/*** the following control a yes/no set of radio buttons that determine if another
     id is shown
		 only need to call connectShowhidePair
		 with the id of the "yes" box, the id of the "no" box, and the id of what you want to 
		 show if "yes" is checked
		 ***/
		
	showhide_checkbox_OnChange = function (checkbox,showid)
	{
		var checkbox = dojo.byId(checkbox);
		var showhideA  = dojo.byId(showid+1);
		var showhideB  = dojo.byId(showid+2);
	  if (checkbox.checked==true)
		{
		   showhideA.style.display="";
		   showhideB.style.display="";
		   if (showhideC  = dojo.byId(showid+3))
		   {
		      showhideC.style.display="";
		   } 
		   if (showhideD  = dojo.byId(showid+4))
		   {
		      showhideD.style.display="";
		   }  			   
		   if (showhideE  = dojo.byId(showid+5))
		   {
		      showhideE.style.display="";
		   }
		   if (showhideF  = dojo.byId(showid+6))
		   {
		      showhideF.style.display="";
		   }
		   if (showhideG  = dojo.byId(showid+7))
		   {
		      showhideG.style.display="";
		   }
		} else {
		   showhideA.style.display="none";
		   showhideB.style.display="none";
		   if (showhideC  = dojo.byId(showid+3))
		   {
		       showhideC.style.display="none";
		   }    
		   if (showhideD  = dojo.byId(showid+4))
		   {
		       showhideD.style.display="none";
		   }  
		   if (showhideE  = dojo.byId(showid+5))
		   {
		       showhideE.style.display="none";
		   } 
		   if (showhidef  = dojo.byId(showid+6))
		   {
		       showhidef.style.display="none";
		   } 
		   if (showhideG  = dojo.byId(showid+7))
		   {
		       showhideG.style.display="none";
		   } 	
		}	 	   		
	}
	
	showhide_value_OnChange = function (valuebox,showid)
	{
		var valuebox = dojo.byId(valuebox);
		var showhideA  = dojo.byId(showid+1);
		var showhideB  = dojo.byId(showid+2);
	  if (valuebox.value>0 && valuebox.value!='' )
		{
		   showhideA.style.display="";
		   showhideB.style.display="";
		} else {
		   showhideA.style.display="none";
		   showhideB.style.display="none";
		}	 	   		
	}
	
	connectShowhidePair = function (yesId,noId,valueId)
	{
	    dojo.connect(dojo.byId(yesId), "onchange", document,function(){showhide_checkbox_OnChange(yesId,valueId);});
			dojo.connect(dojo.byId(noId), "onchange", document,function(){showhide_checkbox_OnChange(yesId,valueId);});
			showhide_checkbox_OnChange(yesId,valueId);
	}		

	formpart_OnChange = function (yesID,valueId,continueID)
	{
     if (continueID !== undefined && continueID != 0 )
     {
        if (dojo.byId(yesID).checked==true )
        {
          dojo.byId(continueID).style.display="";
        }
    }

	  if (dojo.byId(yesID).checked==true)
	  {
	    dojo.byId(valueId).style.display="";
	  } else {
	    dojo.byId(valueId).style.display="none";
	  }
	}	

	toggleFormParts = function (yesId,noId,valueId,continueID)
	{
	    if ( continueID === undefined ) {
         continueID = 0;
      }
	    dojo.connect(dojo.byId(yesId), "onchange", document,function(){formpart_OnChange(yesId,valueId,continueID);});
			dojo.connect(dojo.byId(noId), "onchange", document,function(){formpart_OnChange(yesId,valueId,continueID);});
			formpart_OnChange(yesId,valueId,continueID);
	}	
	
		
	function textCounter(fieldID, countfieldID, maxlimit) {
	    var field=dojo.byId(fieldID);
	    var countfield=dojo.byId(countfieldID);
			if (field.value.length > maxlimit) // if too long...trim it!
			  field.value = field.value.substring(0, maxlimit);
			// otherwise, update 'characters left' counter
			else 
			  countfield.innerHTML = maxlimit - field.value.length;
			  var test = maxlimit - field.value.length;
//			  alert(countfieldID + test);
 }	

  function trim(stringToTrim) {
	   return stringToTrim.replace(/^\s+|\s+$/g,"");
  }	
	
