// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

// global variales to track the no.of articles/videos in homepages
var $articles_counter;
var $videos_counter;
var change_password = false;
// reset counters
function reset_articles_counter()
{
	$articles_counter = 0;
}

// reset counters
function reset_videos_counter()
{
	$videos_counter = 0;
}

// increment articles counter
function increment_articles_counter(){
	$articles_counter += 1;
}

// increment videos counter
function increment_videos_counter(){
	$videos_counter += 1;
}

// decrement articles counter
function decrement_articles_counter(){
	$articles_counter = $articles_counter - 1;
}

// decrement videos counter
function decrement_videos_counter(){
	$videos_counter = $videos_counter - 1;
}

// function to add an article element
function add_article(){
	increment_articles_counter();
	parent_article_div = document.getElementById('articles_fieldset');
	counter = $articles_counter;
	newdiv = document.createElement('div');
	newdivId = 'article_' + counter;
	newdiv.setAttribute('id',newdivId);
	inputFieldId = "article_" + counter + "_title";
	inputFieldName = "article[" + counter + "][title]";
	autoCompleteDivId = "article_" + counter + "_title_auto_complete";
	html = "";
	html += "<fieldset class='form_field'>";
	html += "<ul><li><label for='article_title'>Article Title</label>";
	html += "<a class='close_button' href='#' onclick='remove_article(\""+newdivId+"\")'><img src='/images/icons/close.gif' /></a>";
	html += "<div class='form_input'><input class='text' id='" + inputFieldId + "' name='" + inputFieldName + "' size='30' type='text' />";
	html += "<div class='auto_complete' id='" + autoCompleteDivId + "' ></div>";
	html += "<a class='accept' href='#'><img src='/images/icons/accept.gif' /></a>";
	html += "</div>";
	html += "</li></ul>";
	html += "</fieldset>";
	newdiv.innerHTML = html;
	parent_article_div.appendChild(newdiv);
	new Ajax.Autocompleter(inputFieldId, autoCompleteDivId, '/resources/auto_complete_for_article_title', {});
	
}

// function to add a video element
function add_video(){
	increment_videos_counter();
	parent_video_div = document.getElementById('videos_fieldset');
	counter = $videos_counter;
	newdiv = document.createElement('div');
	newdivId = "video_" + counter;
	newdiv.setAttribute('id',newdivId);
	inputFieldId = "video_" + counter + "_title";
	inputFieldName = "video[" + counter + "][title]";
	autoCompleteDivId = "video_" + counter + "_title_auto_complete";
	html = "";
	html += "<fieldset class='form_field'>";
	html += "<ul><li><label for='video_title'>Video Title</label>";
	html += "<a class='close_button' href='#' onclick='remove_video(\""+newdivId+"\")'><img src='/images/icons/close.gif' /></a>";
	html += "<div class='form_input'><input class='text' id='" + inputFieldId + "' name='" + inputFieldName + "' size='30' type='text' />";
	html += "<div class='auto_complete' id='" + autoCompleteDivId + "' ></div>";
	html += "<a class='accept' href='#'><img src='/images/icons/accept.gif' /></a>";
	html += "</div>";
	html += "</li></ul>";
	html += "</fieldset>";
	newdiv.innerHTML = html;
	parent_video_div.appendChild(newdiv);
	new Ajax.Autocompleter(inputFieldId, autoCompleteDivId, '/resources/auto_complete_for_video_title', {});

}

// function to remove article element
function remove_article(article_div){
	parent_article_div = document.getElementById('sortable_articles');
	child_article_div = document.getElementById(article_div);
	parent_article_div.removeChild(child_article_div);
	decrement_articles_counter();
 }
 
// function to remove video element
function remove_video(video_div){
	parent_video_div = document.getElementById('sortable_videos');
	child_video_div = document.getElementById(video_div);
	parent_video_div.removeChild(child_video_div);
	decrement_videos_counter();
 }

// makes the homepage articles sortable 
function sortable_articles(homepage_id){
	Sortable.create("sortable_articles", {handle:'drag_handle',onUpdate:function(){new Ajax.Request('/resources/save_articles_order?homepage='+homepage_id, {asynchronous:true, evalScripts:true, parameters:Sortable.serialize("sortable_articles")})}, tag:'div'})
}

// makes the homepage articles sortable 
function sortable_videos(homepage_id){
	Sortable.create("sortable_videos", {handle:'drag_handle',onUpdate:function(){new Ajax.Request('/resources/save_videos_order?homepage='+homepage_id, {asynchronous:true, evalScripts:true, parameters:Sortable.serialize("sortable_videos")})}, tag:'div'})
}

// validations for Admin area
function validateFormOnSubmit(theForm) {
   	var reason = "";
   	var food_name = document.getElementById('food_name').value; 
   	var calories = document.getElementById('calories').value; 
   	var fat = document.getElementById('fat').value; 
   	var carbs = document.getElementById('carbs').value; 
   	var proteins = document.getElementById('proteins').value; 
   	var fiber = document.getElementById('fiber').value; 
   	var sodium = document.getElementById('sodium').value; 
   	var cholesterol = document.getElementById('cholesterol').value; 
  	reason += validateFoodname(theForm.food_name);
	  reason += validateCalories(theForm.calories);
	  reason += validatefat(theForm.fat);
	  reason += validateCarbs(theForm.carbs);
	  reason += validateProteins(theForm.proteins);
	  reason += validateFiber(theForm.fiber);
	  reason += validateSodium(theForm.sodium);
	  reason += validateCholesterol(theForm.cholesterol);
        
	  if (reason != "") 
	  {
	    alert("Some fields need correction:\n" + reason);
	    return false;
	  }
	  return true;
}


function validateFoodname(fld) {
    var error = "";
    var legalChars = /\w/ ; // allow letters, numbers,space and underscores
 	var digits = /\D/ ;
    if (fld.value == "") {
 //       fld.style.background = 'Yellow'; 
        error = "Please enter Food Name.\n";
    } else if ((fld.value.length < 4) || (fld.value.length > 100)) {
 //       fld.style.background = 'Yellow'; 
        error = "Food name should exist between 4-100 characters.\n";
    } else if (!legalChars.test(fld.value)) {
  //      fld.style.background = 'Yellow'; 
        error = "Food Name contains Special characters.\n";
    }else if (!digits.test(fld.value)) {
    //    fld.style.background = 'Yellow'; 
        error = "Food Name do not allow all digits.\n";
    }else {
        fld.style.background = 'White';
    }
    return error;
}


