(function ($) {
	"use strict";

	$(function () {

		// Set height to be full screen
		// 251 = admin-bar (32px) + top-margin (10px) + h1 (42px) + top-nav (30px) + footer (65px) + filesize (40px) + padding (32px)
		$('#log-display').css( 'max-height', ($(window).height() - 251) );
		$('#log-display').css( 'height', '100%' );
		
		// Select first item
		var cbLogs = document.getElementById("logs");
		
		// If no logs, this won't exist
		if (cbLogs) cbLogs.selectedIndex = 0;

		var $logs = $('#logs');

		function loadErrorLog() {
			var $t = $logs,
				$clear_button = $('#cv-monitor-errors-clear'),
				$log_display = $('#log-display'),
				$log_size = $('#log-size'),
				fileName = $t.val(),
				validFileName = 'error_log',
				data = {
					action: 'get_error_log',
					log: fileName,
					_wpnonce: $('#error-log-nonce').val()
				};

			// No error logs
			if ( $t.length == 0 ) return;
			
			// While loading...
			$log_display.empty().html('Loading...');
			$log_size.empty().html('');
			$clear_button.attr('disabled', 'disabled');
			
			// Since WordPress 2.8+ ajaxurl
			$.ajax({
				url: ajaxurl,
				type: "POST",
				data: data,
				dataType: "json",
				xhrFields: {
					onprogress: function (e) {
						if ( e.lengthComputable ) {
							$log_display.empty().html('Loading: ' + e.loaded / e.total * 100 + '%');
							//console.log(e.loaded / e.total * 100 + '%');
						}
					}
				},
				success: function ( response ) {
					data = response;// JSON parsed by jquery JSON.parse(response);
					
					if ( response === 0 ) {
						$log_display.empty().html('Error: Ajax failed');
						$log_size.empty().html('0 kB');
						return;
					}

					$log_display.empty().html(data.log);
					$log_size.empty().html(data.size);
					
					// If file is not a standard "error_log", disable clear button
					var fileName = '/error_log';

					//console.log(fileName);
					//console.log(fileName.indexOf(validFileName, fileName.length - validFileName.length));
					if ( fileName.indexOf( validFileName, fileName.length - validFileName.length ) !== -1 ) {
						//console.log('enable');
						$clear_button.removeClass('button-disabled');
						$clear_button.addClass('button');
						$clear_button.removeAttr('disabled');
					} else {
						//console.log('disable');
						$clear_button.addClass('button-disabled');
						$clear_button.removeClass('button');
						$clear_button.attr('disabled', 'disabled');
					}
				},
				fail: function( xhr, status, error ) {
					console.log('CV-Monitor - #logs.onChange - Fail: ' + status + ' : ' + error);
				}
			});
		}
		
		/**
		 * Upon the user selecting a different log from the select
		 * dropdown, trigger loading that log file into the textarea.
		 * 
		 * @param  event e
		 */
		 // jQuery .on() added in 1.7
		$('#logs').bind('change', function(e) {
		//$('#logs').on('change', function(e) {
			loadErrorLog();
		});

		// Load initial log
		loadErrorLog();
	});
}(jQuery));