function getFormItemName(key) {
    switch (key) {
        case "text": return 'متن';
        case "select": return 'لیست انتخاب';
        case "checkbox": return 'چک باکس';
        case "date_fa": return 'تاریخ شمسی';
        case "date_en": return 'تاریخ میلادی';
        case "clock": return 'ساعت';
        case "number": return 'عدد';
        case "number2": return 'عدد';
        case "file": return 'فایل';
        case "phone": return 'تلفن';
        case "email": return 'ایمیل';
        case "password": return 'پسورد';
        case "select2": return 'لیست انتخاب';
        case "checkbox2": return 'چک باکس';
        case "province_city": return 'استان و شهر';
        case "map_location": return 'لوکیشن';
    }
    return key;
}

function openFormBlockEditor(editUrl) {

    $('#dialog-holder').append(dialogHtmlGenerator("large3","form_block_editor_dialog"));

    let dialog = $("#form_block_editor_dialog");
    let dialog_id = "#form_block_editor_dialog";
    let contentBox = dialog.find(".majorisbox-final-content");
    let closeBtn = dialog.find(".majorisbox-close");
    let closeLayout = $(dialog_id+" .majorisbox-close-layout");
    let loadingOverlay = dialog.find('.majorisbox-loading');

    contentBox.hide();

    dialog.fadeIn('fast');
    $("html").css("overflow", "hidden");
    
    closeBtn.add(closeLayout).click(function () {
        selectImageID = null;
        contentBox.html("");
        dialog.fadeOut('fast');
        $("html").css("overflow", "auto");
        $('#dialog-holder').find(dialog_id).remove();
    });

    loadingOverlay.show();

    contentBox.show();
    contentBox.html("");

    setTimeout(function() {

        loadingOverlay.hide();
        let iframeHtml = '<iframe id="form-block-editor-iframe" scrolling="no" style="width:100%;height:100%" src="'+editUrl+'" title="description"></iframe>';
        contentBox.html(iframeHtml);
        let iframe = $('#form-block-editor-iframe');
        iframe.on('load', function(){
            iframe.contents().find('#end-of-form-block-editor').click(function(event){
                let newData = iframe.contents().find('#form_json_area').val();
                $('#form_json_text_area').val(newData);
                dialog.fadeOut('fast');
                $('#dialog-holder').find(dialog_id).remove();
                $("html").css("overflow", "auto");
                contentBox.html("");
                location. reload();
                //FormListItemsMotherAction();
                //actionsListeners();
                //scrollAndEmphasisAnimation("edit");
            });
        });
        
    }, 200);

}

function getEditorFileNameByKey(key) {
    switch (key) {
        case "text":
        case "date_fa":
        case "date_en":
        case "clock":
        case "number":
        case "number2":
        case "file":
        case "phone":
        case "email":
        case "password":
        case "province_city":
        case "map_location":
            return 'text_integrated_editor';
        case "select":
        case "checkbox":
        case "select2":
        case "checkbox2":
            return 'non_text_integrated_editor';
    }
    return key;
}

function WriteFormJsonListToDataBase(message){ 

    let sendData = [];
    let index = 0;
    $("#sortable_field_form_list").children('div').each(function () {

        //update href by new json positions:
        let editbtn = $(this).find(".edit-form-block");
        const formid = editbtn.data("form-id");
        const formNature = editbtn.data("form-nature");
        const editorFileName = editbtn.data("file-name");
        let new_link = mpPanelBaseUrl + "/form-block-editor/" + formid + "/" + formNature + "/" + index + "/" + editorFileName ;
        editbtn.attr("data-url", new_link);

        let val = $(this).find(".json_text_area").val();
        sendData[index] = JSON.parse(val);
        index++;

    });

    let finalRes = JSON.stringify(sendData);

    $('#form_json_text_area').val(finalRes);
    
    let _id = $.trim($('#id').val());

    let _toSave = {
        id             : _id,
        data           : finalRes
    }

    $.ajax({
        type: "POST",
        url: mpPanelBaseUrl + "/update_form_json",
        data: _toSave,
        timeout: 25000,
        cache: false,
        success: function (data) {
            if (data == "ok") {
                notyf.success(message);
            } else {
                notyf.error(data);
            }
        },
        error: function(xhr, status, error) {
            notyf.error('Error: ' + xhr.status + ' ' + xhr.statusText);
        }
    });

}

