jQuery( document ).ready(function ($) {
//	$( '#maintenance_run_now_lnk' ).on('click', function () {
//		//     managemaintenance_selected_sites_init();
//		showMaintenanceTab( true, false, false, false, false );
//		return false;
//	});
//	$( '#maintenance_new_schedule_lnk' ).on('click', function () {
//		//      managemaintenance_selected_sites_init();
//		showMaintenanceTab( false, true, false, false, false );
//		return false;
//	});
	$( '#maintenance_schedules_lnk' ).on('click', function () {
		showMaintenanceTab( false, false, true, false, false );
		return false;
	});
	$( '#maintenance_edit_daily_lnk' ).on('click', function () {
		showMaintenanceTab( false, false, false, true, false );
		return false;
	});
	$( '#maintenance_404_alerts_lnk' ).on('click', function () {
		showMaintenanceTab( false, false, false, false, true );
		return false;
	});

	jQuery( '#maintenance-site-progress-close' ).on('click', function (event)
		{
		bulkTaskRunning = false;
		jQuery( '#maintenance-site-progress-box' ).dialog( 'destroy' );

		location.href = 'admin.php?page=Extensions-Mainwp-Maintenance-Extension';
		return false;
	});

	jQuery( '.maintenance_run_now' ).on('click', function (event)
		{
		if (jQuery( this ).attr( 'optimize-db' ) == 1) {
			if ( ! confirm( __( 'In rare cases, database optimization function can cause issues and crash database. Please confirm that you want to perform this action.' ) )) {
				return false; }
		}
		managemaintenance_trigger_run_now( jQuery( this ) );
		return false;
	});

	jQuery( '#maintenance_run_btn' ).on('click', function (event) {
		var errors = [];
		var selected_sites = [];
		var selected_groups = [];
		managemaintenance_init();
		if (jQuery( '#select_by' ).val() == 'site') {
			jQuery( "input[name='selected_sites[]']:checked" ).each(function (i) {
				selected_sites.push( jQuery( this ).val() );
			});
			if (selected_sites.length == 0) {
				errors.push( __( 'Please select websites or groups.' ) );
			}
		} else {
			jQuery( "input[name='selected_groups[]']:checked" ).each(function (i) {
				selected_groups.push( jQuery( this ).val() );
			});
			if (selected_groups.length == 0) {
				errors.push( __( 'Please select websites or groups.' ) );
			}
		}

		if (jQuery( "input[name='maintenance_options[]']:checked" ).length <= 0) {
			errors.push( __( 'Please select at least one maintenance option to do maintenance.' ) );
		}

		if (errors.length > 0) {
			jQuery( '#maintenance-site-error-box' ).html( errors.join( '<br />' ) );
			jQuery( '#maintenance-site-error-box' ).fadeIn( 500 );
			return;
		} else {
			jQuery( '#maintenance-site-error-box' ).html( "" );
			jQuery( '#maintenance-site-error-box' ).hide();
		}

		if (jQuery( "#mainte_option_optimize" ).is( ':checked' )) {
			if ( ! confirm( __( 'In rare cases, database optimization function can cause issues and crash database. Please confirm that you want to perform this action.' ) )) {
				return false; }
		}

		var data = {
			action: 'maintenance_selected_sites',
			'groups[]': selected_groups,
			'sites[]': selected_sites,
		};

		jQuery( '#maintenance_run_loading' ).show();
		jQuery.post(ajaxurl, data, function (response) {
			jQuery( '#maintenance_run_loading' ).hide();
			if (response !== 'FAIL') {
				jQuery( '#maintenance-site-progress-results' ).html( response );
				var allWebsiteIds = jQuery( "input[name='maintenance_wp_ids[]']" ).map(function (indx, el) {
					return jQuery( el ).val();
				});
				if (allWebsiteIds === null || typeof allWebsiteIds === "undefined") {
					return; }
				maintenance_perform( allWebsiteIds );
			} else {
				jQuery( '#maintenance-site-error-box' ).html( '<i class="fa fa-exclamation-circle"></i>' + "Can not reach sites to perform maintenance." ).show();
			}
		});
	});

	jQuery( '#managemaintenance_add' ).on('click', function (event) {
		managemaintenance_add();
		return false;
	});

	jQuery( '#managemaintenance_update' ).on('click', function (event) {
		managemaintenance_update();
		return false;
	});

	jQuery( '#maintenance_save_settings' ).on('click', function (event) {
		managemaintenance_save_settings();
		return false;
	});


        $( '#maintenance_perform_number' ).change(function () {
             var val = $( this ).val();
             if (val == 1) {
                  $( '#mainwp_maint_send_on_wrap' ).show();
                  var val = $( '#maintenance_perform_schedule' ).val();
                  mainwp_maint_perform_schedule_date_init(val);
             } else {
                  $( '#mainwp_maint_send_on_wrap' ).hide();
             }
        });

        $( '#maintenance_perform_schedule' ).change(function () {
            var perform_num = $( '#maintenance_perform_number' ).val();
            if (perform_num == 1) {
                var val = $( this ).val();
                mainwp_maint_perform_schedule_date_init(val);
            }

	});


        $( '#mainwp_maint_schedule_month' ).change(function () {
            mainwp_maint_select_date_init();
	});


});

