function chkLogin(fname) {
  ff = eval("document."+fname);
  if (ff.login_id.value == "") {
    alert("Please enter your screen name or email address.");
    ff.login_id.focus();
    return false;
  }
  else if (ff.pass.value == "") {
    alert("Please enter your password.");
    ff.pass.focus();
    return false;
  }
  else {
    ff.subtn.value = "Signing in...";
    ff.subtn.disabled = true;
    return true;
  }
}

function chk_text_option() {
  if ($('itext_enabled').checked) {
    $('t1').setStyle('display','');
    $('t2').setStyle('display','');
  }
  else {
    $('t1').setStyle('display','none');
    $('t2').setStyle('display','none');
  }
}

function checkSugForm() {
  ff = eval("document.sugForm");
  if (ff.name.value == "") {
    alert("Please enter your name.");
    ff.name.focus();
    return false;
  }
  else if (ff.email.value.indexOf('@') <= 0) {
    alert("Please enter a valid email address.");
    ff.email.focus();
    ff.email.select();
    return false;
  }
  else if (ff.comments.value == "") {
    alert("Please enter comments.");
    ff.comments.focus();
    return false;
  }
  else {
    ff.subtn.value = "Sending...";
    ff.subtn.disabled = true;
    return true;
  }
}

function regForm_helper_error(elem,msgt) { 
  $('helper_'+elem).set({'html':msgt,'class':'helper_error'}).setStyle('display','');
}

function regForm_helper_msg(elem,msgt) {
  $('helper_'+elem).set({'html':msgt}).setStyle('display','');
}

function regForm_helper_hide(elem) {
  $('helper_'+elem).set({'html':'','class':'helper'}).setStyle('display','none');
}

function regForm_reset_class(elem) {
  cur_class = $('helper_'+elem).get('class');
  if (cur_class != 'helper') {
    $('helper_'+elem).set('class','helper');
  }
}

var illegalChars = /\W/; // alpha-numeric & underscores

function regForm_chkUser() {
  myuser = $('iuser').value;
  if (illegalChars.test(myuser)) {
    regForm_helper_error('iuser','Letters & numbers only!');
  }
  else if (myuser.length < 7) {
    regForm_helper_error('iuser','Too Short!');
  }
  else {
    regForm_reset_class('iuser');
    regForm_helper_msg('iuser','Screen name Good!')
  }
  
  if (myuser != "") {
//    $('myweburl').set('html','Your URL: http://'+myuser+'.goalvana.com/');
  }
  else {
//    $('myweburl').set('html','');
  }
}

function regForm_chkPass() {
  mypass = $('ipass').value;
  if (mypass == "") {
    regForm_helper_error('ipass','Enter a strong password');
  }
  else if (mypass.length < 7) {
    regForm_helper_error('ipass','Password too short');
  }
  else if (!((mypass.search(/[a-z]+/) > -1) && (mypass.search(/[0-9]+/) > -1))) {
    regForm_helper_error('ipass','Password weak');
  }
  else {
    regForm_reset_class('ipass');
    regForm_helper_msg('ipass','Password Strong!')
  }
}

