﻿function message(element, success, show, newtext, newheader) {
    if (!element) {
        return false;
    } else {
        element = $(element);
    }

    element.hide();
    element.removeClass('error');
    element.removeClass('success');

    if (newtext && newheader) {
        element.find('.errorcontent').html('<h3>' + newheader + '</h3><p>' + newtext + '</p>');
    } else if (newtext && !newheader) {
        element.find('.errorcontent').html(newtext);
    }

    if (!show) {
        return false;
    }

    if (!success) {
        element.addClass('error');
    } else if (success == 1) {
        element.addClass('warning');
    } else if (success == 2) {
        element.addClass('info');
    } else if (success == 3) {
        element.addClass('success');
    } else {
        element.addClass('error');
    }

    element.find('.close').bind('click', function (event) {
        element.slideUp('slow');
        event.preventDefault();
    });

    element.fadeIn('slow');
}

function validation(testvalue, type, optional) {
    //returns true if valid
    var rege;
    if (!testvalue || testvalue == '' || undefined == testvalue || testvalue == -1) {
        if (!optional || undefined == optional || 'false' == optional) {
            return false;
        } else {
            return true;
        }
    }

    switch (type) {
        case 'email':
            //email address validation.
            rege = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum|xxx)$/i;
            break;
        case 'name':
            //rege = /^[a-z.-]{1,}$/i;
            rege = /^\s+$/i
            if (!rege.test(testvalue)) {
                rege = /^((\s{1})|([a-z.,-]+))+$/i;
            } else {
                rege = /^\S+$/i;
            }
            break;
        case 'tel':
            //dutch telnr: 16 digits starting with a zero.
            rege = /^0\d{16}$/i;
            break
        case 'initials':
            //Initials A.B. etc
            rege = /^([a-z][.]?\s?)+$/i;
            break;
        case 'cell':
            //dutch cellular number: 06xxxxxxxx
            rege = /^06\d{8}$/i;
            break;
        case 'date':
            //full date: DD-MM-YYYY or D-M-YYYY
            /^((0?[1-9]|[12][0-9]|3[01])[-](0?[1-9]|1[012])[-](?:19|20)\d{2})$/i;
            break;
        case 'dob':
            //full date: DD-MM-YYYY or D-M-YYYY
            rege = /^((0?[1-9]|[12][0-9]|3[01])[-](0?[1-9]|1[012])[-]19\d{2})$/i;
            break;
        case 'day':
            rege = /^(0?[1-9]|[12][0-9]|3[01])$/i;
            break;
        case 'month':
            rege = /^(0?[1-9]|1[012])$/i;
            break;
        case 'year':
            //19 or 20 with 2 digits following.
            rege = /^(?:19|20)\d{2}$/i;
            break;
        case 'dob_year':
            //19 with 2 digits
            rege = /^19\d{2}/i;
            break;
        case 'zip':
            //NL zipcode
            rege = /^\d{4}\s?[a-z]{2}$/i;
            break;
        case 'num':
            //nummeric only
            rege = /^\d+$/i;
            break;
        case 'CVV':
            //for use with credit card CVV validation code.
            rege = /^\d{3}$/i;
            break;
        case 'CCN':
            //for use with credit card number.
            rege = /^\d{16}$/i;
            break;
        case 'kvk':
            //KVK nummers valideren
            rege = /^\d{8}$/i;
            break;
        case 'ID':
            //for use with dutch ID
            rege = /^\w{8,12}$/i;
            break;
        case 'bankaccount':
            rege = /^\d+$/i;
            break;
        case 'password':
            rege = /^[a-zA-Z0-9]{8,}$/i;
            break;
        case 'none':
            return true;
            break;
        case 'select':
            rege = /^[^-].*$/i;
            break;
        case 'checkbox':
            rege = /^selected/gi;
            break;
        case 'iccid':
            rege = /^\d{8,20}$/i;
            break;
        case 'currency':
            rege = /^\d+[.,]?(\d{2})?$/gi;
            break;
        case 'nl_bankaccount':
            switch (testvalue.length) {
                case 9:
                case 10:
                    rege = /^\d{9,10}$/i;
                    return testvalue.ElfCheck() && rege.test(testvalue);
                    break;
                case 8:
                    return false;
                    break;
                default:
                    rege = /^\d{5,7}$/i;
                    break;
            }
            break;
        case 'multiline':
            rege = /^[^<>]+$/i;
            break;
        default:
            rege = /^([a-zA-Z0-9-_.]|\s)+$/i;
            break;
    }
    return rege.test(testvalue);
}

function ValidateThis(element) {
    $(element).each(function () {
        if (validation($(this).val(), $(this).data('validation'), $(this).data('optional'))) {
            Valid($(this));
        } else {
            inValid($(this));
        }
    });
}

function ValidateInitialize(element) {
    $(element).each(function () {
        var ele = $(this);
        if ($(this).is('input[type=checkbox]')) {
            ele = $(this).parent('span');
        }

        $(this).data('validation', ele.attr('data-validation'));
        $(this).data('optional', ele.attr('data-optional'));
        $(this).data('validationname', ele.attr('data-validationname'));
        $(this).bind('change', function () {
            ValidateThis($(this));
        });
        $(this).bind('keyup', function () {
            if (ele.is('.invalid')) {
                ValidateThis(ele);
            }
        });
        ele.removeAttr('data-validation');
        ele.removeAttr('data-optional');
        ele.removeAttr('data-validationname');
    });
}