function reportFormSortableChange() {
    WriteFormJsonListToDataBase('تغییرات ذخیره شد');
};

function buildNewEmptyFieldFormJsonTextTypeAndSave(type){

    let formJsonString = $('#form_json_text_area').val();
    let _form_id       = $('#id').val();
    let _page_url      = $('#form-body-data').data('page-url');

    if(
        (!formJsonString) ||
        (formJsonString.trim() == '') ||
        (formJsonString.trim() == "") ||
        (formJsonString.trim() == "null") ||
        (formJsonString.trim() == "undefined") ||
        (formJsonString.trim() == null)
        ) formJsonString = "[]";
        
    let FormJson = JSON.parse(formJsonString);

    let itemJson = {};
    
    //we do this for json parsing in android:
    //json key types must be always same (int or string) so here we do check for empty
    //and replace it with 0 if user has not entered anything in number input.
    itemJson['id_code']                         = "fic"+randomUID(21);
    itemJson['type']                            = type;
    itemJson['title']                           = "";
    itemJson['description']                     = "";
    itemJson['hint']                            = "";
    itemJson['forced']                          = "0";
    itemJson['visible']                         = "1";
    itemJson['visiblity_related_field_id_code'] = "";
    itemJson['visible_if_field_value_code']     = "";
    itemJson['visible_if_field_value_text']     = "";
    itemJson['align']                           = "rtl";
    itemJson['minchar']                         = "1";
    itemJson['maxchar']                         = "300";
    itemJson['minint']                          = "";
    itemJson['maxint']                          = "";
    itemJson['lines']                           = "1";
    itemJson['multiple_choice']                 = "0";
    itemJson['allowed_format']                  = "png,jpg,jpeg";
    itemJson['max_size']                        = "1";
    itemJson['conditional_operator']            = "off";
    itemJson['val']                             = null;
    itemJson['default_value']                   = "";
    itemJson['get_user_location']               = "0";

    if(type == "number" || type == "number2"){
        itemJson['plus_minus_control_btns'] = "1";
    }else{
        itemJson['plus_minus_control_btns'] = "0";
    }
    

    FormJson.push(itemJson);

    let finalRes = JSON.stringify(FormJson);
    //console.log("toSave: " + JSON.stringify(BigJson));

    let _toSave = {
        id             : _form_id,
        data           : finalRes
    }

    $.ajax({
        type: "POST",
        url: mpPanelBaseUrl + "/update_form_json",
        data: _toSave,
        timeout: 25000,
        cache: false,
        success: function (data) {
            if (data == "ok") {
                notyf.success("فیلد جدید افزوده شد");
                window.location.href = mpPanelBaseUrl + "/" + _page_url + "/" + _form_id + "/form-body"; 
            } else {
                notyf.error(data);
            }
        },
        error: function(e) {
            notyf.error('Error: ' + e.responseText);
        }
    });
}

function buildNewEmptyFieldFormJsonNonTextTypeAndSave(type){

    let formJsonString = $('#form_json_text_area').val();
    let _form_id       = $('#id').val();
    let _page_url      = $('#form-body-data').data('page-url');

    if(
        (!formJsonString) ||
        (formJsonString.trim() == '') ||
        (formJsonString.trim() == "") ||
        (formJsonString.trim() == "null") ||
        (formJsonString.trim() == "undefined") ||
        (formJsonString.trim() == null)
        ) formJsonString = "[]";
        
    let FormJson = JSON.parse(formJsonString);

    let itemJson = {};
    
    //we do this for json parsing in android:
    //json key types must be always same (int or string) so here we do check for empty
    //and replace it with 0 if user has not entered anything in number input.
    itemJson['id_code']                         = "fic"+randomUID(21);
    itemJson['type']                            = type;
    itemJson['title']                           = "";
    itemJson['description']                     = "";
    itemJson['hint']                            = "";
    itemJson['forced']                          = "0";
    itemJson['visible']                         = "1";
    itemJson['visiblity_related_field_id_code'] = "";
    itemJson['visible_if_field_value_code']     = "";
    itemJson['visible_if_field_value_text']     = "";
    itemJson['align']                           = "rtl";
    itemJson['minchar']                         = "1";
    itemJson['maxchar']                         = "300";
    itemJson['minint']                          = "";
    itemJson['maxint']                          = "";
    itemJson['lines']                           = "1";
    itemJson['multiple_choice']                 = "0";
    itemJson['allowed_format']                  = "png,jpg,jpeg";
    itemJson['max_size']                        = "1";
    itemJson['conditional_operator']            = "off";
    itemJson['val']                             = JSON.parse("[]");;
    itemJson['default_value']                   = "";
    itemJson['get_user_location']               = "0";
    itemJson['plus_minus_control_btns']         = "0";

    FormJson.push(itemJson);

    let finalRes = JSON.stringify(FormJson);

    let _toSave = {
        id             : _form_id,
        data           : finalRes
    }

    $.ajax({
        type: "POST",
        url: mpPanelBaseUrl + "/update_form_json",
        data: _toSave,
        timeout: 25000,
        cache: false,
        success: function (data) {
            if (data == "ok") {
                notyf.success("فیلد جدید افزوده شد");
                window.location.href = mpPanelBaseUrl + "/" + _page_url + "/" + _form_id + "/form-body";

            } else {
                notyf.error(data);
            }
        },
        error: function(e) {
            notyf.error('Error: ' + e.responseText);
        }
    });
}

