/*
 * jquery autovalidate 0.1 by Michael Forbes
 * requirements: jquery timer, date.js (optional - needed for date validation), google analytics (optional, needed for event tracking), jquery.mask (optional), will format us phone #
 */


    
(function($){

	//Attach this new method to jQuery
 	$.fn.extend({

 		//This is where you write your plugin's name
 		autoValidate: function(options) {

                
                    
                var defaults = {
                    massValidate: false, //validate all fields on submit
                    useMasks: true,
                    timerDelay:2000,
                    rulesTag: 'class',
                    msgTag: 'class',
                    outlineElement: 'li', //which element do you want to add the background styling to
                    outlinePosition:'outside', //where is this element in relation to the validated field
                    errorDisplay:'inline', //how to show errors.  inline, tooltip, and callback function are acceptable
                    tooltipFunction: function(el,parent,msg){ //so you can use any type of tooltip you want - default is beautytips (http://www.lullabot.com/files/bt/bt-latest/DEMO/index.html)
           
                           
                
                    }, 
                    onClear: function(el){
                        
                    }, //function to use when clearing (to remove tooltip for example)
                    successMessage: 'good',
                    successDisplay:'inline',
                    ajaxURL: '',
                    disabled: false, //allow user to disable validation on a specific field
                    analyticsEvents: false, //setting to true will pass errors to google analytics for form analysis
                    onSubmit:'' //optional callback function 
                }
                var options = $.extend(defaults, options);

                var func = this;
                this.parent = '';
                this.errors = 0;
                this.valid = true; //assume it is valid until proven otherwise

                this.validate = function(el)  // starts the validation
                {
                      
                   var $this = this;
                  //need to add timer here for keydown
                   var name = $(el).attr('id');
                   if(options.useMasks) $this.doMask(el);
                   name = name.replace(/\s/,'_',name);
                   
                  
                    if($(el).attr(options.rulesTag).match(/rules\?/)!=null) {
                      
                      //$this.clear(el);
                      
                        $(el).unbind();
                        if(options.useMasks) $this.doMask(el);
                        $(el).keyup(function(){
                            $(el).oneTime(options.timerDelay,"timer_"+name,function () {
                               $this.setRules(el,'keyup');
                            });
                        })
                        $(el).blur(function(){
                           
                            //$(el).oneTime(options.timerDelay,"timer_"+name,function () {
                               $this.setRules(el,'blur');
                           // });
                        })
                        .keydown(function(){
                            $(el).stopTime("timer_"+name);
                        })
                        
                    }
                }

                this.doMask = function(el)
                {
                    var name = $(el).attr('name');
                    
                    if(name.match(/phone/i)!=null || name.match(/fax/i)!=null) $(el).mask("999-999-9999");
                }

                this.setRules = function(el,action) //take the rules from the class and test them
                {
                    
                    var $this = this;
                    var msg = '';
                    var ruleset = $(el).attr(options.rulesTag);
                    var rightRules = ruleset.split('rules?');
                  
                    var rules = rightRules[1].split(' ');
                    if(ruleset.match(/disabled/)==null && options.disabled==false)
                    {
                       
                        var tagset = $(el).attr(options.msgTag);
                        if(tagset.match(/msg\=/))
                        {
                            var rightMsg = tagset.split('msg=');
                            var message = rightMsg[1].split('&');
                            var msg = message[0];
                          
                           
                        }

                        var errors = 0;
                        var ruleArray = rules[0].split('&');
                        for(i=0;i<ruleArray.length;i++)
                        {
                            var opt={rule:ruleArray[i],msg:msg};
                            var result = $.fn.autovalidateHelper(el,opt);
                           
                            
                            
                            for(r in result)
                            {
                                 if(result[r].success == false)
                                {
                                    $this.setError(el,result[r]);
                                    errors++;
                                }
                            }           
                        }
                        
                        if(errors==0) $this.setSuccess(el);
                        if(action=='submit')
                            {
                                if(errors == 0) return true;
                                else return false;
                            }
                    }
                    var name = $(el).attr('id');
                   
                    //if(name.match(/postal/)!=null || name.match(/zip/)!=null) $(el).mask("99999");
                    name = name.replace(/\s/,'_',name);
                    $(el).stopTime("timer_"+name);
                }

                this.setParent = function(el)
                {
                    
                    if(options.outlineElement == "self")
                        {
                           this.parent = $(el);
                        }
                    else if(options.outlinePosition=="outside")
                        {
                           this.parent =  $(el).parents(options.outlineElement);
                          
                        }
                    else
                        {
                           this.parent =  $(el).find(options.outlineElement);
                        }
                    return this.parent;
                }

                this.setError = function(el,result){
                  
                    if(options.analyticsEvents==true) this.googleAnalyticsEvent(el,result);

                     var parent = this.setParent(el);
                     this.clear(el);

                    if(result.errorField!=null)
                    {
                        parent = result.errorField;
                        this.clear(el,parent);
                    }

                   

                    if($.isFunction(options.errorDisplay))
                    {
                        options.errorDisplay(el,parent,result.msg);
                    }
                    else if(options.errorDisplay=='inline')
                    {
                        this.renderErrorInline(el,parent,result.msg);
                    }
                    else if(options.errorDisplay=='tooltip')
                    {
                        this.renderErrorTooltip(el,parent,result.msg);
                    }
                }


                this.clear = function(el,parent)
                {
                   
                    if(parent==null) var parent = this.setParent(el)
                    parent.removeClass('avError')
                    parent.find('div.avErrorMessage').remove();
                    parent.find('div.avSuccess').remove();

                    if($.isFunction(options.onClear)) options.onClear(el);
                    
                }

                this.renderErrorTooltip = function(el,parent,msg)
                {
                    
                    options.tooltipFunction(el,parent,msg);

                }

                this.renderErrorInline = function(el,parent,msg)
                {
                    parent.addClass('avError').append('<div class="ui-widget avErrorMessage"><span class="fg-button ui-state-error fg-button-icon-left ui-corner-all"><span class="ui-icon ui-icon-alert"></span>'+msg+'</span></div>');
                }


                this.setSuccess = function(el){
                    var parent = this.setParent(el);
                    
                    this.clear(el);
                    
                    if(options.analyticsEvents==true) this.googleAnalyticsEvent(el);

                    if($.isFunction(options.successDisplay))
                    {
                        options.successDisplay(el,parent);
                    }
                    else if(options.successDisplay=='inline')
                    {
                        this.renderSuccessInline(el,parent);
                    }
                    else if(options.successDisplay=='tooltip')
                    {
                        this.renderSuccessTooltip(el,parent);
                    }

                }


                this.renderSuccessInline = function(el,parent)
                {

                    $(el).after('<div class="avSuccess"><div class="avSuccessInner">'+options.successMessage+'</div></div>');
                }

                this.googleAnalyticsEvent = function(el,result)
                {
                     var action = $(el).attr('name');
                     var category = 'FORM FIELD SUCCESS';
                     var label = 'success';

                     

                     if(result!=null) {
                         category = 'FORM FIELD ERRORS';
                         label = result.msg+' : '+$(el).val();
                     }

                    // if (window.console && window.console.log)  window.console.log('category:'+category+',action:'+action+',label:'+label);
                     _gaq.push(['_trackEvent',category, action, label]);
                     
                }


                this.setMassValidate = function(el)  //sets validation on the entire form
                {
                   
                    if(options.massValidate == true) {
                    var $this = this;
                    var errors = 0;
                    $(el).parents('form').unbind().submit(function(){
          
                        $(el).parents('form').find(':input').each(function(){
                            
                            if($(this).attr(options.rulesTag).match(/rules\?/)!=null && $(this).attr('class').match(/disabled/)==null) {
                            var error = $this.setRules(this,'submit');
                            if(!error) {
                                
                                errors++;
                            }
                            }
                        });

                        if($.isFunction(options.onSubmit)) return options.onSubmit(el,errors);
                        
                        if(errors>0) return false;
                        else
                            {
                                
                                return true;
                            }
                    });

                    //what about for ajax mass validate?
                    
                    $(el).parents('form').find('.submit').click(function(){
                   
                        $(el).parents('form').find(':input').each(function(){

                            if($(this).attr(options.rulesTag).match(/rules\?/)!=null && $(this).attr('class').match(/disabled/)==null) {
                            var error = $this.setRules(this,'submit');
                            if(!error) {

                                errors++;
                            }
                            }
                        });

                        if($.isFunction(options.onSubmit)) return options.onSubmit(el,errors);

                        if(errors>0) return false;
                        else
                            {

                                return true;
                            }
                    });


                    }
                }

                var fv = 0;

                
                        //Iterate over the current set of matched elements
    		return this.each(function() {
                    


                    if(fv == 0){
                        if(options.massValidate == true) func.setMassValidate(this);
                        fv++;
                    }

                   

                   if(!$(this).is(':input'))
                   {
                       //element is form, list item etc... the input is contained within
                       $(this).find(':input').each(function(){
                        func.validate(this);
                       })
                       
                   }
                   else
                   {
                       
                        func.validate(this);
                   }
				//code to be inserted here

    		});
    	}
	});


})(jQuery);

  

        

