function check_searchBox() {
	// search receipt
	$("input#srchRecpt").keyup(function() {
		var passedValue = $("input#srchRecpt").val();
		if(passedValue.val!="") {
			$("div.suggest").css("display", "table-row");
			$.post("./assets-and-shares/includes/finance.php?action=searchRec&dest=srchRecpt", { passedValue: passedValue }, function(data) {
				$("div.suggest").html(data);
			});
		}
	});
	$("input#srchRecpt").blur(function() {
		if($("#srchRecpt").val()=="") {
			$("div.suggest").css("display", "none");
		}
	});
	// search other income
	$("input#srchOthrInc").keyup(function() {
		var passedValue = $("input#srchOthrInc").val();
		if(passedValue.val!="") {
			$("div.suggest").css("display", "table-row");
			$.post("./assets-and-shares/includes/finance.php?action=searchRec&dest=srchOthrInc", { passedValue: passedValue }, function(data) {
				$("div.suggest").html(data);
			});
		}
	});
	$("input#srchOthrInc").blur(function() {
		if($("#srchOthrInc").val()=="") {
			$("div.suggest").css("display", "none");
		}
	});
    // search payment
    $("input#srchPyment").keyup(function() {
        var passedValue = $("input#srchPyment").val();
        if(passedValue.val!="") {
            $("div.suggest").css("display", "table-row");
            $.post("./assets-and-shares/includes/finance.php?action=searchRec&dest=srchPyment", { passedValue: passedValue }, function(data) {
                $("div.suggest").html(data);
            });
        }
    });
    $("input#srchPyment").blur(function() {
        if($("#srchPyment").val()=="") {
            $("div.suggest").css("display", "none");
        }
    });
	// search payment
	$("input#srchPrchseBill").keyup(function() {
		var passedValue = $("input#srchPrchseBill").val();
		if(passedValue.val!="") {
			$("div.suggest").css("display", "table-row");
			$.post("./assets-and-shares/includes/finance.php?action=searchRec&dest=srchPrchseBill", { passedValue: passedValue }, function(data) {
				$("div.suggest").html(data);
			});
		}
	});
	$("input#srchPrchseBill").blur(function() {
		if($("#srchPrchseBill").val()=="") {
			$("div.suggest").css("display", "none");
		}
	});
	// search refund
	$("input#srchRefund").keyup(function() {
		var passedValue = $("input#srchRefund").val();
		if(passedValue.val!="") {
			$("div.suggest").css("display", "table-row");
			$.post("./assets-and-shares/includes/finance.php?action=searchRec&dest=srchRefund", { passedValue: passedValue }, function(data) {
				$("div.suggest").html(data);
			});
		}
	});
	$("input#srchPyment").blur(function() {
		if($("#srchPyment").val()=="") {
			$("div.suggest").css("display", "none");
		}
	});
	// search receivable
	$("input#srchRcvble").keyup(function() {
		var passedValue = $("input#srchRcvble").val();
		if(passedValue.val!="") {
			$("div.suggest").css("display", "table-row");
			$.post("./assets-and-shares/includes/finance.php?action=searchRec&dest=srchRcvble", { passedValue: passedValue }, function(data) {
				$("div.suggest").html(data);
			});
		}
	});
	$("input#srchRcvble").blur(function() {
		if($("#srchRcvble").val()=="") {
			$("div.suggest").css("display", "none");
		}
	});
	// search payable
	$("input#srchPyable").keyup(function() {
		var passedValue = $("input#srchPyable").val();
		if(passedValue.val!="") {
			$("div.suggest").css("display", "table-row");
			$.post("./assets-and-shares/includes/finance.php?action=searchRec&dest=srchPyable", { passedValue: passedValue }, function(data) {
				$("div.suggest").html(data);
			});
		}
	});
	$("input#srchPyable").blur(function() {
		if($("#srchPyable").val()=="") {
			$("div.suggest").css("display", "none");
		}
	});
	// search share
	$("input#srchShare").keyup(function() {
		var passedValue = $("input#srchShare").val();
		if(passedValue.val!="") {
			$("div.suggest").css("display", "table-row");
			$.post("./assets-and-shares/includes/finance.php?action=searchRec&dest=srchShare", { passedValue: passedValue }, function(data) {
				$("div.suggest").html(data);
			});
		}
	});
	$("input#srchShare").blur(function() {
		if($("#srchShare").val()=="") {
			$("div.suggest").css("display", "none");
		}
	});
	// search asset
	$("input#srchAsset").keyup(function() {
		var passedValue = $("input#srchAsset").val();
		if(passedValue.val!="") {
			$("div.suggest").css("display", "table-row");
			$.post("./assets-and-shares/includes/finance.php?action=searchRec&dest=srchAsset", { passedValue: passedValue }, function(data) {
				$("div.suggest").html(data);
			});
		}
	});
	$("input#srchAsset").blur(function() {
		if($("#srchAsset").val()=="") {
			$("div.suggest").css("display", "none");
		}
	});
	// search prepaid account
	$("input#srchPaidAcc").keyup(function() {
		var passedValue = $("input#srchPaidAcc").val();
		if(passedValue.val!="") {
			$("div.suggest").css("display", "table-row");
			$.post("./assets-and-shares/includes/finance.php?action=searchRec&dest=srchPaidAcc", { passedValue: passedValue }, function(data) {
				$("div.suggest").html(data);
			});
		}
	});
	$("input#srchPaidAcc").blur(function() {
		if($("#srchPaidAcc").val()=="") {
			$("div.suggest").css("display", "none");
		}
	});

        // search customer deposit / withdraw
    $("input#srchCustDeposit").keyup(function() {
        var passedValue = $("input#srchCustDeposit").val();
        if(passedValue.val!="") {
            $("div.suggest").css("display", "table-row");
            $.post("./assets-and-shares/includes/finance.php?action=searchRec&dest=srchCustDeposit", { passedValue: passedValue }, function(data) {
                $("div.suggest").html(data);
            });
        }
    });
    $("input#srchCustDeposit").blur(function() {
        if($("#srchCustDeposit").val()=="") {
            $("div.suggest").css("display", "none");
        }
    });

		// search vendor deposit / withdraw
	$("input#srchVendorDeposit").keyup(function() {
		var passedValue = $("input#srchVendorDeposit").val();
		if(passedValue.val!="") {
			$("div.suggest").css("display", "table-row");
			$.post("./assets-and-shares/includes/finance.php?action=searchRec&dest=srchVendorDeposit", { passedValue: passedValue }, function(data) {
				$("div.suggest").html(data);
			});
		}
	});
	$("input#srchVendorDeposit").blur(function() {
		if($("#srchVendorDeposit").val()=="") {
			$("div.suggest").css("display", "none");
		}
	});
		// search dividend payment
	$("input#srchDivPyment").keyup(function() {
		var passedValue = $("input#srchDivPyment").val();
		if(passedValue.val!="") {
			$("div.suggest").css("display", "table-row");
			$.post("./assets-and-shares/includes/finance.php?action=searchRec&dest=srchDivPyment", { passedValue: passedValue }, function(data) {
				$("div.suggest").html(data);
			});
		}
	});
	$("input#srchDivPyment").blur(function() {
		if($("#srchDivPyment").val()=="") {
			$("div.suggest").css("display", "none");
		}
	});
}
function callSumOSelect() {
    'namespace sumo';
    $.fn.SumoSelect = function (options) {

        // This is the easiest way to have default options.
        var settings = $.extend({
            placeholder: 'Select Here',   // Dont change it here.
            csvDispCount: 3,              // display no. of items in multiselect. 0 to display all.
            captionFormat:'{0} Selected', // format of caption text. you can set your locale.
            captionFormatAllSelected:'{0} all selected!', // format of caption text when all elements are selected. set null to use captionFormat. It will not work if there are disabled elements in select.
            floatWidth: 400,              // Screen width of device at which the list is rendered in floating popup fashion.
            forceCustomRendering: false,  // force the custom modal on all devices below floatWidth resolution.
            nativeOnDevice: ['Android', 'BlackBerry', 'iPhone', 'iPad', 'iPod', 'Opera Mini', 'IEMobile', 'Silk'], //
            outputAsCSV: false,           // true to POST data as csv ( false for Html control array ie. default select )
            csvSepChar: ',',              // separation char in csv mode
            okCancelInMulti: false,       // display ok cancel buttons in desktop mode multiselect also.
            triggerChangeCombined: true,  // im multi select mode wether to trigger change event on individual selection or combined selection.
            selectAll: false,             // to display select all button in multiselect mode.|| also select all will not be available on mobile devices.

            search: false,                // to display input for filtering content. selectAlltext will be input text placeholder
            searchText: 'Search...',      // placeholder for search input
            noMatch: 'No matches for "{0}"',
            prefix: '',                   // some prefix usually the field name. eg. '<b>Hello</b>'
            locale: ['OK', 'Cancel', 'Select All'],  // all text that is used. don't change the index.
            up: false                     // set true to open upside.
        }, options);

        var ret = this.each(function () {
            var selObj = this; // the original select object.
            if (this.sumo || !$(this).is('select')) return; //already initialized

            this.sumo = {
                E: $(selObj),   //the jquery object of original select element.
                is_multi: $(selObj).attr('multiple'),  //if its a multiple select
                select: '',
                caption: '',
                placeholder: '',
                optDiv: '',
                CaptionCont: '',
                ul:'',
                is_floating: false,
                is_opened: false,
                //backdrop: '',
                mob:false, // if to open device default select
                Pstate: [],

                createElems: function () {
                    var O = this;
                    O.E.wrap('<div class="SumoSelect" tabindex="1">');
                    O.select = O.E.parent();
                    O.caption = $('<span>');
                    O.CaptionCont = $('<p class="CaptionCont"><label><i></i></label></p>').addClass('SelectBox').attr('style', O.E.attr('style')).prepend(O.caption);
                    O.select.append(O.CaptionCont);

                    // default turn off if no multiselect
                    if(!O.is_multi)settings.okCancelInMulti = false

                    if(O.E.attr('disabled'))
                        O.select.addClass('disabled').removeAttr('tabindex');

                    //if output as csv and is a multiselect.
                    if (settings.outputAsCSV && O.is_multi && O.E.attr('name')) {
                        //create a hidden field to store csv value.
                        O.select.append($('<input class="HEMANT123" type="hidden" />').attr('name', O.E.attr('name')).val(O.getSelStr()));

                        // so it can not post the original select.
                        O.E.removeAttr('name');
                    }

                    //break for mobile rendring.. if forceCustomRendering is false
                    if (O.isMobile() && !settings.forceCustomRendering) {
                        O.setNativeMobile();
                        return;
                    }

                    // if there is a name attr in select add a class to container div
                    if(O.E.attr('name')) O.select.addClass('sumo_'+O.E.attr('name'))

                    //hide original select
                    O.E.addClass('SumoUnder').attr('tabindex','-1');

                    //## Creating the list...
                    O.optDiv = $('<div class="optWrapper '+ (settings.up?'up':'') +'">');

                    //branch for floating list in low res devices.
                    O.floatingList();

                    //Creating the markup for the available options
                    O.ul = $('<ul class="options">');
                    O.optDiv.append(O.ul);

                    // Select all functionality
                    if(settings.selectAll) O.SelAll();

                    // search functionality
                    if(settings.search) O.Search();

                    O.ul.append(O.prepItems(O.E.children()));

                    //if multiple then add the class multiple and add OK / CANCEL button
                    if (O.is_multi) O.multiSelelect();

                    O.select.append(O.optDiv);
                    O.basicEvents();
                    O.selAllState();
                },
                prepItems: function(opts, d){
                    var lis = [], O=this;
                    $(opts).each(function (i, opt) {       // parsing options to li
                        opt = $(opt);
                        lis.push(opt.is('optgroup')?
                            $('<li class="group '+ (opt[0].disabled?'disabled':'') +'"><label>' + opt.attr('label') +'</label><ul></ul><li>')
                            .find('ul')
                            .append(O.prepItems(opt.children(), opt[0].disabled))
                            .end()
                            :
                            O.createLi(opt, d)
                            );
                    });
                    return lis;
                },

                //## Creates a LI element from a given option and binds events to it
                //## returns the jquery instance of li (not inserted in dom)
                createLi: function (opt, d) {
                    var O = this;

                    if(!opt.attr('value'))opt.attr('value',opt.val());
                                                                                    // todo: remove this data val
                    li = $('<li class="opt"><label>' + opt.text() + '</label></li>');//.data('val',opt.val());
                    li.data('opt', opt);    // store a direct reference to option.
                    opt.data('li', li);    // store a direct reference to list item.
                    if (O.is_multi) li.prepend('<span><i></i></span>');

                    if (opt[0].disabled || d)
                        li = li.addClass('disabled');

                    O.onOptClick(li);

                    if (opt[0].selected)
                        li.addClass('selected');

                    if (opt.attr('class'))
                        li.addClass(opt.attr('class'));

                    return li;
                },

                //## Returns the selected items as string in a Multiselect.
                getSelStr: function () {
                    // get the pre selected items.
                    sopt = [];
                    this.E.find('option:selected').each(function () { sopt.push($(this).val()); });
                    return sopt.join(settings.csvSepChar);
                },

                //## THOSE OK/CANCEL BUTTONS ON MULTIPLE SELECT.
                multiSelelect: function () {
                    var O = this;
                    O.optDiv.addClass('multiple');
                    O.okbtn = $('<p class="btnOk">'+settings.locale[0]+'</p>').click(function () {

                        //if combined change event is set.
                        if (settings.triggerChangeCombined) {

                            //check for a change in the selection.
                            changed = false;
                            if (O.E.find('option:selected').length != O.Pstate.length) {
                                changed = true;
                            }
                            else {
                                O.E.find('option').each(function (i,e) {
                                    if(e.selected && O.Pstate.indexOf(i) < 0) changed = true;
                                });
                            }

                            if (changed) {
                                O.callChange();
                                O.setText();
                            }
                        }
                        O.hideOpts();
                    });
                    O.cancelBtn = $('<p class="btnCancel">'+settings.locale[1]+'</p>').click(function () {
                        O._cnbtn();
                        O.hideOpts();
                    });
                    O.optDiv.append($('<div class="MultiControls">').append(O.okbtn).append(O.cancelBtn));
                },

                _cnbtn:function(){
                    var O = this;
                    //remove all selections
                        O.E.find('option:selected').each(function () { this.selected = false; });
                        O.optDiv.find('li.selected').removeClass('selected')

                        //restore selections from saved state.
                        for(var i = 0; i < O.Pstate.length; i++) {
                            O.E.find('option')[O.Pstate[i]].selected = true;
                            O.ul.find('li.opt').eq(O.Pstate[i]).addClass('selected');
                        }
                    O.selAllState();
                },

                SelAll:function(){
                    var O = this;
                    if(!O.is_multi)return;
                    O.selAll = $('<p class="select-all"><span><i></i></span><label>' + settings.locale[2] + '</label></p>');
                    O.selAll.on('click',function(){
                        //O.toggSelAll(!);
                        O.selAll.toggleClass('selected');
                        O.optDiv.find('li.opt').not('.hidden').each(function(ix,e){
                            e = $(e);
                            if(O.selAll.hasClass('selected')){
                                if(!e.hasClass('selected'))e.trigger('click');
                            }
                            else
                                if(e.hasClass('selected'))e.trigger('click');
                        });
                    });

                    O.optDiv.prepend(O.selAll);
                },

                // search module (can be removed if not required.)
                Search: function(){
                    var O = this,
                        cc = O.CaptionCont.addClass('search'),
                        P = $('<p class="no-match">');

                    O.ftxt = $('<input type="text" class="search-txt" value="" placeholder="' + settings.searchText + '">')
                        .on('click', function(e){
                            e.stopPropagation();
                        });
                    cc.append(O.ftxt);
                    O.optDiv.children('ul').after(P);

                    O.ftxt.on('keyup.sumo',function(){
                        var hid = O.optDiv.find('ul.options li.opt').each(function(ix,e){
                            e = $(e);
                            if(e.text().toLowerCase().indexOf(O.ftxt.val().toLowerCase()) > -1)
                                e.removeClass('hidden');
                            else
                                e.addClass('hidden');
                        }).not('.hidden');

                        P.html(settings.noMatch.replace(/\{0\}/g, O.ftxt.val())).toggle(!hid.length);

                        O.selAllState();
                    });
                },

                selAllState: function () {
                    var O = this;
                    if (settings.selectAll) {
                        var sc = 0, vc = 0;
                        O.optDiv.find('li.opt').not('.hidden').each(function (ix, e) {
                            if ($(e).hasClass('selected')) sc++;
                            if (!$(e).hasClass('disabled')) vc++;
                        });
                        //select all checkbox state change.
                        if (sc == vc) O.selAll.removeClass('partial').addClass('selected');
                        else if (sc == 0) O.selAll.removeClass('selected partial');
                        else O.selAll.addClass('partial')//.removeClass('selected');
                    }
                },

                showOpts: function () {
                    var O = this;
                    if (O.E.attr('disabled')) return; // if select is disabled then retrun
                    O.is_opened = true;
                    O.select.addClass('open');

                    if(O.ftxt)O.ftxt.focus();
                    else O.select.focus();

                    // hide options on click outside.
                    $(document).on('click.sumo', function (e) {
                        if (!O.select.is(e.target)                  // if the target of the click isn't the container...
                            && O.select.has(e.target).length === 0){ // ... nor a descendant of the container
                            if(!O.is_opened)return;
                            O.hideOpts();
                            if (settings.okCancelInMulti)O._cnbtn();
                        }
                    });

                    if (O.is_floating) {
                        H = O.optDiv.children('ul').outerHeight() + 2;  // +2 is clear fix
                        if (O.is_multi) H = H + parseInt(O.optDiv.css('padding-bottom'));
                        O.optDiv.css('height', H);
                        $('body').addClass('sumoStopScroll');
                    }

                    O.setPstate();
                },

                //maintain state when ok/cancel buttons are available storing the indexes.
                setPstate: function(){
                    var O = this;
                    if (O.is_multi && (O.is_floating || settings.okCancelInMulti)){
                        O.Pstate = [];
                        // assuming that find returns elements in tree order
                        O.E.find('option').each(function (i, e){if(e.selected) O.Pstate.push(i);});
                    }
                },

                callChange:function(){
                    this.E.trigger('change').trigger('click');
                },

                hideOpts: function () {
                    var O = this;
                    if(O.is_opened){
                        O.is_opened = false;
                        O.select.removeClass('open').find('ul li.sel').removeClass('sel');
                        $(document).off('click.sumo');
                        O.select.focus();
                        $('body').removeClass('sumoStopScroll');

                        // clear the search
                        if(settings.search){
                            O.ftxt.val('');
                            O.optDiv.find('ul.options li').removeClass('hidden');
                            O.optDiv.find('.no-match').toggle(false);
                        }
                    }
                 },
                setOnOpen: function () {
                    var O = this,
                        li = O.optDiv.find('li.opt:not(.hidden)').eq(settings.search?0:O.E[0].selectedIndex);

                    O.optDiv.find('li.sel').removeClass('sel');
                    li.addClass('sel');
                    O.showOpts();
                },
                nav: function (up) {
                    var O = this, c,
                    s=O.ul.find('li.opt:not(.disabled, .hidden)'),
                    sel = O.ul.find('li.opt.sel:not(.hidden)'),
                    idx = s.index(sel);
                    if (O.is_opened && sel.length) {

                        if (up && idx > 0)
                            c = s.eq(idx-1);
                        else if(!up && idx < s.length-1 && idx > -1)
                            c = s.eq(idx+1);
                        else return; // if no items before or after

                        sel.removeClass('sel');
                        sel = c.addClass('sel');

                        // setting sel item to visible view.
                        var ul = O.ul,
                            st = ul.scrollTop(),
                            t = sel.position().top + st;
                        if(t >= st + ul.height()-sel.outerHeight())
                            ul.scrollTop(t - ul.height() + sel.outerHeight());
                        if(t<st)
                            ul.scrollTop(t);

                    }
                    else
                        O.setOnOpen();
                },

                basicEvents: function () {
                    var O = this;
                    O.CaptionCont.click(function (evt) {
                        O.E.trigger('click');
                        if (O.is_opened) O.hideOpts(); else O.showOpts();
                        evt.stopPropagation();
                    });

                        O.select.on('keydown.sumo', function (e) {
                            switch (e.which) {
                                case 38: // up
                                    O.nav(true);
                                    break;

                                case 40: // down
                                    O.nav(false);
                                    break;

                                case 32: // space
                                    if(settings.search && O.ftxt.is(e.target))return;
                                case 13: // enter
                                    if (O.is_opened)
                                        O.optDiv.find('ul li.sel').trigger('click');
                                    else
                                        O.setOnOpen();
                                    break;
                                case 9:  //tab
                                case 27: // esc
                                     if (settings.okCancelInMulti)O._cnbtn();
                                    O.hideOpts();
                                    return;

                                default:
                                    return; // exit this handler for other keys
                            }
                            e.preventDefault(); // prevent the default action (scroll / move caret)
                        });

                    $(window).on('resize.sumo', function () {
                        O.floatingList();
                    });
                },

                onOptClick: function (li) {
                    var O = this;
                    li.click(function () {
                        var li = $(this);
                        if(li.hasClass('disabled'))return;
                        txt = "";
                        if (O.is_multi) {
                            li.toggleClass('selected');
                            li.data('opt')[0].selected = li.hasClass('selected');
                            O.selAllState();
                        }
                        else {
                            li.parent().find('li.selected').removeClass('selected'); //if not multiselect then remove all selections from this list
                            li.toggleClass('selected');
                            li.data('opt')[0].selected = true;
                        }

                        //branch for combined change event.
                        if (!(O.is_multi && settings.triggerChangeCombined && (O.is_floating || settings.okCancelInMulti))) {
                            O.setText();
                            O.callChange();
                        }

                        if (!O.is_multi) O.hideOpts(); //if its not a multiselect then hide on single select.
                    });
                },

                setText: function () {
                    var O = this;
                    O.placeholder = "";
                    if (O.is_multi) {
                        sels = O.E.find(':selected').not(':disabled'); //selected options.

                        for (i = 0; i < sels.length; i++) {
                                if (i + 1 >= settings.csvDispCount && settings.csvDispCount) {
                                    if (sels.length == O.E.find('option').length && settings.captionFormatAllSelected) {
                                        O.placeholder = settings.captionFormatAllSelected.replace(/\{0\}/g, sels.length)+',';
                                    } else {
                                        O.placeholder = settings.captionFormat.replace(/\{0\}/g, sels.length)+',';
                                    }

                                    break;
                                }
                                else O.placeholder += $(sels[i]).text() + ", ";
                            }
                            O.placeholder = O.placeholder.replace(/,([^,]*)$/, '$1'); //remove unexpected "," from last.
                    }
                    else {
                        O.placeholder = O.E.find(':selected').not(':disabled').text();
                    }

                    is_placeholder = false;

                    if (!O.placeholder) {

                        is_placeholder = true;

                        O.placeholder = O.E.attr('placeholder');
                        if (!O.placeholder)                  //if placeholder is there then set it
                            O.placeholder = O.E.find('option:disabled:selected').text();
                    }

                    O.placeholder = O.placeholder ? (settings.prefix + ' ' + O.placeholder) : settings.placeholder

                    //set display text
                    O.caption.html(O.placeholder);
                    O.CaptionCont.attr('title', O.placeholder);

                    //set the hidden field if post as csv is true.
                    csvField = O.select.find('input.HEMANT123');
                    if (csvField.length) csvField.val(O.getSelStr());

                    //add class placeholder if its a placeholder text.
                    if (is_placeholder) O.caption.addClass('placeholder'); else O.caption.removeClass('placeholder');
                    return O.placeholder;
                },

                isMobile: function () {

                    // Adapted from http://www.detectmobilebrowsers.com
                    var ua = navigator.userAgent || navigator.vendor || window.opera;

                    // Checks for iOs, Android, Blackberry, Opera Mini, and Windows mobile devices
                    for (var i = 0; i < settings.nativeOnDevice.length; i++) if (ua.toString().toLowerCase().indexOf(settings.nativeOnDevice[i].toLowerCase()) > 0) return settings.nativeOnDevice[i];
                    return false;
                },

                setNativeMobile: function () {
                    var O = this;
                    O.E.addClass('SelectClass')//.css('height', O.select.outerHeight());
                    O.mob = true;
                    O.E.change(function () {
                        O.setText();
                    });
                },

                floatingList: function () {
                    var O = this;
                    //called on init and also on resize.
                    //O.is_floating = true if window width is < specified float width
                    O.is_floating = $(window).width() <= settings.floatWidth;

                    //set class isFloating
                    O.optDiv.toggleClass('isFloating', O.is_floating);

                    //remove height if not floating
                    if (!O.is_floating) O.optDiv.css('height', '');

                    //toggle class according to okCancelInMulti flag only when it is not floating
                    O.optDiv.toggleClass('okCancelInMulti', settings.okCancelInMulti && !O.is_floating);
                },

                //HELPERS FOR OUTSIDERS
                // validates range of given item operations
                vRange: function (i) {
                    var O = this;
                    opts = O.E.find('option');
                    if (opts.length <= i || i < 0) throw "index out of bounds"
                    return O;
                },

                //toggles selection on c as boolean.
                toggSel: function (c, i) {
                    var O = this;
                    if (typeof(i) === "number"){
                        O.vRange(i);
                        opt = O.E.find('option')[i];
                    }
                    else{
                        opt = O.E.find('option[value="'+i+'"]')[0]||0;
                    }
                    if (!opt || opt.disabled)
                        return;

                    if(opt.selected != c){
                        opt.selected = c;
                        if(!O.mob) $(opt).data('li').toggleClass('selected',c);

                        O.callChange();
                        O.setPstate();
                        O.setText();
                        O.selAllState();
                    }
                },

                //toggles disabled on c as boolean.
                toggDis: function (c, i) {
                    var O = this.vRange(i);
                    O.E.find('option')[i].disabled = c;
                    if(c)O.E.find('option')[i].selected = false;
                    if(!O.mob)O.optDiv.find('ul.options li').eq(i).toggleClass('disabled', c).removeClass('selected');
                    O.setText();
                },

                // toggle disable/enable on complete select control
                toggSumo: function(val) {
                    var O = this;
                    O.enabled = val;
                    O.select.toggleClass('disabled', val);

                    if (val) {
                        O.E.attr('disabled', 'disabled');
                        O.select.removeAttr('tabindex');
                    }
                    else{
                        O.E.removeAttr('disabled');
                        O.select.attr('tabindex','0');
                    }

                    return O;
                },

                //toggles alloption on c as boolean.
                toggSelAll: function (c) {
                    var O = this;
                    O.E.find('option').each(function (ix, el) {
                        if (O.E.find('option')[$(this).index()].disabled) return;
                        O.E.find('option')[$(this).index()].selected = c;
                        if (!O.mob)
                            O.optDiv.find('ul.options li').eq($(this).index()).toggleClass('selected', c);
                        O.setText();
                    });
                    if(!O.mob && O.selAll)O.selAll.removeClass('partial').toggleClass('selected',c);
                    O.callChange();
                    O.setPstate();
                },

                /* outside accessibility options
                   which can be accessed from the element instance.
                */
                reload:function(){
                    var elm = this.unload();
                    return $(elm).SumoSelect(settings);
                },

                unload: function () {
                    var O = this;
                    O.select.before(O.E);
                    O.E.show();

                    if (settings.outputAsCSV && O.is_multi && O.select.find('input.HEMANT123').length) {
                        O.E.attr('name', O.select.find('input.HEMANT123').attr('name')); // restore the name;
                    }
                    O.select.remove();
                    delete selObj.sumo;
                    return selObj;
                },

                //## add a new option to select at a given index.
                add: function (val, txt, i) {
                    if (typeof val == "undefined") throw "No value to add"

                    var O = this;
                    opts=O.E.find('option')
                    if (typeof txt == "number") { i = txt; txt = val; }
                    if (typeof txt == "undefined") { txt = val; }

                    opt = $("<option></option>").val(val).html(txt);

                    if (opts.length < i) throw "index out of bounds"

                    if (typeof i == "undefined" || opts.length == i) { // add it to the last if given index is last no or no index provides.
                        O.E.append(opt);
                        if(!O.mob)O.ul.append(O.createLi(opt));
                    }
                    else {
                        opts.eq(i).before(opt);
                        if(!O.mob)O.ul.find('li.opt').eq(i).before(O.createLi(opt));
                    }

                    return selObj;
                },

                //## removes an item at a given index.
                remove: function (i) {
                    var O = this.vRange(i);
                    O.E.find('option').eq(i).remove();
                    if(!O.mob)O.optDiv.find('ul.options li').eq(i).remove();
                    O.setText();
                },

                //## Select an item at a given index.
                selectItem: function (i) { this.toggSel(true, i); },

                //## UnSelect an iten at a given index.
                unSelectItem: function (i) { this.toggSel(false, i); },

                //## Select all items  of the select.
                selectAll: function () { this.toggSelAll(true); },

                //## UnSelect all items of the select.
                unSelectAll: function () { this.toggSelAll(false); },

                //## Disable an iten at a given index.
                disableItem: function (i) { this.toggDis(true, i) },

                //## Removes disabled an iten at a given index.
                enableItem: function (i) { this.toggDis(false, i) },

                //## New simple methods as getter and setter are not working fine in ie8-
                //## variable to check state of control if enabled or disabled.
                enabled : true,
                //## Enables the control
                enable: function(){return this.toggSumo(false)},

                //## Disables the control
                disable: function(){return this.toggSumo(true)},


                init: function () {
                    var O = this;
                    O.createElems();
                    O.setText();
                    return O
                }

            };

            selObj.sumo.init();
        });

        return ret.length == 1 ? ret[0] : ret;
    };
}