function chkRegForm() {
  ff = eval("document.regform");
  if (ff.ifull_name.value == "") {
    regForm_helper_error('ifull_name','Enter your full name.');
    alert("Please enter your full name.");
    ff.ifull_name.focus();
    return false;
  }
  else if (ff.iuser.value == "") {
    regForm_helper_error('iuser','Enter a screen name.');
    alert("Please enter a unique screen name.");
    ff.iuser.focus();
    return false;
  }
  else if (illegalChars.test(ff.iuser.value)) {
    regForm_helper_error('iuser','Letters & numbers only!');
    alert("Your screen name must contain only numbers and letters. Underscores are also acceptable.");
    ff.iuser.focus();
    ff.iuser.select();
    return false;
  }
  else if (ff.iuser.value.length < 7) {
    regForm_helper_error('iuser','Too Short!');
    alert("Your screen name is too short. Must be at least 7 characters.");
    ff.iuser.focus();
    ff.iuser.select();
    return false;
  }
  else if (ff.ipass.value == "") {
    regForm_helper_error('ipass','Enter a strong password.');
    alert("Please enter a strong password.");
    ff.ipass.focus();
    return false;
  }
  else if (ff.ipass.value.length < 7) {
    regForm_helper_error('ipass','Password too short');
    alert("Your password is too short. Must be at least 7 characters.");
    ff.ipass.focus();
    ff.ipass.select();
    return false;
  }
  else if (!((ff.ipass.value.search(/[a-z]+/) > -1) && (ff.ipass.value.search(/[0-9]+/) > -1))) {
    regForm_helper_error('ipass','Password weak');
    alert("Your password is too weak. Please use at least 1 letter and 1 number.");
    ff.ipass.focus();
    ff.ipass.select();
    return false;
  }
  else if (ff.iemail.value.indexOf('@') <= 0) {
    regForm_helper_error('iemail','Enter a valid email.');
    alert("Please enter a valid email address.");
    ff.iemail.focus();
    ff.iemail.select();
    return false;
  }
  else if (ff.recaptcha_response_field.value == "") {
    alert("Please enter the words you see.");
    ff.recaptcha_response_field.focus();
    return false;
  }
  else {
    $('regbtn').setProperties({'src':'/images/register_btn_off.gif','alt':'Processing...please wait','title':'Processing...please wait','type':'button'});
    return true;
  }
}

function URLEncode(str) {
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";
	var plaintext = str;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";	// x-www-urlencoded, rather than 
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert("Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted.");
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	}
	return encoded;
}

function toggle_check(elem) {
  if ($(elem)) {
    if ($(elem).checked) {
      $(elem).checked = false;
    }
    else {
      $(elem).checked = true;
    }
  }
}

function chkForget() {
  ff = eval("document.forgetform");
  if (ff.login_id.value == "") {
    alert("Please enter your screen name or email address.");
    ff.login_id.focus();
    return false;
  }
  else {
    ff.subtn.disabled = true;
    return true;
  }
}

function chkBillingForm() {
  ff = eval("document.billingform");
  if (ff.ibilling_first_name.value == "") {
    alert("Please enter the billing first name as it appears on the card.");
    ff.ibilling_first_name.focus();
    return false;
  }
  else if (ff.ibilling_last_name.value == "") {
    alert("Please enter the billing last name as it appears on the card.");
    ff.ibilling_last_name.focus();
    return false;
  }
  else if (ff.ibilling_address.value == "") {
    alert("Please enter the billing address as it appears on the card statement.");
    ff.ibilling_address.focus();
    return false;
  }
  else if (ff.ibilling_city.value == "") {
    alert("Please enter the billing city as it appears on the card statement.");
    ff.ibilling_city.focus();
    return false;
  }
  else if (ff.ibilling_state.value == "") {
    alert("Please enter the billing state as it appears on the card statement.");
    ff.ibilling_state.focus();
    return false;
  }
  else if (ff.ibilling_zip.value == "") {
    alert("Please enter the billing zip as it appears on the card statement.");
    ff.ibilling_zip.focus();
    return false;
  }
  else if (ff.icn.value == "") {
    alert("Please enter the credit card number, numbers only, no spaces.");
    ff.icn.focus();
    ff.icn.select();
    return false;
  }
  else if (ff.icvv.value == "") {
    alert("Please enter the 3-digit code found on the back of the card.");
    ff.icvv.focus();
    return false;
  }
  else {
    $('regbtn').setProperties({'src':'/images/save_btn_off.gif','alt':'Saving...please wait','title':'Saving...please wait','type':'button'});
    return true;
  }
}

