var customjs = function () {

//global hosturl
    var hosturl = $('#hosturl').val();
    var hideitem = function () {
        //to open model for accept del
        $('.hideitem').click(function () {
            var itemid = $(this).attr('data-id');
            var urlgo = $(this).attr('data-link');
            var ishide = $(this).attr('data-ishide');
            var thisitem = $(this);
            $.post(hosturl + "/" + urlgo + "/hide", {itemid: itemid, ishide: ishide}, function (rst) {

                if (Number(rst) == 1) {
                    var newhide = 0;
                    var textis = 'اخفاء';
                    thisitem.parent().parent().removeClass('unread');
                    if (ishide == 0) {
                        newhide = 1;
                        textis = 'اظهار';
                        thisitem.parent().parent().addClass('unread');
                    }

                    thisitem.attr('data-ishide', newhide);
                    thisitem.html('<i class="fa fa-history"></i> ' + textis);
                    var shortCutFunction = 'success';
                    var msg = 'اكمل باقى العمل .. تم العمل بنجاح ';
                    var title = 'تم بنجاح';
                } else {
                    var shortCutFunction = 'error';
                    var msg = 'جرب مره اخرى ....  لقد حدث خطا';
                    var title = 'حذث خطا';
                }

                toastr.options = {
                    closeButton: $('#closeButton').prop('checked'),
                    debug: $('#debugInfo').prop('checked'),
                    positionClass: $('#positionGroup input:checked').val() || 'toast-top-right',
                    onclick: null
                };
                var $toast = toastr[shortCutFunction](msg, title);
            });
        });
    }

    var firms = function () {

//change type
        $('input[type=radio][name=firmtype]').change(function () {
            $typeis = $(this).val();
            if ($typeis == 1) {
                $('#starno_containers').removeClass('hide');
            } else {
                $('#starno_containers').addClass('hide');
            }
        });
        //upload multi
        var file_dropzone_id;
        Dropzone.options.myDropzone = {
            dictDefaultMessage: "اضغط هنا او يمكنك سحب مجموعه صوره الى هنا",
            maxFilesize: 2, // MB
            init: function () {
                this.on("success", function (e, responseText) {
                    file_dropzone_id = responseText;
                    var n = Dropzone.createElement("<a href='javascript:;' data-id='" + file_dropzone_id + "' class='btn red btn-sm btn-block '>حذف</a>"),
                            t = this;
                    n.addEventListener("click", function (n) {
                        $thisid = $(this).attr('data-id');
                        $.post(hosturl + "/_global_service/delfile", {itemid: $thisid}, function () {
                            n.preventDefault(), n.stopPropagation(), t.removeFile(e);
                        });
                    }), e.previewElement.appendChild(n)

                }), this.on("addedfile", function (e) {

                }), this.on(
                        "sending", function (file, xhr, formData) {
                            formData.append('firmid', $('#firmId').val());
                        });
            }
        };
        $('.delfile_in').click(function () {
            $thisid = $(this).attr('data-id');
            var this_bt = $(this);
            $.post(hosturl + "/_global_service/delfile", {itemid: $thisid}, function () {
                this_bt.parent().remove();
            });
        });
        //add branches
        var bitr = Number($("#bitr").val()) + 1;
        $('#add_branch').click(function () {

//add new branch
            var newbranch = '<div><div class="row">'
                    + '<div class="col-md-3">'
                    + '<div class="form-group">'
                    + '<label class="control-label">اسم الفرع</label>'
                    + '<input type="text" name="bname' + bitr + '" class="form-control" placeholder="اسم الفرع" required="">'
                    + '</div>'
                    + '</div>'
                    + '<div class="col-md-3">'
                    + '<div class="form-group">'
                    + '<label class="control-label">Name</label>'
                    + '<input type="text" name="en_bname' + bitr + '" class="form-control" placeholder="Name" required="">'
                    + '</div>'
                    + '</div>'
                    + '<div class="col-md-3">'
                    + '<div class="form-group">'
                    + '<label class="control-label">هاتف</label>'
                    + '<input type="text" name="bphone' + bitr + '" class="form-control" placeholder="هاتف" required="">'
                    + '</div>'
                    + ' </div>'
                    + '<div class="col-md-3">'
                    + '<div class="form-group">'
                    + '<label class="control-label">جوال</label>'
                    + '<input type="text" name="bmobile' + bitr + '" class="form-control" placeholder="جوال" required="">'
                    + '</div>'
                    + '</div>'
                    + '</div>'
                    + '<div class="row">'
                    + '<div class="col-md-4">'
                    + ' <div class="form-group">'
                    + '<label class="control-label">العنوان</label>'
                    + '<textarea name="baddress' + bitr + '" class="form-control"></textarea>'
                    + '</div>'
                    + '</div>'
                    + '<div class="col-md-4">'
                    + '<div class="form-group">'
                    + '<label class="control-label">Address</label>'
                    + '<textarea name="en_baddress' + bitr + '" class="form-control"></textarea>'
                    + '</div>'
                    + '</div>'
                    + '<div class="col-md-4">'
                    + '<div class="form-group">'
                    + '<label class="control-label">الخريطه للموقع</label>'
                    + '<textarea name="bmap' + bitr + '" class="form-control"></textarea>'
                    + '</div>'
                    + '</div>'
                    + '<div class="col-md-6">'
                    + '<div class="form-group">'
                    + '<label class="control-label">رابط الخريطه للتطبيق</label>'
                    + '<textarea name="bmapmob' + bitr + '" class="form-control"></textarea>'
                    + '</div>'
                    + '</div>'
                    + '<div class="col-md-5">'
                    + ' <div class="form-group">'
                    + '<label class="control-label">المنطقه</label>'
                    + '<select class="form-control" required="" data-placeholder="اختر واحد" id="regionid' + bitr + '" name="regionid' + bitr + '">'
                    + '<option value=""></option>'
                    + $("#regionsforjs").html()
                    + '</select>'
                    + ' </div>'
                    + ' </div>'
                    + '<div class="col-md-1">'
                    + '<a href="javascript:;" data-id="0" data-edit="1" class="btn red btn-sm btn-block delbranch" style="margin-top: 27px;">حذف</a>'
                    + '</div>'
                    + '<div class="clearfix"></div><hr/>'
                    + '</div> </div>'
                    + '<!-- end of one item -->';
            $('#branches_container').append(newbranch);
            $("#regionid" + bitr).select2({placeholder: "Select", allowClear: true});
            $("#bitr").val(bitr);
            bitr++;
        });
        //remove branch
        $('.delbranch').live('click', function () {
//check for edit
            var editcheck = $(this).attr('data-edit');
            var propid = $(this).attr('data-id');
            if (editcheck == 0) {
//here will delete by ajax
                $.post(hosturl + '/firms/delbranch', {propid: propid}, function (data) {
                    if (data == 1) {
                        var shortCutFunction = 'success';
                        var msg = 'تم حذف الفرع بنجاح';
                        var title = 'Success';
                    } else {
                        var shortCutFunction = 'error';
                        var msg = 'جرب مره اخرى .. حدث خطا';
                        var title = 'Error';
                    }
                    toastr.options = {
                        closeButton: $('#closeButton').prop('checked'),
                        debug: $('#debugInfo').prop('checked'),
                        positionClass: $('#positionGroup input:checked').val() || 'toast-top-right',
                        onclick: null
                    };
                    var $toast = toastr[shortCutFunction](msg, title);
                });
            }

            $(this).parent().parent().parent().remove();
        });
    };
    var packages = function () {

        var fitr = Number($("#fitr").val()) + 1;
        $('#add_firm').click(function () {
            var newfirmin = '<div>'
                    + '<div class="row">'
                    + '<div class="col-md-4">'
                    + '<div class="form-group">'
                    + '<label class="control-label">الشركه</label>'
                    + '<select class="form-control" required="" data-placeholder="اختر واحد" id="firmid' + fitr + '" name="firmid' + fitr + '">'
                    + '<option value=""></option>'
                    + $('#firmsforjs').html()
                    + '</select>'
                    + '</div>'
                    + '</div>'
                    + '<div class="col-md-3">'
                    + '<div class="form-group">'
                    + '<label class="control-label">خصم نسبه</label>'
                    + '<input type="text" name="discountratio' + fitr + '" class="form-control" placeholder="خصم نسبه" required="">'
                    + '</div>'
                    + '</div>'
                    + '<div class="col-md-1">'
                    + '<a href="javascript:;" data-id="0" class="btn red btn-sm btn-block delfirm" style="margin-top: 27px;">حذف</a>'
                    + '</div>'
                    + '<div class="clearfix"></div>'
                    + '<hr/>'
                    + '</div>'
                    + '</div>';
            $('#firmsin_continer').append(newfirmin);
            $("#firmid" + fitr).select2({placeholder: "Select", allowClear: true});
            $("#fitr").val(fitr);
            fitr++;
        });
        //remove branch
        $('.delfirm').live('click', function () {
            //check for edit
            var editcheck = $(this).attr('data-edit');
            var propid = $(this).attr('data-id');
            if (editcheck == 0) {
                //here will delete by ajax
                $.post(hosturl + '/package/delcompany', {propid: propid}, function (data) {
                    if (data == 1) {
                        var shortCutFunction = 'success';
                        var msg = 'تم حذف الشركه بنجاح';
                        var title = 'Success';
                    } else {
                        var shortCutFunction = 'error';
                        var msg = 'جرب مره اخرى .. حدث خطا';
                        var title = 'Error';
                    }
                    toastr.options = {
                        closeButton: $('#closeButton').prop('checked'),
                        debug: $('#debugInfo').prop('checked'),
                        positionClass: $('#positionGroup input:checked').val() || 'toast-top-right',
                        onclick: null
                    };
                    var $toast = toastr[shortCutFunction](msg, title);
                });
            }

            $(this).parent().parent().parent().remove();
        });
    };
    var handleDatePickers = function () {
        if (jQuery().datepicker) {
            $('.date-picker').datepicker({rtl: Metronic.isRTL(), orientation: "left", autoclose: true});
        }
    };
    var handleDateTimePickers = function () {
        if (jQuery().datetimepicker) {
            $('.date-time-picker').datetimepicker({rtl: Metronic.isRTL(), orientation: "left", autoclose: true});
        }
    };

    var sendmsgit = function () {
        $('.senditmsg').click(function () {
            var theemail = $(this).attr('data-bind-email');
            if (theemail != "") {
                $('input[name=sendtoit]').val(theemail);
            }
        });
        $('.send_action').click(function () {
            $emailto = $('input[name=sendtoit]').val();
            $subject = $('input[name=subjectit]').val();
            $msgit = $('textarea[name=msgit]').val();
            if ($emailto != "" && $subject != "" && $msgit != "") {
                $.post(hosturl + '/_global_service/sendmsg', {emailto: $emailto, subject: $subject, msgit: $msgit}, function (data) {
                    if (Number(data) == 1) {
                        var shortCutFunction = 'success';
                        var msg = 'تم ارسال الرساله بنجاح.';
                        var title = 'بنجاح';
                    } else {
                        var shortCutFunction = 'error';
                        var msg = 'حاول مره اخرى ... حدث خطأ.';
                        var title = 'خطأ';
                    }
                    toastr.options = {
                        closeButton: $('#closeButton').prop('checked'),
                        debug: $('#debugInfo').prop('checked'),
                        positionClass: $('#positionGroup input:checked').val() || 'toast-top-right',
                        onclick: null
                    };
                    $("#sendmsg").modal('hide');
                    $('input[name=sendtoit]').val('');
                    $('input[name=subjectit]').val('');
                    $('input[name=msgit]').val('');
                    var $toast = toastr[shortCutFunction](msg, title);
                });
            } else {
                var shortCutFunction = 'warning';
                var msg = 'ادخل كل البيانات المطلوبه.';
                var title = 'تحذير';
                var $toast = toastr[shortCutFunction](msg, title);
            }
        });
        $('.send_action_news_letter').click(function () {
            $subject = $('input[name=subjectit]').val();
            $msgit = $('textarea[name=msgit]').val();
            var sendToArr = [];
            $('.checkItem:checked').each(function () {
                sendToArr.push($(this).val());
            });
            var sendToArrLength = Number(sendToArr.length);
            if ($subject != "" && $msgit != "" && sendToArrLength > 0) {
                $.post(hosturl + '/_global_service/sendmsgnewsletter', {sendToArr: sendToArr, subject: $subject, msgit: $msgit}, function (data) {
                    $('.checkItem').parents('tr').css('background-color', 'white');
                    if (Number(data) == 1) {
                        var shortCutFunction = 'success';
                        var msg = 'تم الارسال بنجاح.';
                        var title = 'بنجاح';
                    } else {
                        var shortCutFunction = 'error';
                        var msg = 'حدث خطأ ... بعض الرسائل لم ترسل';
                        var title = 'خطأ';
                        JSON.parse(data).forEach(function (item) {
                            $('[value="' + item + '"]').parents('tr').first().css('background-color', '#F3565D');
                        });
                    }
                    toastr.options = {
                        closeButton: $('#closeButton').prop('checked'),
                        debug: $('#debugInfo').prop('checked'),
                        positionClass: $('#positionGroup input:checked').val() || 'toast-top-right',
                        onclick: null
                    };
                    $("#sendmsg").modal('hide');
                    $('input[name=subjectit]').val('');
                    $('input[name=msgit]').val('');
                    var $toast = toastr[shortCutFunction](msg, title);
                });
            } else {
                var shortCutFunction = 'warning';
                var msg = 'ادخل كل البيانات المطلوبه.';
                var title = 'تحذير';
                var $toast = toastr[shortCutFunction](msg, title);
            }
        });
    };
    var chat = function () {
        $('.getchat_firm').live('click', function () {
            //get all firm chhat
            $firmid = $(this).attr('data-id');
            var thisis = $(this);
            $('#firmId').val($firmid);
            $.post(hosturl + '/chat/getfirm', {firmid: $firmid}, function (rsltin) {
                $.post(hosturl + '/chat/getsubmit', {firmid: $firmid}, function (rslt) {
                    $('#chatsfirm').html(rsltin);
                    $('#submit_container').html(rslt);
                    thisis.removeClass('unreadc');
                    $('.getchat_firm').removeClass('activeit');
                    thisis.addClass('activeit');
                });
            });
        });
        var handleClick = function () {
            var input = $('#msg');
            var text = input.val();
            var cont = $('#chats');
            var list = $('#chatsfirm', cont);
            var firmid = $('#firmId').val();
            if (text.length == 0) {
                return;
            }

            var time = new Date();
            var time_str = (time.getHours() + ':' + time.getMinutes());
            var tpl = '';
            tpl += '<li class="out">';
            tpl += '<img class="avatar" alt="" src="' + hosturl + '/views/aw_ar/_assets/admin/layout/img/avatar3_small.png"/>';
            tpl += '<div class="message">';
            tpl += '<span class="arrow"></span>';
            tpl += '<a href="#" class="name">الاداره</a>&nbsp;';
            tpl += '<span class="datetime pull-left">at ' + time_str + '</span>';
            tpl += '<span class="body">';
            tpl += text;
            tpl += '</span>';
            tpl += '</div>';
            tpl += '</li>';
            var msg = list.prepend(tpl);
            input.val("");
            //add ajax
            $.post(hosturl + '/chat/addfirm', {msg: text, firmid: firmid});
            var getLastPostPos = function () {
                var height = 0;
                cont.find("li.out, li.in").each(function () {
                    height = height + $(this).outerHeight();
                });
                return height;
            };
            cont.find('#scollerchat').slimScroll({
                //scrollTo: getLastPostPos()
            });
        };
        $('#gofirmchat').live('click', function () {
            handleClick();
        });
        $('.message .name').live('click', function (e) {
            e.preventDefault();
            var input = $('#msg');
            var name = $(this).text();
            input.val('@' + name + ':');
            Metronic.scrollTo(input);
        });
        $('#msg').live('keypress', function (e) {
            if (e.which == 13) {
                handleClick();
                return false;
            }
        });
        /************************ client ******************************/
        $('.getchat_client').live('click', function () {
            //get all client chhat
            $clientid = $(this).attr('data-id');
            var thisis = $(this);
            $('#clientId').val($clientid);
            $.post(hosturl + '/chat/getclient', {clientid: $clientid}, function (rsltin) {
                $.post(hosturl + '/chat/getsubmitclient', {clientid: $clientid}, function (rslt) {
                    $('#chatsclient').html(rsltin);
                    $('#submit_container_client').html(rslt);
                    thisis.removeClass('unreadc');
                    $('.getchat_client').removeClass('activeit');
                    thisis.addClass('activeit');
                });
            });
        });
        var handleClickclient = function () {
            var input = $('#msgclient');
            var text = input.val();
            var cont = $('#chats');
            var list = $('#chatsclient');
            var clientid = $('#clientId').val();
            if (text.length == 0) {
                return;
            }

            var time = new Date();
            var time_str = (time.getHours() + ':' + time.getMinutes());
            var tpl = '';
            tpl += '<li class="out">';
            tpl += '<img class="avatar" alt="" src="' + hosturl + '/views/aw_ar/_assets/admin/layout/img/avatar3_small.png"/>';
            tpl += '<div class="message">';
            tpl += '<span class="arrow"></span>';
            tpl += '<a href="#" class="name">الاداره</a>&nbsp;';
            tpl += '<span class="datetime pull-left">at ' + time_str + '</span>';
            tpl += '<span class="body">';
            tpl += text;
            tpl += '</span>';
            tpl += '</div>';
            tpl += '</li>';
            var msg = list.prepend(tpl);
            input.val("");
            //add ajax
            $.post(hosturl + '/chat/addclient', {msg: text, clientid: clientid});
            var getLastPostPos = function () {
                var height = 0;
                cont.find("li.out, li.in").each(function () {
                    height = height + $(this).outerHeight();
                });
                return height;
            };
            cont.find('#scollerchat').slimScroll({
                //scrollTo: getLastPostPos()
            });
        };
        $('#goclientchat').live('click', function () {
            handleClickclient();
        });
        $('#msgclient').live('keypress', function (e) {
            if (e.which == 13) {
                handleClickclient();
                return false;
            }
        });
    };
    var typeshow = function () {
        $('input[type=radio][name=typeshow]').change(function () {
            $whatval = $(this).val();
            if ($whatval == 1) {
                $('#contentshow').hide();
                $('#linkshow').show();
            } else {
                $('#contentshow').show();
                $('#linkshow').hide();
            }
        });
    };
    var checkvali = function () {
        $("#username").blur(function () {
            $("#loforav").show();
            $.ajax({
                url: hosturl + "/_global_service/checkusername",
                data: {username: $("#username").val(), valis: $("#username").attr('data-old')},
                type: "POST",
                success: function (data) {
                    $("#user-availability-status").html(data);
                    $("#loforav").hide();
                },
                error: function () {
                }
            });
        });
        $("#email").blur(function () {
            $("#loforav").show();
            $.ajax({
                url: hosturl + "/_global_service/checkemail",
                data: {email: $("#email").val(), valis: $("#email").attr('data-old')},
                type: "POST",
                success: function (data) {
                    $("#user-availability-email").html(data);
                    $("#loforav").hide();
                },
                error: function () {
                }
            });
        });
        $("#fusername").blur(function () {
            $("#loforav").show();
            $.ajax({
                url: hosturl + "/_global_service/checkfusername",
                data: {username: $("#fusername").val(), valis: $("#fusername").attr('data-old')},
                type: "POST",
                success: function (data) {
                    $("#user-availability-status").html(data);
                    $("#loforav").hide();
                },
                error: function () {
                }
            });
        });
        $("#femail").blur(function () {
            $("#loforav").show();
            $.ajax({
                url: hosturl + "/_global_service/checkfemail",
                data: {email: $("#femail").val(), valis: $("#femail").attr('data-old')},
                type: "POST",
                success: function (data) {
                    $("#user-availability-email").html(data);
                    $("#loforav").hide();
                },
                error: function () {
                }
            });
        });
        $("#natid").blur(function () {
            $("#loforav").show();
            $.ajax({
                url: hosturl + "/_global_service/checknat",
                data: {natid: $("#natid").val(), valis: $("#natid").attr('data-old')},
                type: "POST",
                success: function (data) {
                    $("#user-availability-nat").html(data);
                    $("#loforav").hide();
                },
                error: function () {
                }
            });
        });
    };
    /*============================================nora ==============================*/

    var handleMailsValidation = function () {

        // for more info visit the official plugin documentation:
        // http://docs.jquery.com/Plugins/Validation

        var form3 = $('#maillist_form');
        var error3 = $('.alert-danger', form3);
        var success3 = $('.alert-success', form3);
        form3.validate({
            errorElement: 'span', //default input error message container
            errorClass: 'help-block help-block-error', // default input error message class
            focusInvalid: false, // do not focus the last invalid input
            ignore: "", // validate all fields including form hidden input
            rules: {
                group: {
                    required: true
                },
                email: {
                    required: true,
                    email: true
                }

            },
            errorPlacement: function (error, element) { // render error placement for each input type
                if (element.parent(".input-group").size() > 0) {
                    error.insertAfter(element.parent(".input-group"));
                } else if (element.attr("data-error-container")) {
                    error.appendTo(element.attr("data-error-container"));
                } else if (element.parents('.radio-list').size() > 0) {
                    error.appendTo(element.parents('.radio-list').attr("data-error-container"));
                } else if (element.parents('.radio-inline').size() > 0) {
                    error.appendTo(element.parents('.radio-inline').attr("data-error-container"));
                } else if (element.parents('.checkbox-list').size() > 0) {
                    error.appendTo(element.parents('.checkbox-list').attr("data-error-container"));
                } else if (element.parents('.checkbox-inline').size() > 0) {
                    error.appendTo(element.parents('.checkbox-inline').attr("data-error-container"));
                } else {
                    error.insertAfter(element); // for other inputs, just perform default behavior
                }
            },
            invalidHandler: function (event, validator) { //display error alert on form submit
                success3.hide();
                error3.show();
                Metronic.scrollTo(error3, -200);
            },
            highlight: function (element) { // hightlight error inputs
                $(element)
                        .closest('.form-group').addClass('has-error'); // set error class to the control group
            },
            unhighlight: function (element) { // revert the change done by hightlight
                $(element)
                        .closest('.form-group').removeClass('has-error'); // set error class to the control group

            },
            success: function (label) {
                label
                        .closest('.form-group').removeClass('has-error'); // set success class to the control group
            },
            submitHandler: function (form) {
                success3.show();
                error3.hide();
                var email = $("#maillist_form #email").val();
                var checkedit = $("#maillist_form #email").attr('data-edit');
                var checkmail = false;
                //check email after vaildation
                $.post(hosturl + '/mails/checkemail', {email: email, checkedit: checkedit}, function (data) {
                    if (data.replace(/\s/g, "") == 'yes') {
                        $("#showerroremail").css({'display': 'block'});
                        checkmail = false;
                    } else {
                        $("#showerroremail").css({'display': 'none'});
                        checkmail = true;
                        if (checkmail == true) {
                            form.submit(); // submit the form
                        }
                    }
                });
            }

        });
    }


    var mailer = function () {

        var hosturl = $('#hosturl').val();
        var table = $('#mailer_tb');
        var oTable = table.dataTable({
            "language": {
                "aria": {
                    "sortAscending": ": Used to order Ascending",
                    "sortDescending": ": Used to order Descending"
                },
                "emptyTable": "لا يوجد بيانات",
                "info": "عرض _START_ من _END_ الى _TOTAL_ عناصر",
                // "infoEmpty": "لا يوجد بيانات",
                "infoFiltered": "(تنقيه _MAX_ من الاجمالى)",
                "lengthMenu": " _MENU_ عنصر",
                "search": "البحث:",
                // "zeroRecords": "لا يوجد بيانات تشابه البحث"
            }, "aoColumnDefs": [
                {"sClass": "hide_me", "aTargets": [0]},
                {
                    'targets': [0],
                    'searchable': false,
                    'orderable': false,
                    'className': 'dt-body',
                    'render': function (data, type, full, meta) {
                        return '<input type="checkbox" name="ids[]" value=' + data + ' />';
                    }
                }
            ],
            "order": [
                [0, "desc"]
            ],
            "lengthMenu": [
                [10, 50, 100, -1],
                [10, 50, 100, "All"] // change per page values here
            ],
            // set the initial value
            "pageLength": 10,
            "fnPreDrawCallback": function (oSettings) {

                $('input[type="checkbox"]').uniform();
            }

            //dom: "<'row' <'col-md-12'B>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>"
        });
// Handle click on "Select all" control
        $('#select-all').on('click', function () {

            var rows = table.api().rows().nodes();
            // Check/uncheck checkboxes for all rows in the table
            $('input[type="checkbox"]', rows).attr('checked', this.checked);
            $('input[type="checkbox"]', rows).parent('span').addClass('checked');
            $('input[type="checkbox"]').uniform();
        });
        // Handle click on checkbox to set state of "Select all" control


        // Handle form submission event
        $('#frm-example').on('submit', function (e) {
            var form = this;
            // Iterate over all checkboxes in the table
            table.$('input[type="checkbox"]').each(function () {

// If checkbox doesn't exist in DOM
                if (!$.contains(document, this)) {
// If checkbox is checked
                    if (this.checked) {
// Create a hidden element
                        $(form).append(
                                $('<input>')
                                .attr('type', 'text')
                                .attr('name', this.name)
                                .val(this.value)
                                );
                    }
                }

            });
        });
    }

    var mailer_msg = function () {

        var hosturl = $('#hosturl').val();
        var table = $('#custom_tbl_dt_email');
        var oTable = table.dataTable({
            "language": {
                "aria": {
                    "sortAscending": ": Used to order Ascending",
                    "sortDescending": ": Used to order Descending"
                },
                "emptyTable": "لا يوجد بيانات",
                "info": "عرض _START_ من _END_ الى _TOTAL_ عناصر",
                // "infoEmpty": "لا يوجد بيانات",
                "infoFiltered": "(تنقيه _MAX_ من الاجمالى)",
                "lengthMenu": " _MENU_ عنصر",
                "search": "البحث:",
                // "zeroRecords": "لا يوجد بيانات تشابه البحث"
            }, "aoColumnDefs": [
                {"sClass": "hide_me", "aTargets": [0]},
                {
                    'orderable': false,
                    "searchable": false,
                    "targets": [0]
                }
            ],
            "order": [
                [0, "desc"]
            ],
            "lengthMenu": [
                [10, 50, 100, -1],
                [10, 50, 100, "All"] // change per page values here
            ],
            // set the initial value
            "pageLength": 10,
            //dom: "<'row' <'col-md-12'B>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>"
        });
    }
    var fatma = function () {
        $('[name="pay_method"]').change();
        $('[name="pay_method"]').live('change', function () {
            var pay_method = $(this).val();
            if (pay_method == "0") {
                $('#activation_type1').parents('.radio-inline').first().show();
            } else {
                $('#activation_type0').attr('checked', 'checked');
                $('#activation_type0').uniform();
                $('#activation_type1').removeAttr('checked');
                $('#activation_type1').uniform();
                $('#activation_type1').parents('.radio-inline').first().hide();
            }
        });
        //////////
        $('#country').live('change', function () {
            $('#governorate').select2("val", "").change();
        });
        $(".select2governorate").select2({
            placeholder: "لا يوجد",
            minimumInputLength: 0,
            ajax: {
                url: hosturl + '/country/governorate',
                dataType: 'json',
                delay: 250,
                type: "POST",
                data: function (params) {
                    return {
                        q: params.term, // search term
                        page: params.page,
                        country: $('#country').val(),
                    };
                },
                results: function (data) {
                    return {
                        results: data
                    };
                },
                cache: true,
            },
        });
        ///////////
        $('.statistics_change').live('change', function () {
            var id = $(this).attr('id');
            var val = $(this).val();
            if ($(this).attr("type") == "checkbox") {
                val = 0;
                if ($(this).is(":checked")) {
                    val = 1;
                }
            }
            $.post(hosturl + "/index/statistics", {id: id, val: val}, function (data) {
                if (data == 1) {
                    var shortCutFunction = 'success';
                    var msg = 'تم الحفظ بنجاح ';
                    var title = 'تم بنجاح';
                } else {
                    var shortCutFunction = 'error';
                    var msg = 'جرب مره اخرى ....  لقد حدث خطا';
                    var title = 'حذث خطا';
                }

                toastr.options = {
                    closeButton: $('#closeButton').prop('checked'),
                    debug: $('#debugInfo').prop('checked'),
                    positionClass: $('#positionGroup input:checked').val() || 'toast-top-right',
                    onclick: null
                };
                var $toast = toastr[shortCutFunction](msg, title);
            });
        });
    };

//gallery//
    var gallery = function () {
        /**** new prod ****/
//upload multi
        var file_dropzones_id;
        Dropzone.options.myDropzones = {
            dictDefaultMessage: "اضغط او اسحب هنــا الصور و الفيديو",
            maxFilesize: 50, // MB
            acceptedFiles: "image/*,.flv,.mpeg,.mpg,.mpe,.wmv,.mov,.mp4,.m4v", //using this to stop avi video as it is not supported in most browsers by default
            init: function () {
                this.on("success", function (e, responseText) {
                    file_dropzones_id = responseText;
//                    var n = Dropzone.createElement("<input type='text' placeholder='الاسم' class='form-control filename' data-id='" + file_dropzones_id + "'/>"),
//                        n2 = Dropzone.createElement("<input type='text' placeholder='السعر' class='form-control fileprice' data-id='" + file_dropzones_id + "'/>"),
                    var n1 = Dropzone.createElement("<a href='javascript:;' data-id='" + file_dropzones_id + "' class='btn red btn-sm btn-block '>حذف</a>"),
                            t = this;
                    n1.addEventListener("click", function (n1) {
                        $thisid = $(this).attr('data-id');
                        ;
                        $.post(hosturl + "/_global_service/delprod", {itemid: $thisid}, function () {
                            n1.preventDefault(), n1.stopPropagation(), t.removeFile(e);
                        });
                    }), e.previewElement.appendChild(n1)

                }), this.on("addedfile", function (e) {

                }), this.on(
                        "sending", function (file, xhr, formData) {
//                        formData.append('subcatid', $('#id').val());
                            formData.append('cat_id', $('#cat_id').val());
                        });
            }
        };
        $('.delprod_in').click(function () {

            $thisid = $(this).attr('data-id');
            var this_bt = $(this);
            $.post(hosturl + "/_global_service/delprod", {itemid: $thisid}, function () {
                this_bt.parent().remove();
            });
        });
//        $('.linkvideo').on("change", function () {
//            var thisvalue = $(this).val();
//            $('iframe').attr("src", thisvalue);
//        });
//        //load prop


        $('.addnewVideo').click(function () {
            var Videoitr = Number($('#Videoitr').val()) + 1;
            $.post(hosturl + "/videocategories/insertNewRow", {Videoitr: Videoitr}, function (data) {

                $("#videoDiv").append(data);
            })
            $('#Videoitr').val(Videoitr);
        })

        //remove the selected
        $('.delVideo').live('click', function () {

            $(this).parent().remove();
        })
// edit the new row of modal
//        $(".updateData").live('change', function ()
//        {
//            var value = $(this).val();
//            var colName = $(this).attr("data-colName");
//            var rowId = $(this).attr("data-id");
//            var cat_id = $("#cat_id").val();
//            $.post(hosturl + "/videocategories/insertNewVideo", {colName: colName, value: value, rowId: rowId, cat_id: cat_id}, function (data) {
//                alert(rowId)
//                $(this).attr("data-id", data);
//            });
//        });
    };
    return {
        //main function to initiate the module
        init: function () {
            $('form').validate();
            hideitem();
            firms();
            packages();
            handleDatePickers();
            handleDateTimePickers();
            sendmsgit();
            chat();
            typeshow();
            checkvali();
            handleMailsValidation();
            mailer();
            mailer_msg();
            gallery();
            fatma();
        }

    };
}();
var TableDatatablesButtons = function () {

    var e = function () {
        var e = $("#custom_tbl_dt");
        var lstone, belastone, thrdone;
        $i = 0;
        $('#custom_tbl_dt thead th').each(function () {
            $vl = $(this).html().length;
            var iColumns = $('#custom_tbl_dt thead th').length;
            if ($vl == 0 && $i == 2) {
                //do something
                thrdone = iColumns - 3;
                $i = 3;
            }

            if ($vl == 0 && $i == 1) {
                //do something
                belastone = iColumns - 2;
                $i = 2;
            }

            if ($vl == 0 && $i == 0) {
                //do something
                lstone = iColumns - 1;
                $i = 1;
            }



        });
        e.dataTable({
            "bStateSave": true,
            "language": {
                "aria": {
                    "sortAscending": ": Used to order Ascending",
                    "sortDescending": ": Used to order Descending"
                },
                "emptyTable": "لا يوجد بيانات",
                "info": "عرض _START_ من _END_ الى _TOTAL_ عناصر",
                "infoEmpty": "لا يوجد بيانات",
                "infoFiltered": "(تنقيه _MAX_ من الاجمالى)",
                "lengthMenu": " _MENU_ عنصر",
                "search": "البحث:",
                "zeroRecords": "لا يوجد بيانات تشابه البحث"
            },
            buttons: [{
                    extend: "print",
                    className: "btn dark btn-outline",
                    text: "طباعه",
                    exportOptions: {
                        columns: '.show-print'
                    }

                }, {
                    extend: "copy",
                    className: "btn red btn-outline",
                    text: "نسخ",
                    exportOptions: {
                        columns: '.show-print'
                    }
                }, {
                    extend: "excel",
                    className: "btn yellow btn-outline ",
                    text: "اكسل",
                    exportOptions: {
                        columns: '.show-print'
                    }
                }, {
                    extend: "colvis",
                    className: "btn dark btn-outline",
                    text: "المكونات"
                }],
            responsive: !0,
            "columnDefs": [
                {// set default column settings
                    "orderable": false,
                    "searchable": false,
                    "targets": [lstone],
                    "className": 'hide-print'
                },
                {// set default column settings
                    "orderable": false,
                    "searchable": false,
                    "targets": [belastone],
                    "className": 'hide-print'
                },
                {// set default column settings
                    "orderable": false,
                    "searchable": false,
                    "targets": [thrdone],
                    "className": 'hide-print'
                },
                {targets: '_all', "className": 'show-print'}],
            order: [
                [0, "asc"]
            ],
            lengthMenu: [
                [5, 10, 15, 20, -1],
                [5, 10, 15, 20, "All"]
            ],
            pageLength: 10,
            dom: "<'row' <'col-md-12'B>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>"
        });
    };
    return {
        init: function () {
            jQuery().dataTable && (e())
        }
    };
}();
jQuery(document).ready(function () {
    TableDatatablesButtons.init();
});
var TableDatatablesButtonsx = function () {

    var ee = function () {
        var ee = $("#custom_tbl_dt_rep,#custom_tbl_dt_rep_tw");
        ee.dataTable({
            "bStateSave": true,
            "paging": true,
            "info": false,
            "bFilter": false,
            "language": {
                "aria": {
                    "sortAscending": ": Used to order Ascending",
                    "sortDescending": ": Used to order Descending"
                },
                "emptyTable": "لا يوجد بيانات",
                "info": "عرض _START_ من _END_ الى _TOTAL_ عناصر",
                "infoEmpty": "لا يوجد بيانات",
                "infoFiltered": "(تنقيه _MAX_ من الاجمالى)",
                "lengthMenu": " _MENU_ عنصر",
                "search": "البحث:",
                "zeroRecords": "لا يوجد بيانات تشابه البحث"
            },
            buttons: [{
                    extend: "print",
                    className: "btn dark btn-outline",
                    text: "طباعه"

                }, {
                    extend: "copy",
                    className: "btn red btn-outline",
                    text: "نسخ"
                }, {
                    extend: "excel",
                    className: "btn yellow btn-outline ",
                    text: "اكسل"
                }],
            responsive: !0,
            order: [
                [0, "asc"]
            ],
            lengthMenu: [
                [5, 10, 15, 20, -1],
                [5, 10, 15, 20, "All"]
            ],
            pageLength: 20,
            dom: "<'row' <'col-md-12'B>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>"
        });
    };
    return {
        init: function () {
            jQuery().dataTable && (ee())
        }
    };
}();
jQuery(document).ready(function () {
    TableDatatablesButtonsx.init();
});