/* ---------------------------------------------------------------
---------------------------- receipts ----------------------------
-----------------------------------------------------------------*/

function loadRecpts(pageLimit, perPage, period) {
	$("#dataTable div#loading").css("display", "inline");
	var dataString = 'pageLimit='+ pageLimit+'&period='+ period+'&perPage='+ perPage;
	$.ajax({
		type: "POST",
		url: "./assets-and-shares/includes/finance.php?action=loadTable&dest=allRecpts",
		data: dataString,
		cache: false,
		timeout: 2000,
		success: function(result){
			/*$("#dataTable div#loading").css("display", "none");
			$(".load_more_link").addClass('noneLink');
			$("#dataTable").append(result);*/
            // console.log(result);
            let found = JSON.parse(result);

            $('label#count').html(found.rowsFound)

            let columns = [];
            let dataset = found.dataset;

            columns = [
                {"title": "Action", "className": "gl-3", "render": function(data, type, row, meta) {
                    return `<div class="cave button">
                        <a class="view fa fa-eye" href="${row.showLink}"></a>
                    </div>`;
                }},

                {"title": "RV Number", "data" : "addedDate", "className": "gl-2",  "render": function(data, type, row, meta) {
                    return `<p>${row.rvNumber}</p>`;
                }},

                {"title": "Payee Name", "data" : "invoiceNo", "className": "gl-2",  "render": function(data, type, row, meta) {
                    return `<p>${row.clientName}</p>`;
                }},

                {"title": "Amount", "data" : "clientName", "className": "gl-2",  "render": function(data, type, row, meta) {
                    return `<p>${format_moneyOne(row.amount)}</p>`;
                }},

                {"title": "Date", "data" : "totalAmount", "className": "gl-2",  "render": function(data, type, row, meta) {
                    return `<p>${row.addedDate}</p>`;
                }},
            ]

            // console.log(columns)

            // return false;
            let dataTable = new DataTable('#allReceiptsDataTable', {
                data: dataset,
                paging: true,
                "bDestroy": true,
                "columns": columns
            })
		},
	});
	return false;
}

function smpfyAddRecpt() {
	$("input#txtClient").keyup(function () {
        var clientName = $("#txtClient").val();
		var slcCustType = $("#slcCustType").val();

        if(clientName!="" && slcCustType=="outCustomer") {
            $("div.suggest").css("display", "table-row");
            $.post("./assets-and-shares/includes/finance.php?action=searchRec&dest=pickClient4Recpt", { clientName:clientName }, function(data) {
                $("div.suggest").html(data);
            });
        } else if(clientName!="" && slcCustType=="myStore") {
			$("div.suggest").css("display", "table-row");
			$.post("./assets-and-shares/includes/finance.php?action=searchRec&dest=pickWhouse4Recpt", { clientName:clientName }, function(data) {
				$("div.suggest").html(data);
			});
		} else { $("div.suggest").css("display", "none"); }
		clearErrors();
	});

}
function simplifyReceiptShow() {
    $("#txtWhouse").keyup(function(){
    var passedValue = $("#txtWhouse").val();
    if(passedValue!="") {
        $("div.suggest.one.whouse").css("display", "table-row");
            $.post("./assets-and-shares/includes/finance.php?action=searchRec&dest=pickWhouse",{ passedValue:passedValue}, function(data) {
            $("div.suggest.one.whouse").html(data);
            });

    } else { $("div.suggest.one.whouse").css("display", "none"); }
    });
}
//
function catchWhouse4form(whouseID,wherehouse,phone) {
    $("input.receipt#whouseID").val(whouseID);
    $("p#pCName").html(wherehouse);
    $("#txtWhouse").val(wherehouse);
    $("p#pCPhone").html(phone);
    $("div.displayInfo.whouse.receipt").css("display", "inline");
    $("div.suggest").css("display", "none");
}
//
function check_editReceiptWhouse() {
    var receiptID       = $("#editedreceiptID").val();
    var whouseID      = $("input.receipt#whouseID").val();
    var txtWhouse     = $("#txtWhouse").val();
    var oldwhouseID   = $("#oldwhouseID").val();
    var oldWhouseName = $("#oldWhouseName").val();

    //alert(clientID);return false;

    if(receiptID.length < 1 || whouseID.length < 1 || txtWhouse.length < 1) {
        $("#popuperror31").css("display", "inline");
        $("#popuperror31").html("Please provide wherehouse");
        $("#txtWhouse").addClass("highlight");
        return false;
    } else { clearErrors(); }

    if(whouseID==oldwhouseID && txtWhouse==oldWhouseName){
            swal({
                    title: "Info",
                    text: "Nothing has been changed",
                    type: "info",
                    timer: 1500,
                    button: false
                    })
                        .then(value=>{
                            location.reload();
                        }
                    );

            return false;
    }
    swal({
        title: "Are you sure to edit?",
        text: "You going to change receipt Wherehouse for \n\
        "+oldWhouseName+"\n\
        To "+txtWhouse,
        icon: "warning",
        dangerMode:true,
        buttons:["Cancel","Delete"]
    })
    .then(willDelete=>{
        if(willDelete) {
            $.post("./assets-and-shares/includes/finance.php?action=updateExist&dest=editReceiptWhouse",{receiptID:receiptID, oldwhouseID:oldwhouseID, whouseID:whouseID}, function(data){
                if(data=="updated") {
                    swal({
                        title: "Success",
                        text: "receipt wherehouse has been updated successfully",
                        icon: "success",
                        timer: 1500,
                        button: false
                    })
                    .then(value=>{
                            location.reload();
                        }
                    );
                } else {swal("OOPS",data,"error");}
            });
        }

    });
    return false;
}
//
function catchClient4Recpt(clientID, clientName, clientPhone) {
    $("#clientID").val(clientID);
    $("#txtClient").val(clientName);
    $("#txtPaidBy").val(clientName);
    //alert(clientID)

    //, allSales, ttlSlsBalance, beginBlnce, ttlBalance
    $.post("./assets-and-shares/includes/finance.php?action=searchRec&dest=pickClientSales", { clientID:clientID }, function(data) {
        var response = data.split("||");
        var ttlBalance = response[0];
        var ttlSlsBalance = response[1];
        var beginBlnce = response[2];
        var allSales = response[3];

        $("#originTtlDue").val(ttlBalance);
        $("#totalDue").val(ttlBalance);
        $("#txtAmount").val(ttlBalance);
        inWords($("#txtAmount").val());
       //$("#amount1").val(ttlBalance);

        if(parseFloat(beginBlnce)>0 && client_receipt_procedure=="seperate") {
            $("button.btnSubmit").css("display", "none");
            $("div.record.goPageLinkDiv").css("display", "block");
            $("div.record.goPageLinkDiv a").attr("href", "./workplace.php?role="+myRole+"&task=finance&subtask=receivable&action=addnew&client="+clientID);
            /*href="./workplace.php?role=<?=$myRole;?>&task=finance&subtask=receivable&action=addnew&client"*/
        }

        $("div.allSales").html(allSales);
        $("div.suggest").css("display", "none");
    });

}
function populateInvoiceItems(salesID) {
    //
    window.open('./dp_invoicePopUp.php?recID='+salesID,'_blank', 'width=900 , height=400 , top=150 , left=300, toolbar=yes');
    //
    return false;
}
function check_addReceipt(form) {
    var clientID    = $("#clientID").val();
    var slcWhouse = $("#slcWhouse").val();
	var slcCustType = $("#slcCustType").val();
	var txtClient	= $("#txtClient").val();
	var totalDue	= parseFloat($("#totalDue").val());

    var txtAmount   = $("#txtAmount").val();
    var txtInWords  = $("#txtInWords").val();

    var slcBankID   = $("#slcBankID").val();
    var slcBankAcc  = $("#slcBankAcc").val();
    var txtCheque   = $("#txtCheque").val();

    var txtPaidBy   = $("#txtPaidBy").val();

	var txtRemarks	= $("#txtRemarks").val();
	var transDate	= $("#transDate").val();

    if(clientID.length < 1 || txtClient.length < 1) {
        $("#error1").css("display", "inline");
        $("#error1").html("Please find and select "+typeLabel);
        $("#txtClient").addClass("highlight");
        $("div.suggest").css("display", "none");
        return false;
    } else { clearErrors(); }

	if(slcWhouse=="" || slcWhouse==null) {
		$("#error7").css("display", "inline");
		$("#error7").html("Please select wherehouse");
		$("#slcWhouse").addClass("highlight");
		return false;
	} else { clearErrors(); }

	if(txtAmount.length < 1) {
		$("#error2").css("display", "inline");
		$("#error2").html("Amount value is missing");
		$("#txtAmount").addClass("highlight");
		return false;
	} else if(Number(txtAmount) < 0.1) {
		$("#error2").css("display", "inline");
		$("#error2").html("Amount must be greater than 0");
		$("#txtAmount").addClass("highlight");
		return false;
	} else if(parseFloat(txtAmount) > parseFloat(totalDue)) {
		$("#error2").css("display", "inline");
		$("#error2").html("Amount can't be more than $"+totalDue);
		$("#txtAmount").addClass("highlight");
		return false;
	} else { clearErrors(); }


    if(txtPaidBy.length < 1) {
        $("#error3").css("display", "inline");
        $("#error3").html("This field can't be empty");
        $("#txtPaidBy").css("border-color", "#FF0000");
        return false;
    } else { clearErrors(); }

    if(slcBankID.length < 1) {
        $("#error4").css("display", "inline");
        $("#error4").html("Please select bank");
        $("#slcBankID").css("border-color", "#FF0000");
        return false;
    } else { clearErrors(); }

    if(slcBankAcc==null || slcBankAcc=="---" || slcBankAcc.length < 1) {
        $("#error4").css("display", "inline");
        $("#error4").html("Select bank account");
        $("#slcBankAcc").css("border-color", "#FF0000");
        return false;
    } else { clearErrors(); }

    swal({
        title: "Are you sure?",
        text: "You going to reciept sales reciept!\n\
        Be carefull to do this action\n\
        if this "+typeLabel+" have many invoices in this list \n\
        system makes FIFO concept FIRST IN FIRST OUT, \n\
        means first invoice has first reciept",
        icon: "warning",
        dangerMode:true,
        buttons:["Cancel","Reciept Now"]
    })
    .then(isConfirm=>{
        if(isConfirm) {
            $("label.process").css("display", "inline");
            $("#btnSave").attr("disabled", true);
            $("#btnSave").html("Wait...");
            form.submit();
        }

    });
	return false;
}
function addDiscountBeforeReceipt(btn, salesID, discount, clientID, balance) {
    let isFromClinic = 'Yes';
    let receiptDiscount = 'Yes';
    // let clientID = $('#clientID').val();
    let clientName = $('#txtClient').val();
    let row = $(btn).parents('.row.data-row');
    swal({
        title: "Edit Discount",
        text: 'New discount amount',
        content: "input",
        buttons: ["Cancel","Proceed!"]
    }).then (newDiscount=>{
        var amntReg = /[0-9]/;
        if (newDiscount) {
            if(newDiscount.match(amntReg)) {
                newDiscount = parseFloat(newDiscount);
                    if(newDiscount > parseFloat(balance)) {
                        swal('Oops',`discount $${newDiscount} is greater that balance $${balance}!`, 'error')
                        return false
                    }

                swal({
                    title: "Are you sure?",
                    text: "New discount will be  $"+newDiscount,
                    icon: "warning",
                    buttons: ["Cancel","Yes, do it!"],
                    dangerMode: true,
                }).then (confirmed=>{
                    if(confirmed) {
                        $.post("./includes/inventory.php?action=updateExist&dest=editSalesDiscount",{salesID:salesID, newDiscount:newDiscount, clientID:clientID, isFromClinic:isFromClinic, receiptDiscount:receiptDiscount}, function(data){
                            if(data=="updated") {
                                swal({
                                    title: "Success",
                                    text: "sales discount has been updated successfully",
                                    icon: "success",
                                    timer: 1500,
                                    button: false
                                }).then (value=>{
                                    // $(row).find('input.discount').val(newDiscount);
                                    catchClient4Recpt(clientID, clientName, '');
                                });
                            }
                        });
                    }
                });

            }
        }
    });
    return false;
}
function check_editReceipt() {
	var receiptID	= $("#receiptID").val();
	var salesNo		= $("#salesNo").val();
	var totalDue	= parseFloat($("#totalDue").val());
	var status		= $("#status").val();

	var txtAmount	= $("#txtAmount").val();
	var txtInWords	= $("#txtInWords").val();

	var slcBankID	= $("#slcBankID").val();
	var slcBankAcc	= $("#slcBankAcc").val();
	var txtCheque	= $("#txtCheque").val();

	var txtPaidBy	= $("#txtPaidBy").val();
	var txtRemarks	= $("#txtRemarks").val();
	var transDate   = $("#transDate").val();

	if(salesNo.length < 1) {
		$("#error1").css("display", "inline");
		$("#error1").html("Sales number is missing");
		return false;
	} else { clearErrors(); }

	if(status=="returned") {
		if(txtAmount.length < 1) {
			$("#error2").css("display", "inline");
			$("#error2").html("Amount value is missing");
			$("#txtAmount").addClass("highlight");
			if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.two").offset().top }, 'slow'); }
			return false;
		} else { clearErrors(); }
	} else {
		if(txtAmount.length < 1) {
			$("#error2").css("display", "inline");
			$("#error2").html("Amount value is missing");
			$("#txtAmount").addClass("highlight");
			if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.two").offset().top }, 'slow'); }
			return false;
		} else if(Number(txtAmount) < 0.1) {
			$("#error2").css("display", "inline");
			$("#error2").html("Amount must be greater than 0");
			$("#txtAmount").addClass("highlight");
			if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.two").offset().top }, 'slow'); }
			return false;
		} else if(parseFloat(txtAmount) > parseFloat(totalDue)) {
			$("#error2").css("display", "inline");
			$("#error2").html("Amount can't be more than $"+totalDue);
			$("#txtAmount").addClass("highlight");
			if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.two").offset().top }, 'slow'); }
			return false;
		} else { clearErrors(); }
	}

	if(slcBankID.length < 1) {
		$("#error3").css("display", "inline");
		$("#error3").html("Please select bank");
		$("#slcBankID").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.three").offset().top }, 'slow'); }
		return false;
	} else { clearErrors(); }

	if(slcBankAcc=="---" || slcBankAcc.length < 1) {
		$("#error3").css("display", "inline");
		$("#error3").html("Select bank account");
		$("#slcBankAcc").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.three").offset().top }, 'slow'); }
		return false;
	} else { clearErrors(); }

	if(txtPaidBy.length < 1) {
		$("#error4").css("display", "inline");
		$("#error4").html("This field can't be empty");
		$("#txtPaidBy").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.four").offset().top }, 'slow'); }
		return false;
	} else { clearErrors(); }

	$("label.process").css("display", "inline");
	$("#btnUpdate").attr("disabled", true);
	$("#btnUpdate").html("Wait...");

	$.post("./assets-and-shares/includes/finance.php?action=updateExist&dest=editReceipt", { receiptID:receiptID, salesNo:salesNo, txtAmount:txtAmount, txtInWords:txtInWords, slcBankID:slcBankID, slcBankAcc:slcBankAcc, txtCheque:txtCheque, txtPaidBy:txtPaidBy, txtRemarks:txtRemarks, transDate:transDate }, function(data) {
		$("label.process").css("display", "none");
		if(data=="updated") {
			swal({
				title: "Success!",
				text: "You updated receipt record successfully.",
				icon: "success",
				timer: 1500,
				button: false
			})
                .then(value=>{
					var params = '&task=finance&subtask=receipts&action=showInfo&recID='+receiptID;
					window.location = "./workplace.php?role="+myRole+params;
				}
			);
		} else {
			swal("Oops!", data, "error");
		}
		$("#btnUpdate").attr("disabled", false);
		$("#btnUpdate").html("Update");
	});
	return false;
}
function catchRecpt(recID) {
	$.post("./assets-and-shares/includes/finance.php?action=get_recInfo&dest=getRecpt", { recID:recID }, function(data) {
		$("div#foundNum").html('<label id="count">1</label> record has been selected.<span id="refresh"></span>');
		$("div#dataTable").html(data);
	});
	$("div.suggest").css("display", "none");
}
function delRecieptDetail(reference,type,amount,receiptDetID,receiptID) {
    swal({
        title: "Are you sure?",
        text: "You going to delete this sales receipt!",
        icon: "warning",
        dangerMode:true,
        buttons:["Cancel","Delete"]
    })
    .then(willDelete=>{
        if(willDelete) {
            $.post("./assets-and-shares/includes/finance.php?action=deleteRec&dest=delRecieptDetail", { reference:reference, type:type, amount:amount, receiptDetID:receiptDetID, receiptID:receiptID }, function(data) {
                if(data=="deleted") {
                    swal({
                        title: "Success!",
                        text: "Selected sales receipt record has been deleted.",
                        icon: "success",
                        timer: 1500,
                        button: false
                    })
                .then(value=>{
                        location.reload();
                    });

                } else {
                    swal("Oops", data, "error");
                }
            });
        }
    });
    return false;
}
function delReceipt(recID) {
	swal({
		title: "Are you sure?",
		text: "You going to delete this sales receipt!",
		icon: "warning",
        dangerMode:true,
        buttons:["Cancel","Delete"]
	})
    .then(willDelete=>{
        if(willDelete) {
    		$.post("./assets-and-shares/includes/finance.php?action=deleteRec&dest=delReceipt", { recID:recID }, function(data) {
    			if(data=="deleted") {
    				swal({
    					title: "Success!",
    					text: "Selected sales receipt record has been deleted.",
    					icon: "success",
    					timer: 1500,
    					button: false
    				})
                .then(value=>{
    					location.reload();
    				});

    			} else {
    				swal("Oops", data, "error");
    			}
    		});
        }
	});
	return false;
}


/* ---------------------------------------------------------------
---------------------------- payments ----------------------------
-----------------------------------------------------------------*/