function validateCalories(fld) {
    var error = "";
    var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');    

   if (fld.value == "") {
        error = "Please enter Calories.\n";
     //   fld.style.background = 'Yellow';
    } else if (isNaN(parseInt(stripped))) {
        error = "Calories contains Special characters.\n";
       // fld.style.background = 'Yellow';
    } else if (!(stripped.length > 0) || (stripped.length > 4)) {
        error = "Calories should exist between 1-4 digits\n";
       // fld.style.background = 'Yellow';
    }
    return error;
}


function validatefat(fld) {
    var error = "";
    var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');    

   if (fld.value == "") {
        error = "Please enter Fat.\n";
       // fld.style.background = 'Yellow';
    } else if (isNaN(parseInt(stripped))) {
        error = "Fat contains Special characters.\n";
       // fld.style.background = 'Yellow';
    } else if (!(stripped.length > 0) || (stripped.length > 4)) {
        error = "Fat should exist between 1-4 digits\n";
      //  fld.style.background = 'Yellow';
    }
    return error;
}    


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


function validateCarbs(fld) {
   var error = "";
    var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');    

   if (fld.value == "") {
        error = "Please enter Carbs.\n";
  //      fld.style.background = 'Yellow';
    } else if (isNaN(parseInt(stripped))) {
        error = "Carbs contains Special characters.\n";
    //    fld.style.background = 'Yellow';
    } else if (!(stripped.length > 0) || (stripped.length > 4)) {
        error = "Carbs should exist between 1-4 digits\n";
      //  fld.style.background = 'Yellow';
    }
    return error;
}


function validateProteins(fld) {
    var error = "";
    var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');    

   if (fld.value == "") {
        error = "Please enter Proteins.\n";
      //  fld.style.background = 'Yellow';
    } else if (isNaN(parseInt(stripped))) {
        error = "Proteins contains Special characters.\n";
      //  fld.style.background = 'Yellow';
    } else if (!(stripped.length > 0) || (stripped.length > 4)) {
        error = "Proteins should exist between 1-4 digits\n";
      //  fld.style.background = 'Yellow';
    }
    return error;
}


function validateFiber(fld) {
    var error = "";
    var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');    

   if (fld.value == "") {
        error = "Please enter Fiber.\n";
   //     fld.style.background = 'Yellow';
    } else if (isNaN(parseInt(stripped))) {
        error = "Fiber contains Special characters.\n";
     //   fld.style.background = 'Yellow';
    } else if (!(stripped.length > 0) || (stripped.length > 4)) {
        error = "Fiber should exist between 1-4 digits\n";
      //  fld.style.background = 'Yellow';
    }
    return error;
}


function validateSodium(fld) {
    var error = "";
    var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');    

   if (fld.value == "") {
        error = "Please enter Sodium.\n";
      //  fld.style.background = 'Yellow';
    } else if (isNaN(parseInt(stripped))) {
        error = "Sodium contains Special characters.\n";
      //  fld.style.background = 'Yellow';
    } else if (!(stripped.length > 0) || (stripped.length > 4)) {
        error = "Sodium should exist between 1-4 digits\n";
      //  fld.style.background = 'Yellow';
    }
    return error;
}


function validateCholesterol(fld) {
    var error = "";
    var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');    

   if (fld.value == "") {
        error = "Please enter Cholesterol.\n";
     //   fld.style.background = 'Yellow';
    } else if (isNaN(parseInt(stripped))) {
        error = "Cholesterol contains Special characters.\n";
      //  fld.style.background = 'Yellow';
    } else if (!(stripped.length > 0) || (stripped.length > 4)) {
        error = "Cholesterol should exist between 1-4 digits\n";
      //  fld.style.background = 'Yellow';
    }
    return error;
}


function emailcheck(cur)
{
	var email = document.getElementById('email').value; 
	var customer_id = document.getElementById('customer_id').value; 
	var company = document.getElementById('permission_super_admin').value; 
//	var role = document.getElementById('per').value;
	var role = document.user_form.role.value
	var errors = "";
	var incoming = document.getElementById('email').value; 
	var emailstring = incoming;
	var ampIndex = emailstring.indexOf("@");
	var afterAmp = emailstring.substring((ampIndex + 1), emailstring.length);
		// find a dot in the portion of the string after the ampersand only
	var dotIndex = afterAmp.indexOf(".");
		// determine dot position in entire string (not just after amp portion)
	dotIndex = dotIndex + ampIndex + 1;
		// afterAmp will be portion of string from ampersand to dot
	afterAmp = emailstring.substring((ampIndex + 1), dotIndex);
		// afterDot will be portion of string from dot to end of string
	var afterDot = emailstring.substring((dotIndex + 1), emailstring.length);
	var beforeAmp = emailstring.substring(0,(ampIndex));
		//old regex did not allow subdomains and dots in names
		//var email_regex = /^[\w\d\!\#\$\%\&\'\*\+\-\/\=\?\^\_\`\{\|\}\~]+(\.[\w\d\!\#\$\%\&\'\*\+\-\/\=\?\^\_\`\{\|\}\~])*\@(((\w+[\w\d\-]*[\w\d]\.)+(\w+[\w\d\-]*[\w\d]))|((\d{1,3}\.){3}\d{1,3}))$/;
	var email_regex = /^([a-zA-Z0-9])(([\-.]|[_]+)?([a-zA-Z0-9]+))*(@){1}([a-z0-9]|([a-z0-9][\-]))+[.]{1}(([a-z0-9]{2,20})|([a-z0-9]{2,20}[.]{1}[a-z]{2,3}))$/ 
		// index of -1 means "not found"
	if (!((emailstring.indexOf("@") != "-1") && 
		(emailstring.length < 70) &&
		(afterAmp.length > 0) &&
		(beforeAmp.length > 1) &&
		(email_regex.test(emailstring)) )) {
		errors += "Invalid email format \n Email should not contain speacial characters or spaces \n"
	}
	
	if (customer_id < 1) {
		errors += "Please select a Customer! \n";
	}
	if (role == "") {
		errors += "Please select a Role \n";
	}
	if (customer_id == 29) {
		var space = /\S/;				
		if (company == "") {
			errors += "Please Enter Company \n";
		}
		else 
			if (!space.test(company)) {
			errors += "Please Enter Company \n";				
			}		
	}
//	if (email == ""){
//		  errors += "Please provide Email Address \n";
//	}
//	else if (emailstring.length > 35)  {
//		  errors += "Email shouldn't exceed more than 35 chars \n";
//	}
	
	if (errors != ""){
		alert(errors);
		return false;
	}
	return true;
}