mainwp_maint_perform_schedule_date_init = function (val) {
    jQuery( '.show_if_monthly' ).hide();
    if ( val == 'weekly' || val == 'monthly' || val == 'yearly' ) {
        if (val == 'weekly') {
            jQuery( '#scheduled_send_on_day_of_week_wrap' ).show();
            jQuery( '#scheduled_send_on_day_of_month_wrap' ).hide();
            jQuery( '#scheduled_send_on_month_wrap' ).hide();
        } else if (val == 'monthly') {
            jQuery( '#scheduled_send_on_day_of_week_wrap' ).hide();
            jQuery( '#scheduled_send_on_day_of_month_wrap' ).show();
            jQuery( '#scheduled_send_on_month_wrap' ).hide();
            jQuery( '.show_if_monthly' ).show();
        } else {
            jQuery( '#scheduled_send_on_day_of_week_wrap' ).hide();
            jQuery( '#scheduled_send_on_day_of_month_wrap' ).show();
            jQuery( '#scheduled_send_on_month_wrap' ).show();
        }
        jQuery( '#mainwp_maint_send_on_wrap' ).show();
    } else {
        jQuery( '#mainwp_maint_send_on_wrap' ).hide();
    }
    mainwp_maint_select_date_init();
}

mainwp_maint_select_date_init = function () {
    var recurring = jQuery('#maintenance_perform_schedule').val();
    var selected_month = jQuery('#mainwp_maint_schedule_month').val();
    jQuery( '#mainwp_maint_schedule_day_of_month option').show(); // show all days of month
    if (recurring == 'yearly') {
        if (selected_month == 2) { // Feb
            jQuery( '#mainwp_maint_schedule_day_of_month option').filter(function(){ return (this.value == 31 || this.value == 30 || this.value == 29); }).hide();
        } else if (selected_month == 4 || selected_month == 6 || selected_month == 9 || selected_month == 11 ) {
            jQuery( '#mainwp_maint_schedule_day_of_month option').filter(function(){ console.log(this.value); return (this.value == 31 ); }).hide();
        }
    }
}



maintenance_perform = function (allWebsiteIds, pOptions, pRevisions)
{

	for (var i = 0; i < allWebsiteIds.length; i++) {
		managemaintenance_run_status( allWebsiteIds[i], __( 'PENDING' ) );
	}

	var nrOfWebsites = allWebsiteIds.length;
	jQuery( '#maintenance-site-progress' ).progressbar( {value: 0, max: nrOfWebsites} );
	jQuery( '#maintenance-site-progress-box' ).dialog({
		resizable: false,
		height: 420,
		width: 650,
		modal: true,
		close: function (event, ui) {
			bulkTaskRunning = false;
			jQuery( '#maintenance-site-progress-box' ).dialog( 'destroy' );
			location.href = 'admin.php?page=Extensions-Mainwp-Maintenance-Extension';
		}});

	jQuery( '#maintenance-site-progress-current' ).html( 0 + ' / ' + nrOfWebsites + ' ' + __( 'cleaned' ) );
	maintenance_run_now( allWebsiteIds, pOptions, pRevisions );
}

