function add_sortable_item(parent, value, text){
    var check;
    check = jQuery('#'+ parent).find("div[data-text=" + value + "]");

    if(check.length === 0){
        jQuery('#'+ parent).append("<div class='sitem' data-text='"+ value +"'><span>" + text + "</span><div class='btn btn-danger btn-lg' onclick='remove_sitem(jQuery(this));'><span class='glyphicon glyphicon-trash'></span></div></div>");
    }
}

function add_sortable_item_list(parent, value, text, data_input, max){
    if (typeof max === 'undefined') {
        max = 0;
    }

    if (max > 0) {
        jQuery('#'+ parent).html("");
    }

    var check;
    check = jQuery('#'+ parent).find("div[data-text=" + value + "]");
    if(check.length === 0){
        jQuery('#'+ parent).append("<div class='sitem' data-text='"+ value +"'><span>" + text + "</span><div class='btn btn-danger btn-lg' onclick='remove_sitem_output(jQuery(this)," + data_input + ");'><span class='glyphicon glyphicon-trash'></span></div></div>");
    }

    set_list_values_output(parent,data_input);
}

function add_sortable_item_list_wflag(parent, value, text, data_input){
    var check;
    check = jQuery('#'+ parent).find("div[data-text=" + value + "]");

    if(check.length === 0){
        jQuery('#'+ parent).append("<div class='sitem' data-text='"+ value +"'><span><img src='/wp-content/plugins/ftm-geo-target/flags/" + value + ".png' /><span class='ftm-country-item'>"+value+"</span>" + text + "</span><div class='btn btn-danger btn-lg' onclick='remove_sitem_output(jQuery(this)," + data_input + ");'><span class='glyphicon glyphicon-trash'></span></div></div>");
    }

    set_list_values_output(parent,data_input);
}

function add_geovalue_to_container (ddl, txt, container, fieldid){
    var check;
    var ddl_value;
    var txt_value;

    ddl_value = jQuery("#"+ddl).val();
    txt_value = jQuery("#"+txt).val();
    check = jQuery('#'+ container).find("div[data-text=" + ddl_value + "]");

    //Prep work for valdidation
    jQuery("#"+txt).attr("placeholder","");

    if(txt_value === ""){
        jQuery("#"+txt).attr("placeholder","Value required");
        return false;
    }

    if(check.length === 0){
        //jQuery('#'+ container).append("<div class='gv_item' data-content='"+ txt_value +"' data-text='"+ ddl_value +"'><span><img src='/wp-content/plugins/ftm-geo-target/flags/" +ddl_value+ ".png' />" + txt_value + "</span><div class='btn btn-danger btn-lg' onclick='remove_gv_item_output(jQuery(this)," + fieldid + ");'><span class='glyphicon glyphicon-trash'></span></div></div>");
        jQuery('#'+ container)
            .append("<div class='gv_item' data-content='"+ txt_value +"' data-text='"+ ddl_value +"' data-fieldname='"+fieldid+"'><span><img src='/wp-content/plugins/ftm-geo-target/flags/" +ddl_value+ ".png' />"
                +"<span class='ftm-country-item'>"+ddl_value+"</span>"
                +"<textarea>" + txt_value + "</textarea>"
                +"<div class='btn btn-success btn-lg submit-geo-value'><span class='glyphicon glyphicon-save'></span></div>"
                +"<code class='textarea textarea-display'>" + txt_value + "</code>"
                +"</span>"
                +"<div class='btn btn-info btn-lg edit-geo-value geo-button-display'><span class='glyphicon glyphicon-edit'></span></div>"
                +"<div class='btn btn-danger btn-lg' onclick='remove_gv_item_output(jQuery(this)," + fieldid + ");'><span class='glyphicon glyphicon-trash'></span></div></div>");
    }

    set_json_text_value_to_imput(container, fieldid);
}

function set_geovalue_for_edit(e) {
    var parent = jQuery(this).parent();
    var display = parent.find('.textarea-display');
    var input = parent.find("textarea");
    var edit_button = parent.find(".edit-geo-value");
    var save_button = parent.find(".submit-geo-value");
    display.hide();
    input.show();
    edit_button.removeClass('geo-button-display');
    save_button.addClass('geo-button-display');
}

function set_geovalue_for_saving(e) {
    var parent = jQuery(this).parent().parent();
    var display = parent.find('.textarea-display');
    var input = parent.find("textarea");
    var edit_button = parent.find(".edit-geo-value");
    var save_button = parent.find(".submit-geo-value");
    var values_field_id = parent.data('fieldname');
    var parent_container_id = parent.parent().attr('id');
    var new_value = input.val();
    display.html(new_value);
    parent.attr('data-content', new_value);
    display.show();
    input.hide();
    edit_button.addClass('geo-button-display');
    save_button.removeClass('geo-button-display');
    set_json_text_value_to_imput(parent_container_id, values_field_id);
}

