/* Copyright (c) 2009 JosÃ© JoaquÃn NÃºÃ±ez (josejnv@gmail.com) http://joaquinnunez.cl/blog/
 * Licensed under GPL (http://www.opensource.org/licenses/gpl-2.0.php)
 * Use only for non-commercial usage.
 *
 * Version : 0.1
 *
 * Requires: jQuery 1.2+
 */

(function(jQuery) {
    $(document).on('hidden.bs.modal', '.modal', function() {
        var modal_id = "#" + $(this).attr('id');
        //console.log(modal_id)
        $(modal_id + ' h5.h-labels,' + modal_id + ' div.hide-close,label.hide-close').addClass('hidden')
            //        $(modal_id+' .form-group').removeClass('has-error')
        $(modal_id + ' input.empty,' + modal_id + ' textarea.empty').val('');
        $(modal_id + ' .add-row:gt(0),' + modal_id + ' label.error').remove()
        $(modal_id + ' .add-row span.fa-minus,' + modal_id + ' .add-row .AddButtons span.fa-minus-circle').css({ "display": "none" });
        $(modal_id + ' input.error,' + modal_id + ' textarea.error').removeClass('error')
        $(modal_id + ' input[type=checkbox].empty').attr('checked', false)
            //        $(modal_id+' select.empty').val(null).trigger("change");
    });
    if (activate_scroll_input_number == 0) {
        $(document).on('focus', 'input[type=number]', function(e) {
            $(this).on('mousewheel.disableScroll', function(e) {
                e.preventDefault()
            });
        });
    }
    //When opening several overlapping modals
    //    $(document).on('show.bs.modal', '.modal', function () {
    //        var zIndex = 1040 + (10 * $('.modal:visible').length);
    //        $(this).css('z-index', zIndex);
    //        setTimeout(function () {
    //            $('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack');
    //        }, 0);
    //    });
    //    
    //When opening several overlapping modals
    $(document).on('show.bs.modal', '.modal', function() {
        var zIndex = 1040 + (10 * $('.modal:visible').length);
        $(this).css('z-index', zIndex);
        setTimeout(function() {
            $('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack');
        }, 0);
    });
    //to remove the blue selection color
    document.onselectstart = function() {
        return false
    };
    // This is to show the spinning digital clock inside the header
    jQuery.fn.clock = function(options) {

        var defaults = {
            offset: '+2',
            type: 'analog'
        };
        var _this = this;
        var opts = jQuery.extend(defaults, options);

        setInterval(function() {
            var seconds = jQuery.calcTime(opts.offset).getSeconds();
            seconds = (seconds > 9) ? seconds : ("0" + seconds);


            if (opts.type == 'analog') {
                var sdegree = seconds * 6;
                var srotate = "rotate(" + sdegree + "deg)";
                jQuery(_this).find(".sec").css({ "-moz-transform": srotate, "-webkit-transform": srotate });
            } else {
                jQuery(_this).find(".sec").html(seconds);
            }
        }, 1000);

        setInterval(function() {
            var hours = jQuery.calcTime(opts.offset).getHours();



            var mins = jQuery.calcTime(opts.offset).getMinutes();
            if (opts.type == 'analog') {
                var hdegree = hours * 30 + (mins / 2);
                var hrotate = "rotate(" + hdegree + "deg)";
                jQuery(_this).find(".hour").css({ "-moz-transform": hrotate, "-webkit-transform": hrotate });
            } else {

                jQuery(_this).find(".hour").html(hours - (hours > 12 ? 12 : 00));

            }

            var meridiem = hours < 12 ? meridiemArr[0] : meridiemArr[1];
            jQuery(_this).find('.meridiem').html(meridiem);
        }, 1000);

        setInterval(function() {
            var mins = jQuery.calcTime(opts.offset).getMinutes(),
                mins = (mins > 9) ? mins : ("0" + mins);

            if (opts.type == 'analog') {
                var mdegree = mins * 6;
                var mrotate = "rotate(" + mdegree + "deg)";
                jQuery(_this).find(".min").css({ "-moz-transform": mrotate, "-webkit-transform": mrotate });
            } else {
                jQuery(_this).find(".min").html(mins);
            }
        }, 1000);
    }

})(jQuery);

// Change the offset of any time given
jQuery.calcTime = function(offset) {

    // create Date object for current location
    d = new Date();

    // convert to msec
    // add local time zone offset
    // get UTC time in msec
    utc = d.getTime() + (d.getTimezoneOffset() * 60000);

    // create new Date object for different city
    // using supplied offset
    //nd = new Date(utc + (3600000 * offset));
    nd = new Date(utc + (3600000 * -(d.getTimezoneOffset() / 60)));
    // return time as a string
    return nd;
};

//note if open full screen then click on a link or navigate to another page it will auto close full screen
var is_full_screen_init = false;

function go_full_screen(el) {
    if (el == undefined || el == '')
        el = document.documentElement;
    //to go full screen
    if (is_full_screen_init === false) {
        is_full_screen_init = true;
        if (el.requestFullscreen) {
            el.requestFullscreen();
        } else if (el.mozRequestFullScreen) {
            el.mozRequestFullScreen();
        } else if (el.webkitRequestFullscreen) {
            el.webkitRequestFullscreen();
        } else if (el.msRequestFullscreen) {
            el.msRequestFullscreen();
        }
    }
    //to exit full screen
    else {
        is_full_screen_init = false;
        if (document.exitFullscreen) {
            document.exitFullscreen();
        } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        } else if (document.webkitExitFullscreen) {
            document.webkitExitFullscreen();
        }
    }
}

//
$('body').on('click', '.image_popup', function() {
    $('#main_image_modal .image_modal_preview').attr('src', $(this).attr('popup-src'));
    $('#main_image_modal').modal('show');
});
$('body').on('click', function() {
    $('.snackbar_reminder').removeClass('show');
});

function open_frame_modal(url, post_data) {
    //here put .one not .on so on every call for this ft. keep just one call
    $('#frameModal').one('show.bs.modal', function() {
        $(this).parent().show();
        if (typeof post_data === 'undefined') {
            $('iframe', $(this)).attr("src", url);
        } else {
            var tmp_form = $("<form style='display:none;opacity:0;' method='post' id='tmp_trusto_iframe_form'></form>")
                .attr('target', 'trusto_global_iframe') //to submit on the iframe
                .attr('action', url);
            $('body').append(tmp_form);
            var tmp_inpt;
            //note if there is multi level json this will not work and we must change it to be like recursion fill hidden inputs
            $.each(post_data, function(n, v) {
                tmp_inpt = $("<input type='hidden' />").attr('name', n).val(v);
                tmp_form.append(tmp_inpt);
            });
            tmp_form.submit().remove();
        }
    }).one('hidden.bs.modal', function() {
        $(this).parent().hide();
        //on close free source so second time when open it, it will be empty not old loaded iframe source
        $('iframe', $(this)).attr("src", "about:blank");
        //$('#tmp_trusto_iframe_form').remove();
    });
    $('#frameModal').modal("show");
}

