"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' && !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)
{
    if (confirm("Are you sure you want to delete all posts generated by this rule?") == true) {
        document.getElementById("run_img" + number).style.visibility = "visible";
        document.getElementById("run_img" + number).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";
                }
            }
        }).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";
        });
    } else {
        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)
{
    if (confirm("Are you sure you want to run this rule now?") == true) {
        document.getElementById("run_img" + number).style.visibility = "visible";
        document.getElementById("run_img" + number).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);
            }
        }).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(mycustomsettings.more_logs == '1')
        {
            startPolling();
        }
    } else {
        return;
    }
}

function duplicatePostsManual(number, type, typeId)
{
    if (confirm("Are you sure you want to duplicate this rule?") == true) {
        document.getElementById("run_img" + number).style.visibility = "visible";
        document.getElementById("run_img" + number).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";
                location.reload();
            }
            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";
                }
            }
        }).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";
        });
    } else {
        return;
    }
}
function movePostOrder(number, selectedValue, type, typeId)
{
    document.getElementById("run_img" + number).style.visibility = "visible";
    document.getElementById("run_img" + number).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";
            location.reload();
        }
        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";
            }
        }
    }).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";
    });
}
function eraseManual(number)
{
    if (confirm("Are you sure you want to erase processed keywords by this rule?") == true) {
        document.getElementById("run_img" + number).style.visibility = "visible";
        document.getElementById("run_img" + number).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";
                location.reload();
            }
            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";
                }
            }
        }).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";
        });
    } else {
        return;
    }
}
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);
        }
        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);
            }
            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);
                }
                else
                {
                    if (selectedValue==='trash')
                    {
                        deletePostsManual(ruleId, 'trash', typeId, uniquid);
                    }
                    else
                    {
                        deletePostsManual(ruleId, 'delete', typeId, uniquid);
                    }
                }
            }
        }
    }
}
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")
        {
            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);
}