function loadPayableExp(pageLimit, perPage, period) {
	$("#dataTable div#loading").css("display", "inline");
	var dataString = 'pageLimit='+ pageLimit+'&period='+ period+'&perPage='+ perPage;
	$.ajax({
		type: "POST",
		url: "./assets-and-shares/includes/finance.php?action=loadTable&dest=allPayableExp",
		data: dataString,
		cache: false,
		timeout: 2000,
		success: function(result){
			$("#dataTable div#loading").css("display", "none");
			$(".load_more_link").addClass('noneLink');
			$("#dataTable").append(result);
		},
	});
	return false;
}
function loadPayments(pageLimit, perPage, period) {
    $("#dataTable div#loading").css("display", "inline");
    var dataString = 'pageLimit='+ pageLimit+'&period='+ period+'&perPage='+ perPage;
    $.ajax({
        type: "POST",
        url: "./assets-and-shares/includes/finance.php?action=loadTable&dest=allPayments",
        data: dataString,
        cache: false,
        timeout: 2000,
        success: function(result){
            $("#dataTable div#loading").css("display", "none");
            $(".load_more_link").addClass('noneLink');
            $("#dataTable").append(result);
        },
    });
    return false;
}
function loadPrchseBill(pageLimit, perPage, period) {
	$("#dataTable div#loading").css("display", "inline");
	var dataString = 'pageLimit='+ pageLimit+'&period='+ period+'&perPage='+ perPage;
	$.ajax({
		type: "POST",
		url: "./assets-and-shares/includes/finance.php?action=loadTable&dest=allPrchseBill",
		data: dataString,
		cache: false,
		timeout: 2000,
		success: function(result){
            /*$("#dataTable div#loading").css("display", "none");
            $(".load_more_link").addClass('noneLink');
            $("#dataTable").append(result);*/
            console.log(result);
            let found = JSON.parse(result);

            $('label#count').html(found.rowsFound)

            let columns = [];
            let dataset = found.dataset;

            function setLinks4Load(row) {
                let actions = '';
                if(row.payType != 'VAT') {
                    actions += `<a class="view fa fa-eye" href="${row.showLink}"></a>`;
                    actions += `<a class="view fa fa-pencil" href="${row.updateLink}"></a>`
                    actions += `<a class="view fa fa-trash masax rec${row.payID}" onclick="delPayment(${row.payID})" ></a>`
                }
            }

            columns = [
                {"title": "Action", "className": "gl-3", "render": function(data, type, row, meta) {
                    return `<div class="cave button">
                        ${setLinks4Load(row)}
                    </div>`;
                }},

                {"title": "PV Number", "data" : "addedDate", "className": "gl-2",  "render": function(data, type, row, meta) {
                    return `<div>
                        <a href="${row.showLink}">${row.pvNumber}</a>
                    </div>`;
                }},

                {"title": "Paid To", "data" : "invoiceNo", "className": "gl-2",  "render": function(data, type, row, meta) {
                    return `<div>${row.paidTo}</div>`;
                }},

                {"title": "Amount", "data" : "clientName", "className": "gl-2",  "render": function(data, type, row, meta) {
                    return `<p>${format_moneyOne(row.amount)}</p>`;
                }},

                {"title": "Account Details", "data" : "invoiceNo", "className": "gl-2",  "render": function(data, type, row, meta) {
                    return `<div>${row.details}</div>`;
                }},
            ]

            // console.log(columns)

            // return false;
            let dataTable = new DataTable('#allPurchaseBills', {
                data: dataset,
                paging: true,
                "bDestroy": true,
                "columns": columns
            })
        },
	});
	return false;
}
function catchPayment(recID) {
	$.post("./assets-and-shares/includes/finance.php?action=get_recInfo&dest=getPayment", { recID:recID }, function(data) {
		$("div#foundNum").html('<label id="count">1</label> record has been selected.<span id="refresh"></span>');
		$("div#dataTable").html(data);
	});
	$("div.suggest").css("display", "none");
}
function simplifyFnceAdd(type) {
    if (type === undefined) { type = ""; }

	$("#slcBankID").change(function() {
		var bankID = $("#slcBankID").val();
		if(bankID=="") {
			$("#slcBankAcc").html('');
            $("#bankAccBalance").val(0);
		} else {
			$.post("./assets-and-shares/includes/finance.php?action=searchRec&dest=myBankAccs", { bankID: bankID, type: type }, function(data) {
                $("#slcBankAcc").html(data);
                if(data!=""){
                    var bankAccID = $("#slcBankAcc").val();
                    if(bankAccID!="" && bankAccID!="---") {//alert(bankAccID)
                         $.post("./assets-and-shares/includes/finance.php?action=searchRec&dest=getAccBalance", { bankAccID: bankAccID }, function(data) {
                            $("#bankAccBalance").val(data);
                         });
                    }else {$("#bankAccBalance").val(0);}

                } else {$("#bankAccBalance").val(0);}
			});
		}
	});
    $("#slcBankAcc").change(function() {
        var bankAccID = $("#slcBankAcc").val();
        if(bankAccID=="" || bankAccID=="---") {
            $("#bankAccBalance").val();
        } else {
            $.post("./assets-and-shares/includes/finance.php?action=searchRec&dest=getAccBalance", { bankAccID: bankAccID }, function(data) {
                $("#bankAccBalance").val(data);
            });
        }
    });
	$("#txtAmount").keyup(function() {
		inWords($("#txtAmount").val());
	});
	$("#txtAmount").change(function() {
		inWords($("#txtAmount").val());
	});
	//
	$("#txtRemarks").keyup(function(){
		return tweetFeed(this, 500);
	});
	//
	var yearago = Number(year)-1;
	var picker = new Pikaday({
		field: document.getElementById("transDate"),
		firstDay: 6,
		maxDate: new Date(today),
		yearRange: [yearago,year],
	});
}
//
function addExpenseAcc() {

    var accType     = "expense";//$("#accType").val();
    var accCode     = "";//$("#accCode").val();
    var payableExpense="";

    swal({
        title: "Add Expense Accunt",
        text: 'Give a name to this account',
        content: "input",
        buttons:["Cancel","Save"]
    })
    .then(accName=> {
        if (accName) {
            $.post("./includes/general.php?action=saveNew&dest=addFncAcc", { accName:accName, accType:accType,  payableExpense:payableExpense, accCode:accCode }, function(data) {
                var addedpos = data.search("added");
                $("label.process").css("display", "none");
                if(addedpos==0) {
                    var lastID = data.slice(6,21);
                    swal({
                        title: "Success!",
                        text: "You added "+accType+" account successfully.",
                        icon: "success",
                        timer: 1500,
                        button: false,
                    });
                    //
                    $.post("./assets-and-shares/includes/finance.php?action=get_recInfo&dest=getExpenseAcc", { lastID:lastID}, function(data) {
                        $("select#slcExpense").html(data);
                     });
                    //
                } else {
                    swal("Oops!", data, "error");
                }
                $("#btnSave").attr("disabled", false);
                $("#btnSave").html("Save");
            });
        }
    });
    return false;
}
//
function addIncomeAcc() {

    var accType     = "income";//$("#accType").val();
    var accCode     = "";//$("#accCode").val();
    var payableExpense="";

    swal({
        title: "Add Income Accunt",
        text: 'Give a name to this account',
        content: "input",
        buttons:["Cancel","Save"]
    })
    .then(accName=> {
        if (accName) {
            $.post("./includes/general.php?action=saveNew&dest=addFncAcc", { accName:accName, accType:accType,  payableExpense:payableExpense, accCode:accCode }, function(data) {
                var addedpos = data.search("added");
                $("label.process").css("display", "none");
                if(addedpos==0) {
                    var lastID = data.slice(6,21);
                    swal({
                        title: "Success!",
                        text: "You added "+accType+" account successfully.",
                        icon: "success",
                        timer: 1500,
                        button: false,
                    });
                    //
                    $.post("./assets-and-shares/includes/finance.php?action=get_recInfo&dest=getIncomeAcc", { lastID:lastID}, function(data) {
                        $("select#slcIncAcc").html(data);
                     });
                    //
                } else {
                    swal("Oops!", data, "error");
                }
                $("#btnSave").attr("disabled", false);
                $("#btnSave").html("Save");
            });
        }
    });
    return false;
}
//
function smpfyAddPyment() {
	  callSumOSelect();
	window.asd = $('.SlectBox').SumoSelect({ });
	// if expense required
	$("select#slcPaidFor").change(function () {
        $("#txtAmount").removeAttr("readonly");
		$("div#divs4Expense, div#divs4Vendor, div#divs4ExtraPrchse, div#divs4VAT").css("display", "none");
		$("div.suggest, div.displayInfo").css("display", "none");
		$("select#slcExpense option:first").attr("selected", "selected");
		$("#vendorID, #prchseRef, #prchseBlnce, #txtVendorName, #prchseID, #prchseEBlnce, #txtPaidTo, #txtPrchseRef").val('');
		//
		var slcPaidFor = $("select#slcPaidFor").val();
		if(slcPaidFor=='expense') {
			$("div#divs4Expense").css("display", "inline");
				$("div#divs4PayableExpense").css("display", "none");
				$("div#vreceivable").css("display", "none");
			document.getElementById("beginBalance").checked = false;
			$("#switchBalance").removeClass("switchOn")
		} else if(slcPaidFor=='payable') {
			$("div#divs4PayableExpense").css("display", "inline");
			$("select#slcBankID option:first").attr("selected", "selected");
			$("select#slcBankAcc").html('');
			$("input#txtCheque").val('');
			$("div#vreceivable").css("display", "none");
			document.getElementById("beginBalance").checked = false;
			$("#switchBalance").removeClass("switchOn")
		}  else if(slcPaidFor=='vendor') {
			$("div#divs4Vendor").css("display", "inline");
			$("div#vreceivable").css("display", "inline");
			$("div#divs4PayableExpense").css("display", "none");
		} else if(slcPaidFor=='extraPrchse') {
			$("div#divs4ExtraPrchse").css("display", "inline");
			$("div#divs4PayableExpense").css("display", "none");
			$("#switchBalance").removeClass("switchOn");
			$("div#vreceivable").css("display", "none");
			$("div#divs4VAT").css("display", "none");
			document.getElementById("beginBalance").checked = false;
		} else if(slcPaidFor=='VAT') {
			$("div#divs4VAT").css("display", "inline");
			$("div#divs4PayableExpense").css("display", "none");
			$("#switchBalance").removeClass("switchOn");
			$("div#vreceivable").css("display", "none");
			document.getElementById("beginBalance").checked = false;
            $("input#txtAmount").attr("readonly","readonly");
		}
	});

    $("#checkBlnce, #switchBalance").click(function(){
        $('div#switchBalance').toggleClass("switchOn");
        if (document.getElementById("beginBalance").checked == true) {
            document.getElementById("beginBalance").checked = false;

        } else {
            document.getElementById("beginBalance").checked = true;
         	$("select#slcBankID option:first").attr("selected", "selected");
			$("select#slcBankAcc").html('');
			$("input#txtCheque").val('');
        }

    });
    $("input#txtAmount").keyup(function () {
    	var slcPaidFor = $("select#slcPaidFor").val();
    	var amount = parseFloat($("input#txtAmount").val());
    	var totalVAT = parseFloat($("input#totalVAT").val());
    	if(slcPaidFor=='VAT' && amount>totalVAT){
    		$("input#txtAmount").val(totalVAT);
    	}

    });
    //
    $("select#slcSalesVAT").change(function (){
    	var salesID = $("select#slcSalesVAT").val();
    	var totalVAT = parseFloat($("input#totalVAT").val());
    	$.post("./assets-and-shares/includes/finance.php?action=searchRec&dest=getSalesVAT", { salesID:salesID }, function(data) {
				$("input#txtAmount").val(data);
				inWords($("#txtAmount").val());
			});

    });
    //
	$("#slcBankID, #slcBankAcc").change(function() {
		$('div#switchBalance').removeClass("switchOn");
		document.getElementById("beginBalance").checked = false;

	});

	// if payable expense provided
	$("input#txtPayableExp").keyup(function () {
		$("#vendorID, #prchseRef, #prchseBlnce, #txtPaidTo").val('');
		$("div.displayInfo.vendor").css("display", "none");
		var paidTo	= $("#txtPayableExp").val();

		if(paidTo!="") {
			$("div.suggest.one").css("display", "table-row");
			$.post("./assets-and-shares/includes/finance.php?action=searchRec&dest=pickPaidTo4Pay", { paidTo:paidTo }, function(data) {
				$("div.suggest.one").html(data);
			});
		} else { $("div.suggest.one").css("display", "none"); }

		clearErrors();
	});
	// if vendor name provided
	$("input#txtVendorName").keyup(function () {
		$("#vendorID, #prchseRef, #prchseBlnce, #txtPaidTo").val('');
		$("div.displayInfo.vendor").css("display", "none");
		var vendorName	= $("#txtVendorName").val();
		var pvNumber 	= $("#pvNumber").val();
		var slcPaidFor 	= $("#slcPaidFor :selected").text();
		var activityType="purchase";
		if(slcPaidFor=="Supply Payment"){activityType="purchase-supply";}
		if(vendorName!="") {
			$("div.suggest.one").css("display", "table-row");
			$.post("./assets-and-shares/includes/finance.php?action=searchRec&dest=pickVendor4Pay", { vendorName:vendorName,activityType:activityType, pvNumber:pvNumber }, function(data) {
				$("div.suggest.one").html(data);
			});
		} else { $("div.suggest.one").css("display", "none"); }

		clearErrors();
	});
	// if purchase reference provided
	$("input#txtPrchseRef").keyup(function () {
		$("#prchseID, #prchseEBlnce, #txtPaidTo").val('');
		$("div.displayInfo.extraPrchse").css("display", "none");
		var passedVal	= $("#txtPrchseRef").val();
		var pvNumber 	= $("#pvNumber").val();
		if(passedVal!="") {
			$("div.suggest.two").css("display", "table-row");
			$.post("./assets-and-shares/includes/finance.php?action=searchRec&dest=pickPrchsRefInPay", { passedVal:passedVal, pvNumber:pvNumber }, function(data) {
				$("div.suggest.two").html(data);
			});
		} else { $("div.suggest.two").css("display", "none"); }
		clearErrors();
	});
}
function catchPaidTo4Pay(generateID, paidTo, expenseAccID, balance) {
	$("input#generateID").val(generateID);
	$("input#txtPayableExp").val(paidTo);
	$("input#txtPaidTo").val(paidTo);
	$("input#balance").val(balance);
	$("input#txtAmount").val(balance);
	inWords($("#txtAmount").val());

	$("div.suggest").css("display", "none");
}
function catchVendor4Pay(vndID, fullname, phone, balance) {
	$("input#vendorID").val(vndID);
	$("input#txtVendorName").val(fullname);
	$("input#txtPaidTo").val(fullname);
	$("div.displayInfo.vendor").css("display", "inline");
	$("p#pvndName").html(fullname);
	$("p#pvndPhone").html(phone);
	if(balance>0) {
		$("p#pvndBlnce").html('$'+balance);
	} else {
		$("p#pvndBlnce").html(balance);
	}
	$("div.suggest").css("display", "none");
}
function catchExtraPrchs(prchseID,prchaseRef,ttlCost,balance) {
	$("input#prchseID").val(prchseID);
	$("input#prchseEBlnce").val(balance);
	$("input#txtPrchseRef").val(prchseID);
	$("input#txtPaidTo").val('');
	$("div.displayInfo.extraPrchse").css("display", "inline");
	$("p#pERef").html(prchaseRef);
	$("p#pETotal").html('$'+ttlCost);
	$("input#prchseEBlnce").val(balance);
	if(balance>0) {
		$("p#pEBlnce").html('$'+balance);
	} else {
		$("p#pEBlnce").html(balance);
	}
	$("div.suggest.two").css("display", "none");
}
function check_addPayableExpense() {

	var slcExpense		= $("#slcExpense").val();
	var txtAmount		= $("#txtAmount").val();
	var txtInWords		= $("#txtInWords").val();
	var txtPaidTo		= $("#txtPaidTo").val();
	var txtRemarks		= $("#txtRemarks").val();
	var transDate		= $("#transDate").val();


	if(slcExpense=="") {
		$("#error1").css("display", "inline");
		$("#error1").html("Please select expense");
		$("#slcExpense").addClass("highlight");
		return false;
	} else { clearErrors(); }

	if(txtAmount.length < 1) {
		$("#error4").css("display", "inline");
		$("#error4").html("Amount value is missing");
		$("#txtAmount").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.three").offset().top }, 'slow'); }
		return false;
	} else if(Number(txtAmount) < 0.1) {
		$("#error4").css("display", "inline");
		$("#error4").html("Amount must be greater than 0");
		$("#txtAmount").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.three").offset().top }, 'slow'); }
		return false;
	} else { clearErrors(); }


	if(txtPaidTo.length < 1) {
		$("#error6").css("display", "inline");
		$("#error6").html("This field can't be empty");
		$("#txtPaidTo").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.five").offset().top }, 'slow'); }
		return false;
	} else { clearErrors(); }


	$("label.process").css("display", "inline");
	$("#btnSave").attr("disabled", true);
	$("#btnSave").html("Wait...");

	$.post("./assets-and-shares/includes/finance.php?action=saveNew&dest=addPayableExpense", {  slcExpense:slcExpense,txtAmount:txtAmount, txtInWords:txtInWords, txtPaidTo:txtPaidTo, txtRemarks:txtRemarks,transDate:transDate }, function(data) {
		var addedpos = data.search("added");
		$("label.process").css("display", "none");

		if(addedpos==0) {
			var lastID = data.slice(6,21);
			swal({
				title: "Success!",
				text: "You added payable expense record successfully.",
				icon: "success",
				timer: 1500,
				button: false
			})
                .then(value=>{
					var params = '&task=finance&subtask=payableExpense&action=showInfo&recID='+lastID;
					window.location = "./workplace.php?role="+myRole+params;
				}
			);
		}  else {
			swal("Oops!", data, "error");
		}
		$("#btnSave").attr("disabled", false);
		$("#btnSave").html("Save");
	});
	return false;
}function check_editPayableExpense() {

	var generateID		= $("#generateID").val();
	var slcExpense		= $("#slcExpense").val();
	var txtAmount		= $("#txtAmount").val();
	var txtInWords		= $("#txtInWords").val();
	var txtPaidTo		= $("#txtPaidTo").val();
	var txtRemarks		= $("#txtRemarks").val();
	var transDate		= $("#transDate").val();


	if(slcExpense=="") {
		$("#error1").css("display", "inline");
		$("#error1").html("Please select expense");
		$("#slcExpense").addClass("highlight");
		return false;
	} else { clearErrors(); }

	if(txtAmount.length < 1) {
		$("#error4").css("display", "inline");
		$("#error4").html("Amount value is missing");
		$("#txtAmount").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.three").offset().top }, 'slow'); }
		return false;
	} else if(Number(txtAmount) < 0.1) {
		$("#error4").css("display", "inline");
		$("#error4").html("Amount must be greater than 0");
		$("#txtAmount").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.three").offset().top }, 'slow'); }
		return false;
	} else { clearErrors(); }


	if(txtPaidTo.length < 1) {
		$("#error6").css("display", "inline");
		$("#error6").html("This field can't be empty");
		$("#txtPaidTo").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.five").offset().top }, 'slow'); }
		return false;
	} else { clearErrors(); }


	$("label.process").css("display", "inline");
	$("#btnSave").attr("disabled", true);
	$("#btnSave").html("Wait...");

	$.post("./assets-and-shares/includes/finance.php?action=updateExist&dest=editPayableExpense", {generateID:generateID, slcExpense:slcExpense,txtAmount:txtAmount, txtInWords:txtInWords, txtPaidTo:txtPaidTo, txtRemarks:txtRemarks,transDate:transDate }, function(data) {

		$("label.process").css("display", "none");

		if(data=="updated") {

			swal({
				title: "Success!",
				text: "You updated payable expense record successfully.",
				icon: "success",
				timer: 1500,
				button: false
			})
                .then(value=>{
					var params = '&task=finance&subtask=payableExpense&action=showInfo&recID='+generateID;
					window.location = "./workplace.php?role="+myRole+params;
				}
			);
		}  else {
			swal("Oops!", data, "error");
		}
		$("#btnSave").attr("disabled", false);
		$("#btnSave").html("Save");
	});
	return false;
}
//
function check_addPayment() {

	var expenseType 	= $("#slcPaidFor").val();
	var slcExpense		= $("#slcExpense").val();
	var generateID 		= $("#generateID ").val();
	var vendorName		= $("#txtVendorName").val();
	var vendorID		= $("#vendorID").val();
	//
	var salesID			= "";//$("#slcSalesVAT").val();
	var txtPrchseRef	= $("#txtPrchseRef").val();
	var prchseID		= $("#prchseID").val();
	var prchseEBlnce	= parseFloat($("#prchseEBlnce").val());
	var txtAmount		= $("#txtAmount").val();
	var txtInWords		= $("#txtInWords").val();
	var slcBankID		= $("#slcBankID").val();
	var slcBankAcc		= $("#slcBankAcc").val();
	var txtCheque		= $("#txtCheque").val();
	var txtCheque		= $("#txtCheque").val();
	var txtPaidTo		= $("#txtPaidTo").val();
	var txtRemarks		= $("#txtRemarks").val();
	var transDate		= $("#transDate").val();
	var slcPaidFor 	= $("#slcPaidFor :selected").text();
	var activityType="purchase"

	var beginBalance	= $("input#beginBalance:checked").val();
	if(beginBalance!="on") { var beginBalance="no"; } else { var beginBalance="yes"; }

	if(slcPaidFor=="Supply Payment"){
		activityType="supply"
	}
	var payableExpense	= $("input#payableExpense:checked").val();
	if(payableExpense!="on") { var expType=""; } else { var expType="payable"; }

	if(expenseType=="expense") {
		if(slcExpense=="") {
			$("#error1").css("display", "inline");
			$("#error1").html("Please select expense");
			$("#slcExpense").addClass("highlight");
			if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.two").offset().top }, 'slow'); }
			return false;
		} else { clearErrors(); }

	} else if(expenseType=="payable") {
		if(generateID .length < 1 || txtPayableExp.length < 1) {
			$("#error2").css("display", "inline");
			$("#error2").html("Please select payable expense payee");
			$("#txtPayableExp").addClass("highlight");
			$("div.suggest").css("display", "none");
			if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.two").offset().top }, 'slow'); }
			return false;
		} else { clearErrors(); }

	} else if(expenseType=="vendor") {
		if(vendorID.length < 1 || vendorName.length < 1) {
			$("#error2").css("display", "inline");
			$("#error2").html("Please select vendor");
			$("#txtVendorName").addClass("highlight");
			$("div.suggest").css("display", "none");
			if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.two").offset().top }, 'slow'); }
			return false;
		} else { clearErrors(); }

	} else if(expenseType=="extraPrchse") {
		if(prchseID.length < 1 || txtPrchseRef.length < 1) {
			$("#error3").css("display", "inline");
			$("#error3").html("Please select purchase number");
			$("#txtPrchseRef").addClass("highlight");
			$("div.suggest").css("display", "none");
			if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.two").offset().top }, 'slow'); }
			return false;
		} else { clearErrors(); }
	} else if(expenseType=="VAT") {
		if(salesID.length < 1 || salesID.length < 1) {
			$("#error3").css("display", "inline");
			$("#error3").html("Please select sales number");
			$("#slcSalesVAT").addClass("highlight");
			return false;
		} else { clearErrors(); }
	}

	if(txtAmount.length < 1) {
		$("#error4").css("display", "inline");
		$("#error4").html("Amount value is missing");
		$("#txtAmount").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.three").offset().top }, 'slow'); }
		return false;
	} else if(Number(txtAmount) < 0.1) {
		$("#error4").css("display", "inline");
		$("#error4").html("Amount must be greater than 0");
		$("#txtAmount").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.three").offset().top }, 'slow'); }
		return false;
	} else { clearErrors(); }

	if(expenseType=="extraPrchse") {
		if(Number(txtAmount) > prchseEBlnce) {
			$("#error4").css("display", "inline");
			$("#error4").html("Amount can't be greater than $"+prchseEBlnce);
			$("#txtAmount").addClass("highlight");
			if(window.innerWidth<=768) {
				$('html, body').animate({ scrollTop: $(".record.three").offset().top }, 'slow'); }
			return false;
		} else { clearErrors(); }
	}

    if(beginBalance=="no" ) {
    	if(slcBankID.length < 1) {
    		$("#error5").css("display", "inline");
    		$("#error5").html("Please select bank");
    		$("#slcBankID").addClass("highlight");
    		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.four").offset().top }, 'slow'); }
    		return false;
    	} else { clearErrors(); }

    	if(slcBankAcc=="---" || slcBankAcc.length < 1) {
    		$("#error5").css("display", "inline");
    		$("#error5").html("Select bank account");
    		$("#slcBankAcc").addClass("highlight");
    		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.four").offset().top }, 'slow'); }
    		return false;
    	} else { clearErrors(); }
    }


	if(expenseType!="extraPrchse") {
		if(txtPaidTo.length < 1) {
			$("#error6").css("display", "inline");
			$("#error6").html("This field can't be empty");
			$("#txtPaidTo").addClass("highlight");
			if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.five").offset().top }, 'slow'); }
			return false;
		} else { clearErrors(); }
	}
    if(beginBalance!="no" ) {bankAcc="begin balance";} else {bankAcc=slcBankAcc;}
	   swal({
        title: "Are you sure?",
        text: "You going to pay new payment for \n\
        "+expenseType+" and the amount paying is $"+txtAmount+"\n\
        and the payment bank account is "+bankAcc,
        icon: "warning",
        dangerMode:true,
        buttons:["Cancel","Pay Now"]
    })
    .then(isConfirm=>{
        if(isConfirm) {
            $("label.process").css("display", "inline");
            $("#btnSave").attr("disabled", true);
            $("#btnSave").html("Wait...");

	$.post("./assets-and-shares/includes/finance.php?action=saveNew&dest=addPayment", { beginBalance:beginBalance, expenseType:expenseType, slcExpense:slcExpense, generateID:generateID,  vendorID:vendorID, prchseID:prchseID, salesID:salesID, txtAmount:txtAmount, txtInWords:txtInWords, slcBankID:slcBankID, slcBankAcc:slcBankAcc, txtCheque:txtCheque, txtPaidTo:txtPaidTo, txtRemarks:txtRemarks, activityType:activityType , transDate:transDate }, function(data) {
		var addedpos = data.search("added");
		$("label.process").css("display", "none");

		if(addedpos==0) {
			var lastID = data.slice(6,21);
			swal({
				title: "Success!",
				text: "You added payment record successfully.",
				icon: "success",
				timer: 1500,
				button: false
			})
                .then(value=>{
					if(beginBalance=="no"){
                        if(expenseType=="vendor") {
        					var params = '&task=purchase&subtask=prchseBill&action=showInfo&recID='+lastID;
        					window.location = "./workplace.php?role="+myRole+params;
                        } else {
                            var params = '&task=finance&subtask=payments&action=showInfo&recID='+lastID;
                            window.location = "./workplace.php?role="+myRole+params;
                        }
    				} else {
    					var params = '&task=purchase&subtask=prchseBill';
    					window.location = "./workplace.php?role="+myRole+params;
    				}
				}
			);
		}  else {
			swal("Oops!", data, "error");
		}
		$("#btnSave").attr("disabled", false);
		$("#btnSave").html("Save");
	});
    }
    });
    return false;
}
function check_editPayment() {
	var payID			= $("#payID").val();
	var pvNumber		= $("#pvNumber").val();
	var expenseType 	= $("#slcPaidFor").val();
	var slcExpense		= $("#slcExpense").val();
	var vendorName		= $("#txtVendorName").val();
	var vendorID		= $("#vendorID").val();
	//
	var txtPrchseRef	= $("#txtPrchseRef").val();
	var prchseID		= $("#prchseID").val();
	var prchseEBlnce	= parseFloat($("#prchseEBlnce").val());

	var txtAmount		= $("#txtAmount").val();
	var txtInWords		= $("#txtInWords").val();
	var slcBankID		= $("#slcBankID").val();
	var slcBankAcc		= $("#slcBankAcc").val();
	var txtCheque		= $("#txtCheque").val();
	var txtPaidTo		= $("#txtPaidTo").val();
	var txtRemarks		= $("#txtRemarks").val();
	var transDate		= $("#transDate").val();

	if(expenseType=="expense") {
		if(slcExpense=="") {
			$("#error1").css("display", "inline");
			$("#error1").html("Please select expense");
			$("#slcExpense").addClass("highlight");
			if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.two").offset().top }, 'slow'); }
			return false;
		} else { clearErrors(); }

	} else if(expenseType=="vendor") {
		if(vendorID.length < 1 || vendorName.length < 1) {
			$("#error2").css("display", "inline");
			$("#error2").html("Please select vendor");
			$("#txtVendorName").addClass("highlight");
			$("div.suggest").css("display", "none");
			if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.two").offset().top }, 'slow'); }
			return false;
		} else { clearErrors(); }

	} else if(expenseType=="extraPrchse") {
		if(prchseID.length < 1 || txtPrchseRef.length < 1) {
			$("#error3").css("display", "inline");
			$("#error3").html("Please select purchase number");
			$("#txtPrchseRef").addClass("highlight");
			$("div.suggest").css("display", "none");
			if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.two").offset().top }, 'slow'); }
			return false;
		} else { clearErrors(); }
	}

	if(txtAmount.length < 1) {
		$("#error4").css("display", "inline");
		$("#error4").html("Amount value is missing");
		$("#txtAmount").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.three").offset().top }, 'slow'); }
		return false;
	} else if(expenseType!="vendor") {
		if(Number(txtAmount) < 0.1) {
			$("#error4").css("display", "inline");
			$("#error4").html("Amount must be greater than 0");
			$("#txtAmount").addClass("highlight");
			if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.three").offset().top }, 'slow'); }
			return false;
		} else { clearErrors(); }
	}

	if(expenseType=="extraPrchse") {
		if(Number(txtAmount) > prchseEBlnce) {
			$("#error4").css("display", "inline");
			$("#error4").html("Amount can't be greater than $"+prchseEBlnce);
			$("#txtAmount").addClass("highlight");
			if(window.innerWidth<=768) {
				$('html, body').animate({ scrollTop: $(".record.three").offset().top }, 'slow'); }
			return false;
		} else { clearErrors(); }
	}

	if(slcBankID.length < 1) {
		$("#error5").css("display", "inline");
		$("#error5").html("Please select bank");
		$("#slcBankID").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.four").offset().top }, 'slow'); }
		return false;
	} else { clearErrors(); }

	if(slcBankAcc=="---" || slcBankAcc.length < 1) {
		$("#error5").css("display", "inline");
		$("#error5").html("Select bank account");
		$("#slcBankAcc").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.four").offset().top }, 'slow'); }
		return false;
	} else { clearErrors(); }

	if(expenseType!="extraPrchse") {
		if(txtPaidTo.length < 1) {
			$("#error6").css("display", "inline");
			$("#error6").html("This field can't be empty");
			$("#txtPaidTo").addClass("highlight");
			if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.five").offset().top }, 'slow'); }
			return false;
		} else { clearErrors(); }
	}

	$("label.process").css("display", "inline");
	$("#btnUpdate").attr("disabled", true);
	$("#btnUpdate").html("Wait...");

	$.post("./assets-and-shares/includes/finance.php?action=updateExist&dest=editPayment", { payID:payID, expenseType:expenseType, slcExpense:slcExpense, vendorID:vendorID, prchseID:prchseID, txtAmount:txtAmount, txtInWords:txtInWords, slcBankID:slcBankID, slcBankAcc:slcBankAcc, txtCheque:txtCheque, txtPaidTo:txtPaidTo, txtRemarks:txtRemarks, transDate:transDate }, function(data) {
		$("label.process").css("display", "none");
		if(data=="updated") {
			swal({
				title: "Success!",
				text: "You updated payment record successfully.",
				icon: "success",
				timer: 1500,
				button: false
			})
                .then(value=>{
                    if(expenseType=="vendor") {
                        var params = '&task=purchase&subtask=prchseBill&action=showInfo&recID='+payID;
                        window.location = "./workplace.php?role="+myRole+params;
                    } else {
                        var params = '&task=finance&subtask=payments&action=showInfo&recID='+payID;
                        window.location = "./workplace.php?role="+myRole+params;
                    }

				}
			);
		} else {
			swal("Oops!", data, "error");
		}
		$("#btnUpdate").attr("disabled", false);
		$("#btnUpdate").html("Update");
	});
	return false;
}
function delPayableExp(recID) {
	swal({
		title: "Are you sure?",
		text: "You going to delete this payable expense!",
		icon: "warning",
        dangerMode:true,
        buttons:["Cancel","Delete"]
	})
    .then(willDelete=>{
        if(willDelete) {
    		$.post("./assets-and-shares/includes/finance.php?action=deleteRec&dest=delPayableExpense", { recID:recID }, function(data) {
    			if(data=="deleted") {
    				swal({
    					title: "Success!",
    					text: "Selected payment record has been deleted.",
    					icon: "success",
    					timer: 1500,
    					button: false
    				});
    				var count = $("label#count").html();
    				$("label#count").html(count-1);
    				$("a.masax.rec"+recID).parents("#record").fadeOut(500);
    			} else {
    				swal("Oops", data, "error");
    			}
    		});
        }
	});
	return false;
}
//
function delPayment(recID) {
	swal({
		title: "Are you sure?",
		text: "You going to delete this payment!",
		icon: "warning",
        dangerMode:true,
        buttons:["Cancel","Delete"]
	})
    .then(willDelete=>{
        if(willDelete) {
    		$.post("./assets-and-shares/includes/finance.php?action=deleteRec&dest=delPayment", { recID:recID }, function(data) {
    			if(data=="deleted") {
    				swal({
    					title: "Success!",
    					text: "Selected payment record has been deleted.",
    					icon: "success",
    					timer: 1500,
    					button: false
    				});
    				location.reload();
    			} else {
    				swal("Oops", data, "error");
    			}
    		});
        }
	});
	return false;
}


/* ---------------------------------------------------------------
-------------------------- Refunds --------------------------
-----------------------------------------------------------------*/

function loadRefunds(pageLimit, perPage, period) {
	$("#dataTable div#loading").css("display", "inline");
	var dataString = 'pageLimit='+ pageLimit+'&period='+ period+'&perPage='+ perPage;
	$.ajax({
		type: "POST",
		url: "./assets-and-shares/includes/finance.php?action=loadTable&dest=allRefunds",
		data: dataString,
		cache: false,
		timeout: 2000,
		success: function(result){
			$("#dataTable div#loading").css("display", "none");
			$(".load_more_link").addClass('noneLink');
			$("#dataTable").append(result);
            console.log(result)
		},
	});
	return false;
}
function check_refundCash(){
	var clientID		= $("#clientID").val();
	var ReturnSumID     = $("#ReturnSumID").val();
	var salesSumID      = $("#salesSumID").val();
	var txtClient		= $("#txtClient").val();
	var cashReturn		= $("#cashReturn").val();
	var slcBankID		= $("#slcBankID").val();
	var slcBankAcc		= $("#slcBankAcc").val();
	var txtCheque       = $("#txtCheque").val();
	var transDate		= $("#transDate").val();


	if(clientID.length < 1 || txtClient.length < 1) {
			$("#error1").css("display", "inline");
			$("#error1").html("Please Write "+typeLabel+" Name");
			$("#txtClient").addClass("highlight");
			if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.two").offset().top }, 'slow'); }
			return false;
		} else { clearErrors(); }

	if(cashReturn.length < 1) {
		$("#error2").css("display", "inline");
		$("#error2").html("Cash to Return is missing");
		$("#cashReturn").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.three").offset().top }, 'slow'); }
		return false;
	}

	if(slcBankID.length < 1) {
		$("#error3").css("display", "inline");
		$("#error3").html("Please select bank");
		$("#slcBankID").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.four").offset().top }, 'slow'); }
		return false;
	} else { clearErrors(); }

	if(slcBankAcc=="---" || slcBankAcc.length < 1) {
		$("#error3").css("display", "inline");
		$("#error3").html("Select bank account");
		$("#slcBankAcc").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.four").offset().top }, 'slow'); }
		return false;
	} else { clearErrors(); }

	$("label.process").css("display", "inline");
	$("#btnUpdate").attr("disabled", true);
	$("#btnUpdate").html("Wait...");

	$.post("./assets-and-shares/includes/finance.php?action=updateExist&dest=refundCash", { clientID:clientID, salesSumID:salesSumID, ReturnSumID:ReturnSumID,  clientName:txtClient,  cashReturn:cashReturn, slcBankID:slcBankID, slcBankAcc:slcBankAcc, txtCheque:txtCheque,  transDate:transDate }, function(data) {
		$("label.process").css("display", "none");
		if(data=="updated") {
			swal({
				title: "Success!",
				text: "You Refund cash record successfully.",
				icon: "success",
				timer: 1500,
				button: false
			})
                .then(value=>{
					var params = '&task=finance&subtask=refunds';
					window.location = "./workplace.php?role="+myRole+params;
				}
			);
		} else {
			swal("Oops!", data, "error");
		}
		$("#btnUpdate").attr("disabled", false);
		$("#btnUpdate").html("Update");
	});
	return false;
}
function catchRefund(recID) {
	$.post("./assets-and-shares/includes/finance.php?action=get_recInfo&dest=getRefund", { recID:recID }, function(data) {
		$("div#foundNum").html('<label id="count">1</label> record has been selected.<span id="refresh"></span>');
		$("div#dataTable").html(data);
	});
	$("div.suggest").css("display", "none");
}
/* ---------------------------------------------------------------
-------------------------- other income --------------------------
-----------------------------------------------------------------*/

function loadOthrInc(pageLimit, perPage, period) {
	$("#dataTable div#loading").css("display", "inline");
	var dataString = 'pageLimit='+ pageLimit+'&period='+ period+'&perPage='+ perPage;
	$.ajax({
		type: "POST",
		url: "./assets-and-shares/includes/finance.php?action=loadTable&dest=allOthrInc",
		data: dataString,
		cache: false,
		timeout: 2000,
		success: function(result){
			$("#dataTable div#loading").css("display", "none");
			$(".load_more_link").addClass('noneLink');
			$("#dataTable").append(result);
		},
	});
	return false;
}