//
(function($) {

    $(document).on("click", ".openFrame", function() {
        var url = $(this).attr("data-src");
        if (url.substr(1, 6).toLocaleLowerCase() !== "ttp://" && url.substr(1, 7).toLocaleLowerCase() !== "ttps://")
            url = site_link + url;
        //var url = site_link + $(this).attr("data-src");
        if ($(this)[0].hasAttribute("data-post-json"))
            open_frame_modal(url, JSON.parse($(this).attr("data-post-json")));
        else
            open_frame_modal(url);
    });
    $(document).on("click", ".openAllergyIntolerance", function() {
        var parent = $(this);
        $('#allergy-intolerance-modal input[name=type_id]').val(parent.attr('data-type'));
        $('#allergy-intolerance-modal .add-label').html(parent.attr('data-content'));
        $('#allergy-intolerance-modal').modal("show")
    })
    $(document).ready(function() {
        $(".PrintThisTableButton").on("click", function(e) {
            e.preventDefault();
            PrintThisTable($(this));
        })
        $("[connect-with-city]").each(function() {
                var City = $.trim($(this).attr("connect-with-city"))
                if ($(City).length > 0 && City != "") {
                    LinkCountryCity($(this), $(City));
                }
            })
            //to be removed if not used
        $("[connect-with-Product]").each(function() {
            var Product = $.trim($(this).attr("connect-with-Product"))
            if ($(Product).length > 0 && Product != "") {
                LinkCategoryProduct($(this), $(Product));
            }
        })

        $(".ValSpan").each(function() {
            $(this).html(AddCommas(parseFloat($.trim($(this).text())).toFixed(3))).animate({ opacity: 1 })
        })




        // Auto Select Default Currency
        $(".DropDownForForms[Default-Currency]").each(function() {
            var MyItem = $("ul > li[value='" + $(this).attr("Default-Currency") + "']", this)
            if (MyItem.length > 0) {
                $("> button > span", this).html($(this).hasClass("small") ? $.trim(MyItem.text().split("-")[1]) : MyItem.text())
                $("button > input", this).val(MyItem.attr("value")).attr({ value: MyItem.attr("value") })
            }
            if ($(this).hasClass("small")) {
                $(this).find("li").each(function() {
                    if ($(this).css("display") == "none") {
                        $(this).remove()
                    } else {
                        $(this).html("<a>" + $.trim($(this).text().split("-")[1]) + "</a>");
                    }
                })
                $(this).css({ display: "inline-block", width: "auto" }).find("li:not([mysymbol])").remove()
            }
        })

        // Reset Form After Closing any Modal
        $(".modal:not(.DontReset) > .modal-dialog").each(function() {
            $(this).parent().on("hidden.bs.modal", function() {
                ClearForm($(this).find("form"))
            })
        })

        // Search for download buttons
        $("[data-download-pdf]").on("click", function(e) {
            e.preventDefault();
            DownloadThisPageAs($(this), "pdf")
        })


        // Validator for Wizard Modal for organization
        ValidateAndSubmit($("#form-work"), "orgWizard");
        if ($("#HeaderTime").length)
            $("#HeaderTime").clock({ type: "" })
        if (!$("body").hasClass("NoAutoScroll"))
        //            $("html").niceScroll({styler: "fb", cursorcolor: "#000"});
            $(".list-view-wrapper").scrollbar();
        /*
         $('[data-pages="search"]').search({
         searchField: '#overlay-search',
         closeButton: '.overlay-close',
         suggestions: '#overlay-suggestions',
         brand: '.brand',
         onSearchSubmit: function(searchString) {
         console.log("Search for: " + searchString);
         },
         onKeyEnter: function(searchString) {
         console.log("Live search for: " + searchString);
         var searchField = $('#overlay-search');
         var searchResults = $('.search-results');
         clearTimeout($.data(this, 'timer'));
         searchResults.fadeOut("fast");
         var wait = setTimeout(function() {
         searchResults.find('.result-name').each(function() {
         if (searchField.val().length != 0) {
         $(this).html(searchField.val());
         searchResults.fadeIn("fast");
         }
         });
         }, 500);
         $(this).data('timer', wait);
         }
         })
         */
    });
    $('.panel-collapse label').on('click', function(e) {
        e.stopPropagation();
    })

    // Fix auto-close 





})(window.jQuery);

function GenerateDateForNotes() {
    var monthNames = ["January", "February", "March", "April", "May", "June",
        "July", "August", "September", "October", "November", "December"
    ];
    var dayNames = ["Sun, ", "Mon, ", "Tue, ", "Wed, ", "Thu, ", "Fri, ", "Sat, "]
    var newDate = new Date();
    newDate.setDate(newDate.getDate() + 1);
    var H = jQuery.calcTime(3).getHours(),
        M = jQuery.calcTime(3).getMinutes();


    return dayNames[newDate.getDay()] + " " + newDate.getDate() + ' ' + monthNames[newDate.getMonth()] + ' ' + newDate.getFullYear() + " " + (H - (H > 12 ? 12 : 0)) + ":" + M + (H < 12 ? "am" : "pm");

}

function AddCommas(val) {
    val = parseFloat(val.toString()).toString();
    while (/(\d+)(\d{3})/.test(val.toString())) {
        val = val.toString().replace(/(\d+)(\d{3})/, '$1' + ',' + '$2');
    }
    return val.replace(/\.0$|\.00$/, "") || "0";
}

function FixNumber(val) {
    return AddCommas(parseFloat(val + "").toFixed(2));
}
// Global function to enable automatically validation for a given form
// & to post the form using ajax
function ValidateAndSubmit(FormID, cls) {
    if (typeof(FormID) === "string")
        FormID = $(FormID);
    if (FormID.length == 0)
        return;
    FormID.parent().append($('<div class="WizardDisabler" style="position:absolute;left:0;right:0;top:0px;height:100%;background:rgba(255,255,255,0.9);z-index:999;display:none"><img class="image-responsive-height demo-mw-50" src="img/demo/progress.svg" alt="Progress" style="position: absolute;left: 50%;top: 50%;margin: -25px 0 0 -25px;" /></div>'))
    FormID.validate()
    $('<div class="WizardValidationAlert alert"></div>').insertAfter(FormID.parents(".modal-dialog").find("h5"))
    FormID.find("button[type='submit'],input[type='submit']").on("click", function(e) {
        e.preventDefault();
        var TheForm = $(this).parents("form"),
            AlertBox = TheForm.parents(".modal-dialog").find(".WizardValidationAlert")
        if (TheForm.valid()) {
            AlertBox.attr("class", "WizardValidationAlert alert").empty()
            TheForm.parent().find(".WizardDisabler").show()
            $.ajax({
                url: TheForm.attr("action"),
                method: "POST",
                data: TheForm.serialize(),
                complete: function(v1, v2) {
                    //  console.log(v1.responseText);
                    if (v2 == 'success' && v1.responseText == "OK") {
                        TheForm.parent().find(".WizardDisabler").hide();
                        AlertBox.addClass("alert-success").empty().html("<span>Finished Successfully.</span>");
                        setTimeout(function() {
                            TheForm.parents(".modal[role='dialog']").modal('toggle')
                            $("body").removeClass("NoSearch");
                        }, 1500)

                    } else {
                        AlertBox.addClass("alert-danger").empty().html("<span>Failed to submit, please try again</span>");
                    }
                    TheForm.parent().find(".WizardDisabler").hide();
                }
            })
        } else {
            AlertBox.addClass("alert-danger").empty().html("<span>Please fill the required fields</span>")
        }
    })
}

// To remove the blue in screen when click
// document.onselectstart=function(){return false};



// Enhances the use of bootstrap DropDown with "more" button
$(document).on('hide.bs.dropdown', ".DropDownForForms", function(e) {
    return false
});
$(document).on('show.bs.dropdown', ".DropDownForForms", function(e) {
    var me = this;
    $(".DropDownForForms").each(function() {
        if (this !== me)
            $(this).removeClass("open")
    })
    return true
});
$(document).on("click", function(e) {
    if ($(e.target).parents(".DropDownForForms").length == 0 && $(e.target).parents(".BelongsToDropDownForForms").length == 0) {
        $(".DropDownForForms").removeClass("open")
    }
})
$(document).on("click", ".DropDownForForms li > a.LoadMore", function(e) {
    var it = $(this).parents(".dropdown-menu");
    it.animate({ height: 250 }, 200).find("li").show()
    setTimeout(function() {
        it.find(".formore,.LoadMore").remove()
    }, 100);
    e.preventDefault();
})
$(document).on("click", ".DropDownForForms li > a:not(.LoadMore)", function(e) {
    var it = $(this).parents(".DropDownForForms");
    $("> button > span", it).html($(this).text())
    $("button > input", it).val($(this).parent().attr("value")).attr({ value: $(this).parent().attr("value") }).css("opacity", "0")
    if (it.hasClass("Closable"))
        it.removeClass("open")
    e.preventDefault();
})

// add commas to numbers on each 3 digits.
// Warning: don't use the result for calculations, this function produces string value
function AddCommas(val) {
    val = parseFloat(val.toString()).toString();
    while (/(\d+)(\d{3})/.test(val.toString())) {
        val = val.toString().replace(/(\d+)(\d{3})/, '$1' + ',' + '$2');
    }
    return val.replace(/\.0$|\.00$/, "") || "0";
}

function FixNumber(val) {
    return AddCommas(parseFloat(val + "").toFixed(2));
}

function ucWords(str) {
    return str.replace(/([^\W_]+[^\s-]*) */g, function(txt) {
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });
}

