$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});
var CommonDom_DataTables = '<"datatable_custom_proccessing" r><"datatable-header"fl><"datatable-scroll"t ><"datatable-footer"ip>';
var LangJson_DataTables = {
    "decimal": "",
    "emptyTable": "هیچ داده ای در جدول وجود ندارد",
    "info": "نمایش _START_ تا _END_ از _TOTAL_ رکورد",
    "infoEmpty": "نمایش 0 تا 0 از 0 رکورد",
    "infoFiltered": "(فیلتر شده از _MAX_ رکورد)",
    "infoPostFix": "",
    "thousands": ",",
    "lengthMenu": "نمایش _MENU_ رکورد",
    "loadingRecords": "در حال بارگزاری...",
    "processing": "در حال پردازش...",
    "search": "جستجو: ",
    "zeroRecords": "رکوردی با این مشخصات پیدا نشد",
    "paginate": {
        "first": "ابتدا",
        "last": "انتها",
        "next": "بعدی",
        "previous": "قبلی"
    },
    "aria": {
        "sortAscending": ": فعال سازی نمایش به صورت صعودی",
        "sortDescending": ": فعال سازی نمایش به صورت نزولی"
    }
};

$.extend($.fn.dataTable.defaults, {
    autoWidth: false,
    dom: CommonDom_DataTables,
    language: LangJson_DataTables,
    processing: true,
    serverSide: true,
    drawCallback: function () {
        $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').addClass('dropup');
    },
    preDrawCallback: function () {
        $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').removeClass('dropup');
    }
});

function dataTablesGrid(selector, var_grid_name, url, columns, more_data, initComplete, scrollX, scrollY, scrollCollapse, orderBy, orderByDesc, row_select,fixedColumns,start_item) {
    scrollX = scrollX || false;
    scrollY = scrollY || false;
    scrollCollapse = scrollCollapse || false;
    orderBy = orderBy || 0;
    orderByDesc = orderByDesc || "desc";
    more_data = more_data || {};
    row_select = row_select || false;
    start_item = start_item || 0 ;
    fixedColumns = fixedColumns || false ;
    var columnDefs = [];
    window[var_grid_name + '_rows_selected'] = [];
    if (row_select) {
        checkbox_column = {
            title: '<input name="select_all" value="1" type="checkbox"/>',
            searchable: false,
            orderable: false,
            width: '1%',
            className: 'dt-body-center',
            render: function (data, type, full, meta) {
                return '<input type="checkbox">';
            }
        };
        columns.unshift(checkbox_column);
    }

    var dataTableOptionObj =
        {
            initComplete: function () {
                if (initComplete == true) {
                    this.api().columns().every(function () {
                        var column = this;
                        var select = $('<select class="filter-select" data-placeholder="Filter"><option value=""></option></select>')
                            .appendTo($(column.footer()).not(':last-child').empty())
                            .on('change', function () {
                                var val = $.fn.dataTable.util.escapeRegex(
                                    $(this).val()
                                );
                                column.search(val ? '^' + val + '$' : '', true, false).draw();
                            });
                        column.data().unique().sort().each(function (d, j) {
                            select.append('<option value="' + d + '">' + d + '</option>')
                        });
                    });
                }
            },
            displayStart:start_item,
            fixedColumns: fixedColumns,
            ajax: {
                url: url,
                type: 'POST',
                data: more_data
            },
            columns: columns,
            scrollX: scrollX,
            scrollY: scrollY,
            scrollCollapse: scrollCollapse,
            order: [[ orderBy, orderByDesc ]],
            rowCallback: function (row, data, dataIndex) {
                if (row_select) {
                    var rowId = data;
                    if (func_search_in_obj('id', data['id'], window[var_grid_name + '_rows_selected'])) {
                        $(row).find('input[type="checkbox"]').prop('checked', true);
                        $(row).addClass('selected');
                    }
                }
            },
            destroy: true,
        };

    if(!scrollY)
    {
        delete  dataTableOptionObj.scrollY;
        delete  dataTableOptionObj.scrollCollapse;
    }

    window[var_grid_name] = $(selector).DataTable(dataTableOptionObj);

    if (row_select) {
        $(selector).on('click', 'input[type="checkbox"]', function (e) {
            var $row = $(this).closest('tr');
            // Get row data
            var data = window[var_grid_name].row($row).data();
            // Get row ID
            //var rowId = data['id'];
            var rowId = data;
            // Determine whether row ID is in the list of selected row IDs
            var index = $.inArray(rowId, window[var_grid_name + '_rows_selected']);
            // If checkbox is checked and row ID is not in list of selected row IDs
            if (this.checked && index === -1) {
                window[var_grid_name + '_rows_selected'].push(rowId);
                // Otherwise, if checkbox is not checked and row ID is in list of selected row IDs
            } else if (!this.checked && index !== -1) {
                window[var_grid_name + '_rows_selected'].splice(index, 1);
            }
            if (this.checked) {
                $row.addClass('selected');
            } else {
                $row.removeClass('selected');
            }
            // Update state of "Select all" control
            updateDataTableSelectAllCtrl(window[var_grid_name]);
            // Prevent click event from propagating to parent
            e.stopPropagation();
        });

        // Handle click on table cells with checkboxes
        $(selector).on('click', 'tbody td, thead th:first-child', function (e) {
            $(this).parent().find('input[type="checkbox"]').trigger('click');
        });

        // Handle click on "Select all" control
        $('thead input[name="select_all"]', window[var_grid_name].table().container()).on('click', function (e) {
            if (this.checked) {
                $(selector + ' tbody input[type="checkbox"]:not(:checked)').trigger('click');
            } else {
                $(selector + ' tbody input[type="checkbox"]:checked').trigger('click');
            }

            // Prevent click event from propagating to parent
            e.stopPropagation();
        });

        // Handle table draw event
        window[var_grid_name].on('draw', function () {
            // Update state of "Select all" control
            updateDataTableSelectAllCtrl(window[var_grid_name]);
        });
    }
}

function updateDataTableSelectAllCtrl(table) {
    var $table = table.table().node();
    var $chkbox_all = $('tbody input[type="checkbox"]', $table);
    var $chkbox_checked = $('tbody input[type="checkbox"]:checked', $table);
    var chkbox_select_all = $('thead input[name="select_all"]', $table).get(0);

    // If none of the checkboxes are checked
    if ($chkbox_checked.length === 0) {
        chkbox_select_all.checked = false;
        if ('indeterminate' in chkbox_select_all) {
            chkbox_select_all.indeterminate = false;
        }
        // If all of the checkboxes are checked
    } else if ($chkbox_checked.length === $chkbox_all.length) {
        chkbox_select_all.checked = true;
        if ('indeterminate' in chkbox_select_all) {
            chkbox_select_all.indeterminate = false;
        }
        // If some of the checkboxes are checked
    } else {
        chkbox_select_all.checked = true;
        if ('indeterminate' in chkbox_select_all) {
            chkbox_select_all.indeterminate = true;
        }
    }
}
/*function confirm_alert(title,text_message,type,function_name,confirmButtonText,cancelButtonText) {
 title = title || "بعد از حذف دیگر به این مورد دسترسی نخواهید داشت!";
 text_message = text_message || "بعد از حذف دیگر به این مورد دسترسی نخواهید داشت!";
 type = type || "warning";
 confirmButtonText = confirmButtonText || "بله، حذف شود!";
 cancelButtonText = cancelButtonText || "خیر، منصرف شدم!";
 swal({
 title: title,
 text: text_message,
 type: type,
 showCancelButton: true,
 confirmButtonColor: "#EF5350",
 confirmButtonText: confirmButtonText,
 cancelButtonText: cancelButtonText,
 closeOnConfirm: false,
 closeOnCancel: false
 },
 function (isConfirm) {
 if (isConfirm) {
 deleteWorkerUser(worker_id);
 swal({
 title: "Deleted!",
 text: "Your imaginary file has been deleted.",
 confirmButtonColor: "#66BB6A",
 type: "success"
 });
 }
 else {
 swal({
 title: "Cancelled",
 text: "Your imaginary file is safe :)",
 confirmButtonColor: "#2196F3",
 type: "error"
 });
 }
 });
 }*/
