$(document).ready( function() {
	
	var form = $('FORM:first'),
		textarea = form.find('TEXTAREA[name=code]'),
		editor,
		sidebar = $('#sidebar'),
		request,
		editorModes,
		supportsAce = true;
	
	
	var isMobile = {
	    Android: function() {
	        return navigator.userAgent.match(/Android/i) ? true : false;
	    },
	    BlackBerry: function() {
	        return navigator.userAgent.match(/BlackBerry/i) ? true : false;
	    },
	    iOS: function() {
	        return navigator.userAgent.match(/iPhone|iPad|iPod/i) ? true : false;
	    },
	    Windows: function() {
	        return navigator.userAgent.match(/IEMobile/i) ? true : false;
	    },
	    any: function() {
	        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Windows());
	    }
	};	
	
	
	function refreshEditor() {
		
		var width = $(window).width() - sidebar.outerWidth(),
			height = $(window).height();
		
		form.height(height);
		
		if( supportsAce ) {
			// Resize Ace Editor
			$('#editor-wrapper, #editor').width(width).height(height);
			if( editor ) editor.resize();
		} else {
			// Resize textarea
			var vPadding = parseInt(textarea.css('paddingTop')) + parseInt(textarea.css('paddingBottom')),
				hPadding = parseInt(textarea.css('paddingLeft')) + parseInt(textarea.css('paddingRight'));
			textarea.width(width - hPadding).height(height - vPadding);
		}
		
	}
	
	
	function getMode() {
		return $('#mode .active A').attr('data-mode');
	}
	
	
	function refreshOptions() {
		$('#options LI').hide();
		$('#options').find('.' + getMode()).show();
	}
	
	
	function rememberOptions() {
		// Form fields
		form.find(':input').change( function() {
			if( $(this).is(':radio, :checkbox') ) {
				// Save checked status
				$.cookie($(this).attr('name'), $(this).prop('checked'), { path: '/', domain: '.dirtymarkup.com', expires: 365 });
			} else {
				// Save value
				$.cookie($(this).attr('name'), $(this).val(), { path: '/', domain: '.dirtymarkup.com', expires: 365 });
			}
		});
		
		// Mode changes
		form.find('#mode A').click( function() {
			$.cookie('mode', $(this).attr('data-mode'), { path: '/', domain: '.dirtymarkup.com', expires: 365 });
		});
	}
	
	
	function restoreOptions() {
		
		// Set fields
		form.find(':input').each( function() {
			if( $(this).is(':radio, :checkbox') ) {
				// Update checked status
				$(this).prop('checked', $.cookie($(this).attr('name')) === 'true');
			} else {
				// Update value
				if( $(this).attr('name') ) {
					var val = $.cookie($(this).attr('name'));
					if( val ) $(this).val(val);
				}
			}
		});
		
		// Set mode
		var mode = $.cookie('mode');
		if( mode ) {
			$('#mode').find('A').each( function() {
				if( $(this).attr('data-mode') == mode ) $(this).trigger('click');
			});
		}
		
		// Update print margin
		form.find('SELECT[name=print-margin]').trigger('change');
		
	}
	
	
	// Supports Ace?
	if( $.browser.msie ) supportsAce = false;
	if( isMobile.any() ) supportsAce = false;
	
	
	// Handle window resizing
	$(window).resize(refreshEditor).trigger('resize');
	
	
	// Handle mode switching
	$('#mode A').click( function(event) {
		var a = $(this),
			li = a.parent(),
			mode = a.attr('data-mode');
		
		event.preventDefault();
		
		li.siblings().removeClass('active').end().addClass('active');
		form.find('INPUT[name=mode]').val(a.attr('data-mode'));
		
		refreshOptions();
		
		if( supportsAce ) {
			// Fixes a bug where warnings/errors from the CSS mode still show when switching from CSS to HTML
			editor.getSession().setMode(new editorModes['javascript']);
			// Sets the correct mode
			editor.getSession().setMode(new editorModes[mode]);
		}
		
	});
	
	
	// Print margin
	form.find('SELECT[name=print-margin]').change( function() {
		var m = $(this).val();
		if( m < 20 || m > 200 ) m = 80;
		$(this).val(m);
		if( editor ) editor.setPrintMarginColumn(m);
	});
	
	
	// Enable Ace editor
	if( supportsAce ) {
		
		editorModes = {
			html: require('ace/mode/html').Mode,
			css: require('ace/mode/css').Mode,
			javascript: require('ace/mode/javascript').Mode
		};
		
		textarea.hide().after('<div id="editor" />');
		refreshEditor();
		
		editor = ace.edit('editor');
		editor.getSession().setTabSize(4);
		editor.getSession().setMode(new editorModes.html);
		editor.getSession().setValue(textarea.val());
		
	}
	
	
	// Handle form submit
	$('#submit').click( function(event) {
		
		event.preventDefault();
		
		switch( getMode() ) {
			
			case 'javascript':
				
				var code = editor ? editor.getSession().getValue() : textarea.val(),
					newCode;
				
				newCode = js_beautify(code, {
					indent_size: form.find('SELECT[name=indent-size]').val() === 'tabs' ? 1 : form.find('SELECT[name=indent-size]').val(),
					indent_char: form.find('SELECT[name=indent-size]').val() === 'tabs' ? '\t' : ' ',
					preserve_newlines: form.find(':checkbox[name=preserve-empty-lines]').prop('checked'),
					brace_style: form.find('SELECT[name=brace-style]').val(),
					keep_array_indentation: form.find(':checkbox[name=keep-array-indentation]').prop('checked')
				});
				
				textarea.val(newCode);
				
				if( editor ) {
					editor.getSession().setValue(newCode);
					editor.gotoLine(1);
				}
				
				break;
			
			case 'css':
			case 'html':
			default:
				
				if( form.hasClass('busy') ) return;
				form.addClass('busy');
				if( request ) request.abort();
				
				if( editor ) textarea.val(editor.getSession().getValue());
				request = $.post('/src/ajax/dirty.ajax.php', form.serialize(), function(r) {
					form.removeClass('busy');
					
					textarea.val(r.code);
					
					if( editor ) {
						editor.getSession().setValue(r.code);
						editor.gotoLine(1);
					}
					
				}, 'json');
				
				break;
				
		}
		
	});		
	
	
	// Remember settings via cookie
	rememberOptions();
	restoreOptions();
	
});
