var datetext;

var TimeFormat = '24Hrs';

function DateTime_Picker(ctl_DateTimePicker, _DateFormat, _disabled, TimeFormat1) {

    try {

        TimeFormat = TimeFormat1;

        // $(document).ready(function () {

        $.support.cors = true;

        // alert(ctl_DateTimePicker + ":" + DateFormat + ":" + _disabled);

        $('.txtDateTime').datepicker({

            // $("#" + ctl_DateTimePicker).datepicker({

            maxDate: 0, //By AniruddhaJ to disable future dates , changes done on 21-feb-19 for call log changes informed by kirtika.

            changeMonth: true,

            changeYear: true,

            showOn: "both",

            buttonImage: "../App_Resources/button.png",

            buttonImageOnly: true,

            dateFormat: 'dd-M-yy',

            showOtherMonths: true,

            selectOtherMonths: true,

            showButtonPanel: false,

            createButton: false,

            firstDay: 0,

            isRTL: false,

            stepMonths: 0,

            hideIfNoPrevNext: false,

            onSelect: function (datetext) {

                datetext = datetext;

                DateFormat = $(this).parent().find('input[type = "hidden"]').val();

                // DateFormat = $(this).parent().find('.txtDateFormat').val();

                // DateFormat = $(this).parent().find("#" + _DateFormat).val();

                if (DateFormat == "DATETIME") {

                    h = $(".selHours").val();

                    m = $(".selMinuts").val();

                    s = $(".selSecond").val();

                    if (TimeFormat == "24Hrs") {

                        h = (h > 23) ? (h - 23) : h;

                        datetext = datetext + " " + h + ":" + m + ":" + s;

                    }

                    else {

                        t = $(".selAMPM").val();

                        h = (h > 12) ? (h - 12) : h;

                        datetext = datetext + " " + h + ":" + m + ":" + s + " " + t;

                    }

                }

                else {

                    datetext = datetext;

                }

                $(this).val(datetext);

            },

            onClose: function (input, inst) {

                

                if (input == "") {
                   // var currDate = new Date();
                    var currDate = new Date();
                    lastDate.setDate(currDate.getDate());//any date you want
                    $(this).datepicker('setDate', lastDate);
                }
                DateFormat = $(this).parent().find('input[type="hidden"]').val();

                if (DateFormat == "DATETIME") {

                    $("#" + inst.id).val(getTime(input.toString().split(" ")[0]));

                }

            },

            dayNamesMin: ["S", "M", "T", "W", "T", "F", "S"],

            beforeShow: function (input, inst) {
                
                if (input == "") {
                    // var currDate = new Date();
                    var currDate = new Date();
                    lastDate.setDate(currDate.getDate());//any date you want
                    $(this).datepicker('setDate', lastDate);
                }
                 
                DateFormat = $(this).parent().find('input[type="hidden"]').val();

                if ($(this).attr('disabled') != 'undefined') {

                    var flag = $(this).attr('disabled');

                    if (flag == "disabled") {

                        $(this).datepicker('disable');

                    }

                    else {

                        $(this).datepicker('enable');

                    }

                }

                else {

                    $(this).datepicker('enable');

                }

                // DateFormat = $(this).parent().find('.txtDateFormat').val();

                // DateFormat = $(this).parent().find("#" + _DateFormat).val();

                if (DateFormat == "DATETIME") {

                    datetext = inst;

                    AddTimePicker(datetext);

                }

            },

            onChangeMonthYear: function (year, month, inst) {

                DateFormat = $(this).parent().find('input[type="hidden"]').val();

                // DateFormat = $(this).parent().find('.txtDateFormat').val();

                // DateFormat = $(this).parent().find("#" + _DateFormat).val();

                if (DateFormat == "DATETIME") {

                    AddTimePicker(datetext);

                    $(".ui-datepicker-trigger").attr("alt", "Select Date Time");

                }

                else {

                    $(".ui-datepicker-trigger").attr("alt", "Select Date");

                }

            }

        }).change(function (e) { AddTimePicker(datetext); })

        DisableDateTimePicker(ctl_DateTimePicker, _disabled)

        // });

        // if ($('.txtDateTime').css('display') == 'none') {

        $(".ui-datepicker-trigger").hide();

        //}

    } catch (er) {

        console.log(er);

    }

    //$(".ui-datepicker-trigger").prop("alt", "");

    $(".ui-datepicker-trigger img").remove();

    $(".ui-datepicker-trigger").prop("title", "Ctrl+Shift+w");

}

function DisableDateTimePicker(txtDateTime, _disabled) {

    try {

        $('.txtDateTime').each(function () {

            if ($(this).attr('disabled') != 'undefined') {

                var flag = $(this).attr('disabled');

                if (flag == 'disabled') {

                    $(this).datepicker('disable');

                }

                else {

                    $(this).datepicker('enable');

                }

            }

            else {

                $(this).datepicker('enable');

            }

        });

    } catch (er) {

        console.log(er);

    }

}





