/* jQuery timeslider
 * Shows a slider for selecting a time
 *
 * Copyright (c) 2009 Alex Barrett (spleenboy.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Usage:
 * $('input.time').timeslider({ hide: true|false, step: 30 });
 * @hide indicates whether the slider is hidden when it is initialized
 * @step indicates the number of minutes between steps in the slider
 */

jQuery.fn.timeslider = function(options) {
    var o = $.extend({
		className: '',
        hide: true,
        step: 15 // minutes
    }, options);
    var max = 24 * 60;

    // Gets the number of minutes from 0 - 1440 based on the time from midnight
    var getMinutesFromTime = function(time) {
        try {
            var date = new Date('1/1/2000 ' + time);
            return (date.getHours() * 60) + date.getMinutes();
        } catch (e) {
            return 0;
        }
    };

    // Gets the time from the number of minutes
    var getTimeFromMinutes = function(minutes) {
        var hours = Math.floor(minutes / 60);
        var minutes = minutes % 60;
        var ampm = hours > 11 ? " pm" : " am";
        if (minutes < 10) minutes = "0" + minutes;
        if (hours == 0 || hours == 24) {
            ampm = " am";
            hours = 12;
        } else if (hours > 12) {
            hours = hours - 12;
        }
        return hours + ":" + minutes + ampm;
    };

    var round = function(i) {
        return Math.round(i / o.step) * o.step;
    };

    return this.each(function() {
        var textbox = $(this);
        var current = round(getMinutesFromTime(textbox.val()));
        textbox.val(getTimeFromMinutes(current));

        var sliding = function(e, ui) {
            var time = getTimeFromMinutes(ui.value);
            textbox.val(time);
        };

        var slider = $('<div class="timeslider" />').slider({
            step: o.step,
            max: 24 * 60,
            value: current,
            animate: true,
            slide: sliding
        });
		
		if (o.className != null && o.className.length > 0) {
			slider.addClass(o.className);
		}

        slider.insertAfter(textbox);
        if (o.hide) {
            slider.hide();
            textbox.focus(function() { slider.show(); });
            $(document).mousedown(function(event) {
                var target = $(event.target);
                if (slider.is(':visible') && target.parents('.timeslider').length == 0) {
                    slider.hide();
                }
            });
        }
    });
};