"use strict";
jQuery(document).ready(function(){
    jQuery('span.wpaiomatic-delete').on('click', function(){
        var confirm_delete = confirm('Delete This Rule?');
        if (confirm_delete) {
            jQuery(this).parent().parent().remove();
            jQuery('#myForm').submit();						
        }
    });
});
var unsaved = false;
jQuery(document).ready(function () {
    jQuery(":input").on('change', function(){
        if(this !== undefined)
        {
            var classes = this.className;
            var classes = this.className.split(' ');
            var found = jQuery.inArray('actions', classes) > -1;
            if(this.id != 'select-shortcode' && this.id != 'PreventChromeAutocomplete' && this.id != 'editor_select_template' && this.className != 'sc_chat_form_field_prompt_text' && this.id != 'actions' && this.className != 'codemainfzr' && this.className != 'aiomatic_rule_select' && this.className != 'aiomatic_rule_select_box' && !found)
            {
                unsaved = true;
            }
        }
    });
    function unloadPage(){ 
        if(unsaved){
            return "You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?";
        }
    }
    window.onbeforeunload = unloadPage;
});

function deletePostsManual(number, type, typeId, uniquid, bulk = false, doneCallback = null)
{
    if (bulk || confirm("Are you sure you want to delete all posts generated by this rule?") == true) {
        const img = document.getElementById("run_img" + number);
        if (img) {
            img.style.visibility = "visible";
            img.src= mycustomsettings.plugin_dir_url + "images/running.gif";
        }
        var data = {
            action: 'aiomatic_my_action',
            id: uniquid,
            how: type,
            type: typeId,
            nonce: mycustomsettings.nonce
        };
        jQuery.post(mycustomsettings.ajaxurl, data, function(response) {
            if(response.trim() == 'ok')
            {
                document.getElementById("run_img" + number).src= mycustomsettings.plugin_dir_url + "images/ok.gif";
            }
            else
            {
                if(response.trim() == 'nochange')
                {
                    document.getElementById("run_img" + number).src= mycustomsettings.plugin_dir_url + "images/nochange.gif";
                }
                else
                {
                    document.getElementById("run_img" + number).src= mycustomsettings.plugin_dir_url + "images/failed.gif";
                }
            }
            if(doneCallback) doneCallback();
        }).fail( function(xhr) 
        {
            console.log('Error occured in processing: ' + xhr.statusText + ' - please check plugin\'s \'Activity and Logging\' menu for details.');
            document.getElementById("run_img" + number).src= mycustomsettings.plugin_dir_url + "images/failed.gif";
            if(doneCallback) doneCallback();
        });
    } else {
        if(doneCallback) doneCallback();
        return;
    }
}
function myAIGetDateTime() {
    var now     = new Date(); 
    var year    = now.getFullYear();
    var month   = now.getMonth()+1; 
    var day     = now.getDate();
    var hour    = now.getHours();
    var minute  = now.getMinutes();
    var second  = now.getSeconds(); 
    if(month.toString().length == 1) {
         month = '0'+month;
    }
    if(day.toString().length == 1) {
         day = '0'+day;
    }   
    if(hour.toString().length == 1) {
         hour = '0'+hour;
    }
    if(minute.toString().length == 1) {
         minute = '0'+minute;
    }
    if(second.toString().length == 1) {
         second = '0'+second;
    }   
    var dateTime = year+'-'+month+'-'+day+' '+hour+':'+minute+':'+second;   
     return dateTime;
}
function runNowManual(number, typeId, bulk = false, doneCallback = null)
{
    if (bulk || confirm("Are you sure you want to run this rule now?") == true) {
        const img = document.getElementById("run_img" + number);
        if (img) {
            img.style.visibility = "visible";
            img.src= mycustomsettings.plugin_dir_url + "images/running.gif";
        }
        var data = {
            action: 'aiomatic_run_my_action',
            id: number,
            type: typeId,
            nonce: mycustomsettings.nonce
        };
        var pollingInterval;
        function startPolling() {
            pollingInterval = setInterval(function() 
            {
                jQuery.get(mycustomsettings.ajaxurl, { action: 'aiomatic_check_process_status', nonce: mycustomsettings.bulk_nonce }, function(response) 
                {
                    if (response.status === 'success') 
                    {
                        var datetime = myAIGetDateTime();
                        jQuery('#running_status_ai').html('<hr/><b>Activity Log:</b><br/><br/>' + datetime + ':<br/> ' + response.msg);
                    }
                    else
                    {
                        console.log('Failed to poll results: ' + response);
                        clearInterval(pollingInterval);
                    }
                }).fail(function(xhr) 
                {
                    clearInterval(pollingInterval);
                    console.log('Exception in results polling: ' + JSON.stringify(xhr));
                });
            }, 3000);
        }
        jQuery.post(mycustomsettings.ajaxurl, data, function(response) {
            if(response.trim() == 'ok')
            {
                document.getElementById("run_img" + number).src= mycustomsettings.plugin_dir_url + "images/ok.gif";
            }
            else
            {
                if(response.trim() == 'nochange')
                {
                    document.getElementById("run_img" + number).src= mycustomsettings.plugin_dir_url + "images/nochange.gif";
                }
                else
                {
                    document.getElementById("run_img" + number).src= mycustomsettings.plugin_dir_url + "images/failed.gif";
                }
            }
            if(mycustomsettings.more_logs == '1')
            {
                clearInterval(pollingInterval);
            }
            if(doneCallback) doneCallback();
        }).fail( function(xhr) 
        {
            console.log('Error occured in processing: ' + xhr.statusText + ' - please check plugin\'s \'Activity and Logging\' menu for details.');
            document.getElementById("run_img" + number).src= mycustomsettings.plugin_dir_url + "images/failed.gif";
            if(mycustomsettings.more_logs == '1')
            {
                clearInterval(pollingInterval);
            }
            if(doneCallback) doneCallback();
        });
        if(mycustomsettings.more_logs == '1')
        {
            startPolling();
        }
    } else {
        if(doneCallback) doneCallback();
        return;
    }
}