var websitesToMaintenance = [];
var websitesTotal = 0;
var websitesLeft = 0;
var websitesDone = 0;
var currentWebsite = 0;
var bulkTaskRunning = false;
var currentThreads = 0;
var maxThreads = 15;
var maintenancePerformTask = '';
var man_countErrors = 0;

maintenance_run_now = function (websiteIds, pOptions, pRevisions)
{
	websitesToMaintenance = websiteIds;
	currentWebsite = 0;
	websitesDone = 0;
	websitesTotal = websitesLeft = websitesToMaintenance.length;
	bulkTaskRunning = true;
	var revisions;
	var options;

	if (typeof pOptions !== "undefined" && typeof pRevisions !== "undefined") { // trigger
		options = pOptions;
		revisions = pRevisions;
		if (options == "") {
			return false; }
	} else {
		options = jQuery.map(jQuery( "input[name='maintenance_options[]']:checked" ), function (el) {
			return jQuery( el ).val();
		});
		revisions = jQuery( "#maintenance_options_revisions_count" ).val();
		if (options.length == 0) {
			return false; }
	}

	if (websitesTotal == 1) {
		maintenancePerformTask = 'perform_run_now_one';
	} else if (websitesTotal > 1) {
		maintenancePerformTask = 'perform_run_now_more';
	}

	managemaintenance_run_next( options, revisions );
};

managemaintenance_run_status = function (siteId, newStatus)
{
	jQuery( '.maintenance-status-wp[siteid="' + siteId + '"]' ).html( newStatus );
};

managemaintenance_run_done = function (pOptions, pRevisions)
{
	currentThreads--;
	if ( ! bulkTaskRunning) {
		return;
	}
	websitesDone++;

	jQuery( '#maintenance-site-progress' ).progressbar( 'value', websitesDone );
	jQuery( '#maintenance-site-progress-current' ).html( websitesDone + ' / ' + websitesTotal + ' ' + __( 'cleaned' ) );

	if (websitesDone == websitesTotal && man_countErrors == 0) {
		setTimeout(function () {
			bulkTaskRunning = false;
			jQuery( '#maintenance-site-progress-box' ).dialog( 'destroy' );
			if (maintenancePerformTask == 'trigger') {
				location.href = 'admin.php?page=Extensions-Mainwp-Maintenance-Extension&a=3';
			} else if (maintenancePerformTask == 'perform_run_now_one') {
				location.href = 'admin.php?page=Extensions-Mainwp-Maintenance-Extension&a=4';
			} else if (maintenancePerformTask == 'perform_run_now_more') {
				location.href = 'admin.php?page=Extensions-Mainwp-Maintenance-Extension&a=6';
			}
		}, 3000);
		return;
	}

	managemaintenance_run_next( pOptions, pRevisions );
};
managemaintenance_run_next = function (pOptions, pRevisions)
{
	if (bulkTaskRunning && (currentThreads < maxThreads) && (websitesLeft > 0)) {
		currentThreads++;
		websitesLeft--;
		var websiteId = websitesToMaintenance[currentWebsite++];
		managemaintenance_run_status( websiteId, __( 'CLEANING' ) );

		var data = {
			action: 'maintenance_run_site',
			options: pOptions,
			revisions: pRevisions,
			wp_id: websiteId
		};

		jQuery.post(ajaxurl, data, function (response) {
			jQuery( '#maintenance_run_loading' ).hide();
			if (response && response['status'] == 'SUCCESS') {
				managemaintenance_run_status( websiteId, __( 'DONE' ) );
				managemaintenance_run_done( pOptions, pRevisions );
			} else {
				man_countErrors++;
				if (response['error']) {
					managemaintenance_run_status( websiteId, response['error'] );
					managemaintenance_run_done( pOptions, pRevisions );
				} else {
					managemaintenance_run_status( websiteId, 'An error occurred.' );
					managemaintenance_run_done( pOptions, pRevisions );
				}
			}
		}, 'json');
	}
};



