$.fn.chpText = function(options) {
	this.each(function(i, el) {
		new $.chp.Text(el, options);
	});
	return this;
};

if (!$.chp) $.chp = {};

$.chp.Text = function() { return this.initialize.apply(this, arguments); };

$.chp.Text.prototype = {
	initialize: function(el, options) {
		this.el = el;
		this.dragging = false;
		
		this.options = $.extend({
			onEdit: function(){},
			onMove: function(){},
			onSave: function(){},
			draggable: true,
			placeholderContent: false,
			toolbarButtons: { edit: 'Edit', remove: 'Remove' },
			toolbarClassName: '',
			toolbarOffset: [0, 0]
		}, options);
		
		this.boundModalSave   = $.bind(this, this.modalSave);
		this.boundModalCancel = $.bind(this, this.modalCancel);
		
		this.editToolbar = new $.chp.EditToolbar(this.el, {
			click: $.bind(this, this.editToolbarClick),
			className: this.options.toolbarClassName,
			buttons: this.options.toolbarButtons,
			offset: this.options.toolbarOffset
		});
		
		if (this.options.draggable) {
			$(el).
				draggable({
					grid: [10, 10],
					start: $.bind(this, this.dragStart),
					stop:  $.bind(this, this.dragStop)
				});
		}
	},
	
	modalSave: function() {
		this.modalClose();
		setTimeout($.bind(this, function() {
			this.el.innerHTML = tinyMCE.activeEditor.getContent();
			this.options.onEdit();
			this.options.placeholderContent = false;
		}), 200);
	},
	
	modalCancel: function() {
		this.modalClose();
	},
	
	modalClose: function() {
		$('#textModal .save').unbind('click', this.boundModalSave);
		$('#textModal .cancel').unbind('click', this.boundModalCancel);
		$('#textModal').fadeOut(200);
		$.unblockUI();
	},
	
	edit: function() {
		$.blockUI({ message: '' });
		
		if (this.options.placeholderContent) {
			tinyMCE.activeEditor.setContent('');
		} else {
			tinyMCE.activeEditor.setContent(this.el.innerHTML);
		}
		
		$('#textModal .save').click(this.boundModalSave);
		$('#textModal .cancel').click(this.boundModalCancel);
		
		$('#textModal').fadeIn(200);
	},
	
	remove: function() {
		this.editToolbar.setEnabled(false);
		this.editToolbar.hide();
		$(this.el).addClass('remove');
		if (confirm('Are you sure you want to remove this text box?')) {
			var self = this; $(this.el).slideUp(100, function() { $(this).remove(); });
			this.options.onRemove();
		} else {
			$(this.el).removeClass('remove');
			this.editToolbar.setEnabled(true);
		}
	},
	
	editToolbarClick: function(name) {
		this.editToolbar.hide();
		this[name]();
	},
	
	dragStart: function() {
		this.editToolbar.setEnabled(false);
		this.editToolbar.hide();
	},
	
	dragStop: function() {
		this.editToolbar.setEnabled(true);
		this.editToolbar.beginShow();
		this.options.onMove();
	}
};
