/** @param ctvType can be null */
function jcInsertImgLinkToEmbEditBox(blockSel, backendUrl, entKey, imgSrc, altText, editBoxTitle, ctvType
		, withTitle, pgid, completeBoxUrl) {
	var linkContent = '<img src="' + imgSrc + '" alt="' + altText + '"/>';
	jcInsertLinkToEmbEditBox(blockSel, backendUrl, entKey, linkContent, editBoxTitle, ctvType, withTitle, pgid
			, completeBoxUrl);
}

/** @param ctvType can be null */
function jcInsertLinkToEmbEditBox(blockSel, backendUrl, entKey, linkContent, editBoxTitle, ctvType, withTitle, pgid
		, completeBoxUrl) {
	var elemAddCon = $(blockSel);
	elemAddCon.html(
			'<div class="openEditBoxLink"><a href="#">' + linkContent + '</a></div>\n'
			+ '<div class="editBox" style="display: none;"></div>');
	elemAddCon.show();
	$(blockSel + " a").click(function(e) {
		e.preventDefault();
		jcToggleEmbEditBox(blockSel + " div.editBox", backendUrl, entKey, editBoxTitle, ctvType, withTitle, pgid
				, completeBoxUrl);
	});
}

/** @param ctvType can be null */
function jcToggleEmbEditBox(ebSel, backendUrl, entKey, editBoxTitle, ctvType, withTitle, pgid, completeBoxUrl) {
	var editBox = jcInitEmbEditBox(ebSel, backendUrl, entKey, editBoxTitle, ctvType, withTitle, pgid, completeBoxUrl);
	editBox.toggle();
}

function jcInitPageBox(ebSel, backendUrl) {
	var editBox = new JcEditBox(ebSel, backendUrl, false);
	editBox.initFromLoaded();
}

/** @param ctvType can be null */
function jcInitEmbEditBox(ebSel, backendUrl, entKey, editBoxTitle, ctvType, withTitle, pgid, completeBoxUrl) {
	var editBox = new JcEditBox(ebSel, backendUrl, true);
	editBox.initEmbFromParam(entKey, editBoxTitle, ctvType, withTitle, pgid, completeBoxUrl);
	return editBox;
}

// ---
// --- class JcEditBox
// ---
function JcEditBox(ebSel, backendUrl, bEmbedded) {
	this.bEmbedded = bEmbedded;
	this.ebSel = ebSel;
	this.backendUrl = backendUrl;
	this.globalCancelThreadDate = new Date();
}

