/* Site mini-CMS
 *
 * (c) 2009 Computer Business Services, Inc.
 */

var cms = {
	init: function() {
		$('.cms-record').click(function() {
			cms.edit($(this));
		});
		$('.cms-editFormFloating .cms-closeButton').click(function() {
			$(this).parents('.cms-editFormFloating').hide();
		});
		$('.cms-editFormFloating').appendTo('body');
		$('textarea, .droppable').droppable({accept: '.cms-draggable', drop: function(e, ui) {
			if (ui.helper.hasClass('cms-draggable'))
				$(this).insertAtSelection('[img="' + ui.draggable.data('cms').id + '"]');
		}});
		this.dialog.init();
		this.lightbox.init();
		this.gallery.init();
	},

	edit: function(rec) {
		var form = $(rec.parents('.cms-editMultiRecord').find('.cms-multiRecordAnchor').attr('href'))
			.parents('.cms-editFormFloating')
			.css('width', '50%')
			.centerScreen()
			.show();
		form.find('[id]:input').each(function() {
			$(this).val(rec.find('.cms-recordName--' + $(this).attr('id')).text());
		});
		if (rec.hasClass('cms-multiRecordNew')) {
			form.find('.cms-keyField').removeAttr('readonly').removeClass('cms-readOnly');
			form.find('.cms-deleteButton').hide();
			form.find('.cms-submitButton').val('Insert'); // keyword
		} else {
			form.find('.cms-keyField').attr('readonly', 'readonly').addClass('cms-readOnly');
			form.find('.cms-deleteButton').show();
			form.find('.cms-submitButton').val('Update'); // keyword
		}
		form.find(':input:visible:not(.cms-readOnly):first').focus().select();
	},

	dialog: {
		init: function() {
			$('.dialog').each(function() { cms.dialog.adorn($(this)); });
		},
		adorn: function(dlg) {
			if (!dlg.hasClass('noclose'))
			dlg.find('.titlebar').append(
				$('<button title="Close" class="closeButton"></button>')
					.click(function() { cms.dialog.close(this); })
			);
			dlg.draggable({handle: '.titlebar'}).mousedown(function() {
				$('.dialog:not(.ontop)').css('z-index', 300);
				if (!$(this).hasClass('ontop'))
					$(this).css('z-index', 310);
			});
			dlg.find('.okButton').click(function() { cms.dialog.close(this); });

			// Prevent droppables dropped over a dialog from being dropped "through" it
			// onto an underlying text box.
			dlg.droppable({
				accept: '.cms-draggable, .cms-draggable-bogus',
				over: function(e, ui) {
					var val = parseInt(ui.helper.data('dlgCount')) + 1;
					ui.helper.data('dlgCount', val).removeClass('cms-draggable').addClass('cms-draggable-bogus');
				},
				out: function(e, ui) {
					var val = parseInt(ui.helper.data('dlgCount')) - 1;
					ui.helper.data('dlgCount', val);
					if (val == 0)
						ui.helper.removeClass('cms-draggable-bogus').addClass('cms-draggable');
				}
			});
		},
		create: function() {
			var dlg = $('<div class="dialog"><div class="titlebar"><span></span></div><div class=toolbar></div>' +
					'<div class="dlgContent"></div><div class="buttons"></div></div>');
			this.adorn(dlg);
			return dlg;
		},
		createButton: function(text) {
			return $('<button class="okButton">' + text + '</button>').click(function() { cms.dialog.close(this); });
		},
		close: function(closeBtn) {
			$(closeBtn).parents('.dialog').fadeOut('fast');
		}
	},

	loader: {
		htmlId: 'lb-loading',

		show: function() {
			$('#' + this.htmlId).show().centerScreen();
		},
		hide: function() {
			$('#' + this.htmlId).hide();
		}
	},

	lightbox: {
		backdrop: 'lb-backdrop',
		htmlId: 'lb-lightbox',

		init: function() {
			if ($('#' + this.backdrop).length == 0) // create backdrop
				$('<div id="' + this.backdrop + '"></div>').hide().appendTo('body');
			if ($('#' + this.htmlId).length == 0) // create lightbox
				$('<img id="' + this.htmlId + '" src="" alt="Preview image"/>').hide().appendTo('body');
			if ($('#' + cms.loader.htmlId).length == 0) // create loading indicator
				$('<img id="' + cms.loader.htmlId + '" src="cms/img/loading.gif" width="66" height="66"/>').hide().appendTo('body');
			$('#' + this.htmlId + ', #' + this.backdrop).click(function() { cms.lightbox.hide(); });
			$(document).keypress(function() {
				if ($('#' + cms.lightbox.backdrop + ':visible').length != 0) {
					cms.lightbox.hide();
					return false;
				}
			});
		},
		show: function(url) {
			$('#' + this.backdrop).fadeIn('slow', function() {
				cms.loader.show();
				$('#' + cms.lightbox.htmlId).attr('src', url)
					.load(function() {
						$(this).fadeIn('slow').centerScreen();
						cms.loader.hide();
					});
			});
		},
		hide: function() {
			$('#' + this.htmlId + ', #' + this.backdrop).fadeOut('fast');
		}
	},

	gallery: {
		htmlId: 'dlg-gallery',
		loadId: 'dlg-galleryLoad',
		loadInputId: 'gallery-fileUpload',
		helpId: 'dlg-galleryHelp',
		selected: null,
		undoHistory: Array(),

		init: function() {
			var dlg;
			// create dialogs if not already present
			if ($('#' + this.htmlId).length == 0) { // main dialog
				dlg = cms.dialog.create().addClass('hidden').attr('id', this.htmlId).appendTo('body');
				dlg.find('.titlebar span').text('Picture gallery');
				dlg.find('.toolbar')
					.append($('<button class="help" title="Help"><img src="cms/img/help.png" alt="Help"/></button>')
						.click(function() { $('#' + cms.gallery.helpId).centerScreen().show(); }))
					.append($('<button title="Add Picture"><img src="cms/img/picture_add.png" alt="Add"/></button>')
						.click(function() { $('#' + cms.gallery.loadId).centerScreen().show(); }))
					.append($('<button title="Delete Picture"><img src="cms/img/picture_delete.png" alt="Delete"/></button>')
						.click(function() { cms.gallery.remove(); }))
					.append($('<button title="Preview Picture"><img src="cms/img/picture_zoom.png" alt="Preview"/></button>')
						.click(function() { cms.gallery.preview(); }))
					.append($('<button id="gallery-undo" title="Undo Delete"><img src="cms/img/undo-small.png" alt="Undo"/></button>')
						.click(function() { cms.gallery.undo(); }));
				dlg.find('.dlgContent').append('<div class="strip"></div>');
			}
			if ($('#' + this.loadId).length == 0) { // file upload
				dlg = cms.dialog.create().addClass('hidden ontop').attr('id', this.loadId).appendTo('body');
				dlg.find('.toolbar').remove();
				dlg.find('.titlebar span').text('Load file');
				dlg.find('.dlgContent').append('<h3>Please select a picture file to upload:</h3><p>File:<input id="' +
					this.loadInputId + '" type="file" name="fileUpload"/></p>');
				dlg.find('.buttons')
					.append(cms.dialog.createButton('Add').click(function() { cms.gallery.upload(); }))
					.append(cms.dialog.createButton('Cancel'));
			}
			if ($('#' + this.helpId).length == 0) { // help
				dlg = cms.dialog.create().addClass('hidden ontop').attr('id', this.helpId).appendTo('body');
				dlg.find('.toolbar').remove();
				dlg.find('.titlebar span').text('Gallery help');
				dlg.find('.dlgContent').append('<img class="msgBoxIcon" src="cms/img/icon_info.png" alt="Information"/>' +
					'<div class="msgBoxMessage">' +
					'<ul>' +
						'<li>To insert an image, drag it with mouse to the text box you wish to insert it into.</li>' +
						'<li>To add a new image to the gallery, click the Add button ' +
							'(<img src="cms/img/picture_add.png" alt="Add icon" width="20" height="20"/>).</li>' +
						'<li>To remove an image, select it with mouse and click the Delete button ' +
							'(<img src="cms/img/picture_delete.png" alt="Delete icon" width="20" height="20"/>).' +
							'<ul>' +
								'<li>Note that if the image is referenced from some pages, they may show "broken" images.</li>' +
								'<li>When you remove an image, an Undo button ' +
									'(<img src="cms/img/undo-small.png" alt="Undo icon" width="20" height="20"/>) ' +
									'will appear, so you can restore deleted images.</li>' +
							'</ul></li>' +
						'<li>To preview an image, select it with mouse and click the Preview button ' +
							'(<img src="cms/img/picture_zoom.png" alt="Preview icon" width="20" height="20"/>) or double-click the image.</li>' +
						'<li>To close the gallery, click the Close button (<img src="cms/img/close.gif" alt="Close icon"/>) ' +
							'at the top right corner.</li>' +
					'</ul>' +
					'</div>');
				dlg.find('.buttons').append(cms.dialog.createButton('OK'));
			}
		},
		makeImgSrc: function(id) {
			return 'imgload.php?id=' + id;
		},
		show: function() {
			cms.loader.show();
			$.ajax({
				type: 'GET',
				url: 'imglist.php',
				dataType: 'json',
				success: function(data) {
					$('#' + cms.gallery.htmlId + ' .strip').empty();
					for (var img in data)
						cms.gallery.add(data[img]);
					$('#' + cms.gallery.htmlId).centerScreen().show();
					cms.loader.hide();
				},
				error: function (data, status, err) {
					cms.loader.hide();
					alert(err);
				}
			});
			return false;
		},
		select: function(img) {
			$('#' + this.htmlId + ' img').removeClass('selected');
			this.selected = $(img).addClass('selected');
		},
		add: function(data) {
			$('#' + this.htmlId + ' .strip').append(
				$('<img src="' + this.makeImgSrc(data.id) + '&mode=thumb" class="cms-draggable"/>')
					.data('cms', data)
					.draggable({
						helper: 'clone',
						opacity: 0.7,
						appendTo: 'body',
						zIndex: 100,
						start: function(e, ui) {
							ui.helper.removeClass('selected').data('dlgCount', 0);
						}
					}).mousedown(function() { cms.gallery.select(this); })
					.dblclick(function() { cms.gallery.preview(); })
			);
		},
		remove: function() {
			if (this.selected !== null) {
				$.ajax({
					type: 'GET',
					url: 'imgdelete.php?id=' + cms.gallery.selected.data('cms').id,
					dataType: 'json',
					success: function(data) {
						if (data.success) {
							cms.gallery.selected.data('index', cms.gallery.selected.parent().find('> *').index(cms.gallery.selected))
								.draggable('disable')
								.fadeOut('slow', function() {
									$(this).appendTo('body');
								});
							cms.gallery.undoHistory.push(cms.gallery.selected);
							cms.gallery.selected = null;
							$('#gallery-undo').show();
						} else {
							alert('Error: ' + data.error);
						}
					},
					error: function (data, status, err) {
						alert(err);
					}
				});
			}
		},
		undo: function() {
			$.ajax({
				type: 'GET',
				url: 'imgdelete.php?id=' + cms.gallery.undoHistory[cms.gallery.undoHistory.length - 1].data('cms').id +
					'&cmd=undo',
				dataType: 'json',
				success: function(data) {
					if (data.success) {
						cms.gallery.selected = cms.gallery.undoHistory.pop();
						if (cms.gallery.undoHistory.length == 0)
							$('#gallery-undo').hide();
						// put it back where it belongs
						if (cms.gallery.selected.data('index') > 0)
							cms.gallery.selected.insertAfter('#' + cms.gallery.htmlId + ' .strip img:nth-child(' +
								cms.gallery.selected.data('index') + ')');
						else
							cms.gallery.selected.prependTo('#' + cms.gallery.htmlId + ' .strip');

						cms.gallery.selected.fadeIn('fast').draggable('enable').mousedown(); // simulate selection click
					} else {
						alert('Error: ' + data.error);
					}
				},
				error: function (data, status, err) {
					alert(err);
				}
			});
		},
		preview: function() {
			if (this.selected !== null)
				cms.lightbox.show(this.makeImgSrc(this.selected.data('cms').id));
		},
		upload: function() {
			$.ajaxFileUpload({
				url: 'imgsave.php',
				secureuri: false,
				fileElementId: cms.gallery.loadInputId,
				dataType: 'json',
				success: function(data) {
					if (typeof(data.error) != 'undefined') {
						alert(data.error);
					} else {
						cms.gallery.add(data);
					}
				},
				error: function (data, status, err) {
					alert(err);
				}
			});
		}
	}
};