/***************** Clear all inputs in a form *****************/
function ClearForm(who) {
    $(who).find("input[type='text'],textarea,input[type='number']").val("");
    $(who).find("input[type='file']").each(function() { //clear input file object
        var input_file = $(this);
        input_file.replaceWith(input_file.val('').clone(true));
    });
    $(who).find(".PLusAddedItem").remove()
    $(who).find("table > tbody").each(function() {
        if ($(".TableItem", this).length > 1)
            $(".TableItem", this).not(":last-child").remove()
    })
    $(who).find(".select2-container").each(function() {
        var TargetID = "#" + this.id.substr(5)
        $(TargetID).select2("close");
        $(TargetID).select2("val", $(TargetID + " > option:first-child").attr("value"))
    })
}
/***************** Link Countries Dropdowns with Cities DropDowns *****************/
function LinkCountryCity(Country, City) {
    Country.on("change", function() {
        var City = $(this).data("MyCityListTarget"),
            Countryolder = $("#s2id_" + $(this).attr("id"));
        $("#s2id_" + City.attr("id")).append("<div class='LoadingCities' style='position:absolute;left:0;top:0;width:100%;height:100%;background:rgba(180,180,180,0.5);text-align:center'><img style='height:25px;margin-top:5px;' src='img/demo/progress.svg' /></div>")
        Countryolder.append("<div class='LoadingCities' style='position:absolute;left:0;top:0;width:100%;height:100%;background:rgba(180,180,180,0.5);text-align:center'></div>")

        $.ajax({
            url: "InventoryAjax/getcities?countryId=" + $(this).val(),
            dataType: "json",
            complete: function(v, vv) {
                City.select2("destroy").empty()
                if (vv == "success") {
                    var ToBeAdded = "";
                    for (var x = 0; x < v.responseJSON.length; x++) {
                        ToBeAdded += "<option value='" + v.responseJSON[x]["ID"] + "'>" + v.responseJSON[x]["Name"] + "</option>"
                    }
                    City.html(ToBeAdded);
                }
                City.select2();
                $(">.LoadingCities", Countryolder).remove()
            }
        })



    }).data("MyCityListTarget", City).trigger("change")
}
/***************** Generic Function To Download Current Page as PDF,Word... *****************/
function DownloadThisPageAs(who, what) {

    var Header = $("<div>"),
        Body = $("<div>"),
        Footer = $("<div>"),
        Target = $(who.attr("data-download-pdf"))
    if (Target.length == 0)
        return
    $("head > link,head > style").each(function() {


        (Header.append($(this).clone()))
    })
    $("body link,body style").each(function() {
        Footer.append($(this).clone())
    })


    if (Target[0].tagName.toLowerCase() == "table") {
        if (Target.hasClass("dataTable")) {
            var iWas = Target.dataTable().fnSettings().fnDisplayEnd();
            Target.fnLengthChange(-1)
            Body = Target.clone(false, false).removeAttr("id")
            Target.dataTable().fnLengthChange(iWas)
            if (Body.find("td.dataTables_empty").length == 0)
                Body.dataTable().fnDestroy()
        } else {
            Body = Target.clone(false, false).removeAttr("id")
        }
        Body = Body.wrap("<div>").parent();
        Body.find("tbody").eq(1).find("tr").appendTo(Body.find("tbody").eq(0))
        Body.find("tbody").eq(1).remove()
    } else {
        Body = Target.clone(false, false).removeAttr("id")

    }



    //	Body.prepend($("<div class='Header' style='margin:10px;'><h1>"+who.attr("data-title")+"</h1></div><br>")).find(".no-print").remove()
    Target[0].tagName.toLowerCase() == "table" ? Body.prepend($("<div style='text-align:center'><label style='font-size:2em;text-align:center;margin-top:10px'>" + who.attr("data-title") + "</label></div><br><br>" +
        (who.attr("data-Account") ? "<div style='text-align:center'><label style='font-size:1.5em;'>" + who.attr("data-Account") + "</label></div><br>" : " ") +
        (who.attr("data-Price") ? "<label style='font-size:1.5em;margin-left:475px;'>" + who.attr("data-Price") + "</label><br>" : " ") +
        "<div class='col-xs-4' style='margin:10px;'>" +
        "<label class='bold'>Company : Plastrue</label><br>" +
        "<label class='bold'>Phone : 07785450</label><br>" +
        "<label class='bold'>Email : info@plastrue.com</label><br>" +
        (who.attr("data-date") ? "<label class='bold'>Date :</label><label> " + who.attr("data-date") + "</label><br>" : " ") +
        (who.attr("data-currency") ? "<label class='bold'>Currency :</label><label> " + who.attr("data-currency") + "</label><br>" : " ") +
        "<label class='bold'> trusto Soltuion - Trusto Tech.</label>" +
        "</div>" +
        " <div class='col-xs-4 pull-right'  style='margin:10px'>" +
        (who.attr("data-balance") ? "<label class='bold'>Total Balance :</label><label> " + who.attr("data-balance") + "</label><br>" : " ") +
        (who.attr("data-credit") ? "<label class='bold'>Total Credit :</label><label> " + who.attr("data-credit") + "</label><br>" : " ") +
        (who.attr("data-debit") ? "<label class='bold'>Total Debit :</label><label> " + who.attr("data-debit") + "</label>" : " ") + "</div>"
    )).find(".no-print").remove() : Body.find(".no-print").remove();
    Body.append($("<div class='text-center' style='align-text:center;margin-top:20px;'><label class='bold '>End Of Report </label></div>"));
    //	if(who.attr("data-date") && $.trim(who.attr("data-date")) != ""){
    //		$(">.Header",Body).append($("<h1 style='float:right'>"+$(who.attr("data-date")).val()+"</h1>"))
    //	}
    Body = Body.html();

    //$(".container-fluid").html(Body)
    //window.X = Body;
    //return
    Header.add(Footer).find(".no-print").remove()
    var Data = { filename: who.attr("data-title"), content: "<html><head><style type='text/css'>tr { page-break-inside: avoid; }</style><meta http-equiv='content-type' content='text/html;charset=UTF-8'/>" + Header.html() + "</head><body style='background:#fff'>" + Body + Footer.html() + "</body></html>" },
        inputs = '';
    if (who.attr("data-landscape") != null)
        Data.landscape = "yes";
    $.each(Data, function(v, v2) {

        inputs += '<textarea name="' + v + '">' + v2 + '</textarea>';
    });
    $('<form action="libs/Downloader/download.php" method="post">' + inputs + '</form>').appendTo('body').submit().remove();



    //	$.ajax({
    //		url:"libs/Downloader/download.php",
    //		method:"post",
    //		dataType: 'binary',
    //		data:{headerfiles:Header.html(),footerfiles:Footer.html()},
    //		complete:function(v,v1){
    //			console.log(v)
    //		
    //			
    //			var url = URL.createObjectURL(v);
    //			
    //			var $a = $('<a />', {
    //			'href': url,
    //			'download': 'document.pdf',
    //			'text': "click"
    //			}).hide().appendTo("body")[0].click();
    //URL.revokeObjectURL(url);

    //		}
    //	})


}



/***************** Generic Function To Convert Currency *****************/
/*
 Must create a variable named CurrencyRate with content from $currency->getExchangeRateTable();
 Example use:
 ConvertCurrency2(1500,84,144); From LBP(84) to USD(144) will return 1
 */
function ConvertCurrency2(Val, FromC, ToC, forse_changer = 0) {

    if (FromC == ToC) {
        return Val
    } else {
        var ExchRate;
        for (var x = 0; x < CurrencyRate.length; x++) {

            if (forse_changer > 0) {
                ExchRate = forse_changer;
            } else {
                ExchRate = CurrencyRate[x]['ExchRate'];
            }
            if (CurrencyRate[x]['from_currency'] == FromC && CurrencyRate[x]['to_currency'] == ToC) {

                return Val * ExchRate;
            } else if (CurrencyRate[x]['to_currency'] == FromC && CurrencyRate[x]['from_currency'] == ToC) {
                return Val / ExchRate;
            }
        }
    }
}
/***************** Generic Function To Make any table printable *****************/
function PrintThisTable(who) {


    $("#DivOnlyForPrinting,#PageLandscape").remove()
    $("head").eq(0).append($("<style id='PageLandscape' type='text/css'>@page{size:A4 Portrait;margin: 10px;}</style>"))
    var P = $("<div class='PrintOnly' id='DivOnlyForPrinting'></div>").appendTo("body")
    $("body > .page-container,body > .page-sidebar,body > .pace-inactive").addClass("no-print");


    var row = $(who.attr("data-table")).dataTable().fnGetNodes(),
        tablelength = row.length;
    for (var i = 0; i < tablelength; i++) {

        $(row[i]).find('a').removeAttr('href')
    }
    if (tablelength == 0) {

        $('a').removeAttr('href')
    }

    var TheHeader = $("<label style='font-size:2em;margin-left:450px;margin-top:10px'>" + who.attr("data-title") + "</label><br><br>" +
        (who.attr("data-Account") ? "<label style='font-size:1.5em;margin-left:375px;'>" + who.attr("data-Account") + "</label><br>" : " ") +
        (who.attr("data-Price") ? "<label style='font-size:1.5em;margin-left:475px;'>" + who.attr("data-Price") + "</label><br>" : " ") +
        "<div class='col-xs-4 Header' style='margin:15px'>" +
        "<label class='bold'>Company : Plastrue</label><br>" +
        "<label class='bold'>Phone : 07785450</label><br>" +
        "<label class='bold'>Email : info@plastrue.com</label><br>" +
        "<label class='bold'>Date :</label><label> " + who.attr("data-date") + "</label><br>" +
        (who.attr("data-currency") ? "<label class='bold'>Currency :</label><label> " + who.attr("data-currency") + "</label><br>" : " ") +
        "<label class='bold'> trusto Soltuion - Trusto Tech.</label>" +
        "</div>" +
        " <div class='col-xs-4 pull-right'  style='margin:15px'>" +
        (who.attr("data-balance") ? "<label class='bold'>Total Balance :</label><label> " + who.attr("data-balance") + "</label><br>" : " ") +
        (who.attr("data-credit") ? "<label class='bold'>Total Credit :</label><label> " + who.attr("data-credit") + "</label><br>" : " ") +
        (who.attr("data-debit") ? "<label class='bold'>Total Debit :</label><label> " + who.attr("data-debit") + "</label>" : " ") + "</div>"

    );




    var End = $('<h5 class="text-center" style="margin:20px;">End Of Report</h5>');
    var Items = $(who.attr("data-table")),
        Step = tablelength ? tablelength : 300;


    if (Items.dataTableSettings.length > 0) {

        var iWas = Items.dataTable().fnSettings().fnDisplayEnd();


        Items.fnLengthChange(-1)


        Items = Items.clone().find("tbody:eq(0) > tr")



        $(who.attr("data-table")).dataTable().fnLengthChange(iWas)

    } else {
        Items = Items.clone().find("tbody:eq(0) > tr")
    }
    if (who.attr("data-date") && $.trim(who.attr("data-date")) != "") {
        //        var TheDate = $(who.attr("data-date")).val();
        var TheDate = (who.attr("data-date"));
        $(">h1", TheHeader).append($("<div style='float: right;font-size: 24px;'>" + TheDate + "</div>"))
    }
    var Panel = $('.panel-body > .PrintDiv');




    $("#DivOnlyForPrinting").append(TheHeader)



    for (var x = 0; x < Items.length; x += Step) {



        var Page = $("<div class='Page'></div><br>");
        var Table = $(who.attr("data-table")).clone();


        $(">tbody:eq(0)", Table).empty()

        for (var z = x; z < x + Step; z++) {

            $(">tbody:eq(0)", Table).append(Items[z])

        }


        Page.append(Table)


        P.append(Panel);

        P.append($(Page));


    }
    $(Page).append(End);

    window.print()
}

