// 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 val = new function() {
	$.fn.validate = {
        init: function(o) {
					switch(o.name){
						case 'title': this.lengthcheck(o,2,150); break;
						case 'url_title': this.lengthcheck(o,2,150); break;
						case 'staff_id': this.staff_id(o); break;
						case 'username': this.username(o); break;
						case 'name': this.lengthcheck(o,2,150); break;
						case 'credit_card_name': this.lengthcheck(o,2,150); break;
						case 'credit_card_number': this.lengthcheck(o,13,16); break;
						case 'verification_number': this.lengthcheck(o,3,4); break;
						case 'expiry_date': this.expDate(o); break;
						case 'postal_address': this.lengthcheck(o,12,150); break;
						case 'firstname': this.namepart(o); break;
						case 'first_name': this.namepart(o); break;
						case 'new_first_name': this.namepart(o); break;
						case 'lastname': this.namepart(o); break;
						case 'last_name': this.namepart(o); break;
						case 'new_last_name': this.namepart(o); break;
						case 'permalink': this.permalink(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 'url': this.url(o); break;
						case 'contact_email': this.email(o); break;
						case 'new_email': this.email(o); break;
						case 'email': this.email(o); break;
						case 'dob': this.dob(o); break;
						case 'contact_telephone': this.telephone(o); break;
						case 'phone': this.telephone(o); break;
						case 'contact_mobile': this.mobile(o); break;
						default: doValidate(o);
					}
        },
        lengthcheck: function(o,min_len,max_len) {
          if (o.value.length < min_len || o.value.length > max_len ){
						doError(o,o.id + ' (' + o.value.length + ') must be between ' + min_len + ' and ' + max_len + ' characters.');
					} else {
						doValidate(o);
					}
        },
        username: function(o) {
          var user = /[(\*\(\)\[\]\+\.\,\/\?\:\;\'\"\`\~\\#\$\%\^\&\<\>)+]/;
          if (!o.value.match(user)) {
						if (o.value.length < 6){
						doError(o,o.id + ' (' + o.value.length + ') must be longer than 6 characters');
						} else {
						doValidate(o);
						}
					} else {
						doError(o,'found{'+o.value.match(user)+'}, only a-z,A-Z,0-9,_,- characters allowed');
					};
        },
        namepart: function(o) {
          var user = /[0-9(\*\(\)\[\]\+\_\.\,\/\?\!\[\]\{\}\|\+\*\"\:\;\"\~\\#\$\%\^\&\<\>)+]/;
          if (!o.value.match(user)) {
						this.lengthcheck(o,1,35);//doValidate(o);
					} else {
						doError(o,'found{'+o.value.match(user)+'}, only a-z,A-Z,\',`,- and space characters allowed');
					};
        },
        password: function(o) {
          var pass = /[(\*\(\)\[\]\+\.\,\/\?\:\;\'\"\`\~\\#\$\%\^\&\<\> )+]/;
					if (!o.value.match(pass)) {
						/*if (o.value.length < 6){
							doError(o,o.id + ' (' + o.value.length + ') must be longer than 6 characters');
						} else {*/
							this.lengthcheck(o,6,100);//doValidate(o);
						/*}*/
					} else {
						doError(o,'found{'+o.value.match(pass)+'}, only a-z,A-Z,0-9,_,- characters allowed');
					};
        },
        re_password: function(o) {
          var pass = /[(\*\(\)\[\]\+\.\,\/\?\:\;\'\"\`\~\\#\$\%\^\&\<\> )+]/;
					if (!o.value.match(pass)) {
						
							temp = o.id.split("_");
							if ($("#"+temp[1]).val() == o.value){
								this.lengthcheck(o,6,100);//doValidate(o);
							}else{
								doError(o,' passwords do not match');	
							}
						
					} else {
					doError(o,'only alpha-numeric,_ and - characters allowed');
					};
        },
        url: function(o) {
          var email  = /^(http:\/\/|https:\/\/)+(([a-zA-Z0-9\_\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
           if (o.value.match(email)) {
              this.lengthcheck(o,8,150);
            } else {
							if (o.value.length == 0){
								doValidate(o);
							}else{
              	doError(o,'not a valid url: http(s)://');
							}
            };
        },
        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');
            };
        },
        telephone: function(o) {
          var invalid  = /[A-Za-z(\*\(\)\[\]\_\.\,\/\?\!\[\]\{\}\|\*\"\:\;\"\~\\#\$\%\^\&\<\>)]/;
           if (!o.value.match(invalid)) {
              if (/*o.value.length > 0 &&*/ (o.value.length != 10 && o.value.length != 8) ){
				  doError(o,'doesn\'t appear to be a valid phone number.  Must be 8 or 10 digits');
			  }else{
				  doSuccess(o);
			  }
            } else {
              doError(o,'found{'+o.value.match(invalid)+'}, not a valid telephone number.');
            };
        },
        mobile: function(o) {
          var invalid  = /[A-Za-z(\*\(\)\[\]\_\.\,\/\?\!\[\]\{\}\|\*\"\:\;\"\~\\#\$\%\^\&\<\>)]/;
           if (!o.value.match(invalid)) {
              if (o.value.length > 0 && (o.value.length != 10 && o.value.length != 8) ){
				  doError(o,'doesn\'t appear to be a valid phone number.  Must be 8 or 10 digits');
			  }else{
				  doSuccess(o);
			  }
            } else {
              doError(o,'found{'+o.value.match(invalid)+'}, not a valid telephone number.');
            };
        },
        staff_id: function(o) {
          var staff_id  = /^([0-9]{6})([A-Z]{1})+$/;
           if (o.value.match(staff_id)) {
              this.lengthcheck(o,6,7);
            } else {
              doError(o,'found{'+o.value.match(staff_id)+'}, not a valid Staff id');
            };
        },
        permalink: function(o) {
          var valid_values = /[A-Z(\*\(\)\[\]\+\.\,\/\?\!\[\]\{\}\|\+\*\'\"\:\;\'\"\`\~\\#\$\%\^\&\<\> )+]/;
           if (o.value.match(valid_values) && o.value != 0) {
				doError(o,'found{'+o.value.match(valid_values)+'}, only a-z,0-9,_,- characters allowed.');
            } else {
              this.lengthcheck(o,0,70);//doValidate(o);//doSuccess(o);
            };
        },
        release_code: function(o) {
          var valid_values = /^([A-Z]{1})([0-9]{3})\/([0-9]{2})$/;
					//var valid_values = /[a-z(\*\(\)\[\]\+\.\,\?\!\[\]\{\}\_\-\|\+\*\'\"\:\;\'\"\`\~\\#\$\%\^\&\<\> )+]/;
           if (!o.value.match(valid_values)) {
							doError(o,'must be of the form: C123/56');
            } else {
              if (o.value.length != 7){
								doError(o,o.id + '  (' + o.value.length + ') must be 7 characters');
							} else {
								doValidate(o);//doSuccess(o);
							}
					};
        },
        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');
            };
        },
        expDate: function(o) {
          var dob  = /(0[1-9]|1[012])+\/(19|20)\d\d/;
            if (o.value.match(dob)) {
              doSuccess(o);
            } else {
              doError(o,'not a valid expiry date (should be in the form of MM/YYYY)');
            };
        }
	};


	/* -- private functions -- */

     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.php', { 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")){
						/* validate.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="/admin/resources/images/loading.gif" border="0" style="float:left; margin-left:-25px;"/>');

						$(".form").each(function(){
							$.post('/resources/helpers/'+this.id+'/validate.php', { id: o.id, no_duplicate: true, value: o.value }, function(json) {
								eval("var args = " + json);
								if (args.success == true || duplicate_originals[o.id] == o.value){
									doSuccess(args);
								} else {
									doError(args,args.msg);
								}
							});/**/
						});

					} else {
						doSuccess(args);
					}
				} else {
					doError(args,args.msg);
				}
				});
    };

};

/*============================================================================*/

/*

This routine checks the credit card number. The following checks are made:

1. A number has been provided
2. The number is a right length for the card
3. The number has an appropriate prefix for the card
4. The number has a valid modulus 10 number check digit if required

If the validation fails an error is reported.

The structure of credit card formats was gleaned from a variety of sources on 
the web, although the best is probably on Wikepedia ("Credit card number"):

  http://en.wikipedia.org/wiki/Credit_card_number

Parameters:
            cardnumber           number on the card
            cardname             name of card as defined in the card list below

Author:     John Gardner
Date:       1st November 2003
Updated:    26th Feb. 2005      Additional cards added by request
Updated:    27th Nov. 2006      Additional cards added from Wikipedia
Updated:    18th Jan. 2008      Additional cards added from Wikipedia
Updated:    26th Nov. 2008      Maestro cards extended
Updated:    19th Jun. 2009      Laser cards extended from Wikipedia

*/

/*
   If a credit card number is invalid, an error reason is loaded into the 
   global ccErrorNo variable. This can be be used to index into the global error  
   string array to report the reason to the user if required:
   
   e.g. if (!checkCreditCard (number, name) alert (ccErrors(ccErrorNo);
*/



/*============================================================================*/
