function ajax(options) {
    options.loading = (typeof options.loading === "undefined") || options.loading;
    if (options.loading)
        showLoading();

    return $.ajax({
        url: baseUrl + options.url,
        data: options.data,
        async: (typeof options.async === "undefined") ? true : options.async,
        type: "POST",
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        success: options.success,
        error: options.error ? options.error : function (err) {
            closeLoading();
            var errorMsg, errorDesc;
            if (err.responseJSON) {
                if (err.responseJSON.Description) {
                    errorMsg = err.responseJSON.Message;
                    errorDesc = err.responseJSON.Description;
                    if (errorMsg === "Object reference not set to an instance of an object.") {
                        showMsgModal(0, "خطای ناشناخته");
                    }
                    else {
                        showMsgModal(0, errorMsg, errorDesc);
                    }
                }
                else {
                    errorMsg = err.responseJSON.Message.split('©')[0];
                    errorDesc = err.responseJSON.Message.split('©')[1];
                    if (errorMsg === "Object reference not set to an instance of an object.") {
                        showMsgModal(0, "خطای ناشناخته");
                    }
                    else {
                        showMsgModal(0, errorMsg, errorDesc);
                    }
                }
            }
            else {
                errorMsg = err.responseText;
                showMsgModal(0, errorMsg);

            }
        },
        complete: options.complete ? options.complete : function () { if (options.loading) closeLoading(); }
    });
}

function showLoading() {
    window.top.$("#masterLockScreen").show();
}
function closeLoading() {
    window.top.$("#masterLockScreen").hide();
}
function showMsgModal(type, message) {
    alert(message);
}
function imgToSvg() {
    $.each($("img.svg"), function () {
        var $img = jQuery(this);
        var imgId = $img.attr("id");
        var imgClass = $img.attr("class");
        var imgUrl = $img.attr("src");
        var imgStyle = $img.attr("style");
        var imgClick = $img.attr("onclick");
        jQuery.get(imgUrl, function (data) {
            var $svg = jQuery(data).find("svg");
            $svg = $svg.removeAttr("xmlns:a");
            if (typeof imgId !== "undefined")
                $svg = $svg.attr("id", imgId);
            if (typeof imgClass !== "undefined")
                $svg = $svg.attr("class", imgClass + " replaced-svg");
            if (typeof imgStyle !== "undefined")
                $svg = $svg.attr("style", imgStyle);
            if (typeof imgClick !== "undefined")
                $svg = $svg.attr("onclick", imgClick);
            $img.replaceWith($svg);
        }, "xml");
    });
}


$(document).ready(function () {
    imgToSvg();

    $("[data-mask='price']").blur(function () {
        if ($(this).val().trim() !== "") {
            var decimalCount = Number(window.top.$("#hfDecimalCount").val());
            var number = Number($(this).val()).toFixed(decimalCount);
            $(this).val(numberWithCommas(number));
        }
    });
    $("[data-mask='price']").focus(function () {
        $(this).val(numberNonCommas($(this).val()));
    });
    $("[data-mask='full-date']").datepicker({
        dateFormat: "yy/mm/dd"
    });
    $("[data-mask='full-date']").inputmask("9999/99/99");
    $("[data-mask='full-date']").attr("maxlength", "10");
    $("[data-mask='full-date']").attr("autocomplete", "off");
    $("[data-mask='full-date']").change(function () {
        if ($(this).val().trim() !== "" && $(this).attr("data-required") === "true") {
            $(this).removeClass("validation-error");
            $(this).addClass("validation");
        }
    });
    $("[data-mask='date']").datepicker({
        dateFormat: "y/mm/dd"
    });
    $("[data-mask='date']").inputmask("99/99/99");
    $("[data-mask='date']").attr("maxlength", "8");
    $("[data-mask='date']").attr("autocomplete", "off");
    $("[data-mask='date']").change(function () {
        if ($(this).val().trim() !== "" && $(this).attr("data-required") === "true") {
            $(this).removeClass("validation-error");
            $(this).addClass("validation");
        }
    });
    $("[data-mask='full-time']").inputmask("99:99:99");
    $("[data-mask='full-time']").attr("maxlength", "8");
    $("[data-mask='time']").inputmask("99:99");
    $("[data-mask='time']").attr("maxlength", "5");
    $("[data-mask='num']").inputmask({ "mask": "9", "repeat": 15, "greedy": false });
    $("[data-mask='email']").inputmask({
        mask: "*{1,20}[.*{1,20}][.*{1,20}][.*{1,20}]@*{1,20}[.*{2,6}][.*{1,2}]",
        greedy: false,
        onBeforePaste: function (pastedValue, opts) {
            pastedValue = pastedValue.toLowerCase();
            return pastedValue.replace("mailto:", "");
        },
        definitions: {
            "*": {
                validator: "[0-9A-Za-z!#$%&'*+/=?^_`{|}~\-]",
                cardinality: 1,
                casing: "lower"
            }
        }
    });
    $("[data-required='true']").each(function () {
        $(this).addClass("validation");
        var nextElement = $(this)[0].nextSibling;
        if (nextElement && $(nextElement).hasClass("selectize-control"))
            $(nextElement).find(".selectize-input").addClass("validation");
    });
    $("input[data-length]").blur(function () {
        var value = $(this).val().replace(/\_/g, "").trim();
        if (value.length !== $(this).attr("data-length")) {
            $(this).removeClass("validation");
            $(this).addClass("validation-error");
        }
        else {
            $(this).removeClass("validation-error");
            $(this).attr("title", "");
            if ($(this).attr("data-required") === "true")
                $(this).addClass("validation");

        }
    });
    $("input[data-required='true']").blur(function () {
        var value = $(this).val().replace(/\_/g, "").trim();
        if (value === "") {
            $(this).removeClass("validation");
            $(this).addClass("validation-error");
        }
        else {
            $(this).removeClass("validation-error");
            $(this).addClass("validation");
            $(this).attr("title", "");
        }
    });
    $("select[data-required='true']").blur(function () {
        var value = $(this).val().trim();
        if (value === "") {
            $(this).removeClass("validation");
            $(this).addClass("validation-error");
        }
        else {
            $(this).removeClass("validation-error");
            $(this).addClass("validation");
            $(this).attr("title", "");
        }
    });

});