var modalTemplate = '<div class="modal-dialog modal-lg" role="document">\n' +
    '  <div class="modal-content">\n' +
    '    <div class="modal-header">\n' +
    '      <div class="kv-zoom-actions btn-group">{toggleheader}{fullscreen}{borderless}{close}</div>\n' +
    '      <h6 class="modal-title">{heading} <small><span class="kv-zoom-title"></span></small></h6>\n' +
    '    </div>\n' +
    '    <div class="modal-body">\n' +
    '      <div class="floating-buttons btn-group"></div>\n' +
    '      <div class="kv-zoom-body file-zoom-content"></div>\n' + '{prev} {next}\n' +
    '    </div>\n' +
    '  </div>\n' +
    '</div>\n';

// Buttons inside zoom modal
var previewZoomButtonClasses = {
    toggleheader: 'btn btn-default btn-icon btn-xs btn-header-toggle',
    fullscreen: 'btn btn-default btn-icon btn-xs',
    borderless: 'btn btn-default btn-icon btn-xs',
    close: 'btn btn-default btn-icon btn-xs'
};

// Icons inside zoom modal classes
var previewZoomButtonIcons = {
    prev: '<i class="icon-arrow-right32"></i>',
    next: '<i class="icon-arrow-left32"></i>',
    toggleheader: '<i class="icon-menu-open"></i>',
    fullscreen: '<i class="icon-screen-full"></i>',
    borderless: '<i class="icon-alignment-unalign"></i>',
    close: '<i class="icon-cross3"></i>'
};

// File actions
var fileActionSettings = {
    zoomClass: 'btn btn-link btn-xs btn-icon',
    zoomIcon: '<i class="icon-zoomin3"></i>',
    dragClass: 'btn btn-link btn-xs btn-icon',
    dragIcon: '<i class="icon-three-bars"></i>',
    removeClass: 'btn btn-link btn-icon btn-xs',
    removeIcon: '<i class="icon-trash"></i>',
    indicatorNew: '<i class="icon-file-plus text-slate"></i>',
    indicatorSuccess: '<i class="icon-checkmark3 file-icon-large text-success"></i>',
    indicatorError: '<i class="icon-cross2 text-danger"></i>',
    indicatorLoading: '<i class="icon-spinner2 spinner text-muted"></i>'
};
function init_file_style(selector, object_options, uploadUrl) {
    object_options = object_options || {
            browseLabel: 'Browse',
            browseIcon: '<i class="icon-file-plus"></i>',
            uploadIcon: '<i class="icon-file-upload2"></i>',
            removeIcon: '<i class="icon-cross3"></i>',
            layoutTemplates: {
                icon: '<i class="icon-file-check"></i>',
                modal: modalTemplate
            },
            initialCaption: "No file selected",
            previewZoomButtonClasses: previewZoomButtonClasses,
            previewZoomButtonIcons: previewZoomButtonIcons,
            fileActionSettings: fileActionSettings,
            showUpload: false
    };
    uploadUrl = uploadUrl || false;
    if (uploadUrl)
    {
        object_options.uploadUrl = uploadUrl;
        object_options.showUpload = true;
    }
    selector = selector || '.file-input';
    $(selector).fileinput(object_options);
}
function init_doAfterStopTyping(selector, function_name, function_params, waiting_time, get_full_element, exit_value, exit_operator) {
    exit_value = exit_value || false;
    exit_operator = exit_operator || '=';
    selector = selector || 'document';
    function_params = function_params || false;
    get_full_element = get_full_element || false;
    var waiting_time = waiting_time || 3000;
    //var $this = $(selector);
    //setup before functions
    var typingTimer; //timer identifier
    //on keyup, start the countdown
    $(document).on('keyup', selector, do_after_stop_typing);
    $(document).on('focusout', selector, do_after_stop_typing_on_focusout);

    function do_after_stop_typing() {
        var $this = $(this);
        if (exit_value) {
            switch (exit_operator) {
                case '=':
                    if (exit_value === $this.val())
                        do_function(function_name, function_params, get_full_element, $this, $this.val());
                    break;
                case '>':
                    if ($this.val() > exit_value)
                        do_function(function_name, function_params, get_full_element, $this, $this.val());
                    break;
                case '<':
                    if ($this.val() < exit_value)
                        do_function(function_name, function_params, get_full_element, $this, $this.val());
                    break;
                case '<=':
                    if ($this.val() <= exit_value)
                        do_function(function_name, function_params, get_full_element, $this, $this.val());
                    break;
                case '>=':
                    if ($this.val() >= exit_value)
                        do_function(function_name, function_params, get_full_element, $this, $this.val());
                    break;
                case '!=':
                    if (exit_value !== $this.val())
                        do_function(function_name, function_params, get_full_element, $this, $this.val());
                    break;
            }
        }
        clearTimeout(typingTimer);
        typingTimer = setTimeout(function () {
            do_function(function_name, function_params, get_full_element, $this, $this.val())
        }, waiting_time);
    }

    function do_after_stop_typing_on_focusout() {
        var $this = $(this);
        clearTimeout(typingTimer);
        do_function(function_name, function_params, get_full_element, $this, $this.val());
    }

    function do_function(function_name, function_params, get_full_element, v_this, this_value) {
        if (function_params) {
            if (get_full_element) {
                return function_name(v_this, function_params);
            }
            else {
                return function_name(this_value, function_params);
            }
        }
        else {
            if (get_full_element) {
                return function_name(v_this, function_params);
            }
            else {
                return function_name(this_value);
            }
        }
    }

    //on keydown, clear the countdown
    $(document).on('keydown', selector, function (objEvent) {
        /*if (objEvent.keyCode == 9) {  //tab pressed
            objEvent.preventDefault(); // stops its action
        }*/
        clearTimeout(typingTimer);
    });
}