function duplicatePostsManual(number, type, typeId, bulk = false, doneCallback = null)
{
    console.log(number + ' ' + type+ ' ' + typeId + ' ' + bulk);
    if (bulk || confirm("Are you sure you want to duplicate this rule?") == true) {
        const img = document.getElementById("run_img" + number);
        if (img) {
            img.style.visibility = "visible";
            img.src= mycustomsettings.plugin_dir_url + "images/running.gif";
        }
        var data = {
            action: 'aiomatic_my_action',
            id: number,
            how: type,
            type: typeId,
            nonce: mycustomsettings.nonce
        };
        jQuery.post(mycustomsettings.ajaxurl, data, function(response) {
            if(response.trim() == 'ok')
            {
                document.getElementById("run_img" + number).src= mycustomsettings.plugin_dir_url + "images/ok.gif";
            }
            else
            {
                if(response.trim() == 'nochange')
                {
                    document.getElementById("run_img" + number).src= mycustomsettings.plugin_dir_url + "images/nochange.gif";
                }
                else
                {
                    document.getElementById("run_img" + number).src= mycustomsettings.plugin_dir_url + "images/failed.gif";
                }
            }
            if(doneCallback) doneCallback();
        }).fail( function(xhr) 
        {
            console.log('Error occured in processing: ' + xhr.statusText + ' - please check plugin\'s \'Activity and Logging\' menu for details.');
            document.getElementById("run_img" + number).src= mycustomsettings.plugin_dir_url + "images/failed.gif";
            if(doneCallback) doneCallback();
        });
    } else {
        if(doneCallback) doneCallback();
        return;
    }
}
function bulkToggleRules(ids, state, typeId)
{
    jQuery.post(mycustomsettings.ajaxurl,{
        action: 'aiomatic_toggle_rules_bulk',
        ids: ids,
        type: typeId,
        state: state,
        nonce: mycustomsettings.nonce
    }, function(){
        location.reload();
    });
}
function movePostOrder(number, selectedValue, type, typeId, doneCallback = null)
{
    const img = document.getElementById("run_img" + number);
    if (img) {
        img.style.visibility = "visible";
        img.src= mycustomsettings.plugin_dir_url + "images/running.gif";
    }
    var data = {
        action: 'aiomatic_my_action_move',
        id: number,
        how: selectedValue,
        type: type,
        nonce: mycustomsettings.nonce
    };
    jQuery.post(mycustomsettings.ajaxurl, data, function(response) {
        if(response.trim() == 'ok')
        {
            document.getElementById("run_img" + number).src= mycustomsettings.plugin_dir_url + "images/ok.gif";
        }
        else
        {
            if(response.trim() == 'nochange')
            {
                document.getElementById("run_img" + number).src= mycustomsettings.plugin_dir_url + "images/nochange.gif";
            }
            else
            {
                document.getElementById("run_img" + number).src= mycustomsettings.plugin_dir_url + "images/failed.gif";
            }
        }
        if(doneCallback) doneCallback();
    }).fail( function(xhr) 
    {
        console.log('Error occured in processing: ' + xhr.statusText + ' - please check plugin\'s \'Activity and Logging\' menu for details.');
        document.getElementById("run_img" + number).src= mycustomsettings.plugin_dir_url + "images/failed.gif";
        if(doneCallback) doneCallback();
    });
}
function eraseManual(number, bulk = false, doneCallback = null)
{
    if (bulk || confirm("Are you sure you want to erase processed keywords by this rule?") == true) {
        const img = document.getElementById("run_img" + number);
        if (img) {
            img.style.visibility = "visible";
            img.src= mycustomsettings.plugin_dir_url + "images/running.gif";
        }
        var data = {
            action: 'aiomatic_erase_action',
            id: number,
            nonce: mycustomsettings.nonce
        };
        jQuery.post(mycustomsettings.ajaxurl, data, function(response) {
            if(response.trim() == 'ok')
            {
                document.getElementById("run_img" + number).src= mycustomsettings.plugin_dir_url + "images/ok.gif";
            }
            else
            {
                if(response.trim() == 'nochange')
                {
                    document.getElementById("run_img" + number).src= mycustomsettings.plugin_dir_url + "images/nochange.gif";
                }
                else
                {
                    document.getElementById("run_img" + number).src= mycustomsettings.plugin_dir_url + "images/failed.gif";
                }
            }
            if(doneCallback) doneCallback();
        }).fail( function(xhr) 
        {
            console.log('Error occured in processing: ' + xhr.statusText + ' - please check plugin\'s \'Activity and Logging\' menu for details.');
            document.getElementById("run_img" + number).src= mycustomsettings.plugin_dir_url + "images/failed.gif";
            if(doneCallback) doneCallback();
        });
    } else {
        if(doneCallback) doneCallback();
        return;
    }
}
function go_change_cats(sel, which)
{
    var postType = sel && sel.value ? sel.value : 'post';
    var $select  = jQuery('#default_category' + which);
    $select.prop('disabled', true);
    var prevSelected = $select.val() || [];
    jQuery.post(
        mycustomsettings.ajaxurl,
        {
            action: 'aiomatic_get_terms',
            nonce: mycustomsettings.nonce,
            post_type: postType
        }
    ).done(function(resp) {
        $select.empty();
        $select.append(
            jQuery('<option/>', {
                value: 'aiomatic_no_category_12345678',
                text: 'Do Not Add a Category',
                selected: prevSelected.length === 0 || prevSelected.includes('aiomatic_no_category_12345678')
            })
        );
        if (resp && resp.success && Array.isArray(resp.data)) {
            resp.data.forEach(function(t) {
                $select.append(
                    jQuery('<option/>', {
                        value: String(t.id),
                        text: t.name + ' - ID ' + t.id,
                        selected: prevSelected.includes(String(t.id))
                    })
                );
            });
        }
    }).always(function() {
        $select.prop('disabled', false);
        $select.trigger('change');
    });
}
function actionsChangedManual(ruleId, selectedValue, typeId, uniquid)
{
    if (selectedValue==='run')
    {
        if(unsaved){
            alert("You have unsaved changes on this page. Please save your changes before manually running rules!");
            return;
        }
        runNowManual(ruleId, typeId);
    }
    else
    {
        if (selectedValue==='erase')
        {
            if(unsaved){
                alert("You have unsaved changes on this page. Please save your changes before manually erasing the rule keywords list!");
                return;
            }
            eraseManual(ruleId);
            location.reload();
        }
        else
        {
            if (selectedValue==='duplicate')
            {
                if(unsaved){
                    alert("You have unsaved changes on this page. Please save your changes before manually erasing the rule keywords list!");
                    return;
                }
                duplicatePostsManual(ruleId, 'duplicate', typeId);
                location.reload();
            }
            else
            {
                if (selectedValue==='up' || selectedValue==='down')
                {
                    if(unsaved){
                        alert("You have unsaved changes on this page. Please save your changes before manually erasing the rule keywords list!");
                        return;
                    }
                    movePostOrder(ruleId, selectedValue, typeId, uniquid);
                    location.reload();
                }
                else
                {
                    if (selectedValue==='trash')
                    {
                        deletePostsManual(ruleId, 'trash', typeId, uniquid);
                    }
                    else
                    {
                        deletePostsManual(ruleId, 'delete', typeId, uniquid);
                    }
                }
            }
        }
    }
}