function getTime(datetext) {

    try {
        
        //TimeFormat ="24Hrs"
       // d = new Date();
        d= new Date();
        h = $(".selHours").val();

        m = $(".selMinuts").val();

        s = $(".selSecond").val();

        h = (h == "" || h == undefined) ? d.getHours() : h;

        m = (m == "" || m == undefined) ? d.getMinutes() : m;

        s = (s == "" || s == undefined) ? d.getSeconds() : s;

        // t=Number((t == ""||t == undefined) ? (h<12 ? "AM" : "PM") : t)
        
        if (TimeFormat == "24Hrs") { 
            h = (h > 23) ? (h - 23) : h; 
        } 
        else { 
            t = $(".selAMPM").val(); 
            h = (h > 12) ? (h - 12) : h; 
        }

        h = (h < 10) ? ("0" + Number(h)) : h; 
        m = (m < 10) ? ("0" + Number(m)) : m; 
        s = (s < 10) ? ("0" + Number(s)) : s; 
        //t = h < 12 ? "AM" : "PM"; 
        $(".selHours").val(h); 
        $(".selMinuts").val(m); 
        $(".selSecond").val(s); 
        // $(".selAMPM").val(t); 
         if (TimeFormat == "24Hrs") { 
            datetext = datetext.split(" ")[0] + " " + h + ":" + m + ":" + s; 
        } 
        else { 
            datetext = datetext.split(" ")[0] + " " + h + ":" + m + ":" + s + " " + t; 
        } 
        return datetext;

    }

    catch (error) { }

}



function AllowOnlyNumeric(event) {

    var key;

    try {

        var event = event || window.event;
        key = (event.which ? event.which : event.keyCode);
        e = event; 
        if ((key > 47 && key < 58) || (key == 8 || key == 46)) { 
            return true; 
        } 
        else { 
            event.returnValue = null; 
            return false; 
        } 
    } 
    catch (error) { 
    } 
    finally {
        key = "";
    } 
}

function validHours(txt, event) {
 
    if (event != undefined) {
        var event = event || window.event;
        key = (event.which ? event.which : event.keyCode);
        e = event;
         char = String.fromCharCode(key);
    }

    //var d = new Date();
    var d = new Date();
    h = Number((txt.value == "") ? d.getHours() : txt.value);
    if (TimeFormat == "24Hrs") {

        if (d.getDate() == datetext.selectedDay) {
            if (d.getMonth() == datetext.selectedMonth) {
                if (d.getFullYear() == datetext.selectedYear) {

                       
                    h = (h > d.getHours()) ? h.toString().replace(event.key, "") : h;

                }
            }
                
        }
        else {
            h = (h > 23) ? h.toString().replace(event.key, "") : h;
        }

            
       
    }

    else {  
        h = Number((h > 12) ? h.toString().replace(event.key, "") : h);
    } 
    txt.value = h;
    return true;
}
 


function ValidMints(txt, event) {
   
    if (event != undefined) {
        var event = event || window.event;
        key = (event.which ? event.which : event.keyCode);
        e = event;
        char = String.fromCharCode(key);
    }
   
   // var d = new Date();
    var d = new Date();
    m = Number((txt.value == "") ? d.getMinutes() : txt.value);

    if (d.getDate() == datetext.selectedDay) {
        if (d.getMonth() == datetext.selectedMonth) {
            if (d.getFullYear() == datetext.selectedYear) {

                       
                m = Number((m > d.getMinutes()) ? m.toString().replace(event.key, "") : m); 

            }
        }
                
    }
    else {
        m = Number((m > 59) ? m.toString().replace(event.key, "") : m); 
    }

            
       


        
         txt.value = m;
         return true;  
}



function ValidSec(txt, event) {
 
    if (event != undefined) {
        var event = event || window.event;
        key = (event.which ? event.which : event.keyCode);
        e = event;
        char = String.fromCharCode(key);
    }
  //  var d = new Date();
    var d = new Date();
    s = Number((txt.value == "") ? d.getSeconds() : txt.value);

    if (d.getDate() == datetext.selectedDay) {
        if (d.getMonth() == datetext.selectedMonth) {
            if (d.getFullYear() == datetext.selectedYear) {


                s = Number((s > d.getSeconds()) ? s.toString().replace(event.key, "") : s);

            }
        }

    }
    else {
        s = Number((s > 59) ? s.toString().replace(event.key, "") : s);
    }

   
    txt.value = s;
    return true;

}

function ValidAMPM(dttime) {

    if (dttime.value != 'AM' || dttime.value != 'PM') {

        //var d = new Date();
        var d = new Date();

        var h = d.getHours();

        t = h < 12 ? "AM" : "PM";

        dttime.value = t;

        return null;

    } else { return true; }

}