function buildFormJsonTextTypeAndSave(type) {

    let fullJsonString = $('#form_json_area').val();
    let json_pos       = $('#json_pos').val();
    let _form_id       = $('#id').val();

    fullJsonString = convertStringToJsonArrayEmptyStringIfNull(fullJsonString); 
        
    let BigJson = JSON.parse(fullJsonString);

    let newJson = {};

    newJson['id_code']                         = $('#id_code').val();
    newJson['type']                            = type;
    newJson['title']                           = $('#title').val();
    newJson['description']                     = $('#description').val();
    newJson['hint']                            = $('#hint').val();
    newJson['forced']                          = String($('#forced').val());
    newJson['visible']                         = String($('#visible').val());
    newJson['visiblity_related_field_id_code'] = $('#visiblity_related_field_id_code').val();
    newJson['visible_if_field_value_code']     = $('#visible_if_field_value_code').val();
    newJson['visible_if_field_value_text']     = $('#visible_if_field_value_text').val();
    newJson['align']                           = String($('#align').val());
    newJson['minchar']                         = ($('#minchar').val()=="")?"0":String($('#minchar').val());
    newJson['maxchar']                         = ($('#maxchar').val()=="")?"0":String($('#maxchar').val());
    newJson['minint']                          = String($('#minint').val());
    newJson['maxint']                          = String($('#maxint').val());
    newJson['lines']                           = ($('#lines').val()=="")?"0":String($('#lines').val());
    newJson['multiple_choice']                 = "0";
    
    if(type == "number2") newJson['conditional_operator'] = $('#conditional_operator').val();
    else newJson['conditional_operator'] = "off";
    
    newJson['allowed_format']                  = $('#allowed_format').val();
    newJson['max_size']                        = ($('#max_size').val()=="")?"1":String($('#max_size').val());
    newJson['val']                             = null;

    if(type == "map_location") {
        newJson['default_value'] = $('#default_value').val();
        newJson['get_user_location'] = $('#get_user_location').val();
    }else{
        newJson['default_value'] = "";
        newJson['get_user_location'] = "0";
    }

    if(type == "number" || type == "number2") {
        newJson['plus_minus_control_btns'] = $('#plus_minus_control_btns').val();
    }else{
        newJson['plus_minus_control_btns'] = "0";
    }

    BigJson[json_pos] = newJson;

    let finalRes = JSON.stringify(BigJson, null, 2);

    let _toSave = {
        id: _form_id,
        data: finalRes
    }

    //console.log("new title:"  + $('#title').val());

    $('#form_json_text_area').val(finalRes);

    $.ajax({
        type: "POST",
        url: mpPanelBaseUrl + "/update_form_json",
        data: _toSave,
        timeout: 25000,
        cache: false,
        success: function (data) {
            if (data == "ok") {
                notyf.success("ذخیره انجام شد");
                $('#end-of-form-block-editor').trigger('click');
            } else {
                notyf.error(data);
            }
        },
        error: function(e) {
            notyf.error('Error: ' + e.responseText);
        }
    });
}