function check_addOthrInc() {
	var slcIncAcc	= $("#slcIncAcc").val();
	var slcBankID	= $("#slcBankID").val();
	var slcBankAcc	= $("#slcBankAcc").val();
	var txtCheque	= $("#txtCheque").val();
	var txtReceived	= $("#txtReceived").val();
	var txtAmount	= $("#txtAmount").val();
	var txtInWords	= $("#txtInWords").val();
	var txtRemarks	= $("#txtRemarks").val();
	var transDate	= $("#transDate").val();

	if(slcIncAcc.length < 1) {
		$("#error1").css("display", "inline");
		$("#error1").html("Please select income account");
		$("#slcIncAcc").addClass("highlight");
		return false;
	} else { clearErrors(); }

	if(slcBankID.length < 1) {
		$("#error2").css("display", "inline");
		$("#error2").html("Please select bank");
		$("#slcBankID").addClass("highlight");
		return false;
	} else { clearErrors(); }

	if(slcBankAcc=="---" || slcBankAcc.length < 1) {
		$("#error2").css("display", "inline");
		$("#error2").html("Select bank account");
		$("#slcBankAcc").addClass("highlight");
		return false;
	} else { clearErrors(); }

	if(txtReceived.length < 1) {
		$("#error3").css("display", "inline");
		$("#error3").html("This field can't be empty");
		$("#txtReceived").addClass("highlight");
		return false;
	} else { clearErrors(); }

	if(txtAmount.length < 1) {
		$("#error4").css("display", "inline");
		$("#error4").html("Amount value is missing");
		$("#txtAmount").addClass("highlight");
		return false;
	} else if(Number(txtAmount) < 0.1) {
		$("#error4").css("display", "inline");
		$("#error4").html("Amount must be greater than 0");
		$("#txtAmount").addClass("highlight");
		return false;
	} else { clearErrors(); }

	$("label.process").css("display", "inline");
	$("#btnSave").attr("disabled", true);
	$("#btnSave").html("Wait...");

	$.post("./assets-and-shares/includes/finance.php?action=saveNew&dest=addOtherIncome", {  slcIncAcc:slcIncAcc, slcBankID:slcBankID, slcBankAcc:slcBankAcc, txtCheque:txtCheque, txtReceived:txtReceived,txtAmount:txtAmount, txtInWords:txtInWords, txtRemarks:txtRemarks, transDate:transDate }, function(data) {
		var addedpos = data.search("added");
		$("label.process").css("display", "none");
		if(addedpos==0) {
			var lastID = data.slice(6,21);
			swal({
				title: "Success!",
				text: "You added other income record successfully.",
				icon: "success",
				timer: 1500,
				button: false
			})
                .then(value=>{
					var params = '&task=general&subtask=othrIncome&action=showInfo&recID='+lastID;
					window.location = "./workplace.php?role="+myRole+params;
				}
			);
		} else {
			swal("Oops!", data, "error");
		}
		$("#btnSave").attr("disabled", false);
		$("#btnSave").html("Save");
	});
	return false;
}
function check_editOthrInc() {
	var receiptID	= $("#receiptID").val();
	var slcIncAcc	= $("#slcIncAcc").val();
	var slcBankID	= $("#slcBankID").val();
	var slcBankAcc	= $("#slcBankAcc").val();
	var txtCheque	= $("#txtCheque").val();
	var txtReceived	= $("#txtReceived").val();
	var txtAmount	= $("#txtAmount").val();
	var txtInWords	= $("#txtInWords").val();
	var txtRemarks	= $("#txtRemarks").val();
	var transDate   = $("#transDate").val();

	if(slcIncAcc.length < 1) {
		$("#error1").css("display", "inline");
		$("#error1").html("Please select income account");
		$("#slcIncAcc").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.four").offset().top }, 'slow'); }
		return false;
	} else { clearErrors(); }

	if(slcBankID.length < 1) {
		$("#error2").css("display", "inline");
		$("#error2").html("Please select bank");
		$("#slcBankID").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.four").offset().top }, 'slow'); }
		return false;
	} else { clearErrors(); }

	if(slcBankAcc=="---" || slcBankAcc.length < 1) {
		$("#error2").css("display", "inline");
		$("#error2").html("Select bank account");
		$("#slcBankAcc").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.four").offset().top }, 'slow'); }
		return false;
	} else { clearErrors(); }

	if(txtReceived.length < 1) {
		$("#error3").css("display", "inline");
		$("#error3").html("This field can't be empty");
		$("#txtReceived").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.four").offset().top }, 'slow'); }
		return false;
	} else { clearErrors(); }

	if(txtAmount.length < 1) {
		$("#error4").css("display", "inline");
		$("#error4").html("Amount value is missing");
		$("#txtAmount").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.four").offset().top }, 'slow'); }
		return false;
	} else if(Number(txtAmount) < 0.1) {
		$("#error4").css("display", "inline");
		$("#error4").html("Amount must be greater than 0");
		$("#txtAmount").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.four").offset().top }, 'slow'); }
		return false;
	} else { clearErrors(); }

	$("label.process").css("display", "inline");
	$("#btnUpdate").attr("disabled", true);
	$("#btnUpdate").html("Wait...");

	$.post("./assets-and-shares/includes/finance.php?action=updateExist&dest=editOtherIncome", { receiptID:receiptID, slcIncAcc:slcIncAcc, slcBankID:slcBankID, slcBankAcc:slcBankAcc, txtCheque:txtCheque, txtReceived:txtReceived,txtAmount:txtAmount, txtInWords:txtInWords, txtRemarks:txtRemarks, transDate:transDate }, function(data) {
		$("label.process").css("display", "none");
		if(data=="updated") {
			swal({
				title: "Success!",
				text: "You updated other income record successfully.",
				icon: "success",
				timer: 1500,
				button: false
			})
                .then(value=>{
					var params = '&task=general&subtask=othrIncome&action=showInfo&recID='+receiptID;
					window.location = "./workplace.php?role="+myRole+params;
				}
			);
		} else {
			swal("Oops!", data, "error");
		}
		$("#btnUpdate").attr("disabled", false);
		$("#btnUpdate").html("Update");
	});
	return false;
}
function catchOthrInc(recID) {
	$.post("./assets-and-shares/includes/finance.php?action=get_recInfo&dest=getOthrIncome", { recID:recID }, function(data) {
		$("div#foundNum").html('<label id="count">1</label> record has been selected.<span id="refresh"></span>');
		$("div#dataTable").html(data);
	});
	$("div.suggest").css("display", "none");
}
function delOthrInc(recID) {
	swal({
		title: "Are you sure?",
		text: "You going to delete this other income!",
		icon: "warning",
        dangerMode:true,
        buttons:["Cancel","Delete"]
	})
    .then(willDelete=>{
        if(willDelete) {
    		$.post("./assets-and-shares/includes/finance.php?action=deleteRec&dest=delOthrInc", { recID:recID }, function(data) {
    			if(data=="deleted") {
    				swal({
    					title: "Success!",
    					text: "Selected other income record has been deleted.",
    					icon: "success",
    					timer: 1500,
    					button: false
    				})
                .then(value=>{
    					location.reload();
    				});

    			} else {
    				swal("Oops", data, "error");
    			}
    		});
        }
	});
	return false;
}

/* ---------------------------------------------------------------
------------------------ Acc/ receivable  ------------------------
-----------------------------------------------------------------*/

function loadRecvble(pageLimit, perPage, period) {
	$("#dataTable div#loading").css("display", "inline");
	var dataString = 'pageLimit='+ pageLimit+'&period='+ period+'&perPage='+ perPage;
	$.ajax({
		type: "POST",
		url: "./assets-and-shares/includes/finance.php?action=loadTable&dest=allRcvable",
		data: dataString,
		cache: false,
		timeout: 2000,
		success: function(result){
            /*$("#dataTable div#loading").css("display", "none");
            $(".load_more_link").addClass('noneLink');
            $("#dataTable").append(result);*/
            // console.log(result);
            let found = JSON.parse(result);

            $('label#count').html(found.rowsFound)

            let columns = [];
            let dataset = found.dataset;

            columns = [
                {"title": "Action", "className": "gl-3", "render": function(data, type, row, meta) {
                    return `<div class="cave button">
                        <a class="view fa fa-eye" href="${row.showLink}"></a>
                        <a class="view fa fa-pencil" href="${row.updateLink}"></a>
                    </div>`;
                }},

                {"title": "TR Number", "data" : "addedDate", "className": "gl-2",  "render": function(data, type, row, meta) {
                    return `<div>
                        <a href="${row.showLink}">${row.transRef}</a>
                    </div>`;
                }},

                {"title": typeLabel, "data" : "invoiceNo", "className": "gl-2",  "render": function(data, type, row, meta) {
                    return `<div>${row.clientName}</div>`;
                }},

                {"title": "Account Details", "data" : "invoiceNo", "className": "gl-2",  "render": function(data, type, row, meta) {
                    return `<div>${row.details}</div>`;
                }},

                {"title": "Amount", "data" : "clientName", "className": "gl-2",  "render": function(data, type, row, meta) {
                    return `<p>${format_moneyOne(row.amount)}</p>`;
                }},
            ]

            // console.log(columns)

            // return false;
            let dataTable = new DataTable('#allCustomersReceivables', {
                data: dataset,
                paging: true,
                "bDestroy": true,
                "columns": columns
            })
        },
	});
	return false;
}
function addClient() {
	var popCName = $("#popCName").val();
	var popCPhone = $("#popCPhone").val();
	var popCEmail = $("#popCEmail").val();

	if(popCName.length < 1) {
		$("#qalad1").css("display", "inline");
		$("#qalad1").html("Please type full name");
		$("#popCName").addClass("highlight");
		return false;
	} else { clearErrors(); }

	if(popCPhone.length < 1) {
		$("#qalad2").css("display", "inline");
		$("#qalad2").html("Don't forget phone number");
		$("#popCPhone").addClass("highlight");
		return false;
	} else { clearErrors(); }

	if(popCEmail.length > 0) {
		if(!popCEmail.match(emailExp)) {
			$("#qalad3").css("display", "inline");
			$("#qalad3").html("invalid email address");
			$("#popCEmail").addClass("highlight");
			return false;
		}
	} else { clearErrors(); }

	$("#btnAdd").attr("disabled", true);
	$("#btnAdd").html("wait...");
	$("div.suggest.one").css("display", "none");

	$.post("./assets-and-shares/includes/finance.php?action=saveNew&dest=addClient&addedBy="+myUser, { cname:popCName, cphone:popCPhone, cemail:popCEmail }, function(data) {
		var addedpos = data.search("added");
		if(addedpos==0) {
			var lastID = data.slice(6,21);
			//
			$("input#clientID").val(lastID);
			$("input#txtClient").val(popCName);
			$("p#pCName").html(popCName);
			$("p#pCPhone").html(popCPhone);
			$("p#pCBalance").html(0);
			$("div.displayInfo.client").css("display", "inline");
			$("#lean_overlay").fadeOut(200);
			$("div.popupContainer").css("display","none");
			swal({
				title: "Success!",
				text: "You added new "+typeLabel+" successfully.",
				icon: "success",
				timer: 1500,
				button: false
			});
			$("#popCName, #popCPhone, #popCEmail").val("");
		} else {
			swal("Oops!", data, "error");
		}
		$("#btnAdd").attr("disabled", false);
		$("#btnAdd").html("Add");
	});
	return false;
}
function search_client(page) {
	var txtClient = $("#txtClient").val();
	if(txtClient!="") {
		$("div.suggest.one").css("display", "table-row");
		$.post("./assets-and-shares/includes/finance.php?action=searchRec&dest=pickClient",{ passedValue:txtClient, page:page }, function(data) {
			$("div.suggest.one").html(data);
		});
	} else { $("div.suggest.one").css("display", "none"); }
	clearErrors();
}
function catchClient4form(clientID,clientName,phone,balance) {
    $("#clientID").val(clientID);
    $("p#pCName").html(clientName);
    $("#txtClient").val(clientName);
    $("p#pCPhone").html(phone);
    $("p#pCBalance").html('$'+balance);
    $("div.displayInfo.client").css("display", "inline");
    $("div.suggest.one").css("display", "none");
}
function catchClient4Rcvble(clientID,clientName,phone,arBalance,salesBalance,balance) {
	$("#clientID").val(clientID);
	$("p#pCName").html(clientName);
	$("#txtClient").val(clientName);
	$("p#pCPhone").html(phone);
    $("p#pCSHBalance").html('$'+arBalance);
    $("p#pCSLSBalance").html('$'+salesBalance);
	$("p#pCBalance").html('$'+balance);
	$("div.displayInfo.client").css("display", "inline");
	$("div.suggest.one").css("display", "none");
}
function check_addClient4pop() {
    var txtCName    = $("#txtCName").val();
    var slcGender   = $("#slcGender").val();
    var txtCPhone   = $("#txtCPhone").val();
    var txtCEmail   = $("#txtCEmail").val();
    var slcMaritalStatus    = $("#slcMaritalStatus").val();
    var txtCEmail   = $("#txtCEmail").val();
    var txtAge      = $("#txtAge").val();
    var slcAgeParam = $("#slcAgeParam").val();
    var txtAddress  = $("#txtAddress").val();
    var txtDOB      = $("#txtDOB").val();

    if(txtCName.length < 1) {
        $("#poperror21").css("display", "inline");
        $("#poperror21").html("Please type full name");
        $("#txtCName").addClass("highlight");
        return false;
    } else { clearErrors(); }

    if(txtCPhone.length < 1) {
        $("#poperror22").css("display", "inline");
        $("#poperror22").html("Don't forget phone number");
        $("#txtCPhone").addClass("highlight");
        return false;
    } else { clearErrors(); }

    if(txtCEmail.length > 0) {
        if(!txtCEmail.match(emailExp)) {
            $("#poperror23").css("display", "inline");
            $("#poperror23").html("invalid email address");
            $("#txtCEmail").addClass("highlight");
            return false;
        }
    } else { clearErrors(); }

    $("#btnAdd").attr("disabled", true);
    $("#btnAdd").html("wait...");

    $(".btnAdd").attr("disabled", true);
    $(".btnAdd").html("wait...");

    $("#btnAdd").attr("disabled", true);
    $("#btnAdd").html("wait...");
    $("div.suggest.one").css("display", "none");

    $.post("./includes/inventory.php?action=saveNew&dest=addClient4pop", { txtCName:txtCName, txtCPhone:txtCPhone, txtCEmail:txtCEmail, slcGender:slcGender, txtAge:txtAge, txtAddress:txtAddress, slcMaritalStatus:slcMaritalStatus, slcAgeParam:slcAgeParam, txtDOB:txtDOB }, function(data) {
        // console.log(data)
        let res = JSON.parse(data)
        if(res[0]== 'added') {
            let lastID = res[1].lastID;
            let code = res[1]._code;
            $("input#clientID").val(lastID);
            $("input#txtClient").val(txtCName);
            $("input#clientName").val(txtCName);
            $("input#clientCode").val(code);
            $("input#isCashCustomer").val("No");
            $("input.clientPhone").val(txtCPhone);
            $("input.email").val(txtCEmail);
            $("p#pCName").html(txtCName);
            $("p#pCPhone").html(txtCPhone);
            $("p#pCBalance").html(0);
            $("div.displayInfo.client").css("display", "inline");
            $("div.suggest").css("display", "none");
             $('input#addClientForm').prop('checked', false);
            swal({
                title: "Success!",
                text: "You added new "+typeLabel+" successfully.",
                icon: "success",
                timer: 1500,
                button: false
            });
            $("#txtCName, #txtCPhone, #txtCEmail").val("");
        } else {
            swal("Oops!", data, "error");
        }
        $("#btnAdd").attr("disabled", false);
        $("#btnAdd").html("Add");
    });
    return false;
}
function simplifyAddRecvble() {
    //
    $("#txtClient").keyup(function(){
        var txtClient = $("#txtClient").val();
        if(txtClient!="") {
            $("div.suggest.one").css("display", "table-row");
            $.post("./assets-and-shares/includes/finance.php?action=searchRec&dest=pickClient4Recvble",{ passedValue:txtClient}, function(data) {
                $("div.suggest.one").html(data);
            });
        } else { $("div.suggest.one").css("display", "none"); }
    });
    //
	$("#checkBlnce, #switchBalance").click(function(){
		$('div#switchBalance').toggleClass("switchOn");
		if (document.getElementById("beginBalance").checked == true) {
			document.getElementById("beginBalance").checked = false;
			$("#btnARReceive").attr("disabled",false);
		} else {
			document.getElementById("beginBalance").checked = true;
			$("#slcBankID option:first").attr("selected", "selected");
			$("#slcBankAcc").html('');
			$("#btnARReceive").attr("disabled",true);
		}
	});
	//
	$("#slcBankID, #slcBankAcc").change(function() {
		document.getElementById("beginBalance").checked = false;
		$('div#switchBalance').removeClass("switchOn");
	});
	// receive button
	$("#btnARReceive").click(function() {
		var actionType = "receive";
		insert_receivable(actionType); return false;
	});
	// pay button
	$("#btnARPay").click(function() {
		var actionType = "pay";
		insert_receivable(actionType); return false;
	});
}
function insert_receivable(actionType) {
	var clientID	= $("#clientID").val();
	var txtClient	= $("#txtClient").val();

    var slcPayTerms = $("#slcPayTerms").val();
	var sclRecvbleType	= $("#sclRecvbleType").val();
	var beginBalance	= $("input#beginBalance:checked").val();
	if(beginBalance!="on") { var beginBalance="no"; } else { var beginBalance="yes"; }

	var slcBankID	= $("#slcBankID").val();
	var slcBankAcc	= $("#slcBankAcc").val();
	var txtCheque	= $("#txtCheque").val();
	var txtAmount	= $("#txtAmount").val();
	var txtInWords	= $("#txtInWords").val();
	var txtRemarks	= $("#txtRemarks").val();
	var transDate	= $("#transDate").val();


	if(clientID.length < 1 || txtClient.length < 1) {
		$("#error1").css("display", "inline");
		$("#error1").html("Provide "+typeLabel+" name");
		$("#txtClient").addClass("highlight");
		$("div.suggest").css("display", "none");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.one").offset().top }, 'slow'); }
		return false;
	} else { clearErrors(); }

    if(sclRecvbleType.length < 1 || sclRecvbleType=="" || sclRecvbleType==null) {
        $("#error6").css("display", "inline");
        $("#error6").html("Please choose receivable type");
        $("#sclRecvbleType").addClass("highlight");
        if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.four").offset().top }, 'slow'); }
        return false;
    } else { clearErrors(); }

	if(beginBalance=="no") {
		if(slcBankID.length < 1) {
			$("#error2").css("display", "inline");
			$("#error2").html("Please select bank");
			$("#slcBankID").addClass("highlight");
			if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.three").offset().top }, 'slow'); }
			return false;
		} else { clearErrors(); }

		if(slcBankAcc=="---" || slcBankAcc.length < 1) {
			$("#error2").css("display", "inline");
			$("#error2").html("Select bank account");
			$("#slcBankAcc").addClass("highlight");
			if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.three").offset().top }, 'slow'); }
			return false;
		} else { clearErrors(); }
	}



	if(txtAmount.length < 1) {
		$("#error3").css("display", "inline");
		$("#error3").html("Type amount");
		$("#txtAmount").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.four").offset().top }, 'slow'); }
		return false;
	} else if(Number(txtAmount) < 0.1) {
		$("#error3").css("display", "inline");
		$("#error3").html("Amount must be greater than 0");
		$("#txtAmount").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.four").offset().top }, 'slow'); }
		return false;
	} else { clearErrors(); }

	$("label.process").css("display", "inline");
	if(actionType=="receive") {
		$("#btnARReceive").attr("disabled", true); $("#btnARReceive").html("Wait...");
	} else if(actionType=="pay") {
		$("#btnARPay").attr("disabled", true); $("#btnARPay").html("Wait...");
	}

	$.post("./assets-and-shares/includes/finance.php?action=saveNew&dest=addRcvable", { transType:actionType, clientID:clientID, clientName:txtClient, slcPayTerms:slcPayTerms, sclRecvbleType:sclRecvbleType, beginBalance:beginBalance, slcBankID:slcBankID, slcBankAcc:slcBankAcc, txtCheque:txtCheque, txtAmount:txtAmount, txtInWords:txtInWords, txtRemarks:txtRemarks, transDate:transDate }, function(data) {
		var addedpos = data.search("added");
		$("label.process").css("display", "none");
		if(addedpos==0) {
			var lastID = data.slice(6,21);
			swal({
				title: "Success!",
				text: "You added new record into account receivable.",
				icon: "success",
				timer: 1500,
				button: false
			})
                .then(value=>{
				if(beginBalance=="no"){
					window.location = "./workplace.php?role="+myRole+"&task=finance&subtask=receivable\
					&type="+actionType+"&action=showInfo&recID="+lastID;
				} else {
					window.location = "./workplace.php?role="+myRole+"&task=finance&subtask=receivable";
					}
				}
			);
		} else if(data=="dueBalance<amount") {
			swal("Oops!", "The amount received from "+txtClient+" \n is less than amount you just typed in.", "error");
			if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.four").offset().top }, 'slow'); }
		} else {
			swal("Oops!", data, "error");
		}
		if(actionType=="receive") {
			$("#btnARReceive").attr("disabled", false); $("#btnARReceive").html("Receive");
		} else if(actionType=="pay") {
			$("#btnARPay").attr("disabled", false); $("#btnARPay").html("Pay");
		}

	});
	return false;
}
function check_editRcvble() {
	var changedID	= $("#changedID").val();
	var transType	= $("#transType").val();
	var beginblnce	= $("#beginblnce").val();

	var clientID	= $("#clientID").val();
	var txtClient	= $("p#pCName").html();
	var slcPayTerms	= $("#slcPayTerms").val();
	var slcBankID	= $("#slcBankID").val();
	var slcBankAcc	= $("#slcBankAcc").val();
	var txtCheque	= $("#txtCheque").val();
	var txtAmount	= $("#txtAmount").val();
	var txtInWords	= $("#txtInWords").val();
	var txtRemarks	= $("#txtRemarks").val();

	if(clientID.length < 1) {
		$("#error1").css("display", "inline");
		$("#error1").html("Provide "+typeLabel+" name");
		$("#txtClient").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.one").offset().top }, 'slow'); }
		return false;
	} else { clearErrors(); }

	if(beginblnce!="beginblnce") {
		if(slcBankID.length < 1) {
			$("#error2").css("display", "inline");
			$("#error2").html("Please select bank");
			$("#slcBankID").addClass("highlight");
			if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.three").offset().top }, 'slow'); }
			return false;
		} else { clearErrors(); }

		if(slcBankAcc=="---" || slcBankAcc.length < 1) {
			$("#error2").css("display", "inline");
			$("#error2").html("Select bank account");
			$("#slcBankAcc").addClass("highlight");
			if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.three").offset().top }, 'slow'); }
			return false;
		} else { clearErrors(); }
	}

	if(txtAmount.length < 1) {
		$("#error3").css("display", "inline");
		$("#error3").html("Type amount");
		$("#txtAmount").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.four").offset().top }, 'slow'); }
		return false;
	} else if(Number(txtAmount) < 0.1) {
		$("#error3").css("display", "inline");
		$("#error3").html("Amount must be greater than 0");
		$("#txtAmount").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.four").offset().top }, 'slow'); }
		return false;
	} else { clearErrors(); }

	$("label.process").css("display", "inline");
	$("#btnUpdate").attr("disabled", true);
	$("#btnUpdate").html("Wait...");

	$.post("./assets-and-shares/includes/finance.php?action=updateExist&dest=editRcvable", { changedID:changedID, transType:transType, clientID:clientID, clientName:txtClient, beginblnce:beginblnce, slcPayTerms:slcPayTerms, slcBankID:slcBankID, slcBankAcc:slcBankAcc, txtCheque:txtCheque, txtAmount:txtAmount, txtInWords:txtInWords, txtRemarks:txtRemarks }, function(data) {
		$("label.process").css("display", "none");
		if(data=="updated") {
			swal({
				title: "Success!",
				text: "You updated account receivable details successfully.",
				icon: "success",
				timer: 1500,
				button: false
			})
                .then(value=>{
					window.location = "./workplace.php?role="+myRole+"&task=finance&subtask=receivable\
					&type="+transType+"&action=showInfo&recID="+changedID;
				}
			);
		} else if(data=="dueBalance<amount") {
			swal("Oops!", "The amount received from "+txtClient+" \n is less than amount you just typed in.", "error");
			if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.three").offset().top }, 'slow'); }
		} else {
			swal("Oops!", data, "error");
		}
		$("#btnUpdate").attr("disabled", false);
		$("#btnUpdate").html("Update");

	});
	return false;
}
function catchRecvble(recID) {
	$.post("./assets-and-shares/includes/finance.php?action=get_recInfo&dest=getRecvble", { recID:recID }, function(data) {
		$("div#foundNum").html('<label id="count">1</label> record has been selected.<span id="refresh"></span>');
		$("div#dataTable").html(data);
	});
	$("div.suggest").css("display", "none");
}
function delRcvable(recID) {
	swal({
		title: "Are you sure?",
		text: "You going to delete this account receivable!",
		icon: "warning",
        dangerMode:true,
        buttons:["Cancel","Delete"]
	})
    .then(willDelete=>{
        if(willDelete) {
    		$.post("./assets-and-shares/includes/finance.php?action=deleteRec&dest=delRcvable", { recID:recID }, function(data) {
    			if(data=="deleted") {
    				swal({
    					title: "Success!",
    					text: "Selected account receivable record has been deleted.",
    					icon: "success",
    					timer: 1500,
    					button: false
    				});
    				location.reload();
    			} else {
    				swal("Oops", data, "error");
    			}
    		});
        }
	});
	return false;
}


/* ---------------------------------------------------------------
-------------------------- Acc/ payable  -------------------------
-----------------------------------------------------------------*/

function loadPyable(pageLimit, perPage, period) {
	$("#dataTable div#loading").css("display", "inline");
	var dataString = 'pageLimit='+ pageLimit+'&period='+ period+'&perPage='+ perPage;
	$.ajax({
		type: "POST",
		url: "./assets-and-shares/includes/finance.php?action=loadTable&dest=allPayble",
		data: dataString,
		cache: false,
		timeout: 2000,
		success: function(result){
            /*$("#dataTable div#loading").css("display", "none");
            $(".load_more_link").addClass('noneLink');
            $("#dataTable").append(result);*/
            // console.log(result);
            let found = JSON.parse(result);

            $('label#count').html(found.rowsFound)

            let columns = [];
            let dataset = found.dataset;

            columns = [
                {"title": "Action", "className": "gl-3", "render": function(data, type, row, meta) {
                    return `<div class="cave button">
                        <a class="view fa fa-eye" href="${row.showLink}"></a>
                        <a class="view fa fa-pencil" href="${row.updateLink}"></a>
                    </div>`;
                }},

                {"title": "TR Number", "data" : "addedDate", "className": "gl-2",  "render": function(data, type, row, meta) {
                    return `<div>
                        <a href="${row.showLink}">${row.transRef}</a>
                    </div>`;
                }},

                {"title": "Supplier Name", "data" : "invoiceNo", "className": "gl-2",  "render": function(data, type, row, meta) {
                    return `<div>${row.vendor}</div>`;
                }},

                {"title": "Account Details", "data" : "invoiceNo", "className": "gl-2",  "render": function(data, type, row, meta) {
                    return `<div>${row.typeDetails}</div>`;
                }},

                {"title": "Amount", "data" : "clientName", "className": "gl-2",  "render": function(data, type, row, meta) {
                    return `<p>${format_moneyOne(row.amount)}</p>`;
                }},
            ]

            // console.log(columns)

            // return false;
            let dataTable = new DataTable('#allPayablesData', {
                data: dataset,
                paging: true,
                "bDestroy": true,
                "columns": columns
            })
        },
	});
	return false;
}
function check_addDeptHolder() {
	var txtDName = $("#txtDName").val();
	var txtDPhone = $("#txtDPhone").val();
	var txtDEmail = $("#txtDEmail").val();

	if(txtDName.length < 1) {
		$("#poperror1").css("display", "inline");
		$("#poperror1").html("Please type full name");
		$("#txtDName").addClass("highlight");
		return false;
	} else { clearErrors(); }

	if(txtDPhone.length < 1) {
		$("#poperror2").css("display", "inline");
		$("#poperror2").html("Don't forget phone number");
		$("#txtDPhone").addClass("highlight");
		return false;
	} else { clearErrors(); }

	if(txtDEmail.length > 0) {
		if(!txtDEmail.match(emailExp)) {
			$("#poperror3").css("display", "inline");
			$("#poperror3").html("invalid email address");
			$("#txtDEmail").addClass("highlight");
			return false;
		}
	} else { clearErrors(); }

	$(".btnAdd.deptHolder").attr("disabled", true);
	$(".btnAdd.deptHolder").html("wait...");
	$("div.suggest.one").css("display", "none");

	$.post("./assets-and-shares/includes/finance.php?action=saveNew&dest=addDeptHolder", { txtDName:txtDName, txtDPhone:txtDPhone, txtDEmail:txtDEmail }, function(data) {
		var addedpos = data.search("added");
		if(addedpos==0) {
			var lastID = data.slice(6,21);
			//
			$("input#deptID").val(lastID);
			$("input#txtDeptHolder").val(txtDName);
			$("p#pDName").html(txtDName);
			$("p#pDPhone").html(txtDPhone);
			$("p#pDBalance").html(0);
			$("div.displayInfo.deptHolder").css("display", "inline");
			 $('input#addDeptHolderForm').prop('checked', false);
			swal({
				title: "Success!",
				text: "You added new departure holder successfully.",
				icon: "success",
				timer: 1500,
				button: false
			});
			$("#txtDName, #txtDPhone, #txtDEmail").val("");
		} else {
			swal("Oops!", data, "error");
		}
		$("#btnAdd").attr("disabled", false);
		$("#btnAdd").html("Add");
	});
	return false;
}
function catchDeptHolder(depID,depName,depPhone,balance) {
	$("#vendorID").val(depID);
	$("p#pVName").html(depName);
	$("#txtVendorName").val(depName);
	$("p#pVPhone").html(depPhone);
	$("p#pVBalance").html('$'+balance);
    //
	$("div.displayInfo.vendor").css("display", "inline");
	$("div.suggest.one").css("display", "none");
}
function simplifyAddPyble() {   //
    $("#txtVendorName").keyup(function() {
        $("div.suggest").css("display", "none");
        var txtVendorName = $("#txtVendorName").val();
        if(txtVendorName.length > 0) {
            $("div.suggest.one").css("display", "table-row");
            $.post("./assets-and-shares/includes/finance.php?action=searchRec&dest=pickDeptHolder",{ passedValue:txtVendorName }, function(data) {
                $("div.suggest.one").html(data);
            });
        } else { $("div.suggest.one").css("display", "none"); }
        clearErrors();
    });
    //
    $("#checkBlnce, #switchBalance").click(function(){
        $('div#switchBalance').toggleClass("switchOn");
        if (document.getElementById("beginBalance").checked == true) {
            document.getElementById("beginBalance").checked = false;
            $("#btnARPay").attr("disabled",false);
        } else {
            document.getElementById("beginBalance").checked = true;
            $("#slcBankID option:first").attr("selected", "selected");
            $("#slcBankAcc").html('');
            $("#btnARPay").attr("disabled",true);
        }
    });
    //
    $("#slcBankID, #slcBankAcc").change(function() {
        document.getElementById("beginBalance").checked = false;
        $('div#switchBalance').removeClass("switchOn");
    });
    // receive button
    $("#btnARReceive").click(function() {
        var actionType = "receive";
        insert_payable(actionType); return false;
    });
    // pay button
    $("#btnARPay").click(function() {
        var actionType = "pay";
        insert_payable(actionType); return false;
    });
}