function ReloadScroll() {
    //    $("html").niceScroll().remove();
    //    $("html").niceScroll({styler: "fb", cursorcolor: "#000"});
}

function CommonViewById(url, Data, loader, onReturn) {
    $(loader).removeClass('hidden');
    $.ajax({
        url: url != '' ? url : "common_ajax/ViewByEntryId",
        method: "GET",
        data: Data,
        dataType: "json",
        complete: function(jqXHR, status) {
            if (status == "success") {
                //                console.log(Object.keys(jqXHR.responseJSON).length)
                //                if (Object.keys(jqXHR.responseJSON).length > 0) {
                //                    console.log('here');
                onReturn(jqXHR.responseJSON);

                //                }
                $(loader).addClass('hidden');
            }
        }
    });
}


$('.floatingContainer').hover(function() {
    //$('.subActionButton').addClass('display');
}, function() {
    $('.subActionButton').removeClass('display');
    $('.actionButton').removeClass('open');
});
$('.subActionButton').hover(function() {
    $(this).find('.floatingText').addClass('show');
}, function() {
    $(this).find('.floatingText').removeClass('show');
});

$('.actionButton').hover(function() {
    $(this).addClass('open');
    $(this).find('.floatingText').addClass('show');
    $('.subActionButton').addClass('display');
}, function() {
    $(this).find('.floatingText').removeClass('show');
});