function Validationcheck(cur)
{
	var string1= document.getElementById('check').value;
	if(string1 =="" || string1.toString().match(/^[-]?\d*$/)) 
	{
		alert("Please specify the Customer Name")
		return false;
	}
	else if(string1.length < 3 || string1.length > 15){
		alert("Customer Name should exists between 3-15 characters")
		return false;
	}
	var iChars = "~!@#$%^&*()+=-[]\\\';,./{}|\":<>?";
    for (var i = 0; i < string1.length; i++) {
         if (iChars.indexOf(string1.charAt(i)) != -1) {
           alert ("The Text field has special characters. \nThese are not allowed.\n");
         return false;
        }
    }
	life2go_style = document.getElementById('life2go_style');
	vitalizeu_style = document.getElementById('vitalizeu_style');
	if (life2go_style.checked || vitalizeu_style.checked){
		// do nothing
	}
	else {
		alert("Please select Template. \n");
		return false;
	}
	var sub_domain = document.getElementById('sub_domain').value;
	if(sub_domain =="" || sub_domain.toString().match(/^[-]?\d*$/)) 
	{
		alert("Please specify Subdomain")
		return false;
	}
	else if(sub_domain.length < 2 || sub_domain.length > 15){
		alert("Subdomain Name should exists between 2-15 characters")
		return false;
	}
	var Chars = "~!@#$%^&*()+=[]\\\';,./{}|\":<>?";
    for (var i = 0; i < sub_domain.length; i++) {
         if (Chars.indexOf(sub_domain.charAt(i)) != -1) {
           alert ("Subdomain contains illegal characters. \nThese are not allowed.\n");
         return false;
        }
    }			
	return true;
}


function Validationcheck1(cur)
{
	var string1= document.getElementById('video_file').value;
	var group = document.getElementById('video_group').value;
	var thumbnail = document.getElementById('thumbnail_file').value;
	var digits = /\D/ ;
	var space = /\S/; 
	var iChars = "!@#$%^&*()+=[]\\\';,/{}|\":<>?";
	if(string1 =="" || string1.toString().match(/^[-]?\d*$/)) 
	{
		alert("Please Enter Valid Video File!")
		return false;
	}
	else if(thumbnail =="" || thumbnail.toString().match(/^[-]?\d*$/)){
		alert("Please Enter valid Thumbnail")
		return false;
	}
	var string2= document.getElementById('video_title').value;
	if(string2 =="" || !(space.test(string2))) 
	{
		alert("Enter Title for Video")
		return false;
	}
	else if(string2.length < 3 || string2.length > 20){
		alert("Video Title should contain 3 to 20 characters")
		return false;
	}
	else if(!digits.test(string2)){
		alert("Video Title should not contain all digits")
		return false;
	}
	else if(group==""){
		alert("Select Group From List")
		return false;
	}
	for (var i = 0; i < string2.length; i++) {
         if (iChars.indexOf(string2.charAt(i)) != -1) {
           alert ("Video Title has special characters. \nThese are not allowed.\n");
         return false;
        }
    }	
	  return true;
}

function toggle_admin_modules()
{
  if(document.getElementById("super_admin").checked == true)
   {
    document.getElementById("customer_admin").disabled = true;
    document.getElementById("user_admin").disabled = true;
	document.getElementById("fitness_admin").disabled = true;
    document.getElementById("nutrition_admin").disabled = true;
	document.getElementById("reporting_admin").disabled = true;
   }
  else
   {
    document.getElementById("customer_admin").disabled = false;
    document.getElementById("user_admin").disabled = false;
	document.getElementById("fitness_admin").disabled = false;
    document.getElementById("nutrition_admin").disabled = false;
	document.getElementById("reporting_admin").disabled = false;
   }
}

function toggle_permissions()
{
	if (document.getElementById('permissions').value == 1)
	{
		document.getElementById('for_admin').style.display = "block";
	}
	else
	{
		document.getElementById('for_admin').style.display = "none";
	}
}

//validations for Public Area 