function insert_payable(actionType) {
	var deptID	= $("#vendorID").val();
	var txtDeptHolder	= $("#txtVendorName").val();

	var slcPayTerms	= $("#slcPayTerms").val();
	var beginBalance	= $("input#beginBalance:checked").val();
	if(beginBalance!="on") { var beginBalance="no"; } else { var beginBalance="yes"; }

	var slcBankID	= $("#slcBankID").val();
	var slcBankAcc	= $("#slcBankAcc").val();
	var txtCheque	= $("#txtCheque").val();
	var txtAmount	= $("#txtAmount").val();
	var txtInWords	= $("#txtInWords").val();
	var txtRemarks	= $("#txtRemarks").val();
	var transDate	= $("#transDate").val();

	if(beginBalance=="yes" && actionType=="pay") {
		clearErrors();
		swal("Oops!", "Only receive action can be used for begin balance", "error");
		return false;
	}
	if(deptID.length < 1 || txtDeptHolder.length < 1) {
		$("#error1").css("display", "inline");
		$("#error1").html("Provide departure holder");
		$("#txtVendorName").addClass("highlight");
		$("div.suggest").css("display", "none");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.one").offset().top }, 'slow'); }
		return false;
	} else { clearErrors(); }

	if(beginBalance=="no") {
		if(slcBankID.length < 1) {
			$("#error2").css("display", "inline");
			$("#error2").html("Please select bank");
			$("#slcBankID").addClass("highlight");
			if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.two").offset().top }, 'slow'); }
			return false;
		} else { clearErrors(); }

		if(slcBankAcc=="---" || slcBankAcc.length < 1) {
			$("#error2").css("display", "inline");
			$("#error2").html("Select bank account");
			$("#slcBankAcc").addClass("highlight");
			if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.two").offset().top }, 'slow'); }
			return false;
		} else { clearErrors(); }
	}

	if(txtAmount.length < 1) {
		$("#error3").css("display", "inline");
		$("#error3").html("Type amount");
		$("#txtAmount").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.three").offset().top }, 'slow'); }
		return false;
	} else if(Number(txtAmount) < 0.1) {
		$("#error3").css("display", "inline");
		$("#error3").html("Amount must be greater than 0");
		$("#txtAmount").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.three").offset().top }, 'slow'); }
		return false;
	} else { clearErrors(); }

	$("label.process").css("display", "inline");
	if(actionType=="receive") {
		$("#btnARReceive").attr("disabled", true); $("#btnARReceive").html("Wait...");
	} else if(actionType=="pay") {
		$("#btnARPay").attr("disabled", true); $("#btnARPay").html("Wait...");
	}

	$.post("./assets-and-shares/includes/finance.php?action=saveNew&dest=addPyble", { transType:actionType, deptID:deptID, txtDeptHolder:txtDeptHolder, beginBalance:beginBalance, slcPayTerms:slcPayTerms, slcBankID:slcBankID, slcBankAcc:slcBankAcc, txtCheque:txtCheque, txtAmount:txtAmount, txtInWords:txtInWords, txtRemarks:txtRemarks, transDate:transDate }, function(data) {
		var addedpos = data.search("added");
		$("label.process").css("display", "none");
		if(addedpos==0) {
			var lastID = data.slice(6,21);
			swal({
				title: "Success!",
				text: "You added new record into account payable.",
				icon: "success",
				timer: 1500,
				button: false
			})
                .then(value=>{
					if(beginBalance=="no"){
					window.location = "./workplace.php?role="+myRole+"&task=purchase&subtask=payable\
					&type="+actionType+"&action=showInfo&recID="+lastID;
				} else {
					window.location = "./workplace.php?role="+myRole+"&task=purchase&subtask=payable";
				}
				}
			);
		} else if(data=="dueBalance<amount") {
			swal("Oops!", "The amount received from "+txtClient+" \n is less than amount you just typed in.", "error");
			if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.four").offset().top }, 'slow'); }
		} else {
			swal("Oops!", data, "error");
		}
		if(actionType=="receive") {
			$("#btnARReceive").attr("disabled", false); $("#btnARReceive").html("Receive");
		} else if(actionType=="pay") {
			$("#btnARPay").attr("disabled", false); $("#btnARPay").html("Pay");
		}

	});
	return false;
}
function check_editPyable() {
	var changedID	= $("#changedID").val();
	var transType	= $("#transType").val();
	var beginblnce	= $("#beginblnce").val();

	var depID	= $("#depID").val();
	var txtDeptHolder	= $("#txtDeptHolder").val();
	var slcPayTerms	= $("#slcPayTerms").val();
	var slcBankID	= $("#slcBankID").val();
	var slcBankAcc	= $("#slcBankAcc").val();
	var txtCheque	= $("#txtCheque").val();
	var txtAmount	= $("#txtAmount").val();
	var txtInWords	= $("#txtInWords").val();
	var txtRemarks	= $("#txtRemarks").val();

	if(depID.length < 1) {
		$("#error1").css("display", "inline");
		$("#error1").html("Provide departure holder");
		$("#txtDeptHolder").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.one").offset().top }, 'slow'); }
		return false;
	} else { clearErrors(); }

	if(beginblnce!="beginblnce") {
		if(slcBankID.length < 1) {
			$("#error2").css("display", "inline");
			$("#error2").html("Please select bank");
			$("#slcBankID").addClass("highlight");
			if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.three").offset().top }, 'slow'); }
			return false;
		} else { clearErrors(); }

		if(slcBankAcc=="---" || slcBankAcc.length < 1) {
			$("#error2").css("display", "inline");
			$("#error2").html("Select bank account");
			$("#slcBankAcc").addClass("highlight");
			if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.three").offset().top }, 'slow'); }
			return false;
		} else { clearErrors(); }
	}

	if(txtAmount.length < 1) {
		$("#error3").css("display", "inline");
		$("#error3").html("Type amount");
		$("#txtAmount").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.four").offset().top }, 'slow'); }
		return false;
	} else if(Number(txtAmount) < 0.1) {
		$("#error3").css("display", "inline");
		$("#error3").html("Amount must be greater than 0");
		$("#txtAmount").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.four").offset().top }, 'slow'); }
		return false;
	} else { clearErrors(); }

	$("label.process").css("display", "inline");
	$("#btnUpdate").attr("disabled", true);
	$("#btnUpdate").html("Wait...");

	$.post("./assets-and-shares/includes/finance.php?action=updateExist&dest=editPyable", { changedID:changedID, transType:transType, depID:depID, txtDeptHolder:txtDeptHolder, beginblnce:beginblnce, slcPayTerms:slcPayTerms, slcBankID:slcBankID, slcBankAcc:slcBankAcc, txtCheque:txtCheque, txtAmount:txtAmount, txtInWords:txtInWords, txtRemarks:txtRemarks }, function(data) {
		$("label.process").css("display", "none");
		if(data=="updated") {
			swal({
				title: "Success!",
				text: "You updated account payable details successfully.",
				icon: "success",
				timer: 1500,
				button: false
			})
                .then(value=>{
					window.location = "./workplace.php?role="+myRole+"&task=purchase&subtask=payable\
					&type="+transType+"&action=showInfo&recID="+changedID;
				}
			);
		} else if(data=="dueBalance<amount") {
			swal("Oops!", "The amount received from "+txtDeptHolder+" \n is less than amount you just typed in.", "error");
			if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.four").offset().top }, 'slow'); }
		} else {
			swal("Oops!", data, "error");
		}
		$("#btnUpdate").attr("disabled", false);
		$("#btnUpdate").html("Update");

	});
	return false;
}
function catchPyable(recID) {
	$.post("./assets-and-shares/includes/finance.php?action=get_recInfo&dest=getPyable", { recID:recID }, function(data) {
		$("div#foundNum").html('<label id="count">1</label> record has been selected.<span id="refresh"></span>');
		$("div#dataTable").html(data);
		$("#srchPyable").val('');
	});
	$("div.suggest").css("display", "none");
}
function delPayble(recID) {
	swal({
		title: "Are you sure?",
		text: "You going to delete this account payable!",
		icon: "warning",
        dangerMode:true,
        buttons:["Cancel","Delete"]
	})
    .then(willDelete=>{
        if(willDelete) {
    		$.post("./assets-and-shares/includes/finance.php?action=deleteRec&dest=delPayble", { recID:recID }, function(data) {
    			if(data=="deleted") {
    				swal({
    					title: "Success!",
    					text: "Selected account payable record has been deleted.",
    					icon: "success",
    					timer: 1500,
    					button: false
    				})
                    .then(value=>{
    					location.reload();
    				});

    			} else {
    				swal("Oops", data, "error");
    			}
    		});
        }
	});
	return false;
}

/* ---------------------------------------------------------------
--------------------------- vendor payable  ------------------------
-----------------------------------------------------------------*/
function loadVPayable(pageLimit, perPage, period) {
    $("#dataTable div#loading").css("display", "inline");
    var dataString = 'pageLimit='+ pageLimit+'&period='+ period+'&perPage='+ perPage;
    $.ajax({
        type: "POST",
        url: "./assets-and-shares/includes/finance.php?action=loadTable&dest=allVPayable",
        data: dataString,
        cache: false,
        timeout: 2000,
        success: function(result){
            $("#dataTable div#loading").css("display", "none");
            $(".load_more_link").addClass('noneLink');
            $("#dataTable").append(result);
        },
    });
    return false;
}

function simplifyVendorPyble() {
    $("#txtVendorName").keyup(function(){
        var vendorName = $("#txtVendorName").val();
        var externalVendor    = $("input#externalVendor:checked").val();
        if(externalVendor!="on") { var externalVendor="no"; } else { var externalVendor="yes"; }
        if(vendorName!="") {
            $("div.suggest.one").css("display", "table-row");
            $.post("./assets-and-shares/includes/finance.php?action=searchRec&dest=pickVendor4payable", { vendorName:vendorName,externalVendor:externalVendor }, function(data){
                $("div.suggest.one").html(data);
            });
        } else { $("div.suggest.one").css("display", "none"); }
        clearErrors();
    });
    //
    $("#checkExVendor, #switchExVendor").click(function(){
        $("#txtVendorName").val('');
        $("#vendorID").val('');
        $("#txtPaidTo").val('');
        $('div#switchExVendor').toggleClass("switchOn");
        if (document.getElementById("externalVendor").checked == true) {
            document.getElementById("externalVendor").checked = false;

        } else {
            document.getElementById("externalVendor").checked = true;
            document.getElementById("beginBalance").checked = true;
            $('div#switchBalance').addClass("switchOn");
            $("#slcBankID option:first").attr("selected", "selected");
            $("#slcBankAcc").html('');
        }

    });

    //
        $("#checkBlnce, #switchBalance").click(function(){
        $('div#switchBalance').toggleClass("switchOn");
        if (document.getElementById("beginBalance").checked == true) {
            document.getElementById("beginBalance").checked = false;
            document.getElementById("externalVendor").checked = false;
            $('div#switchExVendor').removeClass("switchOn");
        } else {
            document.getElementById("beginBalance").checked = true;
            $("#slcBankID option:first").attr("selected", "selected");
            $("#slcBankAcc").html('');
        }
    });
    //
     $("#slcBankID, #slcBankAcc").change(function() {
        document.getElementById("beginBalance").checked = false;
        $('div#switchBalance').removeClass("switchOn");
        //
        document.getElementById("externalVendor").checked = false;
        $('div#switchExVendor').removeClass("switchOn");
    });
}
function catchVendor4Prchse(vndID,fullname,phone,balance) {
    $("input#vendorID").val(vndID);
    $("input#txtVendorName").val(fullname);
    $("div.displayInfo.vendor").css("display", "inline");
    $("p#pVName").html(fullname);
    $("p#pVPhone").html(phone);
    if(balance>0) {
        $("p#pVBalance").html('$'+balance);
    } else {
        $("p#pVBalance").html(balance);
    }
    $("div.suggest").css("display", "none");
}
function check_addLocalVendor4Pop() {
    var txtVName    = $("#txtVName4Local").val();
    var txtVPhone   = $("#txtVPhone4Local").val();
    var txtVEmail   = $("#txtVEmail4Local").val();



    if(txtVName.length < 1) {
        $("#poplocalerror1").css("display", "inline");
        $("#poplocalerror1").html("Provide vendor's full name");
        $("#txtVName4Local").css("border-color", "#FF0000");
        return false;
    } else { clearErrors(); }

    if(txtVPhone.length < 1) {
        $("#poplocalerror2").css("display", "inline");
        $("#poplocalerror2").html("Phone number is missing");
        $("#txtVPhone4Local").css("border-color", "#FF0000");
        return false;
    } else { clearErrors(); }

    if(txtVEmail.length > 0) {
        var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
        if(!txtVEmail.match(emailExp)) {
            $("#poplocalerror3").css("display", "inline");
            $("#poplocalerror3").html("invalid email address");
            $("#txtVEmail4Local").css("border-color", "#FF0000");
            return false;
        } else { clearErrors(); }
    }

    $(".btnAdd").attr("disabled", true);
    $(".btnAdd").html("Wait...");

    $.post("./includes/general.php?action=saveNew&dest=addLocalVendor", { txtName:txtVName, txtPhone:txtVPhone, txtEmail:txtVEmail }, function(data) {
        var addedpos = data.search("added");
        $("label.process").css("display", "none");
        if(addedpos==0) {
            var lastID = data.slice(6,21);
            swal({
                title: "Success!",
                text: "You added new vendor successfully.",
                icon: "success",
                timer: 1500,
                button: false,
            });
            $("#txtVName, #txtVPhone, #txtVEmail").val('');
            $("input#vendorID").val(lastID);
            $("input#txtVendorName").val(txtVName);
            $("div.displayInfo.vendor").css("display", "inline");
            $("p#pVName").html(txtVName);
            $("p#pVPhone").html(txtVPhone);
            $("p#pVBalance").html(0);
            $("div.suggest").css("display", "none");
            $('input#addLocalVendorForm').prop('checked', false);
            $('input#externalVendor').prop('checked', false);
            document.getElementById("externalVendor").checked = false;
            $('div#switchExVendor').removeClass("switchOn");

        } else {
            swal("Oops!", data, "error");
        }
        $("#btnAdd").attr("disabled", false);
        $("#btnAdd").html("Add");
    });
    return false;
}
function check_addVendorPayable() {
    var vendorID  = $("#vendorID").val();
    var txtVendorName   = $("#txtVendorName").val();
    var txtAmount   = $("#txtAmount").val();

    var txtAmount   = $("#txtAmount").val();
    var txtInWords  = $("#txtInWords").val();

    var slcBankID   = $("#slcBankID").val();
    var slcBankAcc  = $("#slcBankAcc").val();
    var txtCheque   = $("#txtCheque").val();
    var txtRemarks   = $("#txtRemarks").val();
    var transDate   = $("#transDate").val();

    var beginBalance    = $("input#beginBalance:checked").val();
    if(beginBalance!="on") { var beginBalance="no"; } else { var beginBalance="yes"; }

    if(vendorID.length < 1 || txtVendorName.length < 1) {
        $("#error1").css("display", "inline");
        $("#error1").html("Provide vendor");
        $("#txtVendorName").addClass("highlight");
        return false;
    } else { clearErrors(); }


    if(txtAmount.length < 1) {
        $("#error2").css("display", "inline");
        $("#error2").html("Type amount");
        $("#txtAmount").addClass("highlight");
        return false;
    } else if(Number(txtAmount) < 0.1) {
        $("#error2").css("display", "inline");
        $("#error2").html("Amount must be greater than 0");
        $("#txtAmount").addClass("highlight");
        return false;
    } else { clearErrors(); }

    if(beginBalance=="no") {
        if(slcBankID.length < 1) {
            $("#error4").css("display", "inline");
            $("#error4").html("Please select bank");
            $("#slcBankID").css("border-color", "#FF0000");
            return false;
        } else { clearErrors(); }

        if(slcBankAcc=="---" || slcBankAcc.length < 1) {
            $("#error4").css("display", "inline");
            $("#error4").html("Select bank account");
            $("#slcBankAcc").css("border-color", "#FF0000");
            return false;
        } else { clearErrors(); }
    }

    $("label.process").css("display", "inline");
    $("#btnSave").attr("disabled", true);
    $("#btnSave").html("Wait...");

    $.post("./assets-and-shares/includes/finance.php?action=saveNew&dest=addVendorPyble", { vendorID:vendorID, txtVendorName:txtVendorName, txtAmount:txtAmount, txtInWords:txtInWords, beginBalance:beginBalance, slcBankID:slcBankID, slcBankAcc:slcBankAcc, txtCheque:txtCheque, txtRemarks:txtRemarks, transDate:transDate}, function(data) {
        var addedpos = data.search("added");
        $("label.process").css("display", "none");
        if(addedpos==0) {
            var lastID = data.slice(6,21);
            swal({
                title: "Success!",
                text: "You added new begin balance record into vendor payable.",
                icon: "success",
                timer: 1500,
                button: false
            })
                .then(value=>{
                   location.reload();
                }
            );
        } else {
            swal("Oops!", data, "error");
        }

        $("label.process").css("display", "inline");
        $("#btnSave").attr("disabled", false);
        $("#btnSave").html("Save");

    });
    return false;
}
function check_editVendorPayable() {
    var acvtyID  = $("#acvtyID").val();
    var vendorID  = $("#vendorID").val();
    var txtVendorName   = $("#txtVendorName").val();
    var txtAmount   = $("#txtAmount").val();


    if(vendorID.length < 1 || txtVendorName.length < 1 || acvtyID.length < 1) {
        $("#error1").css("display", "inline");
        $("#error1").html("Provide vendor");
        $("#txtVendorName").addClass("highlight");
        if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.one").offset().top }, 'slow'); }
        return false;
    } else { clearErrors(); }


    if(txtAmount.length < 1) {
        $("#error2").css("display", "inline");
        $("#error2").html("Type amount");
        $("#txtAmount").addClass("highlight");
        if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.three").offset().top }, 'slow'); }
        return false;
    } else if(Number(txtAmount) < 0.1) {
        $("#error2").css("display", "inline");
        $("#error2").html("Amount must be greater than 0");
        $("#txtAmount").addClass("highlight");
        if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.three").offset().top }, 'slow'); }
        return false;
    } else { clearErrors(); }


    $.post("./assets-and-shares/includes/finance.php?action=updateExist&dest=editVendorPyble", { acvtyID:acvtyID, vendorID:vendorID, txtVendorName:txtVendorName, txtAmount:txtAmount}, function(data) {

        $("label.process").css("display", "none");
        if(data=="updated") {
            swal({
                title: "Success!",
                text: "You updated begin balance record into vendor payable.",
                icon: "success",
                timer: 1500,
                button: false
            })
                .then(value=>{
                   window.location="./workplace.php?role='.$myRole.'&task=finance&subtask=vendorPyable&action=showInfo&recID="+acvtyID;
                }
            );
        } else {
            swal("Oops!", data, "error");
        }

    });
    return false;
}
function delVPayble(recID) {
    swal({
        title: "Are you sure?",
        text: "You going to delete this vendor payable!",
        icon: "warning",
        dangerMode:true,
        buttons:["Cancel","Delete"]
    })
    .then(willDelete=>{
        if(willDelete) {
            $.post("./assets-and-shares/includes/finance.php?action=deleteRec&dest=delVPayble", { recID:recID }, function(data) {
                if(data=="deleted") {
                    swal({
                        title: "Success!",
                        text: "Selected vendor payable record has been deleted.",
                        icon: "success",
                        timer: 1500,
                        button: false
                    })
                    .then(value=>{
                        location.reload();
                    });

                } else {
                    swal("Oops", data, "error");
                }
            });
        }
    });
    return false;
}
/* ---------------------------------------------------------------
--------------------------- share holder  ------------------------
-----------------------------------------------------------------*/

function loadShares(pageLimit, perPage, period) {
	$("#dataTable div#loading").css("display", "inline");
	var dataString = 'pageLimit='+ pageLimit+'&period='+ period+'&perPage='+ perPage;
	$.ajax({
		type: "POST",
		url: "./assets-and-shares/includes/finance.php?action=loadTable&dest=allShares",
		data: dataString,
		cache: false,
		timeout: 2000,
		success: function(result){
			$("#dataTable div#loading").css("display", "none");
			$(".load_more_link").addClass('noneLink');
			$("#dataTable").append(result);
		},
	});
	return false;
}
function check_addShareHolder() {
	var txtSName = $("#txtSName").val();
	var txtSPhone = $("#txtSPhone").val();
	var txtSEmail = $("#txtSEmail").val();

	var txtKName = $("#txtKName").val();
	var txtKPhone = $("#txtKPhone").val();
	var txtKEmail = $("#txtKEmail").val();


	if(txtSName.length < 1) {
		$("#qalad1").css("display", "inline");
		$("#qalad1").html("Please type full name");
		$("#txtSName").addClass("highlight");
		return false;
	} else { clearErrors(); }

	if(txtSPhone.length < 1) {
		$("#qalad2").css("display", "inline");
		$("#qalad2").html("Don't forget phone number");
		$("#txtSPhone").addClass("highlight");
		return false;
	} else { clearErrors(); }

		if(txtSEmail.length > 0) {
		if(!txtSEmail.match(emailExp)) {
			$("#qalad3").css("display", "inline");
			$("#qalad3").html("invalid email address");
			$("#txtSEmail").addClass("highlight");
			return false;
		}
	} else { clearErrors(); }

	if(txtKName.length < 1) {
		$("#qalad4").css("display", "inline");
		$("#qalad4").html("Please Provide next of kin");
		$("#txtKName").addClass("highlight");
		return false;
	} else { clearErrors(); }

	if(txtKPhone.length < 1) {
		$("#qalad5").css("display", "inline");
		$("#qalad5").html("Don't forget next of kin phone number");
		$("#txtKPhone").addClass("highlight");
		return false;
	} else { clearErrors(); }

	if(txtKEmail.length > 0) {
		if(!txtKEmail.match(emailExp)) {
			$("#qalad6").css("display", "inline");
			$("#qalad6").html("invalid email address");
			$("#txtKEmail").addClass("highlight");
			return false;
		}
	} else { clearErrors(); }


	$("#btnAdd").attr("disabled", true);
	$("#btnAdd").html("wait...");
	$("div.suggest.one").css("display", "none");

	$.post("./assets-and-shares/includes/finance.php?action=saveNew&dest=addShareHolder", {  txtSName:txtSName, txtSPhone:txtSPhone,txtSEmail:txtSEmail,txtKName:txtKName, txtKPhone:txtKPhone, txtKEmail:txtKEmail }, function(data) {
		var addedpos = data.search("added");
		if(addedpos==0) {
			var lastID = data.slice(6,21);
			//
			$("input#shareHID").val(lastID);
			$("input#shareHolder").val(txtSName);
			$("p#pSName").html(txtSName);
			$("p#pSPhone").html(txtSPhone);
			$("div.displayInfo").css("display", "inline");
			$('input#addShareHolderForm').prop('checked', false);
			swal({
				title: "Success!",
				text: "You added new shareholder successfully.",
				icon: "success",
				timer: 1500,
				button: false
			});
			$("#txtSName,#txtSPhone,#txtSEmail,#txtKName,#txtKPhone,#txtKEmail").val("");
		} else {
			swal("Oops!", data, "error");
		}
		$(".btnAdd.shareHolder").attr("disabled", false);
		$(".btnAdd.shareHolder").html("Add");
	});
	return false;
}

