$(document).ready(function() {

    $.validator.addMethod(
        "birthday",
        function(value, element) {
            var check = false;
            var re = /^\d{2}\/\d{2}\/\d{4}$/;
            if( re.test(value)){
                var currentYear = (new Date).getFullYear();
                var adata = value.split('/');
                var gg = parseInt(adata[1],10);
                var mm = parseInt(adata[0],10);
                var aaaa = parseInt(adata[2],10);
                var xdata = new Date(aaaa,mm-1,gg);
                if ( ( xdata.getFullYear() == aaaa ) && ( xdata.getMonth () == mm - 1 ) && ( xdata.getDate() == gg ) && aaaa<currentYear-5)
                    check = true;
                else
                    check = false;
            } else
                check = false;
            return this.optional(element) || check;
        },
        "(mm/dd/yyyy)"
        );

    $.validator.addMethod(
        "dateITA",
        function(value, element) {
            var check = false;
            var re = /^\d{2}\/\d{2}\/\d{4}$/;
            if( re.test(value)){
                var currentYear = (new Date).getFullYear();
                var adata = value.split('/');
                var gg = parseInt(adata[1],10);
                var mm = parseInt(adata[0],10);
                var aaaa = parseInt(adata[2],10);
                var xdata = new Date(aaaa,mm-1,gg);
                if ( ( xdata.getFullYear() == aaaa ) && ( xdata.getMonth () == mm - 1 ) && ( xdata.getDate() == gg ))
                    check = true;
                else
                    check = false;
            } else
                check = false;
            return this.optional(element) || check;
        },
        "Please enter a valid date (mm/dd/yyyy)"
        );

    $.validator.addMethod("fullDate",function(value,element){
        return this.optional(element) || /^((((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|([1-2][0-9]))))[\-\/\s]?\d{2}(([02468][048])|([13579][26])))|(((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))[\-\/\s]?\d{2}(([02468][1235679])|([13579][01345789]))))(\s(((0?[1-9])|(1[0-2]))\:([0-5][0-9])((\s)|(\:([0-5][0-9])\s))([AM|PM|am|pm]{2,2})))?$/i.test(value);
    },"Must format date mm/dd/yyyy hh:mm:ss AM|PM");


    $.validator.addMethod("phoneUS", function(phone_number, element) {
        phone_number = phone_number.replace(/\s+/g, "");
        return this.optional(element) || phone_number.length > 9 &&
        phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
    }, "invalid phone");

    $.validator.addMethod("pswrdrule",function(value,element){
        return this.optional(element) || /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,16}$/i.test(value);
    },"Passwords are 8-16 characters with uppercase letters, lowercase letters and at least one number.");

    $.validator.addMethod("noemail",function(value,element){
        return this.optional(element) || value!="noemail@raceregister.net";
    },"Invalid email.");

    $.validator.addMethod( "proxy", function(value, element) {
        var val;
        var tsTimeStamp= new Date().getTime();
        $.ajax({
            type: "GET",
            async: false,
            url: "profile",
            data: "action=json&requestType=checkProxy&email="+value+"&ts="+tsTimeStamp,
            complete: handleResults
        });

        function handleResults(r){
            //alert(r.responseText);
            if(r.responseText=="false")
            {
                val =  false;
            }
            else
            {
                val =  true;
            }
        }

        return this.optional(element) || val;

    }, "You cannot register on behalf of this member.");

    $.validator.addMethod( "registered", function(value, element) {
        var val;
        var tsTimeStamp= new Date().getTime();
        $.ajax({
            type: "GET",
            async: false,
            url: "register",
            data: "action=validate&validationtype=email&email="+value+"&ts="+tsTimeStamp,
            complete: handleResults
        });

        function handleResults(r){
            //alert(r.responseText);
            if(r.responseText=="false")
            {
                val =  false;
            }
            else
            {
                val =  true;
            }
            if(value=="noemail@raceregister.net")
            {
                val = true;
            }
        }

        return this.optional(element) || val;

    }, "Registered User");

    $.validator.addMethod( "registered_email", function(value, element) {
        var val;
        var tsTimeStamp= new Date().getTime();
        $.ajax({
            type: "GET",
            async: false,
            url: "eventregister",
            data: "action=validate&validationtype=email&email="+value+"&ts="+tsTimeStamp,
            complete: handleResults
        });

        function handleResults(r){
            if(r.responseText=="false")
            {
                val =  false;
            }
            else
            {
                val =  true;
            }
            if(value=="noemail@raceregister.net")
            {
                val = true;
            }
        }
        return this.optional(element) || val;
    }, "In use");

    $.validator.addMethod("division", function(value, element) {
        var optionValues = [];
        var optionTexts = [];
        // iterate through all option elements
        $('gender').each(function() {
            // get value/text and push it into respective array
            optionValues.push($(this).val());
            optionTexts.push($(this).text());
        });
    }, "Please specify a valid phone number");
});