function validateProfileFormOnSubmit(theForm){
	var fname = document.getElementById('first_name').value
	var lname = document.getElementById('last_name').value
	var digits = /\d/;
	var non_digits = /\D/ ;
	var space = /\S/;
	var whitspace = /\s/;
	var iChars = "!@#$%^&*()+-_=[]\\\';,/{}|\":<>?";
	var allow_digits = "!@#$%^&*()+-_=[]\\\';,/{}|\":<>?qwertyuiopasdfghjklzxcvbnm";	
	reason = "";

	// validations for First Name
	if (fname == "") {
		reason += "Please provide a First Name \n";
	}
	else if (fname.length < 3 || fname.length > 15) {
		reason += "First Name should be 3-15 characters \n";
	}
	else if(!non_digits.test(fname)){
		reason += "First Name should be alphanuneric \n"
	}
	else if(!space.test(fname)){
		reason += "Too many spaces in First Name \n";
	}
	else {
		legal = true;
		for (var i = 0; i < fname.length; i++) {
     		if (iChars.indexOf(fname.charAt(i)) != -1) {
       			legal = false;
    		}
		}
		if (legal == false){
			reason += "First Name contains invalid characters \n";	
		}		
	}
	
		
	// validations for Last Name
	if(lname =="" || !space.test(lname)){
		reason += "Please provide Last Name \n";
	}
	else if(!non_digits.test(lname)){
			reason += "Last Name should be alphanumeric \n";
		}
	else if(lname.length < 3 || lname.length > 15){
			reason += "Last name should be 3-15 characters \n";
	}
	else {
		legal = true;
		for (var i = 0; i < lname.length; i++) {
     		if (iChars.indexOf(lname.charAt(i)) != -1) {
       			legal = false;
    		}
		}
		if (legal == false){
			reason += "Last Name contains invalid characters \n";
		}
	}
	
   // validations for diet or fitness Requirements when user checks
	if(document.getElementById('create_meals').checked == true || document.getElementById('create_fitness').checked == true){
	  var weight = document.getElementById('weight').value;
      var stripped_weight = weight.replace(/[\(\)\.\-\ ]/g, '');
      var dob = document.getElementById('dob').value
	  var stripped_dob = dob.replace(/[\(\)\.\-\ ]/g, '');
	  var height = document.getElementById('height_feet').value
	  var height_inches = document.getElementById('height_inches').value
	  var allow_digits = "!@#$%^&*()+-_=[]\\\';,/{}|\":<>?qwertyuiopasdfghjklzxcvbnm";
	  var digits = /\d/;
	  var whitspace = /\s/;
	  var dtCh= "-";
      var minYear=1900;
	  var maxYear=2100;
  	  var mth = document.getElementById('month').value
	  var dy = document.getElementById('day').value
	  var yr = document.getElementById('dob').value
	  var full_date = mth+"-"+dy+"-"+yr
	  var date_year = yr+"-"+mth+"-"+dy
      var thisDate = new Date();
	  var dYear = parseInt(date_year.substring(0,4),10);
	  var dMonth = parseInt(date_year.substring(5,7),10);
	  var dDate = parseInt(date_year.substring(8,10),10);
	  var dobDate = new Date(dYear, dMonth, dDate);
	  var age = thisDate.getFullYear() - dobDate.getFullYear()
	

	// validations for weight 
		if (weight == "" || weight == 0 || weight == 0.0) {
			reason += "Please provide Weight \n";
		}
		else if (whitspace.test(weight) || (!digits.test(weight))) {
			reason += "Please provide a proper weight \n";
		}
		else if (weight < 50 || weight > 500) {
			reason += "Weight is expected to be between 50-500 lbs \n";
		}
		else {
			legal = true;
			for (var i = 0; i < weight.length; i++) {
				if (allow_digits.indexOf(weight.charAt(i)) != -1) {
					legal = false;
				}
			}
			if (legal == false){
				reason += "Weight contains invalid characters \n";
			}
		}
		
	// validations for gender
		genderMale = document.getElementById('gender_male');
		genderFemale = document.getElementById('gender_female');
		if (genderMale.checked || genderFemale.checked){
			// do nothing
		}
		else {
			reason += "Please select your Gender \n"
		}
		
	// validations for Date Of Birth
	if (age < 19) {
	    	reason += "You must be atleast 18 years old !! \n";
			reason += "Please check the Date of Birth you entered \n"
		}	

	function isInteger(s){
		var i;
	    for (i = 0; i < s.length; i++){   
	        // Check that current character is number.
	        var c = s.charAt(i);
	        if (((c < "0") || (c > "9"))) return false;
	    }
	    // All characters are numbers.
	    return true;
	}

	function stripCharsInBag(s, bag){
		var i;
	    var returnString = "";
	    // Search through string's characters one by one.
	    // If character is not in bag, append to returnString.
	    for (i = 0; i < s.length; i++){   
	        var c = s.charAt(i);
	        if (bag.indexOf(c) == -1) returnString += c;
	    }
	    return returnString;
	}
	
	function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
	}
	
	function DaysArray(n) {
		for (var i = 1; i <= n; i++) {
			this[i] = 31
			if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
			if (i==2) {this[i] = 29}
	   } 
	   return this
	}

	function isDate(dtStr){
		var daysInMonth = DaysArray(12)
		var pos1=dtStr.indexOf(dtCh)
		var pos2=dtStr.indexOf(dtCh,pos1+1)
		var strMonth=dtStr.substring(0,pos1)
		var strDay=dtStr.substring(pos1+1,pos2)
		var strYear=dtStr.substring(pos2+1)
		strYr=strYear
		if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
		if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
		for (var i = 1; i <= 3; i++) {
			if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
		}
		month=parseInt(strMonth)
		day=parseInt(strDay)
		year=parseInt(strYr)
		if (pos1==-1 || pos2==-1){
			reason += "The date format should be : mm-dd-yyyy \n"
		}
		if (strMonth.length<1 || month<1 || month>12){
			reason += "Please enter a valid month \n"
		}
		if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
			reason += "Please enter a valid day \n"
		}
		if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
			reason += "Please enter a valid 4 digit year between "+minYear+" to "+maxYear+"\n"
		}
		if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
			reason += "Please enter a valid date \n"
		}
	return true
	}

	if (isDate(full_date)==false){
		return false
	}
	
	// validations for height
	if (height == 0) {
		reason += "Please provide a valid Height \n"
	}
	else if (!validateHeight(allow_digits, height) || !validateHeight(allow_digits, height_inches)) {
		reason += "Height contains invalid characters \n"
	}
	else if (whitspace.test(height) ||(!digits.test(height))) {
		reason += "Please provide a proper Height \n";
	}
	else if (height < 1 || height > 10){
		reason += "Height expected to be in between 1 - 10 ft"
	}
	else if (height_inches < 0 || height_inches > 12){
		reason += "Height-Inches expected to be in between 0-12 inches"
	}
	
	}
	
	function validateHeight(allow_digits, value){
		legal = true;
		for (var i = 0; i < value.length; i++) {
			if (allow_digits.indexOf(value.charAt(i)) != -1) {
				legal = false;
			}
		}
		if (legal == false){
			return false;
		}
		return true;
	}
	
	if(change_password == true){
		var new_password = document.getElementById('new_password').value;
		var confirm_password = document.getElementById('confirm_new_password').value;
		var illegalChars = /[\W_]/;
		if (new_password == "") {
			reason += "Please provide New Password \n";
		}
		if ((new_password.length < 4)||(new_password.length > 40)) { 
			reason += "Password should be 4-8 chars in length \n";
		}
		if (illegalChars.test(new_password)){
			reason += "Password contains illegal characters \n";
		}
		if (new_password != confirm_password){
			reason = "Password do not match \n"
		}
	}
	
	if (reason != ""){
		alert(reason);
		return false;
	} 
	return true;
}

//validations for Signup Page

