var HeatbrainCMS = {
	setup: function() {
		
		var buttonTemplate = $("<div class='cms_edit_button'></div>");
		var oldContent; // Stores the content pulled from the database initially

		// Editor options
		elRTE.prototype.options.panels.heatbrainPanel = [
			'bold', 'italic', 'underline', 'blockquote', 'pasteformattext', 'justifyleft', 'justifyright', 
			'justifycenter', 'justifyfull', 'formatblock', 'insertorderedlist',
			'insertunorderedlist', 'link', 'image', 'elfinder'
		];

		elRTE.prototype.options.toolbars.heatbrainPanel = ['heatbrainPanel'];

		var options = {
			cssClass : 'el-rte',
			height   : 200,
			toolbar  : 'heatbrainPanel',
			cssfiles : ['css/elrte-inner.css'],
			fmAllow: true,
			fmOpen: function(callback) {
				$('<div id="myelfinder" />').elfinder({
						url : '../connectors/php/connector.php',
						lang : 'en',
						dialog : { width : 900, modal : true, title : 'elFinder - file manager for web' },
						closeOnEditorCallback : true,
						editorCallback : callback
					})
			}
		}

		function saveContentChanges(contentArea, contentToSave) {
			// Save using the full content_id, not just the id. Usually a combination of the page and the id, but not always.
			var id = contentArea.attr('content_id');
			function error() {
				alert('There was an error saving your content!')
			}

			$.ajax({
				url: 'update.php',
				type: 'POST',
				success: function(result) {
					if (isNaN(result)) {
						error();
					}
				},
				error: function() {
					error();
				},
				data: {
					id: id, 
					content: contentToSave
				}
			});
		}

		// ********************************************
		// *** CMS Edit Button Delegate for WYSIWYG ***
		// ********************************************		
		$('body').delegate('div.cms_edit_button[single_line=false]', 'click', function() {
			var editable = $(this).prevAll().first();
			oldContent = editable.html();

			function getEditor() {
				return modal.find('div.cms_modal_content');
			}

			// Reference to save function
			var saveChanges = saveContentChanges;

			var modal = $('<div class="cms_modal"><div class="cms_modal_content"></div></div>');
			modal.dialog({
				modal: true,
				closeOnEscape: false,
				resizable: false,
				title: 'Edit Your Content',
				minWidth: 600,
				maxWidth: 500,
				position: ['center', 20],
				buttons: {
					Preview: function() {						
						var newContent = getEditor().elrte('val');
						modal.dialog('close');
						editable.html(newContent);
						editable.effect('highlight');

						var buttons = $('.cms_edit_button').remove();
						var previewMenu = $('<div class="cms_preview_options"></div>');

						function savePreview() {
							previewMenu.dialog('destroy');
							saveChanges(editable, newContent);
						}

						function replaceButtons(){
							$('[editable=true]').each(function(i){
								$(this).after(buttons.eq(i));
							});
						}

						previewMenu.dialog({
							closeOnEscape: false,
							resizable: false,
							title: 'Preview Options',
							height: 20,
							position: ['right', 'top'],
							buttons: {
								'Return to Editor': function() {
									$(this).dialog('close');
									replaceButtons();
									editable.next('.cms_edit_button').click();
								},

								'Save Changes': function() {
									$(this).dialog('close');
									savePreview();
									replaceButtons();
								}
							},
							open: function() {
								$(this).prev().children('.ui-dialog-titlebar-close').hide();
							}
						});
					},
					Save: function() {
						var newContent = getEditor().elrte('val');
						saveChanges(editable, newContent);
						modal.dialog('close');

						editable.html(newContent);
						editable.effect('highlight');
					}
				}
			});

			getEditor().html(oldContent).elrte(options);
		});
		// End CMS Edit Button Delegate for WYSIWYG

		// ***************************************
		// *** CMS Edit Button for Single Line ***
		// ***************************************
		$('body').delegate('div.cms_edit_button[single_line=true]', 'click', function() {
			var editable = $(this).prevAll().first();
			oldContent = editable.html();			
			
			var modal = $('<div class="cms_modal"><div class="cms_modal_content"><input type="text" id="cms_single_line_edit" /></div></div>')
				.find('input#cms_single_line_edit').val(oldContent);				

			modal.dialog({
				modal: true,
				closeOnEscape: false,
				resizable: false,
				title: 'Edit Your Content',
				buttons: {
					Cancel: function() {
						$(this).dialog('close');
					},
					Save: function() {
						var newContent = $(this).val();
						saveContentChanges(editable, newContent);

						$(this).dialog('close');
						editable.html(newContent);
						editable.effect('highlight');
					}
				}
			}).css({
				border: 'solid 1px Gray',
				padding: '0',
				minHeight: '24px',
				width: '98%',
				marginTop: '8'
			});;
		});
		// End CMS Edit Button Delegate for Single Line

		
		// ***************************
		// *** Insert Edit Buttons ***
		// ***************************		
		$('[editable=true]').each(function() {			
			var position = $(this).position();
			var offset = $(this).offset();

			var button = buttonTemplate.clone().css({
				top: offset.top,
				left: position.left - 20
			});

			// Set whether this should use the single or multi-line editor
			var is_single = $(this).attr('single_line');
			button.attr('single_line', is_single || false);

			$(this).after(button);
		});

	}
}
