// vim: set ts=4 sts=4 sw=4 si noet:

fmweb.tinymce = function() {
	var fileBrowserCallback = function(fieldName, url, type, win) {
//		var id = $('#ContentId').val();
		if (typeof($('#ContentId').val()) != "undefined") {
			var id = $('#ContentId').val();
		} else if (typeof($('#PromotionId').val()) != "undefined") {
			var id = $('#PromotionId').val();
		} else if (typeof($('#ProductId').val()) != "undefined") {
			var id = $('#ProductId').val();
		} else {
			var id = $('#ProgrammeId').val();
		}
		var url = fmweb.cfg.base + '/attachments/browse/content_id:' + 
				id + '/type:' + type;

		tinyMCE.activeEditor.windowManager.open({
				file : url,
				title : 'File Browser',
				width : 520,
				height : 400,
				resizable : "yes",
				inline : "yes",
				close_previous : "no",
				popup_css: false
			}, {
				window : win,
				input : fieldName
			});
		return false;
	}

	var selectAttachment = function(evt) {

		var win = tinyMCEPopup.getWindowArg("window");
		var input = tinyMCEPopup.getWindowArg("input");
		var res = tinyMCEPopup.getWindowArg("resizable");
		var inline = tinyMCEPopup.getWindowArg("inline");

		var url = this.attributes.surl.value;

		win.document.getElementById(tinyMCEPopup.getWindowArg("input")).value = url;

		// are we an image browser
		if (typeof(win.ImageDialog) != "undefined") {
			// we are, so update image dimensions...
			if (win.ImageDialog.getImageData)
				win.ImageDialog.getImageData();

			// ... and preview if necessary
			if (win.ImageDialog.showPreviewImage)
				win.ImageDialog.showPreviewImage(URL);
		}

		tinyMCEPopup.close();
	}

	var submitForm = function(evt) {
		tinyMCE.triggerSave();
		return true; // let browser to continue form submission
	}

	var init = function(el) {
		return this;
	}

	var attach = function() {
		var container = $('#attachments-form');
		var count = $('#existing-photos img.content-photo').length + $('div.attachments.element').length;
		if (count < 50) {
			$.get(fmweb.cfg.base + '/contents/attach', 'count=' + count, function(data, stat) {
			$(data).appendTo(container).slideDown();
			});
		} else {
			alert('You can only attach up to 5 photos');
		}
	}

	var attach_img = function() {
		var container = $('#attachments-img-form');
		var count = $('#existing-img img.programme-img').length + $('div.attachments.elements').length;
		if (count < 50) {
			$.get(fmweb.cfg.base + '/programmes/attach_img', 'count=' + count, function(data, stat) {
				$(data).appendTo(container).slideDown();
			});
		} else {
			alert('You can only attach up to 5 photos');
		}
	}

	return {
		field: null,
		init: init,
		selectAttachment: selectAttachment,
		submitForm: submitForm,
		fileBrowserCallback: fileBrowserCallback,
		attach: attach,
		attach_img: attach_img
	}
}().init(this);