(function($){

    $.fn.autovalidateHelper = function(el,options) {
        $.fn.autovalidateHelper.results={};
        var $this = this;
        this.el = $(el);
        var main_options = $.extend({}, $.fn.inputUpdater.defaults, options);
        var options = $.meta ? $.extend({}, main_options, $this.data()) : main_options;
        return $.fn.autovalidateHelper.validate(el, options);

    }

    $.fn.autovalidateHelper.results = {};

    $.fn.autovalidateHelper.validate = function(el,options) { //decide which validations to use

           this.options = options;
           var rule = options.rule;

           var keyVal = rule.split('=');

           var key = keyVal[0];
           var value = keyVal[1];

           if(key=='present') $.fn.autovalidateHelper.isPresent(el);  //is there a value set
           if(key=='format') $.fn.autovalidateHelper.isFormat(el, value); //regular expression format
           if(key=='cvv') $.fn.autovalidateHelper.isCVV(el, value); //validate CC security code length
           if(key=='checked') $.fn.autovalidateHelper.isChecked(el); //is checkbox checked
           if(key=='match') $.fn.autovalidateHelper.isMatch(el, value); //do two fields match
           if(key=='email') $.fn.autovalidateHelper.isEmail(el); //is this an email address
           if(key=='state') $.fn.autovalidateHelper.isState(el); // is this a state (from array of states)
           if(key=='stateabbreviation') $.fn.autovalidateHelper.isStateAbbr(el); // is this a state 2 letter abbreviation
           if(key=='alpha') $.fn.autovalidateHelper.isAlpha(el); //is this letters only
           if(key=='numeric') $.fn.autovalidateHelper.isNumeric(el); //is this numbers only
           if(key=='alphanumeric') $.fn.autovalidateHelper.isAlphaNumeric(el); // letters and numbers, no punctuation
           if(key=='postal') $.fn.autovalidateHelper.isPostal(el); //a zip code
           if(key=='date') $.fn.autovalidateHelper.isDate(el); //is this a date (date.js required)
           if(key=='creditcarddate') $.fn.autovalidateHelper.isCreditcarddate(el); //is this a valid credit card date (future date - date.js required)
           if(key=='length') $.fn.autovalidateHelper.isLength(el,value); //does the character count match this length
           if(key=='maxlength') $.fn.autovalidateHelper.isMaxLength(el,value); //does the character count not exceed this length
           if(key=='minlength') $.fn.autovalidateHelper.isMinLength(el,value); //are there at least this many characters
           if(key=='ajax') $.fn.autovalidateHelper.isAjax(el,options); //pass data to an ajax action to set the result
           if(key=='custom') $.fn.autovalidateHelper.isCustom(el,options,value); //pass a callback function to set the result
           if(key=='chooseatleast') $.fn.autovalidateHelper.isChooseAtLeast(el,value); //for checkboxes - select X number of options
           if(key=='chooseatmost') $.fn.autovalidateHelper.isChooseAtMost(el,value); //checkboxes - select no more than X number of options
           if(key=='phone') $.fn.autovalidateHelper.isPhone(el); //checkboxes - select no more than X number of options
           if(key=='creditcard') $.fn.autovalidateHelper.isCreditcard(el); //checkboxes - select no more than X number of options

           if(options.msg!="" && $.fn.autovalidateHelper.results[key]!=undefined) $.fn.autovalidateHelper.results[key].msg = options.msg;
           return $.fn.autovalidateHelper.results;

        };

       

        $.fn.autovalidateHelper.isAjax = function(el,options)
        {
            var $this = this;
            var p = {};
            var name = $(el).attr('name');
            var value = $(el).val();
            p['name'] = value;

            $.ajax({
                type:'get',
                dataType:'json',
                data:p,
                url: options.ajaxURL,
                success: function(data){
                    $this.results[name] = data;
                },
                beforeSend: function(){
                    $(el).after('<div class="avLoading"></div>');
                },
                complete: function(){
                    $('.avLoading').remove();
                },
                error: function(){
                    $this.results[name] = {
                        success: false,
                        msg: 'There has been a problem processing this request.'
                    }
                }
            })


        }

        $.fn.autovalidateHelper.isCustom = function(el,options,value)
        {
            if($.isFunction(value)) return value(el,options)
        }

        $.fn.autovalidateHelper.isCVV = function(el,value)
        {
            if($(el).val().length >4 || $(el).val().length < 3 || $(el).val().match(/^\d*$/)==null || $(el).val().match(/^\d*$/)=="") {
                this.results['cvv'] = {
                    success:'false',
                    msg: 'Please enter the 3 or 4 digit security number from your credit card'
                }

            }
            else
            {
                 this.results['cvv'] = {
                    success:true
                }
            }
        }


        $.fn.autovalidateHelper.isChooseAtMost = function(el,value)
        {
            //assuming that checkbox is placed inside an li or td for formatting
            var parent = $(el).parent().parent();
            var count = 0;
            parent.find(':input').each(function(){
                if($(this).is(":checked")) count++;
            })


            if(count > value)
            {
               
                this.results['chooseatmost'] = {
                    success:false,
                    errorField: parent,
                    msg: 'Please choose no more than '+value+' selections'
                }
            }
            else
            {
                this.results['chooseatmost'] = {
                    success:true
                }
            }
        }

        $.fn.autovalidateHelper.isChooseAtLeast = function(el,value)
        {
            //assuming that checkbox is placed inside an li or td for formatting
            var parent = $(el).parent().parent();
            var count = 0;
            parent.find(':input').each(function(){
                if($(this).is(":checked")) count++;
            })


            if(count < value)
            {
                this.results['chooseatleast'] = {
                    success:false,
                    errorField: parent,
                    msg:'Please choose at least '+value+' selections'
                }
            }
            else
            {
                this.results['chooseatleast'] = {
                    success:true
                }
            }
        }

        $.fn.autovalidateHelper.isPresent = function(el)
        {
            
            if($(el).val()=='')
            {
                
                this.results['present'] = {
                    success:false,
                    msg:'This field is required'
                }
            }
            else
            {
                this.results['present'] = {
                    success:true
                }
            }
        }

        $.fn.autovalidateHelper.isEmail = function(el) { //make sure value is not empty
            
            if($(el).val().match(/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i)==-1 || $(el).val().match(/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i)==null){
                
                $.fn.autovalidateHelper.results['email '] = {
                    success:false,
                    msg:'Please enter a valid e-mail address'
                }
            }
             else
            {
                this.results['email'] = {
                    success:true
                }
            }
        };

        $.fn.autovalidateHelper.isStateAbbr = function(el) { //make sure value is not empty
           
            if($(el).val().match(/[a-z]{2}/i)==null){
                $.fn.autovalidateHelper.results['stateabbreviation'] = {
                    success:false,
                    msg:'Please enter a valid state abbreviation'
                }
            }
             else
            {
                this.results['stateabbreviation'] = {
                    success:true
                }
            }

        };


        $.fn.autovalidateHelper.isChecked = function(el) { //make sure checkbox is checked

            if(!$(el).is(":checked")){
                $.fn.autovalidateHelper.results['checked'] = {
                    success:false,
                    msg:'Please accept these terms to continue'
                }
            }
             else
            {
                this.results['checked'] = {
                    success:true
                }
            }

        };


        $.fn.autovalidateHelper.isMatch = function(el,matchElement) { //make sure checkbox is checked
            var $match = $("#"+matchElement);
            
            var elName = $(el).attr('id');
            var matchElementName = $match.attr('id');
            if($(el).val()!= $match.val()){
                 
                $.fn.autovalidateHelper.results['match'] = {
                    success:false,
                    msg:'The '+elName+' and '+matchElementName+' do not match.'
                }
            }
             else
            {
                this.results['match'] = {
                    success:true
                }
            }

        };


        $.fn.autovalidateHelper.isFormat = function(el,format) { //make sure value matches an included regexp format

            if($(el).val().match(format)==null){
                $.fn.autovalidateHelper.results['format'] = {
                    success:false,
                    msg:'Please enter the data in the proper format'
                }
            }
             else
            {
                this.results['format'] = {
                    success:true
                }
            }

        };

        $.fn.autovalidateHelper.isNumeric = function(el) { //make sure value is a digit
            if($(el).val().match(/^\d*$/)==null || $(el).val().match(/^\d*$/)==""){
              
                $.fn.autovalidateHelper.results['numberic'] = {
                    success:false,
                    msg:'Please enter numbers only'
                }
            }
             else
            {
                this.results['numeric'] = {
                    success:true
                }
            }

        };



         $.fn.autovalidateHelper.isPhone = function(el) { //make sure value is a valid postal code
            if($(el).val().match(/^(1\s*[-\/\.]?)?(\((\d{3})\)|(\d{3}))\s*[-\/\.]?\s*(\d{3})\s*[-\/\.]?\s*(\d{4})\s*(([xX]|[eE][xX][tT])\.?\s*(\d+))*$/) == null)   {
               
                $.fn.autovalidateHelper.results['phone'] = {
                    success:false,
                    msg:'Please enter a valid phone number'
                }
            }
             else
            {
                this.results['phone'] = {
                    success:true
                }
            }
        };



         $.fn.autovalidateHelper.isCreditcard = function(el) { //make sure value is a valid postal code
            if($(el).val().match(/ ^(\d{4}-){3}\d{4}$|^(\d{4} ){3}\d{4}$|^\d{16}$|^\d{15}$/) == null)   {
     
                $.fn.autovalidateHelper.results['creditcard'] = {
                    success:false,
                    msg:'Please enter a valid credit card number'
                }
            }
             else
            {
                this.results['creditcard'] = {
                    success:true
                }
            }
        };

        $.fn.autovalidateHelper.isPostal = function(el) { //make sure value is a valid postal code
            if($(el).val().match(/^(?!0{5})(\d{5})(?!-?0{4})(-?\d{4})?$/) == null)   {
                $.fn.autovalidateHelper.results['postal'] = {
                    success:false,
                    msg:'Please enter a valid zip code'
                }
            }
             else
            {
                this.results['postal'] = {
                    success:true
                }
            }
        };

        $.fn.autovalidateHelper.isAlpha = function(el) { //make sure value is a letter only

            if($(el).val().match(/[a-z][A-Z]/)==null) {
                $.fn.autovalidateHelper.results['alpha'] = {
                    success:false,
                    msg:'Please enter letters only'
                }
            }
             else
            {
                this.results['alpha'] = {
                    success:true
                }
            }
        };

        $.fn.autovalidateHelper.isAlphaNumeric = function(el) { //make sure value is a letter and/or number only (no punctuation)

            if($(el).val().match(/^[a-zA-Z0-9]*$/)==null) {
                $.fn.autovalidateHelper.results['alphanumeric'] = {
                    success:false,
                    msg:'Please enter letters and numbers only'
                }
            }
             else
            {
                this.results['alphanumeric'] = {
                    success:true
                }
            }
        };

        

        $.fn.autovalidateHelper.isDate = function(el) { //make sure value is a date
            //requires date.js
            var val = ""+$(el).val();
            if(Date.parse(val) == null) {
                $.fn.autovalidateHelper.results['date'] = {
                    success:false,
                    msg:'Please enter a valid date'
                }
            }
             else
            {
                this.results['date'] = {
                    success:true
                }
            }

        };


        $.fn.autovalidateHelper.isCreditcarddate = function(el) { //make sure value is a valid date for creditcard - date must be > today
            //requires date.js
            var val = $(el).val();
            var today = Date.today().set({day:1});
            var future = Date.parse(''+val);
            if(Date.today().set({day:1}).compareTo(future) < 1){
                this.results['creditcarddate'] = {
                    success:true
                }
            }
            else{
                $.fn.autovalidateHelper.results['creditcarddate'] = {
                    success:false,
                    msg:'Please enter a valid credit card date'
                }
            }

        };

        $.fn.autovalidateHelper.isLength = function(el,len) { //make sure value is a digit
            if($(el).val().length != len) {
                $.fn.autovalidateHelper.results['length'] = {
                    success:false,
                    msg:'This field must be '+len+' characters in length'
                }
            }
             else
            {
                this.results['length'] = {
                    success:true
                }
            }

        };

        $.fn.autovalidateHelper.isMaxLength = function(el,len) { //make sure value is a digit
          
          if($(el).val().length > len) {
            
                $.fn.autovalidateHelper.results['maxlength'] = {
                    success:false,
                    msg:'This field may not be more than '+len+' characters in length'
                }
            }
             else
            {
                this.results['maxlength'] = {
                    success:true
                }
            }

        };

        $.fn.autovalidateHelper.isMinLength = function(el,len) { //make sure value is a digit
            if($(el).val().length < len) {
                $.fn.autovalidateHelper.results['minlength'] = {
                    success:false,
                    msg:'This field must be at least '+len+' characters in length'
                }
            }
             else
            {
                this.results['minlength'] = {
                    success:true
                }
            }

        };

       

})(jQuery);