function LinkCategoryProduct(Cat, Prod) {
    Cat.on("change", function() {
        var Prod = $(this).data("MyProdListTarget"),
            Catolder = $("#s2id_" + $(this).attr("id"));
        $("#s2id_" + Prod.attr("id")).append("<div class='LoadingCities' style='position:absolute;left:0;top:0;width:100%;height:100%;background:rgba(180,180,180,0.5);text-align:center'><img style='height:25px;margin-top:5px;' src='img/demo/progress.svg' /></div>")
        Catolder.append("<div class='LoadingProd' style='position:absolute;left:0;top:0;width:100%;height:100%;background:rgba(180,180,180,0.5);text-align:center'></div>")

        $.ajax({
            url: "xhr/ajaxProductMaterial.php?type=" + $(this).val(),
            dataType: "json",
            complete: function(v, vv) {
                Prod.select2("destroy").empty()
                if (vv == "success") {
                    var ToBeAdded = "";

                    for (var x = 0; x < v.responseJSON.length; x++) {
                        ToBeAdded += "<option value='" + v.responseJSON[x]["ID"] + "'>" + v.responseJSON[x]["CODE"] + ' - ' + v.responseJSON[x]["NAME"] + "</option>"
                    }
                    Prod.html(ToBeAdded);
                }
                Prod.select2();
                $(">.LoadingProd", Catolder).remove()
            }
        })
    }).data("MyProdListTarget", Prod).trigger("change")
}
//
var lang = $('html').attr('lang');
//
function RebuildDataTable(title, colArr, url, data, table, rowSpan, tmp_optns, footer_print) {
    footer_print = (typeof footer_print == 'undefined' ? true : footer_print)
        //we clone it since object send by reference so if we change here it will change by the main variable we send
    var optns = (tmp_optns == undefined || tmp_optns == '' || tmp_optns == false || tmp_optns == null) ? {} : Object.create(tmp_optns);
    //    console.log(url)
    //    var org_name = org_head[0]['Organization_Legal_Name'],
    //            org_phone = org_head[0]['Organization_Phone'],
    //            org_address = org_head[0]['Name'] + '-' + org_head[0]['Organization_Province'],
    //            org_vat = org_head[0]['Organization_Commercial_Registry'];
    data = (data == undefined || data == '' || data == false || data == null) ? {} : data;
    var span_arr = rowSpan === undefined || rowSpan == '' || rowSpan == false || !rowSpan.length ? '' : rowSpan;
    var name = ((table === undefined || table === '' || table === false) ? "#tableWithSearch" : table);
    //
    var myurl = ((url === undefined || url === '' || url === false) ? '' : (window.site_link + url));
    var is_server_side = myurl === '' ? false : true;
    //
    var visible_col_indx = [];
    $(name + ' thead tr.filter_columns_row td').each(function() {
        var is_col_exist = $(name + ' thead tr:first th').eq($(this).attr('data-col-index')).length > 0;
        if (is_col_exist) //we add this condition since some times we dynamically remove specific col. but it's filter col. still exist
            visible_col_indx.push(parseFloat($(this).attr('data-col-index')));
    });


    //
    $(name).DataTable().destroy();
    if (is_server_side)
        $(name + " tbody").empty();
    $(name + " thead tr.filter_columns_row").remove();
    var is_footer = $(name + " tfoot tr").length > 0; //needed for buttons to know with footer or not
    //
    var search_col_row = "";
    if (optns === undefined || optns['hide_search_row'] === undefined || optns['hide_search_row'] !== true) {
        if (optns !== undefined && optns['hide_search_row'] !== undefined)
            delete optns.hide_search_row;
        search_col_row += "<tr class='filter_columns_row' style=' '>";
        var col_indx = 0;
        $(name + ' thead th').each(function() {
            //console.log($(this).html())
            //var title = $(this).text();  // placeholder="Search ' + title + '"
            search_col_row += '<td data-col-index="' + (col_indx++) + '" style="background-color:#e5e5e5;" class="dt-input-search"><input type="search"  class="form-control" style="width:100%;padding:3px 2px;min-height:0px;height:auto;" /></td>';
        });
        search_col_row += '</tr>';
        search_col_row = $(search_col_row);
        search_col_row.appendTo($(name + ' thead'));
    }
    //
    var msg = '';
    if (optns != undefined && optns['msg'] != undefined) {
        msg = optns['msg'];
        delete optns['msg'];
    }
    var print_footer = '';
    if (optns != undefined && optns['footer'] != undefined) {
        print_footer = optns['footer'];
        delete optns['footer'];
    }
    var print_header = datatable_header.replace('[[msg]]', msg);
    var buttons_arr = [{
            extend: 'excelHtml5',
            exportOptions: { "columns": ':visible:not(.no-print)' /*colArr*/ },
            title: title,
            footer: footer_print ? is_footer : footer_print,
            text: '<i class="fa fa-file-excel-o"></i> ' + excel_lang
        },
        //        {
        //            extend: 'pdfHtml5',
        //            exportOptions: {"columns": ':visible:not(.no-print)' /*colArr*/},
        //            footer: is_footer,
        //            title: title,
        //            text: '<i class="fa fa-file-pdf-o"></i> Pdf',
        //            "sCharSet": 'utf-8'
        //        },
        {
            extend: 'print',
            text: '<i class="fa fa-print"></i> ' + print_lang,
            exportOptions: {
                "columns": ':visible:not(.no-print)' /*colArr*/ ,
                stripHtml: false //like in product list want to show the image
            },
            title: function() {
                var printTitle = '<div class="text-center">' + title + '</div>';
                return printTitle;
            },
            footer: footer_print ? is_footer : footer_print,
            messageTop: (datatable_message_top == '' ? '' : ('<div class="clear-after-div dt-print-msg-top-container">' + datatable_message_top + '</div>')),
            messageBottom: (datatable_message_bottom == '' ? '' : ('<div class="clear-after-div dt-print-msg-bottom-container">' + datatable_message_bottom + '</div>')),
            customize: function(win, btn_obj, dt_api) {
                //                console.log(win)

                var win_body = $(win.document.body);
                //                win_body.content[1].table.widths = ['5%','30%','30%','10%','10%','10%','5%']

                var tmp_print_header = print_header; //to don't change the original var, or on click print twice will get the replaced var
                if (smc__view_name !== undefined)
                    win_body.addClass('main-print-div-' + smc__view_name);
                //if there is title in tmp_print_header then remove from here
                if (tmp_print_header.indexOf("[[title]]") != -1) {
                    $('.datatable-title-h1', win_body).remove();
                    tmp_print_header = tmp_print_header.replace('[[title]]', title);
                }
                //note on bootstrap we stop: , a[href]:after{content: " (" attr(href) ")";} to don't print link
                var prpnd_txt = '<style type="text/css">@media print{.hidden{display:none;}}.clear-after-div:after {content:"";display:block;clear: both;}</style>';
                prpnd_txt += '<div class="clear-after-div dt-print-header-container">' + tmp_print_header + '</div>';
                win_body
                    .css('font-size', '50px')
                    .prepend(prpnd_txt);
                //
                win_body.find('table').addClass('compact').css({ 'margin-top': '20px' });

                //
                var hdr_class = [],
                    hdr_width = [],
                    hdr_ttl_wdth = 0;
                //below to$() to convert to jquery object
                dt_api.columns().header().to$().each(function(tmp_indx) {
                    //check only visible columns maybe hidden from column visibility
                    if (dt_api.column(tmp_indx).visible()) {
                        var tmp_class = " " + $(this).attr('class') + " ";
                        tmp_class = tmp_class.replace(" sorting_asc_disabled ", " ");
                        tmp_class = tmp_class.replace(" sorting_desc_disabled ", " ");
                        tmp_class = tmp_class.replace(" sorting_disabled ", " ");
                        tmp_class = tmp_class.replace(" sorting_asc ", " ");
                        tmp_class = tmp_class.replace(" sorting_desc ", " ");
                        hdr_class.push(tmp_class);
                        hdr_width.push($(this).width());
                        hdr_ttl_wdth += $(this).width();
                    }
                });
                $('thead th', win_body).each(function(indx) {
                    if (hdr_ttl_wdth != 0 && !$(name).hasClass('table-print-no-width'))
                        win_body.find('thead th:nth-child(' + (indx + 1) + ')').css('width', ((hdr_width[indx] * 100) / hdr_ttl_wdth) + '%');
                    //if there is a class on the header then add this class on print to the thead th & tbody td
                    if (hdr_class[indx] != undefined && hdr_class[indx] != '')
                        win_body.find('thead th:nth-child(' + (indx + 1) + '), tbody td:nth-child(' + (indx + 1) + ')').addClass(hdr_class[indx]);
                    //we can add it in the header column ex: <th><span style="display:none;">[[is_empty_col]]</span>Column Name</th>
                    //we also hide the text from buttons.colVis.min.js file
                    if ($(this).text().indexOf('[[is_hide_col]]') != -1) //hide whole column
                        win_body.find('thead th:nth-child(' + (indx + 1) + '), tbody td:nth-child(' + (indx + 1) + ')').addClass('hidden');
                    if ($(this).text().indexOf('[[is_empty_col]]') != -1) { //empty data for this col., keep header only
                        win_body.find('tbody td:nth-child(' + (indx + 1) + ')').html('');
                        $(this).html($(this).html().replace('[[is_empty_col]]', ''));
                    }
                });
                //if need to keep table tr row class on print
                if ($(name).hasClass('table-print-tr-class')) {
                    var tmp_cls = '';
                    dt_api.rows().nodes().to$().each(function(indx) {
                        tmp_cls = " " + $(this).attr('class') + " ";
                        tmp_cls = tmp_cls.replace(" odd ", " ");
                        tmp_cls = tmp_cls.replace(" even ", " ");
                        if ($.trim(tmp_cls) != '')
                            $('tbody tr:nth-child(' + (indx + 1) + ')', win_body).addClass(tmp_cls);
                    });
                }
                //
                $("<div class='col-xs-12'><div class='row'>" + print_footer + "</div></div>").insertAfter($(win.document.body).find('table'));
            }
        }
    ];
    //
    buttons_arr.push((is_server_side ? {
        text: '<i class="fa fa-file-excel-o"></i> CSV',
        action: function(e, dt, node, config) {
            var ajax_url = $(name).DataTable().ajax.url();
            ajax_url += (ajax_url != "" || ajax_url.indexOf('?') === -1 ? '?' : '&');
            ajax_url += 'smc__is_export_csv=1';
            var url_params = $(name).DataTable().ajax.params();
            //get visible col. indexed
            var tmp_vsbl_col = [];
            var th_indx = 0;
            var col_lbl = [];
            dt.columns().eq(0).each(function(index) {
                if (dt.column(index).visible()) {
                    tmp_vsbl_col.push(index);
                    col_lbl[index] = $(name + ' thead tr:first th').eq(th_indx++).text();
                }
                // ... can do something with dt.column(index).data(), or dt.column(index).nodes(), etc
            });
            var cols_params = { "ExportedColumns": tmp_vsbl_col /*colArr*/ , "LabelColumns": col_lbl };
            url_params = $.extend(true, {}, url_params, cols_params);
            var is_post = true; //we use post not get since in large data table columns we get error: Submitted URI too large!
            if (is_post) {
                if ($('#tmp_trusto_iframe_export_csv_iframe').length === 0)
                    $('body').append("<iframe id='tmp_trusto_iframe_export_csv_iframe' name='tmp_trusto_iframe_export_csv_iframe' src='about:blank' style='display:none;opacity:0;border:0;width:0px;height:0px;' frameborder='0'></iframe>");
                var tmp_form = $("<form style='display:none;opacity:0;' method='post' id='tmp_trusto_iframe_export_csv_form'></form>")
                    .attr('target', 'tmp_trusto_iframe_export_csv_iframe') //to submit on the iframe
                    .attr('action', ajax_url + '&smc__is_datatable_method=post');
                $('body').append(tmp_form);
                //we send them as one hidden input or we must send multi hidden inputs but must make recursion since there is multi level json
                tmp_form.append($("<input type='hidden' />").attr('name', 'smc__datatable_post_data').val(JSON.stringify(url_params)));
                if (typeof optns['ajax'] !== 'undefined' && typeof optns['ajax'].type !== 'undefined')
                    tmp_form.append($("<input type='hidden' />").attr('name', 'smc__datatable_request_method').val(optns['ajax'].type));
                tmp_form.submit().remove();
            } else {
                ajax_url += '&' + $.param(url_params);
                window.location = ajax_url;
            }
            //alert(dt.toSource())
            //node.attr('disabled', 'disabled'); //disable download button to prevent multi-click, probably some sort of *busy* indicator is a good idea
            //dt.ajax.reload(); //re-run *DataTables* AJAX query with current filter and sort applied
        }
    } : {
        extend: 'excelHtml5', //with csv 'csvHtml5' problem in arabic encoding
        text: '<i class="fa fa-file-excel-o"></i> CSV',
        exportOptions: { "columns": ':visible:not(.no-print)' /*colArr*/ },
        title: title,
        footer: is_footer,
        titleAttr: 'CSV',
        className: 'downloadCSV'
    }));
    //
    buttons_arr.push({
        extend: 'colvis',
        text: colvis_lang,
        //        columns: ':gt(0)',  //don't allow hide first col.
        collectionLayout: 'fixed two-column',
        //        postfixButtons: ['colvisRestore']
    });
    //
    var dflt_align = 'dt-center';
    if (typeof datatable_default_align !== undefined) {
        if (datatable_default_align == 'center')
            dflt_align = 'dt-center';
        else if (datatable_default_align == 'right' || (datatable_default_align == 'language' && lang_code == 'ar'))
            dflt_align = 'dt-right';
        else if (datatable_default_align == 'left' || (datatable_default_align == 'language' && lang_code != 'ar'))
            dflt_align = 'dt-left';
    }
    //
    var data_table_optns = {
        processing: true,
        serverSide: is_server_side,
        stateSave: true, //needed more for col. visibility to save state
        stateDuration: 0, //default is 7200 seconds, ex: for 1 day: [60*60*24], 0: not time limit, -1: use session and not local storage
        stateSaveParams: function(settings, data) {
            //console.log(data);
            delete data.search.search; //clear for global search
            for (var i = 0; i < data.columns.length; i++) //clear search per column
                delete data.columns[i].search;
            data.start = 0; //clear paging
        },
        //aLengthMenu: [[10, 25, 50,100,500, -1], [10, 25, 50, 100,500,"All"]],
        aLengthMenu: [
            [10, 25, 50, 100, 500, 1000],
            [10, 25, 50, 100, 500, 1000]
        ],
        pageLength: 10,
        orderCellsTop: true,
        //"ajax": {
        //    "url": myurl,
        //    "data": data
        //},
        rowsGroup: span_arr,
        bSort: true,
        dom: 'ZBlfrtip', //we add 'Z' for column resize
        pagingType: "full_numbers",
        aaSorting: [], //we empty since by default it will take [[0,'asc']] so it will sort 1st col.
        "language": {
            "url": lang_code == 'ar' ? site_link + "/Theme/plugins/datatables/datatable_arabic_lang.json" : ""
        },
        createdRow: function(row, data, index) {
            if ($('td input[name=check_done]', row).hasClass('text-line-through')) {
                $(row).addClass('text-line-through');
            }
        },
        // to allow user to resize columns, https://github.com/Silvacom/colResize
        colResize: {
            //if put true, that means fixed table width, so if we maimize a specific col. it will be subtracted from it's neighbor
            //col. while if false it will be added to the whole table width and only the desired column will be effected.
            tableWidthFixed: false,
            rtl: ($(name).css('direction') == 'rtl'),
            handleWidth: 12 //in px. resize handle width, ex: 10px so will get 5 from right and 5 from left the col. separator
                //            , exclude: [0, 2]  //if want to exclude specific columns from resize
                //            , resizeCallback: function (column) { //if want to make a callback ft. when resize a column
                //                alert("Column Resized");
                //            }
        },
        columnDefs: [
            { "className": dflt_align, "targets": "_all" },
            //{targets: [0, 2], visible: true},
            //{targets: '_all', visible: false}
        ],
        //rowsGroup: [1],
        buttons: buttons_arr,
        "fnDrawCallback": function(oSettings) {}

    };
    //
    if (is_server_side)
        data_table_optns.ajax = { url: myurl, data: data };
    //
    if (!visible_col_indx.length)
        data_table_optns.columnDefs.push({ targets: '_all', visible: true });
    else {
        data_table_optns.columnDefs.push({ targets: visible_col_indx, visible: true });
        data_table_optns.columnDefs.push({ targets: '_all', visible: false });
    }
    //
    if (optns !== undefined && optns['cb_ft'] !== undefined) {
        optns.cb_ft(data_table_optns); //here object are send by reference so in side cb_ft. we can directly modify data_table_optns
        delete optns.cb_ft;
    }
    //
    if (optns !== undefined && optns['extra_columnDefs'] !== undefined) {
        $.each(optns['extra_columnDefs'], function(index, col_def_row) {
            data_table_optns.columnDefs.push(col_def_row);
        });
        delete optns.extra_columnDefs;
    }
    data_table_optns = $.extend(true, {}, data_table_optns, optns);
    //    console.log(data_table_optns);
    //
    var mytable = $(name).DataTable(data_table_optns);
    //
    mytable.columns().every(function(e) {
        if (search_col_row != "") {
            $(search_col_row).on('keyup change', 'td input', function() {
                var col = mytable.column($(this).parent().attr('data-col-index')); //get current column
                if (col.search() !== this.value) {
                    col.search(this.value).draw();
                }
            });
        }
    });
    //console.log(data_table_optns)
    jQuery.extend(jQuery.fn.dataTableExt.oSort, {
        "formatted-num-pre": function(a) {
            a = (a === "-" || a === "" || a === null || a === undefined) ? 0 : a.replace(/[^\d\-\.]/g, "");
            return parseFloat(a);
        },
        "formatted-num-asc": function(a, b) {
            return a - b;
        },
        "formatted-num-desc": function(a, b) {
            return b - a;
        }
    });
    return mytable;
}
//function RebuildDataTable(title, colArr, url, data, table, rowSpan, optns,msg) {
//    msg = msg===undefined ? '':msg;
//    var org_name = org_head[0]['Organization_Legal_Name'],
//            org_phone = org_head[0]['Organization_Phone'],
//            org_address = org_head[0]['Name'] + '-' + org_head[0]['Organization_Province'];
//    data = (data == undefined || data == '' || data == false || data == null) ? {} : data;
//    var span_arr = rowSpan === undefined || rowSpan == '' || rowSpan == false || !rowSpan.length ? '' : rowSpan;
//    var name = ((table === undefined || table === '' || table === false) ? "#tableWithSearch" : table);
//    //
//    var myurl = ((url === undefined || url === '' || url === false) ? '' : (window.site_link + url));
//    var is_server_side = myurl === '' ? false : true;
//    //
//    var visible_col_indx = [];
//    $(name + ' thead tr.filter_columns_row td').each(function () {
//        visible_col_indx.push(parseFloat($(this).attr('data-col-index')));
//    });
//    //
//    $(name).DataTable().destroy();
//    if (is_server_side)
//        $(name + " tbody").empty();
//    $(name + " thead tr.filter_columns_row").remove();
//    var is_footer = $(name + " tfoot tr").length > 0;   //needed for buttons to know with footer or not
//    //
//    var search_col_row = "<tr class='filter_columns_row' style=' '>";
//    var col_indx = 0;
//    $(name + ' thead th').each(function () {
//        //console.log($(this).html())
//        //var title = $(this).text();  // placeholder="Search ' + title + '"
//        search_col_row += '<td data-col-index="' + (col_indx++) + '" style="background-color:#e5e5e5;" class="dt-input-search"><input type="search" class="form-control" style="width:100%;padding:3px 2px;min-height:0px;height:auto;" /></td>';
//    });
//    search_col_row += '</tr>';
//    search_col_row = $(search_col_row);
//    search_col_row.appendTo($(name + ' thead'));
//    //
//    var buttons_arr = [
//        {
//            extend: 'excelHtml5',
//            exportOptions: {"columns": ':visible'/*colArr*/},
//            title: title,
//            footer: is_footer,
//            text: '<i class="fa fa-file-excel-o"></i> Excel'
//        },
////        {
////            extend: 'pdfHtml5',
////            exportOptions: {"columns": ':visible' /*colArr*/},
////            footer: is_footer,
////            title: title,
////            text: '<i class="fa fa-file-pdf-o"></i> Pdf',
////            "sCharSet": 'utf-8'
////        },
//        {
//            extend: 'print',
//            text: '<i class="fa fa-print"></i> Print',
//            exportOptions: {"columns": ':visible'/*colArr*/},
//            title: title,
//            footer: is_footer,
//            customize: function (win) {
//                $(win.document.body)
//                        .css('font-size', '50px')
//                        .prepend(
//                                '<div class="col-xs-6">' +
//                                '<h4>' + org_name + '</h4>' +
////                                '<h4>' + org_phone + '</h4>' +
////                                '<h4>' + org_address + '</h4>'+
//                                msg+'</div>' +
//                                '<img src="' + window.site_link + 'img/logo_white.png" style="margin-rightt:20px;margin-bottom:20px;width:150px;heigth:150px;float:right;position:absolute;opacity:0.5; top:0; right:0;" />'
//                                );
//                $(win.document.body).find('table').addClass('compact').css({'margin-top': '150px'});
//            }
//        }
//    ];
//    //
//    buttons_arr.push((is_server_side ?
//            {
//                text: '<i class="fa fa-file-excel-o"></i> CSV',
//                action: function (e, dt, node, config) {
//                    var ajax_url = $(name).DataTable().ajax.url();
//                    ajax_url += (ajax_url != "" || ajax_url.indexOf('?') === -1 ? '?' : '&');
//                    ajax_url += 'smc__is_export_csv=1&';
//                    ajax_url += $.param($(name).DataTable().ajax.params());
//                    ajax_url += '&' + $.param({"ExportedColumns": colArr});
//                    window.location = ajax_url;
//                    //alert(dt.toSource())
//                    //node.attr('disabled', 'disabled'); //disable download button to prevent multi-click, probably some sort of *busy* indicator is a good idea
//                    //dt.ajax.reload(); //re-run *DataTables* AJAX query with current filter and sort applied
//                }
//            } :
//            {
//                extend: 'excelHtml5', //with csv 'csvHtml5' problem in arabic encoding
//                text: '<i class="fa fa-file-excel-o"></i> CSV',
//                exportOptions: {"columns": ':visible'/*colArr*/},
//                title: title,
//                footer: is_footer,
//                titleAttr: 'CSV',
//                className: 'downloadCSV'
//            }));
//    //
//    buttons_arr.push({
//        extend: 'colvis',
//        columns: ':gt(0)',
//        collectionLayout: 'fixed two-column',
////        postfixButtons: ['colvisRestore']
//    });
//    //
//    var data_table_optns = {
//        "processing": true,
//        "serverSide": is_server_side,
//        stateSave: true, //needed more for col. visibility to save state
//        stateSaveParams: function (settings, data) {
////            console.log(data);
//            delete data.search.search;    //clear for global search
//            for (var i = 0; i < data.columns.length; i++)   //clear search per column
//                delete data.columns[i].search;
//            data.start = 0;   //clear paging
//        },
//        /*    "aLengthMenu": [[10, 25, 50,100,500, -1], [10, 25, 50, 100,500,"All"]],*/
//        "aLengthMenu": [[10, 25, 50, 100, 500, 800], [10, 25, 50, 100, 500, 800]],
//        orderCellsTop: true,
////        "ajax": {
////            "url": myurl,
////            "data": data
////        },
//        rowsGroup: span_arr,
//        "bSort": true,
//        dom: 'Blfrtip',
//        "pagingType": "full_numbers",
//        "aaSorting": [],
//        "createdRow": function (row, data, index) {
//            if ($('td input[name=check_done]', row).hasClass('text-line-through')) {
//                $(row).addClass('text-line-through');
//            }
//        },
//        "columnDefs": [
//            {"className": "dt-center", "targets": "_all"}
////            {targets: [0, 2], visible: true},
////            {targets: '_all', visible: false}
//        ],
//        //       rowsGroup: [1],
//        buttons: buttons_arr,
//        "pageLength": 10
//    };
//    //
//    if (is_server_side) {
//        data_table_optns.ajax = {
//            "url": myurl,
//            "data": data
//        };
//    }
//    //
//    if (!visible_col_indx.length) {
//        data_table_optns.columnDefs.push({targets: '_all', visible: true});
//    } else {
//        data_table_optns.columnDefs.push({targets: visible_col_indx, visible: true});
//        data_table_optns.columnDefs.push({targets: '_all', visible: false});
//    }
//    //
////    if(optns.cb_ft !== undefined){
////        data_table_optns = optns.cb_ft(data_table_optns);
////        delete optns.cb_ft;
////    }
//    data_table_optns = $.extend(true, {}, data_table_optns, optns);
//    //console.log(data_table_optns);
//    //
//    var mytable = $(name).DataTable(data_table_optns);
//    //
//    mytable.columns().every(function (e) {
//        $(search_col_row).on('keyup change', 'td input', function () {
//            var col = mytable.column($(this).parent().attr('data-col-index'));   //get current column
//            if (col.search() !== this.value) {
//                col.search(this.value).draw();
//            }
//        });
//    });
//}