showMaintenanceTab = function (run_now, new_sche, sches, edit_sche, alert_404) {

	var maintenance_run_now_lnk = jQuery( "#maintenance_run_now_lnk" );
	if (run_now) {
		maintenance_run_now_lnk.addClass( 'mainwp_action_down' );
		jQuery( '#maintenance-run-now-notice-box' ).show();
	} else {
		maintenance_run_now_lnk.removeClass( 'mainwp_action_down' );
		jQuery( '#maintenance-run-now-notice-box' ).hide();
	}

	var maintenance_new_schedule_lnk = jQuery( "#maintenance_new_schedule_lnk" );
	if (new_sche) {
		maintenance_new_schedule_lnk.addClass( 'mainwp_action_down' );
	} else {
		maintenance_new_schedule_lnk.removeClass( 'mainwp_action_down' );
	}

	var maintenance_schedules_lnk = jQuery( "#maintenance_schedules_lnk" );
	if (sches) {
		maintenance_schedules_lnk.addClass( 'mainwp_action_down' );
	} else {
		maintenance_schedules_lnk.removeClass( 'mainwp_action_down' );
	}

	var maintenance_edit_daily_lnk = jQuery( "#maintenance_edit_daily_lnk" );
	if (edit_sche) {
		maintenance_edit_daily_lnk.addClass( 'mainwp_action_down' );
	} else {
		maintenance_edit_daily_lnk.removeClass( 'mainwp_action_down' );
	}

	var maintenance_404_alerts_lnk = jQuery( "#maintenance_404_alerts_lnk" );
	if (alert_404) {
		maintenance_404_alerts_lnk.addClass( 'mainwp_action_down' );
	} else {
		maintenance_404_alerts_lnk.removeClass( 'mainwp_action_down' );
	}

	var maintenance_run_now_box = jQuery( "#maintenance_run_now_box" );
	var maintenance_new_schedule_box = jQuery( "#maintenance_new_schedule_box" );
	var maintenance_schedules_box = jQuery( "#maintenance_schedules_box" );
	var maintenance_edit_daily_box = jQuery( "#maintenance_edit_daily_box" );
	var maintenance_select_sites_box = jQuery( "#maintenance_select_sites_box" );
	var maintenance_404_alerts_box = jQuery( "#maintenance_404_alerts_box" );

//	if (run_now) {
//            maintenance_run_now_box.show();
//	}
//        else if (new_sche) {
//            maintenance_new_schedule_box.show();
//        }
        if (sches) {
            maintenance_schedules_box.show();
            maintenance_select_sites_box.hide();
        } else if (edit_sche) {
            maintenance_edit_daily_box.show();
        } else if (alert_404) {
            maintenance_404_alerts_box.show();
        }

        if ( ! run_now) {
                maintenance_run_now_box.hide();
        }
        if ( ! new_sche) {
                maintenance_new_schedule_box.hide();
        }
        if ( ! sches) {
                maintenance_schedules_box.hide();
                maintenance_select_sites_box.show();
        }
        if ( ! edit_sche) {
                maintenance_edit_daily_box.hide();
        } else {
                task_id = jQuery( '#edit_managemaintenance_id' ).val();
                if (task_id) {
                        managemaintenance_reload_select_sites_box( 'task', task_id ); }
        }

        if ( ! alert_404) {
                maintenance_404_alerts_box.hide();
        } else {
                managemaintenance_reload_select_sites_box( 'alert', 0 );
        }

};

managemaintenance_init = function () {
	jQuery( '#maintenance-site-error-box' ).html( '' ).hide();
	jQuery( '#maintenance-site-info-box' ).html( '' ).hide();
	jQuery( '#selected_sites' ).removeClass( 'form-invalid' );
	jQuery( '#selected_groups' ).removeClass( 'form-invalid' );
};


