
tinyMCE.init({
	plugins : "imagemanager",
	convert_urls : true,
	relative_urls : false,
	urlconverter_callback : "urlConvert"
});


imagePreviewer = new ImagePreviewer();



/**
 * This class is used to keep track of image preview div elements
 * that we will need to update after an image has been selected
 * using the TinyMCE Image Manager.
 *
 * This is needed because image manager will update the input fields
 * but there's no way to tell it to update another html element via
 * its callback mechanism.
 */
function ImagePreviewer() {
	this.pairs = [];   // Array of objects with attributes:
			   // inputId   - the id of the input element that holds the image path
			   // previewId - the id of the div element that will show the image preview
}
/**
 * Keep track of the input fields that will be updated by image manager,
 * and their corresponding preview img elements.
 */
ImagePreviewer.prototype.add = function(inputId, previewId) {
	for (var i=0; i<this.pairs.length; i++) {
		if (this.pairs[i].inputId == inputId) {
			return;  // We don't want duplicates.
		}
	}
	this.pairs.push({
		inputId: inputId,
		previewId: previewId
	});
}
/**
 * Sync the preview images with the image path that's been inserted in the
 * input elements by image manager.
 */
ImagePreviewer.prototype.update = function() {
	for (var i=0; i<this.pairs.length; i++) {
		inputEl = document.getElementById(this.pairs[i].inputId);
		previewEl = document.getElementById(this.pairs[i].previewId);
		if (inputEl && previewEl) {
			previewEl.innerHTML = "<img src=\"/image.php?file=" 
				+ inputEl.value 
				+ "&width=100&height=100\" alt=\"\" />";
		} else {
			alert('Could not update the image previewer');
		}
	}
}




function urlConvert(url, node, on_save) {
	if (url.match("#")) {
		// If the URL is the current page, strip the url
		if (url.indexOf("/edit") != -1) {
			url = url.replace("/edit", "");
		}
	}
	url = url.replace(location.protocol + "//" + location.host + "/", "");
	url = url.replace(/\/*?resources\//, "/resources/");
	return url;
}


/**
 * Opens the TinyMCE image picker/manager.
 */
function launchImageManager(formName, inputId, previewId) {
	var inputEl = document.getElementById(inputId);

	if (inputEl) {
		mcImageManager.open(
			formName, 
			inputEl.name, 
			'', 
			'changeImage', 
			{}
		);
		imagePreviewer.add(inputId, previewId);
	} else {
		alert('Could not open the image manager.');
	}
}


/**
 * Update the form with the selected image.
 */
function changeImage(url) {
	url = url.replace("http://" + window.location.hostname, "");
	mcImageManager.insertFileToForm(url);
	imagePreviewer.update();
	return true;
}