//function build_select2(select_name, url,new_class) {
//    new_class ==undefined ? '' : new_class;
//    select_name.select2({
//        initSelection: function (element, callback) {
//            if ($(element).val() != "") {
//                try {
//                    text_val = JSON.parse($(element).attr('data-select-name'));
//                } catch (e) {
//                    text_val = $(element).attr('data-select-name');
//                }
//                var data = {id: $(element).val(), text: text_val};
//                callback(data);
//            }
//        },
//        placeholder: 'Select',
//        allowClear: true,
//        dropdownCssClass : new_class,
//        ajax: {
//            url: url,
//            dataType: 'json',
//            delay: 250,
//            data: function (term, page) {
//                return {
//                    term: term,
//                    page: page,
//                    limit: 10
//                };
//            },
//            results: function (data, page) {
//                return {results: data.data, more: data.is_more};
//            },
//            cache: true
//        },
//        minimumInputLength: 0
//    });
//}
function build_select2(select_name, url, multiple, new_class, tmp_optns) {
    //we clone it since object send by reference so if we change here it will change by the main variable we send
    var optns = (tmp_optns == undefined || tmp_optns == '' || tmp_optns == false || tmp_optns == null) ? {} : Object.create(tmp_optns);
    //
    new_class = (new_class == undefined ? '' : new_class);
    var is_multiple = (multiple === undefined || multiple == '' || multiple == false ? false : true);
    //
    var select2_optns = {
        initSelection: function(element, callback) {
            var optns_val = $(element).val();
            if (optns_val != "") {
                var optns_txt, other_data;
                try {
                    optns_txt = JSON.parse($(element).attr('data-select-name'));
                } catch (e) {
                    optns_txt = $(element).attr('data-select-name');
                }
                try {
                    other_data = JSON.parse($(element).attr('data-other-data'));
                } catch (e) {
                    other_data = $(element).attr('data-other-data');
                }
                //if it is object then it is array and value is multi with comma as separator
                if (optns_txt != undefined && optns_txt != null && typeof optns_txt == 'object' && optns_txt.length > 0) {
                    var ids_arr = optns_val.split(",");
                    var optns_count = Math.min(ids_arr.length, optns_txt.length);
                    var data = [];
                    for (var i = 0; i < optns_count; i++) {
                        var tmp_row = { id: ids_arr[i], text: optns_txt[i] };
                        if (other_data != undefined && other_data != null && typeof other_data == 'object') {
                            $.each(other_data[i], function(indx, val) {
                                tmp_row[indx] = val;
                            });
                        }
                        data.push(tmp_row);
                    }
                    callback(data);
                } else {
                    var data = { id: optns_val, text: optns_txt };
                    if (other_data != undefined && other_data != null && typeof other_data == 'object') {
                        $.each(other_data, function(indx, val) {
                            data[indx] = val;
                        });
                    }
                    callback(data);
                }
            }
        },
        multiple: is_multiple,
        placeholder: select_lang,
        allowClear: true,
        dropdownCssClass: new_class,
        ajax: {
            url: url,
            dataType: 'json',
            delay: 250,
            data: function(term, page) {
                return {
                    term: term,
                    page: page,
                    limit: 10
                };
            },
            results: function(data, page) {
                return { results: data.data, more: data.is_more };

            },
            cache: true
        },
        minimumInputLength: 0
    };
    select2_optns = $.extend(true, {}, select2_optns, optns);
    //
    select_name.select2(select2_optns);
}