function catchShare4form(shID,shareHolder,phone,shareAmount,sharePercentage) {
	$("#shareHID").val(shID);
	$("#shareHolder").val(shareHolder);
	$("p#pSName").html(shareHolder);
	$("p#pSPhone").html(phone);
	$("p#pSAmnt").html(shareAmount);
	$("p#pSPercentage").html(sharePercentage);
	$("div.displayInfo").css("display", "inline");
	$("div.suggest.one").css("display", "none");
}
function simplifyAddShare() {
	$("#shareHolder").keyup(function(){
		var shareHolder = $("#shareHolder").val();
		if(shareHolder!="") {
			$("div.suggest.one").css("display", "table-row");
			$.post("./assets-and-shares/includes/finance.php?action=searchRec&dest=pickSHolder",{ passedValue:shareHolder}, function(data) {
				$("div.suggest.one").html(data);
			});
		} else { $("div.suggest.one").css("display", "none"); }
		clearErrors();
	});
	$("#checkBlnce, #switchBalance").click(function(){
		$('div#switchBalance').toggleClass("switchOn");
		if (document.getElementById("beginBalance").checked == true) {
			document.getElementById("beginBalance").checked = false;
			$("#btnWithdraw").attr("disabled", false);
		} else {
			document.getElementById("beginBalance").checked = true;
			$("#slcBankID option:first").attr("selected", "selected");
			$("#slcBankAcc").html('');
			$("#btnWithdraw").attr("disabled", true);


		}
	});
	//
	$("#slcBankID, #slcBankAcc").change(function() {
		document.getElementById("beginBalance").checked = false;
		$('div#switchBalance').removeClass("switchOn");
		$("#btnWithdraw").attr("disabled", false);
	});
	// deposit button
	$("#btnDeposit").click(function() {
		var actionType = "deposit";
		insert_share(actionType); return false;
	});
	// withdraw button
	$("#btnWithdraw").click(function() {
		var actionType = "withdraw";
		insert_share(actionType); return false;
	});
}
function insert_share(actionType) {
	var beginBalance	= $("input#beginBalance:checked").val();
	if(beginBalance!="on") { var beginBalance="no"; } else { var beginBalance="yes"; }

	var shareHID	= $("#shareHID").val();
	var shareHolder	= $("#shareHolder").val();
	var transDate	= $("#transDate").val();
	var slcBankID	= $("#slcBankID").val();
	var slcBankAcc	= $("#slcBankAcc").val();
	var txtCheque	= $("#txtCheque").val();
	var txtAmount	= $("#txtAmount").val();
	var txtInWords	= $("#txtInWords").val();
	var txtRemarks	= $("#txtRemarks").val();

	if(shareHID.length < 1 || shareHolder.length < 1) {
		$("#error1").css("display", "inline");
		$("#error1").html("Provide shareholder name");
		$("#shareHolder").addClass("highlight");
		$("div.suggest").css("display", "none");
		return false;
	} else { clearErrors(); }
    if(beginBalance=="no"){
    	if(slcBankID.length < 1) {
    		$("#error2").css("display", "inline");
    		$("#error2").html("Please select bank");
    		$("#slcBankID").addClass("highlight");
    		return false;
    	} else { clearErrors(); }

    	if(slcBankAcc=="---" || slcBankAcc.length < 1) {
    		$("#error2").css("display", "inline");
    		$("#error2").html("Select bank account");
    		$("#slcBankAcc").addClass("highlight");
    		return false;
    	} else { clearErrors(); }
    }

	if(txtAmount.length < 1) {
		$("#error3").css("display", "inline");
		$("#error3").html("Type amount");
		$("#txtAmount").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.three").offset().top }, 'slow'); }
		return false;
	} else if(Number(txtAmount) < 0.1) {
		$("#error3").css("display", "inline");
		$("#error3").html("Amount must be greater than 0");
		$("#txtAmount").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.three").offset().top }, 'slow'); }
		return false;
	} else { clearErrors(); }

	$("label.process").css("display", "inline");
	if(actionType=="deposit") {
		$("#btnDeposit").attr("disabled", true); $("#btnDeposit").html("Wait...");
	} else if(actionType=="withdraw") {
		$("#btnWithdraw").attr("disabled", true); $("#btnWithdraw").html("Wait...");
	}

	$.post("./assets-and-shares/includes/finance.php?action=saveNew&dest=addShare", { transType:actionType, shareHID:shareHID, shareHolder:shareHolder, transDate:transDate, beginBalance:beginBalance,  slcBankID:slcBankID, slcBankAcc:slcBankAcc, txtCheque:txtCheque, txtAmount:txtAmount, txtInWords:txtInWords, txtRemarks:txtRemarks }, function(data) {
		var addedpos = data.search("added");
		$("label.process").css("display", "none");
		if(addedpos==0) {
			var lastID = data.slice(6,21);
				$.post("./assets-and-shares/includes/finance.php?action=get_recInfo&dest=getShareInfo", { recID:lastID,myRole:myRole}, function(data) {
				var lastID2 = data;
				//alert(lastID);
				swal({
				title: "Success!",
				text: "You added new record as shareholder.",
				icon: "success",
				timer: 1500,
				button: false
			})
                .then(value=>{
					window.location = "./workplace.php?role="+myRole+"&task=settings&subtask=shares\
					&type="+actionType+"&action=showInfo&recID="+lastID2;
				}
			);
			});

		} else if(data=="dueBalance<amount") {
			swal("Oops!", "The amount received from "+shareHolder+" \n is less than amount you just typed in.", "error");
			if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.four").offset().top }, 'slow'); }
		} else {
			swal("Oops!", data, "error");
		}
		if(actionType=="deposit") {
			$("#btnDeposit").attr("disabled", false); $("#btnDeposit").html("Deposit");
		} else if(actionType=="withdraw") {
			$("#btnWithdraw").attr("disabled", false); $("#btnWithdraw").html("Withdraw");
		}
	});
	return false;
}
//
function check_editShareHolder(){
	var shID		= $("#shID").val();
	var shareHolder	= $("#shareHolder").val();
	var sharePhone	= $("#sharePhone").val();
	var shareEmail	= $("#shareEmail").val();
	var kinName		= $("#kinName").val();
	var kinPhone	= $("#kinPhone").val();
	var kinEmail	= $("#kinEmail").val();

    var emailExp 	= /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
    	if(shareHolder.length < 1) {
    	$("#error1").css("display", "inline");
    	$("#error1").html("Provide shareholder name");
    	$("#shareHolder").addClass("highlight");
    	return false;
    	} else { clearErrors(); }

    	if(sharePhone.length < 1) {
    	$("#error2").css("display", "inline");
    	$("#error2").html("Provide shareholder Phone");
    	$("#sharePhone").addClass("highlight");
    	return false;
    	} else { clearErrors(); }

    	if(shareEmail.length > 0) {
    	if(!shareEmail.match(emailExp)) {
    		$("#error3").css("display", "inline");
    		$("#error3").html("invalid email address");
    		$("#shareEmail").addClass("highlight");
    		return false;
    	}
    } else { clearErrors(); }

    	if(kinName.length < 1) {
    	$("#error4").css("display", "inline");
    	$("#error4").html("Provide next of kin");
    	$("#kinName").addClass("highlight");
    	return false;
    	} else { clearErrors(); }

    	if(kinPhone.length < 1) {
    	$("#error5").css("display", "inline");
    	$("#error5").html("Provide next of kin phone");
    	$("#kinPhone").addClass("highlight");
    	return false;
    	} else { clearErrors(); }

    		if(kinEmail.length > 0) {
    		if(!kinEmail.match(emailExp)) {
    			$("#error6").css("display", "inline");
    			$("#error6").html("invalid email address");
    			$("#kinEmail").addClass("highlight");
    			return false;
    		}
    	} else { clearErrors(); }

    	$("label.process").css("display", "inline");
    	$("#btnUpdate").attr("disabled", true);
    	$("#btnUpdate").html("Wait...");

    		$.post("./assets-and-shares/includes/finance.php?action=updateExist&dest=editShareHolder", { shID:shID, shareHolder:shareHolder, sharePhone:sharePhone,shareEmail:shareEmail, kinName:kinName, kinPhone:kinPhone, kinEmail:kinEmail }, function(data) {

    		if(data=="updated") {
    			swal({
    				title: "Success!",
    				text: "You updated shareholder successfully.",
    				icon: "success",
    				timer: 1500,
    				button: false
    			})
                .then(value=>{
    					window.location = "./workplace.php?role="+myRole+"&task=settings&subtask=shares&action=showInfo&recID="+shID;
    				}

    			);

    		} else {
    			swal("Oops!", data, "error");
    		}
    		$("#btnAdd").attr("disabled", false);
    		$("#btnAdd").html("Add");
    	});
    	return false;
}
function check_editShare() {
	var changedID	= $("#changedID").val();
	var transType	= $("#transType").val();
	//alert(transType); return false;

	var shareHID	= $("#shareHID").val();
	var shareHolder	= $("p#pSName").html();
	var slcBankID	= $("#slcBankID").val();
	var slcBankAcc	= $("#slcBankAcc").val();
	var txtCheque	= $("#txtCheque").val();
	var txtAmount	= $("#txtAmount").val();
	var txtInWords	= $("#txtInWords").val();
	var txtRemarks	= $("#txtRemarks").val();

	if(shareHID.length < 1) {
		$("#error1").css("display", "inline");
		$("#error1").html("Provide shareholder name");
		$("#txtClient").addClass("highlight");
		return false;
	} else { clearErrors(); }

	if(slcBankID.length < 1) {
		$("#error2").css("display", "inline");
		$("#error2").html("Please select bank");
		$("#slcBankID").addClass("highlight");
		return false;
	} else { clearErrors(); }

	if(slcBankAcc=="---" || slcBankAcc.length < 1) {
		$("#error2").css("display", "inline");
		$("#error2").html("Select bank account");
		$("#slcBankAcc").addClass("highlight");
		return false;
	} else { clearErrors(); }

	if(txtAmount.length < 1) {
		$("#error3").css("display", "inline");
		$("#error3").html("Type amount");
		$("#txtAmount").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.three").offset().top }, 'slow'); }
		return false;
	} else if(Number(txtAmount) < 0.1) {
		$("#error3").css("display", "inline");
		$("#error3").html("Amount must be greater than 0");
		$("#txtAmount").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.three").offset().top }, 'slow'); }
		return false;
	} else { clearErrors(); }

	$("label.process").css("display", "inline");
	$("#btnUpdate").attr("disabled", true);
	$("#btnUpdate").html("Wait...");

	$.post("./assets-and-shares/includes/finance.php?action=updateExist&dest=editShare&updatedBy="+myUser, { changedID:changedID, transType:transType, shareHID:shareHID, shareHolder:shareHolder, slcBankID:slcBankID, slcBankAcc:slcBankAcc, txtCheque:txtCheque, txtAmount:txtAmount, txtInWords:txtInWords, txtRemarks:txtRemarks }, function(data) {
		$("label.process").css("display", "none");
		if(data=="updated") {
			swal({
				title: "Success!",
				text: "You updated share details successfully.",
				icon: "success",
				timer: 1500,
				button: false
			})
                .then(value=>{
					window.location = "./workplace.php?role="+myRole+"&task=settings&subtask=shares\
					&type="+transType+"&action=showInfo&recID="+changedID;
				}
			);
		} else if(data=="dueBalance<amount") {
			swal("Oops!", "The amount received from "+shareHolder+" \n is less than amount you just typed in.", "error");
			if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.three").offset().top }, 'slow'); }
		} else {
			swal("Oops!", data, "error");
		}
		$("#btnUpdate").attr("disabled", false);
		$("#btnUpdate").html("Update");
	});
	return false;
}
function catchShare(recID) {
	$.post("./assets-and-shares/includes/finance.php?action=get_recInfo&dest=getShare", { recID:recID }, function(data) {
		$("div#foundNum").html('<label id="count">1</label> record has been selected.<span id="refresh"></span>');
		$("div#dataTable").html(data);
	});
	$("div.suggest").css("display", "none");
}
function delShare(recID) {
	swal({
		title: "Are you sure?",
		text: "You going to delete this share holder!",
		icon: "warning",
        dangerMode:true,
		buttons:["Cancel","Delete"]
	})
    .then(willDelete=>{
        if(willDelete) {
    		$.post("./assets-and-shares/includes/finance.php?action=deleteRec&dest=delShare", { recID:recID }, function(data) {
    			if(data=="deleted") {
    				swal({
    					title: "Success!",
    					text: "Selected share holder record has been deleted.",
    					icon: "success",
    					timer: 1500,
    					button: false
    				});
    				var count = $("label#count").html();
    				$("label#count").html(count-1);
    				$("a.masax.rec"+recID).parents("#record").fadeOut(500);
    			} else {
    				swal("Oops", data, "error");
    			}
    		});
        }
	});
	return false;
}
//
//
function delBeginBlcShareAmount(shareActvtyID) {
    swal({
        title: "Are you sure?",
        text: "You going to delete this activity!",
        icon: "warning",
        dangerMode:true,
        buttons:["Cancel","Delete"]
    })
    .then(willDelete=>{
        if(willDelete) {
            $.post("./assets-and-shares/includes/finance.php?action=deleteRec&dest=delBeginBlcShareAmount", { shareActvtyID:shareActvtyID }, function(data) {
                if(data=="deleted") {
                    swal({
                        title: "Success!",
                        text: "Selected record has been deleted.",
                        icon: "success",
                        timer: 1500,
                        button: false
                    })
                .then(value=>{
                        location.reload();
                    });
                } else {
                    swal("Oops", data, "error");
                }
            });
        }
    });
    return false;
}

/* ------------------------------------------------------------
------------------------ cash transfer ------------------------
--------------------------------------------------------------*/

function simplifyCshTrnsfer() {
	$("#slcBankID").change(function() {
		var bankID = $("#slcBankID").val();
		if(bankID=="") {
			$("#slcBankAcc").html('');
		} else {
			$.post("./assets-and-shares/includes/finance.php?action=searchRec&dest=myBankAccs", { bankID: bankID }, function(data) {
				$("#slcBankAcc").html(data);
			});
		}
	});
	//
	$("#slcBankIDTo").change(function() {
		var bankID = $("#slcBankIDTo").val();
		if(bankID=="") {
			$("#slcBankAccTo").html('');
		} else {
			$.post("./assets-and-shares/includes/finance.php?action=searchRec&dest=myBankAccs", { bankID: bankID }, function(data) {
				$("#slcBankAccTo").html(data);
			});
		}
	});
    //
    $("#slcBankAcc").change(function() {
        var bankAccID = $(this).val();
        if(bankAccID=="") {
            $("#error1").css("display", "none");
        } else {
            $.post("./assets-and-shares/includes/finance.php?action=searchRec&dest=getAccBalance", { bankAccID: bankAccID }, function(data) {
                $("#error1").css("display", "inline");
                $("#error1").html('$'+data);
            });
        }
    });
    //
    $("#slcBankAccTo").change(function() {
        var bankAccID = $(this).val();
        if(bankAccID=="") {
            $("#error2").css("display", "none");
        } else {
            $.post("./assets-and-shares/includes/finance.php?action=searchRec&dest=getAccBalance", { bankAccID: bankAccID }, function(data) {
                $("#error2").css("display", "inline");
                $("#error2").html('$'+data);
            });
        }
    });
    //
	$("#txtAmount").keyup(function() {
		inWords($("#txtAmount").val());
	});
	$("#txtAmount").change(function() {
		inWords($("#txtAmount").val());
	});
	//
	$("#txtRemarks").keyup(function(){
		return tweetFeed(this, 500);
	});
	//
	var yearago = Number(year)-1;
	var picker = new Pikaday({
		field: document.getElementById("transDate"),
		firstDay: 6,
		maxDate: new Date(today),
		yearRange: [yearago,year],
	});
}
function check_trnsfrCash() {
	var bankID1		= $("#slcBankID").val();
	var accNum1		= $("#slcBankAcc").val();
	var bankID2		= $("#slcBankIDTo").val();
	var accNum2		= $("#slcBankAccTo").val();
	var txtAmount	= $("#txtAmount").val();
	//
	var txtCheque	= $("#txtCheque").val();
	var txtRemarks	= $("#txtRemarks").val();
	var transDate	= $("#transDate").val();

	if(bankID1 == "---") {
		$("#error1").css("display", "inline");
		$("#error1").html("Select bank where amount comes from");
		$("#slcBankFrom").addClass("highlight");
		return false;
	} else { clearErrors(); }

	if(accNum1 == "---") {
		$("#error1").css("display", "inline");
		$("#error1").html("Select account number");
		$("#slcBankAccFrom").addClass("highlight");
		return false;
	} else { clearErrors(); }

	if(bankID2 == "---") {
		$("#error2").css("display", "inline");
		$("#error2").html("Select bank getting this amount");
		$("#slcBankTo").addClass("highlight");
		return false;
	} else { clearErrors(); }

	if(accNum2 == "---") {
		$("#error2").css("display", "inline");
		$("#error2").html("Select account number");
		$("#slcBankAccTo").addClass("highlight");
		return false;
	} else { clearErrors(); }

	if(accNum1==accNum2) {
		$("#error2").css("display", "inline");
		$("#error2").html("Select different accounts");
		$("#slcBankAccTo").addClass("highlight");
		return false;
	} else { clearErrors(); }

	if(txtAmount.length < 1) {
		$("#error3").css("display", "inline");
		$("#error3").html("Type amount value");
		$("#txtAmount").addClass("highlight");
		return false;
	} else if(Number(txtAmount) < 1) {
		$("#error3").css("display", "inline");
		$("#error3").html("Amount must be greater than 0");
		$("#txtAmount").addClass("highlight");
		return false;
	} else { clearErrors(); }

	$("label.process").css("display", "inline");
	$("#btnTransfer").attr("disabled", true);
	$("#btnTransfer").html("wait...");

	$.post("./assets-and-shares/includes/finance.php?action=saveNew&dest=trnsferCash", {  bankID1:bankID1, accNum1:accNum1, bankID2:bankID2, accNum2:accNum2, txtAmount:txtAmount, txtCheque:txtCheque, txtRemarks:txtRemarks, transDate:transDate }, function(data) {
		var addedpos = data.search("added");
		$("label.process").css("display", "none");
		if(addedpos==0) {
			var transRef = data.slice(6,50);
			swal({
				title: "Success!",
				text: "You transfered cash successfully.",
				icon: "success",
				timer: 1500,
				button: false
			})
                .then(value=>{
					window.location = "./workplace.php?role="+myRole+"&task=finance&subtask=cshTrnsfer\
					&action=showInfo&transRef="+transRef;
				}
			);
		} else {
			swal("Oops!", data, "error");
		}
		$("#btnTransfer").attr("disabled", false);
		$("#btnTransfer").html("Transfer");

	});
	return false;
}


/* ------------------------------------------------------------
--------------------------- assets ----------------------------
--------------------------------------------------------------*/

function loadAssets(pageLimit, perPage, period) {
	$("#dataTable div#loading").css("display", "inline");
	var dataString = 'pageLimit='+ pageLimit+'&period='+ period+'&perPage='+ perPage;
	$.ajax({
		type: "POST",
		url: "./assets-and-shares/includes/finance.php?action=loadTable&dest=allAssets",
		data: dataString,
		cache: false,
		timeout: 2000,
		success: function(result){
			$("#dataTable div#loading").css("display", "none");
			$(".load_more_link").addClass('noneLink');
			$("#dataTable").append(result);
		},
	});
	return false;
}
function simplifyAssetAdd() {
	//$("#addNew").leanModal({top : 160, overlay : 0.6, closeButton: "span.close" });
	$("#txtClient").keyup(function(){
		search_client('asset');
	});
	//
	$("#checkLoan, #switchLoan").click(function(){
		$('div#switchLoan').toggleClass("switchOn");
		if(document.getElementById("assetLoan").checked == true) {
			document.getElementById("assetLoan").checked = false;
			$("#loanDiv").css("display","none");
		} else {
			document.getElementById("assetLoan").checked = true;
			$("select#slcBankID option:first").attr("selected", "selected");
			$("select#slcBankAcc").html('');
			$("input#txtCheque").val('');
			$("#loanDiv").css("display","inline");
		}
	});
	//
	$("#checkBlnce, #switchBalance").click(function(){
		$('div#switchBalance').toggleClass("switchOn");
		if(document.getElementById("beginBalance").checked == true) {
			document.getElementById("beginBalance").checked = false;
		} else {
			document.getElementById("beginBalance").checked = true;
			$("#slcBankID option:first").attr("selected", "selected");
			$("#slcBankAcc").html('');
		}
	});
	//
	$("#slcBankID, #slcBankAcc").change(function() {
		var beginBalance	= $("input#beginBalance:checked").val();
		var assetLoan	= $("input#assetLoan:checked").val();
		if(beginBalance=="on" || beginBalance=="off") {
			document.getElementById("beginBalance").checked = false;
			$('div#switchBalance').removeClass("switchOn");

		}
		if(assetLoan=="on" || assetLoan=="off") {
			document.getElementById("assetLoan").checked = false;
			$('div#switchLoan').removeClass("switchOn");
			$("#loanDiv").css("display","none");
		}
	});
}
//

function check_addAssetCategory4Form() {
    var txtName = $("#txtName").val();
    var slcOrder  = $("#slcOrder").val();

    if(txtName.length < 1) {
        $("#poperror24").css("display", "inline");
        $("#poperror24").html("Please provide category name");
        $("#txtName").addClass("highlight");
        return false;
    } else { clearErrors(); }

    if(slcOrder=="") {
        $("#poperror25").css("display", "inline");
        $("#poperror25").html("provide order number");
        $("#slcOrder").addClass("highlight");
        return false;
    } else { clearErrors(); }

    $("label.process").css("display", "inline");
    $("#btnSave").attr("disabled", true);
    $("#btnSave").html("Wait...");

    $.post("./assets-and-shares/includes/finance.php?action=saveNew&dest=addAssetCategory4Form", { txtName:txtName, slcOrder:slcOrder}, function(data) {
        var addedpos = data.search("added");
        $("label.process").css("display", "none");
        if(addedpos==0) {
            var lastID = data.slice(6,21);
            swal({
                title: "Success!",
                text: "You added new category record successfully.",
                icon: "success",
                timer: 1500,
                button: false,
            });
            $("select#slcCategory").append('<option value="'+lastID+'" selected="selected">'+txtName+'</option>');
            $('input#addAssetCategoryForm').prop('checked', false);
        } else {
            swal("Oops!", data, "error");
        }
        $("#btnSave").attr("disabled", false);
        $("#btnSave").html("Save");
    });
    return false;
}
//
function check_addAsset() {
	var assetName 	= $("#assetName").val();
	var loanPeriod 	= $("#txtLoanPeriod").val();
	var assetLoan	= $("input#assetLoan:checked").val();
	if(assetLoan!="on") { var payType="paid"; } else { var payType="loan"; }
	var txtUsage	= $("#txtUsage").val();
	var beginBalance	= $("input#beginBalance:checked").val();
	if(beginBalance!="on") { var beginBalance="no"; } else { var beginBalance="yes"; }
	var txtAmount 	= $("#txtAmount").val();
	var txtInWords	= $("#txtInWords").val();
	var slcBankID	= $("#slcBankID").val();
	var slcBankAcc	= $("#slcBankAcc").val();
	var txtCheque	= $("#txtCheque").val();
    var transDate   = $("#transDate").val();
    var slcCategory     = $("#slcCategory").val();

	var txtRemarks 	= $("#txtRemarks").val();

    if(assetName.length < 1) {
        $("#error2").css("display", "inline");
        $("#error2").html("Provide asset details");
        $("#assetName").addClass("highlight");
        return false;
    } else { clearErrors(); }

	if(slcCategory=="") {
		$("#error1").css("display", "inline");
		$("#error1").html("Provide asset category");
		$("#slcCategory").addClass("highlight");
		return false;
	} else { clearErrors(); }

	if(txtUsage.length < 1) {
		$("#error3").css("display", "inline");
		$("#error3").html("Asset usage not mentioned");
		$("#txtUsage").addClass("highlight");
		return false;
	} else { clearErrors(); }

	if(txtAmount.length < 1) {
		$("#error4").css("display", "inline");
		$("#error4").html("Amount can't be empty");
		$("#txtAmount").addClass("highlight");
		return false;
	} else if(Number(txtAmount) < 0.1) {
		$("#error4").css("display", "inline");
		$("#error4").html("Amount must be greater than 0");
		$("#txtAmount").addClass("highlight");
		return false;
	} else { clearErrors(); }

	if(payType=="paid" && beginBalance == "no") {
		if(slcBankID.length < 1) {
			$("#error5").css("display", "inline");
			$("#error5").html("Please select bank");
			$("#slcBankID").addClass("highlight");
			return false;
		} else { clearErrors(); }

		if(slcBankAcc=="---" || slcBankAcc.length < 1) {
			$("#error5").css("display", "inline");
			$("#error5").html("Select bank account");
			$("#slcBankAcc").addClass("highlight");
			return false;
		} else { clearErrors(); }
	}
	if(payType=="loan") {
		if(loanPeriod.length < 1) {
		$("#error6").css("display", "inline");
		$("#error6").html("Loan Perion not mentioned");
		$("#txtLoanPeriod").addClass("highlight");
		return false;
	} else { clearErrors(); }

	}
	$("label.process").css("display", "inline");
	$("#btnSave").attr("disabled", true);
	$("#btnSave").html("Wait...");

	$.post("./assets-and-shares/includes/finance.php?action=saveNew&dest=addAsset", {  assetName:assetName, slcCategory:slcCategory, payType:payType, txtUsage:txtUsage, beginBalance:beginBalance, txtAmount:txtAmount, txtInWords:txtInWords, slcBankID:slcBankID, slcBankAcc:slcBankAcc, txtCheque:txtCheque, transDate:transDate , loanPeriod:loanPeriod,txtRemarks:txtRemarks }, function(data) {
		var addedpos = data.search("added");
		$("label.process").css("display", "none");
		if(addedpos==0) {
			var lastID = data.slice(6,21);
			swal({
				title: "Success!",
				text: "You added asset record successfully.",
				icon: "success",
				timer: 1500,
				button: false,
			})
                .then(value=>{
					window.location = "./workplace.php?role="+myRole+"&task=settings&subtask=assets\
					&action=showInfo&recID="+lastID;
				}
			);
		} else {
			swal("Oops!", data, "error");
		}
		$("#btnSave").attr("disabled", false);
		$("#btnSave").html("Save");
	});
	return false;
}
function check_editAsset() {
	var astID 		= $("#astID").val();
	var payType		= $("#payType").val();
	var assetName 	= $("#assetName").val();
	var slcCategory		= $("#slcCategory").val();
	var txtUsage	= $("#txtUsage").val();
	var loanPeriod	= $("#txtLoanPeriod").val();
	var txtAmount 	= $("#txtAmount").val();
	var txtInWords	= $("#txtInWords").val();

	if(assetName.length < 1) {
		$("#error2").css("display", "inline");
		$("#error2").html("Provide asset details");
		$("#assetName").addClass("highlight");
		return false;
	} else { clearErrors(); }

    if(slcCategory=="") {
        $("#error1").css("display", "inline");
        $("#error1").html("Provide asset category");
        $("#slcCategory").addClass("highlight");
        return false;
    } else { clearErrors(); }

	if(txtAmount.length < 1) {
		$("#error3").css("display", "inline");
		$("#error3").html("Amount can't be empty");
		$("#txtAmount").addClass("highlight");
		return false;
	} else if(Number(txtAmount) < 0.1) {
		$("#error3").css("display", "inline");
		$("#error3").html("Amount must be greater than 0");
		$("#txtAmount").addClass("highlight");
		return false;
	} else { clearErrors(); }

	if(txtUsage.length < 1) {
		$("#error4").css("display", "inline");
		$("#error4").html("Asset usage not mentioned");
		$("#txtUsage").addClass("highlight");
		return false;
	} else { clearErrors(); }

	$("label.process").css("display", "inline");
	$("#btnUpdate").attr("disabled", true);
	$("#btnUpdate").html("Wait...");

	$.post("./assets-and-shares/includes/finance.php?action=updateExist&dest=editAsset", { astID:astID, payType:payType,assetName:assetName, slcCategory:slcCategory, txtAmount:txtAmount, txtInWords:txtInWords, txtUsage:txtUsage,  loanPeriod:loanPeriod }, function(data) {
		$("label.process").css("display", "none");
		if(data=="updated") {
			swal({
				title: "Success!",
				text: "You updated asset record successfully.",
				icon: "success",
				timer: 1500,
				button: false,
			})
                .then(value=>{
					window.location = "./workplace.php?role="+myRole+"&task=settings&subtask=assets\
					&action=showInfo&recID="+astID;
				}
			);
		} else {
			swal("Oops!", data, "error");
		}
		$("#btnUpdate").attr("disabled", false);
		$("#btnUpdate").html("Update");
	});
	return false;
}
function check_depreAsset() {
	var astID		= $("#astID").val();
	var payType		= $("#payType").val();
	var txtAmount	= $("#txtAmount").val();
	var txtInWords	= $("#txtInWords").val();
	var theMonth	= $("#theMonth").val();
	var transDate	= $("#transDate").val();

	if(astID.length < 1) {
		$("#error1").css("display", "inline");
		$("#error1").html("Asset record is missing");
		$("#shareHolder").addClass("highlight");
		return false;
	} else { clearErrors(); }

	if(txtAmount.length < 1) {
		$("#error2").css("display", "inline");
		$("#error2").html("Type amount");
		$("#txtAmount").addClass("highlight");
		return false;
	} else if(Number(txtAmount) < 0.1) {
		$("#error2").css("display", "inline");
		$("#error2").html("Amount must be greater than 0");
		$("#txtAmount").addClass("highlight");
		return false;
	} else { clearErrors(); }

	swal({
		title: "Confirm?",
		text: "You going to make depreciation this month "+theMonth,
		icon: "warning",
        dangerMode:true,
        buttons:["Cancel","Confirm"]
	})
    .then(willDelete=>{
        if(willDelete) {
    		$("label.process").css("display", "inline");
    		$("#btnSave").attr("disabled", true);
    		$("#btnSave").html("Wait...");
    		$.post("./assets-and-shares/includes/finance.php?action=updateExist&dest=addAssetDepr", { astID:astID, payType:payType, txtAmount:txtAmount, txtInWords:txtInWords, theMonth:theMonth,transDate:transDate}, function(data) {
    			$("label.process").css("display", "none");
    			if(data=="updated") {
    				swal({
    					title: "Success!",
    					text: "You made monthly depreciation for this asset",
    					icon: "success",
    					timer: 1500,
    					button: false
    				})
                    .then(value=>{
    						window.location = "./workplace.php?role="+myRole+"&task=settings&subtask=assets&action=showInfo&recID="+astID;
    					}
    				);
    			} else {
    				swal("Oops!", data, "error");
    			}
    			$("#btnSave").attr("disabled", false);
    			$("#btnSave").html("Depreciate");
    		});
        }
	});
	return false;
}
function check_payAsset() {
	var astID		= $("#astID").val();
	var astName		= $("#astName").val();
	var balance		= parseFloat($("#balance").val());

	var txtAmount	= $("#txtAmount").val();
	var txtInWords	= $("#txtInWords").val();
	var slcBankID	= $("#slcBankID").val();
	var slcBankAcc	= $("#slcBankAcc").val();
	var txtCheque	= $("#txtCheque").val();
	var transDate	= $("#transDate").val();

	if(astID.length < 1) {
		$("#error1").css("display", "inline");
		$("#error1").html("Asset record is missing");
		$("#astName").addClass("highlight");
		return false;
	} else { clearErrors(); }

	if(txtAmount.length < 1) {
		$("#error2").css("display", "inline");
		$("#error2").html("Amount can't be empty");
		$("#txtAmount").addClass("highlight");
		return false;
	} else if(Number(txtAmount) < 0.1) {
		$("#error2").css("display", "inline");
		$("#error2").html("Amount must be greater than 0");
		$("#txtAmount").addClass("highlight");
		return false;
	} else if(Number(txtAmount) > balance) {
		$("#error2").css("display", "inline");
		$("#error2").html("Amount can't be greater than $"+balance);
		$("#txtAmount").addClass("highlight");
		return false;
	} else { clearErrors(); }

	if(slcBankID.length < 1) {
		$("#error3").css("display", "inline");
		$("#error3").html("Please select bank");
		$("#slcBankID").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.three").offset().top }, 'slow'); }
		return false;
	} else { clearErrors(); }

	if(slcBankAcc=="---" || slcBankAcc.length < 1) {
		$("#error3").css("display", "inline");
		$("#error3").html("Select bank account");
		$("#slcBankAcc").addClass("highlight");
		if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.three").offset().top }, 'slow'); }
		return false;
	} else { clearErrors(); }

	swal({
		title: "Confirm?",
		text: "You going to pay sum of $"+txtAmount+" for this asset",
		type: "info",
		showCancelButton: true,
		closeOnConfirm: true
	})
    .then(value=>{
		$("label.process").css("display", "inline");
		$("#btnPay").attr("disabled", true);
		$("#btnPay").html("Wait...");
		$.post("./assets-and-shares/includes/finance.php?action=saveNew&dest=addAssetPay", { astID:astID, txtAmount:txtAmount, txtInWords:txtInWords, slcBankID:slcBankID, slcBankAcc:slcBankAcc, txtCheque:txtCheque, transDate:transDate}, function(data) {
			$("label.process").css("display", "none");
			var addedpos = data.search("added");
			if(addedpos==0) {
				var lastID = data.slice(6,21);
				swal({
					title: "Success!",
					text: "You successfully made payment for this asset",
					icon: "success",
					timer: 1500,
					button: false
				})
                .then(value=>{
						window.location = "./workplace.php?role="+myRole+"&task=settings&subtask=assets&action=showInfo&recID="+astID;
					}
				);
			} else {
				swal("Oops!", data, "error");
			}
			$("#btnPay").attr("disabled", false);
			$("#btnPay").html("Pay Now");
		});
	});
	return false;
}
function catchAsset(recID) {
	$.post("./assets-and-shares/includes/finance.php?action=get_recInfo&dest=getAsset", { recID:recID }, function(data) {
		$("div#foundNum").html('<label id="count">1</label> record has been selected.<span id="refresh"></span>');
		$("div#dataTable").html(data);
	});
	$("div.suggest").css("display", "none");
}