function checkValidation(divName) {
    var expectationMessage = "";
    var control = true;
    var focus = false;
    var div = "";
    if (divName)
        div = divName;
    $(div + " input[data-length]").each(function () {
        if (!$(this).is(":hidden")) {
            if ($(this).val().replace(/\_/g, "").length !== Number($(this).attr("data-length"))) {
                control = false;
                $(this).removeClass("validation");
                $(this).addClass("validation-error");
                if ($(this).attr("data-error-validation"))
                    expectationMessage += $(this).attr("data-error-validation") + "<br/>";
                else if ($(this).attr("data-title"))
                    expectationMessage += "تعداد کاراکترهای " + $(this).attr("data-title") + " باید " + $(this).attr("data-length") + " باشد<br/>";
                if (!focus) {
                    $(this).focus();
                    focus = true;
                }
            }
        }
    });
    $(div + " input[data-required='true']").each(function () {
        if (!$(this).is(":hidden")) {
            var value = $(this).val().replace(/\_/g, "").trim();
            if (value === "") {
                control = false;
                $(this).removeClass("validation");
                $(this).addClass("validation-error");
                if ($(this).attr("data-error-validation"))
                    expectationMessage += $(this).attr("data-error-validation") + "<br/>";
                if (!focus) {
                    $(this).focus();
                    focus = true;
                }
            }
        }
    });
    $(div + " select[data-required='true']").each(function () {
        if (!$(this).is(":hidden")) {
            var value = $(this).val().trim();
            if (value === "") {
                control = false;
                $(this).removeClass("validation");
                $(this).addClass("validation-error");
                if ($(this).attr("data-error-validation"))
                    expectationMessage += $(this).attr("data-error-validation") + "<br/>";
                if (!focus) {
                    $(this).focus();
                    focus = true;
                }
            }
        }
    });

    if (!control && expectationMessage === "")
        expectationMessage = "لطفا مقادیر را تکمیل کنید";
    return expectationMessage;
}
function getJsonValue(divName) {
    var stuff = {};
    var field;
    var div = "";
    if (divName)
        div = divName;
    $(div + " [data-id]").each(function () {
        if ($(this).is("input[type='text']") || $(this).is("input[type='hidden']") || $(this).is("input[type='password']") || $(this).is("textarea")) {
            field = $(this).attr("data-id");
            if ($(this).attr("data-mask") === "price")
                stuff[field] = $(this).val() === "" ? null : numberNonCommas($(this).val());
            else if ($(this).attr("data-mask") === "num")
                stuff[field] = $(this).val() === "" ? -1 : $(this).val().trim();
            else
                stuff[field] = $(this).val() === "" ? null : $(this).val().trim();
        }
        else if ($(this).is("input[type='checkbox']") || $(this).is("input[type='radio']")) {
            field = $(this).attr("data-id");
            stuff[field] = $(this).prop("checked");
        }
        else if ($(this).is("label") || $(this).is("span") || $(this).is("p")) {
            field = $(this).attr("data-id");
            stuff[field] = $(this).text();
        }
        else if ($(this).is("select")) {
            field = $(this).attr("data-id");
            stuff[field] = $(this).val();
        }
    });
    return stuff;
}




