var antenalvisit = function () {
    //global hosturl
    var hosturl = $('#hosturl').val();
    var patientid = $('#patientId').val();

    var antenalvisit_fun = function () {
        jQuery.fn.mybpmask = function () {
            return this.each(function () {
                $(this).keydown(function (e) {
                    var id = $(this).attr("data-id");
                    var colName = $(this).attr("data-colName");
                    var tableName = $(this).attr("data-tableName");
                    var key = e.which || e.keyCode;
                    if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
                            // numbers
                            key >= 48 && key <= 57 ||
                            // Numeric keypad
                            key >= 96 && key <= 105 ||
                            // comma, period and minus, . on keypad
                            //key == 190 || key == 188 || key == 109 || key == 110 ||
                            // Backspace and Tab and Enter
                            key == 8 || key == 9 || key == 13 ||
                            // Home and End
                            key == 35 || key == 36 ||
                            // left and right arrows
                            key == 37 || key == 39 ||
                            // Del and Ins
                            key == 46 || key == 45)
                    {
                        //alert($(this).val());
                        var field = $(this);
                        var prevValue = field.val();
                        setTimeout(function () {
                            var newvalue = field.val();
                            // check if new value is more or equal to 255
                            var res = newvalue.split("");
                            //alert(jQuery.type(res));

                            $slashIndex = res.indexOf("/");
                            if ($slashIndex == -1)//not exist
                            {
                                if (res.length > 3)
                                {
                                    //re arrange
                                    $temp3 = res[3];
                                    $temp4 = res[4];
                                    $temp5 = res[5];

                                    res[3] = '/';
                                    res[4] = $temp3;
                                    res[5] = $temp4;
                                    res[6] = $temp5;

                                    $newres = res.join("")
                                    field.val($newres);
                                }
                            } else if ($slashIndex != 3)
                            {
                                //remove it
                                res[$slashIndex] = '';
                                res = res.join("")
                                res = res.split("");

                                if (res.length > 3)
                                {
                                    //re arrange
                                    $temp3 = res[3];
                                    $temp4 = res[4];
                                    $temp5 = res[5];

                                    res[3] = '/';
                                    res[4] = $temp3;
                                    res[5] = $temp4;
                                    res[6] = $temp5;


                                }
                                $newres = res.join("")
                                field.val($newres);
                                //then put it in index 3
                            }
                            //field.val(newvalue+'/');




                            if (res.length > 7 && key != 46 && key != 8) {
                                // fill with previous value
                                field.val(prevValue);
                            }



                            var value = field.val();

                            //var value = $(this).val();
                            var controllName = $('#controllName').val();
                            var patientId = $('#patientId').val();

                            $.post(hosturl + '/controllers/' + controllName + '.php?ac=update', {id: id, value: value, tableName: tableName, colName: colName, patientId: patientId}, function (data)
                            {
                                $x = data;
                            });

                        }, 1);

                        return true;
                    }

                    return false;
                });
            });
        }

//        $(document).ready(function (e) {lmplmplmplmp
//            $(".bp_mask").mybpmask();
//
//        });

        $(".bp_mask").inputmask("999/999", {
            autoUnmask: true});

        $('#antenal_add').click(function () {
            var lmp = $('#lmp').val();
            if (lmp == "" || lmp == "0000-00-00")
            {
                alert('Please choose LMP date first.');
            } else
            {
                $.post(hosturl + '/controllers/antenalvisit.php?ac=newrow&id=' + patientid, function (data) {
                    $('#antenalvisit').prepend(data);

                    var check_heigt_and_make_new_class = $(".check_heigt_and_make_new_class").height();
                    if (check_heigt_and_make_new_class > 400) {
                        $(".check_heigt_and_make_new_class").addClass("overflow_scroll");
                    }

                });
            }


        });

        /*--------------------------- end perg modal -----------------------------*/
        $('#antenalvisit_add').click(function () {
            var patientId = $('#patientId').val();

            $.post(hosturl + '/controllers/antenalvisit.php?ac=endpreg', {patientid: patientid}, function (data) {

                if (data == -1)
                {
                    //$('#endpreg').attr('disabled', 'disabled');
                    alert('������ ������');
                } else
                {
                    window.location = hosturl + '/controllers/patienthistory.php?ac=show&patientid=' + patientId + '&endpreg=1#tab_2_6';
                }
            });

            //$("#endPregnancy_model").modal('show');
        });
        /* $('#endpreg').click(function () {
         if ($('#endPregH-form').validate().form()) {
         
         var obstrduration = $('#obstrduration').val();
         var obstermination = $('#obstermination').val();
         var obsplace = $('#obsplace').val();
         var obsdate = $('#obsdate').val();
         var obsnote = $('#obsnote').val();
         var patientId = $('#patientId').val();
         
         
         $.post(hosturl + '/controllers/antenalvisit.php?ac=endpreg', {obstrduration: obstrduration, obstermination: obstermination, obsplace: obsplace, obsdate: obsdate, obsnote: obsnote, patientid: patientid}, function (data) {
         
         if (data == -1)
         {
         $('#endpreg').attr('disabled', 'disabled');
         }
         else
         {
         window.location = hosturl + '/controllers/patienthistory.php?ac=show&patientid=' + patientId + '#tab_2_6';
         }
         });
         }
         
         
         });*/

        //--date------------------------------------------------------------------//
        /*$(document).ready(function () {
         
         $('.datepicker').datepicker({
         format: "yy/mm/dd",
         })
         //Listen for the change even on the input
         //.change(dateChanged)
         .on('changeDate', dateChanged);
         });*/

        //function dateChanged(ev) {
        $('body').on('change', '.datepicker', function ()
        {
            var value = $(this).val();//$(this).data('datepicker').getFormattedDate('yy/mm/dd');//choosen date
            var id = $(this).attr("data-id");
            var colName = $(this).attr("data-colName");
            var tableName = $(this).attr("data-tableName");
            //var value = $(this).val();
            var controllName = $('#controllName').val();
            var patientId = $('#patientId').val();
            var vdateFlag = $(this).hasClass('vdate');
            var usDateFlag = $(this).hasClass('usDate');
            if (colName == 'obsdate') {
                return false;
            }
            if (colName == "lmp" || colName == "eed" || vdateFlag == true || usDateFlag == true)
            {
                /*var tempvalue = value.split('/');
                 value = tempvalue[2] + '-' + tempvalue[1] + '-' + tempvalue[0];
                 alert(value);*/
                $.post(hosturl + '/controllers/' + controllName + '.php?ac=update', {id: id, value: value, tableName: tableName, colName: colName, patientId: patientId, vdateFlag: vdateFlag}, function (res)
                {
                    if (colName == "lmp" || colName == "eed")
                    {
                        res = res.split(",");
                        $('#eed').val(res[0]);
                        $('#ivf').val(res[1]);
                        $('#lmp').val(res[2]);

                        var lmp = $('#lmp').val();
                        var templmp = lmp.split('-');
                        lmp = templmp[2] + '-' + templmp[1] + '-' + templmp[0];
                        var firstDate = new Date(lmp);

                        $('.vdate').each(function () {
                            var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds

                            var thisval = $(this).val();
                            var tempthisval = thisval.split('-');
                            thisval = tempthisval[2] + '-' + tempthisval[1] + '-' + tempthisval[0];
                            var secondDate = new Date(thisval);

                            var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime()) / (oneDay)));
                            var diffInWeeks = Math.round(Math.abs(diffDays / 7));

                            $('label[data-id=' + $(this).attr('data-id') + ']').text(diffInWeeks);

                            if (secondDate < firstDate)
                            {
                                $('label[data-id=' + $(this).attr('data-id') + ']').css('color', 'red');
                                $('label[data-id=' + $(this).attr('data-id') + ']').css('font-weight', 'bold');
                            } else
                            {
                                $('label[data-id=' + $(this).attr('data-id') + ']').css('color', 'maroon');
                                $('label[data-id=' + $(this).attr('data-id') + ']').css('font-weight', 'bolder');
                            }

                        });

                        if (controllName == 'antenalvisit') {

                            $('.usDate').each(function () {
                                var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds

                                var thisval = $(this).val();
                                var tempthisval = thisval.split('-');
                                thisval = tempthisval[2] + '-' + tempthisval[1] + '-' + tempthisval[0];
                                var secondDate = new Date(thisval);

                                var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime()) / (oneDay)));
                                var diffInWeeks = Math.round(Math.abs(diffDays / 7));

                                $('#usLabel' + $(this).attr('data-id')).text(diffInWeeks);
                                //$('label[data-id=' + $(this).attr('data-id') + ']').text(diffInWeeks);

                                if (secondDate < firstDate)
                                {
                                    $('#usLabel' + $(this).attr('data-id')).css('color', 'red');
                                    $('#usLabel' + $(this).attr('data-id')).css('font-weight', 'bold');

//                                    $('label[data-id=' + $(this).attr('data-id') + ']').css('color', 'red');
//                                    $('label[data-id=' + $(this).attr('data-id') + ']').css('font-weight', 'bold');
                                } else
                                {
                                    $('#usLabel' + $(this).attr('data-id')).css('color', 'maroon');
                                    $('#usLabel' + $(this).attr('data-id')).css('font-weight', 'bolder');

//                                    $('label[data-id=' + $(this).attr('data-id') + ']').css('color', 'maroon');
//                                    $('label[data-id=' + $(this).attr('data-id') + ']').css('font-weight', 'bolder');
                                }

                            });
                        }
                    }

                    if (vdateFlag == true)
                    {
                        var lmp = $('#lmp').val();
                        var templmp = lmp.split('-');
                        lmp = templmp[2] + '-' + templmp[1] + '-' + templmp[0];
                        var firstDate = new Date(lmp);
                        var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
                        var secondDate = new Date(value);
                        var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime()) / (oneDay)));
                        var diffInWeeks = Math.round(Math.abs(diffDays / 7));
                        $('label[data-id=' + id + ']').text(diffInWeeks);

                        if (secondDate < firstDate)
                        {
                            $('label[data-id=' + id + ']').css('color', 'red');
                            $('label[data-id=' + id + ']').css('font-weight', 'bold');
                        } else
                        {
                            $('label[data-id=' + id + ']').css('color', 'maroon');
                            $('label[data-id=' + id + ']').css('font-weight', 'bolder');
                        }

                    }

                    if (usDateFlag == true)
                    {
                        var lmp = $('#lmp').val();
                        var templmp = lmp.split('-');
                        lmp = templmp[2] + '-' + templmp[1] + '-' + templmp[0];
                        var firstDate = new Date(lmp);
                        var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
                        var secondDate = new Date(value);
                        var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime()) / (oneDay)));
                        var diffInWeeks = Math.round(Math.abs(diffDays / 7));

                        if (controllName == 'antenalvisit') {
                            $('#usLabel' + id).text(diffInWeeks);

                            if (secondDate < firstDate)
                            {
                                $('#usLabel' + id).css('color', 'red');
                                $('#usLabel' + id).css('font-weight', 'bold');
                            } else
                            {
                                $('#usLabel' + id).css('color', 'maroon');
                                $('#usLabel' + id).css('font-weight', 'bolder');
                            }
                        }


                    }
                });
            }
        });

        ////////////////////////Diagnosis////////////////////////////////
        $iDsArray = $('#iDsArray').val();
        if ($iDsArray != '')
        {
            $iDsArray = $iDsArray.split(',');
            for ($i = 0; $i < $iDsArray.length; $i++)
            {
                diagnosis_itr = $iDsArray[$i];

                $('#diagnosis' + diagnosis_itr).select2({
                    width: '270px',
                    allowClear: true,
                    formatNoMatches: function (term) {
                        /* customize the no matches output */
                        $thisitr = $(this).attr('data-id');
                        // return '<input class="form-control" id="newregTerm' + $thisitr + '" value="' + term + '"><a href="#" id="addregnew' + $thisitr + '" data-itr="' + $thisitr + '" class="btn btn-default addnewselect">Add</a>';

                    }
                });
            }
        }
        //////////////// Diagnosis Multiple Select
        $('.updateDiagnosis').live('change', function ()
        {
            var id = $(this).attr("data-id");
            var colName = $(this).attr("data-colName");
            var tableName = $(this).attr("data-tableName");
            //var value = $(this).val();
            var controllName = $('#controllName').val();
            var patientId = $('#patientId').val();
            var dated = 0;

            var realvalues = new Array(); //storing the selected values inside an array
            var lastvalue;
            var slcttable;
            if (colName == "diagnosisid")
            {
                $('#diagnosis' + id + ' :selected').each(function (i, selected) {
                    realvalues[i] = $(selected).val();
                    lastvalue = $(selected).val();
                });
                slcttable = "diagnosisant";
            } else
            {
                $('#complaint' + id + ' :selected').each(function (i, selected) {
                    realvalues[i] = $(selected).val();
                    lastvalue = $(selected).val();
                });
                slcttable = "complaintant";
            }

            if (lastvalue == -2)
            {
                var selectId = $(this).attr('id');
                $("#" + selectId + " option[value='-2']").prop("selected", false);
                $("#" + selectId + "").select2();
                $.post(hosturl + '/controllers/' + controllName + '.php?ac=alldiagnosis', {colName: colName}, function (data)
                {
                    $("#alldatadiv").html(data);
                    $("#newitem_name").val("");
                    $("#newitem_id").val("");
                    $("#slctTbl").val(slcttable);
                    $("#edit_model").modal('show');
                    $("#edtSlct").attr("data-tableName", slcttable);
                    realvalues.pop();
                });
            }
            if ($.inArray("-1", realvalues) != -1)
            {
                var selectId = $(this).attr('id');
                $("#" + selectId + " option[value='-1']").prop("selected", false);
                $("#" + selectId + "").select2();
                $("#add_model").modal('show');
                realvalues.pop();
                $("#diagnosisName").val('');
                $("#diagnosisName").attr("data-select", selectId);
                $("#diagnosisName").attr("data-tablename", slcttable);
                $("#diagnosisName").attr("data-id", id);

            }
            if (lastvalue != '-1' && lastvalue != '-2' && $.inArray("-1", realvalues) == -1)
            {
                $.ajax({
                    url: hosturl + '/controllers/' + controllName + '.php?ac=update',
                    data: {
                        value: JSON.stringify(realvalues),
                        id: id,
                        tableName: tableName,
                        colName: colName,
                        patientId: patientId,
                        dated: dated
                    },
                    type: 'POST',
                    success: function (data) {

                    }
                });

            }
        });


        $(".addDiagnosisName").live('change', function () {
            var hosturl = $('#hosturl').val();
            var selectId = $(this).attr('data-select');
            var table = $(this).attr('data-tablename');
            var id = $(this).attr("data-id");
            var newitem = $(this).val();
            var select;

            $.post(hosturl + '/controllers/antenalvisit.php?ac=adddiagnosis', {diagnosisName: newitem, id: id, table: table}, function (data) {

                $('.' + table + ' > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + newitem + '</option>');
                $('#' + selectId + ' option[value="' + Number(data) + '"]').attr('selected', true);
                $("#" + selectId + "").select2();
                //$('#diagnosis' + $thisitr).select2('val', Number(data)); // select the new term
            });
        });

        $('body').on('click', '.delrow', function () {
            var itemid = $(this).attr('data-id');
            var urlgo = $(this).attr('data-link');
            var fngo = $(this).attr('data-fn');
            var tableName = $(this).attr('data-tableName');
            var tr = $(this).parent().parent();
            $.post(hosturl + '/controllers/' + urlgo + '.php?ac=' + fngo, {id: itemid, tableName: tableName}, function (res) {
                if (res == 1)
                {
                    tr.remove();
                    //$(".diagnosis option[value=" + itemid + "]").remove();
                    $("#newitem_name").val("");
                    $("#newitem_id").val("");
                    $('.updateDiagnosis').children('option[value = ' + itemid + ']').remove();
                    $('select').select2();

                } else
                {
                    alert("!!!!!!!!!!!!! some thing wrong here");
                }
            });
        });

        $("#addnewRow").live('click', function () {
            var tablename = $(this).attr('data-tableName');
            var selectname = $(this).attr('data-selectClass');
            var dtcount = $("#dtcount").val();
            dtcount++;
            $.post(hosturl + "/controllers/antenalvisit.php?ac=addNewRow", {tablename: tablename}, function (data) {

                var dataid = Number(data);
                $('.' + selectname + ' > .deleteoptincompo').before('<option value="' + dataid + '" ></option>');

                $("#dtAddTbl").prepend('<tr>\
                                            <td style="width: 100%">\
                                                <a href="#" >\
                                                    <input type="text" class="form-control updateElementSelect" data-selectClass="' + tablename + '"  data-select2="yes" data-id="' + dataid + '" data-colName="name" data-tableName="' + tablename + '" value=""/>\
                                                </a>\
                                            </td>\
                                            <td>\
                                                <a class="delrow fa fa-times btn red fleft" data-colName="conditions" data-link="antenalvisit" data-fn="deldiagnosis" data-tableName="' + tablename + '" data-id="' + dataid + '" ></a>\
                                            </td>\
                                        </tr>');
            });
            $("#dtcount").val(dtcount);
        });

        //------------------------------------------------------------------------//
        /*------------------------ select add ,edit ,del -------------------------*/
        //--------------add------------------//
        /*$("#obstermination").select2({
         width: '230px',
         allowClear: true,
         formatNoMatches: function (term) {
         return "<input class='form-control' id='newTerm_termination' value='" + term + "'><a href='#' id='addNew_termination' class='btn btn-default'>ADD</a>"
         }
         }).parent().find('.select2-with-searchbox').on('click', '#addNew_termination', function () {
         
         var jobname = $('#newTerm_termination').val();
         $.post(hosturl + '/controllers/antenalvisit.php?ac=addtermination', {name: jobname, inline: 1}, function (data) {
         
         $('#obstermination > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + jobname + '</option>');
         //$('<option value="' + Number(data) + '" >' + jobname + '</option>').appendTo('#obstermination');
         $('#obstermination').select2('val', Number(data)); // select the new term
         $("#obstermination").select2('close');       // close the dropdown
         
         });
         
         
         });
         $("#obsplace").select2({
         width: '230px',
         allowClear: true,
         formatNoMatches: function (term) {
         return "<input class='form-control' id='newTerm_place' value='" + term + "'><a href='#' id='addNew_place' class='btn btn-default'>ADD</a>"
         }
         }).parent().find('.select2-with-searchbox').on('click', '#addNew_place', function () {
         
         var jobname = $('#newTerm_place').val();
         $.post(hosturl + '/controllers/antenalvisit.php?ac=addplace', {name: jobname, inline: 1}, function (data) {
         
         $('#obsplace > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + jobname + '</option>');
         //$('<option value="' + Number(data) + '" >' + jobname + '</option>').appendTo('#obsplace');
         $('#obsplace').select2('val', Number(data)); // select the new term
         $("#obsplace").select2('close');       // close the dropdown
         
         });
         
         
         });
         
         //--------------edit------------------//
         $(".clikMe").live('click', function ()
         {
         var id = $(this).attr('data-id');
         var name = $(this).text();
         $("#newitem_name").val(name);
         $("#newitem_id").val(id);
         });
         
         
         $('.all').on('change', '.editme', function ()
         {
         var id = $(this).attr('id');
         
         var action = '';
         if (id == 'obstermination') {
         action = 'alltermination';
         }
         if (id == 'obsplace') {
         action = 'allplace';
         }
         var thisvalue = $(this).val();
         if (thisvalue == '-2' && action != '') {
         var dataClass = $(this).attr('data-class');
         $.post(hosturl + '/controllers/antenalvisit.php?ac=' + action, function (data) {
         $("#alldatadiv").html(data);
         $("#editmodel_submit").attr('data-action', action);
         $("#newitem_name").val("");
         $("#newitem_id").val("");
         $("#dataClass").val(dataClass);
         $("#edit_model").modal('show');
         });
         }
         });
         
         $("#editmodel_submit").live('click', function () {
         var value = $("#newitem_name").val();
         var id = $("#newitem_id").val();
         var oldAction = $(this).attr('data-action');
         var tableName = '';
         var selectid = '';
         if (oldAction == 'alltermination') {
         tableName = 'phobstericterminate';
         selectid = 'obstermination';
         }
         if (oldAction == 'allplace') {
         tableName = 'phobstericterplace';
         selectid = 'obsplace';
         }
         if (id > 0)
         {
         $.post(hosturl + '/controllers/antenalvisit.php?ac=update', {tableName: tableName, id: id, colName: 'name', value: value}, function (data) {
         $("#" + selectid + " option[value='" + id + "']").text(value);
         $("#" + selectid).select2('val', id);
         $('#edit_model').modal('hide');
         $("#newamount_id").val('');
         $("#newitem_name").val('');
         });
         }
         else
         {
         alert('choose element to edit first !');
         }
         });
         
         //--------------del------------------//
         
         $(".delrow").live('click', function () {
         var itemid = $(this).attr('data-id');
         var fngo = $(this).attr('data-fn');
         var tr = $(this).parent().parent();
         var selectid = '';
         if (fngo == 'deltermination') {
         selectid = 'obstermination';
         }
         if (fngo == 'delplace') {
         selectid = 'obsplace';
         }
         $.post(hosturl + '/controllers/antenalvisit.php?ac=' + fngo, {id: itemid}, function (res) {
         if (res == 1)
         {
         tr.remove();
         $("#" + selectid + " option[value=" + itemid + "]").remove();
         $("#newitem_name").val("");
         $("#newitem_id").val("");
         }
         else
         {
         alert("!!!!!!!!!!!!! some thing wrong here");
         }
         });
         });
         
         /*------------------------------------------------------------------------*/

        /*var deletemsg = function () {
         //to open model for accept del
         $('.deletemsg').click(function () {
         var itemid = $(this).attr('data-id');
         var urlgo = $(this).attr('data-link');
         bootbox.dialog({
         message: "Do you want to delete this item?",
         title: "Delete confirmation",
         buttons: {
         danger: {
         label: "Cancel",
         className: "btn-danger"
         },
         main: {
         label: "Delete",
         className: "btn-primary",
         callback: function () {
         //do something else
         window.location.href = hosturl + "/controllers/" + urlgo + ".php?ac=del&id=" + itemid;
         }
         }
         }
         }).find('.modal-content').addClass('modal-sm');
         });
         }*/






    }

    return {
        //main function to initiate the module
        init: function () {

            if ($('#controllName').val() == "antenalvisit")
            {
                antenalvisit_fun();
            }

        }

    };

}();