// function used to compare two dates
function daydiff(interval, date1,date2) {
    var second=1000, minute=second*60, hour=minute*60, day=hour*24, week=day*7;
    date1 = new Date(date1);
    date2 = new Date(date2);
    var timediff = date2 - date1;
    if (isNaN(timediff)) return NaN;
    switch (interval) {
        case "years":
            return date2.getFullYear() - date1.getFullYear();
        case "months":
            return (
                ( date2.getFullYear() * 12 + date2.getMonth() )
                -
                ( date1.getFullYear() * 12 + date1.getMonth() )
                );
        case "weeks"  :
            return Math.floor(timediff / week);
        case "days"   :
            return Math.floor(timediff / day);
        case "hours"  :
            return Math.floor(timediff / hour);
        case "minutes":
            return Math.floor(timediff / minute);
        case "seconds":
            return Math.floor(timediff / second);
        default:
            return undefined;
    }
}

// check to see if each age field in the form is at least the age defined in the division select
function checkDivisionAge(raceDate, minDivisionAge, maxDivisionAge){
    //alert("min: " + minDivisionAge + " max: " + maxDivisionAge);
    var ret = true;
    $('.birthday').each(function() {
        if($(this).val()=='')
        {
            ret = false;
        }
        var tmpDate = $(this).val();
        if(Math.abs(daydiff("years", raceDate, tmpDate))<minDivisionAge)
        {
            $.growlUI('Registration Error', 'Entrants must be at least ' + minDivisionAge + " years old.");
            ret = false;
        }
        if(Math.abs(daydiff("years", raceDate, tmpDate))>maxDivisionAge)
        {
            $.growlUI('Registration Error', 'Entrants cannot be older than ' + maxDivisionAge + ".");
            ret = false;
        }
    });
    return ret;
}

// check to see if the gender selection is valid for the division selection
function checkDivisionGender(divisionGender, maxEntrants){
    var optionValues = [];
    $('.gender').each(function() {
        optionValues.push($(this).val());
    });
    switch(maxEntrants)
    {
        case "1":
            optionValues = optionValues.splice(0,1);
            break;
        case "2":
            optionValues = optionValues.splice(0,2);
            break;
        case "3":
            optionValues = optionValues.splice(0,3);
            break;
        case "4":
            break;
        default:
    }
    // after we put each gender field into an array, parse according to division
    switch(divisionGender)
    {
        case "male":
            if($.inArray("female", optionValues) > -1)
            {
                $.growlUI('Registration Error', 'You cannot have any females in this division.');
                return false;
            }
            break;
        case "female":
            if($.inArray("male", optionValues) > -1)
            {
                $.growlUI('Registration Error', 'You cannot have any males in this division.');
                return false;
            }
            break;
        case "coed":
            if($.inArray("male", optionValues) == -1 || $.inArray("female", optionValues)== -1)
            {
                $.growlUI('Registration Error', 'You must have at least one female or one male in this division.');
                return false;
            }
            break;
        default:
    }
    return true;
}