JcEditBox.prototype = {

	isLoaded: function() {
		return ($(this.ebSel + " form.edit").size() > 0);
	},

	toggle: function() {
		if (this.isLoaded())
			$(this.ebSel).slideToggle(250);
		else {
			var gthis = this;
			var $editBox = $(this.ebSel);
			$.post(this.backendUrl, {action: "printEmbEditBox", ct: this.ifUndef(this.ctvType, "")
					, wt: this.withTitle ? "1" : "0", ebt: this.editBoxTitle, pgid: this.pgid}, function(html) {
				if (gthis.reportIfXml(html))
					return;
				$editBox.hide();
				$editBox.html(html);
				gthis.initFromLoaded();
				$editBox.slideDown(250);
			});
		}
	},

	initEmbFromParam: function(entKey, editBoxTitle, ctvType, withTitle, pgid, completeBoxUrl) {
		this.entKey = entKey;
		this.editBoxTitle = editBoxTitle;
		this.ctvType = (ctvType == null) ? "" : ctvType;
		this.withTitle = withTitle;
		this.pgid = pgid;
		this.completeBoxUrl = completeBoxUrl;
	},
	
	initFromLoaded: function() {
		var formSel = this.ebSel + " form.edit";
		// - init instance variables
		if (!this.bEmbedded) {
			this.entKey = $(formSel + " input[name='ent']").val();
			this.editBoxTitle = $(formSel + " input[name='ebt']").val();
			this.ctvType = $(formSel + " input[name='ct']").val();  // can be undefined
			this.withTitle = ($(formSel + " input[name='wt']").val() == '1');
			this.pgid = $(formSel + " input[name='pgid']").val();
			this.closeUrl = $(formSel + " input[name='closeUrl']").val();  // undefined when embedded edit box
		}
		// - init events
		this.globalCancelThreadDate = new Date();
		var gthis = this;
		this.reinitButtons();
		$(this.ebSel + " div.reportEndOK a.closeBox").click(function(e) {
			e.preventDefault();
			gthis.close(true);
		});
		if (this.bEmbedded) {
			$(this.ebSel + " .loadPageBox a").click(function(e) {
				e.preventDefault();
			 	gthis.loadPageBox();
			});
		}
		$(formSel + " input[name='preview']").click(function() {
			if (gthis.checkFields())
				gthis.preview();
		});
		$(formSel + " input[name='save']").click(function() {
			if (gthis.checkFields())
				gthis.save();
		});
		$(formSel + " input[name='cancel']").click(function() {
			gthis.close(false);
		});
		$(formSel + " input[name='title']").change(function() {
			gthis.displayOrHideSaveButton();
		});
		$(formSel + " input[name='title']").keyup(function() {
			gthis.displayOrHideSaveButton();
		});
		$(formSel + " input[name='subtitle']").change(function() {
			gthis.displayOrHideSaveButton();
		});
		$(formSel + " input[name='subtitle']").keyup(function() {
			gthis.displayOrHideSaveButton();
		});
		$(formSel + " textarea[name='body']").change(function() {
			gthis.displayOrHideSaveButton();
		});
		$(formSel + " textarea[name='body']").keyup(function() {
			gthis.displayOrHideSaveButton();
		});
	},
	
	checkFields: function() {
		var errMsg = "";
		var formValue;
		var formSel = this.ebSel + " form.edit";
		// - authName
		formValue = $(formSel + " input[name='authName']").val();
		if (formValue == null || formValue == "")
			errMsg += "\n	- Le nom ou pseudo"; // [LANG]
		// - authEmail
		formValue = $(formSel + " input[name='authEmail']").val();
		if (formValue == null || formValue == "")
			errMsg += "\n	- L'e-mail";
		// - title
		if (this.withTitle) {
			formValue = $(formSel + " input[name='title']").val();
			if (formValue == null || formValue == "")
				errMsg += "\n	- Le titre du commentaire";
		}
		// - body
		formValue = $(formSel + " textarea[name='body']").val();
		if (formValue == null || formValue == "")
			errMsg += "\n	- Le contenu du commentaire";
		// - end
		if (errMsg != "") {
			alert("Il manque :" + errMsg); // [LANG]
			return false;
		}
		return true;
	},

	save: function() {
		var gthis = this;
		var localStartThreadDate = new Date();
		// - report
		if (!this.canBeSaved()) {
			this.displayOrHideSaveButton();
			return;
		}
		var formSel = this.ebSel + " form.edit";
		var elemButtons = $(formSel + " input[type='button']");
		elemButtons.attr("disabled", "disabled");
		elemButtons.css("cursor", "wait");
		setTimeout(function() {
			if (gthis.globalCancelThreadDate > localStartThreadDate)
				return;
			var elemSaveButton = $(formSel + " input[name='save']");
			elemSaveButton.attr("value", "Ré-envoyer");  // [LANG]
			elemButtons.css("cursor", "");
			elemButtons.removeAttr("disabled");
			}, 10000);
		this.reportAction("OK", "Envoi des informations d'enregistrement", false);
		// - post
		var authName = $(formSel + " input[name='authName']").val();
		var authEmail = $(formSel + " input[name='authEmail']").val();
		var authUrl = $(formSel + " input[name='authUrl']").val();
		var title = this.withTitle ? $(formSel + " input[name='title']").val() : "";
		var subtitle = this.withTitle ? $(formSel + " input[name='subtitle']").val() : "";
		var body = $(formSel + " textarea[name='body']").val();
		var privateNote = this.ifUndef($(formSel + " textarea[name='privateNote']").val(), "");
		$.post(this.backendUrl, {action: "ctvInsert", authName: authName
				, authEmail: authEmail, authUrl: authUrl, title: title, subtitle: subtitle, body: body, privateNote: privateNote
				, ct: this.ctvType, wt: this.withTitle ? "1" : "0", pgid: this.pgid}, function(xml) {
			if (gthis.globalCancelThreadDate > localStartThreadDate)
				return;
			gthis.globalCancelThreadDate = new Date();
			var code = gthis.report(xml);
			if (code == "OK") {
				$(formSel + " input[type='button']").attr("disabled", "disabled");
				var elemAddAndReport = $(gthis.ebSel + " .addAndReport");
				var elemEndOK = $(gthis.ebSel + " div.reportEndOK");
				elemEndOK.width(elemAddAndReport.width());
				var elemMiddle = $(gthis.ebSel + " div.reportEndOK .middle");
				var paddingArt = Math.max(0, (elemAddAndReport.height() - Math.max(elemMiddle.height(), 96)) / 2);
				elemEndOK.height(elemAddAndReport.height() - paddingArt);
				elemEndOK.css("padding-top", paddingArt);
				elemEndOK.fadeIn();
			} else {
				gthis.reinitButtons();
				gthis.displayOrHideSaveButton();
			}
		});
	},

	preview: function() {
		var gthis = this;
		var formSel = this.ebSel + " form.edit";
		// - fixes in javascript
		this.fixeFieldsInJavascript();
		// - report
		var $previewedBody = $(this.ebSel + " .previewedBody");
		$previewedBody.html("<p class='loading'>Chargement...</p>");
		$previewedBody.slideDown();
		this.reportAction("OK", "Envoi des informations de prévisualisation", false);
		var elemPreviewButton = $(formSel + " input[name='preview']");
		elemPreviewButton.css("cursor", "wait");
		this.displayOrHideSaveButton();
		// - post
		var authName = $(formSel + " input[name='authName']").val();
		var authEmail = $(formSel + " input[name='authEmail']").val();
		var authUrl = $(formSel + " input[name='authUrl']").val();
		var title = this.withTitle ? $(formSel + " input[name='title']").val() : "";
		var subtitle = this.withTitle ? $(formSel + " input[name='subtitle']").val() : "";
		var body = $(formSel + " textarea[name='body']").val();
		var privateNote = $(formSel + " textarea[name='privateNote']").val();
		if (privateNote == null)
			privateNote = "";
		$.post(this.backendUrl, {action: "ctvPreview", authName: authName
				, authEmail: authEmail, authUrl: authUrl, title: title, subtitle: subtitle, body: body, privateNote: privateNote
				, ct: this.ctvType, wt: this.withTitle ? "1" : "0", pgid: this.pgid}, function(html) {
			elemPreviewButton.css("cursor", "");
			if (gthis.reportIfXml(html))
				return;
			gthis.reportAction("OK", "... le contenu est prévisualisé", false); // [LANG]
			$previewedBody.html(html);
			$previewedBody.fadeIn();
			var ctvReadySel = gthis.ebSel + " form.ctvReady";
			if (gthis.withTitle) {
				$(formSel + " input[name='title']").val($(ctvReadySel + " input[name='title']").val());
				$(formSel + " input[name='subtitle']").val($(ctvReadySel + " input[name='subtitle']").val());
			}
			$(formSel + " textarea[name='body']").val($(ctvReadySel + " textarea[name='body']").val());
			$(formSel + " input[name='save']").fadeIn();
		});
	},

	fixeFieldsInJavascript: function() {
		var formSel = this.ebSel + " form.edit";
		var elemAuthUrl = $(formSel + " input[name='authUrl']");
		var authUrl = elemAuthUrl.val();
		var newAuthUrl = this.fixeAuthUrl(authUrl);
		if (authUrl != newAuthUrl)
			elemAuthUrl.val(newAuthUrl);
	},

	fixeAuthUrl: function(url) {
		if (url.length > 0 && url[0] != "/" && url.indexOf("://") == -1)
			return "http://" + url;
		return url;
	},

	reinitButtons: function() {
		var formSel = this.ebSel + " form.edit";
		var elemSaveButton = $(formSel + " input[name='save']");
		var elemButtons = $(formSel + " input[type='button']");
		elemSaveButton.attr("value", "Soumettre");  // [LANG]
		elemSaveButton.hide();
		elemButtons.removeAttr("disabled");
		elemButtons.css("cursor", "");
	},

	canBeSaved: function() {
		var formSel = this.ebSel + " form.edit";
		var ctvReadySel = this.ebSel + " form.ctvReady";
		var $readyBody = $(ctvReadySel + " textarea[name='body']");
		if ($readyBody.size() != 1)
			return false;
		var res = true;
		if (this.withTitle) {
			res = ($(formSel + " input[name='title']").val() == $(ctvReadySel + " input[name='title']").val());
			res &= ($(formSel + " input[name='subtitle']").val() == $(ctvReadySel + " input[name='subtitle']").val());
		}
		if (res)
			res = ($(formSel + " textarea[name='body']").val() == $readyBody.val());
		return res;
	},

	displayOrHideSaveButton: function() {
		var formSel = this.ebSel + " form.edit";
		if (this.canBeSaved())
			$(formSel + " input[name='save']").fadeIn();
		else
			$(formSel + " input[name='save']").fadeOut();
	},

	reportIfXml: function(xmlOrHtml) {
		if (typeof(xmlOrHtml) == "string")
			return false;
		this.report(xmlOrHtml);
		return true;
	},

	report: function(xml) {
		// - type string
		if (typeof(xml) == "string") {
			if (xml == "")
				xml = "Le serveur ne répond rien.";
			this.reportAction("ERR", xml, false);
			return "ERR";
		}
		// - report
		var jXml = $(xml);
		var code = $("code", jXml).text();
		var message;
		if (code == "") {
			code = "ERR";
			message = jXml.text();
		} else
			message = $("message", jXml).text();
		this.reportAction(code, message, false);
		return code;
	},

	reportAction: function(code, message, forceShowing) {
		var elemReport = $(this.ebSel + " .actionReport");
		var style;
		switch (code) {
			case "OK":
				style = " style='color: blue'";
				break;
			case "ERR":
				message = "Erreur : " + message;
				style = " style='color: red; font-weight: bold'";
				break;
			case "WARN":
				message = "Avertissement : " + message;
				style = " style='color: orange'";
				break;
			default:
				style = "";
		}
		elemReport.prepend("<p" + style + ">" + message + "</p>");
		if (forceShowing || code != "OK")
			elemReport.fadeIn();
	},
	
	close: function(reinitBox) {
		if (!this.bEmbedded) {
			window.location.href = this.closeUrl;
			return;
		}
		var gthis = this;
		if ($.browser.msie)
			$(this.ebSel + " div.reportEndOK").hide();
		$(this.ebSel).slideUp(250, function() {
			if (reinitBox) {
				gthis.globalCancelThreadDate = new Date();
				$(gthis.ebSel + " .previewedBody").css("display", "none");
				$(gthis.ebSel + " div.reportEndOK").css("display", "none");
				var formSel = gthis.ebSel + " form.edit";
				$(formSel + " input[name='title']").val("");
				$(formSel + " input[name='subtitle']").val("");
				$(formSel + " textarea").val("");
				$(gthis.ebSel + " div.previewedBody").html("");
				gthis.reinitButtons();
			}
		});
	},

	loadPageBox: function() {
		$(this.ebSel + " .report").html("");
		var formSel = this.ebSel + " form.edit";
		// - save the context
		$(formSel + " input[name='ebt']").val(this.editBoxTitle);
		$(formSel + " input[name='ct']").val(this.ifUndef(this.ctvType, ""));
		$(formSel + " input[name='wt']").val(this.withTitle ? "1" : "0");
		$(formSel + " input[name='pgid']").val(this.pgid);
		// - post the form
		var $form = $(formSel);
		$form.attr("action", this.completeBoxUrl);
		$form.submit();
	},

	ifUndef: function(value, defaultValue) {
		return (value == undefined) ? defaultValue : value;
	}
};

