/*
 * jQuery Form Validator Plugin
 * Version: 1.0
 * @requires jQuery v1.3.2 or later
 *
 * Copyright (c) Shawn Adrian
 * Usage and documentation at: http://blog.nerdburn.com
 *
 */
(function($){  

   var defaults = {
      required: true,
      nochars: true,
      somechars: false,
      email: false,
      url: false,
      user: false,
      disableSubmit: true,
      containerClass: '.row',
      errorClass: '.error',       
      inputErrorClass: 'badinput'
   };  

   var valid = new Array;

   // run this to set up a form for validation (required)
   $.fn.setupForm = function(){
      
      var formName = $(this).attr('id');
      valid[formName] = new Array;
      
      // builds an array of form element names and
      // assigns a value of false to them (will be assigned true when validated)
      this.find('input').each(function(){
      
         var objname = $(this).attr('name');
         valid[formName][objname] = false; 
      
      });
      
   };

   // run this on individual or groups of fields to validate
   $.fn.validateFields = function(options) {
       
      var formName = $(this).closest('form').attr('id');
       
      return this.each(function(){  

         var opts = $.extend({}, defaults, options); 
   
         // obj is now the form field, assign it's value to var contents
         obj = $(this);
         var objContents = obj.val();
         var objName = obj.attr('name');
         
         // if there's nothing in the field, throw an error because it's empty
         if(!objContents)
         {
            doError('Cannot be blank.');
         }
         else
         {
            doSuccess('Great!');
  
            // if the special chars option is true, check for special chars
            if(opts.nochars)
            {
               var special = /[(\*\(\)\[\]\+\.\,\/\?\:\;\"\'\@\`\~\\#\$\%\^\&\<\>)+]/;
               if(!objContents.match(special)){
                  doSuccess('Great!');
               } else {
                  doError('Cannot contain special characters.');
               };               
            }    
            
            // if the special chars option is true, check for special chars
            if(opts.somechars)
            {
               var special = /[(\*\(\)\[\]\+\.\,\/\?\:\;\"\@\`\~\\#\$\%\^\<\>)+]/;
               if(!objContents.match(special)){
                  doSuccess('Great!');
               } else {
                  doError('Letters and numbers only.');
               };               
            }                    
            
            // if email option is set to true, check that the value is an email address
            if(opts.email)
            {
               var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
               if(filter.test(objContents))
               {
                  doSuccess('Great!');                
               }               
               else
               {
                  doError('Invalid Email.');
               }
            }
            
            // if the url option is true, throw an error
            if(opts.url)
            {
                $.post('http://golfgroupmanager.com/users/ajax/checkurl', { url: objContents }, function(data) {
                   if(data == 'true')
                   {
                        doError('URL already exists.');
                   }
                   else
                   {
                       doSuccess('Great!');                       
                   }
                });           
            }       
            
            // if the user option is true, check if the user exists or not
            if(opts.user)
            {
                $.post('http://golfgroupmanager.com/users/ajax/checkuser', { email: objContents }, function(data) {
                   if(data == 'true')
                   {
                        doError('Email already exists.');
                   }
                   else
                   {
                       doSuccess('Great!');                       
                   }
                });
            }                 
         }
         
         function doSuccess(message) {
            $(obj).removeClass(opts.inputErrorClass);
            $(obj.siblings(opts.errorClass)).hide();
            valid[formName][objName] = true;
            
            // commented out for edit ringerboard score - need to mess with this
            //if(!in_array(false, valid[formName]))
            //{
               enableSubmit();               
            //}

         }

         function doError(message) {
            $(obj.parent(opts.containerClass)).prepend('<div class="error"><img src="images/msg_red_left.png" class="msg_left" /><div>' + message + '</div><img src="images/msg_red_right.png" class="msg_right" /></div>');
            // do something to disable form submission & submission button
            $(obj).addClass(opts.inputErrorClass);
            valid[formName][objName] = false;
            disableSubmit();
         }
         
         function disableSubmit()
         {
            $('a.dialog_btn').removeClass('dialog_btn').addClass('dialog_disabled_btn');            
         }             
         
         function enableSubmit()
         {
            $('a.dialog_disabled_btn').removeClass('dialog_disabled_btn').addClass('dialog_btn');             
         }
         
         // create a fake php function that's super useful
         function in_array(needle, haystack, argStrict) {
             var key = '', strict = !!argStrict; 
             if (strict) {
                 for (key in haystack) {
                     if (haystack[key] === needle) {
                         return true;            
                     }
                 }
             } else {
                 for (key in haystack) {
                     if (haystack[key] == needle) {                
                        return true;
                     }
                 }
             }
              return false;
         }         
         
      });  

   };
     
})(jQuery);

jQuery.fn.delay = function(time,func){
    return this.each(function(){
        setTimeout(func,time);
    });
};
