// JavaScript Document
/**
*	Based largely on Will Jessup's jQuery form validator
*	http://www.willjessup.com/?p=9
*	removed most of the formatting issues from the front end so
*	it validates (no empty divs etc)
*	
*/
var thing = new function() {
       // $.fn.validate = validate() {};
    $.fn.validate = {
        init: function(o) {
					switch(o.name){
						case 'username': this.username(o); break;
						case 'name': this.username(o); break;
						case 'firstname': this.username(o); break;
						case 'lastname': this.username(o); break;
						case 'login': this.username(o); break;
						case 'password': this.password(o); break;
						case 'pass': this.password(o); break;
						case 're_pass': this.re_password(o); break;
						case 'email': this.email(o); break;
						case 'dob': this.dob(o); break;
						default: doValidate(o);
					}
        },
        username: function(o) {
          var user = /[(\*\(\)\[\]\+\.\,\/\?\:\;\'\"\`\~\\#\$\%\^\&\<\>)+]/;
          if (!o.value.match(user)) {
			  if (o.value.length < 6){
				doError(o,o.id + ' must be longer than ' + o.value.length + ' characters');
			  } else {
				doValidate(o);
			  }
            } else {
				doError(o,'only alpha-numeric,_ and - characters allowed');
            };
        },
        password: function(o) {
          var pass = /[(\*\(\)\[\]\+\.\,\/\?\:\;\'\"\`\~\\#\$\%\^\&\<\>)+]/;
           if (!o.value.match(pass)) {
             if (o.value.length < 6){
				doError(o,o.id + ' must be longer than ' + o.value.length + ' characters');
			  } else {
				doValidate(o);
			  }
            } else {
             doError(o,'only alpha-numeric,_ and - characters allowed');
            };
        },
        re_password: function(o) {
          var pass = /[(\*\(\)\[\]\+\.\,\/\?\:\;\'\"\`\~\\#\$\%\^\&\<\>)+]/;
           if (!o.value.match(pass)) {
             if (o.value.length < 6){
				doError(o,o.id + ' must be longer than ' + o.value.length + ' characters');
			  } else {
				temp = o.id.split("_");
				if ($("#"+temp[1]).val() == o.value){
					doValidate(o);
				}else{
					doError(o,' passwords do not match');	
				}
			  }
            } else {
             doError(o,'only alpha-numeric,_ and - characters allowed');
            };
        },
        email: function(o) {
          var email  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
           if (o.value.match(email)) {
              doSuccess(o);
            } else {
              doError(o,'not a valid email');
            };
        },
        dob: function(o) {
          var dob  = /(0[1-9]|1[012])+\/(0[1-9]|[12][0-9]|3[01])+\/(19|20)\d\d/;
            if (o.value.match(dob)) {
              doSuccess(o);
            } else {
              doError(o,'not a valid date');
            };
        }
     };

     function doSuccess(o) {
		$('#' + o.id).removeClass("error");
		$('#' + o.id).removeClass("validate");
		$('#' + o.id).addClass("validated");
		$('#' + o.id).parent().find(".warning").remove();
		$('#' + o.id).parent().find(".loading").remove();
     }

     function doError(o,m) {
		$('#' + o.id).removeClass("validate");
		$('#' + o.id).removeClass("validated");
		$('#' + o.id).addClass("error");
		$('#' + o.id).parent().find(".warning").remove();
		$('#' + o.id).parent().append('<span class="warning">'+m+'</span>');
		$('#' + o.id).parent().find(".loading").remove();
     }
     //private helper, validates each type after check
     function doValidate(o) {
				/*	Any validation where server-side support is needed
				*	this is business model functionality rather than
				*	light, client side functionality
				*/
				$.post('/resources/helpers/validate.cfm', { id: o.id, value: o.value }, function(json) {
				eval("var args = " + json);
				if (args.success == true){
					/*	test for duplication class in form element
					*	refer to duplicate checking serverside page */
					if (o.className.match("no_duplicate")){
						/* check_exists.cfm simply queries the database for a string match.
						*	this obviously needs to be a custom written component because I don't know
						*	what you're wanting to compare.  The thinking would be that your id name
						*	is the same as it is in the datasource, so you could simply do something like:
						*	"SELECT id FROM datasource WHERE #id# = '#value#'" (coldfusion) 
						*	or
						*	"SELECT id FROM datasource WHERE " . $id . " = '" . $value . "'" (php)
						*/
						
						$('#' + o.id).parent().prepend('<img class="loading" src="/resources/images/loading.gif" border="0" style="float:left; margin-left:-25px;"/>');
						$.post('/resources/helpers/validate.cfm', { id: o.id, no_duplicate: true, value: o.value }, function(json) {
							eval("var args = " + json);
							if (args.success == true){
								doSuccess(args);
							} else {
								doError(args,args.msg);
							}
						});
					} else {
						doSuccess(args);
					}
				} else {
					doError(args,args.msg);
				}
				});
    };

};

$(document).ready(function(){
  /* register any elements that need validation 
	*	force validation on field change*/
	$(".validate").change(function() {
		$(this).validate.init(this);
	});
	
	/* force validation on submit */  
	$("form").submit(function(e){
		var approve = true;
		$(this).find(".validate").each(function() {
			$(this).validate.init(this);
			//approve = false;
		});
		$(this).find(".error").each(function() {approve = false});
		if (!approve){
			e.preventDefault();
		}
	});
	
	/* force confirmation on any delete element */
	$('.delete').find('a').click(function(e){
		if (!confirm(this.title+'?')){
			e.preventDefault();
		}
	});
	
	$('.list_item').hover(
		function(e){ $(this).addClass('list_highlight');},
		function(e){ $(this).removeClass('list_highlight');}
	);
});