function validNumricOnly(txt, event) {
    var event = event || window.event;
    key = (event.which ? event.which : event.keyCode);
    e = event;
    if (((key > 47 && key < 58) || (key > 96 && key < 106)) || (key == 8 || key == 46) || (key >= 37 && key <= 40)) {
        return true;
    }
    else { return false; }

}



function AddTimePicker(datetext) {

    setTimeout(function () {

        //var d = new Date(); // for now
        var d = new Date();

        var h = d.getHours();

        if (TimeFormat == "24Hrs") { 
            h = (h > 23) ? (h - 23) : h; 
        } 
        else { 
            h = (h > 12) ? (h - 12) : h; 
        }

        t = h < 12 ? "AM" : "PM";

        h = (h < 10) ? ("0" + h) : h;

        var m = d.getMinutes();

        m = (m < 10) ? ("0" + m) : m;

        var s = d.getSeconds();

        s = (s < 10) ? ("0" + s) : s;

      
        var validatemin;
        var validatesec;

        var str = '<div class="ui-Timepicker">';

        str = str + '<input maxlength="2" onkeypress="return validNumricOnly(this, event);" onkeyup="return validHours(this, event);" class="selHours" value="' + h + '" data-rule="hour" />';

        str = str + '<span>:</span>';

        str = str + '<input maxlength="2" onkeypress="return validNumricOnly(this, event);"  onkeyup="return ValidMints(this, event);" class="selMinuts" value="' + m + '" />';

        str = str + '<span>:</span>';

        str = str + '<input maxlength="2" onkeypress="return validNumricOnly(this, event);" onkeyup="return ValidSec(this, event);" class="selSecond" value="' + s + '" />';

        if (TimeFormat == "24Hrs") {

            if (d.getDate() == datetext.selectedDay) {
                if (d.getMonth() == datetext.selectedMonth) {
                    if (d.getFullYear() == datetext.selectedYear) {

                       
                        hMax = d.getHours();
                        validatemin=d.getMinutes();
                        validatesec = d.getSeconds();

                    }
                }
                
            }
            else {
                hMax = 23;
                validatemin = 59;
                validatesec = 59;
            }

            
            hMin=0
        }

        else {

            hMax = 12;
            hMin = 1

            str = str + '<span>:</span>';

            str = str + '<input maxlength="2" onkeyup="return ValidAMPM(this);" class="selAMPM" value="' + t + '" />';

        }



        str = str + '</div>';

        $(".ui-datepicker .ui-datepicker-calendar").after(str);

        h = "";

        m = "";

        s = "";



        $(".selHours").spinner({
            step: 1,
            max: hMax,
            min: hMin,
            mouseWheel: true,
            increment: 'fast',
            numberFormat: "d2",
            allowNull: false,
            disabled: false,
            change: function () {
                h =Number($(this).spinner('value'));
                h = (Number(h) < 10) ? ("0" + h) : h;
                $(this).val(h); 
            }
        });





        $(".selMinuts").spinner({
            step: 1,
            max: validatemin,
            min: 0,
            mouseWheel: true,
            increment: 'fast',
            numberFormat: "d2",
            allowNull: false,
            disabled: false,
            change: function () {
                m = $(this).spinner('value');
                m = (m < 10) ? ("0" + m) : m;
                $(this).val(m);
             //  return ValidMints(this, event);
            }
        });

        $(".selSecond").spinner({
            step: 1,
            max: validatesec,
            min: 0,
            mouseWheel: true,
            increment: 'fast',
            numberFormat: "d2",
            allowNull: false,
            disabled: false,
            change: function () {
                s = $(this).spinner('value');
                s = (s < 10) ? ("0" + s) : s;
                $(this).val(s);
               // return ValidSec(this, event);
            }
        });

        var arrText = ["AM", "PM"];

        $(".selAMPM").textSpinner({
            values: arrText,
            spin: function (event, ui) {
                $("#spinner-value").text(ui.value);
            }
        }); 
    }, 100);

}







$.widget("ui.textSpinner", $.ui.spinner, {

    options: {

        wrap: false

    },

    _parse: function (value) {

        if ((value === '') || isNaN(value)) {

            value = this.options.values.indexOf(value);

            if (value === -1) {

                value = 0;

            }

        }

        if (value < 0) {

            value = this.options.wrap ? (this.options.values.length - 1) : 0;

        } else if (value >= this.options.values.length) {

            value = this.options.wrap ? 0 : (this.options.values.length - 1);

        }

        return value;

    },

    _format: function (value) {

        return this.options.values[value];

    },

    _adjustValue: function (value) {

        if (value < 0) {

            value = this.options.wrap ? (this.options.values.length - 1) : 0;

        } else if (value >= this.options.values.length) {

            value = this.options.wrap ? 0 : (this.options.values.length - 1);

        }

        return value;

    }

});