function buildFormJsonNonTextTypeAndSave(type) {

    let fullJsonString = $('#form_json_area').val();
    let json_pos       = $('#json_pos').val();
    let _form_id       = $('#id').val();

    fullJsonString = convertStringToJsonArrayEmptyStringIfNull(fullJsonString); 
        
    let BigJson = JSON.parse(fullJsonString);

    let val_data = $('#val_data').val();

    if(
        (!val_data) ||
        (val_data.trim() == '') ||
        (val_data.trim() == "") ||
        (val_data.trim() == "null") ||
        (val_data.trim() == "undefined") ||
        (val_data.trim() == null)
        ) val_data = "[]";

    let newJson = {};

    newJson['id_code']                         = $('#id_code').val();
    newJson['type']                            = type;
    newJson['title']                           = $('#title').val();
    newJson['description']                     = $('#description').val();
    newJson['hint']                            = "";
    newJson['forced']                          = String($('#forced').val());
    newJson['visible']                         = String($('#visible').val());
    newJson['visiblity_related_field_id_code'] = $('#visiblity_related_field_id_code').val();
    newJson['visible_if_field_value_code']     = $('#visible_if_field_value_code').val();
    newJson['visible_if_field_value_text']     = $('#visible_if_field_value_text').val();
    newJson['align']                           = "rtl";
    newJson['minchar']                         = "0";
    newJson['maxchar']                         = "0";
    newJson['minint']                          = String($('#minint').val());
    newJson['maxint']                          = String($('#maxint').val());
    newJson['lines']                           = "0";
    newJson['multiple_choice']                 = String($('#multiple_choice').val());
    newJson['conditional_operator']            = $('#conditional_operator').val();
    newJson['allowed_format']                  = "png,jpg,jpeg";
    newJson['max_size']                        = "1";
    newJson['val']                             = JSON.parse(val_data);
    newJson['default_value']                   = "";
    newJson['get_user_location']               = "0";
    newJson['plus_minus_control_btns']         = "0";

    BigJson[json_pos] = newJson;

    let finalRes = JSON.stringify(BigJson, null, 2);

    let _toSave = {
        id: _form_id,
        data: finalRes
    }

    //console.log("finalRes:" + finalRes);

    $('#form_json_text_area').val(finalRes);

    $.ajax({
        type: "POST",
        url: mpPanelBaseUrl + "/update_form_json",
        data: _toSave,
        timeout: 25000,
        cache: false,
        success: function (data) {
            if (data == "ok") {
                notyf.success("ذخیره انجام شد");
                $('#end-of-form-block-editor').trigger('click');
                //console.log("test1");
            } else {
                notyf.error(data);
            }
        },
        error: function(e) {
            notyf.error('Error: ' + e.responseText);
        }
    });
}


function formAddItemByTypeConfirm(type) {

    let dialog_id = "#form_field_adder_dialog";
    $(dialog_id).fadeOut('fast');
    $('#dialog-holder').find(dialog_id).remove();
    $("html").css("overflow", "auto");

    Swal.fire({
        title: 'از افزودن این فیلد مطمئن هستید؟',
        text: '',
        icon: '',
        showCancelButton: true,
        confirmButtonColor: '#007bff',
        cancelButtonColor: '#909090',
        confirmButtonText: 'بله',
        cancelButtonText: 'انصراف'
    }).then((result) => {
        if (result.isConfirmed) {
            switch(type){
                case 'text':
                case 'phone':
                case 'email':
                case 'number':
                case 'number2':
                case 'date_fa':
                case 'date_en':
                case 'clock':
                case 'password':
                case 'file':
                case 'province_city':
                case 'map_location':
                    buildNewEmptyFieldFormJsonTextTypeAndSave(type);
                    break;     
                case 'select':      
                case 'checkbox':
                case 'select2':   
                case 'checkbox2':
                    buildNewEmptyFieldFormJsonNonTextTypeAndSave(type);
                    break;                
            }
        }
    });

}

function getEmptyFormIconNoteHtml() {

    emptyIconHtml = '';
    emptyIconHtml += '<div class="bnpb-card-item-empty">';
    emptyIconHtml += '<img class="bcie-img" src="'+mpPanelBaseUrl+'/core/_dist/img/empty_page_icon.png">';
    emptyIconHtml += '<span class="bcie-title">این فرم خالی است</span>';
    emptyIconHtml += '<span class="bcie-desc-wrapper">';
    emptyIconHtml += '<span>با کلیک بروی + افزودن فیلد جدید</span>';
    emptyIconHtml += '<span>اولین فیلد فرم خود را ایجاد کنید</span>';
    emptyIconHtml += '</span>';
    emptyIconHtml += '</div>';

    return emptyIconHtml;
}