managemaintenance_reload_select_sites_box = function (what, taskid) {
	var data = {
		action: 'maintenace_reload_select_sites',
		taskid: taskid,
		what: what
	};

	if (what == 'task') {
		jQuery( "#maintenance_edit_loading" ).show();
	} else {
		jQuery( "#maintenance_save_loading" ).show();
	}

	jQuery.ajax({
		type: 'POST',
		url: ajaxurl,
		data: data,
		success: function () {
			return function (response) {
				if (what == 'task') {
					if (response.substr( 0, 6 ) != 'NOTASK') {
						jQuery( "#maintenance_select_sites_box" ).html( response );
					}
					jQuery( "#maintenance_edit_loading" ).hide();
				} else {
					jQuery( "#maintenance_select_sites_box" ).html( response );
					jQuery( "#maintenance_save_loading" ).hide();
				}
			}
		}(jQuery( this )),
		async: false
	});
};



managemaintenance_add = function () {
	managemaintenance_init();
	var errors = [];
	if (jQuery( '#managemaintenance_title' ).val().trim() == '') {
		errors.push( 'Please enter a valid title for your maintenance task' );
		jQuery( '#managemaintenance_title' ).addClass( 'form-invalid' );
	} else {
		jQuery( '#managemaintenance_title' ).removeClass( 'form-invalid' );
	}

	if (jQuery( "input[name='maintenance_options[]']:checked" ).length <= 0) {
		errors.push( __( 'Please select at least one maintenance option.' ) );
		jQuery( '#maintenance_new_schedule_box .maintenance_checkboxes' ).addClass( 'form-invalid' );
	} else {
		jQuery( '#maintenance_new_schedule_box .maintenance_checkboxes' ).removeClass( 'form-invalid' );
	}

	if (jQuery( '#select_by' ).val() == 'site') {
		var selected_sites = [];
		jQuery( "input[name='selected_sites[]']:checked" ).each(function (i) {
			selected_sites.push( jQuery( this ).val() );
		});
		if (selected_sites.length == 0) {
			errors.push( 'Please select websites or groups.' );
			jQuery( '#selected_sites' ).addClass( 'form-invalid' );
		} else {
			jQuery( '#selected_sites' ).removeClass( 'form-invalid' );
		}
	} else {
		var selected_groups = [];
		jQuery( "input[name='selected_groups[]']:checked" ).each(function (i) {
			selected_groups.push( jQuery( this ).val() );
		});
		if (selected_groups.length == 0) {
			errors.push( __( 'Please select websites or groups.' ) );
			jQuery( '#selected_groups' ).addClass( 'form-invalid' );
		} else {
			jQuery( '#selected_groups' ).removeClass( 'form-invalid' );
		}
	}

	if (errors.length > 0) {
		setHtml( '#maintenance-site-error-box', errors.join( '<br />' ) );
	} else {
		if (jQuery( "#mainte_option_optimize" ).is( ':checked' )) {
                    if ( ! confirm( __( 'In rare cases, database optimization function can cause issues and crash database. Please confirm that you want to perform this action.' ) )) {
                        return false;
                    }
		}
		jQuery( '#maintenance-site-info-box' ).html( __( 'Adding the maintenance task...' ) ).show();
		jQuery( '#managemaintenance_add' ).attr( 'disabled', 'true' ); //disable button to add.
		jQuery( '#maintenance_new_loading' ).show();
                var schedule = jQuery( '#maintenance_perform_schedule' ).val();
                var data = {
			action: 'maintenance_addtask',
			title: jQuery( '#managemaintenance_title' ).val(),
			schedule: schedule,
			revisions: jQuery( '#maintenance_options_revisions_count' ).val(),
			perform: jQuery( '#maintenance_perform_number' ).val(),
                        recurring_day: maintenance_get_schedule_day(schedule),
                        recurring_hour: jQuery( '#mainwp_maint_schedule_at_time' ).val(),
			'options[]': jQuery.map(jQuery( "input[name='maintenance_options[]']:checked" ), function (el) {
				return jQuery( el ).val();
			}),
			'groups[]': selected_groups,
			'sites[]': selected_sites
		};
		jQuery.post(ajaxurl, data, function (response) {
			response = jQuery.trim( response );
			managebackups_init();
			if (response.substr( 0, 5 ) == 'ERROR') {
				setHtml( '#maintenance-site-error-box', response.substr( 6 ) );
			} else {
				//Message the maintenance task was added
				location.href = 'admin.php?page=Extensions-Mainwp-Maintenance-Extension&a=1';
				return;
			}
			jQuery( '#managemaintenance_add' ).removeAttr( 'disabled' ); //Enable add button
			jQuery( '#maintenance_new_loading' ).hide();
		});
	}
};

