
var isFormValid = true;
var orFieldsValid = true;

var error_state = function(el)
{
    iva = el.data('valArray');
    
    var errState = true;
    
    for (i in iva) {                
        if (!iva[i]) {
            errState = false;
            isFormValid = false;
            break;
        }
    }
    
    if (iva.val_mustmatch != null/* && !iva.val_mustmatch*/) {		
        var mmArray = get_mustmatch_fields(el);        
        elMM = mmArray[0];
        elCompare = mmArray[1];
        
        pecMM = elMM.parents('.error_container');
        pecCompare =  elCompare.parents('.error_container');
        
        pecMM.data('isValid',errState);
        error_toggle(pecMM);
        pecCompare.data('isValid',errState);
        error_toggle(pecCompare);
        
    } else {
        pec = el.parents('.error_container');	
        
        pec.data('isValid',errState);
        error_toggle(pec);
    }
    
    if (iva.val_required_tandc != null)
    {
        if (!iva.val_required_tandc) {
            Custom.errorOff(el[0].nextSibling);
        } else {
            Custom.error(el[0].nextSibling);
        }
    }
}

var error_toggle = function(pec) 
{    
    if (!pec.data('isValid')) {
        pec.addClass('error_on');
    } else {         
        pec.removeClass('error_on');
    } 

}

var get_mustmatch_fields = function(el)
{   
    mmClass = el.attr('className').match(/val_mustmatch_[a-zA-Z0-9]+/);
    
    strClass = new String(mmClass);
    mmGroup = strClass.replace(/val_mustmatch_/,'');
    
    mmCompareClass = 'val_compare_' + mmGroup;	
    
    mmArray = new Array();		
    mmArray.push($('*.' + mmClass));
    mmArray.push($('*.' + mmCompareClass));
    
    return mmArray;
}

var get_allrequired_fields = function(el)
{   
    arClass = el.attr('className').match(/val_allrequired_[a-zA-Z0-9]+/);
      
    arArray = new Array();		
    arArray = $('*.' + arClass);
    
    return arArray;
}

var get_ph_fields = function(el) 
{
    //return phArray;
}

var val_phone = function()
{
    lenClass = $(this).attr('className').match(/val_phone_[0-9]/);
    len = new String(lenClass);
    len = len.replace(/[^0-9]/g, '');
    
    var v = $(this).val();
    var isValid = (v.length == len && v.match(/^[0-9]+$/)) ? true : false;
    
    return isValid;
}

var validate_privpol_form = function(fid) 
{
    isFormValid = true;
    
    theForm = fid + "Form";

    $('#' + theForm + ' .error_container input.val_required:visible, ' +
        '#' + theForm + ' .error_container textarea.val_required:visible').each($(this).validate_field);

    if (!isFormValid) {
        $('#' + theForm + ' .error_msg').css('display','block');
        return false;
    } else {
        $('#' + theForm + ' .error_msg').css('display','none');
        return true;
    }
}

var phone_complete_submit = function() {
    if ($(this).parents('.error_on').length == 0) {
    
        //var phones = $('.phone_3:visible, .phone_4:visible').not('input[name="frm_c_phoneext"]');
        var phones = $('.phone_3:visible, .phone_4:visible').not('input.phone_ext');
        var phoneStarted = false;
        var phoneEmpty = false;
        var extStarted = false;
        
        //extVal = $('input[name="frm_c_phoneext"]').val();
        extVal = $('input.phone_ext').val();
        
        $(phones).each(function() {
            if ($(this).val() != '' && $(this).val() != null && $(this).val() != 'undefined') {
                phoneStarted = true;           
            }
            if (extVal != '' && extVal != null && extVal != 'undefined') {
                extStarted = true;           
            }
            if ($(this).val() == '' || $(this).val() == null || $(this).val() == 'undefined') {
               phoneEmpty = true;   
            } 
        });                               
        
        if(phoneStarted && phoneEmpty) {                    
            $('.phone_3').parents('.error_container_allvalid').addClass('error_on');
            return false;
        } else if(phoneEmpty && extStarted) {                    
            $('.phone_3').parents('.error_container_allvalid').addClass('error_on');
            return false;
        } else {
            $('.phone_3').parents('.error_container_allvalid').removeClass('error_on');
            return true;
        };       
    }
}