function set_json_text_value_to_imput(source, field){
    var values;

    values = new Array();
    jQuery('#' + source + ' .gv_item').each(function(){
        values.push(
            {
                "country" : jQuery(this).attr("data-text"),
                "value" : jQuery(this).attr("data-content")
            }
        )
    });

    var myJSON = JSON.stringify(values);
    jQuery('#' + field).val(myJSON);
    console.log(JSON.parse(myJSON));
}

function set_list_values_output(container, source){
    var values;

    values = "";
    jQuery('#' + container + ' .sitem').each(function(){
        values += jQuery(this).attr("data-text") + ",";
    });

    values = values.replace(/.$/,"");
    jQuery('#' + source).val(values);
}

function remove_gv_item_output(handler, source){
    var container;
    container = jQuery(handler).parent().parent().attr("id");

    jQuery(handler).parent().detach();
    set_json_text_value_to_imput(container,jQuery(source).attr("id"));
}

function remove_sitem(handler){
    jQuery(handler).parent().detach();
}

function remove_sitem_output(handler, source){
    var container;
    container = jQuery(handler).parent().parent().attr("id");

    jQuery(handler).parent().detach();
    set_list_values_output(container,jQuery(source).attr("id"));
}

function update_theme_preview(base_url, ddl,img_el){
    var img_new = jQuery("#" + img_el + "_new");
    var ddl = jQuery("#" + ddl + ' option:selected');
    var value = ddl.text();
    var src_new= img_new.attr('src').replace(/(\/.+\/)([a-z_-]+)(\/preview.png)/i, '$1'+value.replace(" ", "-")+'$3');
    img_new.attr("src",src_new);
}

function check_gruop_availability(group_name, current_group_id){
    var result;
    var service_url;
    result = true;

    service_url = ajaxurl;

    jQuery.ajax({
        type: "POST",
        url: service_url,
        async: false,
        data: {action:'check_group', gname : group_name, gid : current_group_id},
        success: function(data) {
            result = (data == 'true');
        }
    });

    return result;
}

function special_validation(form_id, current_group_id){

    var result;
    if(current_group_id != ''){
        result = check_gruop_availability( jQuery('#gname').val(), jQuery("#" + current_group_id).val());
    }
    else
    {
        result = check_gruop_availability( jQuery('#gname').val(), 0);
    }



    if(result == true){
        jQuery("#" + form_id).validate().showErrors({gname:"This group already exists."});
        return false;
    }
    else
    {
        jQuery("#" + form_id).submit();
    }
    return false;
}

function show_update_field_popup(field_id, field_value,field_type_value){
    jQuery("#update_option_form #optionId").val(field_id);
    jQuery("#update_option_form #uname").val(field_value);

    jQuery('#update_option_form select#ftmgeo_update_ftype option:selected').removeAttr("selected");
    jQuery("#update_option_form select#ftmgeo_update_ftype option[value="+field_type_value+"]").attr("selected", "selected");
}

function fill_confirm_popup_key_value(form_id, key_field_id,key_field_value){
    jQuery("#" + form_id  + " #" +key_field_id).val(key_field_value);
}

function showMediaUploader(e) {
    var attachment = null;
    var contrl_id =  jQuery(this).attr("id").replace("_button", "");

    // Create the media frame, if applicable.
    if (typeof custom_uploader === 'undefined' || custom_uploader === null) {
        //Extend the wp.media object
        custom_uploader = wp.media.frames.custom_uploader = wp.media({
            title: 'Choose Image',
            button: {
                text: 'Choose Image'
            },
            multiple: false
        });

        custom_uploader.on("select", function() {
            attachment = custom_uploader.state().get('selection').first().toJSON();
            jQuery('#' + contrl_id + '.upload_image').val(attachment.url);
            jQuery('#'+contrl_id+'_preview').html('<img src="' + attachment.url + '"/>');
            custom_uploader = null;
        });
    }


    custom_uploader.open();
}

