(function($) {
    
    var $activeElm = null;

    $.fn.selectTime = function(settings) {
        var config = {};

        if (settings) $.extend(config, settings);

        this.each(function() {
            $(this).css('z-index','999999');
            $(this).focus(function() {
                if($('.timePopup').is(':visible')) {
                    return true;
                }
                timePopup($(this));
                $(this).data('lastGoodValue',$(this).val());
            }).keydown(function() {
                timeClose(true);
            }).change(function() {
                var regTime = /^[0-1]?[0-9]:[0-5][0-9]\s(am|pm)$/gi;
                var input = $(this).val();
                var good = input.match(regTime);
                if(good !== null) {
                    $(this).data('lastGoodValue', input);
                } else {
                    $(this).val($(this).data('lastGoodValue'));
                }
            });;
        });

        return this;

    };


    var timePopup = function($elm) {

        $activeElm = $elm;

        if($('.timePopup').length == 0) {

            $('body').prepend('<div class="timeBlinder" style="z-index: 3000"></div><div class="timePopup"><div class="inner"></div></div>');

            var hoursLi = '';
            for(var i=1; i<=12; i++) {
                hoursLi += '<li><a href="#" rel="'+i+'">'+i+'</a></li>'
            }
            $('.timePopup .inner').append('<ul class="hours">'+hoursLi+'</ul>'); 
            $('.timePopup .inner').append('<ul class="ampm"><li><a href="#" rel="am">am</a></li><li><a href="#" rel="pm" style="margin-bottom: 0px !important">pm</a></li></ul>');

            $('.timePopup .hours a').click(function(){
                $('.timePopup .hours a').removeClass('active');
                $(this).addClass('active');
                if($('.timePopup .ampm .active').length) {
                    timeClose();
                }
                return false;
            });

            $('.timePopup .ampm a').click(function(){
                $('.timePopup .ampm a').removeClass('active');
                $(this).addClass('active');
                if($('.timePopup .hours .active').length) {
                    timeClose();
                }
                return false;
            });
        }

        $('.timePopup a').removeClass('active');


        if($elm.val() != '' && $elm.val() != $elm.attr('default')) {
            var date = $elm.val().split(' ');
            date[0] = date[0].split(':')[0];
            if(date[0] != '') {
                $('.timePopup .hours li a[rel='+date[0]+']').addClass('active');
            }   
            if(date[1] != '') {
                $('.timePopup .ampm li a[rel='+date[1]+']').addClass('active');
            }
        }

        $('.timeBlinder').height($(document).height()).show().click(function(){
            $elm.focus();
            timeClose();
        });

        var left = $elm.offset().left

            if(left + $('.timePopup').width() > $(window).width() - 20) {
                left = $(window).width() - $('.timePopup').outerWidth() - 20;        
            }

        $('.timePopup').css({top: $elm.offset().top+$elm.height(), left: left }).show();

        $elm.focus();

    }

    var timeClose = function(noChange) {
        if(!noChange) {
            noChange = false;
        }
        $time = $('.timePopup');

        var hours = $('.hours li a.active', $time).text();
        var ampm = $('.ampm li a.active', $time).text();
        if(noChange === false) {
            $activeElm.val(hours+':00 '+ampm);
        }

        $activeElm.removeClass('default');
        if(noChange === false) {
            $activeElm.change();
        }
        $('.timeBlinder').hide();
        $time.hide();
    }

})(jQuery);