/* ------------------------------------------------------------
---------------------- pre-paid account -----------------------
--------------------------------------------------------------*/

function loadPaidAccs(pageLimit, perPage, period) {
	$("#dataTable div#loading").css("display", "inline");
	var dataString = 'pageLimit='+ pageLimit+'&period='+ period+'&perPage='+ perPage;
	$.ajax({
		type: "POST",
		url: "./assets-and-shares/includes/finance.php?action=loadTable&dest=allPaidAccs",
		data: dataString,
		cache: false,
		timeout: 2000,
		success: function(result){
			$("#dataTable div#loading").css("display", "none");
			$(".load_more_link").addClass('noneLink');
			$("#dataTable").append(result);
		},
	});
	return false;
}

function check_addPrepaidAcc() {
	var txtAName = $("#txtAName").val();
	var txtACode = $("#txtACode").val();

	if(myWhouse=="all" || myWhouse=="") {
		swal("Oops!", "While you won't work on specific wherehouse, \
		\nyou can't create any prepaid account completely.", "error");
		return false;
	}

	if(txtAName.length < 1) {
		$("#poperror61").css("display", "inline");
		$("#poperror61").html("Please account name");
		$("#txtAName").addClass("highlight");
		return false;
	} else { clearErrors(); }

	$("#btnAdd").attr("disabled", true);
	$("#btnAdd").html("wait...");
	$("div.suggest.one").css("display", "none");

	$.post("./assets-and-shares/includes/finance.php?action=saveNew&dest=addPrepaidPop", { txtAName:txtAName, txtACode:txtACode }, function(data) {
		var addedpos = data.search("added");
		if(addedpos==0) {
			var lastID = data.slice(6,21);
			//
			if(txtACode==""){txtACode="N/A";}
			$("input#accID").val(lastID);
			$("input#txtPrpaidAcc").val(txtAName);
			$("p#pCode").html(txtACode);
			$("p#pAmount, p#pBalance, p#pDrtion").html(0);
			$("div.displayInfo").css("display", "inline");
			$('input#addPaidAcssFrom').prop('checked', false);
			swal({
				title: "Success!",
				text: "You added new prepaid account successfully.",
				icon: "success",
				timer: 1500,
				button: false
			});
			$("#txtAName").val("");
			$("#txtACode").val("");
		} else {
			swal("Oops!", data, "error");
		}
		$("#btnAdd").attr("disabled", false);
		$("#btnAdd").html("Add");
	});
	return false;
}
function catchprepaid4form(accID,accName,accCode,amount,balance,duration) {
	$("#accID").val(accID);
	$("#txtPrpaidAcc").val(accName);
	$("p#pCode").html(accCode);
	$("p#pAmount").html('$'+amount);
	$("p#pBalance").html('$'+balance);
	$("p#pDrtion").html(duration);
	$("div.displayInfo").css("display", "inline");
	$("div.suggest.one").css("display", "none");
}
function simplifyPaidAcceAdd(){
	$("#txtPrpaidAcc").keyup(function(){
	var txtPrpaidAcc = $("#txtPrpaidAcc").val();
	if(txtPrpaidAcc!="") {
		$("div.suggest.one").css("display", "table-row");
		$.post("./assets-and-shares/includes/finance.php?action=searchRec&dest=pickPrpaidAcc",{ passedValue:txtPrpaidAcc }, function(data) {
			$("div.suggest.one").html(data);
		});
	} else { $("div.suggest.one").css("display", "none"); }
	clearErrors();
	});
	//
		$("#checkBlnce, #switchBalance").click(function(){
		$('div#switchBalance').toggleClass("switchOn");
		if (document.getElementById("beginBalance").checked == true) {
			document.getElementById("beginBalance").checked = false;

		} else {
			document.getElementById("beginBalance").checked = true;
			$("#slcBankID option:first").attr("selected", "selected");
			$("#slcBankAcc").html('');
		}
	});
	//
	$("#slcBankID, #slcBankAcc").change(function() {
		document.getElementById("beginBalance").checked = false;
		$('div#switchBalance').removeClass("switchOn");
	});
}
function check_addPrepaid(){
	var accID		= $("#accID").val();
	var txtPrpaidAcc= $("#txtPrpaidAcc").val();
	var transDate	= $("#transDate").val();
	var slcBankID	= $("#slcBankID").val();
	var slcBankAcc	= $("#slcBankAcc").val();
	var txtCheque	= $("#txtCheque").val();
	var txtAmount	= $("#txtAmount").val();
	var txtInWords	= $("#txtInWords").val();
	var txtDration	= $("#txtDration").val();

	var beginBalance	= $("input#beginBalance:checked").val();
	if(beginBalance!="on") { var beginBalance="no"; } else { var beginBalance="yes"; }

	if(myWhouse=="all" || myWhouse=="") {
		swal("Oops!", "While you won't work on specific wherehouse, \
		\nyou can't add prepaid payment record completely.", "error");
		return false;
	}

	if(accID.length < 1 || txtPrpaidAcc.length < 1) {
		$("#error1").css("display", "inline");
		$("#error1").html("Provide account name");
		$("#shareHolder").addClass("highlight");
		$("div.suggest").css("display", "none");
		return false;
	} else { clearErrors(); }
    if(beginBalance=="no"){
    	if(slcBankID.length < 1) {
    		$("#error2").css("display", "inline");
    		$("#error2").html("Please select bank");
    		$("#slcBankID").addClass("highlight");
    		return false;
    	} else { clearErrors(); }

    	if(slcBankAcc=="---" || slcBankAcc.length < 1) {
    		$("#error2").css("display", "inline");
    		$("#error2").html("Select bank account");
    		$("#slcBankAcc").addClass("highlight");
    		return false;
    	} else { clearErrors(); }
    }

	if(txtAmount.length < 1) {
		$("#error3").css("display", "inline");
		$("#error3").html("Type amount");
		$("#txtAmount").addClass("highlight");
		return false;
	} else if(Number(txtAmount) < 0.1) {
		$("#error3").css("display", "inline");
		$("#error3").html("Amount must be greater than 0");
		$("#txtAmount").addClass("highlight");
		return false;
	} else { clearErrors(); }

	if(txtDration.length < 1) {
		$("#error6").css("display", "inline");
		$("#error6").html("Type Duration");
		$("#txtDration").addClass("highlight");
		return false;
	} else if(Number(txtDration) < 0.1) {
		$("#error6").css("display", "inline");
		$("#error6").html("Duration must be greater than 0");
		$("#txtDration").addClass("highlight");
		return false;
	} else { clearErrors(); }

	$("label.process").css("display", "inline");
	$("#btnSave").attr("disabled", true);
	$("#btnSave").html("Wait...");

	$.post("./assets-and-shares/includes/finance.php?action=saveNew&dest=addPrepaidAcc", { accID:accID, txtAmount:txtAmount, txtInWords:txtInWords,  beginBalance:beginBalance, txtDration:txtDration, transDate:transDate, slcBankID:slcBankID, slcBankAcc:slcBankAcc, txtCheque:txtCheque}, function(data) {
		var addedpos = data.search("added");
		$("label.process").css("display", "none");
		if(addedpos==0) {
			var lastID = data.slice(6,21);
			swal({
				title: "Success!",
				text: "You added new prepaid payment successfully.",
				icon: "success",
				timer: 1500,
				button: false
			})
                .then(value=>{
					window.location = "./workplace.php?role="+myRole+"&task=finance&subtask=paidAccs\
					&action=showInfo&recID="+accID;
				}
			);
		} else {
			swal("Oops!", data, "error");
		}
		$("#btnSave").attr("disabled", false);
		$("#btnSave").html("Save");
	});
	return false;
}
function check_deprePrepaid(){
	var accID		= $("#accID").val();
	var txtPrpaidAcc= $("#txtPrpaidAcc").val();
	var transDate	= $("#transDate").val();
	var txtAmount	= $("#txtAmount").val();
	var txtInWords	= $("#txtInWords").val();
	var balance		= $("#balance").val();
	var txtRemarks	= $("#txtRemarks").val();
	var theMonth	= $("#theMonth").val();

	if(myWhouse=="all") {
		swal("Oops!", "While you won't work on specific wherehouse, \
		\nyou can't make depreciation for any prepaid account completely.", "error");
		return false;
	}

	if(accID.length < 1 || txtPrpaidAcc.length < 1) {
		$("#error1").css("display", "inline");
		$("#error1").html("Provide account name");
		$("#shareHolder").addClass("highlight");
		$("div.suggest").css("display", "none");
		return false;
	} else { clearErrors(); }

	if(txtAmount.length < 1) {
		$("#error3").css("display", "inline");
		$("#error3").html("Type amount");
		$("#txtAmount").addClass("highlight");
		return false;
	} else if(Number(txtAmount) < 0.1) {
		$("#error3").css("display", "inline");
		$("#error3").html("Amount must be greater than 0");
		$("#txtAmount").addClass("highlight");
		return false;
	} else { clearErrors(); }

	if(Number(balance) < Number(txtAmount)) {
		$("#error3").css("display", "inline");
		$("#error3").html("Amount can't be greater than balance");
		$("#txtAmount").addClass("highlight");
		return false;
	} else { clearErrors(); }

	swal({
		title: "Confirm?",
		text: "You going to generate expense this month "+theMonth,
		type: "info",
		showCancelButton: true,
		closeOnConfirm: true
	})
                .then(value=>{
		$("label.process").css("display", "inline");
		$("#btnSave").attr("disabled", true);
		$("#btnSave").html("Wait...");
		$.post("./assets-and-shares/includes/finance.php?action=saveNew&dest=addDeprPrepaid", { accID:accID, txtAmount:txtAmount, txtInWords:txtInWords, transDate:transDate, txtRemarks:txtRemarks, theMonth:theMonth}, function(data) {
			$("label.process").css("display", "none");
			if(data=="depreciated") {
				swal({
					title: "Success!",
					text: "You generated monthly expense for prepaid account "+txtPrpaidAcc,
					icon: "success",
					timer: 1500,
					button: false
				})
                .then(value=>{
						window.location = "./workplace.php?role="+myRole+"&task=finance&subtask=paidAccs\
						&action=showInfo&recID="+accID;
					}
				);
			} else {
				swal("Oops!", data, "error");
			}
			$("#btnSave").attr("disabled", false);
			$("#btnSave").html("Generate Expense");
		});
	});
	return false;
}
function check_editPrepaid() {
	var accID		= $("#accID").val();
	var accName		= $("#accName").val();
	var accCode		= $("#accCode").val();
	var slcStatus	= $("#slcStatus").val();

	if(accID.length < 1 || accName.length < 1) {
		$("#error1").css("display", "inline");
		$("#error1").html("Provide account name");
		$("#accName").addClass("highlight");
		return false;
	} else { clearErrors(); }

	$("label.process").css("display", "inline");
	$("#btnUpdate").attr("disabled", true);
	$("#btnUpdate").html("Wait...");

	$.post("./assets-and-shares/includes/finance.php?action=updateExist&dest=editPrepaid", { accID:accID, accName:accName, accCode:accCode, slcStatus:slcStatus}, function(data) {
		$("label.process").css("display", "none");
		if(data=="updated") {
			swal({
				title: "Success!",
				text: "You updated prepaid account successfully.",
				icon: "success",
				timer: 1500,
				button: false,
			})
                .then(value=>{
					window.location = "./workplace.php?role="+myRole+"&task=finance&subtask=paidAccs\
					&action=showInfo&recID="+accID;
				}
			);
		} else {
			swal("Oops!", data, "error");
		}
		$("#btnUpdate").attr("disabled", false);
		$("#btnUpdate").html("Update");
	});
	return false;
}
//
function removePaidAccUsage(accID,actvtyID){
    swal({
        title: "Are you sure?",
        text: "You going to remove this pre-paid activity !",
        icon: "warning",
        dangerMode:true,
        buttons:["Cancel","Remove"]
    })
                .then(value=>{
        $.post("./assets-and-shares/includes/finance.php?action=deleteRec&dest=delPaidAccUsage", { accID:accID,actvtyID:actvtyID }, function(data) {
            if(data=="deleted") {
                swal({
                    title: "Success!",
                    text: "Selected activity has been successfully removed.",
                    icon: "success",
                    timer: 1500,
                    button: false
                })
                .then(value=>{
                    location.reload();
                });

            } else {
                swal("Oops", data, "error");
            }
        });
    });
    return false;
}
//
function catchPaidAcc(recID) {
	$.post("./assets-and-shares/includes/finance.php?action=get_recInfo&dest=getPaidAcc", { recID:recID }, function(data) {
		$("div#foundNum").html('<label id="count">1</label> record has been selected.<span id="refresh"></span>');
		$("div#dataTable").html(data);
	});
	$("div.suggest").css("display", "none");
}

/* ---------------------------------------------------------------
------------------------ Customer Deposit  ------------------------
-----------------------------------------------------------------*/

function loadCustDeposit(pageLimit, perPage, period) {
	$("#dataTable div#loading").css("display", "inline");
	var dataString = 'pageLimit='+ pageLimit+'&period='+ period+'&perPage='+ perPage;
	$.ajax({
		type: "POST",
		url: "./assets-and-shares/includes/finance.php?action=loadTable&dest=allcustDeposit",
		data: dataString,
		cache: false,
		timeout: 2000,
		success: function(result){
            /*$("#dataTable div#loading").css("display", "none");
            $(".load_more_link").addClass('noneLink');
            $("#dataTable").append(result);*/
            console.log(result);
            let found = JSON.parse(result);

            $('label#count').html(found.rowsFound)

            let columns = [];
            let dataset = found.dataset;

            columns = [
                {"title": "Action", "className": "gl-3", "render": function(data, type, row, meta) {
                    return `<div class="cave button">
                        <a class="view fa fa-eye" href="${row.showLink}"></a>
                        <a class="view fa fa-pencil" href="${row.updateLink}"></a>
                        <a class="view fa fa-trash masax rec${row.actvtyID}" onclick="delCustDeposit('${row.actvtyID}','${row.type}')" ></a>
                    </div>`;
                }},

                {"title": "TR Number", "data" : "addedDate", "className": "gl-2",  "render": function(data, type, row, meta) {
                    return `<div>
                        <a href="${row.showLink}">${row.transRef}</a>
                    </div>`;
                }},

                {"title": typeLabel, "data" : "invoiceNo", "className": "gl-2",  "render": function(data, type, row, meta) {
                    return `<div>${row.clientName}</div>`;
                }},

                {"title": "Account Details", "data" : "invoiceNo", "className": "gl-2",  "render": function(data, type, row, meta) {
                    return `<div>${row.type2}</div>`;
                }},

                {"title": "Amount", "data" : "clientName", "className": "gl-2",  "render": function(data, type, row, meta) {
                    return `<p>${format_moneyOne(row.amount)}</p>`;
                }},

            ]

            // console.log(columns)

            // return false;
            let dataTable = new DataTable('#allCustomersDeposit', {
                data: dataset,
                paging: true,
                "bDestroy": true,
                "columns": columns
            })
        },
	});
	return false;
}
function simplifyAddcustDeposit() {
	$("#checkBlnce, #switchBalance").click(function(){
		$('div#switchBalance').toggleClass("switchOn");
		if (document.getElementById("beginBalance").checked == true) {
			document.getElementById("beginBalance").checked = false;
			$("#btnCDWithdarw").attr("disabled",false);
		} else {
			document.getElementById("beginBalance").checked = true;
			$("#slcBankID option:first").attr("selected", "selected");
			$("#slcBankAcc").html('');
			$("#btnCDWithdarw").attr("disabled",true);
		}
	});
	//
	$("#slcBankID, #slcBankAcc").change(function() {
		document.getElementById("beginBalance").checked = false;
		$('div#switchBalance').removeClass("switchOn");
	});
	// deposit button
	$("#btnCDDeposit").click(function() {
		var actionType = "deposit";
		insert_custDeposit(actionType); return false;
	});
	// withdraw button
	$("#btnCDWithdarw").click(function() {
		var actionType = "withdraw";
		insert_custDeposit(actionType); return false;
	});
}
function insert_custDeposit(actionType) {
	var clientID	= $("#clientID").val();
	var txtClient	= $("#txtClient").val();

	var slcUsageTerms	= "withdraw"; //$("#slcUsageTerms").val();
	var beginBalance	= $("input#beginBalance:checked").val();
	if(beginBalance!="on") { var beginBalance="no"; } else { var beginBalance="yes"; }

	var slcBankID	= $("#slcBankID").val();
	var slcBankAcc	= $("#slcBankAcc").val();
	var txtCheque	= $("#txtCheque").val();
	var txtAmount	= $("#txtAmount").val();
	var txtInWords	= $("#txtInWords").val();
	var txtRemarks	= $("#txtRemarks").val();
	var transDate	= $("#transDate").val();

	if(clientID.length < 1 || txtClient.length < 1) {
		$("#error1").css("display", "inline");
		$("#error1").html("Provide "+typeLabel+" name");
		$("#txtClient").addClass("highlight");
		$("div.suggest").css("display", "none");
		return false;
	} else { clearErrors(); }

	if(beginBalance=="no") {
		if(slcBankID.length < 1) {
			$("#error2").css("display", "inline");
			$("#error2").html("Please select bank");
			$("#slcBankID").addClass("highlight");
			return false;
		} else { clearErrors(); }

		if(slcBankAcc=="---" || slcBankAcc.length < 1) {
			$("#error2").css("display", "inline");
			$("#error2").html("Select bank account");
			$("#slcBankAcc").addClass("highlight");
			return false;
		} else { clearErrors(); }
	}

	if(txtAmount.length < 1) {
		$("#error3").css("display", "inline");
		$("#error3").html("Type amount");
		$("#txtAmount").addClass("highlight");
		return false;
	} else if(Number(txtAmount) < 0.1) {
		$("#error3").css("display", "inline");
		$("#error3").html("Amount must be greater than 0");
		$("#txtAmount").addClass("highlight");
		return false;
	} else { clearErrors(); }

	$("label.process").css("display", "inline");
	if(actionType=="deposit") {
		$("#btnCDDeposit").attr("disabled", true); $("#btnCDDeposit").html("Wait...");
	} else if(actionType=="withdraw") {
		$("#btnCDWithdarw").attr("disabled", true); $("#btnCDWithdarw").html("Wait...");
	}

	$.post("./assets-and-shares/includes/finance.php?action=saveNew&dest=addcustDeposit", { transType:actionType, clientID:clientID, clientName:txtClient, slcUsageTerms:slcUsageTerms, beginBalance:beginBalance, slcBankID:slcBankID, slcBankAcc:slcBankAcc, txtCheque:txtCheque, txtAmount:txtAmount, txtInWords:txtInWords, txtRemarks:txtRemarks, transDate:transDate }, function(data) {
		var addedpos = data.search("added");
		$("label.process").css("display", "none");
		if(addedpos==0) {
			var lastID = data.slice(6,21);
			swal({
				title: "Success!",
				text: "You added new record into account "+typeLabel+" deposit.",
				icon: "success",
				timer: 1500,
				button: false
			})
                .then(value=>{
				if(beginBalance=="no"){
					window.location = "./workplace.php?role="+myRole+"&task=finance&subtask=custDeposit\
					&type="+actionType+"&action=showInfo&recID="+lastID;
				} else {
					window.location = "./workplace.php?role="+myRole+"&task=finance&subtask=custDeposit";
					}
				}
			);
		} else if(data=="dueBalance<amount") {
			swal("Oops!", "The amount deposited from "+txtClient+" \n is less than amount you just typed in.", "error");
			if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.four").offset().top }, 'slow'); }
		} else {
			swal("Oops!", data, "error");
		}
		if(actionType=="deposit") {
			$("#btnCDDeposit").attr("disabled", false); $("#btnARReceive").html("Deposit");
		} else if(actionType=="withdraw") {
			$("#btnCDWithdarw").attr("disabled", false); $("#btnCDWithdarw").html("Withdraw");
		}

	});
	return false;
}
function check_editCustDeposit() {
	var changedID	    = $("#changedID").val();
	var transType	    = $("#transType").val();
	var beginblnce	    = $("#beginblnce").val();

	var clientID	    = $("#clientID").val();
	var txtClient	    = $("p#pCName").html();
	var slcUsageTerms	= "withdraw"; //$("#slcPayTerms").val();
	var slcBankID	    = $("#slcBankID").val();
	var slcBankAcc	    = $("#slcBankAcc").val();
	var txtCheque	    = $("#txtCheque").val();
	var txtAmount	    = $("#txtAmount").val();
	var txtInWords	    = $("#txtInWords").val();
	var txtRemarks	    = $("#txtRemarks").val();

	if(clientID.length < 1) {
		$("#error1").css("display", "inline");
		$("#error1").html("Provide "+typeLabel+" name");
		$("#txtClient").addClass("highlight");
		return false;
	} else { clearErrors(); }

	if(beginblnce!="beginblnce") {
		if(slcBankID.length < 1) {
			$("#error2").css("display", "inline");
			$("#error2").html("Please select bank");
			$("#slcBankID").addClass("highlight");
			return false;
		} else { clearErrors(); }

		if(slcBankAcc=="---" || slcBankAcc.length < 1) {
			$("#error2").css("display", "inline");
			$("#error2").html("Select bank account");
			$("#slcBankAcc").addClass("highlight");
			return false;
		} else { clearErrors(); }
	}

	if(txtAmount.length < 1) {
		$("#error3").css("display", "inline");
		$("#error3").html("Type amount");
		$("#txtAmount").addClass("highlight");
		return false;
	} else if(Number(txtAmount) < 0.1) {
		$("#error3").css("display", "inline");
		$("#error3").html("Amount must be greater than 0");
		$("#txtAmount").addClass("highlight");
		return false;
	} else { clearErrors(); }

	$("label.process").css("display", "inline");
	$("#btnUpdate").attr("disabled", true);
	$("#btnUpdate").html("Wait...");

	$.post("./assets-and-shares/includes/finance.php?action=updateExist&dest=editCustDeposit", { changedID:changedID, transType:transType, clientID:clientID, clientName:txtClient, beginblnce:beginblnce, slcUsageTerms:slcUsageTerms, slcBankID:slcBankID, slcBankAcc:slcBankAcc, txtCheque:txtCheque, txtAmount:txtAmount, txtInWords:txtInWords, txtRemarks:txtRemarks }, function(data) {
		$("label.process").css("display", "none");
		if(data=="updated") {
			swal({
				title: "Success!",
				text: "You updated account receivable details successfully.",
				icon: "success",
				timer: 1500,
				button: false
			})
                .then(value=>{
					window.location = "./workplace.php?role="+myRole+"&task=finance&subtask=custDeposit\
					&type="+transType+"&action=showInfo&recID="+changedID;
				}
			);
		} else if(data=="dueBalance<amount") {
			swal("Oops!", "The amount deposited from "+txtClient+" \n is less than amount you just typed in.", "error");
			if(window.innerWidth<=768) { $('html, body').animate({ scrollTop: $(".record.three").offset().top }, 'slow'); }
		} else {
			swal("Oops!", data, "error");
		}
		$("#btnUpdate").attr("disabled", false);
		$("#btnUpdate").html("Update");

	});
	return false;
}
function catchCustDeposit(recID) {
	$.post("./assets-and-shares/includes/finance.php?action=get_recInfo&dest=getCustDeposit", { recID:recID }, function(data) {
		$("div#foundNum").html('<label id="count">1</label> record has been selected.<span id="refresh"></span>');
		$("div#dataTable").html(data);
	});
	$("div.suggest").css("display", "none");
}
function delCustDeposit(recID,type) {
	swal({
		title: "Are you sure?",
		text: "You going to delete this "+typeLabel+" "+type+" !",
		icon: "warning",
        dangerMode:true,
        buttons:["Cancel","Delete"]
	})
    .then(willDelete=>{
        if(willDelete) {
    		$.post("./assets-and-shares/includes/finance.php?action=deleteRec&dest=delCustDeposit", { recID:recID }, function(data) {
    			if(data=="deleted") {
    				swal({
    					title: "Success!",
    					text: "Selected account receivable record has been deleted.",
    					icon: "success",
    					timer: 1500,
    					button: false
    				})
                .then(value=>{
    					location.reload();
    				});

    			} else {
    				swal("Oops", data, "error");
    			}
    		});
        }
	});
	return false;
}

/* ---------------------------------------------------------------
------------------------ Vendor Deposit  ------------------------
-----------------------------------------------------------------*/