maintenance_get_schedule_day = function (schedule) {
    var sche_day = '';
    if ( schedule == 'yearly' ) {
        sche_day = jQuery('#mainwp_maint_schedule_month').val() + '-' + jQuery('#mainwp_maint_schedule_day_of_month').val();
    } else if ( schedule == 'monthly' ) {
        sche_day = jQuery('#mainwp_maint_schedule_day_of_month').val();
    } else if ( schedule == 'weekly' ) {
        sche_day = jQuery('#mainwp_maint_schedule_day').val();
    }
    return sche_day;
}

managemaintenance_save_settings = function () {
	var selected_sites = [];
	var selected_groups = [];
	if (jQuery( '#select_by' ).val() == 'site') {
		jQuery( "input[name='selected_sites[]']:checked" ).each(function (i) {
			selected_sites.push( jQuery( this ).val() );
		});
	} else {
		jQuery( "input[name='selected_groups[]']:checked" ).each(function (i) {
			selected_groups.push( jQuery( this ).val() );
		});
	}

	jQuery( '#maintenance_save_settings' ).attr( 'disabled', 'true' ); //disable button to add.
	jQuery( '#maintenance_save_loading' ).show();
	var data = {
		action: 'maintenance_save_settings',
		email: jQuery( '#managemaintenance_404_alert_email' ).val(),
		enable: jQuery( '#managemaintenance_enable_404_alert' ).attr( "checked" ) ? 1 : 0,
		'groups[]': selected_groups,
		'sites[]': selected_sites
	};
	jQuery.post(ajaxurl, data, function (response) {
		jQuery( '#maintenance_save_settings' ).removeAttr( 'disabled' ); //Enable add button
		jQuery( '#maintenance_save_loading' ).hide();
		jQuery( '#maintenance-site-info-box' ).hide();
		jQuery( '#maintenance-site-error-box' ).hide();

		if (response) {
			if (response == 'SUCCESS') {
				jQuery( '#maintenance-site-info-box' ).hide();
				jQuery( '#maintenance-site-error-box' ).hide();
				var data = {
					action: 'maintenance_save_settings_load_sites'
				};
				jQuery.post(ajaxurl, data, function (response) {
					if (response && response !== 'FAIL') {
						jQuery( '#maintenance-site-info-box' ).html( response );
                        main_TotalThreads = jQuery( '.mainwpMaintenanceSitesItem[status="queue"]' ).length;
						mainwp_maintenance_save_settings_start_next();
					} else {
						jQuery( '#maintenance-site-error-box' ).html( 'Loading sites failed.' ).show();
					}
				});
			} else if (response == 'FAIL') {
				jQuery( '#maintenance-site-error-box' ).html( __( 'Saving settings failed.' ) ).show();
			} else {
				jQuery( '#maintenance-site-error-box' ).html( response ).show();
			}
		} else {
			jQuery( '#maintenance-site-error-box' ).html( 'Undefined Error' ).show();
		}
	});
}

var main_MaxThreads = 3;
var main_CurrentThreads = 0;
var main_TotalThreads = 0;
var main_FinishedThreads = 0;



mainwp_maintenance_save_settings_start_next = function ()
{
	while ((siteToMain = jQuery( '.mainwpMaintenanceSitesItem[status="queue"]:first' )) && (siteToMain.length > 0) && (main_CurrentThreads < main_MaxThreads)) {
		mainwp_maintenance_save_settings_start_specific( siteToMain );
	}
};

