﻿/* Custon validation rules

Use following code as example (return true or false)

jQuery.validator.addMethod("zipcode", function(zipcode, element) {
	return this.optional(element) || zipcode.match(/(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXYabceghjklmnpstvxy]{1}\d{1}[A-Za-z]{1} ?\d{1}[A-Za-z]{1}\d{1})$/);
}, "Please specify a valid zip code");
*/

var hadError = false; // this is to store a value that says we HAD an error, but overrode it.  used on goal page to determine when to show goal msg

(function () {

    function _validateAustralianDate(value) {
        return value.match(/^\d{2}\/\d{2}\/\d{4}$/);
    }

    function _getDate(element) {
        var inputDate,
            selects = $(element).parents('.date-selector:first').find('select'),
            month = selects.eq(0).val(),
            day = selects.eq(1).val(),
            year = selects.eq(2).val();
        if (!month || !day || !year) {
            return null;
        }
        else {
            var date = Date.parse([year, month, day].join('-'));
            if (null === date) {
                return NaN;
            }
            else {
                return date;
            }
        }
        // $('select.BirthDate').removeClass('error').addClass('valid');
        // $('.date-selector').prev().prev('span.error').remove();
    }

    function _validateDate(element, callback) {
        var date = _getDate(element),
            others = $(element).siblings('select'),
            i,
            valid;

        if (null === date) {
            return true;
        }

        if (typeof callback === "function") {
            valid = callback(date);
        }

        method = valid ? 'unhighlight' : 'highlight';
        for (i = others.length - 1; i > -1; i--) {

            if (this.settings[method]) {
                this.settings[method].call(this, others[i], this.settings.errorClass, this.settings.validClass);
                if (valid) {
                    $('span.error[for=' + others[i].id + ']').remove();
                }
            }
        }
        return valid;
    }



    jQuery.validator.addMethod(
        "threeFieldBirthDay",
        function (value, element) {
            // validation logic for three field birthday at registration step 2

            return _validateDate.call(this, element, function (date) {
                return !isNaN(date) && date <= new Date().addYears(-18);
            });
        },
        "Sorry! You need to be at least 18 to start a plan."
    );

    jQuery.validator.addMethod(
        "validDate",
        function (value, element) {

            return _validateDate.call(this, element, function (date) {
                return !isNaN(date);
            });
        },
        "Please select a birth date that is a valid date."
    );


    jQuery.validator.addMethod("heightRange", function (value, element) {
        var minInch = 4 * 12 + 5,
            maxInch = 6 * 12 + 5,
            value = parseInt(value, 10), // foot value just entered
            inchVal = $('input[name="height2"]').val(),
            inch = inchVal === "" ? 0 : parseInt( inchVal, 10);
        if (!isNaN(value) && (value * 12 + inch ) < maxInch && (value * 12+ inch) > minInch) {
            $("#height2-h").removeClass("error").addClass("valid");
            return true;
        } else {
            return false;
        }
    },  "Sorry! Based on the information you entered, we don't recommend this meal plan. Ask your physician for the best weight management plan for you." /*"Sorry! Our plans aren't designed for anyone under 4.5 ft or over 6.5 ft. Ask your physician for the best weight management plan for you."*/);

    jQuery.validator.addMethod("heightRangeIn", function (value, element) {
        var minInch = 4 * 12 + 5,
            maxInch = 6 * 12 + 5,
            ftVal = $('input[name="height1"]').val(),
            ft = ftVal === "" ? 0 : parseInt(ftVal, 10),
            value = parseInt(value, 10); // inch value just entered
        if (!isNaN(value) && (ft * 12 + value) < maxInch && (ft * 12+ value) > minInch) {
            $("#height1-h").removeClass("error").addClass("valid");
             if ( $(".height-error em.error:visible").length ) { $(".height-error em.error").hide(); }
            return true;
        } else {
            return false;
        }
    }, "Sorry! Based on the information you entered, we don't recommend this meal plan. Ask your physician for the best weight management plan for you." /*"Sorry! Our plans aren't designed for anyone under 4.5 ft or over 6.5 ft. Ask your physician for the best weight management plan for you."*/);

    jQuery.validator.addMethod(
    "australianDate",
    function (value, element) {
        return _validateAustralianDate(value) && Date.parse(value);
    },
    "Please enter the date in this format: 01/01/2012"
    );

    jQuery.validator.addMethod(
    "birthday",
    function (value, element) {
        inputDate = Date.parse(value);
        if (_validateAustralianDate(value) && inputDate) {
            return this.optional(element) || inputDate <= new Date().addYears(-18);
        } else {
            return true; 
        }
    },
    "Sorry! We don't recommend this plan for anyone younger than 18."
    );

    jQuery.validator.addMethod(
    "bmiok",
    function (value, element) {
        var weight = parseInt($('input[name="weight"]').val(), 10),
            feet = parseFloat($('input[name="height1"]').val(), 10),
            inches = parseInt($('input[name="height2"]').val(), 10);

        if (weight && !isNaN(weight) && feet && !isNaN(feet) && !isNaN(inches)) {
            inches = feet * 12 + inches;
            if (((weight * 703) / (inches * inches)) > 20.5) {
                return true;
            }
            else {
                $("#reponseBox").slideUp();
                return false;
            }
        }
        return true;
    },
    "Sorry! Based on the information you entered, we don't recommend this meal plan. Ask your physician for the best weight management plan for you.");

    jQuery.validator.addMethod(
    "resultBmiok",
    function (value, element) {
        var weight = parseInt($('input[name="weight"]').val()),
            feet = parseFloat($('input[name="height1"]').val()),
            inches = parseInt($('input[name="height2"]').val());

        var tolose = parseInt($('input[name="tolose"]').val());

        if (weight && !isNaN(weight) && feet && !isNaN(feet) && !isNaN(inches)) {
            var goalWeight = weight - tolose;
            inches = feet * 12 + inches;
            if (((goalWeight * 703) / (inches * inches)) > 20.5) {
                return true;
            }
            else {
                var toLoseProper = weight - (20.5 * (inches * inches) / 703);
                
                // check which is more 10% or 20.5
                var toLoseProperTen = weight * .10;
                if (toLoseProperTen < toLoseProper) toLoseProper = toLoseProperTen;

                var toLoseDate = Date.today().addDays(Math.floor(toLoseProper / 2 * 7)).toString('MM/dd/yyyy');
                /*commented*/
                //$('input[name="tolose"]').val(Math.floor(toLoseProper));

                $('#responseBox').html("<p>The goal you entered will result in a BMI of less than 20.5, something that isn’t recommended as part of this Special K Plan™.  " +
                "We think you can try losing up to " + Math.floor(toLoseProper) + " lbs before " + toLoseDate + ".</p>").slideDown();

                // NOT A TYPO - true

                hadError = true;

                return true;
            }
        }
    },
    ""
    );

    jQuery.validator.addMethod(
    "resultBmiokEvent",
    function (value, element) {
        var weight = parseInt($('input[name="weight"]').val()),
            feet = parseFloat($('input[name="height1"]').val()),
            inches = parseInt($('input[name="height2"]').val());

        var tolose = (Date.parse($('input[name="eventdate"]').val()) - Date.today().getTime()) / 1000 / 60 /60 / 24 * 2 / 7;

        if (weight && !isNaN(weight) && feet && !isNaN(feet) && !isNaN(inches) && !isNaN(tolose)) {

            var goalWeight = weight - tolose;
            inches = feet * 12 + inches;
            if (((goalWeight * 703) / (inches * inches)) > 20.5) {
                return true;
            }
            else {
                var toLoseProper = _toloseResultBmiok = weight - (20.5 * (inches * inches) / 703);
                
                // check which is more 10% or 20.5
                var toLoseProperTen = weight * .10;
                if (toLoseProperTen < toLoseProper) toLoseProper = toLoseProperTen;

                var toLoseProperDate = Date.today().addDays(Math.floor(toLoseProper / 2 * 7)).toString('MM/dd/yyyy');

                $('#responseBox').html("<p>The date you entered will result in a BMI of less than 20.5, something that isn’t recommended as part of this Special K Plan™. " +
                                       "We think you can try losing up to " + Math.floor(toLoseProper) + " lbs before " + toLoseProperDate + ".</p>").slideDown();

                $('input[name="eventdate"]').val(toLoseProperDate);

                hadError = true;

                return true;
            }
        }
        return true;
    },
    ""
    );

    jQuery.validator.addMethod(
    "callevel",
    function (value, element) {
        var g = $('input[name="gender"]').val();
        var w = parseInt($('input[name="weight"]').val()) * 0.45359237;
        var birthDate = new Date($('input[name="birthday"]').val());
        var mainreason = parseInt($('input[name="mainreason"]').val());
        var todaysDate = new Date();
        var yrs = 365 * 24 * 60 * 60 * 1000;
        var bmr, cal, pal;
        var pals = new Array('1.4', '1.6', '1.8');
        var pal = pals[parseInt($('input[name="activitylevel"]').val()) - 1];

        if (g == "man") {

            if (todaysDate.getTime() - birthDate.getTime() <= 30 * yrs) { // 30
                bmr = 15.1 * w + 692;
            }
            else if (todaysDate.getTime() - birthDate.getTime() <= 60 * yrs) { // 60
                bmr = 11.5 * w + 873;
            }
            else if (todaysDate.getTime() - birthDate.getTime() <= 75 * yrs) { // 75
                bmr = 11.9 * w + 700;
            }
            else {
                bmr = 8.4 * w + 821;
            }
        }
        else {
            if (todaysDate.getTime() - birthDate.getTime() <= 30 * yrs) { // 30
                bmr = 14.8 * w + 487;
            }
            else if (todaysDate.getTime() - birthDate.getTime() <= 60 * yrs) { // 60
                bmr = 8.3 * w + 846;
            }
            else if (todaysDate.getTime() - birthDate.getTime() <= 75 * yrs) { // 75
                bmr = 9.2 * w + 687;
            }
            else {
                bmr = 9.8 * w + 624;
            }
        }

        cal = (mainreason == 4) ? (bmr * pal) : (bmr * pal) - 600;
        if (isNaN(cal) || (cal < 2800)) {
            return true;
        }
        else {
            $("#responseBox").slideUp();
            $("#sendForm").addClass("inactive");
            return false;
        }
    },
    "Sorry! Based on the information you entered, we don't recommend this meal plan. Ask your physician for the best weight management plan for you."
);

    jQuery.validator.addMethod(
    "greaterThanFour",
    function (value, element) {
        if (value >= 4) {
            return true;
        }
        else {
            $('#responseBox').html("<p>This program was designed for healthy weight management plan of at least 14 days in length. We think you can try losing up to 4 lbs before " +
            Date.today().addDays(15).toString('MM/dd/yyyy') + ".</p>").slideDown();

            //$(element).val(4);

            hadError = true;

            return true;
        }
    },
    ""
);

    jQuery.validator.addMethod(
    "infuture",
    function (value, element) {
        return this.optional(element) || (Date.parse(value) > Date.today());
    },
    "The event date must be in the future."
    );

    jQuery.validator.addMethod(
    "justayear",
    function (value, element) {
        return this.optional(element) || (Date.parse(value) < Date.today().addYears(1));
    },
    "It's great you're planning so far ahead. We think you can try losing up to 16lbs by 00/00/0000. After that, we may recommend that you switch to a weight."
    );

    jQuery.validator.addMethod(
    "over14days",
    function (value, element) {
        if (Date.parse(value) > Date.today().addDays(14)) {
            return true;
        }
        else {
            $('#responseBox').html("<p>This program was designed for healthy weight management plan of at least 14 days in length. We think you can try losing up to 4 lbs before " +
            Date.today().addDays(15).toString('MM/dd/yyyy') + ".</p>").slideDown();

            //$(element).val(Date.today().addDays(15).toString('MM/dd/yyyy'));

            hadError = true;

            return true;
        }
    },
    ""
);

    jQuery.validator.addMethod("commaemails",
    function (value, element) {

        if(value[value.length - 1] == ",") value = value.slice(0, -1);

        var emails = value.split(",");
        var totalCount = emails.length;
        var ok = true;
        var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

        for (i = 0; i < totalCount; i++) {
            if (!re.test(trimMe(emails[i])))
                ok = false;
        }
        return this.optional(element) || ok;
    }, jQuery.format("Please enter the correct value "));

    jQuery.validator.addMethod(
    "notMinusThanTenEvent",
    function (value, element) {
 
        var dateString = $('input[name="eventdate"]').val();
        if (dateString != '')
        {
            var theDate = new Date(dateString);
            var current = parseInt($('input[name="weight"]').val()),
                            plpw = 2, // pound loss per week
                            t = Date.today(),
            //var days = Date.compare(t, ed);
                            tdoy = t.getDayOfYear(),
                            edoy = theDate.getDayOfYear(),
                            wtl,
                            daysDiff,
                            pct;
            if (edoy > tdoy) {
                daysDiff = edoy - tdoy - 1;
            }
            else {
                daysDiff = 365 - tdoy + edoy - 1;
            }
            var wtl = daysDiff * 2 / 7;

            if (!isNaN(current)) {
                var pct = wtl / current * 100;
                
                if (pct < 10) {
             
                    return true;
                }
                else {
                    var w = Math.floor(current / 10);
                    var days = Math.floor(w / 2 * 7);
                    var toLoseProperDate = Date.today().addDays(days).toString('MM/dd/yyyy');

                    $('#responseBox').html("<p>Since your event is a ways away, we suggest shorter-term goals to make sure you don't lose more weight than recommended. We think you can try losing up to " + w + " lbs " + 
                    "before " + toLoseProperDate + ". After that, you can update and continue your plan based on your new weight.</p>").slideDown();

                    $('input[name="eventdate"]').val(toLoseProperDate);

                    hadError = true;

                    return true;
                }
            }
        }

        return true;
    },
    ""
);

    jQuery.validator.addMethod(
    "notMinusThanTen",
    function (value, element) {
        var w = parseInt($('#weight-h').val());
        var tolose = parseInt($('input[name="tolose"]').val());

        w = w * 10 / 100;
  
        if (!isNaN(tolose) && !isNaN(w)) {
            if (tolose <= w) {
                return true;
            }
            else {
                var days = Math.floor(w / 2 * 7);

                $('#responseBox').html("<p>The goal you entered could result in you losing more than 10% of your current weight, " +
                "something that isn’t recommended as part of this Special K Plan™. We think you can try losing up to " + Math.floor(w) + " lbs " + 
                "before " + Date.today().addDays(days).toString('MM/dd/yyyy') + ". After that, you can update and continue your plan based on your new weight.</p>").slideDown();
                /*alert("commented");*/
                //$('input[name="tolose"]').val(Math.floor(w));

                hadError = true;

                return true;
            }
        }
        return true;
    },
    ""
    );


    jQuery.validator.addMethod(
    "notMinus",
    function (value, element) {
        if (value > 0) {
            return true;
        }
        else {
            $('#responseBox').slideUp();
            return false;
        }
    },
    "Your goal weight must be less than your current weight"
    );

    /*jQuery.validator.addMethod("profanityCheck", function(value, element) {
    return checkProfanity(element);
    }, "Hmm...That language won\'t be tolerated here.");*/


    jQuery.validator.addMethod("emailcountlimit", function (emails, element) {
        if (emails.split(",").length > 10) {
            return false;
        } else {
            return true;
        }
    }, "You can only send 10 invites at a time. Remove some to send.");

})();