jQuery(document).ready(function($){
    var custom_uploader;

    $('.upload_image_button').on("click", showMediaUploader);

    $('.multiselect').multiselect({keepRenderingSort: true});

    $(".sortable_list" ).sortable({
        update: function(event, ui){
            var containerid;
            var sourceid;

            containerid = $(this).attr("id");
            sourceid = containerid + "_list";

            if($("#" + sourceid).length > 0){
                set_list_values_output(containerid, sourceid);
            }
        }
    });

    $(".edit-geo-value").on("click", set_geovalue_for_edit);
    $(".submit-geo-value").on("click", set_geovalue_for_saving);

    $("#ddl_countries").chosen({disable_search_threshold: 10});
    $("#ddl_regions").chosen({disable_search_threshold: 10});
    $("#ddl_sites").bind('chosen:ready', function(c){
        var parent = $(this).parent();
        $(parent).parent().find('span').each(function(iter, element) {
            var text = element.innerHTML.replace(/\[/gi, '<em>').replace(/\]/gi, '</em>');
            element.innerHTML = text;
        });
    });
    $("#ddl_sites").bind('chosen:showing_dropdown', function(c){
        var parent = $(this).parent();
        $(parent).find('li').each(function(iter, element) {
            var text = element.innerHTML.replace(/\[/gi, '<em>').replace(/\]/gi, '</em>');
            element.innerHTML = text;
        });
    });
    $("#ddl_sites").bind('chosen:hiding_dropdown', function(c){
        var parent = $(this).parent();
        $(parent).parent().find('span').each(function(iter, element) {
            var text = element.innerHTML.replace(/\[/gi, '<em>').replace(/\]/gi, '</em>');
            element.innerHTML = text;
        });
    });
    $("#ddl_sites").chosen({disable_search_threshold: 10});
    $("#ddl_groups").bind('chosen:ready', function(c){
        var parent = $(this).parent();
        $(parent).parent().find('span').each(function(iter, element) {
            var text = element.innerHTML.replace(/\[/gi, '<em>').replace(/\]/gi, '</em>');
            element.innerHTML = text;
        });
    });
    $("#ddl_groups").bind('chosen:showing_dropdown', function(c){
        var parent = $(this).parent();
        $(parent).find('li').each(function(iter, element) {
            var text = element.innerHTML.replace(/\[/gi, '<em>').replace(/\]/gi, '</em>');
            element.innerHTML = text;
        });
    });
    $("#ddl_groups").bind('chosen:hiding_dropdown', function(c){
        var parent = $(this).parent();
        $(parent).parent().find('span').each(function(iter, element) {
            var text = element.innerHTML.replace(/\[/gi, '<em>').replace(/\]/gi, '</em>');
            element.innerHTML = text;
        });
    });
    $("#ddl_groups").chosen({disable_search_threshold: 10});
    $(".chosen_ddl").chosen({disable_search_threshold: 10});
    if($('#site_groups_list').length > 0){
        $('#site_groups_list').DataTable({
            columnDefs: [
                {targets: [-1], "searchable": false}
            ]
        });
    }
});

(() => {
    let current_paths = [];
    let template = ''

    const remove_from_paths = (remove_path) => {
        current_paths = current_paths.filter(path => path !== remove_path)
        re_render_paths()
    }
    const add_to_paths = (path) => {
        current_paths.push(path)
        re_render_paths()
    }
    const re_render_paths = () => {
        let content = ''
        if (document.getElementById("banned-affiliate-folder") && current_paths) {
            document.getElementById("banned-affiliate-folder").value = current_paths.join('/')
            current_paths.forEach(path => {
                content += replace_template(path)
            })
            document.getElementById("affiliate_folders-container").innerHTML = content
        }
    }
    const load_template = () => {
        let template_container = document.getElementById("affiliate-item-template")
        let template = ''
        if (template_container) {
            template = template_container.innerHTML
        }
        return template
    }
    const replace_template = (path) => {
        const regex = /{{path}}/ig;
        return template.replace(regex, path)
    }
    const remove_affiliate_path = (e) => {
        let old_path = e.target.getAttribute("data-path")
        if (old_path) {
            remove_from_paths(old_path)
        }
    }
    const add_affiliate_path = (e) => {
        e.preventDefault()
        e.stopPropagation()
        let new_path = document.getElementById("banned-affiliate-folder-input").value
        add_to_paths(new_path)
        document.getElementById("banned-affiliate-folder-input").value = ''
    }

    const setup_events = (e) => {
        let add_button = document.getElementById("affiliate-add-button")
        if (add_button) {
            add_button.addEventListener('click', add_affiliate_path)
        }
        document.addEventListener('click', remove_affiliate_path)
    }

    const setup_paths = () => {
        let input = document.getElementById("banned-affiliate-folder")
        if (input)  {
            let path_string = input.value
            current_paths = path_string.split('/')
        }
        template = load_template()
    }

    const init = () => {
        setup_paths()
        setup_events()
        re_render_paths()
    }

    init()
})();