function chkSaveForm() {
  ff = eval("document.regform");
  if (ff.ifull_name.value == "") {
    regForm_helper_error('ifull_name','Enter your full name.');
    alert("Please enter your full name.");
    ff.ifull_name.focus();
    return false;
  }
  else if (ff.iuser.value == "") {
    regForm_helper_error('iuser','Enter a screen name.');
    alert("Please enter a unique screen name.");
    ff.iuser.focus();
    return false;
  }
  else if (illegalChars.test(ff.iuser.value)) {
    regForm_helper_error('iuser','Letters & numbers only!');
    alert("Your screen name must contain only numbers and letters. Underscores are also acceptable.");
    ff.iuser.focus();
    ff.iuser.select();
    return false;
  }
  else if (ff.iuser.value.length < 7) {
    regForm_helper_error('iuser','Too Short!');
    alert("Your screen name is too short. Must be at least 7 characters.");
    ff.iuser.focus();
    ff.iuser.select();
    return false;
  }
  else if (ff.iemail.value.indexOf('@') <= 0) {
    regForm_helper_error('iemail','Enter a valid email.');
    alert("Please enter a valid email address.");
    ff.iemail.focus();
    ff.iemail.select();
    return false;
  }
  else if ((ff.ipass.value != "") && (ff.icur_pass.value == "")) {
    regForm_helper_error('icur_pass','Enter current password.');
    alert("Please enter your current password.");
    ff.icur_pass.focus();
    return false;
  }
  else if ((ff.ipass.value != "") && (ff.ipass.value.length < 7)) {
    regForm_helper_error('ipass','Password too short');
    alert("Your password is too short. Must be at least 7 characters.");
    ff.ipass.focus();
    ff.ipass.select();
    return false;
  }
  else if ((ff.ipass.value != "") && (!((ff.ipass.value.search(/[a-z]+/) > -1) && (ff.ipass.value.search(/[0-9]+/) > -1)))) {
    regForm_helper_error('ipass','Password weak');
    alert("Your password is too weak. Please use at least 1 letter and 1 number.");
    ff.ipass.focus();
    ff.ipass.select();
    return false;
  }
  else if ((ff.ipass.value != "") && (ff.ipass.value != ff.ipassr.value)) {
    alert("Your new passwords did not match. Please re-enter.");
    ff.ipassr.value = "";
    ff.ipass.focus();
    ff.ipass.select();
    return false;
  }
  else if ((ff.itext_enabled.checked) && (ff.imobile_number.value == "")) {
    alert("Please enter your 10-digit mobile phone number.");
    ff.imobile_number.focus();
    return false;
  }
  else if ((ff.itext_enabled.checked) && (ff.imobile_carrier_id.value == "")) {
    alert("Please select your mobile carrier.");
    ff.imobile_carrier_id.focus();
    return false;
  }
  else {
    $('regbtn').setProperties({'src':'/images/save_btn_off.gif','alt':'Saving...please wait','title':'Saving...please wait','type':'button'});
    return true;
  }
}

function chk_add_goal_cat() {
  if (!$('parent_id')) {
	  if ($('category_id').value == "add") {
	    $('add_category').setStyle('display','');
	    $('new_category').value = "Enter a category name";
	    $('new_category').focus();
	    $('new_category').select();
	  }
	  else {
	    $('add_category').setStyle('display','none');
	    $('new_category').value = "";
	  }
  }
}

function chk_goal_add_form() {
  if ($('goal_content').value == "") {
    alert("Please enter a goal.");
    $('goal_content').focus();
    return false;
  }
  else {
    $('gsubtn1').value = "Saving...";
    $('gsubtn1').disabled = true;
	return true;
  }
}