function printExternal(url) {
    $("#print_iframe").remove();
    $("<iframe id='print_iframe' style='position:absolute;top:0px;left:0;width:0px;height:0px;opacity:0;' src='" + url + "' onload='document.getElementById(\"print_iframe\").contentWindow.print();'  ></iframe>").appendTo("body");


}

function apply_autocomplete(who, url, callback) {
    var source_obj = url;
    //    console.log(typeof url);
    if (typeof url !== 'string')
        source_obj = function(request, response) {
            $.getJSON(url(who), request, function(s, status, xhr) {
                response(s);
            });
        };
    //
    who.autocomplete({
        source: source_obj,
        minLength: 0,
        select: function(event, ui) {
            callback(event, ui, who);
            return false;
        }
    });
    who.focus(function() {
        $(this).autocomplete("search", $(this).val());
    });
    who.autocomplete("instance")._resizeMenu = function(ul, items) {
        this.menu.element.outerWidth(who.width() * 3);
    };
    who.autocomplete("instance")._renderItem = function(ul, item) {
        var MyType = item.text;
        return $("<li>").html("<table cellspacing='0' cellpadding='0'><tr><td class='OnlyText'>" + MyType + "</td></tr></table>").appendTo(ul);
    };
    who.addClass("AutoAdded");
}

function rangepicker_js(onchange, from, to) {
    //    console.log(from)
    //    console.log(to)
    window.start = (from == undefined ? today : from);
    window.end = (to == undefined ? today : to);
    $("input[name=From_To_Date]").daterangepicker({
        autoApply: true,
        singleDatePicker: false,
        showDropdowns: true,
        locale: {
            format: 'YYYY-MM-DD'
        },
        ranges: {
            'Today': [moment(), moment()],
            'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
            'Last 7 Days': [moment().subtract(6, 'days'), moment()],
            'Last 30 Days': [moment().subtract(29, 'days'), moment()],
            'This Month': [moment().startOf('month'), moment().endOf('month')],
            'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
        },
        startDate: (from == undefined ? today : from),
        endDate: (to == undefined ? today : to)
    }, function(start, end) {

        window.start = (from == undefined ? start.format('YYYY-MM-DD') : from);
        window.end = (to == undefined ? end.format('YYYY-MM-DD') : to);
        if (onchange)
            onchange()
    });
    //        console.log(window.start)
    //        $("input[name=From_To_Date]").daterangepicker({
    //            locale: {
    //                format: 'YYYY-MM-DD'
    //            },
    //
    //            startDate: window.today
    //
    //        },     function(start, end,label){
    //            window.startDate = start.format("YYYY-MM-DD"),
    //                window.endDate = end.format("YYYY-MM-DD")
    //
    //        });
}

function CurrentDate(freq) {

    var FinalDate;

    if (freq == 1) {

        window.FinalDate = $("#Daily_Date").val()

    } else
    if (freq == 2) {
        window.FinalDate = [moment($("#Month_Date").val()).format("YYYY"), moment($("#Month_Date").val()).format("MM"), moment($("#Month_Date").val()).format("DD")]
    } else
    if (freq == 3) {
        window.FinalDate = [moment($("#Year_Date").val()).format("YYYY"), moment($("#Year_Date").val()).format("MM"), moment($("#Year_Date").val()).format("DD")]
    }

}

function addCommas(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];

    x2 = x.length > 1 ? '.' + x[1] : '';

    var rgx = /(\d+)(\d{3})/;

    while (rgx.test(x1)) {

        x1 = x1.replace(rgx, '$1' + ',' + '$2');

    }

    return x1 + x2;
}

function AddAlert(AlertID, Description, type) {
    $(AlertID).attr('class', 'alert alert-' + type).html(Description)
    setTimeout(function() {
        $(AlertID).addClass('hidden')
    }, 6000);
}

function hideModalAlert(modal_id, alert_id) {
    setTimeout(function() {
        $("#" + modal_id).modal('hide');
        $("#" + alert_id).addClass('hidden');
    }, 1500)
}

