/*
Questo e' il codice per avere un i-frame modificabile Object Oriented.
Il Secondo parametro specifica un CSS per la pagina editabile (composition) ed e' facoltativo
*/
function IframeEditable(idIframeDoc, internalCSShref) {
	var idIframe = idIframeDoc;
	var strIframeDoc = (document.all) ?
		"document.frames('"+idIframe+"').document" :
		"document.getElementById('"+idIframe+"').contentDocument";
  var internalCSS = internalCSShref;
  /** Specifica il massimo di caratteri consentiti nell'iframe */
  var maxTextLength = 10000;
	
	/** Il costruttore, e' possibile passargli un testo iniziale */
	this.initialize = function(initial) {
		if(initial == null) initial = "";
    var css = "";
    if(internalCSS != null) css = "<link rel=\"stylesheet\" type=\"text/css\" href=\""+internalCSS+"\">";
		var iFrameDoc = eval(strIframeDoc);
		iFrameDoc.open();
		iFrameDoc.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"><html><head><title>Editor Web</title>"+css+"</head><body>"+initial+"</body></html>");
		iFrameDoc.close();
		iFrameDoc.designMode = "On";
		this.setFocus();
	}
	
	/** Restituisce il contenuto esatto dell'editor */
	this.getText = function() {
		return pulisciCodice(eval(strIframeDoc).body.innerHTML);
	}
	
	/** Cancella tutto cio' che e' stato scritto */
	this.cancellaTesto = function() {
		eval(strIframeDoc).body.innerHTML = "";
		this.setFocus();
	}
	
	/** Richiede l'inserimento di un link o una img */
	this.richiestaInserimento = function(tipo, background) {
		if(background == null) background = "none";
		var div = document.createElement("div");
		var divId = "div_generated_by_Editor_instance";
		div.setAttribute("id", divId);
		if(!document.all) div.setAttribute("style", "position:absolute;width:100%;height:100%;top:0px;left:0px;background-image:url("+background+");background-repeat:repeat;z-index:10000;");
		else {	// explorer e' ignorante
			div.style.position = "absolute";
			div.style.width = "100%";
			document.body.style.height = "100%";
			div.style.height = "100%";
			div.style.top = "0px";
			div.style.left = "0px";
			div.style.backgroundImage = "url("+background+")";
			div.style.backgroundRepeat = "repeat";
			div.style.zIndex = "10000";
		}
		document.body.appendChild(div);
		
		var divInt = document.createElement("div");
		divInt.setAttribute("id", "iframeEdRichiestaURL");		
		var input = document.createElement("input");
		input.setAttribute("id", "iframeEdRichiestaInput");
		var butOk = document.createElement("button");
		butOk.appendChild(document.createTextNode("OK"));
		
		/** assegnamento degli eventi ai 2 pulsanti **/
		var thisObject = this;	// devo tenerlo qui, altrimenti non viene visto dall'evento del pulsante ok
		butOk.onclick = function() {
			if(tipo == "img")
				thisObject.inserisciIMG(document.getElementById("iframeEdRichiestaInput").value);
			else if(tipo == "link")
				thisObject.inserisciA(document.getElementById("iframeEdRichiestaInput").value);
			document.body.removeChild(document.getElementById("div_generated_by_Editor_instance"));
			thisObject.setFocus();
		}
		var butClose = document.createElement("button");
		butClose.appendChild(document.createTextNode("Annulla"));
		butClose.onclick = function() {
			document.body.removeChild(document.getElementById("div_generated_by_Editor_instance"));
		}
		
		divInt.appendChild(document.createElement("br"));
		divInt.appendChild(document.createElement("br"));
		divInt.appendChild(document.createElement("br"));
		divInt.appendChild(document.createElement("br"));
		divInt.appendChild(document.createTextNode("inserisci l'indirizzo"));
		divInt.appendChild(document.createElement("br"));
		divInt.appendChild(input);
		divInt.appendChild(document.createElement("br"));
		divInt.appendChild(butOk);
		divInt.appendChild(document.createTextNode(" "));
		divInt.appendChild(butClose);
		
		div.appendChild(divInt);
	}

	/** Sposta il focus sull'iframe modificabile */
	this.setFocus = function() {
		if(document.all)
		 document.frames(idIframe).focus();
		else
		 document.getElementById(idIframe).contentWindow.focus();
		return;
	}
	
	/** Esegue le operazioni interfacciandosi col browser */
	this.formatC = function(what,opt) {
		//alert("eseguo " + what + " con " + opt);
		eval(strIframeDoc).execCommand(what,false,opt);
		this.setFocus();
	}
	
	// inserisce un tag IMG con l'attributo alt="immagine"
	this.inserisciIMG = function(url) {
		var sizes = getProporzioni(url, 400, 400);
		var html = "<img src='"+url+"' alt='immagine'/>";
		if(sizes) html = "<img src='"+url+"' alt='immagine' width='"+sizes[0]+"' height='"+sizes[1]+"'/>";
		if(document.all) { // Se Explorer
			var testoIframe = eval(strIframeDoc).body.innerHTML;
			testoIframe += html;
			this.initialize(testoIframe);
		}
		else this.formatC("inserthtml", html);
	}
	
	// inserisce il tag A sul testo selezionato col valore in input
	this.inserisciA = function(url) {
		var html = "<a href='"+url+"' target='_blank'>"+url+"</a>";
		if(document.all) { // Se Explorer
			var testoIframe = eval(strIframeDoc).body.innerHTML;
			testoIframe += html;
			this.initialize(testoIframe);
		}
		else this.formatC("inserthtml", html);
	}
	
	// restituisce un array con width e height ridimensionate in proporzione
	function getProporzioni(imgURL, maxWidth, maxHeight) {
		var img = new Image();
		img.src = imgURL
		var width = img.width;
		var height = img.height;
		if(width == 0 || height == 0) return null;
		var scale = Math.min(maxWidth/width, maxHeight/height);
		if(scale < 1) return new Array(Math.floor(scale*width), Math.floor(scale*height));
		return new Array(width, height);
	}
	
	// pulisce tutti gli orrori generati da Explorer
	function pulisciCodice(codice){   
	  codice = codice.replace(/</g,"<");
	  /*
	  codice = codice.replace(/<\/font\>/gi,"</span>");
	  codice = codice.replace(/(<font )(color)(=)([A-Za-z0-9]*)/gi,"<span style=\"$2:$4;\"");
	  codice = codice.replace(/(<font )(face)(=)([A-Za-z0-9]*)/gi,"<span style=\"font-family:$4;\"");
	  codice = codice.replace(/(<font )(size)(=\")([A-Za-z0-9]*)\"/gi,"<span style=\"font-size:$4px;\"");
	  //codice = codice.replace(/(<font )(size)(=\")([0-9]*)\">(.*)<\/font>/gi,"<span style=\"font-size:$4px;\">$5</span>");
	  codice = codice.replace(/(<font )(size)(=)([0-9]*)/gi,"<span style=\"font-size:$4px;\"");
	  codice = codice.replace(/(<font )(color)(=)(#?([A-Fa-f0-9]){3}(([A-Fa-f0-9]){3})?)/gi,"<span style=\"$2:$4;\""); //internet explorer
	  codice = codice.replace(/(<font )(color)(=\")(#?([A-Fa-f0-9]){3}(([A-Fa-f0-9]){3})?)(\")/gi,"<span style=\"$2:$4;\""); //opera
	  */
		codice = codice.replace(/(<p )(align)(=)([A-Za-z]*)(>)(.*)(<\/p\>)/gi,"<div style=\"text-align: $4;\">$6</div>"); // per explorer
		codice = codice.replace(/(<div )(align)(=\")([A-Za-z]*)(\")(>)(.*)(<\/div\>)/gi,"<div style=\"text-align:$4;\">$7</div>"); // opera
		codice = codice.replace(/(<em\>)(.*)(<\/em\>)/gi,"<span style=\"font-style: italic;\">$2</span>");	// per Explorer
		codice = codice.replace(/(<i\>)(.*)(<\/i\>)/gi,"<span style=\"font-style: italic;\">$2</span>");	// per Opera
		codice = codice.replace(/(<p\>)\&nbsp\;(<\/p\>)/gi,"<br/>");  // il break di Explorer
		return codice;
	}
	
	// crea un i frame senza src e lo aggiunge al componente specificato (iframeEditableContainer se non specificato)
	this.creaIframe = function(containerId) {
		if(containerId == null || containerId == "") containerId = "iframeEditableContainer";	// nome default
		var iframe = document.createElement("iframe");
		iframe.setAttribute("id", idIframe);
		iframe.setAttribute("frameBorder", 0); // frameborder non funziona!! La B va maiuscola!!!!! Fottuto Explorer!
		document.getElementById(containerId).appendChild(iframe);
	}
	
	// inserisce il contenuto dell'iframe nel campo specificato e fa un submit del form specificato
	this.inviaDati = function(formId, inputId) {
		try {
			var testo = this.getText();
			if(testo != "" || testo == "<br/>" || testo.length <= maxTextLength) {
				document.getElementById(inputId).value = testo;
				document.getElementById(formId).submit();
			}
			else return false;
		}
		catch(e) {alert(e);return false;}
	}
}