function chk_goal_save_form() {

  lbl = "goal";

  if ($('goal_content').value == "") {
    alert("Please enter a "+lbl+".");
    $('goal_content').focus();
    return false;
  }
  else if (($('goal_date').value == "") && (!$('ongoing_goal').checked)) {
    alert("Please select a date you want to achieve this "+lbl+" by or check \"This is an Ongoing\".");
    $('goal_date').focus();
    return false;
  }
  else if ( ($('category_id').value == "add") && ( ($('new_category').value == "") || ($('new_category').value == "Enter a category name") ) ) {
    alert('Please enter a new category name.');
    $('new_category').value = "Enter a category name";
    $('new_category').focus();
    $('new_category').select();
    return false;
  }
  else if (($('reminder_option').value == '1') && ($('reminder_timing').value == "")) {
    alert('Please select when you want to be reminded about this '+lbl+'.');
    $('reminder_timing').focus();
    return false;
  }
  else if (($('reminder_option').value == '1') && ($('reminder_method').value == "")) {
    alert('Please select how you want to be reminded about this '+lbl+'.');
    $('reminder_method').focus();
    return false;
  }
  else {
    $('gsubtn2').value = "Saving...";
    $('gsubtn2').disabled = true;
	return true;
  }
}

function fix_goal_numbers() {
  sort_order = 1;
  $$('span.priority').each(function(item){
    item.set('html',sort_order);
	sort_order++;
  });
}

mygoalsort = false;

function init_my_goals() {
  $$('li.goal').each(function(item){
	item.addEvent('mouseover', function(e) {
	  item.set('class','goal_on');
	  $(item.get('id')+'_options').setStyle('display','');
	});
	item.addEvent('mouseout', function(e) {
	  item.set('class','goal');
	  $(item.get('id')+'_options').setStyle('display','none');
	});
  });
  $$('li.goal_comp').each(function(item){
	item.addEvent('mouseover', function(e) {
	  item.set('class','goal_on');
	  $(item.get('id')+'_options').setStyle('display','');
	});
	item.addEvent('mouseout', function(e) {
	  item.set('class','goal_comp');
	  $(item.get('id')+'_options').setStyle('display','none');
	});
  });
  if (mygoalsort) {
    mygoalsort = false;
  }
  mygoalsort = new Sortables('mygoals', {
		constrain: true,
		revert: true,
		clone: true,
		opacity: .5,
		handle: '.handle',
		onComplete: function() {
			str = this.serialize();
		    var myAjax = new Request.JSON({
		    	url:		'/ajax/goal_sort_order',
		    	data:		'&str='+str,
		    	onSuccess:	function(arsp, html) {
			      fix_goal_numbers();
		    	},
		    	onFailure: 	function() {
		    	  alert('Operation Failed!')
		    	}
		    }).get();
		}
  });
}


var Countable = new Class({
  initialize: function(inputId, max, className, errorClass) {
    this.input = $(inputId);
    this.max = max;
 	this.className = className ? className : "count";
 	this.errorClass = errorClass ? errorClass : "error";
 	this.handle = new Element("div").set('class',this.className);
    this.handle.set('html','&nbsp;').injectAfter(this.input);
    this.input.addEvent('keydown', this.onKeyPress.bindWithEvent(this));
    this.input.addEvent('keyup', this.onKeyPress.bindWithEvent(this));
    this.update();
  },
  
  onKeyPress: function(event) {
    event = new Event(event);
    if(!event.shift && !event.control && !event.alt && !event.meta) this.update();
  },
  
  update: function() {
    if (this.input.value.length > this.max)
      this.input.value = this.input.value.substring(0, this.max);
      
    var count = this.max - this.input.value.length;
      
    if (count == 0) {
      var string = "<span class=\""+this.errorClass+"\">Maximum characters entered!</span>";
    }
    else if (count == 1) {
      var string = "1 character left";
    }
    else {
      var string = count + " characters left";
    }
    this.handle.set('html',string);
  }
});

function toggle_filters(istat) {
	if (istat == 1) {
	  $('filters_off').setStyle('display','none');
	  $('filters_on').setStyle('display','');
	  $('filters').setStyle('display','');
	}
	else {
	  $('filters_off').setStyle('display','');
	  $('filters_on').setStyle('display','none');
	  $('filters').setStyle('display','none');
	}
}

function rn() {
  return Math.floor(Math.random()*9999999);
}

function work_on_goal(goal_id) {
//  MOOdalBox_I.open(
//    "/ajax/work_on_goal?goal_id="+goal_id+"&rn="+rn(),
//    "Work On Your Goal",
//    "750 450"
//  );
  window.location = '/work_on_goal?goal_id='+goal_id;
}