function IncludeDeleteModal(translateArray, Data, OnRemove, url, alertBeforeSubmit, prevent_delete) {
    alertBeforeSubmit = (alertBeforeSubmit === undefined ? '' : alertBeforeSubmit);
    prevent_delete = (prevent_delete === undefined ? '' : prevent_delete);
    var GlobalDeleteObject = '<div class="modal fade" style="max-width: 400px;margin: auto;max-height: 100%;"  data-backdrop="static" id="GlobalDeleteObject" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">' +
        '<div class="modal-dialog">' +
        '    <div class="modal-content">' +
        '        <div class="modal-header">' +
        '<button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="pg-close fs-20"></i>' +
        '</button>' +
        '            <h5 class="text-left bold" id="myModalLabel">' + translateArray[0] + '</h5>' +
        '        </div>' +
        '        <div class="modal-body">' +
        '        <div class="row">' +
        '<div class="col-md-12 m-t-10"><div class="alert hidden" id="GlobalDeleteAlert"></div></div>' +
        '          <div class="Conf col-md-12 m-t-10">' +
        '            <p>' + translateArray[1] + '</p>' +
        '            	<p>' + translateArray[2] + '</p>' +
        '          </div>' +
        '        </div>' +
        '        </div>' +
        '        <div class="modal-footer">' +
        '            <button type="button" class="btn btn-default cancelDelete" data-dismiss="modal">' + translateArray[3] + '</button>' +
        '            <button type="button" class="RemoveThisItem btn btn-danger danger widthauto">' + translateArray[4] + '</button>' +
        '        </div>' +
        '    </div>' +
        '<div ID="GlobalDeleteLoader" style="position:absolute;left:0;right:0;top:0px;height:100%;background:rgba(255,255,255,0.9);z-index:999" class="hidden"><img class="image-responsive-height demo-mw-50" src="' + site_link + 'img/demo/progress.svg" alt="Progress" style="position: absolute;left: 50%;top: 50%;margin: -25px 0 0 -25px;" /></div>' +
        '</div>' +
        '</div>';
    $(GlobalDeleteObject).appendTo("body")
    $("#GlobalDeleteObject .RemoveThisItem").attr('disabled', false)
    $("#GlobalDeleteObject").modal('show');
    if (alertBeforeSubmit) {
        $('#GlobalDeleteAlert').attr('class', 'alert alert-danger').html(alertBeforeSubmit);
    }
    if (prevent_delete)
        $("#GlobalDeleteObject .RemoveThisItem").attr('disabled', true);
    $("#GlobalDeleteObject .RemoveThisItem").on("click", function(e) {
        $.ajax({
            url: site_link + url,
            data: Data,
            complete: function(jqXHR, status) {
                if (status == 'success') {
                    $("#GlobalDeleteLoader").removeClass('hidden')
                    $("#GlobalDeleteObject .RemoveThisItem").attr('disabled', true);
                    if (jqXHR.responseText == 'ok') {
                        AddAlert('#GlobalDeleteAlert', translateArray[5], 'success')
                        setTimeout(function() {
                            $('#GlobalDeleteObject').modal("hide");
                        }, 1500)
                        if (OnRemove)
                            OnRemove()
                    } else {
                        AddAlert('#GlobalDeleteAlert', jqXHR.responseText, 'danger')
                    }
                    $("#GlobalDeleteLoader").addClass('hidden')
                }
            }
        });
        e.preventDefault();
    });
    $("#GlobalDeleteObject").on("hidden.bs.modal", function(e) {
        $(this).remove()
    });
}

function deleteSpecificImage(Data, loader, onDelete) {
    $(loader).removeClass('hidden')
    $.ajax({
        url: "SettingsAjax/deletSpecificImage",
        data: Data,
        dataType: "json",
        complete: function(jqXHR, status) {
            if (status == 'success') {
                if (onDelete)
                    onDelete(jqXHR.responseJSON)

                $(loader).addClass('hidden')
            }
        }
    });
}

function validateImage(input) {
    var IsFileOK = false;
    if (input.files && input.files[0]) {
        var FileName = $.trim(input.files[0].name)
        var FileType = FileName.substring(FileName.lastIndexOf("."));
        //console.log(FileType)
        if (FileType) {
            var is_error = '';
            FileType = FileType.toLowerCase();
            if (FileType != ".png" && FileType != ".jpg" && FileType != ".jpeg")
                is_error = "You can't upload this type of files <br> Avaliable types(.png, .jpg, .jpeg)";
            // check file size
            var max_size = input.getAttribute('data-max-size');
            if (!is_error && max_size != null && max_size != undefined) {
                var FileSizeKB = input.files[0].size / 1024;
                if (FileSizeKB > max_size)
                    is_error = 'File Size Exceed (' + max_size + ' KB)';
            }
            if (is_error) {
                toastr.warning(is_error);
                $(input).val('');
            } else
                IsFileOK = true;
        }
    }
}

function subtractFromTime(start_time, value, type) {
    return moment(start_time, 'HH:mm:ss').subtract(value, type).format('HH:mm:ss');
}

function round_number(number, digits) {
    digits = 2;
    if (digits === undefined)
        digits = 7;

    digits = parseFloat(1 + '0'.repeat(digits));
    //    console.log(digists+'==')
    return total = Math.round(number * digits) / digits;
}

function fillQuestionDetails(questions, main_div, question_div) {
    $(main_div).empty();
    if (questions.length > 0) {
        $(question_div).removeClass('hidden');
        $.each(questions, function(index, value) {
            var question_type = questions[index]['answer_type_id'],
                question_solution = "question_solution" in questions[index] ? questions[index]['question_solution'] : false,
                content = '<div class="row m-t-10 question-row" data-id="' + questions[index]['checklist_question_id'] + '" data-type="' + question_type + '"><div class="col-md-12">' +
                '<div class="col-md-6">' +
                '<input type="text" name="question_name" readonly value="' + questions[index]['question_name'] + '"  class="full-width form-control question_name" >' +
                '</div><div class="col-md-6">';
            if (question_type == "1") {
                content += '<div class="radio radio-success-dark "><input type="radio" ' + ((question_solution && question_solution == "1") ? 'checked' : '') + ' class="yes_no" value="1"  name="yes_no' + index + '" id="yes' + index + '" ><label for="yes' + index + '">Yes</label><input type="radio" ' + ((question_solution && question_solution == "2") ? 'checked' : '') + ' value="2"  name="yes_no' + index + '" class="yes_no" id="no' + index + '" ><label for="no' + index + '">No</label></div>';
            } else if (question_type == "2") {
                content += '<input type="number" placeholder="Number" name="question_number" value="' + (question_solution ? question_solution : '') + '" class="form-control">';
            } else if (question_type == "3") {
                var range_from_to = questions[index]['answer_type_value'].split(",");
                content += '<input type="number" min="' + range_from_to[0] + '" max="' + range_from_to[1] + '" placeholder="Range (min: ' + range_from_to[0] + ' max: ' + range_from_to[1] + ')"  name="range" value="' + (question_solution ? question_solution : '') + '"   class="form-control ">';
            } else if (question_type == "4") {
                content += '<input type="text" placeholder="Text" name="question_text" value="' + (question_solution ? question_solution : '') + '" class="form-control">';
            } else {
                var content_select = questions[index]['answer_type_value'].split(","),
                    select_type = question_type == "5" ? '' : 'multiple';
                content += '<select name="select' + index + '"  ' + select_type + ' class="full-width single_multiple_select">';
                content += question_type == "5" ? '<option value=""></option>' : '';
                $.each(content_select, function(index, value) {
                    content += '<option value="' + content_select[index] + '" ' + (question_solution ? (content_select[index] == question_solution ? 'selected' : '') : '') + '>' + content_select[index] + '</option>';
                });
                content += '<select>';
            }
            content += '</div></div></div>';
            $(main_div).append($(content));
            $("select[name=select" + index + "]").select2();
            if (question_type == "6" && question_solution) {
                $("select[name=select" + index + "]").val(question_solution.split(","));
                $("select[name=select" + index + "]").select2();
            }
        });

    } else {
        $(question_div).addClass('hidden');
    }
}

function set_storage_element(key, value) {
    //    console.log(value)
    var object = JSON.stringify(value);
    sessionStorage.setItem(key, object);
}

function get_storage_element(key, sub_key) {

    var array = JSON.parse(sessionStorage.getItem(key));
    if (array == null)
        return '';
    if (sub_key == undefined)
        return array;
    return array[sub_key];
}

function ValidateForNewAttachment(input, allowedExtensions) {
    var FileUploadError = '',
        maxAllowedSizeKB = 10000,
        is_not_validated = false;
    $.each(input.files, function(index) {
        var FileSizeKB = input.files[index].size / 1024,
            FileName = $.trim(input.files[index].name),
            FileType = FileName.substring(FileName.lastIndexOf(".")).toLowerCase(),
            specific_image_error = '';
        if (FileSizeKB > maxAllowedSizeKB) {
            specific_image_error += 'File Size Exceed (' + maxAllowedSizeKB + ' KB) for file (' + (index + 1) + ')  ';
            is_not_validated = true;
        }
        if (allowedExtensions.indexOf(FileType) == -1) {
            specific_image_error += 'File Extension (' + FileType + ') not Supported (Supported Extensions: ' + allowedExtensions.join() + ' ) for file (' + (index + 1) + ')';
            is_not_validated = true;
        }
        FileUploadError += specific_image_error + (specific_image_error != '' ? '<br>' : '');
    });
    if (is_not_validated) {
        $(input).val('');
        $("html").animate({ scrollTop: 0 }, "slow");
        toastr.error(FileUploadError);
    }
    return false;
}