function isNumeric(value) {
    value = value.toString().trim();
    return Number(value).toString() === value;
}
function numberWithCommas(value) {
    if (value.toString().split(".").length === 1)
        return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return value.toString().split(".")[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + "." + value.toString().split(".")[1];
}
function numberNonCommas(value, defaultValue) {
    if (value === undefined || value === null || value.toString().trim() === '') {
        if (defaultValue)
            return defaultValue;
        return null;
    }
    return Number(value.toString().trim().replace(/\,/g, ""));
}
function guid() {
    function s4() {
        return Math.floor((1 + Math.random()) * 0x10000)
            .toString(16)
            .substring(1);
    }
    return s4() + s4();
}

function getQuery(name, url) {
    if (!url)
        url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return '';
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}


function removeQuery(name, url) {
    if (!url)
        url = window.location.href;
    var urlParts = url.split('?');
    if (urlParts.length >= 2) {

        var prefix = encodeURIComponent(name) + "=";
        var pars = urlParts[1].split(/[&;]/g);
        for (var i = pars.length; i-- > 0;) {
            if (pars[i].lastIndexOf(prefix, 0) !== -1) {
                pars.splice(i, 1);
            }
        }
        url = urlParts[0] + "?" + pars.join("&");
        return url;
    } else {
        return url;
    }
}
var wordifyfa = function (num, level) {
    "use strict";
    if (num === null) {
        return "";
    }
    num = Number(numberNonCommas(num).toString().split(".")[0]);
    // convert negative number to positive and get wordify value
    if (num < 0) {
        num = num * -1;
        return window.top.negative + wordifyfa(num, level);
    }
    if (num === 0) {
        if (level === 0) {
            return window.top.zero;
        } else {
            return "";
        }
    }
    var result = "";
    var yekan = [window.top.one, window.top.two, window.top.three, window.top.four, window.top.five, window.top.six, window.top.seven, window.top.eight, window.top.nine];
    var dahgan = [window.top.twenty, window.top.thirty, window.top.forty, window.top.fifty, window.top.sixty, window.top.seventy, window.top.eighty, window.top.ninety];
    var sadgan = [window.top.hundred, window.top.twoHundred, window.top.threeHundred, window.top.fourHundred, window.top.fiveHundred, window.top.sixHundred, window.top.sevenHundred, window.top.eightHundred, window.top.nineHundred];
    var dah = [window.top.ten, window.top.eleven, window.top.twelve, window.top.thirteen, window.top.fourteen, window.top.fifteen, window.top.sixteen, window.top.seventeen, window.top.eighteen, window.top.nineteen];

    if (level > 0) {
        result += " " + window.top.and + " ";
        level -= 1;
    }

    if (num < 10) {
        result += yekan[num - 1] + " ";
    } else if (num < 20) {
        result += dah[num - 10] + " ";
    } else if (num < 100) {
        result += dahgan[parseInt(num / 10, 10) - 2] + wordifyfa(num % 10, level + 1) + " ";
    } else if (num < 1000) {
        result += sadgan[parseInt(num / 100, 10) - 1] + wordifyfa(num % 100, level + 1) + " ";
    } else if (num < 1000000) {
        result += wordifyfa(parseInt(num / 1000, 10), level) + window.top.thousand + wordifyfa(num % 1000, level + 1) + " ";
    } else if (num < 1000000000) {
        result += wordifyfa(parseInt(num / 1000000, 10), level) + window.top.million + wordifyfa(num % 1000000, level + 1) + " ";
    } else if (num < 1000000000000) {
        result += wordifyfa(parseInt(num / 1000000000, 10), level) + window.top.milliard + wordifyfa(num % 1000000000, level + 1) + " ";
    } else if (num < 1000000000000000) {
        result += wordifyfa(parseInt(num / 1000000000000, 10), level) + window.top.trilliard + wordifyfa(num % 1000000000000, level + 1) + " ";
    }
    return result;

};
var wordifyRials = function (num) {
    return wordifyfa(num, 0) + " " + window.top.rial;
};
function isDate(value) {
    var currentVal = value;
    if (currentVal === "")
        return false;

    var rxDatePattern = /^(\d{2})(\/)(\d{2})(\/)(\d{2})$/;
    var dtArray = currentVal.match(rxDatePattern);

    if (dtArray == null)
        return false;

    var dtMonth = dtArray[3];
    var dtDay = dtArray[5];
    var dtYear = dtArray[1];


    if (dtMonth < 1 || dtMonth > 12)
        return false
    else if (dtDay < 1 || dtDay > 31)
        return false;

    return true;
}
function isFullDate(value) {
    var currentVal = value;
    if (currentVal === "")
        return false;
    var rxDatePattern = /^(\d{4})(\/)(\d{2})(\/)(\d{2})$/;
    var dtArray = currentVal.match(rxDatePattern);
    if (dtArray == null)
        return false;
    var dtMonth = dtArray[3];
    var dtDay = dtArray[5];
    var dtYear = dtArray[1];
    if (dtMonth < 1 || dtMonth > 12)
        return false;
    else if (dtDay < 1 || dtDay > 31)
        return false;
    return true;
}

function savePicture($container, base64, description, ratio) {
    if (!ratio)
        ratio = 16 / 9;
    ajax({
        url: "Admin/SavePicture",
        data: JSON.stringify({ base64: base64 }),
        success: function (result) {
            window.top.$("#panelCrop").html("<img id='cropImage' src='" + window.top.baseSrc + "App_Attachments/" + result + "' />");
            window.top.initCropPicture($container, ratio);
            window.top.$("#divDescription").html(description);
            window.top.$("#cropPicture").modal("show");
        }
    });
}

$(".close").on("click", function () {
    $('.modal.show').modal('hide');
});





