/**
 * Classe per mini editor
 * @name		editor.js
 * @encoding	UTF-8
 * @project		Socialnet - trilla.it
 * @package		trilla
 * @author		Giorgio Tonelli <giorgio.tonelli@staff.libero.it>, <giorgio.tonelli@email.it>,www.thantalas.net
 * @creation	04/jun/09
 * @version		1.0
 */



Libero.SimpleEditor=Class.create();
Libero.SimpleEditor.prototype = {
	options: {
		titleMaxChar: 10,
		descMaxChar: 10,
		titleField:'postTitle',
		textField:'postText',
		moreOptionsContainer:'editor-area-moreoptions-container',
		moreOptionsLik:'editor-area-moreoptionsLink',
		openTag:'[',
		closeTag:']',
		titleMaxChar:100,
		textMaxChar:1024,
		descLinkMaxChar:100,
		titleLinkMaxChar:100,
		descFotoMaxChar:1024,
		descVideoMaxChar:100,
		urlVideoMaxChar:300,
		quoteMaxChar:1024,
		urlsMaxChar:100,
		textareaMinHeight:40,
		textareaMaxHeight:300,
		errorDiv:'editor-error',
		debug: false,
		useAjax:1
	},
	
	initialize: function(options){
		this._setoptions(options);
		this.ot=this.options.openTag;
		this.et=this.options.closeTag;
		this.currentTab=0;
		this.taburl=[];
		this.taburl[0]={'url':'','div':'editor-area-text','bkgx':'16'};
		this.taburl[1]={'url':'','div':'editor-area-link','bkgx':'70'};
		this.taburl[2]={'url':'','div':'editor-area-foto','bkgx':'118'};
		this.taburl[3]={'url':'','div':'editor-area-video','bkgx':'171'};
		this.taburl[4]={'url':'','div':'editor-area-qoute','bkgx':'239'};
		this.tablink=[];
		this.tablink=$c('editor-tab','li');
		this.tabFotoSwitch=0;
		this.divErrorObj='';
		this.topMenuLink=[];

		this.selectText = '';
		this.selectTextstartPos = 0;
		this.selectTexendPos = 0;
		this.timeoutEditorCssClass=null;

		menua=$('editor-menu').getElementsByTagName('a');
		for(i=0;i<menua.length;i++){
			this.topMenuLink[i]={};
			this.topMenuLink[i].obj=menua[i];
			this.topMenuLink[i].click=menua[i].onclick;
		}
		edField=$c('editor-field');
	},
	/**
	 * ripopolo corretto dei dati in un form provenientoi da json dopo inoltro form
	 * @param {Object} form modulo 
	 * @param {Object} json dati json
	 */
	_setFormFieldRightValues: function(form, json){
		if (typeof(json.params) !== 'undefined') {
			return;
		}
		if (typeof(json.params) !== 'undefined') {
			for (var obj in json.params) {
				jj = json.params[obj];
				if (jj.status == true) {
				}
				else {
					if (typeof(jj.errmsg) != 'undefined' && jj.errmsg != 'undefined') {
						errormsg += jj.errmsg;
					}
				}
				if (typeof(form[obj]) == 'object') {
					if (typeof(jj.value) != 'undefined') {
						if (typeof(jj.value) != 'Array') {

							if (form[obj].type == 'text' || form[obj].type == 'textarea') {
								setFieldValue(form[obj], jj.value);
							}
						}
					}
				}
			}
		}
	},
	
	/**
	 * prima dell'invio del form setta i campi con il valore di default a vuoti
	 * @param {Object} form form da elaborare
	 */
	_setEmptyDefVal: function(form){
		fl=form.elements.length;
		if (fl > 0) {
			for (i = 0; i < fl; i++) {
				el = form.elements[i];
				if (el.type == "text" || el.type == "textarea") {
					r=null;
					c=null;
					if(r=el.getAttribute('rel')){// valore di defautl
						if(r==getFieldValue(el).text){
							setFieldValue(el,'');
						}
					}
				}
			}
		}	
	},
	/**
	 * dopo  l'invio del form setta i campi con il valore di default a vuoti
	 * @param {Object} form form da elaborare
	 */
	_setDefVal: function(form){
		fl=form.elements.length;
		if (fl > 0) {
			for (i = 0; i < fl; i++) {
				el = form.elements[i];
				if (el.type == "text" || el.type == "textarea") {
					r=null;
					c=null;
					if(r=el.getAttribute('rel')){// valore di defautl
						if(!getFieldValue(el).len){
							setFieldValue(el,r);
					   }
					}
				}
			}
		}	
	},
	/**
	 * invia il form tramite ajax
	 * @param {Object} form 
	 */
	_sendForm: function(form){
		var _this=this;
 		var hxr=new Libero.Request({
			url: 'scrivi.php',
			method: 'post',
				secure : true, 
				requestType: 'json',
			data : {}
		});
		
		//this._setEmptyDefVal(form);
		hxr.onSuccess = function(){
			//_this._hidePreload();

			if(json.status==true){
				// json.params
				window.location.href=json.reload;
				return;
			}else{
				_this._hidePreload();
				_this._showError(json.errormessage);
			}
			//_this._setFormFieldRightValues(form, json);
		}
		hxr.onFailure = function(){
			_this._hidePreload();
			_this._setDefVal(form);
			_this._showError('<h2>Servizio momentaneamente non raggiungibile!</h2> <p>Si è verificato un errore durante la verifica. Prego riprovare più tardi</p>');
		}.bind(this);
		hxr.send(form);
	},
	/**
	 * controllo dei dati form prima dell'invio
	 * @param {Object} form 
	 * @param {Integer} w  numero progressivo 
	 */
	sendForm: function(formm,w){
		success=true;
		error='';
		switch(w){
			//testo
			case 0:
				// titolo
				ta=$(this.options.titleField);
				tval=this._getFieldValue(ta);
				rel=ta.getAttribute('rel').toLowerCase();
				if(rel==tval.text.toLowerCase()){
					this._setFieldValue(ta,'');
				}else{
					if(tval.len>this.options.textMaxChar){
						error +='Il titolo inserito è troppo lungo:<br />sono ammessi massimo '+this.options.titleMaxChar+' caratteri <br />';
						success = false;
					}
				}
				// testo 
				ta=$(this.options.textField);
				tval=this._getFieldValue(ta);
				rel=ta.getAttribute('rel').toLowerCase();
				if(rel==tval.text.toLowerCase() || tval.len==0){
					error +='Inserire correttamente il testo del messaggio <br />';
					success = false;
				}
				if(tval.len>this.options.textMaxChar){
					error +='Il testo inserito è troppo lungo:<br />sono ammessi massimo '+this.options.textMaxChar+' caratteri <br />';
					success = false;
				}
				if(success){
					formm.useAjax.value=this.options.useAjax;
				}
			break; // fine testo
			
			// link
			case 1:
				// descrizione 
				ta=$('linkDesc');
				tval=this._getFieldValue(ta);
				rel=ta.getAttribute('rel').toLowerCase();
				if(rel==tval.text.toLowerCase()){
					this._setFieldValue(ta,'');
				}else{
					if(tval.len>this.options.descLinkMaxChar){
						error +='Il testo inserito per la descrizione del link  è troppo lungo:<br />sono ammessi massimo '+this.options.descLinkMaxChar+' caratteri <br />';
						success = false;
					}
				}
				tlinkUrl=$('linkUrl');
				tvallinkUrl=this._getFieldValue(tlinkUrl);
				if (tvallinkUrl.text.indexOf('http://') == -1) {
					tvallinkUrl.text='http://'+tvallinkUrl.text;
				}
				this._setFieldValue(tlinkUrl,tvallinkUrl.text);
				if(validateUrl(tvallinkUrl.text)){
					if(tvallinkUrl.len>this.options.urlsMaxChar){
						error +='Il  link è troppo lungo:<br />sono ammessi massimo '+this.options.urlsMaxChar+' caratteri <br />';
						success = false;
					}
				}else{
					error +='Inserire correttamente un url valido <br />';
					success = false;
				}
				if(success){
					formm.useAjax.value=this.options.useAjax;
				}
			break;// fine link
			// upload
			case 2:
				ta=$('fotoDesc');
				tval=this._getFieldValue(ta);
				rel=ta.getAttribute('rel').toLowerCase();
				if(rel==tval.text.toLowerCase()){
					this._setFieldValue(ta,'');
				}else{
					if(tval.len>this.options.descFotoMaxChar){
						error +='Il testo inserito per la descrizione della foto è troppo lungo:<br />sono ammessi massimo '+this.options.descFotoMaxChar+' caratteri <br />';
						success = false;
					}
				}
				if(success){
					// 0 link web 1 upload
					tval=this._getFieldValue($('editor-foto-uploadflag')); 
					fotoType=tval.text;
					tfoloLink=$('fotoLink');
					tvalfotoLink=this._getFieldValue(tfoloLink);
					if(fotoType==0){// link web
						if (tvalfotoLink.text.indexOf('http://') == -1) {
							tvalfotoLink.text='http://'+tvalfotoLink.text;
						}
						this._setFieldValue(tfoloLink,tvalfotoLink.text);
						if(validateUrl(tvalfotoLink.text)){
							if(tvalfotoLink.len>this.options.urlsMaxChar){
								error +='L\'indirizzo dell\' immagine è troppo lungo:<br />sono ammessi massimo '+this.options.urlsMaxChar+' caratteri <br />';
								success = false;
							}
						}else{
							error +='Inserire correttamente un url valido <br />';
							success = false;
						}
						if(success){
							this._showPreload();
							formm.useAjax.value=this.options.useAjax;
						}
					}else{// upload
						this._showPreload();
						formm.useAjax.value=0;
						return true;
					}
				}
			break;// fine foto
			// video
			case 3:
				ta=$('videoDesc');
				tval=this._getFieldValue(ta);
				rel=ta.getAttribute('rel').toLowerCase();
				if(rel==tval.text.toLowerCase()){
					this._setFieldValue(ta,'');
				}else{
					if(tval.len>this.options.descVideoMaxChar){
						error +='Il testo inserito per la descrizione del video è troppo lungo:<br />sono ammessi massimo '+this.options.descVideoMaxChar+' caratteri <br />';
						success = false;
					}
				}
				tvideoUrl=$('videoUrl');
				tvalvideoUrl=this._getFieldValue(tvideoUrl);
				if (tvalvideoUrl.text.indexOf('http://') == -1) {
					tvalvideoUrl.text='http://'+tvalvideoUrl.text;
				}
				this._setFieldValue(tvideoUrl,tvalvideoUrl.text);
				if(tvalvideoUrl.len>this.options.urlVideoMaxChar){
					error +='L\'indirizzo o il codice del video è troppo lungo:<br />sono ammessi massimo '+this.options.urlVideoMaxChar+' caratteri <br />';
					success = false;
				}
				if(success){
					formm.useAjax.value=this.options.useAjax;
				}
			break;// fine video
			// citazione
			case 4:
				tquoteLink=$('editor-quote-link');
				tvalquoteLink=this._getFieldValue(tquoteLink);
				if (tvalquoteLink.text.indexOf('http://') == -1) {
					tvalquoteLink.text='http://'+tvalquoteLink.text;
				}
				this._setFieldValue(tquoteLink,tvalquoteLink.text);
				if(validateUrl(tvalquoteLink.text)){
					if(tvalquoteLink.len>this.options.urlsMaxChar){
						error +='L\'indirizzo di riferimento per la citazione è troppo lungo:<br />sono ammessi massimo '+this.options.urlsMaxChar+' caratteri <br />';
						success = false;
					}
				}else{
					error +='Inserire correttamente un url valido <br />';
					success = false;
				}
				// testo 
				ta=$('quoteText');
				tval=this._getFieldValue(ta);
				rel=ta.getAttribute('rel').toLowerCase();
				if(rel==tval.text.toLowerCase() || tval.len==0){
					error +='Inserire correttamente il testo per la citazione <br />';
					success = false;
				}
				if(tval.len>this.options.quoteMaxChar){
					error +='La citazione inserita è troppo lunga:<br />sono ammessi massimo '+this.options.quoteMaxChar+' caratteri <br />';
					success = false;
				}
				if(success){
					formm.useAjax.value=this.options.useAjax;
				}
			break;// fine citazione
		}
		if(success){
			if(this.options.useAjax==1){
				this.currentform=formm;
				this._showPreload();
				this._sendForm(formm);
			}else{
				return true;
			}
		}else{
			formm.useAjax.value=0;
			this._showError(error);
		}
		return false ;
	},

	/**
	 * switch dei tab per post di foto
	 * @param {Integer} w  numero progressivo  tab
	 */
	swicthFotoField: function(w){
		if(w != this.tabFotoSwitch){
			if(w==0){// da web
				removeClass($('editor-foto-switch2'),'editor-switch-int-active');
				addClass($('editor-foto-switch1'),'editor-switch-int-active');
				$s('editor-foto-switch-web').display='block';
				$s('editor-foto-switch-upload').display='none';
				this._setFieldValue($('editor-foto-uploadflag'),'0');
				
			}else{// da pc
				removeClass($('editor-foto-switch1'),'editor-switch-int-active');
				addClass($('editor-foto-switch2'),'editor-switch-int-active');
				$s('editor-foto-switch-upload').display='block';
				$s('editor-foto-switch-web').display='none';
				this._setFieldValue($('editor-foto-uploadflag'),'1');
			}
			this.tabFotoSwitch=w;
		}
		
	},
	/**
	 * switch dei tab dell'editor
	 * @param {Integer} w  numero progressivo  tab
	 */
	sowTab: function(w){
		olde=$(this.tablink[this.currentTab]);
		removeClass(olde,'editor-tab-active')
		
		this.currentTab
		if(tl=$(this.tablink[w])){
			if(!hasClass(tl,'editor-tab-active')){
				addClass(tl,'editor-tab-active');
			}
		}
		var t=$(this.taburl[w].div);
		ct=this.taburl[this.currentTab].div;
		$s(ct).display='none';
		$s(t).display='block';
		arrox=this.taburl[w].bkgx;
		$s('editorbox-inside').backgroundPosition=arrox+ 'px 0'
		if(w==0){
			$s('editor-area-moreoptions').display='block';
		}else{
			$s('editor-area-moreoptions').display='none';
		}
		this.currentTab=w;
	},
	
	/**
	 * prende il testo e la lunghezza dei valori di un campo
	 * @param {Object} ta campo form
	 * @return {Object}
	 */
	_getFieldValue: function(ta){
		return getFieldValue(ta);
	},
	/**
	 * setta il testo di un campo
	 * @param {Object} ta campo form
	 * @param {String} value testo da inserire
	 */
	_setFieldValue: function(ta,value){
		if (typeof ta.value!='undefined') {
			ta.value=value;
		}else {
			if (typeof ta.textContent!='undefined') {
				ta.textContent=value;
			}
			if (typeof ta.innerText!='undefined') {
				ta.innerText=value;
			}else{
				ta.innerHTML=value;
			}	
		}
	},
	/**
	 * visualizza il div del preload
	 */
	_showPreload: function(){
		createPageVeil();
		for(i=0;i<this.topMenuLink.length;i++){
			this.topMenuLink[i].obj.onclick=null;
		}
		Libero.Utils.prototype.setOpacity($('editor-menu'),0.5);
		if(typeof(this.currentform) =='object'){
			for(i=0;i<this.currentform.length;i++){
				this.currentform.elements[i].disabled=true;
			}
		}
		if(el=$('editorplssubmit'+this.currentTab)){
			//el.disabled=true;
			//el.style.display='none';
		}
		//Libero.Utils.prototype.setOpacity($('editorbox-inside'),0.5);
		preload=$s('editor-area-ajaxpreload');
		preload.display='block';
	},
	/**
	 * nasconde il div del preload
	 */
	_hidePreload: function(){
		removePageVeil();
		for(i=0;i<this.topMenuLink.length;i++){
			this.topMenuLink[i].obj.onclick=this.topMenuLink[i].click;
		}
		Libero.Utils.prototype.setOpacity($('editor-menu'),1);
		if(typeof(this.currentform) =='object'){
			for(i=0;i<this.currentform.length;i++){
				this.currentform.elements[i].disabled=false;
			}
		}
		this.currentform=false;
		if(el=$('editorplssubmit'+this.currentTab)){
			el.disabled=false;
			el.style.display='block';
		}
		$s('editor-area-ajaxpreload').display='none';
	},
	/**
	 * visualizza il campo del titolo del post e il pulsanti del mini editor
	 */
	showOptions: function(){
		moc=$(this.options.moreOptionsContainer);
		mocl=$(this.options.moreOptionsLik);
		if($s(moc).display!='block'){
			$s(moc).display='block';
			mocl.innerHTML='Meno opzioni';
		}else{
			mocl.innerHTML='Pi&ugrave; opzioni';
			$s(moc).display='none';
		}
	},
	/**
	 * rimette  il testo di default in un campo for prendedolo dall'attributo rel 
	 * nel caso in cui l'utente lasci vuoto il campo
	 *  @param {Object} field  
	 */
	restoreDefaultText: function(field){
		var _this=this;
		if(field.type=='textarea'){
			this.timeoutEditorCssClass= setTimeout(
				function(){
					removeClass(field,'editor-field-active');
					clearTimeout(_this.timeoutEditorCssClass);
				},80
			);
		}else{
			removeClass(field,'editor-field-active');
		}
		val=field.value.length;
		rel=field.getAttribute('rel');
		if(val<=0){
			//field.style.color='#999999';
			field.value=rel;
		}
	},
	/**
	 * rimuove il testo di default da un campo di un form
	 *  @param {Object} field 
	 */
	removeDefaultText: function(field){
		if (!hasClass(field, 'editor-field-active')) {
			addClass(field,'editor-field-active');
		}
		val=field.value.toLowerCase();
		rel=field.getAttribute('rel').toLowerCase();
		if(val==rel){
			field.value='';
		}
	},
	/**
	 * Inserisce in un campo form il valore di un altro campo
	 *  @param {Object} src  campo sorgente
	 *  @param {Object} dest campo destinazione  
	 */
	setHiddenValue: function(src,dest){
		if (typeof src.value!='undefined') {
			dest.value=src.value;
		}else{
			if (typeof src.textContent!='undefined') {
				dest.textContent=src.textContent;
			}
			if (typeof src.innerText!='undefined') {
				dest.innerText=src.innerText;
			}else{
				dest.innerHTML=src.innerHTML;
			}	
		}
	},

	/**
	 * rimuove prompt html
     *  @param {Object} ele div da nascondere  
	 */
	_hidePrompt: function(ele){
		ele.style.left ='-1000px';
		ele.style.top ='-1000px';
		ele.style.display='none';
		setFieldValue($('editorThelink'),'http://');
	},
	/**
	 * visualizza prompt html per l'inserimento dei link
	 * 	@param {Object} textArea  oggetto dom textarea 
	 *  @param {Object} elemContainer  oggetto dom contenitore textarea 
	 */
	_showPrompt: function(textArea,elemContainer){
		if(this.timeoutEditorCssClass){
			clearTimeout(this.timeoutEditorCssClass);
		}
		
	    var  coords; 
		var _this=this;
		if(typeof(textArea)!='object'){
			textArea=$('postText');
		}
		if(typeof(elemContainer)!='object'){
			elemContainer=$('editorMsgBodyContainer');
		}
	    coords = getPageCoords(elemContainer); 
		var linkdiv=$('editorInsertLink');
		var linkVal;
		linkdiv.style.left =coords.x + 'px';
		linkdiv.style.top =(coords.y -40)+ 'px';
		linkdiv.style.display='block';
		conf=$('editorConfirmLinkButton');
		this.setSelRange($('editorThelink'), 8, 8);
		
		$('editorThelink').onkeyup=function(event){
			if ( typeof event == "undefined" ) event = window.event
			if(event.keyCode==13){
				error=''
				success=true;
				linkVal=getFieldValue($('editorThelink'));
				if(validateUrl(linkVal.text)){
					if(linkVal.len>_this.options.urlsMaxChar){
						error +='L\'indirizzo   è troppo lungo:<br />sono ammessi massimo '+_this.options.urlsMaxChar+' caratteri <br />';
						success = false;
					}
				}else{
					error +='Inserire correttamente un url valido <br />';
					success = false;
				}
				if (success) {
					_this._realInsertLink(linkVal.text,textArea);
					_this._hidePrompt(linkdiv);
				}else {
					_this._showError(error);
				}
			}

		}
		conf.onclick=function(){
			error=''
			success=true;
			linkVal=getFieldValue($('editorThelink'));
			if(validateUrl(linkVal.text)){
				if(linkVal.len>_this.options.urlsMaxChar){
					error +='L\'indirizzo   è troppo lungo:<br />sono ammessi massimo '+_this.options.urlsMaxChar+' caratteri <br />';
					success = false;
				}
			}else{
				error +='Inserire correttamente un url valido <br />';
				success = false;
			}
			if (success) {
				_this._realInsertLink(linkVal.text,textArea);
				_this._hidePrompt(linkdiv);
			}else {
				_this._showError(error);
			}
		};
		
		unconf=$('editorcloseLinkBox');
		unconf.onclick=function(){
			_this._hidePrompt(linkdiv);
		};
	},

	/**
	 * Apre la finestra di dialogo del prompt per il link
	 * 	@param {Object} textArea  oggetto dom textarea 
	 *  @param {Object} elemContainer  oggetto dom contenitore textarea 
	 */
	insertLink: function(textArea,elemContainer){
		this._showPrompt(textArea,elemContainer);
	},
	
	/**
	 * setta il la posizione del cursore nella test area dopo l'inserimento di short tag
	 * @param {Object} ele elemento dom
	 * @param {Int} start posizione inizio
	 * @param {Int} end posizione fine
	 */
	setSelRange: function(ele, start, end) {
		if (ele.setSelectionRange) {
			ele.focus(); 
			ele.setSelectionRange(start, end);  
		} else if (ele.createTextRange) {
			var range = ele.createTextRange();  
			range.collapse(true);  
			range.moveEnd('character', end); 
			range.moveStart('character', start); 
			range.select();  
		}
	},
	/**
	 * Inserisce tag nell'editor in stile forum (shortTag)
	 *  @param {String} tag  
	 *  @param {Object} textArea  oggetto dom textarea 
	 */
	insertTag: function(tag,textArea){
		if(this.timeoutEditorCssClass){
			clearTimeout(this.timeoutEditorCssClass);
		}
		if(typeof(textArea)=='undefined'){
			this.textf=$(this.options.textField);
		}else{
			this.textf=textArea;
		}
		this.removeDefaultText(this.textf);
		if (!hasClass(this.textf, 'editor-field-active')) {
			addClass(this.textf,'editor-field-active');
		}
		defTxt=this.textf.getAttribute('rel');
		curText=getFieldValue(this.textf).text;
		textBefore=this.ot + tag + this.et;
		textAfter=this.ot + '/' + tag + this.et;
		var startPos =this.selectTextstartPos;
		var endPos = this.selectTexendPos;
		this.selectTextstartPos+=textBefore.length;
		this.selectTexendPos=this.selectTextstartPos;
		var valueLen=this.textf.value.length;
		if (document.selection) {// ie 
		  selectedText=curText.substring(startPos, endPos);
			if(startPos==endPos){
				nextSelection=(curText.substring(0, startPos) + textBefore + selectedText).length;
				this.textf.value = curText.substring(0, startPos) + textBefore + selectedText + textAfter +  curText.substring(endPos, valueLen);
			}else{
				startPos+=(this.crlf-1);
				if(curText.substring(startPos, endPos)!=''){
					nextSelection=(curText.substring(0, startPos) + textBefore+ curText.substring(startPos, endPos) +textAfter).length-(this.crlf-1);
					this.textf.value = curText.substring(0, startPos) + textBefore+ curText.substring(startPos, endPos) +textAfter+  curText.substring(endPos, valueLen);
				}else{
					nextSelection=(curText.substring(0, startPos) + textBefore).length-(this.crlf-1);
					this.textf.value = curText.substring(0, startPos) + textBefore+ textAfter+  curText.substring(endPos, valueLen);
				}
			}
			this.textf.focus();
			this.setSelRange(this.textf,nextSelection,nextSelection);
/*
		    this.textf.focus();
		 	sel =document.selection.createRange();
			if(sel.text!=''){
				sel.text =textBefore+ sel.text +textAfter
				sel.select();
				window.focus();// forzatura 
				this.textf.focus();
			}else{
				sel.text =textBefore+textAfter; 
				this.setSelRange(this.textf,this.selectTextstartPos,this.selectTexendPos);
				this.textf.focus();
			}
*/
		  } else if (this.textf.selectionStart || this.textf.selectionStart == '0') {
			var startPos = this.textf.selectionStart;
			var endPos = this.textf.selectionEnd;
			selectedText=this.textf.value.substring(startPos, endPos);
			
			this.textf.value = this.textf.value.substring(0, startPos) + this.ot + tag + this.et + selectedText + this.ot + '/' + tag + this.et +  this.textf.value.substring(endPos, valueLen);
			if(selectedText.length>0){
				this.textf.selectionEnd=endPos+((textAfter.length *2)-1);
			}else{
				this.textf.selectionStart=endPos+(textAfter.length);
				this.textf.selectionEnd=this.textf.selectionStart-1;
			}
			this.textf.focus();
		  } else {
		     this.textf.value +=  this.ot + tag + this.et  + this.ot + '/' + tag + this.et ;
			 this.textf.focus();
		  }
	},
	/**
	 * salva il range di testo selezionato 
	 * @param {Object} textarea   textarea corrente
	 */
	saveTextRange: function(textarea){
		// opera firefox etc
		taValue=getFieldValue(textarea).text;
		if (typeof(textarea.selectionStart) == 'number'){	
			this.selectTextstartPos=textarea.selectionStart;
		}else if(document.selection){//per quel maledetto di ie
			var selectionRange = document.selection.createRange().duplicate();
			this.selectText= document.selection.createRange();
			if (selectionRange.parentElement() == textarea) {// controllo se la selezione è sulla ta corrente
				/**
				 * Creiamo 3 range che contengano :
				 * 1: testo prima di selezione
				 * 2: testo selezionato
				 * 3: testo dopo la selezione
				 */
				var rangeBefore = document.body.createTextRange();
				rangeBefore.moveToElementText(textarea);
				rangeBefore.setEndPoint("EndToStart", selectionRange);
		
				var rengeAfter = document.body.createTextRange();
				rengeAfter.moveToElementText(textarea);
				rengeAfter.setEndPoint("StartToEnd", selectionRange);
				var primadiFinito = false, fineSelezione = false, dopoFinito = false;
				var textBefore, unBeforeText, testoSelezione, unTestoSelezione, testoDopo, unTestoDopo;
				textBefore = unBeforeText = rangeBefore.text;
				testoSelezione = unTestoSelezione = selectionRange.text;
				testoDopo = unTestoDopo = rengeAfter.text;
				do {
				  if (!primadiFinito) {
				      if (rangeBefore.compareEndPoints("StartToEnd", rangeBefore) == 0) {
				          primadiFinito = true;
				      } else {
				          rangeBefore.moveEnd("character", -1)
				          if (rangeBefore.text == textBefore) {
				              unBeforeText += "\r\n";
				          } else {
				              primadiFinito = true;
				          }
				      }
				  }
				  if (!fineSelezione) {
				      if (selectionRange.compareEndPoints("StartToEnd", selectionRange) == 0) {
				          fineSelezione = true;
				      } else {
				          selectionRange.moveEnd("character", -1)
				          if (selectionRange.text == testoSelezione) {
				              unTestoSelezione += "\r\n";
				          } else {
				              fineSelezione = true;
				          }
				      }
				  }
				  if (!dopoFinito) {
				      if (rengeAfter.compareEndPoints("StartToEnd", rengeAfter) == 0) {
				          dopoFinito = true;
				      } else {
				          rengeAfter.moveEnd("character", -1)
				          if (rengeAfter.text == testoDopo) {
				              unTestoDopo += "\r\n";
				          } else {
				              dopoFinito = true;
				          }
				      }
				  }
		
				} while ((!primadiFinito || !fineSelezione || !dopoFinito));
		
				var textTocheck = unBeforeText + unTestoSelezione + unTestoDopo;
				var untrimmed_successful = false;
				if (taValue == textTocheck) {
				  untrimmed_successful = true;
				}
				// conto i ritorni a capo .. in caso contrario la posizione del curzore viene sfalsata di 1 per ogni riga
				nl=unBeforeText.split('\r\n')
				this.selectTextstartPos=(unBeforeText.length-(nl.length-1));
				this.selectTexendPos=this.selectTextstartPos+((unTestoSelezione).length)+(nl.length-1);
				this.crlf=nl.length;

				//$('textTest').innerHTML='';
/*
				$('textTest').innerHTML+='\r\n crlf:'+nl.length
				$('textTest').innerHTML+='\r\n testoselezione:'+(unTestoSelezione).length
				$('textTest').innerHTML+='\r\n startPos:'+this.selectTextstartPos
				$('textTest').innerHTML+='\r\n endPos:'+this.selectTexendPos
*/
			}
		}
	},



	/**
	 * Inserisce un link nella selezione del testo
	 *  @param {String} linkret   link inserito
* 	@param {Object} textArea  oggetto dom textarea 
	 */
	_realInsertLink: function(linkret,textArea){
		tag='url';
		ret2=linkret;
		if(!linkret){
			return false;
		}
		if (linkret.indexOf('http://') == -1) {
			linkret='http://'+linkret;
		}
		linkret=linkret.replace(/ /g,'');
		if(typeof(textArea)!='object'){
			this.textf=$(this.options.textField);
		}else{
			this.textf=textArea;
		}
		taValue=getFieldValue(this.textf).text;
		this.removeDefaultText(this.textf);
		if (!hasClass(textArea, 'editor-field-active')) {
			addClass(textArea,'editor-field-active');
		}
		textBefore= this.ot + tag + '=' + linkret + '' + this.et;
		textAfter=this.ot + '/' + tag + this.et;
		var valueLen=this.textf.value.length;
		  if (document.selection) {// ie 
 			var startPos =this.selectTextstartPos;
			var endPos = this.selectTexendPos;
			if(startPos==endPos){
				nextSelection=(this.textf.value.substring(0, startPos) + textBefore + linkret + textAfter).length
				this.textf.value = taValue.substring(0, startPos) + textBefore + linkret + textAfter +  taValue.substring(endPos, valueLen);
			}else{
				startPos+=(this.crlf-1);
				if(taValue.substring(startPos, endPos)!=''){
					nextSelection=(taValue.substring(0, startPos) + textBefore+ taValue.substring(startPos, endPos) +textAfter).length-(this.crlf-1)
					this.textf.value = taValue.substring(0, startPos) + textBefore+ taValue.substring(startPos, endPos) +textAfter+  taValue.substring(endPos, valueLen);
				}else{
					nextSelection=(taValue.substring(0, startPos) + textBefore+ linkret +textAfter).length-(this.crlf-1)
					this.textf.value = taValue.substring(0, startPos) + textBefore+ linkret +textAfter+  taValue.substring(endPos, valueLen);
				}
			}
			this.textf.focus();
			this.setSelRange(this.textf,nextSelection,nextSelection);

		  } else if (this.textf.selectionStart || this.textf.selectionStart == '0') {
 			var startPos = this.textf.selectionStart;
			var endPos = this.textf.selectionEnd;
			if(startPos==endPos){
				nextSelection=(this.textf.value.substring(0, startPos) + textBefore + linkret + textAfter).length
				this.textf.value = this.textf.value.substring(0, startPos) + textBefore + linkret + textAfter +  this.textf.value.substring(endPos, valueLen);
			}else{
				nextSelection=(this.textf.value.substring(0, startPos) + textBefore+ this.textf.value.substring(startPos, endPos) +textAfter).length
				this.textf.value = this.textf.value.substring(0, startPos) + textBefore+ this.textf.value.substring(startPos, endPos) +textAfter+  this.textf.value.substring(endPos, valueLen);
			}
			this.textf.selectionStart=nextSelection;
			this.textf.selectionEnd=nextSelection;
			this.textf.focus();
		  } else {
		     this.textf.value +=  textBefore + linkret + textAfter;
			 this.textf.focus();
		  }
		  this.saveTextRange(this.textf);
	},
	/**
	 * resize delle text aree
	 *  @param {Object} ta text area 
	 */
	resizeTa: function(ta){
		return resizeTa(ta,this.options.textMaxChar,this.options.textareaMinHeight,this.options.textareaMaxHeight);
	},
	/**
	 * implementare in questa funzione i metodi di fare il display 
	 * degli errori agli utenti
	 *  @param {String} message messaggio da mostrare
	 */
	_showError: function(message){
		removePageVeil();
		if(this.divErrorObj==''){
			this.divErrorObj=$(this.options.errorDiv);
		}
		this.divErrorObj.style.display='block';
		if (typeof message!='undefined') {
			this.divErrorObj.innerHTML=message;
		}
		var _this=this;
		window.setTimeout(function(){
			_this._hideError();
		}, 4000);
	},
	/**
	 * nasconde e "svuota il div di errore"
	 */
	_hideError: function(){
		if(this.divErrorObj==''){
			this.divErrorObj=$(this.options.errorDiv);
		}
		this.divErrorObj.style.display='none';
		this.divErrorObj.innerHTML='';
	},
		/**
	 * override delle opzioni di default
	 * @param {Object} opzioni passate come oggetto
	 */
	_setoptions : function (options){
		if (typeof(options)=='object') {
			var result={};
			for (var i in this.options) {
				if(typeof(options[i])!='undefined'){
					result[i]=options[i];
				}else{
					result[i]=this.options[i];	
				}
			}
		}else{
			result=this.options;
		}
		this.options=result;
	}
}