function load_goal_stats() {
  if ($('goal_id')) {
    load_action_stats();
  }
  else {
	  new Request({
	    url: '/ajax/goal_stats?rn='+rn()+'&sc='+$('sc').value,
	    onSuccess: 	function(txt) {
		  $('gstats').set('html',txt);
	    }
	  }).send();
  }
}

function reload_goal(goal_id) {
  mygoalsort.removeItems($('goal'+goal_id));
  new Request({
    url: '/ajax/reload_goal?rn='+rn()+'&goal_id='+goal_id,
    onSuccess: 	function(txt) {
	  $('goal'+goal_id).set('html',txt);
	  fix_goal_numbers();
	  load_goal_stats();
	  mygoalsort.addItems($('goal'+goal_id));
    }
  }).send();
}

function mark_goal_complete(id) {
  var cc = confirm("Are you sure you want to mark this goal complete?");
  if (cc == true) {
    new Request({
      url: '/ajax/goal_complete?rn='+rn()+'&mode=mark_complete&goal_id='+id,
      onSuccess: 	function(txt) {
	    $('goal'+id).destroy();
	    load_goal_stats();
	    fix_goal_numbers();
	    mygoalsort.removeItems($('goal'+id));
      }
    }).send();
  }
  else {
    $('comp'+id).checked = false;
  }
}

function mark_goal_uncomplete(id) {
  var cc = confirm("Are you sure you want to mark this goal as UNCOMPLETED?");
  if (cc == true) {
    new Request({
      url: '/ajax/goal_complete?rn='+rn()+'&mode=mark_uncomplete&goal_id='+id,
      onSuccess: 	function(txt) {
	    $('goal'+id).destroy();
	    load_goal_stats();
	    fix_goal_numbers();
	    mygoalsort.removeItems($('goal'+id));
      }
    }).send();
  }
  else {
    $('comp'+id).checked = false;
  }
}

function delete_goal(id) {
  var kk = confirm("Are you sure you want to delete this goal?");
  if (kk == true) {
    var myAjax = new Request.JSON({
    	url:		'/ajax/delete_goal',
    	data:		'goal_id='+id,
    	onSuccess:	function(arsp, html) {
	      $('goal'+id).destroy();
	      load_goal_stats();
	      fix_goal_numbers();
	      mygoalsort.removeItems($('goal'+id));
    	},
    	onFailure: 	function() {
    	  alert('Operation Failed!')
    	}
    }).get();
  }
}

function chk_reminder_options(rtag) {
  if ($('reminder_option'+rtag).value == "1") {
    $('reminder_options'+rtag).setStyle('display','');
  }
  else {
    $('reminder_options'+rtag).setStyle('display','none');
  }
}

function chk_reminder_timing(rtag) {
  $('reminder_timing1'+rtag).setStyle('display','none');
  $('reminder_timing2'+rtag).setStyle('display','none');
  $('reminder_timing3'+rtag).setStyle('display','none');
  $('reminder_timing4'+rtag).setStyle('display','none');
  ii = $('reminder_timing'+rtag).value;
  if (ii != "") {
    $('reminder_timing'+ii+rtag).setStyle('display','');
  }
}

function chk_reminder_annually_date(rtag) {
  // 28 = 2
  // 31 = 1 3 5 7 8 10 12
  // 30 = 4 6 9 11
  ii = $('reminder_annually_month'+rtag).value;
  if (ii == '2') {
    $('reminder_annually_day'+rtag).options[28].disabled = true;
    $('reminder_annually_day'+rtag).options[29].disabled = true;
    $('reminder_annually_day'+rtag).options[30].disabled = true;
  }
  else if ((ii == '4') || (ii == '6') || (ii == '9') || (ii == '11')) {
    $('reminder_annually_day'+rtag).options[28].disabled = false;
    $('reminder_annually_day'+rtag).options[29].disabled = false;
    $('reminder_annually_day'+rtag).options[30].disabled = true;
  }
  else {
    $('reminder_annually_day'+rtag).options[28].disabled = false;
    $('reminder_annually_day'+rtag).options[29].disabled = false;
    $('reminder_annually_day'+rtag).options[30].disabled = false;
  }
}