var validate_sharps_form = function()
{
    isFormValid = true;
    
    $('.error_container input[class*=val_]:visible, ' +  // added this one for non-required email inputs on Sharps form
        '.error_container input.val_required:visible, ' +
        '.error_container textarea.val_required:visible, ' +
        '.error_container select:visible, ' +
        '.error_container .radio:visible, ' +
        '.error_container .checkbox:visible').each($(this).validate_field);        

    $('.error_container_allvalid').each(function() {
        errKids = $(this).find('.error_on');
        if (errKids.length > 0) {
            $(this).addClass('error_on');
        } else {
            $(this).removeClass('error_on');
        }

        //alert('asdf');
    });

    var isPhoneValid = phone_complete_submit();    

    if (!isFormValid || !isPhoneValid) {
        $('.error_msg').css('display','block');
        /*$('#specialty_text').css('color','#EA3424');*/
        var os = $('.error_msg').offset();
        if (os.top > 0) $('html, body').animate({scrollTop:os.top}, 'slow');
        return false;
    } else {
        $('.error_msg').css('display','none');
        /*$('#specialty_text').css('color','#5C5959');*/
        return true;
    }	
}

var validate_form = function()
{
    isFormValid = true;
    
    $('.error_container input[class*=val_]:visible, ' + 
        '.error_container input.val_required:visible, ' +
        '.error_container textarea.val_required:visible, ' +
        '.error_container select:visible, ' +
        '.error_container .radio:visible, ' +
        '.error_container .checkbox:visible').each($(this).validate_field);        

    $('.error_container_allvalid').each(function() {
        errKids = $(this).find('.error_on');
        if (errKids.length > 0) {
            $(this).addClass('error_on');
        } else {
            $(this).removeClass('error_on');
        }    

    });

    var isPhoneValid = phone_complete_submit();    

    if (!isFormValid || !isPhoneValid) {
        $('.error_msg').css('display','block');
        /*$('#specialty_text').css('color','#EA3424');*/
        var os = $('.error_msg').offset();
        if (os.top > 0) $('html, body').animate({scrollTop:os.top}, 'slow');
        return false;
    } else {
        $('.error_msg').css('display','none');
        /*$('#specialty_text').css('color','#5C5959');*/
        return true;
    }	
}
var validate_popup_form = function()
{
    isFormValid = true;
    
    $('#email_page_popup .error_container input.val_required:visible').each($(this).validate_field);        
    
    if (!isFormValid) {
        $('#error_popup_msg').css('display','block');
        return false;
    } else {
        $('#error_popup_msg').css('display','none');
        return true;
    }	
}
var validate_schedulecall_form = function()
{
    isFormValid = true;
   
    $('#schedulecall_popper .error_container input:visible, ' +
        '#schedulecall_popper .error_container select:visible:not(:disabled), ' +
        '#schedulecall_popper .error_container .radio:visible').each($(this).validate_field); 
    

    $('.error_container_allvalid').each(function() {
        errKids = $(this).find('.error_on');
        if (errKids.length > 0) {
            $(this).addClass('error_on');
        } else {
            $(this).removeClass('error_on');
        }
    });
    
    if (!isFormValid) {
        //$('#error_sc_msg').css('display','block');
        return false;
    } else {
        //$('#error_sc_msg').css('display','none');
        return true;
    }	
}

var validate_activateBegin_form = function() {
    isFormValid = true;

    $('.activate_form .error_container input:visible').each($(this).validate_field);
    
    if (!isFormValid) {
        $('.activate_form:visible .act_error_msg').css('display','block');
        return false
    } else {
        $('.activate_form:visible .act_error_msg').css('display','none');
        return true;	
    }
}