function validateSignupFormOnSubmit(theForm){
	var email = document.getElementById('email').value
	var fname = document.getElementById('first_name').value
	var lname = document.getElementById('last_name').value
	var digits = /\d/;
	var non_digits = /\D/ ;
	var space = /\S/;
	var whitspace = /\s/;
	var iChars = "!@#$%^&*()+-_=[]\\\';,/{}|\":<>?";
	var allow_digits = "!@#$%^&*()+-_=[]\\\';,/{}|\":<>?qwertyuiopasdfghjklzxcvbnm";
	var new_password = document.getElementById('password').value;
	var confirm_password = document.getElementById('confirm_new_password').value;
	var illegalChars = /[\W_]/;		
	reason = "";

	// validations for email
	var incoming = document.getElementById('email').value; 
	var emailstring = incoming;
	var ampIndex = emailstring.indexOf("@");
	var afterAmp = emailstring.substring((ampIndex + 1), emailstring.length);
		// find a dot in the portion of the string after the ampersand only
	var dotIndex = afterAmp.indexOf(".");
		// determine dot position in entire string (not just after amp portion)
	dotIndex = dotIndex + ampIndex + 1;
		// afterAmp will be portion of string from ampersand to dot
	afterAmp = emailstring.substring((ampIndex + 1), dotIndex);
		// afterDot will be portion of string from dot to end of string
	var afterDot = emailstring.substring((dotIndex + 1), emailstring.length);
	var beforeAmp = emailstring.substring(0,(ampIndex));
		//old regex did not allow subdomains and dots in names
		//var email_regex = /^[\w\d\!\#\$\%\&\'\*\+\-\/\=\?\^\_\`\{\|\}\~]+(\.[\w\d\!\#\$\%\&\'\*\+\-\/\=\?\^\_\`\{\|\}\~])*\@(((\w+[\w\d\-]*[\w\d]\.)+(\w+[\w\d\-]*[\w\d]))|((\d{1,3}\.){3}\d{1,3}))$/;
	var email_regex = /^([a-zA-Z0-9])(([\-.]|[_]+)?([a-zA-Z0-9]+))*(@){1}([a-z0-9]|([a-z0-9][\-]))+[.]{1}(([a-z0-9]{2,20})|([a-z0-9]{2,20}[.]{1}[a-z]{2,3}))$/ 
		// index of -1 means "not found"
	if (!((emailstring.indexOf("@") != "-1") && 
		(emailstring.length < 35) &&
		(afterAmp.length > 0) &&
		(beforeAmp.length > 1) &&
		(email_regex.test(emailstring)) )) {
		reason += "Invalid email format \n Email should not contain speacial characters or spaces \n"
	}


	// validations for First Name
	if (fname == "") {
		reason += "Please provide a First Name \n";
	}
	else if (fname.length < 3 || fname.length > 15) {
		reason += "First Name should be 3-15 characters \n";
	}
	else if(!non_digits.test(fname)){
		reason += "First Name should be alphanuneric \n"
	}
	else if(!space.test(fname)){
		reason += "Too many spaces in First Name \n";
	}
	else {
		legal = true;
		for (var i = 0; i < fname.length; i++) {
     		if (iChars.indexOf(fname.charAt(i)) != -1) {
       			legal = false;
    		}
		}
		if (legal == false){
			reason += "First Name contains invalid characters \n";	
		}		
	}
	
		
	// validations for Last Name
	if(lname =="" || !space.test(lname)){
		reason += "Please provide Last Name \n";
	}
	else if(!non_digits.test(lname)){
			reason += "Last Name should be alphanumeric \n";
		}
	else if(lname.length < 3 || lname.length > 15){
			reason += "Last name should be 3-15 characters \n";
	}
	else {
		legal = true;
		for (var i = 0; i < lname.length; i++) {
     		if (iChars.indexOf(lname.charAt(i)) != -1) {
       			legal = false;
    		}
		}
		if (legal == false){
			reason += "Last Name contains invalid characters \n";
		}
	}
	
	// validations for password
	if (new_password == "") {
		reason += "Please provide Password \n";
	}
	else if ((new_password.length < 4)||(new_password.length > 40)) { 
		reason += "Password should be 4-8 chars in length \n";
	}
	else if (illegalChars.test(new_password)){
		reason += "Password contains illegal characters \n";
	}
	else if (new_password != confirm_password){
		reason += "Password do not match \n"
	}
		
	
   // validations for diet or fitness Requirements when user checks
	if(document.getElementById('create_meals').checked == true || document.getElementById('create_fitness').checked == true){
	  var weight = document.getElementById('weight').value;
      var stripped_weight = weight.replace(/[\(\)\.\-\ ]/g, '');
      var dob = document.getElementById('dob').value
	  var stripped_dob = dob.replace(/[\(\)\.\-\ ]/g, '');
	  var height = document.getElementById('height_feet').value
	  var height_inches = document.getElementById('height_inches').value
	  var allow_digits = "!@#$%^&*()+-_=[]\\\';,/{}|\":<>?qwertyuiopasdfghjklzxcvbnm";
	  var digits = /\d/;
	  var whitspace = /\s/;
	  var dtCh= "-";
      var minYear=1900;
	  var maxYear=2100;
  	  var mth = document.getElementById('month').value
	  var dy = document.getElementById('day').value
	  var yr = document.getElementById('dob').value
	  var full_date = mth+"-"+dy+"-"+yr
	  var date_year = yr+"-"+mth+"-"+dy
      var thisDate = new Date();
	  var dYear = parseInt(date_year.substring(0,4),10);
	  var dMonth = parseInt(date_year.substring(5,7),10);
	  var dDate = parseInt(date_year.substring(8,10),10);
	  var dobDate = new Date(dYear, dMonth, dDate);
	  var age = thisDate.getFullYear() - dobDate.getFullYear()
	

	// validations for weight 
		if (weight == "" || weight == 0 || weight == 0.0) {
			reason += "Please provide Weight \n";
		}
		else if (whitspace.test(weight) || (!digits.test(weight))) {
			reason += "Please provide a proper weight \n";
		}
		else if (weight < 50 || weight > 500) {
			reason += "Weight is expected to be between 50-500 lbs \n";
		}
		else {
			legal = true;
			for (var i = 0; i < weight.length; i++) {
				if (allow_digits.indexOf(weight.charAt(i)) != -1) {
					legal = false;
				}
			}
			if (legal == false){
				reason += "Weight contains invalid characters \n";
			}
		}
		
	// validations for gender
		genderMale = document.getElementById('gender_male');
		genderFemale = document.getElementById('gender_female');
		if (genderMale.checked || genderFemale.checked){
			// do nothing
		}
		else {
			reason += "Please select your Gender \n"
		}
		
	// validations for Date Of Birth
	if (age < 19) {
	    	reason += "You must be atleast 18 years old !! \n";
			reason += "Please check the Date of Birth you entered \n"
		}	

	function isInteger(s){
		var i;
	    for (i = 0; i < s.length; i++){   
	        // Check that current character is number.
	        var c = s.charAt(i);
	        if (((c < "0") || (c > "9"))) return false;
	    }
	    // All characters are numbers.
	    return true;
	}

	function stripCharsInBag(s, bag){
		var i;
	    var returnString = "";
	    // Search through string's characters one by one.
	    // If character is not in bag, append to returnString.
	    for (i = 0; i < s.length; i++){   
	        var c = s.charAt(i);
	        if (bag.indexOf(c) == -1) returnString += c;
	    }
	    return returnString;
	}
	
	function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
	}
	
	function DaysArray(n) {
		for (var i = 1; i <= n; i++) {
			this[i] = 31
			if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
			if (i==2) {this[i] = 29}
	   } 
	   return this
	}

	function isDate(dtStr){
		var daysInMonth = DaysArray(12)
		var pos1=dtStr.indexOf(dtCh)
		var pos2=dtStr.indexOf(dtCh,pos1+1)
		var strMonth=dtStr.substring(0,pos1)
		var strDay=dtStr.substring(pos1+1,pos2)
		var strYear=dtStr.substring(pos2+1)
		strYr=strYear
		if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
		if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
		for (var i = 1; i <= 3; i++) {
			if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
		}
		month=parseInt(strMonth)
		day=parseInt(strDay)
		year=parseInt(strYr)
		if (pos1==-1 || pos2==-1){
			reason += "The date format should be : mm-dd-yyyy \n"
		}
		if (strMonth.length<1 || month<1 || month>12){
			reason += "Please enter a valid month \n"
		}
		if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
			reason += "Please enter a valid day \n"
		}
		if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
			reason += "Please enter a valid 4 digit year between "+minYear+" to "+maxYear+"\n"
		}
		if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
			reason += "Please enter a valid date \n"
		}
	return true
	}

	if (isDate(full_date)==false){
		return false
	}
	
	// validations for height
	if (height == 0) {
		reason += "Please provide a valid Height \n"
	}
	else if (!validateHeight(allow_digits, height) || !validateHeight(allow_digits, height_inches)) {
		reason += "Height contains invalid characters \n"
	}
	else if (whitspace.test(height) ||(!digits.test(height))) {
		reason += "Please provide a proper Height \n";
	}
	else if (height < 1 || height > 10){
		reason += "Height expected to be in between 1 - 10 ft"
	}
	else if (height_inches < 0 || height_inches > 12){
		reason += "Height-Inches expected to be in between 0-12 inches"
	}
	
	}
	
	function validateHeight(allow_digits, value){
		legal = true;
		for (var i = 0; i < value.length; i++) {
			if (allow_digits.indexOf(value.charAt(i)) != -1) {
				legal = false;
			}
		}
		if (legal == false){
			return false;
		}
		return true;
	}
	
	if (reason != ""){
		alert(reason);
		return false;
	} 
	return true;
}