function FormListItemsMotherAction(){

    //console.log("test");

    if($('#sortable_field_form_list')[0]){

        let bigJson = $('#form_json_text_area').val();

        //console.log("bigJson: " + bigJson);

        if((!bigJson) || (bigJson.trim() == '') || (bigJson.trim() == "") ||
            (bigJson.trim() == "null") || (bigJson.trim() == "undefined") ||
            (bigJson.trim() == null)){
                bigJson = "[]";
            }
    
        let BigJson = JSON.parse(bigJson);
        let item_index = 0;
        let formid = $('#id').val();
        let formNature = $('#nature').val();
        let html = '';

        $('#sortable_field_form_list').empty();

        if (Array.isArray(BigJson) && BigJson.length === 0) {

            html += getEmptyFormIconNoteHtml();
        
        } else {

            BigJson.forEach(function(item) {

                let feild_title = item['title'];
                if(feild_title == "") feild_title = '<span class="tnem">عنوان وارد نشده</span>';
                
                let options = "";
                if(item['type'] == "checkbox" || item['type'] == "select" || item['type'] == "select2" || item['type'] == "checkbox2"){
                    options = '<div class="form-array-items-box">';
                    item['val'].forEach(function(it) {
                        if(item['type'] == "checkbox2" || item['type'] == "select2"){
                            let cond_val = "";
                            if(item['conditional_operator'] != "off" && it['cond_val'] != ""){
                                cond_val = '<span class="copval">'+it['cond_val']+'</span>';
                            }
                            options += '<span class="faibitem"><span>'+it['text']+'</span>'+cond_val+'</span>';
                        }else{
                            options += '<span class="faibitem"><span>'+it+'</span></span>';
                        }
                    });
                    options += '</div>';
                }

                let visibility_status = "";
                if(item['visible'] == 0){
                    visibility_status = '<span class="visibility-status-none"><i class="ph ph-eye-slash"></i>عدم نمایش فیلد</span>';
                }else if (item['visible'] == 2){
                    
                    let relatedField = BigJson.find(field => field.id_code === item['visiblity_related_field_id_code']);
                    let relatedFieldTitle = relatedField ? relatedField.title : "Unknown";

                    let relatedValue = relatedField && relatedField.val ? 
                        relatedField.val.find(value => value.item_code === item['visible_if_field_value_code']) : null;
                    let relatedValueText = relatedValue ? relatedValue.text : "Unknown";

                    visibility_status += '<span class="visibility-status-cond">';
                    visibility_status += '<i class="ph ph-eye"></i>';
                    visibility_status += '<span class="vscp1">نمایش اگر فیلد</span>';
                    visibility_status += '<span class="vscp2">'+relatedFieldTitle+'</span>';
                    visibility_status += '<span class="vscp3">برابر بود با</span>';
                    visibility_status += '<span class="vscp4">'+relatedValueText+'</span>';
                    visibility_status += '</span>';

                }

                let cond_operator = "";
                if(item['conditional_operator'] == "add"){
                    cond_operator = '<span class="conditional-operator-box"><i class="ph ph-math-operations"></i>عملگر: جمع</span>';
                }else if(item['conditional_operator'] == "multiply"){
                    cond_operator = '<span class="conditional-operator-box"><i class="ph ph-math-operations"></i>عملگر: ضرب</span>';
                }else if(item['conditional_operator'] == "dual"){
                    cond_operator = '<span class="conditional-operator-box"><i class="ph ph-math-operations"></i>عملگر: ضرب‌وجمع</span>';
                }

                let forced = "";
                if(item['forced'] == "1") forced = '<i class="form-f-forced ph ph-asterisk"></i>';

                html += '<div class="ar-post-body-items ar-form-items card-json-item">';
                html += '<div class="form-items-inner rtl">';

                html += '<div class="fii-data">';
                html += '<div class="my-handle"><i class="ph ph-caret-up-down"></i></div>';
                html += '<span class="row_form_type_text">'+getFormItemName(item['type'])+'</span>';
                html += '<div class="fii-data-titles-options"><div class="fii-data-titles">';
                html += '<div class="fiparent">';
                html += '<span class="fdttm">'+ feild_title + forced +'</span>';
                html += visibility_status;
                html += '</div>';
                html += '<div class="foparent">';
                html += cond_operator + options;
                html += '</div>';
                html += '</div></div>';
                html += '<textarea style="display:none" class="form-control json_text_area" rows="4">'+JSON.stringify(item)+'</textarea>';
                html += '</div>';

                html += '<div class="fii-tools">';
                html += '<button type="button" class="delete_form_body_json_field btn edit-small-btn3 btn-danger-light2"><i class="ph ph-trash"></i></button>';
                let editorFileName = getEditorFileNameByKey(item['type']);
                html += '<button type="button" class="edit-form-block btn edit-small-btn3 btn-primary-light2" data-index="'+item_index+'" data-form-id="'+formid+'" data-form-nature="'+formNature+'" data-file-name="'+editorFileName+'" data-url="'+mpPanelBaseUrl+'/form-block-editor/'+formid+'/'+formNature+'/'+item_index+'/'+editorFileName+'"><i class="ph ph-pencil"></i></button>';
                html += '</div>';

                html += '</div>';
                html += '</div>';

                item_index = item_index+1;
                
            });

        }

        $('#sortable_field_form_list').append(html);

    }
}