var validate_renewBegin_form = function() {
    isFormValid = true;
    orFieldsValid = false;
    otherFieldsValid = false;
    
    $('.renew_form .error_container input:visible').not('.renew_form .val_onevalid_renew input').each($(this).validate_field);
    otherFieldsValid = isFormValid;
    //alert('otherFieldsValid = '+otherFieldsValid);

    $('.renew_form .val_onevalid_renew input:visible').each($(this).validate_field);
    
    $('.renew_form .error_container_allvalid:visible').each(function() {
        errKids = $(this).find('.error_on');
        if (errKids.length > 0) {
            $(this).addClass('error_on');
        } else {
            $(this).removeClass('error_on');
        }
    });    
    
    $('.renew_form .val_onevalid_renew:visible').each(function() {
        if (!$(this).hasClass('error_on')) {
            $('.val_onevalid_renew').find('.error_container').removeClass('error_on');
            $('.val_onevalid_renew').removeClass('error_on');
            orFieldsValid = true;
        }
    })  

    //alert('orFieldsValid = '+orFieldsValid);

    if (!otherFieldsValid || !orFieldsValid) {
        $('.renew_form:visible .ren_error_msg').css('display','block');
        return false
    } else {
        $('.renew_form:visible .ren_error_msg').css('display','none');
        return true;	
    }

}

var validate_replaceBegin_form = function() {
    isFormValid = true;
    orFieldsValid = false;
    otherFieldsValid = false;
    
    $('.replace_form .error_container input:visible').not('.replace_form .val_onevalid_replace input').each($(this).validate_field);
    otherFieldsValid = isFormValid;
    //alert('otherFieldsValid = '+otherFieldsValid);

    $('.replace_form .val_onevalid_replace input:visible').each($(this).validate_field);
    
    $('.replace_form .error_container_allvalid:visible').each(function() {
        errKids = $(this).find('.error_on');
        if (errKids.length > 0) {
            $(this).addClass('error_on');
        } else {
            $(this).removeClass('error_on');
        }
    });    
    
    $('.replace_form .val_onevalid_replace:visible').each(function() {
        if (!$(this).hasClass('error_on')) {
            $('.val_onevalid_replace').find('.error_container').removeClass('error_on');
            $('.val_onevalid_replace').removeClass('error_on');
            orFieldsValid = true;
        }
    })  

    //alert('orFieldsValid = '+orFieldsValid);

    if (!otherFieldsValid || !orFieldsValid) {
        $('.replace_form:visible .rep_error_msg').css('display','block');
        return false
    } else {
        $('.replace_form:visible .rep_error_msg').css('display','none');
        return true;	
    }
}

var val_findazip = function() 
{
    isFormValid = true;
    
    $('.error_container input.val_required:visible, ' +
        '.error_container select:visible, ' +
        '.error_container .radio:visible, ' +
        '.error_container .checkbox:visible').each($(this).validate_field);        
    
    if (!isFormValid) {
        $('#zip_error_msg').css('display','block');
        return false;
    } else {
        $('#zip_error_msg').css('display','none');
        return true;
    }	
}

var val_findaaddress = function() 
{
    isFormValid = true;
    
    $('.error_container input.val_required:visible, ' +
        '.error_container select:visible, ' +
        '.error_container .radio:visible, ' +
        '.error_container .checkbox:visible').each($(this).validate_field);        
    
    if (!isFormValid) {
        $('#address_error_msg').css('display','block');
        return false;
    } else {
        $('#address_error_msg').css('display','none');
        return true;
    }	
}

var val_onkeyup = function() 
{
    
}