// toggle weight tracker input field display
function showMe(input_field){
	if (document.getElementById(input_field).style.display == "block") {
		document.getElementById(input_field).style.display = "none"
	}
	else {
		document.getElementById(input_field).style.display = "block"
	}
}

	
// validations for weight details
function validateWeightdetails(val){
	var weight = document.getElementById('weight').value;
	var chest = document.getElementById('chest').value;
	var ual = document.getElementById('upper_arm_left').value;
	var uar = document.getElementById('upper_arm_right').value;
	var waist = document.getElementById('waist').value;
	var hips = document.getElementById('hips').value;
	var tl = document.getElementById('thigh_left').value;
	var tr = document.getElementById('thigh_right').value;
	var stripped_weight = weight.replace(/[\(\)\.\-\ ]/g, '');
	var stripped = chest.replace(/[\(\)\.\-\ ]/g, '');
	var stripped_ual = ual.replace(/[\(\)\.\-\ ]/g, ''); 
	var stripped_uar = uar.replace(/[\(\)\.\-\ ]/g, ''); 
	var stripped_waist = waist.replace(/[\(\)\.\-\ ]/g, ''); 
	var stripped_hips = hips.replace(/[\(\)\.\-\ ]/g, ''); 
	var stripped_tl = tl.replace(/[\(\)\.\-\ ]/g, ''); 
	var stripped_tr = tr.replace(/[\(\)\.\-\ ]/g, '');  
	var iChars = "!@#$%^&*()+-=[]\\\';,/{}|\":<>?";
	var space = /\S/;
	var whitspace = /\s/;
	var allow_digits = "!@#$%^&*()+-_=[]\\\';,/{}|\":<>?qwertyuiopasdfghjklzxcvbnm";	
	errors = "";
	
	function validateInputs(value){
		var allow_digits = "!@#$%^&*()+-_=[]\\\';,/{}|\":<>?qwertyuiopasdfghjklzxcvbnm";
		legal = true;
		for (var i = 0; i < value.length; i++) {
			if (allow_digits.indexOf(value.charAt(i)) != -1) {
				legal = false;
			}
		}
		if (legal == false){
			return false;
		}
		return true;
	}
	
	// validations for weight
	if (isNaN(parseInt(stripped_weight)) || whitspace.test(weight) || !validateInputs(weight)){
		errors += "Weight contains invalid characters \n";
	}
	else if(weight < 50 || weight > 500){
		errors += "Weight is expected to be between 50-500 lbs \n";
	}
	
	//validations for Chest
	if (isNaN(parseInt(stripped)) || whitspace.test(chest) || !validateInputs(chest)){
		errors += "Chest contains invalid characters \n";
	}
	else if(chest < 0 || chest > 100){
		errors += "Chest expected to be between 0-100 inches \n";
	}
	
	//validations for Upper Arm Left
	if (isNaN(parseInt(stripped_ual)) || whitspace.test(ual) || !validateInputs(ual)){
		errors += "Upper Arm Left contains invalid characters \n";
	}
	else if(ual < 0 || ual > 100){
		errors += "Upper Arm Left expected to be between 0-100 inches \n";
	}
	
	//validations for Upper Arm Right
	if (isNaN(parseInt(stripped_uar)) || whitspace.test(uar) || !validateInputs(uar)){
		errors += "Upper Arm Right contains invalid characters \n";
	}
	else if(uar < 0 || uar > 100){
		errors += "Upper Arm Right expected to be between 0-100 inches \n";
	}
	
	//validations for Waist
	if (isNaN(parseInt(stripped_waist)) || whitspace.test(waist) || !validateInputs(waist)){
		errors += "Waist contains invalid characters \n";
	}
	else if(waist < 0 || waist > 80){
		errors += "Waist expected to be between 0-80 inches \n";
	}
	
	//validations for Hips
	if (isNaN(parseInt(stripped_hips)) || whitspace.test(hips) || !validateInputs(hips)){
		errors += "Hips contains invalid characters \n";
	}
	else if(hips < 0 || hips > 50){
		errors += "Hips expected to be between 0-50 inches \n";
	}
	
	//validations for Thigh Left
	if (isNaN(parseInt(stripped_tl)) || whitspace.test(tl) || !validateInputs(tl)){
		errors += "Thigh Left contains invalid characters \n";
	}
	else if(tl < 0 || tl > 50){
		errors += "Thigh Left expected to be between 0-50 inches \n";
	}
	
	//validations for Thigh Right
	if (isNaN(parseInt(stripped_tr)) || (whitspace.test(tr)) || !validateInputs(tr)){
		errors += "Thigh Right contains invalid characters \n";
	}
	else if(tr < 0 || tr > 50){
		errors += "Thigh Right expected to be between 0-50 inches \n";
	}
	
	if (errors != "") {
		alert(errors);
		return false;
	}
	return true;
}

