var parseTime = function (dt)
{
    colonPos = dt.search(':');

    var m = 0, h = 0, a = '';

    if (this._colonPos != -1) {
        h = parseInt(dt.substr(colonPos - 2, 2), 10);
        m = parseInt(dt.substr(colonPos + 1, 2), 10);
        a = jQuery.trim(dt.substr(colonPos + 3, 3));
    }

    a = a.toLowerCase();

    if (a != 'am' && a != 'pm') {
        a = '';
    }

    if (h < 0) h = 0;
    if (m < 0) m = 0;

    if (h > 23) h = 23;
    if (m > 59) m = 59;

    fh = h;

    if (a == 'pm' && h  < 12) h += 12;
    if (a == 'am' && h == 12) h  = 0;
    
    return {h: h, m: m, hp: fh, a: a};
}


$(document).ready(function(){
    $('#scheduleTime').datepicker({
    	duration: '',
        showTime: true,
        constrainInput: false,
        stepMinutes: 15,
        stepHours: 1,
        altTimeField: '',
        time24h: false,
        minDate : '+1',
        onClose : function(dateText, inst) {
            var timeObj = parseTime(dateText);
            var d = new Date();
            var t = new Date(d.getTime() + 24*60*60*1000);
            var curDate  = d.getFullYear()*10000+((d.getMonth()+1)*100)+d.getDate();
            var minDate  = t.getFullYear()*10000+((t.getMonth()+1)*100)+t.getDate();
            var selDate  = inst.selectedYear*10000+((inst.selectedMonth+1)*100)+inst.selectedDay;
            
            // User selected Tomorrow date.
            if (minDate >= selDate) {
                var curH = d.getHours()*60;
                var curM = d.getMinutes();
                var selH = timeObj.h*60;
                var selM = timeObj.m;
                if (curH+curM >= selH+selM) {
                    alert (
                        "Please call 979-680-8840 to schedule"+'\n'+
                        " testing with less than 24 hours notice"
                    );
                    $(this).val('');
                    return false;
                }
            }
        }
     });
    $('#scheduleTestingForm').validate({
        submitHandler : function(form){
            $(form).ajaxSubmit({
                dataType : 'json',
                success  : function(data) {
                    if (data) {
                        alert (data.message.replace('<br />', '\n'));
                    }
                }
            });
            return false;
        }
    });
});