var validate_init = function() 
{       
    jQuery.fn.val_checktc_required = function()
    {      
        //Custom.errorOff(this[0].nextSibling);
        var grpName = this[0].nextSibling.name;
        var grpChkLen = $("input[name='" + grpName + "']:checked").length;	
        var isValid = (grpChkLen==0) ? false : true; 	
        return isValid;	
    }
        
    jQuery.fn.val_radio_required = function()
    {      
        var grpName = this[0].nextSibling.name;
        var grpChkLen = $("input[name='" + grpName + "']:checked").length;	
        var isValid = (grpChkLen==0) ? false : true; 	
        return isValid;	
    }
    
        
    jQuery.fn.val_check_required = function()
    {      
        chkClass = $(this).next().attr('className').match(/val_checkgroup_[a-zA-Z0-9]+/);        
        
        var grpChkLen = $("input." + chkClass + ":checked").length;	
        //alert(grpChkLen);
        var isValid = (grpChkLen==0) ? false : true; 	
        return isValid;	
    }
    
    jQuery.fn.val_required = function()
    {      
        //alert($(this).val());
        var isValid = ($(this).val()=="" || $(this).val()=="--") ? false : true; 		
        return isValid;	
    }
    
    jQuery.fn.val_email = function() 
    {
        var isValid = ($(this).val().match(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/i) || $(this).val()=='') ? true : false;	// allows for blank entry (let val_required take care of that)	
        return isValid;
    }
    
    jQuery.fn.val_numeric = function() 
    {
        lenClass = $(this).attr('className').match(/val_numeric_[0-9]/);
        len = new String(lenClass);
        len = len.replace(/[^0-9]/g, '');
        
        var v = $(this).val();
        var isValid = (v.length == len && v.match(/^[0-9]+$/) || v=='') ? true : false;

        return isValid;
    }
    
    jQuery.fn.val_numeric_any = function() 
    {
        var isValid = ($(this).val().match(/^[0-9]+$/) || $(this).val()=='') ? true : false;    // allows field to be blank
        
        return isValid;
    }    

    jQuery.fn.val_max = function() 
    {
        maxClass = $(this).attr('className').match(/val_max_[0-9]+/);
        max = new String(maxClass);
        max = max.replace(/[^0-9]/g, '');
        
        var v = $(this).val();
        var isValid = (v <= max && v.match(/^[0-9]+$/)) ? true : false;
        
        return isValid;
    }


    jQuery.fn.val_min = function() 
    {
        minClass = $(this).attr('className').match(/val_min_[0-9]+/);
        min = new String(minClass);
        min = min.replace(/[^0-9]/g, '');
        
        var v = $(this).val();
        var isValid = (v >= min && v.match(/^[0-9]+$/)) ? true : false;
        
        return isValid;
    }
    
    jQuery.fn.val_mustmatch = function()
    {
        var mmArray = get_mustmatch_fields($(this));	
        
        var isValid = (mmArray[0].val() != mmArray[1].val()) ? false : true;		
        return isValid;
    }	
    
    jQuery.fn.val_allrequired = function()
    {
        var arArray = get_allrequired_fields($(this));	
        
        var isValid = true;
        
        for (i=1; i<arArray.length; i++) {
            if ($(arArray[i]).val() == "") {
                isValid = false;
                break;
            }
        }
		
        return isValid;
    }	    

    jQuery.fn.validate_field = function()
    {
    
        el = $(this);		
        obj = new Object();
        
        //if (el.hasClass('val_required')) {
            //if (el.next().hasClass('val_checkbox_tandc')) alert(el.next().attr('className'));
            
            if (el.next().hasClass('val_checkbox_tandc')) {
                obj['val_required_tandc'] = el.val_checktc_required();
            } else if (el.hasClass('radio')) {
                obj['val_required'] = el.val_radio_required();
            } else if (el.hasClass('checkbox')) {
                obj['val_required'] = el.val_check_required();
            } else if (el.hasClass('val_notrequired')) {       
                obj['val_notrequired'] = true;
            } else {
                obj['val_required'] = el.val_required();
            }
        //}
        
        if (el.hasClass('val_email')) {                 // checks for email format
            obj['val_email'] = el.val_email();
        }			
        
        if (el.attr('class').match(/val_numeric_[0-9]/)) {    // checks for numeric characters only and with a specified length (eg. val_numeric_5 for use zip code) 
            obj['val_numeric'] = el.val_numeric();
        }   
        
        if (el.hasClass('val_numeric_any')) {    // checks for numeric characters only 
            obj['val_numeric_any'] = el.val_numeric_any();
        }   
        
        if (el.attr('class').match(/val_mustmatch/)) {  // checks two fields that must match (eg. val_mustmatch_email is compared against val_compare_email)
            obj['val_mustmatch'] = el.val_mustmatch();
            obj['val_compare'] = obj['val_mustmatch'];
        }
        
        if (el.attr('class').match(/val_allrequired/)) { // checks that all fields with same class have all been filled out
            obj['val_allrequired'] = el.val_allrequired();
        }   

        if (el.attr('class').match(/val_max/)) {    // checks for numeric characters only and a value that is less than or equal to a maximum value
            obj['val_max'] = el.val_max();
        }  

        if (el.attr('class').match(/val_min/)) {    // checks for numeric characters only and a value that is greater than or equal to a minimum value 
            obj['val_min'] = el.val_min();
        }  
        
        el.data('valArray', obj);		
        error_state(el);		
    }
    
/*
    $('.error_container .val_required').keyup(function(e) {
        if (!$(this).attr('class').match(/val_mustmatch/) && !$(this).attr('class').match(/val_compare/)) { // prevents immediate comparison of inputs which must match
            if (e.keyCode != 9) $(this).validate_field();
        }
    });
*/
    $('.error_container .val_required').keyup(function(e) {
        if ($(this).parents('.error_container').hasClass('error_on')) {
            if (!$(this).attr('class').match(/val_mustmatch/) && !$(this).attr('class').match(/val_compare/)) { // prevents immediate comparison of inputs which must match
                if (e.keyCode != 9) $(this).validate_field();
            }
        }
    });    
    $('.error_container_allvalid .val_required').keyup(function(e) {        
        errKids = $(this).parents('.error_container_allvalid').find('.error_on');
        if (errKids.length > 0) {
            //if (e.keyCode != 9) $(this).parents('.error_container').addClass('error_on');
        } else {
            if (e.keyCode != 9) $(this).parents('.error_container').removeClass('error_on');
            if (e.keyCode != 9) $(this).parents('.error_container_allvalid').removeClass('error_on');
        }        
    });    

    
 //   $('.error_container .val_required').blur(
    $('.error_container input[class*=val_]').blur(
        $(this).validate_field
    );

    $('.error_container_allvalid .val_required').blur(function(e) {        
        errKids = $(this).parents('.error_container_allvalid').find('.error_on');
        if (errKids.length > 0) {
            //$(this).parents('.error_container').addClass('error_on');
        } else {
            $(this).parents('.error_container').removeClass('error_on');
            $(this).parents('.error_container_allvalid').removeClass('error_on');
        }        
    }); 
    
    
    $('.error_container select').change(
        $(this).validate_field
    );
      
    $('.error_container_allvalid select').change(function(e) {        
        errKids = $(this).parents('.error_container_allvalid').find('.error_on');
        if (errKids.length > 0) {
            $(this).parents('.error_container_allvalid').addClass('error_on');
        } else {
            $(this).parents('.error_container_allvalid').removeClass('error_on');
        }        
    });      
    
    $('.error_container select').not('.error_on select').blur(
        $(this).validate_field
    );
    
    $('.error_container .radio, .error_container .checkbox').click(function() {
        if (!$(this).next().attr('disabled')) {
            $(this).validate_field;
        }
    });

    $('input[name="frm_c_phone1"], input[name="frm_op_phone1"],'+
        'input[name="frm_c_phone2"], input[name="frm_op_phone2"],'+
        'input[name="frm_c_phone3"], input[name="frm_op_phone3"],').blur(function(e) { 
        //if ($(this).parents('.error_on').length == 0) {
        
            var phones = $('.phone_3:visible, .phone_4:visible').not('input.phone_ext');
            var phoneEmpty = false;
            
            $(phones).each(function() {
                if ($(this).val() == '' || $(this).val() == null || $(this).val() == 'undefined') {
                   phoneEmpty = true;   
                } 
            });                               
            
            if(phoneEmpty) {                    
                $(this).parents('.error_container_allvalid').removeClass('error_on');
            }        
        //}
    }); 

    $('input[name="frm_c_phone3"], input[name="frm_op_phone3"],').blur(function(e) { 
        //if ($(this).parents('.error_on').length == 0) {
        
            var phones = $('.phone_3:visible, .phone_4:visible').not('input.phone_ext');
            var phoneStarted = false;
            var phoneEmpty = false;
            
            $(phones).each(function() {
                if ($(this).val() != '' && $(this).val() != null && $(this).val() != 'undefined') {
                    phoneStarted = true;           
                }  
                if ($(this).val() == '' || $(this).val() == null || $(this).val() == 'undefined') {
                   phoneEmpty = true;   
                } 
            });                               
            
            if(phoneStarted && phoneEmpty) {                    
                $(this).parents('.error_container_allvalid').addClass('error_on');
            } else {
                $(this).parents('.error_container_allvalid').removeClass('error_on');
            }        
        //}
    });     
}

