

var TableEditable = function () {

    var forAll = function ()
    {
        jQuery.fn.forcepositiveNum = function () {

            return this.each(function () {
                $(this).keydown(function (e) {
                    var key = e.which || e.keyCode;
                    //alert(key);
                    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)
                        return true;

                    return false;
                });
            });
        }

        jQuery.fn.forcepositivefloat = function () {

            return this.each(function () {
                $(this).keydown(function (e) {
                    var key = e.which || e.keyCode;
                    //alert(key);
                    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 ||
                            //dot or point  .  on keyboard  for one time
                                    (key == 110 && $(this).val().indexOf(".") < 0) ||
                                    // Del and Ins
                                    key == 46 || key == 45)
                        return true;

                    return false;
                });
            });
        }


        $(document).ready(function (e)
        {
            $(".positiveNo").forcepositiveNum();
            $(".positivefloat").forcepositivefloat();
        });
    };



    var handleTable = function () {
        var hosturl = $("#hosturl").val();

        var getdata = function () {
            //happened in load the plugins
            //load all datalist
            var searchtxt = '';
            //name
            var listidn = 'namemedcine';
            $.post(hosturl + '/controllers/drugs.php?ac=getthisserach', {listid: listidn, searchtxt: searchtxt}, function (data) {
                $('#' + listidn).html(data);
                //cat
                var listidc = 'groupmedcine';
                $.post(hosturl + '/controllers/drugs.php?ac=getthisserach', {listid: listidc, searchtxt: searchtxt}, function (data) {
                    $('#' + listidc).html(data);
                    //dos
                    var listidu = 'usemedcine';
                    $.post(hosturl + '/controllers/drugs.php?ac=getthisserach', {listid: listidu, searchtxt: searchtxt}, function (data) {
                        $('#' + listidu).html(data);
                        //type
                        var listidf = 'frommedcine';
                        $.post(hosturl + '/controllers/drugs.php?ac=getthisserach', {listid: listidf, searchtxt: searchtxt}, function (data) {
                            $('#' + listidf).html(data);
                        });
                    });

                });

            });



        };



        function restoreRow(oTable, nRow) {
            var aData = oTable.fnGetData(nRow);
            var jqTds = $('>td', nRow);
            for (var i = 0, iLen = jqTds.length; i < iLen; i++) {
                oTable.fnUpdate(aData[i], nRow, i, false);
            }

            // oTable.fnDraw();
        }

        function editRow(oTable, nRow) {
            var aData = oTable.fnGetData(nRow);

            var jqTds = $('>td', nRow);
            jqTds[0].innerHTML = '<input type="text"  class="form-control input-small " value="' + aData[0] + '" disabled="disabled">';

            jqTds[0].innerHTML = '<input type="text"   class="form-control input-small " value="' + aData[0] + '" disabled="disabled">';
            jqTds[1].innerHTML = '<input type="text"  list="groupmedcine" id="drugcat"  class="form-control input-small testautocom getallwidth" value="' + aData[1] + '"><datalist id="groupmedcine"></datalist> ';
            jqTds[2].innerHTML = '<input type="text" list="namemedcine"  id="drugname"  class="form-control input-small testautocom getallwidth" value="' + aData[2] + '"><datalist id="namemedcine"></datalist> ';
            jqTds[3].innerHTML = '<input type="text" list="frommedcine" id="drugtype"  class="form-control input-small testautocom getallwidth" value="' + aData[3] + '"><datalist id="frommedcine"></datalist>';
            jqTds[4].innerHTML = '<input type="text" list="usemedcine" id="drugdos"  class="form-control input-small testautocom getallwidth" value="' + aData[4] + '"><datalist id="usemedcine"></datalist>';
            jqTds[5].innerHTML = '<input type="text" class="form-control input-small " disabled="disabled" value="' + aData[5] + '">';
            jqTds[6].innerHTML = '<a class="edit" href="">Save</a>';
            jqTds[7].innerHTML = '<a class="cancel" href="">Cancel</a>';
            jqTds[8].innerHTML = '';


        }




        function saveRow(oTable, nRow) {
            var jqInputs = $('input', nRow);
            oTable.fnUpdate(jqInputs[0].value, nRow, 0, false);
            oTable.fnUpdate(jqInputs[1].value, nRow, 1, false);
            oTable.fnUpdate(jqInputs[2].value, nRow, 2, false);
            oTable.fnUpdate(jqInputs[3].value, nRow, 3, false);
            oTable.fnUpdate(jqInputs[4].value, nRow, 4, false);
            oTable.fnUpdate('<a class="edit" href="">Edit</a>', nRow, 6, false);
            oTable.fnUpdate('<a class="duplicate" href="">Duplicate</a>', nRow, 7, false);
            oTable.fnUpdate('<a class="delete" href="">Delete</a>', nRow, 8, false);
            // oTable.fnDraw();
        }

        function cancelEditRow(oTable, nRow) {
            var jqInputs = $('input', nRow);
            oTable.fnUpdate(jqInputs[0].value, nRow, 0, false);
            oTable.fnUpdate(jqInputs[1].value, nRow, 1, false);
            oTable.fnUpdate(jqInputs[2].value, nRow, 2, false);
            oTable.fnUpdate(jqInputs[3].value, nRow, 3, false);
            oTable.fnUpdate(jqInputs[4].value, nRow, 4, false);
            oTable.fnUpdate('<a class="edit" href="">Edit</a>', nRow, 6, false);
            //oTable.fnDraw();
        }
        var table = $('#drug_edit');

        var oTable = table.dataTable({
            // Uncomment below line("dom" parameter) to fix the dropdown overflow issue in the datatable cells. The default datatable layout
            // setup uses scrollable div(table-scrollable) with overflow:auto to enable vertical scroll(see: assets/global/plugins/datatables/plugins/bootstrap/dataTables.bootstrap.js).
            // So when dropdowns used the scrollable div should be removed.
            //"dom": "<'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r>t<'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>",

            "bProcessing": true,
            "bServerSide": true,
            "sAjaxSource": hosturl + '/controllers/drugs.php?ac=show', //  server side processing
            "sPaginationType": "full_numbers",
            "aoColumnDefs": [
                {"sClass": "hide_me", "aTargets": [0]},
                {
                    'orderable': false,
                    "searchable": false,
                    "targets": [6]
                }, {
                    'orderable': false,
                    "searchable": false,
                    "targets": [7]
                }, {
                    'orderable': false,
                    "searchable": false,
                    "targets": [8]
                }
            ],
            "lengthMenu": [
                [50, 100, 150, -1],
                [50, 100, 150, "All"] // change per page values here
            ],
            // set the initial value
            "pageLength": 50,
            "language": {
                "lengthMenu": " _MENU_ records"
            },
            "columnDefs": [{// set default column settings
                    'orderable': true,
                    'targets': [0]
                }, {
                    "searchable": true,
                    "targets": [0]
                }],
            "order": [
                [1, "asc"]       // order by drug cat
            ] // set first column as a default sort by asc
        });


        var tableWrapper = $("#sample_editable_1_wrapper");
        tableWrapper.find(".dataTables_length select").select2({
            showSearchInput: false //hide search box with special css class
        }); // initialize select2 dropdown

        var nEditing = null;
        var nNew = false;
        $('#sample_editable_1_new').click(function (e) {
            e.preventDefault();
            getdata();
            if (nNew && nEditing) {
                if (confirm("Previose row not saved. Do you want to save it ?")) {
                    saveRow(oTable, nEditing); // save
                    $(nEditing).find("td:first").html("Untitled");
                    nEditing = null;
                    nNew = false;
                } else {
                    oTable.fnDeleteRow(nEditing); // cancel
                    nEditing = null;
                    nNew = false;
                    return;
                }
            }

            var row = $("<tr></tr>");


            var col2 = $('<td><input type="text" list="groupmedcine"  id="drugcat" class="form-control input-small testautocom getallwidth" value=""> <datalist id="groupmedcine"></datalist></td>');
            var col1 = $('<td><input type="text" list="namemedcine"   id="drugname" class="form-control input-small  testautocom getallwidth" value=""> <datalist id="namemedcine"></datalist></td>');
            var col3 = $('<td><input type="text" list="frommedcine"  id="drugtype" class="form-control input-small    testautocom getallwidth" value=""> <datalist id="frommedcine"></datalist></td>');
            var col4 = $('<td><input type="text" list="usemedcine"  id="drugdos" class="form-control input-small  testautocom getallwidth" value=""> <datalist id="usemedcine"></datalist></td>');

            var col5 = $('<td><input type="text"  id="initial"  class="form-control input-small  testautocom getallwidth positivefloat" value=""> </td>');
            var col6 = $('<td><a class="add_new" href="">Save</a></td>');
            var col7 = $('<td><a class="cancel_xx" href="">Cancel</a></td>');
            var col8 = $('<td></td>');
            var col9 = $('<td></td>');
            row.append(col2, col1, col3, col4, col5, col6, col7, col8, col9).prependTo("#drug_edit");

            $(".positivefloat").forcepositivefloat();
        });



        table.on('click', '.delete', function (e)
        {
            e.preventDefault();
            if (confirm("Are you sure to delete this row ?") == false) {
                return;
            }

            var nRow = $(this).parents('tr')[0];
            var aData = oTable.fnGetData(nRow);

            $drugid = aData[0];
            $.post(hosturl + '/controllers/drugs.php?ac=deletedrug', {d_id: $drugid}, function ()
            {
                oTable.fnDeleteRow(nRow);
            });
            //alert("Deleted! Do not forget to do some ajax to sync with backend :)");
        });
        table.on('click', '.cancel', function (e)
        {
            e.preventDefault();
            if (nNew) {
                oTable.fnDeleteRow(nEditing);
                nEditing = null;
                nNew = false;
            } else {
                restoreRow(oTable, nEditing);
                nEditing = null;
            }
        });
        table.on('click', '.edit', function (e)
        {
            e.preventDefault();
            getdata();
            /* Get the row as a parent of the link that was clicked on */
            var nRow = $(this).parents('tr')[0];
            //getdata();
            if (nEditing !== null && nEditing != nRow) {
                /* Currently editing - but not this row - restore the old before continuing to edit mode */

                restoreRow(oTable, nEditing);
                nEditing = null;
                editRow(oTable, nRow);
                nEditing = nRow;
            } else if (nEditing == nRow && this.innerHTML == "Save") {
                /* Editing this row and want to save it */
                saveRow(oTable, nEditing);
                var aData = oTable.fnGetData(nRow);
                if (aData[0] === '') {
                    //alert("Insert! Do not forget to do some ajax to sync with backend :)");
                    $drugname = aData[2];
                    $drugcat = aData[1];
                    $drugdos = aData[4];
                    $druguse = aData[3];
                    $.post(hosturl + '/controllers/drugs.php?ac=adddrug', {drugname: $drugname, drugtype: $druguse, drugcat: $drugcat, drugdos: $drugdos}, function (data)
                    {
                        //draw in return ajax
                        oTable.fnUpdate(Number(data), nRow, 0, false); //return id
                        oTable.fnUpdate(aData[1].value, nRow, 1, false);
                        oTable.fnUpdate(aData[2].value, nRow, 2, false);
                        oTable.fnUpdate(aData[3].value, nRow, 3, false);
                        oTable.fnUpdate(aData[4].value, nRow, 4, false);
                        oTable.fnUpdate('<a class="edit" href="">Edit</a>', nRow, 5, false);
                        oTable.fnUpdate('<a class="delete" href="">Delete</a>', nRow, 6, false);
                        oTable.fnUpdate('<a class="duplicate" href="">Duplicate</a>', nRow, 7, false);
                        //oTable.fnDraw();
                    });


                } else {
                    //alert("Updated! Do not forget to do some ajax to sync with backend :)");
                    $drugname = aData[2];
                    $drugcat = aData[1];
                    $drugdos = aData[4];
                    $druguse = aData[3];
                    $drugid = aData[0];



                    if ($drugname == "" && $drugcat == "" && $drugdos == "" && $druguse == "")
                    {
                        oTable.fnDraw();
                        nEditing = null;
                    }
                    else
                    {
                        $.post(hosturl + '/controllers/drugs.php?ac=updatedrug', {drugname: $drugname, drugtype: $druguse, drugcat: $drugcat, drugdos: $drugdos, d_id: $drugid}, function (data)
                        {
                        });
                    }
                }
                nEditing = null;
            } else {
                /* No edit in progress - let's start one */
                editRow(oTable, nRow);
                nEditing = nRow;
            }
        });
        table.on('click', '.duplicate', function (e)
        {
            e.preventDefault();
            getdata();
            var nRow = $(this).parents('tr')[0];
            var aData = oTable.fnGetData(nRow);

            $drugname = aData[2];
            $drugcat = aData[1];
            $drugdos = aData[4];
            $druguse = aData[3];
            var initial = aData[5];
            var row = $("<tr></tr>");
            var col2 = $('<td><input type="text" list="groupmedcine"  id="drugcat" class="form-control input-small testautocom getallwidth" value="' + $drugcat + '"> <datalist id="groupmedcine"></datalist></td>');
            var col1 = $('<td><input type="text" list="namemedcine"   id="drugname" class="form-control input-small  testautocom getallwidth" value="' + $drugname + '"> <datalist id="namemedcine"></datalist></td>');
            var col3 = $('<td><input type="text" list="frommedcine"  id="drugtype" class="form-control input-small    testautocom getallwidth" value="' + $druguse + '"> <datalist id="frommedcine"></datalist></td>');
            var col4 = $('<td><input type="text" list="usemedcine"  id="drugdos" class="form-control input-small  testautocom getallwidth" value="' + $drugdos + '"> <datalist id="usemedcine"></datalist></td>');

            var col5 = $('<td><input type="text"  id="initial"  class="form-control input-small  testautocom getallwidth positivefloat" value="' + initial + '"> </td>');
            var col6 = $('<td><a class="add_new" href="">Save</a></td>');
            var col7 = $('<td><a class="cancel_xx" href="">Cancel</a></td>');
            var col8 = $('<td></td>');
            var col9 = $('<td></td>');


            row.append(col2, col1, col3, col4, col5, col6, col7, col8, col9).prependTo("#drug_edit");

            $(".positivefloat").forcepositivefloat();


        });
        table.on('click', '.add_new', function (e)     // save new row
        {
            e.preventDefault();
            //getdata();
            if (this.innerHTML == "Save")
            {
                $drugname = $('#drugname').val();
                $drugcat = $('#drugcat').val();
                $drugdos = $('#drugdos').val();
                $druguse = $('#drugtype').val();
                var initial = $('#initial').val();



                if ($drugname == "" && $drugcat == "" && $drugdos == "" && $druguse == "")
                {
                    oTable.fnDeleteRow(nEditing);
                    nEditing = null;
                    nNew = false;
                }
                else
                {
                    $.post(hosturl + '/controllers/drugs.php?ac=adddrug', {drugname: $drugname, drugtype: $druguse, drugcat: $drugcat, drugdos: $drugdos, initial: initial}, function (data)
                    {
                        oTable.fnDraw();
                    });
                }


            }
        });





    };
    return {
        //main function to initiate the module
        init: function () {
            handleTable();
            forAll();
        }

    };
}();