function loadVendorDeposit(pageLimit, perPage, period) {
	$("#dataTable div#loading").css("display", "inline");
	var dataString = 'pageLimit='+ pageLimit+'&period='+ period+'&perPage='+ perPage;
	$.ajax({
		type: "POST",
		url: "./assets-and-shares/includes/finance.php?action=loadTable&dest=allVendorDeposit",
		data: dataString,
		cache: false,
		timeout: 2000,
		success: function(result){
			$("#dataTable div#loading").css("display", "none");
			$(".load_more_link").addClass('noneLink');
			$("#dataTable").append(result);
		},
	});
	return false;
}
function check_addVendor4Pop() {

    var txtVName    = $("#txtVName").val();
    var txtVPhone   = $("#txtVPhone").val();
    var txtVEmail   = $("#txtVEmail").val();
    var txtAddress  = $("#txtAddress").val();
    var slcCurrency     = $("#slcCurrency").val(); var slcCurrency2     = $("#slcCurrency :selected").text();
    var slcCountry  = $("#slcCountry").val(); var slcCountry2  = $("#slcCountry :selected").text();
    var txtComm     = $("#txtComm").val();

    if(txtVName.length < 1) {
        $("#poperror1").css("display", "inline");
        $("#poperror1").html("Provide vendor's full namess");
        $("#txtVName").addClass("highlight");
        return false;
    } else { clearErrors(); }

    if(txtVPhone.length < 1) {
        $("#poperror2").css("display", "inline");
        $("#poperror2").html("Phone number is missing");
        $("#txtVPhone").addClass("highlight");
        return false;
    } else { clearErrors(); }

    if(txtVEmail.length > 0) {
        var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
        if(!txtVEmail.match(emailExp)) {
            $("#poperror3").css("display", "inline");
            $("#poperror3").html("invalid email address");
            $("#txtVEmail").addClass("highlight");
            return false;
        } else { clearErrors(); }
    }

    if(slcCurrency==null || slcCurrency=="") {
        $("#poperror4").css("display", "inline");
        $("#poperror4").html("Please select currency");
        $("#slcCurrency").addClass("highlight");
        return false;
    } else { clearErrors(); }

        if(txtComm.length < 1) {
        $("#poperror5").css("display", "inline");
        $("#poperror5").html("Please provide commission");
        $("#txtComm").addClass("highlight");
        return false;
    } else { clearErrors(); }

    $(".btnAdd").attr("disabled", true);
    $(".btnAdd").html("Wait...");

    $.post("./includes/inventory.php?action=saveNew&dest=addVendorFromPopUp", { txtName:txtVName, txtPhone:txtVPhone, txtEmail:txtVEmail,  slcCurrency:slcCurrency,  txtAddress:txtAddress,  txtComm:txtComm,  slcCountry:slcCountry }, function(data) {
        var addedpos = data.search("added");
        $("label.process").css("display", "none");
        if(addedpos==0) {
            var lastID = data.slice(6,21);
            swal({
                title: "Success!",
                text: "You added new vendor successfully.",
                icon: "success",
                timer: 1500,
                button: false,
            });
            $("#txtVName, #txtVPhone, #txtVEmail, #txtAddress, #txtComm").val('');
            $("input#vendorID").val(lastID);
            $("input#txtVendorName").val(txtVName);
            $("input#txtComm").val(txtComm);
            $("div.displayInfo.vendor").css("display", "inline");
            $("p#pVName").html(txtVName);
            $("p#pVPhone").html(txtVPhone);
            $("p#pVCountry").html(slcCountry2);
            $("p#pVCurrency").html(slcCurrency2);
            $("p#pVBalance").html(0);

            $.post("./assets-and-shares/includes/finance.php?action=get_recInfo&dest=getExchangeRate",{ slcCurrency:slcCurrency }, function(data) {
            $("input#txtRate").val(data);
            });
            $("div.suggest.vendor").css("display", "none");
             $('input#addVendorForm').prop('checked', false);

        } else {
            swal("Oops!", data, "error");
        }
        $("#btnAdd").attr("disabled", false);
        $("#btnAdd").html("Add");
    });
    return false;

}
function catchVndr4dpst(vndID,fullname,phone,countryName,currency,currencyName,rate,commission,balance,outStanding,symbol) {
	$("input#vendorID").val(vndID);
	$("input#txtRate").val(rate);
	$("input#currency").val(currency);
	$("input#txtCommission").val(commission);
	$("input#txtVendorName").val(fullname);
	$("div.displayInfo.vendor").css("display", "inline");
	$("p#pVName").html(fullname);
	$("p#pVPhone").html(phone);
    $("p#pVCountry").html(countryName+" , "+currencyName);
	$("p#pVComm").html(commission+"%");
	if(outStanding>0) {
        $("p#pVOutStd").html(outStanding+" USD");
    } else {
        $("p#pVOutStd").html(outStanding);
    }

    if(balance>0) {
		$("p#pVBalance").html(balance+" USD");
	} else {
		$("p#pVBalance").html(balance+" USD");
	}
    $("div.suggest").css("display", "none");
    $("span.currency").css("display", "block");
	$("span.check.foriegn").html(symbol);
}
function simplifyAddVendorDeposit() {
$("#txtVendorName").keyup(function(){
	var vendorName = $("#txtVendorName").val();
	if(vendorName!="") {
		$("div.suggest.one").css("display", "table-row");
		$.post("./assets-and-shares/includes/finance.php?action=searchRec&dest=pickVendor",{ passedValue:vendorName }, function(data) {
			$("div.suggest.one").html(data);
		});
	} else { $("div.suggest.one").css("display", "none"); }
	clearErrors();
});

	$("#checkBlnce, #switchBalance").click(function(){
		$('div#switchBalance').toggleClass("switchOn");
		if (document.getElementById("beginBalance").checked == true) {
			document.getElementById("beginBalance").checked = false;
            $("div.beginPart").css("display","block");

		} else {
			document.getElementById("beginBalance").checked = true;
			$("#slcBankID option:first").attr("selected", "selected");
            $("#slcBankAcc").html('');
			$("div.beginPart").css("display","none");
		}
	});
	//
	$("#slcBankID, #slcBankAcc").change(function() {
		document.getElementById("beginBalance").checked = false;
		$('div#switchBalance').removeClass("switchOn");
	});
	$("#txtAmount").on("keyup change", function() {
			 $("#ttlAmnt2destination,#txtNetCash,#txtNetAfterComm,#txtNetComm,#txtTtlXawala,#txtNetAmount,#txtXawala").val('');
		});
    $("input#txtXawala").on("keyup change", function (){
         $("#ttlAmnt2destination,#txtNetCash,#txtNetAfterComm,#txtNetComm,#txtTtlXawala").val(0);
        var amount = parseFloat($("#txtAmount").val());
        var txtXawala = parseFloat($("#txtXawala").val());
        var ttlXawala = 0;
        var netAmount= 0;
          if(txtXawala != "" && txtXawala > 0 && amount != "" && amount > 0 ) {
               ttlXawala = Number(txtXawala/amount).toFixed(decimalPt);
               netAmount = Number(amount-txtXawala).toFixed(decimalPt);
               $("#txtTtlXawala").val(ttlXawala);
               $("#txtNetAmount").val(netAmount);

               //
              var comm = parseFloat($("#txtCommission").val());
                var rate = parseFloat($("#txtRate").val());
                 var ttlAmnt2destination = 0;
                if(comm != "" && comm > 0 && amount != "" && amount > 0) {
                    var ttlCom = (netAmount*(comm/100)).toFixed(decimalPt);
                       var netCash = Number(netAmount).toFixed(decimalPt);
                       if(rate>0 && rate!=""){
                         ttlAmnt2destination = (netCash*rate).toFixed(decimalPt);
                       }

                       $("#txtNetComm").val(ttlCom);
                       $("#txtNetAfterComm").val(netCash);
                       $("#ttlAmnt2destination").val(ttlAmnt2destination);
                    } else {
                        ttlAmnt2destination = (netAmount*rate).toFixed(decimalPt);
                       $("#txtNetComm").val(0);
                       $("#txtNetAfterComm").val(netAmount);
                       $("#ttlAmnt2destination").val(ttlAmnt2destination);
                    }
               //

            } else {
                $("#txtTtlXawala,#txtNetAmount").val('');
            }
    });
//
	$("input#txtCommission").on("keyup change", function (){
		 $("#ttlAmnt2destination,#txtNetAfterComm,#txtNetComm").val(0);
		var amount = parseFloat($("#txtNetAmount").val());
            var comm = $("#txtCommission").val();
				var rate = parseFloat($("#txtRate").val());
				 var ttlAmnt2destination = 0;

				if(comm != "" && comm > 0 && amount != "" && amount > 0) {
					var ttlCom = (amount*(comm/100)).toFixed(decimalPt);
					   var netCash = Number(amount).toFixed(decimalPt);
					   if(rate>0 && rate!=""){
					   	 ttlAmnt2destination = (netCash*rate).toFixed(decimalPt);
					   }

					   $("#txtNetComm").val(ttlCom);
					   $("#txtNetAfterComm").val(netCash);
					   $("#ttlAmnt2destination").val(ttlAmnt2destination);
					} else {
                        ttlAmnt2destination = (amount*rate).toFixed(decimalPt);
                       $("#txtNetComm").val(0);
                       $("#txtNetAfterComm").val(amount);
                       $("#ttlAmnt2destination").val(ttlAmnt2destination);
                    }

	});
	$("input#txtRate").on("keyup change", function (){
		var rate = parseFloat($("#txtRate").val());
		var amount = parseFloat($("#txtNetAfterComm").val());
        if(amount<=0 || amount==""){amount=parseFloat($("#txtNetAmount").val())}
            if(rate>0 && rate!=""){
        		ttlAmnt2destination = (amount*rate).toFixed(decimalPt);
        		$("#ttlAmnt2destination").val(ttlAmnt2destination);
            } else {
                $("#ttlAmnt2destination").val(0);
            }
	});
}
function check_addVendorDeposit() {
	var vendorID	= $("#vendorID").val();
	var vendorName	= $("#txtVendorName").val();
	var slcBankID	= $("#slcBankID").val();
	var slcBankAcc	= $("#slcBankAcc").val();
	var txtAmount	= $("#txtAmount").val();
	var txtXawala	= $("#txtXawala").val();
	var txtNetAmount = $("#txtNetAmount").val();
	var txtComm		= $("#txtCommission").val();
	var txtNetComm	= $("#txtNetComm").val();
	var txtNetDeposit = $("#txtNetAfterComm").val();
	var txtRate		= $("#txtRate").val();
	var slcCurrency	= $("#currency").val();
	var ttlAmnt2dest = $("#ttlAmnt2destination").val();
	var txtInWords	= $("#txtInWords").val();
	var txtRemarks	= $("#txtRemarks").val();
    var transDate   = $("#transDate").val();
	var txtXawalaName	= $("#txtXawalaName").val();
    var beginBalance    = $("input#beginBalance:checked").val();
    if(beginBalance!="on") { var beginBalance="no"; } else { var beginBalance="yes"; }


	if(vendorID.length < 1 || vendorName.length < 1) {
		$("#error1").css("display", "inline");
		$("#error1").html("Provide vendor name");
		$("#txtVendorName").addClass("highlight");
		$("div.suggest").css("display", "none");
		return false;
	} else { clearErrors(); }

	if(txtAmount.length < 1) {
		$("#error2").css("display", "inline");
		$("#error2").html("Type amount");
		$("#txtAmount").addClass("highlight");
		return false;
	} else if(Number(txtAmount) < 0.1) {
		$("#error2").css("display", "inline");
		$("#error2").html("Amount must be greater than 0");
		$("#txtAmount").addClass("highlight");
		return false;
	} else { clearErrors(); }
if(beginBalance=="no"){
	if(txtXawala.length < 1) {
		$("#error3").css("display", "inline");
		$("#error3").html("Type xawala cost");
		$("#txtXawala").addClass("highlight");
		return false;
	} else if(Number(txtXawala) <= 0) {
		$("#error3").css("display", "inline");
		$("#error3").html("Xawala Cost must be greater than 0");
		$("#txtXawala").addClass("highlight");
		return false;
	} else { clearErrors(); }

	if(txtComm.length < 1) {
		$("#error4").css("display", "inline");
		$("#error4").html("Type commission");
		$("#txtCommission").addClass("highlight");
		return false;
	} else { clearErrors(); }

	if(slcBankID.length < 1) {
		$("#error5").css("display", "inline");
		$("#error5").html("Please select bank");
		$("#slcBankID").addClass("highlight");
		return false;
	} else { clearErrors(); }

	if(slcBankAcc=="---" || slcBankAcc.length < 1) {
		$("#error5").css("display", "inline");
		$("#error5").html("Select bank account");
		$("#slcBankAcc").addClass("highlight");
		return false;
	} else { clearErrors(); }

		if(txtRate.length < 1) {
		$("#error6").css("display", "inline");
		$("#error6").html("Type exchange rate");
		$("#txtRate").addClass("highlight");
		return false;
	} else if(Number(txtRate) <= 0) {
		$("#error6").css("display", "inline");
		$("#error6").html("Exchange rate must be greater than 0");
		$("#txtRate").addClass("highlight");
		return false;
	} else { clearErrors(); }
    }

	$("label.process").css("display", "inline");
	$("#btnVndrDeposit").attr("disabled", true);
	$("#btnVndrDeposit").html("Wait...");

	$.post("./assets-and-shares/includes/finance.php?action=saveNew&dest=addVendorDeposit", {
			vendorID:vendorID,
			vendorName:vendorName,
			slcBankID:slcBankID,
			slcBankAcc:slcBankAcc,
			txtAmount:txtAmount,
			txtInWords:txtInWords,
			txtXawala:txtXawala,
			txtNetAmount:txtNetAmount,
			txtComm:txtComm,
			txtNetComm:txtNetComm,
			txtNetDeposit:txtNetDeposit,
			txtRate:txtRate,
			slcCurrency:slcCurrency,
			ttlAmnt2dest:ttlAmnt2dest,
			txtRemarks:txtRemarks,
            transDate:transDate ,
            txtXawalaName:txtXawalaName ,
			beginBalance:beginBalance },
		 function(data) {
		var addedpos = data.search("added");
		$("label.process").css("display", "none");
		if(addedpos==0) {
			var lastID = data.slice(6,21);
			swal({
				title: "Success!",
				text: "You added new record into account "+typeLabel+" deposit.",
				icon: "success",
				timer: 1500,
				button: false
			})
                .then(value=>{
                    if(beginBalance=="no"){
    					window.location = "./workplace.php?role="+myRole+"&task=finance&subtask=vendorDeposit&action=showInfo&recID="+lastID;
                    } else {
                        window.location = "./workplace.php?role="+myRole+"&task=finance&subtask=vendorDeposit";
                    }

				}
			);
		} else {
			swal("Oops!", data, "error");
		}

	$("#btnVndrDeposit").attr("disabled", false);
	$("#btnVndrDeposit").html("Deposit");


	});
	return false;
}
function check_editVendorDeposit() {
    var changedID   = $("#changedID").val();
    var vendorID   = $("#vendorID").val();
	var vendorName	= $("#txtVendorName").val();
    var txtRate     = $("#txtRate").val();
    var payID       = $("#payID").val();
    var txtAmount   = $("#txtAmount").val();
    var txtInWords  = $("#txtInWords").val();
    var txtXawala   = $("#txtXawala").val();
    var txtXawalaName = $("#txtXawalaName").val();
    var txtNetAmount  = $("#txtNetAmount").val();
    var txtComm = $("#txtCommission").val();
    var txtNetComm    = $("#txtNetComm").val();
    var txtNetDeposit = $("#txtNetAfterComm").val();
    var slcBankID     = $("#slcBankID").val();
    var slcBankAcc    = $("#slcBankAcc").val();
    var txtRemarks       = $("#txtRemarks").val();
    var ttlAmnt2dest  = $("#ttlAmnt2destination").val();


    if(txtAmount.length < 1) {
        $("#error2").css("display", "inline");
        $("#error2").html("Type amount");
        $("#txtAmount").addClass("highlight");
        return false;
    } else if(Number(txtAmount) < 0.1) {
        $("#error2").css("display", "inline");
        $("#error2").html("Amount must be greater than 0");
        $("#txtAmount").addClass("highlight");
        return false;
    } else { clearErrors(); }

        if(txtXawala.length < 1) {
        $("#error3").css("display", "inline");
        $("#error3").html("Type xawala cost");
        $("#txtXawala").addClass("highlight");
        return false;
    } else if(Number(txtXawala) <= 0) {
        $("#error3").css("display", "inline");
        $("#error3").html("Xawala Cost must be greater than 0");
        $("#txtXawala").addClass("highlight");
        return false;
    } else { clearErrors(); }

    if(txtComm.length < 1) {
        $("#error4").css("display", "inline");
        $("#error4").html("Type commission");
        $("#txtCommission").addClass("highlight");
        return false;
    } else { clearErrors(); }

    if(slcBankID.length < 1) {
        $("#error5").css("display", "inline");
        $("#error5").html("Please select bank");
        $("#slcBankID").addClass("highlight");
        return false;
    } else { clearErrors(); }

    if(slcBankAcc=="---" || slcBankAcc.length < 1) {
        $("#error5").css("display", "inline");
        $("#error5").html("Select bank account");
        $("#slcBankAcc").addClass("highlight");
        return false;
    } else { clearErrors(); }

        if(txtRate.length < 1) {
        $("#error6").css("display", "inline");
        $("#error6").html("Type exchange rate");
        $("#txtRate").addClass("highlight");
        return false;
    } else if(Number(txtRate) <= 0) {
        $("#error6").css("display", "inline");
        $("#error6").html("Exchange rate must be greater than 0");
        $("#txtRate").addClass("highlight");
        return false;
    } else { clearErrors(); }


	$("label.process").css("display", "inline");
	$("#btnUpdate").attr("disabled", true);
	$("#btnUpdate").html("Wait...");
    //alert(txtXawalaName);return false;
    $.post("./assets-and-shares/includes/finance.php?action=updateExist&dest=editVendorDeposit", {
            changedID:changedID,
            vendorID:vendorID,
            vendorName:vendorName,
            slcBankID:slcBankID,
            slcBankAcc:slcBankAcc,
            txtAmount:txtAmount,
            txtInWords:txtInWords,
            txtXawala:txtXawala,
            txtNetAmount:txtNetAmount,
            txtComm:txtComm,
            txtNetComm:txtNetComm,
            txtNetDeposit:txtNetDeposit,
            txtRate:txtRate,
            ttlAmnt2dest:ttlAmnt2dest,
            txtRemarks:txtRemarks,
            txtXawalaName:txtXawalaName }, function(data) {
		$("label.process").css("display", "none");

		if(data=="updated") {
			swal({
				title: "Success!",
				text: "You updated vendor deposit details successfully.",
				icon: "success",
				timer: 1500,
				button: false
			})
                .then(value=>{
					window.location = "./workplace.php?role="+myRole+"&task=finance&subtask=vendorDeposit\
					&action=showInfo&recID="+payID;
				}
			);
		} else {
			swal("Oops!", data, "error");
		}
		$("#btnUpdate").attr("disabled", false);
		$("#btnUpdate").html("Update");

	});
	return false;
}
function catchVendorDeposit(recID) {
	$.post("./assets-and-shares/includes/finance.php?action=get_recInfo&dest=getVendorDeposit", { recID:recID }, function(data) {
		$("div#foundNum").html('<label id="count">1</label> record has been selected.<span id="refresh"></span>');
		$("div#dataTable").html(data);
	});
	$("div.suggest").css("display", "none");
}
function delVendorDeposit(recID,type) {
	swal({
		title: "Are you sure?",
		text: "You going to delete this "+typeLabel+" "+type+" !",
		icon: "warning",
        dangerMode:true,
        buttons:["Cancel","Delete"]
	})
    .then(willDelete=>{
        if(willDelete) {
    		$.post("./assets-and-shares/includes/finance.php?action=deleteRec&dest=delVendorDeposit", { recID:recID }, function(data) {
    			if(data=="deleted") {
    				swal({
    					title: "Success!",
    					text: "Selected account receivable record has been deleted.",
    					icon: "success",
    					timer: 1500,
    					button: false
    				})
                .then(value=>{
    					location.reload();
    				});

    			} else {
    				swal("Oops", data, "error");
    			}
    		});
        }
	});
	return false;
}

/*-----------------------------------------------------------------------------------------------
---------------------------------- closing and dividend payment -------------------------------------------------------
--------------------------------------------------------------------------------------------------*/

//
function check_closeFinanceYr() {
	var isDividend	= $("input#isGiven:checked").val();
	if(isDividend!="on") { var isDividend="no"; } else { var isDividend="yes"; }

	swal({
		title: "Are you sure?",
		text: "You going to close financial year!\nAnd once closed, it can't be used any more.",
		icon: "warning",
        dangerMode:true,
        buttons:["Cancel","Close"]
	})
    .then(willDelete=>{
        if(willDelete) {
    		swal({
    			title: "Create new",
    			text: 'Please provide new financial year',
    			content: "input",
    			buttons:["Cancel","Close"]
    		})
            .then(fnyear=>{
    			if (fnyear) {
        			if(isDividend=="yes") {
        				window.location = "./workplace.php?role="+myRole+"&task=settings&subtask=closing&action=showInfo&nextfnYear="+fnyear;
        				return false;
        			}
                        swal({
                            title: "Closing Finance Year",
                            text: "Please wait minutes to close finance year",
                            imageUrl:"assets/images/system/loading.gif",
                            button: false
                        });

        			$.post("./assets-and-shares/includes/finance.php?action=saveNew&dest=addFnYear",{ nextfnYear:fnyear,isDividend:isDividend },function(data){
        				var addedpos = data.search("added");
        				if(addedpos==0) {
        					swal({
        						title: "Success!",
        						text: "You successfully created new financial year.",
        						icon: "success",
        						timer: 1500,
        						button: false
        					})
                                .then(value=>{
        							window.location = "./dashboard.php";
        						}
        					);
        				} else {
        					swal("Oops!", data, "error");
        				}
        			});
                }
    		});
        }
	});
}
//

function check_addDividend() {
	var isDividend	= "yes";
	var nextfnYear	= $("#nextfnYear").val();
	var divident_amount	= $("#divident_amount").val();
	swal({
		title: "Are you sure?",
		text: "You going to close financial year!\nAnd once closed, it can't be used any more.",
		icon: "warning",
        dangerMode:true,
        buttons:["Cancel","Close"]
	})
    .then(willDelete=>{
        if(willDelete) {
                swal({
                    title: "Closing Finance Year",
                    text: "Please wait minutes to close finance year",
                    imageUrl:"assets/images/system/loading.gif",
                    button: false
                });

			$.post("./assets-and-shares/includes/finance.php?action=saveNew&dest=addFnYear",{ isDividend:isDividend,nextfnYear:nextfnYear, divident_amount:divident_amount },function(data){
				var addedpos = data.search("added");
				if(addedpos==0) {
					swal({
						title: "Success!",
						text: "You successfully created new financial year.",
						icon: "success",
						timer: 1500,
						button: false
					})
                        .then(value=>{
							window.location = "./dashboard.php";
						}
					);
				} else {
					swal("Oops!", data, "error");
				}
			});
		}
	});
}
//
function loadDivPayments(pageLimit, perPage, period) {
	$("#dataTable div#loading").css("display", "inline");
	var dataString = 'pageLimit='+ pageLimit+'&period='+ period+'&perPage='+ perPage;
	$.ajax({
		type: "POST",
		url: "./assets-and-shares/includes/finance.php?action=loadTable&dest=allDivPayments",
		data: dataString,
		cache: false,
		timeout: 2000,
		success: function(result){
			$("#dataTable div#loading").css("display", "none");
			$(".load_more_link").addClass('noneLink');
			$("#dataTable").append(result);
		},
	});
	return false;
}
function catchDivPayment(recID) {
	$.post("./assets-and-shares/includes/finance.php?action=get_recInfo&dest=getDivPayment", { recID:recID }, function(data) {
		$("div#foundNum").html('<label id="count">1</label> record has been selected.<span id="refresh"></span>');
		$("div#dataTable").html(data);
	});
	$("div.suggest").css("display", "none");
}

function smpfyAddDivPyment() {

	// if shareholder name provided
	$("input#txtShareHolder").keyup(function () {
		$("#shareID").val('');
		$("div.displayInfo.shareInfo").css("display", "none");
		var shareName	= $("#txtShareHolder").val();
		if(shareName!="") {
			$("div.suggest.one").css("display", "table-row");
			$.post("./assets-and-shares/includes/finance.php?action=searchRec&dest=pickShare4Pay", { shareName:shareName }, function(data) {
				$("div.suggest.one").html(data);
			});
		} else { $("div.suggest.one").css("display", "none"); }

		clearErrors();
	});

    $("#checkDiv2share, #switchDiv2share").click(function(){
        $('div#switchDiv2share').toggleClass("switchOn");
        if (document.getElementById("addDiv2share").checked == true) {
            document.getElementById("addDiv2share").checked = false;

        } else {
            document.getElementById("addDiv2share").checked = true;
            $("select#slcBankID option:first").attr("selected", "selected");
            $("select#slcBankAcc").html('');
            $("input#txtCheque").val('');
        }

    });

}
function catchShare4Pay(shID, shareHolder, phone, balance, balanceTxt) {
	$("input#shareID").val(shID);
	$("input#balance").val(balance);
	$("input#txtShareHolder").val(shareHolder);
	$("div.displayInfo.shareInfo").css("display", "inline");
	$("p#shName").html(shareHolder);
	$("p#shPhone").html(phone);
	$("p#divAmnt").html(balanceTxt);
	if(balance>0) {
		$("p#divAmnt").html('$'+balanceTxt);
	} else {
		$("p#divAmnt").html(balanceTxt);
	}
	$("div.suggest").css("display", "none");
}

function check_addDivPayment() {
	var shareID 		= $("#shareID").val();
	var txtShareHolder 	= $("#txtShareHolder").val();
	var txtAmount		= $("#txtAmount").val();
	var balance			= $("input#balance").val();
	var txtInWords		= $("#txtInWords").val();
	var slcBankID		= $("#slcBankID").val();
	var slcBankAcc		= $("#slcBankAcc").val();
	var txtCheque		= $("#txtCheque").val();
	var txtRemarks		= $("#txtRemarks").val();
    var transDate       = $("#transDate").val();

    var addDiv2share    = $("input#addDiv2share:checked").val();
    if(addDiv2share!="on") { var addDiv2share="no"; } else { var addDiv2share="yes"; }

		if(txtShareHolder.length < 1 || shareID=="") {
			$("#error1").css("display", "inline");
			$("#error1").html("Please provide shareholder");
			$("#txtShareHolder").addClass("highlight");
			return false;
		} else { clearErrors(); }

	if(txtAmount.length < 1) {
		$("#error2").css("display", "inline");
		$("#error2").html("Amount value is missing");
		$("#txtAmount").addClass("highlight");
		return false;
	} else if(Number(txtAmount) < 0.1) {
		$("#error2").css("display", "inline");
		$("#error2").html("Amount must be greater than 0");
		$("#txtAmount").addClass("highlight");
		return false;
	} else if(txtAmount > parseFloat(balance)) {
		$("#error2").css("display", "inline");
		$("#error2").html("Amount can't be more than $"+balance);
		$("#txtAmount").addClass("highlight");
		return false;
	} else { clearErrors(); }
	if(addDiv2share=="no"){
    	if(slcBankID.length < 1) {
    		$("#error4").css("display", "inline");
    		$("#error4").html("Please select bank");
    		$("#slcBankID").addClass("highlight");
    		return false;
    	} else { clearErrors(); }

    	if(slcBankAcc=="---" || slcBankAcc.length < 1) {
    		$("#error4").css("display", "inline");
    		$("#error4").html("Select bank account");
    		$("#slcBankAcc").addClass("highlight");
    		return false;
    	} else { clearErrors(); }
    }

	$("label.process").css("display", "inline");
	$("#btnSave").attr("disabled", true);
	$("#btnSave").html("Wait...");

	$.post("./assets-and-shares/includes/finance.php?action=saveNew&dest=addDivPayment", {shareID:shareID, txtAmount:txtAmount, txtInWords:txtInWords, slcBankID:slcBankID, slcBankAcc:slcBankAcc, txtCheque:txtCheque, txtRemarks:txtRemarks, transDate:transDate, addDiv2share:addDiv2share }, function(data) {
		var addedpos = data.search("added");
		$("label.process").css("display", "none");
		if(addedpos==0) {
			var lastID = data.slice(6,21);
			swal({
				title: "Success!",
				text: "You added dividend payment record successfully.",
				icon: "success",
				timer: 1500,
				button: false
			})
                .then(value=>{
                    if(addDiv2share=="no") {
    					var params = '&task=finance&subtask=divPayments&action=showInfo&recID='+lastID;
    					window.location = "./workplace.php?role="+myRole+params;
                    } else {
                        var params = '&task=finance&subtask=shares&action=showInfo&recID='+shareID;
                        window.location = "./workplace.php?role="+myRole+params;
                    }
				}
			);
		} else {
			swal("Oops!", data, "error");
		}
		$("#btnSave").attr("disabled", false);
		$("#btnSave").html("Save");
	});
	return false;
}
function check_editDivPayment() {
	var shareID			= $("#shareID").val();
	var txtShareHolder	= $("#txtShareHolder").val();
	var payID			= $("#payID").val();
	var pvNumber		= $("#pvNumber").val();
	var txtAmount		= $("#txtAmount").val();
	var txtInWords		= $("#txtInWords").val();
	var slcBankID		= $("#slcBankID").val();
	var slcBankAcc		= $("#slcBankAcc").val();
	var txtCheque		= $("#txtCheque").val();
	var txtRemarks		= $("#txtRemarks").val();
	var transDate		= $("#transDate").val();


		if(txtShareHolder.length < 1 && shareID=="") {
			$("#error1").css("display", "inline");
			$("#error1").html("Please provide shareholder");
			$("#txtShareHolder").addClass("highlight");
			return false;
		} else { clearErrors(); }

	if(txtAmount.length < 1) {
		$("#error2").css("display", "inline");
		$("#error2").html("Amount value is missing");
		$("#txtAmount").addClass("highlight");
		return false;
	} else if(Number(txtAmount) < 0.1) {
			$("#error2").css("display", "inline");
			$("#error2").html("Amount must be greater than 0");
			$("#txtAmount").addClass("highlight");
			return false;
		} else { clearErrors(); }

	if(slcBankID.length < 1) {
		$("#error3").css("display", "inline");
		$("#error3").html("Please select bank");
		$("#slcBankID").addClass("highlight");
		return false;
	} else { clearErrors(); }

	if(slcBankAcc=="---" || slcBankAcc.length < 1) {
		$("#error3").css("display", "inline");
		$("#error3").html("Select bank account");
		$("#slcBankAcc").addClass("highlight");
		return false;
	} else { clearErrors(); }


	$("label.process").css("display", "inline");
	$("#btnUpdate").attr("disabled", true);
	$("#btnUpdate").html("Wait...");

	$.post("./assets-and-shares/includes/finance.php?action=updateExist&dest=editDivPayment", { payID:payID, shareID:shareID, txtAmount:txtAmount, txtInWords:txtInWords, slcBankID:slcBankID, slcBankAcc:slcBankAcc, txtCheque:txtCheque, txtRemarks:txtRemarks, transDate:transDate }, function(data) {
		$("label.process").css("display", "none");
		if(data=="updated") {
			swal({
				title: "Success!",
				text: "You updated dividend payment record successfully.",
				icon: "success",
				timer: 1500,
				button: false
			})
                .then(value=>{
					var params = '&task=finance&subtask=divPayments&action=showInfo&recID='+payID;
					window.location = "./workplace.php?role="+myRole+params;
				}
			);
		} else {
			swal("Oops!", data, "error");
		}
		$("#btnUpdate").attr("disabled", false);
		$("#btnUpdate").html("Update");
	});
	return false;
}
function delDivPayment(recID) {
	swal({
		title: "Are you sure?",
		text: "You going to delete this dividend payment!",
		icon: "warning",
        dangerMode:true,
        buttons:["Cancel","Delete"]
	})
    .then(willDelete=>{
        if(willDelete) {
    		$.post("./assets-and-shares/includes/finance.php?action=deleteRec&dest=delDivPayment", { recID:recID }, function(data) {
    			if(data=="deleted") {
    				swal({
    					title: "Success!",
    					text: "Selected dividend payment record has been deleted.",
    					icon: "success",
    					timer: 1500,
    					button: false
    				})
                .then(value=>{
    					location.reload();
    				});

    			} else {
    				swal("Oops", data, "error");
    			}
    		});
        }
	});
	return false;
}
function catchDivPayment(recID) {
	$.post("./assets-and-shares/includes/finance.php?action=get_recInfo&dest=getDivPayment", { recID:recID }, function(data) {
		$("div#foundNum").html('<label id="count">1</label> record has been selected.<span id="refresh"></span>');
		$("div#dataTable").html(data);
	});
	$("div.suggest").css("display", "none");
}