mainwp_maintenance_save_settings_start_specific = function (pSiteToMain)
{
	main_CurrentThreads++;
	pSiteToMain.attr( 'status', 'progress' );
	var statusEl = pSiteToMain.find( '.status' ).html( '<i class="fa fa-spinner fa-pulse"></i> ' + 'Running...' );

	var data = {
		action: 'mainwp_maintenance_performsavesettings',
		siteId: pSiteToMain.attr( 'siteid' ),
		email: jQuery( '#mainwp_maintenance_settings_email' ).val(),
		enable: jQuery( '#mainwp_maintenance_settings_enable_alert' ).val(),
		do_action: pSiteToMain.attr( 'action' ),
	};

	jQuery.post(ajaxurl, data, function (response)
		{
		pSiteToMain.attr( 'status', 'done' );
		if (response && response['result'] == 'SUCCESS') {
			statusEl.html( 'Successful' ).show();
		} else if (response && response['error']) {
			statusEl.html( response['error'] ).show();
			statusEl.css( 'color', 'red' );
		} else {
			statusEl.html( __( 'Undefined Error' ) ).show();
			statusEl.css( 'color', 'red' );
		}

		main_CurrentThreads--;
		main_FinishedThreads++;
		if (main_FinishedThreads == main_TotalThreads && main_FinishedThreads != 0) {
			jQuery( '#mainwp_maintenance_apply_setting_ajax_message_zone' ).html( 'Settings saved to child sites' ).fadeIn( 100 );
			setTimeout(function () {
				location.href = 'admin.php?page=Extensions-Mainwp-Maintenance-Extension';
			}, 2000);
		} else {
            mainwp_maintenance_save_settings_start_next();
        }
	}, 'json');
};


managemaintenance_update = function (event) {
	managemaintenance_init();
	var errors = [];
	if (jQuery( '#managemaintenance_title' ).val().trim() == '') {
		errors.push( 'Please enter a valid title for your maintenance task' );
		jQuery( '#managemaintenance_title' ).addClass( 'form-invalid' );
	} else {
		jQuery( '#managemaintenance_title' ).removeClass( 'form-invalid' );
	}

	if (jQuery( "input[name='maintenance_options[]']:checked" ).length <= 0) {
		errors.push( __( 'Please select at least one maintenance option.' ) );
		jQuery( '#maintenance_edit_schedule_box .maintenance_checkboxes' ).addClass( 'form-invalid' );
	} else {
		jQuery( '#maintenance_edit_schedule_box .maintenance_checkboxes' ).removeClass( 'form-invalid' );
	}

	if (jQuery( '#select_by' ).val() == 'site') {
		var selected_sites = [];
		jQuery( "input[name='selected_sites[]']:checked" ).each(function (i) {
			selected_sites.push( jQuery( this ).val() );
		});
		if (selected_sites.length == 0) {
			errors.push( 'Please select websites or groups.' );
			jQuery( '#selected_sites' ).addClass( 'form-invalid' );
		} else {
			jQuery( '#selected_sites' ).removeClass( 'form-invalid' );
		}
	} else {
		var selected_groups = [];
		jQuery( "input[name='selected_groups[]']:checked" ).each(function (i) {
			selected_groups.push( jQuery( this ).val() );
		});
		if (selected_groups.length == 0) {
			errors.push( __( 'Please select websites or groups.' ) );
			jQuery( '#selected_groups' ).addClass( 'form-invalid' );
		} else {
			jQuery( '#selected_groups' ).removeClass( 'form-invalid' );
		}
	}

	if (errors.length > 0) {
		setHtml( '#maintenance-site-error-box', errors.join( '<br />' ) );
	} else {
		jQuery( '#maintenance-site-info-box' ).html( __( 'Updating the maintenance task' ) ).show();
		jQuery( '#managemaintenance_update' ).attr( 'disabled', 'true' ); //disable button to add.
		jQuery( '#maintenance_edit_loading' ).show();
		task_id = jQuery( '#edit_managemaintenance_id' ).val();
        var schedule = jQuery( '#maintenance_perform_schedule' ).val();
		var data = {
			action: 'maintenance_updatetask',
			taskid: task_id,
			title: jQuery( '#managemaintenance_title' ).val(),
			schedule: schedule,
			revisions: jQuery( '#maintenance_options_revisions_count' ).val(),
			perform: jQuery( '#maintenance_perform_number' ).val(),
            recurring_day: maintenance_get_schedule_day(schedule),
            recurring_hour: jQuery( '#mainwp_maint_schedule_at_time' ).val(),
			'options[]': jQuery.map(jQuery( "input[name='maintenance_options[]']:checked" ), function (el) {
				return jQuery( el ).val();
			}),
			'groups[]': selected_groups,
			'sites[]': selected_sites
		};

		jQuery.post(ajaxurl, data, function (response) {
			response = jQuery.trim( response );
			if (response.substr( 0, 5 ) == 'ERROR') {
				setHtml( '#maintenance-site-error-box', response.substr( 6 ) );
			} else if (response.substr( 0, 10 ) == 'NOAFFECTED') {
				location.href = 'admin.php?page=Extensions-Mainwp-Maintenance-Extension&a=5';
				return;
			} else {
				//Message the maintenance task was added
				location.href = 'admin.php?page=Extensions-Mainwp-Maintenance-Extension&a=2';
				return;
			}
			jQuery( '#managemaintenance_update' ).removeAttr( 'disabled' ); //Enable add button
			jQuery( '#maintenance_edit_loading' ).hide();
		});
	}
};


