﻿var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;
$(document).ready(function()
    {
    $(".time").blur(function()
        {
        var time = $(this).val();
        var hour = null;
        var minutes = null;
        var second = null;
        var ampm = null;


        if (time != null && time != "")
        {
            if (time.indexOf(":") == -1)
            {
                var ampmArray = time.match("(AM|am|PM|pm)");
                if (ampmArray != null)
                {
                    ampm = ampmArray[0];
                }
                var timeNumber = parseInt(time, 10).toString();

                if (time.substring(0, 1) == "0")
                {

                }
                if (timeNumber.length < 3)
                {
                    hour = timeNumber;
                    minutes = "00";
                }
                else
                {
                    hour = timeNumber.substring(0, timeNumber.length - 2);
                    minutes = timeNumber.substring(timeNumber.length - 2, timeNumber.length);
                }
            }
            else
            {
                var matchArray = time.match(timePat);
                if (matchArray == null)
                {
                    alert("Time is not in a valid format.");
                    $(this).val("");
                    $(this).focus();
                    return false;
                }
                hour = matchArray[1];
                minutes = matchArray[2];
                second = matchArray[4];
                ampm = matchArray[6];
            }
            if (second == "") { second = null; }
            if (ampm == "") { ampm = null; }
            if (hour > 12)
            {
                alert("Hour must be between 1 and 12.");
                $(this).val("");
                $(this).focus();
                return false;
            }
            if (ampm == null)
            {
                alert("You must specify AM or PM.");
                $(this).setCursorPosition($(this).val().length, $(this).val().length);
                return false;
            }
            if (minutes < 0 || minutes > 59)
            {
                alert("Minute must be between 0 and 59.");
                $(this).val("");
                $(this).focus();
                return false;
            }
            minutes = (Math.round(minutes / 15) * 15) % 60;
            minutes = minutes == 0 ? "00" : minutes.toString();
            var ctrlName = $(this).attr("name");
            var prefix = ctrlName.substring(0, ctrlName.indexOf("-"));
            var currentTime = hour.toString() + ":" + minutes + " " + ampm.toUpperCase();
            $(this).val(currentTime);
            if (ValidateInOut($(this)))
            {
                var dailyHours = TotalDailyHours(prefix);
                if (parseInt(dailyHours) < 0)
                {
                    alert("Total for days hours can not be less than zero.");
                    $(this).val("");
                    $(this).focus();
                    return false;
                }
                $("input[name=" + prefix + "-total]").val(dailyHours);
                TotalTimesheet();
            }
        }
        return false;
    });
    function ValidateInOut(jqueryCtrl)
    {
        var ctrlName = jqueryCtrl.attr("name");
        var prefix = ctrlName.substring(0, ctrlName.indexOf("-"));
        var partnerControl = null;
        var isJqueryCtrlOut = false;
        if (ctrlName.indexOf("lunchout") != -1)
        {
            partnerControl = $("input[name=" + prefix + "-lunchin]");
            isJqueryCtrlOut = true;
        }
        else if (ctrlName.indexOf("lunchin") != -1)
        {
            partnerControl = $("input[name=" + prefix + "-lunchout]");
        }
        else if (ctrlName.indexOf("timein") != -1)
        {
            partnerControl = $("input[name=" + prefix + "-timeout]");
        }
        else if (ctrlName.indexOf("timeout") != -1)
        {
            isJqueryCtrlOut = true;
            partnerControl = $("input[name=" + prefix + "-timein]");
        }
        if (jqueryCtrl.val() == "" || partnerControl.val() == "")
        {
            return true;
        }
        else
        {
            var inSeconds = 0;
            var outSeconds = 0;
            if (isJqueryCtrlOut)
            {
                inSeconds = GetSecounds(partnerControl.val().match(timePat));
                outSeconds = GetSecounds(jqueryCtrl.val().match(timePat));
            }
            else
            {
                outSeconds = GetSecounds(partnerControl.val().match(timePat));
                inSeconds = GetSecounds(jqueryCtrl.val().match(timePat));
            }
            if (outSeconds < inSeconds)
            {
                alert("Out time must be greater than In time.");
                jqueryCtrl.val("");
                jqueryCtrl.focus();
                return false;
            }
        }
        return true;
    }
    function TotalTimesheet()
    {
        var timesheetTotalSeconds = 0;
        $("input[name$='total']").each(function()
            {
            if ($(this).val() != "")
            {
                timesheetTotalSeconds += GetSecounds($(this).val().match(timePat));
            }
        });
        if (timesheetTotalSeconds > 0)
        {
            if (timesheetTotalSeconds >= 144000)
            {
                $("input[name=regular-hours]").val("40:00");
                $("input[name=overtime-hours]").val(CreateTimeFromSeconds(timesheetTotalSeconds - 144000));
            }
            else
            {
                $("input[name=regular-hours]").val(CreateTimeFromSeconds(timesheetTotalSeconds));
            }
        }
    }
    function TotalDailyHours(prefix)
    {
        var hoursWorked = null;
        var timeForLunch = null;
        var timeIn = $("input[name=" + prefix + "-timein]").val();
        var timeOut = $("input[name=" + prefix + "-timeout]").val();
        var lunchIn = $("input[name=" + prefix + "-lunchin]").val();
        var lunchOut = $("input[name=" + prefix + "-lunchout]").val();
        if (timeIn != "" && timeOut != "")
        {
            hoursWorked = TimeDiffernce(timeIn, timeOut);
        }
        if (lunchIn != "" && lunchOut != "")
        {
            timeForLunch = TimeDiffernce(lunchIn, lunchOut);
        }
        if (hoursWorked != null && timeForLunch == null)
        {
            return hoursWorked;
        }
        if (hoursWorked != null && timeForLunch != null)
        {
            return TimeDiffernce(timeForLunch, hoursWorked);
        }
        return "";
    }
    function TimeDiffernce(startTime, endTime)
    {
        var timePart = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/ ;
        var startTimeSeconds = GetSecounds(startTime.match(timePart));
        var endTimeSeconds = GetSecounds(endTime.match(timePart));
        var timeDifferenceSeconds = endTimeSeconds - startTimeSeconds;
        return CreateTimeFromSeconds(timeDifferenceSeconds);
    }
    function CreateTimeFromSeconds(seconds)
    {
        var minutes = parseInt(seconds / 60);
        var hours = parseInt(minutes / 60);

        var remainingMinutes = minutes % 60;
        remainingMinutes = remainingMinutes == 0 ? "00" : remainingMinutes;
        return hours + ":" + remainingMinutes;
    }
    function GetSecounds(time)
    {
        var seconds;
        if (time[6] == "AM" && time[1] == 12)
        {
            time[1] = 0;
        }
        if (time[6] == "PM" && time[1] != 12)
        {
            seconds = (((parseInt(time[1]) + 12) * 60 * 60) + (parseInt(time[2]) * 60));
        }
        else
        {
            seconds = ((parseInt(time[1]) * 60 * 60) + (parseInt(time[2]) * 60));
        }
        return seconds;
    }
    $.fn.setCursorPosition = function(pos)
    {
        this.each(function(index, elem)
            {
            if (elem.setSelectionRange)
            {
                elem.setSelectionRange(pos, pos);
            } else if (elem.createTextRange)
            {
                var range = elem.createTextRange();
                range.collapse(true);
                range.moveEnd('character', pos);
                range.moveStart('character', pos);
                range.select();
            }
        });
        return this;
    };
});