jQuery(function($){

    $('#aiomatic_select_all_rules').on('change', function(){
        $('.aiomatic_rule_select').prop('checked', this.checked);
    });
    $('#aiomatic_apply_bulk').on('click', async function(){

        const action = $('#aiomatic_bulk_action').val();

        if(!action) return;

        if(unsaved){
            alert("Please save changes first.");
            return;
        }

        const selectedRules = $('.aiomatic_rule_select:checked')
            .map(function(){ return {
        id: $(this).attr('data-ruleid'),
        type: $(this).attr('data-type'),
        unique: $(this).attr('data-unique')
    }; }).get();

        if(!selectedRules.length){
            alert('No rules selected.');
            return;
        }

        if(!confirm('Execute bulk action on selected rules?'))
            return;

        if(action === 'activate' || action === 'deactivate')
        {
            const ids = selectedRules.map(r => r.id);

            bulkToggleRules(
                ids,
                action === 'activate' ? 1 : 0,
                selectedRules[0].type
            );

            return;
        }
        if(action === 'deleterule')
        {
            const ids = selectedRules.map(r => r.id);

            deleteRulesBulkManual(
                ids,
                selectedRules[0].type
            );

            return;
        }
        await runBulkSequential(selectedRules, action);
        return;
    });

});
async function runBulkSequential(rules, action)
{
    for(const rule of rules)
    {
        await executeRuleActionAsync(
            rule.id,
            action,
            rule.type,
            rule.unique
        );
    }

    location.reload();
}
function executeRuleActionAsync(ruleId, action, typeId, uniquid)
{
    return new Promise((resolve) => {

        switch(action)
        {
            case 'run':
                runNowManual(ruleId, typeId, true, resolve);
            break;

            case 'erase':
                eraseManual(ruleId, true, resolve);
            break;

            case 'duplicate':
                duplicatePostsManual(ruleId,'duplicate',typeId,true,resolve);
            break;

            case 'up':
            case 'down':
                movePostOrder(ruleId, action, typeId, uniquid, resolve);
            break;

            case 'trash':
                deletePostsManual(ruleId,'trash',typeId,uniquid,true,resolve);
            break;

            case 'delete':
                deletePostsManual(ruleId,'delete',typeId,uniquid,true,resolve);
            break;

            default:
                resolve();
        }

    });
}
function deleteRulesBulkManual(ids, typeId)
{
    jQuery.post(mycustomsettings.ajaxurl,{
        action: 'aiomatic_delete_rules_bulk',
        ids: ids,
        type: typeId,
        nonce: mycustomsettings.nonce
    }, function(response){

        if(response.trim() === 'ok')
            location.reload();
        else
            alert('Failed deleting rules.');

    }).fail(function(){
        alert('Ajax error while deleting rules.');
    });
}
function productSourceChanged(ruleid)
{
    var selected = jQuery('#product_source' + ruleid).val();
    if(selected == '' || selected == null || selected == 'amazon')
    {
        jQuery('.ai-amazon' + ruleid).show();
        jQuery('.ai-clickbank' + ruleid).hide();
    }
    else
    {
        jQuery('.ai-amazon' + ruleid).hide();
        jQuery('.ai-clickbank' + ruleid).show();
    }
}
function productSourceChangedSingle()
{
    var selected = jQuery('#product_source3').val();
    if(selected == '' || selected == null || selected == 'amazon')
    {
        jQuery('.ai-amazon').show();
        jQuery('.ai-clickbank').hide();
    }
    else
    {
        jQuery('.ai-amazon').hide();
        jQuery('.ai-clickbank').show();
    }
}
function productSourceChangedReview()
{
    var selected = jQuery('#product_source4').val();
    if(selected == '' || selected == null || selected == 'amazon')
    {
        jQuery('.ai-amazon4').show();
        jQuery('.ai-clickbank4').hide();
    }
    else
    {
        jQuery('.ai-amazon4').hide();
        jQuery('.ai-clickbank4').show();
    }
}
function assistantSelected(ruleid)
{
    var selected = jQuery('#assistant_id' + ruleid).val();
    if(selected == '' || selected == null)
    {
        jQuery('.hideAssistant' + ruleid).find('option').removeAttr('disabled');
    }
    else
    {
        var selectElement = jQuery('.hideAssistant' + ruleid);
        var selectedValue = selectElement.val();
        jQuery('.hideAssistant' + ruleid).find('option').attr('disabled', 'disabled');
        selectElement.find('option[value="' + selectedValue + '"]').removeAttr('disabled');
    }
}
jQuery(document).ready(function() {
    
    jQuery('.aiomatic_image_button').on('click', function(){
        tb_show('',"media-upload.php?type=image&TB_iframe=true");
        window.send_to_editor = function(html) {
            var url = jQuery(html).attr('src');
            jQuery('#cr_input_box').val(url);
            tb_remove();
        };
    });
});
function thisonChangeHandler(cb) {
if(cb.checked == true)
{
    jQuery("input.activateDeactivateClass:checkbox").each( function () {
        jQuery(this).prop('checked', true);
    });
}
else
{
    jQuery("input.activateDeactivateClass:checkbox").each( function () {
        jQuery(this).prop('checked', false);
    });
}
}
var codemodalfzr = document.getElementById('mymodalfzr');
var btn = document.getElementById("mybtnfzr");
var span = document.getElementById("aiomatic_close");
var ok = document.getElementById("aiomatic_ok");
if(btn != null)
{
    btn.onclick = function() {
        codemodalfzr.style.display = "block";
    }
}
if(span != null)
{
    span.onclick = function() {
        codemodalfzr.style.display = "none";
    }
}
if(ok != null)
{
    ok.onclick = function() {
        codemodalfzr.style.display = "none";
    }
}
var codemodalauto = document.getElementById('mymodalauto');
var btn = document.getElementById("mybtnauto");
var span = document.getElementById("aiomatic_auto_close");
var ok = document.getElementById("aiomatic_auto_ok");
if(btn != null)
{
    btn.onclick = function() {
        codemodalauto.style.display = "block";
    }
}
if(span != null)
{
    span.onclick = function() {
        codemodalauto.style.display = "none";
    }
}
if(ok != null)
{
    ok.onclick = function() {
        codemodalauto.style.display = "none";
    }
}
window.onclick = function(event) {
    if (codemodalauto != null && event.target == codemodalauto) {
        codemodalauto.style.display = "none";
    }
    else if (event.target == codemodalfzr) {
        codemodalfzr.style.display = "none";
    }
}
jQuery("#myForm").on('submit', function (e) {
    jQuery(this).on('submit', function() {
        return false;
    });

    e.preventDefault();
    var changedCheckboxes = [];

    var this_master = jQuery(this);
    jQuery('button[type=submit], input[type=submit]').prop('disabled',true);
    this_master.find('input[type="checkbox"]').each( function () {
        var checkbox_this = jQuery(this);

        if (
            checkbox_this.attr("id") !== "exclusion" &&
            checkbox_this.closest('.aiomatic-workspace-grid').length === 0
        )
        {
            if( checkbox_this.is(":checked") == true ) {
                checkbox_this.attr('value','1');
            } else {
                checkbox_this.prop('checked',true);  
                checkbox_this.attr('value','0');
                changedCheckboxes.push(checkbox_this);
            }
        }
    });
    if (typeof mycustomsettings.max_input_vars !== 'undefined' && jQuery('input, textarea, select, button').length >= mycustomsettings.max_input_vars) {
        this_master.append("<span style='color:red;'>Saving settings, please wait...</span>");
        var coderevolution_max_input_var_data = this_master.serialize();
        this_master.find("table").remove();
        this_master.append("<input type='hidden' class='coderevolution_max_input_var_data' name='coderevolution_max_input_var_data'/>");
        this_master.find("input.coderevolution_max_input_var_data").val(coderevolution_max_input_var_data);
    }
    setTimeout(() => {
        this.submit();
        changedCheckboxes.forEach(function(item) {
            item.prop('checked', false);
        });
    }, 10);
});
function createAdmin(i) {
    var modals = [];
    var btns = [];
    var spans = [];
    var oks = [];
    var btns = [];
    modals = document.getElementById("mymodalfzr" + i);
    btns = document.getElementById("mybtnfzr" + i);
    spans = document.getElementById("aiomatic_close" + i);
    oks = document.getElementById("aiomatic_ok" + i);
    btns.onclick = function(e) {
        modals.style.display = "block";
    }
    spans.onclick = function(e) {
        modals.style.display = "none";
    }
    oks.onclick = function(e) {
        modals.style.display = "none";
    }
    modals.addEventListener("click", function(e) {
        if (e.target !== this)
            return;
        modals.style.display = "none";
    }, false);
}