function init_toPersianSwitchKey(selector) {
    $(document).on('keyup', selector, function () {
        var $this = $(this);
        var fa = _toPersianSwitchKey($this.val());
        $this.val(fa);
    });
}
function init_toEnglishSwitchKey(selector) {
    $(document).on('keyup', selector, function () {
        var $this = $(this);
        var en = _toEnglishSwitchKey($this.val());
        $this.val(en);
    });
}
function _toPersianSwitchKey(value) {
    if (!value) {
        return;
    }
    var persianChar = ["ض", "ص", "ث", "ق", "ف", "غ", "ع", "ه", "خ", "ح", "ج", "چ", "ش", "س", "ی", "ب", "ل", "ا", "ت", "ن", "م", "ک", "گ", "ظ", "ط", "ز", "ر", "ذ", "د", "ئ", "پ", "پ", "و", "؟", "ض", "ص", "ث", "ق", "ف", "غ", "ع", "ه", "خ", "ح", "ش", "س", "ی", "ب", "ل", "ا", "ت", "ن", "م", "ظ", "ط", "ژ", "ر", "ذ", "د", "ء"],
        englishChar = ["q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "[", "]", "a", "s", "d", "f", "g", "h", "j", "k", "l", ";", "'", "z", "x", "c", "v", "b", "n", "m", "~", "`", ",", "?", "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "A", "S", "D", "F", "G", "H", "J", "K", "L", "Z", "X", "C", "V", "B", "N", "M"];

    for (var i = 0, charsLen = englishChar.length; i < charsLen; i++) {
        value = value.replaceAll(englishChar[i], persianChar[i]);
    }
    return value;
}
function _toEnglishSwitchKey(value) {
    if (!value) {
        return;
    }
    var persianChar = ["ض", "ص", "ث", "ق", "ف", "غ", "ع", "ه", "خ", "ح", "ج", "چ", "ش", "س", "ی", "ب", "ل", "ا", "ت", "ن", "م", "ک", "گ", "ظ", "ط", "ز", "ر", "ذ", "د", "ئ", "پ", "پ", "و", "؟", "ض", "ص", "ث", "ق", "ف", "غ", "ع", "ه", "خ", "ح", "ش", "س", "ی", "ب", "ل", "ا", "ت", "ن", "م", "ظ", "ط", "ژ", "ر", "ذ", "د", "ء"],
        englishChar = ["q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "[", "]", "a", "s", "d", "f", "g", "h", "j", "k", "l", ";", "'", "z", "x", "c", "v", "b", "n", "m", "~", "`", ",", "?", "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "A", "S", "D", "F", "G", "H", "J", "K", "L", "Z", "X", "C", "V", "B", "N", "M"];

    for (var i = 0, charsLen = persianChar.length; i < charsLen; i++) {
        value = value.replaceAll(persianChar[i], englishChar[i]);
    }
    return value;
}

function _toEnglishSwitchDigit(value) {
    if (!value) {
        return;
    }
    var persianDigit = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'],
        englishDigit = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];

    for (var i = 0, charsLen = persianDigit.length; i < charsLen; i++) {
        value = value.replaceAll(persianDigit[i], englishDigit[i]);
    }
    return value;
}
function init_checkboxes_and_radios() {
    $(".styled, .multiselect-container, input").uniform({
        radioClass: 'choice'
    });

    $(".control-primary").uniform({
        radioClass: 'choice',
        wrapperClass: 'border-primary-600 text-primary-800'
    });
}
function button_loader_init(selector, type, old_icon_class, new_icon_class) {
    type = type || false;
    if (type) {
        $(selector).children('i').removeClass(old_icon_class);
        $(selector).children('i').addClass(new_icon_class);
        $(selector).children('i').prop("disabled", true);
        $(selector).css('cursor', 'wait');
        $(selector).children('i').addClass('spinner');
    }
    else {
        $(selector).children('i').removeClass(new_icon_class);
        $(selector).children('i').addClass(old_icon_class);
        $(selector).children('i').prop("disabled", false);
        $(selector).css('cursor', 'pointer');
        $(selector).children('i').removeClass('spinner');
    }

}
function generate_loader_html(loading_text) {
    var loader_html = '' +
        '<div class="total_loader">' +
        '   <div class="total_loader_content" style="">' +
        '       <div class="spinner_area">' +
        '           <div class="spinner_rects">' +
        '               <div class="rect1"></div>' +
        '               <div class="rect2"></div>' +
        '               <div class="rect3"></div>' +
        '               <div class="rect4"></div>' +
        '               <div class="rect5"></div>' +
        '           </div>' +
        '       </div>' +
        '       <div class="text_area">' + loading_text + '</div>' +
        '   </div>' +
        '</div>';
    return loader_html;
}
function modal_init(modal_id, modal_size, modal_header, modal_content, modal_footer) {
    //console.log(modal_id);
    $('#' + modal_id).remove();
    var public_modal = '' +
        '<div id="' + modal_id + '" class="modal fade">' +
        '   <div class="modal-dialog ' + modal_size + '">' +
        '       <div class="modal-content">' +
        '           <div class="modal-header no-padding" style="border-bottom: 1px solid #ddd; background-color: #eee;">' +
        modal_header +
        '           </div>' +
        '           <div class="modal-body no-margin no-padding">' +
        modal_content +
        '           </div>' +
        '           <div class="modal-footer">' +
        modal_footer +
        '           </div>' +
        '       </div>' +
        '   </div>' +
        '</div>';

    $('#all_modals').append(public_modal);
    $('#' + modal_id).modal('show');
}
function init_select2_ajax(selector, url, allowClear, multiple, tags, placeholder, selectable_id, format_result_func_name, format_selection_func_name, var_input_width, dropdownAutoWidth, dropdownCssClass) {
    format_result_func_name = format_result_func_name || false;
    format_selection_func_name = format_selection_func_name || false;
    var_input_width = var_input_width || "100%";
    dropdownAutoWidth = dropdownAutoWidth || false;
    allowClear = allowClear || false;
    selectable_id = selectable_id || null;
    tags = tags || false;
    multiple = multiple || false;
    placeholder = placeholder || "جستجو کنید ...";
    dropdownCssClass = dropdownCssClass || "select2_dropdown_area";
    url = url || '{{ "sample_url"}}';
    var options = {
        minimumInputLength: 3,
        allowClear: allowClear,
        multiple: multiple,
        tags: tags,
        dir: "rtl",
        width: var_input_width,
        placeholder: placeholder,
        language: "fa",
        templateResult: format_result_func_name,
        templateSelection: format_selection_func_name,
        dropdownAutoWidth: dropdownAutoWidth,
        dropdownCssClass: dropdownCssClass,
        ajax: {
            url: url,
            dataType: "json",
            type: "POST",
            quietMillis: 150,
            data: function (term) {
                return {
                    term: term,
                    selectable_id: selectable_id
                };
            },
            results: function (data) {
                return {
                    results: $.map(data, function (item) {
                        return {
                            text: item.text,
                            id: item.id,
                            item: item
                        }
                    })
                };
            }
        }
    };
    if (!format_result_func_name) {
        delete options.templateResult;
    }
    if (!format_selection_func_name) {
        delete options.templateSelection;
    }
    $(selector).select2(options);
}

function init_select2_data(selector, data, minimumInputLength, allowClear, multiple, tags, placeholder, dropdownAutoWidth, dropdownCssClass) {
    //console.log(data);

    allowClear = allowClear || false;
    minimumInputLength = minimumInputLength || false;
    dropdownAutoWidth = dropdownAutoWidth || false;
    dropdownCssClass = dropdownCssClass || false;
    tags = tags || false;
    multiple = multiple || false;
    placeholder = placeholder || "جستجو کنید ...";
    data = data || '{{ "222"}}';

    $(selector).each(function (index, selected_input) {
        var selected_item = $(selected_input).data('selected_option_value');
        selected_item = selected_item || false;
        _.find(data, function (item) {
            if (item.selected === true) {
                item.selected = false;
                return item;
            }
        });
        if (selected_item) {

            _.find(data, function (item) {
                if (item.id === selected_item) {
                    item.selected = true;
                    return item;
                }
            });
        }

        $(selected_input).select2({
            dropdownAutoWidth: dropdownAutoWidth,
            dropdownCssClass: dropdownCssClass,
            minimumInputLength: minimumInputLength,
            allowClear: allowClear,
            multiple: multiple,
            tags: tags,
            dir: "rtl",
            width: "100%",
            placeholder: placeholder,
            language: "fa",
            data: data
        });
    });
}
function validate_func_check_username(str) {
    var error = "";
    var illegalChars = /\W/; // allow letters, numbers, and underscores

    if (str == null) {
        error = "^<strong>وارد کردن نام کاربری الزامی است.</strong>";
    } else if (illegalChars.test(str)) {
        error = "^<strong>نام کاربری فقط می تواند ترکیبی از اعداد و حروف انگلیسی باشد.</strong>";
    } else if (str.length < 5) {
        error = "^<strong>نام کابری باید حداقل 5 کاراکتر باشد.</strong>";
    } else if (str.length > 20) {
        error = "^<strong>نام کابری باید حداکثر 20 کاراکتر باشد.</strong>";
    } else {
        error = null;
    }
    return error;
}

function validate_func_check_code_melli(code) {
    if (!/^\d{10}$/.test(code)
        || code == '0000000000'
        || code == '1111111111'
        || code == '2222222222'
        || code == '3333333333'
        || code == '4444444444'
        || code == '5555555555'
        || code == '6666666666'
        || code == '7777777777'
        || code == '8888888888'
        || code == '9999999999')
        return false;
    var check = parseInt(code[9]);
    var sum = 0;
    var i;
    for (i = 0; i < 9; ++i) {
        sum += parseInt(code[i]) * (10 - i);
    }
    sum %= 11;
    return (sum < 2 && check == sum) || (sum >= 2 && check + sum == 11);
}

function validate_func_check_iran_mobile_number(mobile_number) {
    if (/^09[0-9]{9}$/.test(mobile_number))
        return true;
    return false;
}

function validate_func_check_national_id(code) {
    var L = code.length;

    if (L < 11 || parseInt(code, 10) == 0) return false;

    if (parseInt(code.substr(3, 6), 10) == 0) return false;
    var c = parseInt(code.substr(10, 1), 10);
    var d = parseInt(code.substr(9, 1), 10) + 2;
    var z = new Array(29, 27, 23, 19, 17);
    var s = 0;
    for (var i = 0; i < 10; i++)
        s += (d + parseInt(code.substr(i, 1), 10)) * z[i % 5];
    s = s % 11;
    if (s == 10) s = 0;
    return (c == s);
}

validate.validators.username = function (value, options, key, attributes) {
    var res = validate_func_check_username(value);
    if (res == "") {
        return null;
    }
    else {
        if (options.message) {
            return options.message;
        }
        else {
            return res;
        }
    }
};

validate.validators.only_english = function (value, options, key, attributes) {
    if (value != null) {
        if (/[^A-Za-z]/g.test(value)) {
            return options.message;
        } else {
            return null;
        }
    }
};

validate.validators.only_persian = function (value, options, key, attributes) {
    if (value != null) {
        if (/@"^([\u0600-\u06FF]+\s?)+$"/g.test(value)) {
            return options.message;
        } else {
            return null;
        }
    }
};

validate.validators.only_numbers = function (value, options, key, attributes) {
    if (value != null) {
        if (/[^0-9]/g.test(value)) {
            return options.message;
        } else {
            return null;
        }
    }
};

validate.validators.national_id = function (value, options, key, attributes) {
    if (value != null) {
        if (validate_func_check_national_id(value)) {
            return null;
        }
        return options.message;
    }
};

validate.validators.codeMelli = function (value, options, key, attributes) {
    if (value != null) {
        if (validate_func_check_code_melli(value)) {
            return null;
        }
        return options.message;
    }
};

validate.validators.iranMobileNumber = function (value, options, key, attributes) {
    if (value != null) {
        if (validate_func_check_iran_mobile_number(value)) {
            return null;
        }
        return options.message;
    }
};

validate.validators.require_if_presence = function (value, options, key, attributes) {
    other_attribute_presence = attributes[options.other_attribute_name] == null;
    if (other_attribute_presence) {
        return null;
    }
    else {
        if (value == null) {
            return options.message;
        }
        else {
            return null;
        }
    }
};

validate.validators.require_if = function (value, options, key, attributes) {
    var make = false;
    options.other_attribute_operand || '==';
    target_field_value = attributes[options.other_attribute_name] == null ? 0 : attributes[options.other_attribute_name];
    switch (options.other_attribute_operand) {
        case '>':
            make = target_field_value > options.other_attribute_value;
            break;
        case '<':
            make = target_field_value < options.other_attribute_value;
            break;
        case '>=':
            make = target_field_value >= options.other_attribute_value;
            break;
        case '<=':
            make = target_field_value <= options.other_attribute_value;
            break;
        case '<>':
        case '!=':
            make = target_field_value != options.other_attribute_value;
            break;
        case '!==':
            make = target_field_value !== options.other_attribute_value;
            break;
        case '=':
        case '==':
        default:
            make = target_field_value == options.other_attribute_value;
            break;
    }
    if (make) {
        if (value == null) {
            return options.message;
        }
        if (options.exclusion) {
            var result = true;
            options.exclusion.forEach(function (item) {
                if (value == item) {
                    result = false;
                }
            });
            if (!result) {
                if (options.exclusion_message) {
                    return options.exclusion_message;
                }
                else {
                    return options.message;
                }
            }
            return null;
        }
        if (options.inclusion) {
            var result = true;
            options.inclusion.forEach(function (item) {
                if (value != item) {
                    result = false;
                }
            });
            if (!result) {
                if (options.inclusion_message) {
                    return options.inclusion_message;
                }
                else {
                    return options.message;
                }
            }
            return null;
        }
        return null;
    }
    return null;
};

validate.validators.datetime_jalali = function (value, options, key, attributes) {
    var en_digit_value = _toEnglishSwitchDigit(value);
    var format = options.format ? options.format : "jYYYY-jMM-jDD hh:mm:ss";
    m = moment(en_digit_value, format);
    var res = m.isValid();
    if (!res) {
        return options.message;
    }
    else {
        return null;
    }
};
//---------------------------------------------------------------------------------------------------------------------//
//---------------------------------------------------------------------------------------------------------------------//
//---------------------------------------------------------------------------------------------------------------------//
// Before using it we must add the parse and format functions
// Here is a sample implementation using moment.js
validate.extend(validate.validators.datetime, {
    // The value is guaranteed not to be null or undefined but otherwise it
    // could be anything.
    parse: function (value, options) {
        return +moment.utc(value);
    },
    // Input is a unix timestamp
    format: function (value, options) {
        var format = options.dateOnly ? "YYYY-MM-DD" : "YYYY-MM-DD hh:mm:ss";
        return moment.utc(value).format(format);
    }
});

/*validate.validators.datetime_jalali=function(value) {
 // The value is guaranteed not to be null or undefined but otherwise it
 // could be anything.
 parse: function (value, options) {
 return +moment.utc(value);
 },
 // Input is a unix timestamp
 format: function (value, options) {
 var format = options.dateOnly ? "jYYYY-jMM-jDD" : "jYYYY-jMM-jDD hh:mm:ss";
 moment().format(format);

 }
 });*/
//init validator js
function init_validatejs(form, constraints, function_name, selector_loader_area, console_log) {
    var console_log = console_log || false;
    // Hook up the form so we can prevent it from being posted
    selector_loader_area = selector_loader_area || '#' + form.id;

    $(document).off('click', selector_loader_area + ' button:submit');
    $(document).on('click', selector_loader_area + ' button:submit', function (e) {
        e.preventDefault();
        var submit_value = $(this).val();
        handleFormSubmit(form, constraints, function_name, submit_value, selector_loader_area, console_log);
    });
    // Hook up the inputs to validate on the fly
    var inputs = form.querySelectorAll(".form-group input,.form-group textarea,.form-group select");
    for (var i = 0; i < inputs.length; ++i) {
        if (inputs.item(i).type == 'select-one') {
            $('#' + inputs.item(i).name).on('select2:unselect', function (e) {
                unformat_all_elements_autoNumeric();
                var errors = validate(form, constraints) || {};
                //showErrors(form, errors || {});
                showErrorsForInput(this, errors[this.name]);
                reformat_all_elements_autoNumeric();
            });
            $('#' + inputs.item(i).name).on('select2:select', function (e) {
                unformat_all_elements_autoNumeric();
                var errors = validate(form, constraints) || {};
                //showErrors(form, errors || {});
                showErrorsForInput(this, errors[this.name]);
                reformat_all_elements_autoNumeric();
            });
        }
        inputs.item(i).removeEventListener("focusout", function (e) {
        }, false);
        inputs.item(i).addEventListener("focusout", function (ev) {
            unformat_all_elements_autoNumeric();
            var errors = validate(form, constraints) || {};
            showErrorsForInput(this, errors[this.name]);
            reformat_all_elements_autoNumeric();
        });
    }
}

function check_validate_input(input_element, form, constraints) {
    unformat_all_elements_autoNumeric();
    var errors = validate(form, constraints) || {};
    showErrorsForInput(input_element, errors[input_element.name]);
    reformat_all_elements_autoNumeric();
}

function handleFormSubmit(form, constraints, function_name, submit_value, selector_loader_area, console_log) {
    // validate the form aainst the constraints
    unformat_all_elements_autoNumeric();
    var errors = validate(form, constraints);
    if (console_log) {
        console.log(errors);
    }
    // then we update the form to reflect the results
    showErrors(form, errors || {});
    if (!errors) {
        $(selector_loader_area).append(generate_loader_html('لطفا منتظر بمانید...'));
        function_name(form, submit_value);
    } else {
        reformat_all_elements_autoNumeric();
    }
}
// Updates the inputs with the validation errors
function showErrors(form, errors) {
    // We loop through all the inputs and show the errors for that input
    _.each(form.querySelectorAll(".form-group input[name],.form-group select[name],.form-group textarea[name]"), function (input) {
        // Since the errors can be null if no errors were found we need to handle
        // that
        showErrorsForInput(input, errors && errors[input.name]);
    });
}
// Shows the errors for a specific input
function showErrorsForInput(input, errors) {
    if (input.type == 'hidden')
        return;
    // This is the root of the input
    var formGroup = closestParent(input.parentNode, "form-group")
        // Find where the error messages will be insert into
        , messages = formGroup.querySelector(".messages");
    // First we remove any old messages and resets the classes
    resetFormGroup(formGroup);
    // If we have errors
    if (errors) {
        // we first mark the group has having errors
        formGroup.classList.add("has-error");
        // then we append all the errors
        _.each(errors, function (error) {
            addError(messages, error);
        });
    } else {
        // otherwise we simply mark it as success
        formGroup.classList.add("has-success");
    }
}
// Recusively finds the closest parent that has the specified class
function closestParent(child, className) {
    if (!child || child == document) {
        return null;
    }
    if (child.classList.contains(className)) {
        return child;
    } else {
        return closestParent(child.parentNode, className);
    }
}
function resetFormGroup(formGroup) {
    // Remove the success and error classes
    formGroup.classList.remove("has-error");
    formGroup.classList.remove("has-success");
    // and remove any old messages
    _.each(formGroup.querySelectorAll(".help-block.error"), function (el) {
        el.parentNode.removeChild(el);
    });
}
// Adds the specified error with the following markup
// <p class="help-block error">[message]</p>
function addError(messages, error) {
    var block = document.createElement("p");
    block.classList.add("help-block");
    block.classList.add("error");
    block.innerHTML = error;
    messages.appendChild(block);
}

function showMessages(messages, form_message_box_id, type, form_element) {
    $(document).off("click", '#' + form_message_box_id);
    $(document).on('click', '#' + form_message_box_id, function () {
        formMessagesArea.classList.remove("message_show");
    });
    var formMessagesArea = document.querySelector('#' + form_message_box_id);
    formMessagesArea.innerHTML = "";
    formMessagesArea.classList.remove("message_show");
    formMessagesArea.classList.remove("message_info");
    formMessagesArea.classList.remove("message_success");
    formMessagesArea.classList.remove("message_error");
    formMessagesArea.classList.add("message_show");
    if (type == 'info') {
        formMessagesArea.classList.add("message_info");
    }
    if (type == 'success') {
        formMessagesArea.classList.add("message_success");
    }
    if (type == 'error') {
        formMessagesArea.classList.add("message_error");
    }
    if (type == 'warning') {
        formMessagesArea.classList.add("message_warning");
    }
    var ul = document.createElement("ul");
    $.each(messages, function (index, value) {
        var title_li = document.createElement("li");
        var title_items_ul = document.createElement("ul");
        $.each(value.items, function (k, v) {
            var title_items_li = document.createElement("li");
            title_items_li.innerHTML = '<h6>' + v + '</h6>';
            title_items_ul.appendChild(title_items_li);
        });
        title_li.innerHTML = '<h5>' + value.title + '</h5>';
        title_li.append(title_items_ul);
        ul.appendChild(title_li);
    });
    formMessagesArea.append(ul);
    var close_btn = document.createElement("button");
    close_btn.classList.add("close_message_btn");
    close_btn.classList.add("fa");
    close_btn.classList.add("fa-times");
    formMessagesArea.append(close_btn);
    document.getElementById(form_message_box_id).scrollIntoView();

    $(document).off("click", '.close_message_btn');
    $(document).on('click', '.close_message_btn', function (e) {
        var $this =  $(this);
        var message_box_element = '#'+form_message_box_id;
        $(message_box_element).html('');
        $(message_box_element).removeAttr('class');
    });

}
window.number_with_separator_inputs = [];
function init_autoNumeric(selector, variable_name, Options,direction,text_align) {
    variable_name = variable_name || 'v';
    direction = direction || 'ltr';
    text_align = text_align || 'text-left';
    remove_old_init_autoNumeric(variable_name);
    //remove_all_old_init_autoNumeric();

    selector = selector || '.number_with_separator';
    Options = Options || {
            modifyValueOnWheel: false,
            maximumValue: '9999999999999.99999',
            leadingZero: 'deny',
            decimalPlaces: '0',
            digitGroupSeparator: ',',
            decimalCharacter: '.',
            decimalCharacterAlternative: ',',
            //currencySymbol: 'ريال',
            unformatOnSubmit: true,
            currencySymbolPlacement: AutoNumeric.options.currencySymbolPlacement.suffix,
            roundingMethod: 'U'
        };
    $(selector).addClass(direction + ' ' + text_align);
    $(function () {
        window['number_with_separator_inputs'][variable_name] = new AutoNumeric.multiple(selector, Options);
        //console.log(window.number_with_separator_inputs);
    });
}
//https://github.com/autoNumeric/autoNumeric#perform-actions-globally-on-a-shared-list-of-autonumeric-elements
//init_autoNumeric('.d',{});
function remove_old_init_autoNumeric(variable_name) {
    variable_name = variable_name || 'v';
    variable_name_inputs = window['number_with_separator_inputs'][variable_name];
    for (element_key in variable_name_inputs) {
        element = variable_name_inputs[element_key];
        element.remove();
        //console.log(element_key);
    }
}

function remove_all_old_init_autoNumeric() {
    var all_inputs = window['number_with_separator_inputs'];
    for (variable_name in all_inputs) {
        variable_value = all_inputs[variable_name];
        for (element_key in variable_value) {
            element = variable_value[element_key];
            element.global.remove();
            element.remove();
            // console.log(element);
        }
    }
}

function reformat_inited_element_autoNumeric(variable_name) {
    variable_name = variable_name || 'v';
    variable_value = window['number_with_separator_inputs'][variable_name];
    try {
        for (element_key in variable_value) {
            element = variable_value[element_key];
            element.global.reformat();
            element.reformat();
        }
    } catch (err) {
        console.log(err);
    }
}

function unformat_inited_element_autoNumeric(variable_name) {
    variable_name = variable_name || 'v';
    variable_value = window['number_with_separator_inputs'][variable_name];
    try {
        for (element_key in variable_value) {
            element = variable_value[element_key];
            element.global.unformat();
            element.unformat();
        }
    } catch (err) {
        console.log(err);
    }
}

function reformat_all_elements_autoNumeric() {
    try {
        var all_inputs = window['number_with_separator_inputs'];
        for (variable_name in all_inputs) {
            variable_value = all_inputs[variable_name];
            for (element_key in variable_value) {
                element = variable_value[element_key];
                element.global.reformat();
                element.reformat();
            }
        }
    } catch (err) {
        console.log(err);
    }
}

function unformat_all_elements_autoNumeric() {
    try {
        var all_inputs = window['number_with_separator_inputs'];
        for (variable_name in all_inputs) {
            variable_value = all_inputs[variable_name];
            for (element_key in variable_value) {
                element = variable_value[element_key];
                element.global.unformat();
                element.unformat();
            }
        }
    } catch (err) {
        console.log(err);
    }
}

function set_value_to_inited_element_autoNumeric(variable_name,value) {
    value = value || 0;
    variable_name = variable_name || 'v';
    variable_value = window['number_with_separator_inputs'][variable_name];
    try {
        for (element_key in variable_value) {
            element = variable_value[element_key];
            element.set(value);
        }
    } catch (err) {
        console.log(err);
    }
}
function yesNoAlert(title, text, type, confirm_button_text, cancel_button_text, func, function_params,unconfirm_func,unconfirm_func_params) {
    unconfirm_func = unconfirm_func || false ;
    unconfirm_func_params = unconfirm_func_params || {} ;
    swal({
            title: title,
            text: text,
            type: type,
            showCancelButton: true,
            confirmButtonColor: "#EF5350",
            confirmButtonText: confirm_button_text,
            cancelButtonText: cancel_button_text,
            closeOnConfirm: false,
            closeOnCancel: false
        },
        function (isConfirm) {
            if (isConfirm) {
//                    swal({
//                        title: "Deleted!",
//                        text: "Your imaginary file has been deleted.",
//                        confirmButtonColor: "#66BB6A",
//                        type: "success"
//                    });
                func(function_params);
                swal.close();
            }
            else {
                if (unconfirm_func)
                {
                    unconfirm_func(unconfirm_func_params);
                }
                swal.close();
//                    swal({
//                        title: "Cancelled",
//                        text: "Your imaginary file is safe :)",
//                        confirmButtonColor: "#2196F3",
//                        type: "error"
//                    });
            }
        });
}
function confirmAlert(title, text, type, confirm_button_text, cancel_button_text, func, function_params, confirm_params, cancel_params,btn_success_class) {
   var btn_class;
    if(btn_success_class)
   {
       btn_class=btn_success_class;
   }
   else{
        btn_class='btn-danger';
    }
    var confirm_pars = confirm_params || false;
    var cancel_pars = cancel_params || false;
    if (!confirm_button_text) {
        $.confirm({
            title: title,
            content: text,
            type: type,
            cancelButton: 'cancel_button_text',
            typeAnimated: true,
            buttons: {
                close: {
                    text: cancel_button_text,
                    action: function (cancel_pars) {
                    }
                }
            }
        });
    }
    else {
    $.confirm({
        title: title,
        content: text,
        type: type,
        cancelButton: 'cancel_button_text',
        typeAnimated: true,
        buttons: {
            tryAgain: {
                text: confirm_button_text,
                btnClass: btn_class,
                action: function (confirm_pars) {
                    return func(function_params,confirm_pars);
                }
            },
            close: {
                text: cancel_button_text,
                action: function (cancel_pars) {
                }
            }
        }
    });
    }
}

function init_input_just_int(selector) {
    $(document).off('keydown', selector);
    $(document).on('keydown', selector, function (e) {
        -1 !== $.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) || (/65|67|86|88/.test(e.keyCode) && (e.ctrlKey === true || e.metaKey === true)) && (!0 === e.ctrlKey || !0 === e.metaKey) || 35 <= e.keyCode && 40 >= e.keyCode || (e.shiftKey || 48 > e.keyCode || 57 < e.keyCode) && (96 > e.keyCode || 105 < e.keyCode) && e.preventDefault()
    });
}
init_input_just_int('.input_only_number');