function ValidateAll(element) {
    var counter = 0;
    var invalids = '';
    $(element).filter(':visible').each(function () {
        if ($(this).is('input[type=text], input[type=password], textarea') && (!$(this).val() == '' || $(this).filter('input[type=text], input[type=password], textarea').data('optional') == 'true')) {
            if (validation($(this).val(), $(this).data('validation'), $(this).data('optional'))) {
                counter++;
                Valid($(this));
            } else {
                inValid($(this));
                if (($(this).data('validation') == 'tel' || $(this).data('validation') == 'cell') && !$(this).data('optional') && $(this).val().length < 10) {
                    invalids += '<li> Een mobiel nummer dient uit 10 cijfers te bestaan.</li>';
                } else if ($(this).data('validation') == 'CCN' && !$(this).data('optional') && $(this).val().length < 13) {
                    invalids += '<li> Het creditcard nummer is niet correct.</li>';
                } else {
                    invalids += '<li>' + $(this).data('validationname') + '</li>';
                }
            }
        } else if ($(this).is(':checked') || ($(this).is(':checkbox') && $(this).data('optional') == 'true')) {
            counter++;
            Valid($(this));
        } else if (!$(this).is(':checked') && $(this).is(':checkbox') && $(this).data('optional') != 'true') {
            invalids += '<li>' + $(this).data('validationname') + ' is verplicht</li>';
            inValid($(this));
        } else if ($(this).is('select')) {
            if (validation($(this).find('option:selected').val(), $(this).data('validation'), $(this).data('optional')) || $(this).data('optional') == 'true') {
                counter++;
                Valid($(this));
            } else {
                invalids += '<li>' + $(this).data('validationname') + ' is verplicht</li>';
            }
        } else {
            invalids += '<li>' + $(this).data('validationname') + ' is verplicht</li>';
            inValid($(this));
        }
    });

    if (counter == $(element).filter(':visible').length) {
        return true;
    } //else
    return invalids;
}

function Valid(element) {
    $(element).addClass('valid').removeClass('invalid');
    $(element).closest('li, dt').addClass('valid').removeClass('invalid');
}
function inValid(element) {
    $(element).addClass('invalid').removeClass('valid');
    $(element).closest('li, dt').addClass('invalid').removeClass('valid');
}

function doValidateAll(checkelement, statusboxel) {
    var valid = ValidateAll(checkelement);
    if (valid === true) {
        return true;
    }
    //message(statusboxel, false, true, '<h3>Fout</h3><p>De volgende velden zijn niet goed ingevuld: </p><ul>' + valid + '</ul>');
    return false;
}

function validateRadio(element) {
    var total = [];
    var select = [];
    $(element).find('input[type=radio]').bind('change', function () {
        validateRadio(element);
    });
    $(element).find('input[type=radio]').filter(':visible').each(function () {
        total.push($(this).attr('name'));
    });
    $(element).find('input[type=radio]').filter(':visible').filter(':checked').each(function () {
        select.push($(this).attr('name'));
    });
    var diff = ArrayDiff(ArrayUnique(select), ArrayUnique(total));
    //var diff = select.unique().diff(total.unique());
    Valid($(element).find('input[type=radio]').parent());
    if (diff.length > 0) {
        var x = 0;
        if (true) {
            //$.browser.msie && $.browser.version < 9
            $('input[type=radio]').each(function (index, radiobtn) {
                if (!$(radiobtn).is('.' + $(radiobtn).attr('name').replace(/\W/gi, ''))) {
                    $(radiobtn).addClass($(radiobtn).attr('name').replace(/\W/gi, ''));
                }
            });
            while (x < diff.length) {
                inValid($('.' + diff[x].replace(/\W/gi, '') + '').parent());
                x++;
            }
        } else {
            while (x < diff.length) {
                inValid($('input[name=' + diff[x] + ']').parent());
                x++;
            }
        }
        return false;
    }
    return true;
}

function validateDate(element, year, modifier) {
    var yearyear = (year) ? year : 0;
    var today = new Date();
    var dates = true;

    $(element).each(function (ind, tr) {
        if ($(tr).find('input').length == 3) {
            var datetemp = '';
            $(tr).find('input').each(function (index, input) {
                datetemp += $(this).val();
            });
            var testdate = new Date(datetemp.substr(4, 4), datetemp.substr(2, 2), datetemp.substr(0, 2));
            today.setFullYear(today.getFullYear() + year);
            //alert(today);
            var tmp = (modifier == 'gte') ? today >= testdate : today <= testdate;

            if (tmp && testdate.isValid()) {
                dates = dates && true;
            } else {
                inValid($(tr).find('input'));
                dates = dates && false;
                if (year == 18 && modifier == 'gte') {
                    message($('#error'), false, true, 'Je bent nog geen 18 jaar oud.');
                } else if (year == 0 && modifier == 'lte') {
                    message($('#error'), false, true, 'Startdatum dient in de toekomst te liggen');
                }
            }
        }
    });
    return dates;
}