function validateFitnessMusclegroup(val){
	if (val.muscle_group.selectedIndex <= 0)
	{
		alert("Please select the Muscle group");
		return (false);
	}
	return true;
}	 

function Validatetitle(val){
	var exercise_title = document.getElementById('edit_video_name').value;
	var legalChars = /\w/ ;
	var iChars = "!@#$%^&*()+=[]\\\';,/{}|\":<>?";
	var non_digits = /\D/ ;
	if(exercise_title==""){
		alert('Enter Exercise Title')
		return false;
	}
	else if(!non_digits.test(exercise_title)){
		alert('For exercise title all digits are not accepted')
		return false;
	}
	else if (!legalChars.test(exercise_title)){
		alert('Exercise Title contains Special characters')
		return false;
	}
	for (var i = 0; i < exercise_title.length; i++) {
         if (iChars.indexOf(exercise_title.charAt(i)) != -1) {
           alert ("The Exercise Title  has special characters. \nThese are not allowed.\n");
         return false;
        }
    }	
		return true;
}

// set default focus for all pages when loaded
function setfocus(a_field_id) {
        $(a_field_id).focus()
   }

//function validatePasswordFields() {
//	var new_password = document.getElementById('new_password').value;
//	var confirm_password = document.getElementById('confirm_new_password').value;
//	var illegalChars = /[\W_]/;
//	reason = "";
//	if (new_password == "") {
//		reason += "Please provide New Password \n";
//	}
//	if ((new_password.length < 4)||(new_password.length > 40)) { 
//		reason += "Password should be 4-8 chars in length \n";
//	}
//	if (illegalChars.test(new_password)){
//		reason += "Password contains illegal characters \n";
//	}
//	if (new_password != confirm_password){
//		reason = "Password do not match \n"
//	}
//	if (reason != "") 
//	  {
//	    alert(reason);
//	    return false;
//	  }
//	  return true;
//}

function toggleChangePassword(){
	if(change_password == false){
		change_password = true;	
		cpdiv = document.getElementById('change_password');
		html = "<ul>"
		html += "<li><label for='email'>Current Password</label> <input type='password' id='old_password' name='change_pswd[old_password]' /></li>" ;
		html += "<li><label for='password'>New Password &nbsp;&nbsp;&nbsp;&nbsp;</label> <input type='password' id='new_password' name='change_pswd[new_password]' /></li>" ;
		html += "<li><label for='confirm'>Confirm Password</label> <input type='password' id='confirm_new_password' name='change_pswd[confirm_new_password]' /></li>" ;
		html += "</ul>";
		cpdiv.innerHTML = html;
	}
	else if(change_password == true){
		change_password = false;	
		cpdiv = document.getElementById('change_password');
		cpdiv.innerHTML = "";
	}
}

// new category validation script
function validateCategoryOnSubmit(theForm){
	var errors = "";
    var legalChars = /[\w]/ ; 
	var illegalChars = /[\W]/ ; 
    var digits = /\D/ ;
	var catName = theForm.category_name.value;
	var subCat = theForm.sub_category.value;
	
	if(catName == ""){
		errors += "Category Name required \n";
	} else if (!legalChars.test(catName)) {
  		errors += "Invalid Category Name \n";
	} else if (!digits.test(catName)) {
			errors += "Invalid Category Name \n";
	}
//	if(!validCatName(catName)){
//		errors += "Invalid Category Name. Speacial characters not allowed.\n"
//	}
	if(catName.length > 50){
		errors += "Category Name should exists between 1-50 characters."		
	}
	var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?";
    for (var i = 0; i < catName.length; i++) {
         if (iChars.indexOf(catName.charAt(i)) != -1) {
           alert ("Category Name contains special characters. \nThese are not allowed.\n");
         return false;
        }
    }
	if(errors != ""){
		alert(errors);
		return false;
	}
	return true;
}

// new article validation script
function validateArticle(){
	var legalChars = /\w/ ; // allow letters, numbers,space and underscores
	var title = document.getElementById('title').value;
//	var sub_title = document.getElementById('sub_title').value;
//	var author_name = document.getElementById('author_name').value;
	var article_image = document.getElementById('article_image').value;
	var excerpt = document.getElementById('new_article_excerpt').value;
	var category = document.getElementById('category_id').value;
	var whitespace = /\S/;
	var errors = ""
	
	// validate title
	if(title == "" || !whitespace.test(title)){
		errors += "Article Title required \n";
	}else if (title.length > 100){
		errors += "Title limited to 100 chars only \n"
	}
	
	// validate sub title
//	if(sub_title == ""){
//		errors += "SubTitle required \n";
//	}else if (sub_title.length > 200){
//		errors += "SubTitle limited to 200 chars only \n"
//	}
	
	// validate author name
//	if(author_name == ""){
//		errors += "Author Name required \n";
//	}else if (author_name.length > 50){
//		errors += "Author Name limited to 50 chars only \n"
//	}
	
	// validate excerpt
	if(excerpt == ""){
		errors += "Article Excerpt required \n";
	}else if(!whitespace.test(excerpt)){
		errors += "Article Excerpt required \n"
	}else if (excerpt.length > 1000){
		errors += "Article Excerpt limited to 1000 chars only \n"
	}
	
	//validate category
	if(category == 0){
		errors += "Please select a Category \n";
	}
	
	if (errors != ""){
		alert(errors);
		return false;
	}
	return true;
}