function chk_ongoing_goal(rtag) {
  if ($('ongoing_goal'+rtag).checked) {
    $('goal_date'+rtag).value = "";
  }
}

function uncheck_ongoing_goal(rtag) {
  $('ongoing_goal'+rtag).checked = false;
}

function toggle_action_form() {
  if ($('action_form').getStyle('display') == "none") {
    $('action_form').setStyle('display','');
    $('add_action_btn').setStyle('display','none');
  }
  else {
    if ($('action_action').value == "save_action") {
      window.location = "?goal_id="+$('action_goal_id').value;
    }
    else {
      $('action_form').setStyle('display','none');
      $('add_action_btn').setStyle('display','');
    }
  }
}

function chk_save_action_form() {
  lbl = "action item";

  if ($('goal_content_action').value == "") {
    alert("Please enter a "+lbl+".");
    $('goal_content_action').focus();
    return false;
  }
  else if (($('goal_date_action').value == "") && (!$('ongoing_goal_action').checked)) {
    alert("Please select a date you want to achieve this "+lbl+" by or check \"This is an Ongoing\".");
    $('goal_date_action').focus();
    return false;
  }
  else if (($('reminder_option_action').value == '1') && ($('reminder_timing_action').value == "")) {
    alert('Please select when you want to be reminded about this '+lbl+'.');
    $('reminder_timing_action').focus();
    return false;
  }
  else if (($('reminder_option_action').value == '1') && ($('reminder_method_action').value == "")) {
    alert('Please select how you want to be reminded about this '+lbl+'.');
    $('reminder_method_action').focus();
    return false;
  }
  else {
    $('subtn_action').value = "Saving...";
    $('subtn_action').disabled = true;
	return true;
  }
}

function init_action_sort() {
  mygoalsort = new Sortables('my_action_items', {
		constrain: true,
		revert: true,
		clone: true,
		opacity: .5,
		handle: '.handle',
		onComplete: function() {
			str = this.serialize();
		    var myAjax = new Request.JSON({
		    	url:		'/ajax/goal_sort_order',
		    	data:		'&str='+str,
		    	onSuccess:	function(arsp, html) {
		    	
		    	},
		    	onFailure: 	function() {
		    	  alert('Operation Failed!')
		    	}
		    }).get();
		}
  });
}

function edit_action(action_id, goal_id) {
  window.location = "?goal_id="+goal_id+"&action=edit_action&action_id="+action_id;
}

function delete_action(action_id, goal_id) {
  var kk = confirm("Are you sure you want to delete this Action Item?");
  if (kk) {
    window.location = "?goal_id="+goal_id+"&action=delete_action&action_id="+action_id;
  }
}

function load_action_stats() {
  new Request({
    url: '/ajax/action_stats?rn='+rn()+'&sc='+$('sc').value+'&goal_id='+$('goal_id').value,
    onSuccess: 	function(txt) {
	  $('gstats').set('html',txt);
    }
  }).send();
}

function scroll_to_elem(elem) {
  myScrollFx = new Fx.Scroll(window);
  myScrollFx.toElement($(elem));
}

function init_sub_action_sort() {
  $$('ul.subaction').each(function(item){
    new Sortables(item.get('id'), {
		constrain: true,
		revert: true,
		clone: true,
		opacity: .5,
		handle: '.zhandle',
		onComplete: function() {
			str = this.serialize();
		    var myAjax = new Request.JSON({
		    	url:		'/ajax/goal_sort_order',
		    	data:		'&str='+str,
		    	onSuccess:	function(arsp, html) {
		    	
		    	},
		    	onFailure: 	function() {
		    	  alert('Operation Failed!')
		    	}
		    }).get();
		}
    });
  });
}