managemaintenance_remove = function (id) {
	managemaintenance_init();
	var q = confirm( __( 'Are you sure you want to delete this maintenance task?' ) );
	if (q) {
		jQuery( '#task-status-' + id ).html( __( 'Removing the task...' ) );
		var data = {
			action: 'maintenance_removetask',
			id: id
		};
		jQuery.post(ajaxurl, data, function (response) {
			response = jQuery.trim( response );
			managemaintenance_init();
			var result = '';
			var error = '';
			if (response == 'SUCCESS') {
				result = __( 'Your task has been removed.' );
			} else {
				error = __( 'Unspecified error occured.' );
			}

			if (error != '') {
				setHtml( '#maintenance-site-error-box', error );
			}
			if (result != '') {
				jQuery( '#maintenance-site-info-box' ).html( result ).show();
			}
			jQuery( '#task-status-' + id ).html( '' );
			if (error == '') {
				jQuery( '#task-' + id ).remove();
			}
		});
	}
};

managemaintenance_trigger_run_now = function (el)
{
	el = jQuery( el );
	el.hide();
	el.parent().find( '.maintenance_trigger_loading' ).show();

	var taskId = el.closest( 'tr' ).attr( 'taskid' );
	//Fetch the sites to backup
	var data = {
		action: 'maintenance_maintenancetask_get_sites_to_run',
		task_id: taskId
	};

	managemaintenance_init();
	maintenancePerformTask = 'trigger';
	jQuery.post(ajaxurl, data, function (response) {
		jQuery( '#maintenance_trigger_loading' ).hide();
		if (response !== 'FAIL') {
			jQuery( '#maintenance-site-progress-results' ).html( response );
			var allWebsiteIds = jQuery( "input[name='maintenance_wp_ids[]']" ).map(function (indx, el) {
				return jQuery( el ).val();
			});
			if (allWebsiteIds === null || typeof allWebsiteIds === "undefined") {
				return;
			}
			var options = jQuery( '#mainwp_mainten_trigger_data' ).attr( 'options' );
			var revisions = jQuery( '#mainwp_mainten_trigger_data' ).attr( 'revisions' );
			maintenance_perform( allWebsiteIds, options, revisions );
		} else {
			jQuery( '#maintenance-site-error-box' ).html( "Can not get sites to perform maintenance." ).show();
		}
	});
};
