// Date fields in forms
//
// Andy Smith <andy@zambezi.org.uk>

/*
Copyright (c) 2010, Andy Smith
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of Andy Smith nor the names of its contributors may be used to endorse or promote products derived from this software
      without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
*/


//
// Date pickers
//

// Add date pickers to all <input> elements with class "date-picker". Other
// classes can be used in addition to "date-picker":
//
// date-picker-past: limit to dates in the past.
// date-picker-future: limit to dates in the future.
// date-range-XXX: treat this field as the start of a date range, where the
//   end is in the field with ID "XXX", which should also have the class
//   "date-picker". The end date field is constrained so dates earlier than
//   the start date cannot be selected.

if ((typeof $ != "undefined") && document.getElementById) {
    $(document).ready(function () {

        $("input.date-picker").each(function () {

                var limit_past = $(this).hasClass("date-picker-past");
                var limit_future = $(this).hasClass("date-picker-future") && !limit_past;

                $(this).datepicker({
                    dateFormat: "d/m/yy",
                    constrainInput: true,
                    minDate: limit_future ? 0 : null,
                    maxDate: limit_past ? 0 : null,
                    yearRange: "-10:+10",
                    showOn: "button",
                    buttonImage: "/admin/imgs/calendar.gif",
                    buttonText: "Choose",
                    buttonImageOnly: true
                  });

            });

        // Set up date ranges (in a separate pass so the end field already has
        // its date picker).

        $("input.date-picker").each(function () {

            var range_re = /(?:^|\s)date-range-(\S+)(?:$|\s)/;
            var range_match = range_re.exec(this.className);
            if (range_match) {
                var start_field = this;
                var end_field = document.getElementById(range_match[1]);
                if (end_field) {
                    var end_limit_past = $(end_field).hasClass("date-picker-past");
                    var end_limit_future = $(end_field).hasClass("date-picker-future") && !end_limit_past;

                    var min_end_date = new Date();

                    var updateLimits = function () {
                        var start_date = $(start_field).datepicker("getDate");
                        if (start_field.value != "") {
                            $(start_field).datepicker("setDate", start_date);
                        }

                        min_end_date = start_date || (end_limit_future ? 0 : null);
                        $(end_field).datepicker("change", { "minDate": min_end_date });

                        var end_date = $(end_field).datepicker("getDate");
                        if (end_date && (end_date < min_end_date)) {
                            $(end_field).datepicker("setDate", min_end_date);
                        }
                    };

                    $(start_field).bind("change", updateLimits);
                    $(end_field).bind("change", function () {
                        if (this.value != "") {
                            var end_date = $(this).datepicker("getDate");
                            if ((end_date == null) || (end_date < min_end_date)) {
                                end_date = min_end_date;
                            }
                            $(this).datepicker("setDate", end_date);
                        }
                    });

                    if (start_field.value && (start_field.value != "")) {
                        updateLimits();
                    }
                }
            }

        });

    });
}



//
// Validation
//

// The validation method 'dateDMY' checks for valid dates in dd/mm/yyyy
// format. The year must be four digits. Out-of-range dates (eg 32/1/2010) are
// rejected.

if ((typeof jQuery != "undefined") && jQuery.validator) {
    jQuery.validator.addMethod("dateDMY", function (value, element) {
        if (this.optional(element)) return true;
        var re = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
        var match = re.exec(value);
        if (match) {
            // Check whether date is in range by using it to build a Date
            // instance and checking whether it matches the input.
            // Out-of-range dates may result in an 'invalid date' object or an
            // adjusted date (eg 32/1/2010 -> 1/2/2010); either way, the
            // result will not match the input.
            var day = parseInt(match[1], 10);
            var month = parseInt(match[2], 10) - 1;
            var year = parseInt(match[3], 10);
            var date = new Date(year, month, day);
            if (date && date.getDate && date.getMonth && date.getFullYear) {
                return ((day == date.getDate()) && (month == date.getMonth())
                        && (year == date.getFullYear()));
            } else {
                return false;
            }
        } else {
            return false;
        }
    }, "Please enter a date in dd/mm/yyyy format.");
}

// Validation error placement function for use with forms containing date
// pickers. If a field has a date picker button, place validation error
// messages after the button, otherwise place errors directly after the
// <input> element. Should be passed as the 'errorPlacement' setting to the
// 'validate' function, eg:
//
//     $("#form").validate({
//         errorPlacement: datePickerValidatorErrorPlacement
//       });
//
// Without this function, validation errors for fields with date pickers will
// appear between the field and the date picker button.

datePickerValidatorErrorPlacement = function (error, element) {
    if (element.next().hasClass("ui-datepicker-trigger")) {
        element.next().after(error);
    } else {
        element.after(error);
    }
}