$(function () { // start of document ready:

    FormListItemsMotherAction();

    $('.edit-form-block').click(function () {
        
        let index = $(this).attr('data-index');
        //reset block-add/modify-position:
        //$('#block-add-or-modify-position').attr('data-pos',index);
        let url = $(this).attr('data-url');
        openFormBlockEditor(url);
        
    });
        
    $('#sortable_field_form_list').sortable({
        group: 'list',
        animation: 200,
        delay: 100, // time in milliseconds to define when the sorting should start
        delayOnTouchOnly: true, // only delay if user is using touch
        handle: ".my-handle", // Drag handle selector within list items
        ghostClass: 'ghost',
        onSort: reportFormSortableChange
    });
    
    $('.delete_form_body_json_field').click(function () {
        Swal.fire({
            title: 'از حذف این فیلد مطمئن هستید؟',
            text: 'این فرایند غیر قابل بازگشت است',
            icon: '',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#007bff',
            confirmButtonText: 'حذف فیلد',
            cancelButtonText: 'انصراف'
        }).then((result) => {
            if (result.isConfirmed) {
                $(this).parent().parent().parent().remove();
                WriteFormJsonListToDataBase('حذف انجام شد');
            }
        })
    });
    
    $('#visible').on('change', function () {
        const value = $(this).val();
        if (value == '2') {
            $('#relation-visibility-box').slideDown();
        } else {
            $('#relation-visibility-box').slideUp();
        }
    });

    $('#visiblity_related_field_id_code').on('change', function () {

        let valsJs = $('#all_relation_ready_fields_values').val();
        if((!valsJs) || (valsJs.trim() == '') || (valsJs.trim() == "") ||
            (valsJs.trim() == "null") || (valsJs.trim() == "undefined") ||
            (valsJs.trim() == null)){
                valsJs = "[]";
            }
    
        let all_relation_ready_fields_values = JSON.parse(valsJs);
        const newKey = $(this).val();

        const options = all_relation_ready_fields_values[newKey];

        // Clear the current options in the select input
        const select = $('#visible_if_field_value_code');
        select.empty();

        if (options) {
            for (const [value, text] of Object.entries(options)) {
                select.append(new Option(text, value));
            }
        } else {
            $select.append(new Option('گزینه‌ای وجود ندارد', ''));
        }

    });
    
    $('#form_json_field_save').click(function () {
        
        let type = $(this).data("type");

        Swal.fire({
            title: 'از ذخیره این فیلد و گزینه‌ها مطمئن هستید؟',
            text: '',
            icon: '',
            showCancelButton: true,
            confirmButtonColor: '#007bff',
            cancelButtonColor: '#909090',
            confirmButtonText: 'بله',
            cancelButtonText: 'انصراف'
        }).then((result) => {
            if (result.isConfirmed) {
               
                switch(type){
                    case 'text':
                    case 'phone':
                    case 'email':
                    case 'number':
                    case 'number2':
                    case 'date_fa':
                    case 'date_en':
                    case 'clock':
                    case 'password':  
                    case 'file':
                    case 'province_city':
                    case 'map_location':
                        buildFormJsonTextTypeAndSave(type);
                        break;       
                    case 'select':     
                    case 'select2':     
                    case 'checkbox':
                    case 'checkbox2':
                        buildFormJsonNonTextTypeAndSave(type);
                        break;              
                }

                //nonTextOptionSave();

            }
        }) 
    });

}); //end of jqury doc ready