// function to validate the File type
	function validateImageExtension(fld)
	{
		image = document.getElementById('article_image').value;
		if(!/(\.png|\.jpg|\.jpeg)$/i.test(image)) {
			alert("Select jpg or png files for Article Images.");
			var imagespan =	document.getElementById('imagespan');
	     	imagespan.innerHTML="";
		  	imagespan.innerHTML='<input type="file" size=30 name="article_image" id="article_image" onchange="return validateImageExtension(this)" />';
			return false;
		}
	  	return true;
	}
//Event.addBehavior.reassignAfterAjax = true;
//  Event.addBehavior({
//    'div.pagination a' : Remote.Link
//  })

//function to validate New Videos
 function validateVideosForm(){
 	var video_file = document.getElementById('video_file').value;
	var thumbnail_file = document.getElementById('thumbnail_file').value;
	var title = document.getElementById('video_title').value;
	var category = document.getElementById('video_category').value;
	var digits = /\D/ ; 
	var space = /\S/;
	
	var errors = ""
	
	if(video_file =="" || video_file.toString().match(/^[-]?\d*$/)){
		errors += "Video : Select a .flv file \n" ;
	}
	if(thumbnail_file =="" || thumbnail_file.toString().match(/^[-]?\d*$/)){
		errors += "Thumbnail : Select a .jpg/.png file \n";
	}
	if(title =="") 
	{
		errors += "Title required \n";
	}
	else if(!space.test(title)){
		errors += "Specify Title name \n"
	}
	else if(title.length > 100){
		errors += "Title too lengthy \n";
	}
	if(category == 0){
		errors += "Category required \n";
	}
	if (errors != ""){
		alert(errors);
		return false;
	}
	return true;
 }

// function to validate edit videos
function validateEditVideosForm(){
 	var video_file = document.getElementById('video_file').value;
	var thumbnail_file = document.getElementById('thumbnail_file').value;
	var title = document.getElementById('video_title').value;
	var category = document.getElementById('video_category').value;
	var digits = /\D/ ; 
	var space = /\S/;	
	
	var errors = ""
	
	if(title =="") 
	{
		errors += "Title Required \n";
	}
	else if(!space.test(title)){
		errors += "Specify Title name \n"
	}
	else if(title.length > 100){
		errors += "Title too lengthy \n";
	}
	if(category == 0){
		errors += "Category required \n";
	}
	
	if (errors != ""){
		alert(errors);
		return false;
	}
	return true;
 }
 
 function validateUserReportForm(){
 	var customer = document.getElementById('customer_id').value;
	var month = document.getElementById('month').value;
	errors = "";
	if(customer == ""){
		errors += "Select a Customer <br>";
	}
	if(month == ""){
		errors += "Select a Month \n";
	}
	
	if(errors != ""){
		document.getElementById('report').innerHTML = "<font color='red'>"+errors+"</font>";
		return false;
	}
	return true;
 }
 
 function validateQuery() {
 	var query = document.getElementById('query_string').value
	if (query == "") {
		return false;
	}
	return true;
 }
 
 /* phase -3 javsscript by venkat 
  if someone adds want to add code, please label your as above and please dont mix it with this...
  */
 function validate_food_option(){
	var food_option = document.getElementById('options_food_name').value;
	if (food_option == ''){
		alert('Please enter a food option');
		return false;
	}
	else{
		return true;
	}
}

function validate_food_rule(){
	var food_option = document.getElementById('rules_food_name').value;
	var rules = ['rules_redmeat', 'rules_pork', 'rules_poultry', 'rules_fish', 'rules_eggs', 'rules_tofu', 'rules_dairy', 'rules_peanuts', 'rules_high_sodium', 'rules_high_cholesterol']
	reason = ""
	var counter = 0;
	if (food_option == ''){
		reason += 'Please enter a replacement food \n';
		for (i = 0; i < rules.length; i++){   
	        if (document.getElementById(rules[i]).checked == true){
				counter += 1;
			}
	    }
		if (counter == 0){
			reason += "Please specify a rule \n";
		}
		else if (counter > 1){
			reason += "Only one rule accepeted \n";
		}
	}
	if (reason == ''){
		return true;
	}
	else{
		alert(reason);
		return false;
	}
}

function reset_field(field_id){
	document.getElementById(field_id).value="";
}

// function repeated in nutritions/index.rhtml 
// function used here for enabling when page loads for firt time in nutrition tracker and user checks any food item
	function enable_recipe_popup(food_popup_id){
		myLightWindow.createWindow(food_popup_id);
	}
	
// function to recognize which radio option clicked in edit and new foodoptions in mealplans
// function used in support of Observe field for radio buttons
	function radio_optionClick (food_id, subfood_id) {
		ele_id = 'food_option_type_' + food_id;
		document.getElementById(ele_id).value = subfood_id;
	}
	
// function to validate Sales Lead users when editing.
	function validateSalesLead(cmpny){
		var company = document.getElementById('user_company').value;
		var space = /\S/;		
		if(company == ""){
			alert('Please Enter Company')
			return false;	
		}
	else if(!space.test(company)){
		alert('Please Enter Company')
		return false;
	}		
		return true;
	}
	
	
// checks whether the Customer was Sales Lead or not when creating new user or editing a user 
// from drop down list and displays accordingly.
	function sales_user_company(cmpy){
		if(cmpy.value == 29){
			document.getElementById('company').style.display = "block"
		}
		else{
			document.getElementById('company').style.display = "none"			
		}
	}
	
// function calls when admin tries to change Customer Name to Sales Lead in editing Life2Go users
	function validate_sales_lead(cmpny){
		var customer_id = document.getElementById('user_customer_name').value;
		var company = document.getElementById('permission_super_admin').value;
		if (customer_id == 29) {
			var space = /\S/;				
			if (company == "") {
				alert('Please Enter Company')
				return false;
			}
			else 
				if (!space.test(company)) {
				alert('Please Enter Company')
				return false;				
				}		
			}
			return true;
		}
	