function menotify(type, title, text) {
    PNotify.desktop.permission();
    (new PNotify({
            title: title,
            type: type,
            text: text,
            desktop: {
                desktop: true
            }
        })
    )
}
function pm_notify(type, title, message) {
    var opts = {
        addclass: "stack-bottomleft"
    };
    switch (type) {
        case 'error':
            opts.title = title;
            opts.text = message;
            opts.type = type;
            break;
        case 'info':
            opts.title = title;
            opts.text = message;
            opts.type = type;
            break;
        case 'success':
            opts.title = title;
            opts.text = message;
            opts.type = type;
            break;
    }
    new PNotify(opts);
}
function clear_form_elements(selector) {
    selector = selector || 'document';
    $(selector).find(':input').each(function () {
        switch (this.type) {
            case 'password':
            case 'select-multiple':
            case 'select-one':
            case 'text':
            case 'number':
            case 'textarea':
                $(this).val('');
                break;
            case 'checkbox':
            case 'radio':
                this.checked = false;
        }
    });
    $('#form_message_box').html('');
    $('#form_message_box').removeAttr('class');
}
//     Underscore.js 1.8.3
//     http://underscorejs.org
//     (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
//     Underscore may be freely distributed under the MIT license.
(function(){function n(n){function t(t,r,e,u,i,o){for(;i>=0&&o>i;i+=n){var a=u?u[i]:i;e=r(e,t[a],a,t)}return e}return function(r,e,u,i){e=b(e,i,4);var o=!k(r)&&m.keys(r),a=(o||r).length,c=n>0?0:a-1;return arguments.length<3&&(u=r[o?o[c]:c],c+=n),t(r,e,u,o,c,a)}}function t(n){return function(t,r,e){r=x(r,e);for(var u=O(t),i=n>0?0:u-1;i>=0&&u>i;i+=n)if(r(t[i],i,t))return i;return-1}}function r(n,t,r){return function(e,u,i){var o=0,a=O(e);if("number"==typeof i)n>0?o=i>=0?i:Math.max(i+a,o):a=i>=0?Math.min(i+1,a):i+a+1;else if(r&&i&&a)return i=r(e,u),e[i]===u?i:-1;if(u!==u)return i=t(l.call(e,o,a),m.isNaN),i>=0?i+o:-1;for(i=n>0?o:a-1;i>=0&&a>i;i+=n)if(e[i]===u)return i;return-1}}function e(n,t){var r=I.length,e=n.constructor,u=m.isFunction(e)&&e.prototype||a,i="constructor";for(m.has(n,i)&&!m.contains(t,i)&&t.push(i);r--;)i=I[r],i in n&&n[i]!==u[i]&&!m.contains(t,i)&&t.push(i)}var u=this,i=u._,o=Array.prototype,a=Object.prototype,c=Function.prototype,f=o.push,l=o.slice,s=a.toString,p=a.hasOwnProperty,h=Array.isArray,v=Object.keys,g=c.bind,y=Object.create,d=function(){},m=function(n){return n instanceof m?n:this instanceof m?void(this._wrapped=n):new m(n)};"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=m),exports._=m):u._=m,m.VERSION="1.8.3";var b=function(n,t,r){if(t===void 0)return n;switch(null==r?3:r){case 1:return function(r){return n.call(t,r)};case 2:return function(r,e){return n.call(t,r,e)};case 3:return function(r,e,u){return n.call(t,r,e,u)};case 4:return function(r,e,u,i){return n.call(t,r,e,u,i)}}return function(){return n.apply(t,arguments)}},x=function(n,t,r){return null==n?m.identity:m.isFunction(n)?b(n,t,r):m.isObject(n)?m.matcher(n):m.property(n)};m.iteratee=function(n,t){return x(n,t,1/0)};var _=function(n,t){return function(r){var e=arguments.length;if(2>e||null==r)return r;for(var u=1;e>u;u++)for(var i=arguments[u],o=n(i),a=o.length,c=0;a>c;c++){var f=o[c];t&&r[f]!==void 0||(r[f]=i[f])}return r}},j=function(n){if(!m.isObject(n))return{};if(y)return y(n);d.prototype=n;var t=new d;return d.prototype=null,t},w=function(n){return function(t){return null==t?void 0:t[n]}},A=Math.pow(2,53)-1,O=w("length"),k=function(n){var t=O(n);return"number"==typeof t&&t>=0&&A>=t};m.each=m.forEach=function(n,t,r){t=b(t,r);var e,u;if(k(n))for(e=0,u=n.length;u>e;e++)t(n[e],e,n);else{var i=m.keys(n);for(e=0,u=i.length;u>e;e++)t(n[i[e]],i[e],n)}return n},m.map=m.collect=function(n,t,r){t=x(t,r);for(var e=!k(n)&&m.keys(n),u=(e||n).length,i=Array(u),o=0;u>o;o++){var a=e?e[o]:o;i[o]=t(n[a],a,n)}return i},m.reduce=m.foldl=m.inject=n(1),m.reduceRight=m.foldr=n(-1),m.find=m.detect=function(n,t,r){var e;return e=k(n)?m.findIndex(n,t,r):m.findKey(n,t,r),e!==void 0&&e!==-1?n[e]:void 0},m.filter=m.select=function(n,t,r){var e=[];return t=x(t,r),m.each(n,function(n,r,u){t(n,r,u)&&e.push(n)}),e},m.reject=function(n,t,r){return m.filter(n,m.negate(x(t)),r)},m.every=m.all=function(n,t,r){t=x(t,r);for(var e=!k(n)&&m.keys(n),u=(e||n).length,i=0;u>i;i++){var o=e?e[i]:i;if(!t(n[o],o,n))return!1}return!0},m.some=m.any=function(n,t,r){t=x(t,r);for(var e=!k(n)&&m.keys(n),u=(e||n).length,i=0;u>i;i++){var o=e?e[i]:i;if(t(n[o],o,n))return!0}return!1},m.contains=m.includes=m.include=function(n,t,r,e){return k(n)||(n=m.values(n)),("number"!=typeof r||e)&&(r=0),m.indexOf(n,t,r)>=0},m.invoke=function(n,t){var r=l.call(arguments,2),e=m.isFunction(t);return m.map(n,function(n){var u=e?t:n[t];return null==u?u:u.apply(n,r)})},m.pluck=function(n,t){return m.map(n,m.property(t))},m.where=function(n,t){return m.filter(n,m.matcher(t))},m.findWhere=function(n,t){return m.find(n,m.matcher(t))},m.max=function(n,t,r){var e,u,i=-1/0,o=-1/0;if(null==t&&null!=n){n=k(n)?n:m.values(n);for(var a=0,c=n.length;c>a;a++)e=n[a],e>i&&(i=e)}else t=x(t,r),m.each(n,function(n,r,e){u=t(n,r,e),(u>o||u===-1/0&&i===-1/0)&&(i=n,o=u)});return i},m.min=function(n,t,r){var e,u,i=1/0,o=1/0;if(null==t&&null!=n){n=k(n)?n:m.values(n);for(var a=0,c=n.length;c>a;a++)e=n[a],i>e&&(i=e)}else t=x(t,r),m.each(n,function(n,r,e){u=t(n,r,e),(o>u||1/0===u&&1/0===i)&&(i=n,o=u)});return i},m.shuffle=function(n){for(var t,r=k(n)?n:m.values(n),e=r.length,u=Array(e),i=0;e>i;i++)t=m.random(0,i),t!==i&&(u[i]=u[t]),u[t]=r[i];return u},m.sample=function(n,t,r){return null==t||r?(k(n)||(n=m.values(n)),n[m.random(n.length-1)]):m.shuffle(n).slice(0,Math.max(0,t))},m.sortBy=function(n,t,r){return t=x(t,r),m.pluck(m.map(n,function(n,r,e){return{value:n,index:r,criteria:t(n,r,e)}}).sort(function(n,t){var r=n.criteria,e=t.criteria;if(r!==e){if(r>e||r===void 0)return 1;if(e>r||e===void 0)return-1}return n.index-t.index}),"value")};var F=function(n){return function(t,r,e){var u={};return r=x(r,e),m.each(t,function(e,i){var o=r(e,i,t);n(u,e,o)}),u}};m.groupBy=F(function(n,t,r){m.has(n,r)?n[r].push(t):n[r]=[t]}),m.indexBy=F(function(n,t,r){n[r]=t}),m.countBy=F(function(n,t,r){m.has(n,r)?n[r]++:n[r]=1}),m.toArray=function(n){return n?m.isArray(n)?l.call(n):k(n)?m.map(n,m.identity):m.values(n):[]},m.size=function(n){return null==n?0:k(n)?n.length:m.keys(n).length},m.partition=function(n,t,r){t=x(t,r);var e=[],u=[];return m.each(n,function(n,r,i){(t(n,r,i)?e:u).push(n)}),[e,u]},m.first=m.head=m.take=function(n,t,r){return null==n?void 0:null==t||r?n[0]:m.initial(n,n.length-t)},m.initial=function(n,t,r){return l.call(n,0,Math.max(0,n.length-(null==t||r?1:t)))},m.last=function(n,t,r){return null==n?void 0:null==t||r?n[n.length-1]:m.rest(n,Math.max(0,n.length-t))},m.rest=m.tail=m.drop=function(n,t,r){return l.call(n,null==t||r?1:t)},m.compact=function(n){return m.filter(n,m.identity)};var S=function(n,t,r,e){for(var u=[],i=0,o=e||0,a=O(n);a>o;o++){var c=n[o];if(k(c)&&(m.isArray(c)||m.isArguments(c))){t||(c=S(c,t,r));var f=0,l=c.length;for(u.length+=l;l>f;)u[i++]=c[f++]}else r||(u[i++]=c)}return u};m.flatten=function(n,t){return S(n,t,!1)},m.without=function(n){return m.difference(n,l.call(arguments,1))},m.uniq=m.unique=function(n,t,r,e){m.isBoolean(t)||(e=r,r=t,t=!1),null!=r&&(r=x(r,e));for(var u=[],i=[],o=0,a=O(n);a>o;o++){var c=n[o],f=r?r(c,o,n):c;t?(o&&i===f||u.push(c),i=f):r?m.contains(i,f)||(i.push(f),u.push(c)):m.contains(u,c)||u.push(c)}return u},m.union=function(){return m.uniq(S(arguments,!0,!0))},m.intersection=function(n){for(var t=[],r=arguments.length,e=0,u=O(n);u>e;e++){var i=n[e];if(!m.contains(t,i)){for(var o=1;r>o&&m.contains(arguments[o],i);o++);o===r&&t.push(i)}}return t},m.difference=function(n){var t=S(arguments,!0,!0,1);return m.filter(n,function(n){return!m.contains(t,n)})},m.zip=function(){return m.unzip(arguments)},m.unzip=function(n){for(var t=n&&m.max(n,O).length||0,r=Array(t),e=0;t>e;e++)r[e]=m.pluck(n,e);return r},m.object=function(n,t){for(var r={},e=0,u=O(n);u>e;e++)t?r[n[e]]=t[e]:r[n[e][0]]=n[e][1];return r},m.findIndex=t(1),m.findLastIndex=t(-1),m.sortedIndex=function(n,t,r,e){r=x(r,e,1);for(var u=r(t),i=0,o=O(n);o>i;){var a=Math.floor((i+o)/2);r(n[a])<u?i=a+1:o=a}return i},m.indexOf=r(1,m.findIndex,m.sortedIndex),m.lastIndexOf=r(-1,m.findLastIndex),m.range=function(n,t,r){null==t&&(t=n||0,n=0),r=r||1;for(var e=Math.max(Math.ceil((t-n)/r),0),u=Array(e),i=0;e>i;i++,n+=r)u[i]=n;return u};var E=function(n,t,r,e,u){if(!(e instanceof t))return n.apply(r,u);var i=j(n.prototype),o=n.apply(i,u);return m.isObject(o)?o:i};m.bind=function(n,t){if(g&&n.bind===g)return g.apply(n,l.call(arguments,1));if(!m.isFunction(n))throw new TypeError("Bind must be called on a function");var r=l.call(arguments,2),e=function(){return E(n,e,t,this,r.concat(l.call(arguments)))};return e},m.partial=function(n){var t=l.call(arguments,1),r=function(){for(var e=0,u=t.length,i=Array(u),o=0;u>o;o++)i[o]=t[o]===m?arguments[e++]:t[o];for(;e<arguments.length;)i.push(arguments[e++]);return E(n,r,this,this,i)};return r},m.bindAll=function(n){var t,r,e=arguments.length;if(1>=e)throw new Error("bindAll must be passed function names");for(t=1;e>t;t++)r=arguments[t],n[r]=m.bind(n[r],n);return n},m.memoize=function(n,t){var r=function(e){var u=r.cache,i=""+(t?t.apply(this,arguments):e);return m.has(u,i)||(u[i]=n.apply(this,arguments)),u[i]};return r.cache={},r},m.delay=function(n,t){var r=l.call(arguments,2);return setTimeout(function(){return n.apply(null,r)},t)},m.defer=m.partial(m.delay,m,1),m.throttle=function(n,t,r){var e,u,i,o=null,a=0;r||(r={});var c=function(){a=r.leading===!1?0:m.now(),o=null,i=n.apply(e,u),o||(e=u=null)};return function(){var f=m.now();a||r.leading!==!1||(a=f);var l=t-(f-a);return e=this,u=arguments,0>=l||l>t?(o&&(clearTimeout(o),o=null),a=f,i=n.apply(e,u),o||(e=u=null)):o||r.trailing===!1||(o=setTimeout(c,l)),i}},m.debounce=function(n,t,r){var e,u,i,o,a,c=function(){var f=m.now()-o;t>f&&f>=0?e=setTimeout(c,t-f):(e=null,r||(a=n.apply(i,u),e||(i=u=null)))};return function(){i=this,u=arguments,o=m.now();var f=r&&!e;return e||(e=setTimeout(c,t)),f&&(a=n.apply(i,u),i=u=null),a}},m.wrap=function(n,t){return m.partial(t,n)},m.negate=function(n){return function(){return!n.apply(this,arguments)}},m.compose=function(){var n=arguments,t=n.length-1;return function(){for(var r=t,e=n[t].apply(this,arguments);r--;)e=n[r].call(this,e);return e}},m.after=function(n,t){return function(){return--n<1?t.apply(this,arguments):void 0}},m.before=function(n,t){var r;return function(){return--n>0&&(r=t.apply(this,arguments)),1>=n&&(t=null),r}},m.once=m.partial(m.before,2);var M=!{toString:null}.propertyIsEnumerable("toString"),I=["valueOf","isPrototypeOf","toString","propertyIsEnumerable","hasOwnProperty","toLocaleString"];m.keys=function(n){if(!m.isObject(n))return[];if(v)return v(n);var t=[];for(var r in n)m.has(n,r)&&t.push(r);return M&&e(n,t),t},m.allKeys=function(n){if(!m.isObject(n))return[];var t=[];for(var r in n)t.push(r);return M&&e(n,t),t},m.values=function(n){for(var t=m.keys(n),r=t.length,e=Array(r),u=0;r>u;u++)e[u]=n[t[u]];return e},m.mapObject=function(n,t,r){t=x(t,r);for(var e,u=m.keys(n),i=u.length,o={},a=0;i>a;a++)e=u[a],o[e]=t(n[e],e,n);return o},m.pairs=function(n){for(var t=m.keys(n),r=t.length,e=Array(r),u=0;r>u;u++)e[u]=[t[u],n[t[u]]];return e},m.invert=function(n){for(var t={},r=m.keys(n),e=0,u=r.length;u>e;e++)t[n[r[e]]]=r[e];return t},m.functions=m.methods=function(n){var t=[];for(var r in n)m.isFunction(n[r])&&t.push(r);return t.sort()},m.extend=_(m.allKeys),m.extendOwn=m.assign=_(m.keys),m.findKey=function(n,t,r){t=x(t,r);for(var e,u=m.keys(n),i=0,o=u.length;o>i;i++)if(e=u[i],t(n[e],e,n))return e},m.pick=function(n,t,r){var e,u,i={},o=n;if(null==o)return i;m.isFunction(t)?(u=m.allKeys(o),e=b(t,r)):(u=S(arguments,!1,!1,1),e=function(n,t,r){return t in r},o=Object(o));for(var a=0,c=u.length;c>a;a++){var f=u[a],l=o[f];e(l,f,o)&&(i[f]=l)}return i},m.omit=function(n,t,r){if(m.isFunction(t))t=m.negate(t);else{var e=m.map(S(arguments,!1,!1,1),String);t=function(n,t){return!m.contains(e,t)}}return m.pick(n,t,r)},m.defaults=_(m.allKeys,!0),m.create=function(n,t){var r=j(n);return t&&m.extendOwn(r,t),r},m.clone=function(n){return m.isObject(n)?m.isArray(n)?n.slice():m.extend({},n):n},m.tap=function(n,t){return t(n),n},m.isMatch=function(n,t){var r=m.keys(t),e=r.length;if(null==n)return!e;for(var u=Object(n),i=0;e>i;i++){var o=r[i];if(t[o]!==u[o]||!(o in u))return!1}return!0};var N=function(n,t,r,e){if(n===t)return 0!==n||1/n===1/t;if(null==n||null==t)return n===t;n instanceof m&&(n=n._wrapped),t instanceof m&&(t=t._wrapped);var u=s.call(n);if(u!==s.call(t))return!1;switch(u){case"[object RegExp]":case"[object String]":return""+n==""+t;case"[object Number]":return+n!==+n?+t!==+t:0===+n?1/+n===1/t:+n===+t;case"[object Date]":case"[object Boolean]":return+n===+t}var i="[object Array]"===u;if(!i){if("object"!=typeof n||"object"!=typeof t)return!1;var o=n.constructor,a=t.constructor;if(o!==a&&!(m.isFunction(o)&&o instanceof o&&m.isFunction(a)&&a instanceof a)&&"constructor"in n&&"constructor"in t)return!1}r=r||[],e=e||[];for(var c=r.length;c--;)if(r[c]===n)return e[c]===t;if(r.push(n),e.push(t),i){if(c=n.length,c!==t.length)return!1;for(;c--;)if(!N(n[c],t[c],r,e))return!1}else{var f,l=m.keys(n);if(c=l.length,m.keys(t).length!==c)return!1;for(;c--;)if(f=l[c],!m.has(t,f)||!N(n[f],t[f],r,e))return!1}return r.pop(),e.pop(),!0};m.isEqual=function(n,t){return N(n,t)},m.isEmpty=function(n){return null==n?!0:k(n)&&(m.isArray(n)||m.isString(n)||m.isArguments(n))?0===n.length:0===m.keys(n).length},m.isElement=function(n){return!(!n||1!==n.nodeType)},m.isArray=h||function(n){return"[object Array]"===s.call(n)},m.isObject=function(n){var t=typeof n;return"function"===t||"object"===t&&!!n},m.each(["Arguments","Function","String","Number","Date","RegExp","Error"],function(n){m["is"+n]=function(t){return s.call(t)==="[object "+n+"]"}}),m.isArguments(arguments)||(m.isArguments=function(n){return m.has(n,"callee")}),"function"!=typeof/./&&"object"!=typeof Int8Array&&(m.isFunction=function(n){return"function"==typeof n||!1}),m.isFinite=function(n){return isFinite(n)&&!isNaN(parseFloat(n))},m.isNaN=function(n){return m.isNumber(n)&&n!==+n},m.isBoolean=function(n){return n===!0||n===!1||"[object Boolean]"===s.call(n)},m.isNull=function(n){return null===n},m.isUndefined=function(n){return n===void 0},m.has=function(n,t){return null!=n&&p.call(n,t)},m.noConflict=function(){return u._=i,this},m.identity=function(n){return n},m.constant=function(n){return function(){return n}},m.noop=function(){},m.property=w,m.propertyOf=function(n){return null==n?function(){}:function(t){return n[t]}},m.matcher=m.matches=function(n){return n=m.extendOwn({},n),function(t){return m.isMatch(t,n)}},m.times=function(n,t,r){var e=Array(Math.max(0,n));t=b(t,r,1);for(var u=0;n>u;u++)e[u]=t(u);return e},m.random=function(n,t){return null==t&&(t=n,n=0),n+Math.floor(Math.random()*(t-n+1))},m.now=Date.now||function(){return(new Date).getTime()};var B={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;"},T=m.invert(B),R=function(n){var t=function(t){return n[t]},r="(?:"+m.keys(n).join("|")+")",e=RegExp(r),u=RegExp(r,"g");return function(n){return n=null==n?"":""+n,e.test(n)?n.replace(u,t):n}};m.escape=R(B),m.unescape=R(T),m.result=function(n,t,r){var e=null==n?void 0:n[t];return e===void 0&&(e=r),m.isFunction(e)?e.call(n):e};var q=0;m.uniqueId=function(n){var t=++q+"";return n?n+t:t},m.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var K=/(.)^/,z={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},D=/\\|'|\r|\n|\u2028|\u2029/g,L=function(n){return"\\"+z[n]};m.template=function(n,t,r){!t&&r&&(t=r),t=m.defaults({},t,m.templateSettings);var e=RegExp([(t.escape||K).source,(t.interpolate||K).source,(t.evaluate||K).source].join("|")+"|$","g"),u=0,i="__p+='";n.replace(e,function(t,r,e,o,a){return i+=n.slice(u,a).replace(D,L),u=a+t.length,r?i+="'+\n((__t=("+r+"))==null?'':_.escape(__t))+\n'":e?i+="'+\n((__t=("+e+"))==null?'':__t)+\n'":o&&(i+="';\n"+o+"\n__p+='"),t}),i+="';\n",t.variable||(i="with(obj||{}){\n"+i+"}\n"),i="var __t,__p='',__j=Array.prototype.join,"+"print=function(){__p+=__j.call(arguments,'');};\n"+i+"return __p;\n";try{var o=new Function(t.variable||"obj","_",i)}catch(a){throw a.source=i,a}var c=function(n){return o.call(this,n,m)},f=t.variable||"obj";return c.source="function("+f+"){\n"+i+"}",c},m.chain=function(n){var t=m(n);return t._chain=!0,t};var P=function(n,t){return n._chain?m(t).chain():t};m.mixin=function(n){m.each(m.functions(n),function(t){var r=m[t]=n[t];m.prototype[t]=function(){var n=[this._wrapped];return f.apply(n,arguments),P(this,r.apply(m,n))}})},m.mixin(m),m.each(["pop","push","reverse","shift","sort","splice","unshift"],function(n){var t=o[n];m.prototype[n]=function(){var r=this._wrapped;return t.apply(r,arguments),"shift"!==n&&"splice"!==n||0!==r.length||delete r[0],P(this,r)}}),m.each(["concat","join","slice"],function(n){var t=o[n];m.prototype[n]=function(){return P(this,t.apply(this._wrapped,arguments))}}),m.prototype.value=function(){return this._wrapped},m.prototype.valueOf=m.prototype.toJSON=m.prototype.value,m.prototype.toString=function(){return""+this._wrapped},"function"==typeof define&&define.amd&&define("underscore",[],function(){return m})}).call(this);
//# sourceMappingURL=underscore-min.map