/*
	Config
*/
var commentOptions = {
	/* submit */
	submitUrl: '/dinamiche/CommentInserter',
	idForm: 'formInvioCommento',
	idDiv: 'divInvioCommento',
	idStartDiv: 'divStartCommento',
	idStatusBar: 'submit_status',
	maxCharCount: 500,	
	multimediaMaxCharCount: 1500,
	/* pagination */
	pageUrl: '/inc/commenti/#{contentTypeId}/#{shortItemId}/commenti_#{contentItemId}_#{pageIndex}.inc',
	anchorUrl: 'anchorCommenti',
	elmTotalLink: 'link_commenti',
	elmTotalLinkSimple: 'link_commenti_simple',
	totalLinkPostfix: ' commenti',
	elmPaginazione: 'comment-pagination',
	elmNavigazione: 'comment-navigation',
	elmList: 'commenti_list_',
	pageGroup: 3, /* usato per la visualizzazione dei "..." nell'elenco delle pagine */
	startAtLast: false,
	firstIsZero: false,
	singleTargetDiv: false,
	firstPageName: 'first',
	isShort: false,
	invert: true,
	twoLines: true
};

/*
	Config articolo options per Concorso MotoGP
*/
var articoloOptions = {
	/* submit */
	submitUrl: '/dinamiche/ArticoliInserter',
	idForm: 'formInvioCommento',
	idDiv: 'divInvioCommento',
	idStartDiv: 'divStartCommento',
	idStatusBar: 'submit_status',
	maxCharCount: 1500,	
	multimediaMaxCharCount: 1500,
	/* pagination */
	pageUrl: '/inc/commenti/#{contentTypeId}/#{shortItemId}/commenti_#{contentItemId}_#{pageIndex}.inc',
	anchorUrl: 'anchorCommenti',
	elmTotalLink: 'link_commenti',
	elmTotalLinkSimple: 'link_commenti_simple',
	totalLinkPostfix: ' commenti',
	elmPaginazione: 'comment-pagination',
	elmNavigazione: 'comment-navigation',
	elmList: 'commenti_list_',
	pageGroup: 3, /* usato per la visualizzazione dei "..." nell'elenco delle pagine */
	startAtLast: false,
	firstIsZero: false,
	singleTargetDiv: false,
	firstPageName: 'first',
	isShort: false,
	invert: true,
	twoLines: true
};

var captchaOptions = {
	captchaUrl: '/dinamiche/GetCaptcha'
}

/*
	Class Paginator
*/
var Paginator = Class.create();
Paginator.prototype = {
	initialize: function (options) {
		this.options = options;
		this.linkedPaginators = $A([]);
	},
	
	prepare: function (iAllItemCount, iItemsPerPage, iFirstPageMaxItems, contentTypeId, contentItemId) {
		this.contentTypeId = contentTypeId;
		this.contentItemId = contentItemId;
		this.urlTemplate = new Template(this.options.pageUrl);
		
		this.innerPrepare(iAllItemCount, iItemsPerPage, iFirstPageMaxItems);		
	},
	
	prepareWithFunction: function (iAllItemCount, iItemsPerPage, iFirstPageMaxItems, urlGetter, postBodyGetter) {		
		this.urlTemplate = null;
		this.urlGetter = urlGetter;
		if (postBodyGetter) {
			this.postBodyGetter = postBodyGetter;
		} else {
			this.postBodyGetter = null;
		}
		
		this.innerPrepare(iAllItemCount, iItemsPerPage, iFirstPageMaxItems);		
	},
	
	innerPrepare: function (iAllItemCount, iItemsPerPage, iFirstPageMaxItems) {
			
		this.iAllItemCount = iAllItemCount;
		this.iItemsPerPage = iItemsPerPage;
		this.iFirstPageMaxItems = iFirstPageMaxItems;
		
		this.totalPages = 1;
		if (iAllItemCount > iFirstPageMaxItems) {
       		this.totalPages = 1 + 
       			Math.floor((iAllItemCount - iFirstPageMaxItems + iItemsPerPage - 1) / iItemsPerPage);
       		this.iFirstPageItemCount = iAllItemCount - (this.totalPages - 1) * iItemsPerPage;
        }
        if (this.options.startAtLast) {
        	this.currentPage = this.totalPages;
        } else {
        	this.currentPage = 1;
        }
        
        if (this.options.elmTotalLink && $(this.options.elmTotalLink)) {
        	$(this.options.elmTotalLink).innerHTML = iAllItemCount + this.options.totalLinkPostfix;
        }
        if (this.options.elmTotalLinkSimple && $(this.options.elmTotalLinkSimple)) {
        	$(this.options.elmTotalLinkSimple).innerHTML = iAllItemCount;
        }
        
        this.handlers = new Array();
        this.updatePagination();
	},
	
	updatePagination: function () {
		// unregistering previous event handlers
		$A(this.handlers).each(function (hndl) {
			Event.stopObserving(hndl.target, 'click', hndl.fnct);
		});
		this.handlers.clear();
	
		var pagElm = $(this.options.elmPaginazione); 
		if (pagElm) {
			pagElm.innerHTML = '';
		}
		
		var navElm = pagElm;
		if (this.options.twoLines) {
			if (pagElm) {
				pagElm.up().addClassName('commentPagination');
			}
			navElm = $(this.options.elmNavigazione);
			if (navElm) {
				navElm.innerHTML = '';
			} else {
				new Insertion.After(pagElm, '<ul id="' + this.options.elmNavigazione + '"></ul>');
				navElm = $(this.options.elmNavigazione);
			}
		}
		
		if (this.currentPage == 1) {
			//new Insertion.Bottom(pagElm, '<li class="previous">&laquo; Precedente</li> |');
		} else {
			new Insertion.Bottom(navElm, '<li class="txt_Previous"><a href="javascript:;" title="Precedente">&laquo; Precedente</a></li>');
			var target = navElm.getElementsByClassName('txt_Previous')[0].firstDescendant();
			var fnct = this.switchTo.bind(this, this.currentPage - 1);
			Event.observe(target, 'click', fnct);
			this.handlers.push({ target: target, fnct: fnct });
		}
		
		if (!this.options.isShort) {
			var dots = false;
			for (var i = 1; i <= this.totalPages; i++) {
				if ((i > this.options.pageGroup) && 
						(this.totalPages - i >= this.options.pageGroup) &&
						(Math.abs(i - this.currentPage) > this.options.pageGroup)) {
					if (!dots) {
						new Insertion.Bottom(pagElm, '<li>...</li>');
						dots = true;
					}
					continue;
				}
				dots = false;
				
				var lastPage = i == this.totalPages;
			
				if (i == this.currentPage) {
					new Insertion.Bottom(pagElm, '<li class="' + (lastPage ? 'last' : '') + 
						'"><strong>' + i + '</strong></li>');
				} else {
					new Insertion.Bottom(pagElm, '<li class="' + (lastPage ? 'last' : '') + 
						'"><a href="javascript:;" title="" class="pag_btn_' + 
						i + '">' + i + '</a></li>');
						
					var target = pagElm.getElementsByClassName('pag_btn_' + i)[0];
					var fnct = this.switchTo.bind(this, i);
					Event.observe(target, 'click', fnct);
					this.handlers.push({ target: target, fnct: fnct });
				}
			}
			
			var firstItemIndex = (this.currentPage - 1) * this.iItemsPerPage + 1; 
			var lastItemIndex = this.currentPage == this.totalPages ? 
				this.iAllItemCount : (this.currentPage * this.iItemsPerPage);
				
			if (this.options.invert) {
				firstItemIndex = this.currentPage == 1 ? 1 :
					(this.iAllItemCount + 1 - (this.iItemsPerPage * (this.totalPages + 1 - this.currentPage))); 
				lastItemIndex = this.iAllItemCount - (this.iItemsPerPage * (this.totalPages - this.currentPage));
			}
				
			if (this.iAllItemCount == 0) {
				firstItemIndex = 0; 
				lastItemIndex = 0;
			}
				
			new Insertion.Bottom(navElm, '<li class="txt_ItemNumber">[ da ' + firstItemIndex + 
				' a ' + lastItemIndex + ' di ' + this.iAllItemCount + ' ]</li>');
		}
		
		if (this.currentPage == this.totalPages) {
			//new Insertion.Bottom(navElm, '<li class="next">Successiva &raquo;</li>');
		} else {
			new Insertion.Bottom(navElm, '<li class="txt_Next"><a href="javascript:;" title="Successiva">Successiva &raquo;</a></li>');
			var target = navElm.getElementsByClassName('txt_Next')[0].firstDescendant();
			var fnct = this.switchTo.bind(this, this.currentPage + 1);
			Event.observe(target, 'click', fnct);
			this.handlers.push({ target: target, fnct: fnct });
		}
	},
	
	switchTo: function (page) {
		if (page == this.currentPage) {
			return;
		}
		
		var pageIndex = this.options.invert ? (this.totalPages + 1 - page) : page;
		var currentPageIndex = this.options.invert ? (this.totalPages + 1 - this.currentPage) : this.currentPage;
		
		if (this.options.firstIsZero) {
			pageIndex--;
			currentPageIndex--;
			if (this.options.firstPageName) {
				if (pageIndex == this.totalPages - 1) {
					pageIndex = this.options.firstPageName;
				}
				if (currentPageIndex == this.totalPages - 1) {
					currentPageIndex = this.options.firstPageName;
				}
			}
		} else {
			if (this.options.firstPageName) {
				if (pageIndex == this.totalPages) {
					pageIndex = this.options.firstPageName;
				}
				if (currentPageIndex == this.totalPages) {
					currentPageIndex = this.options.firstPageName;
				}
			}
		}
		
		if (!this.options.singleTargetDiv && $(this.options.elmList + pageIndex) != undefined) {
			// page already downloaded
			$(this.options.elmList + currentPageIndex).hide();
			$(this.options.elmList + pageIndex).show();
			this.currentPage = page;
			this.updatePagination();
			this.updateLinkedPaginators();
		} else {
			// page to be downloaded
			var url;
			var postBody = "";
			if (this.urlTemplate != null) {
				url = this.urlTemplate.evaluate({ 
					pageIndex: pageIndex, 
					contentTypeId: this.contentTypeId,
					contentItemId: this.contentItemId,
					shortItemId: (this.contentItemId % 1000) 
				});
			} else {
				url = this.urlGetter(pageIndex);
				if (this.postBodyGetter != null) {
					postBody = this.postBodyGetter(pageIndex);
				}				
			}
			
			new Ajax.Request(url, {
				method: (postBody != '' ? 'POST' : 'GET'),
				postBody: postBody,
				onSuccess: function (transport) {
					if (this.options.singleTargetDiv) {
						$(this.options.elmList).update(transport.responseText);
					} else {
						$(this.options.elmList + currentPageIndex).hide();
						if (this.options.insertAfter) {
							new Insertion.After($(this.options.elmPaginazione).up(), transport.responseText);
						} else {
							new Insertion.Before($(this.options.elmPaginazione).up(), transport.responseText);
						}
					}
					
					this.currentPage = page;
					this.updatePagination();
					this.updateLinkedPaginators();
				}.bind(this)
			});
		}
		
		if (this.options.anchorUrl) {
			document.location.href = '#' + this.options.anchorUrl;
		}		
	},
	
	updateLinkedPaginators: function () {
		this.linkedPaginators.each(function (paginator) {
			if (paginator.currentPage != this.currentPage) {
				paginator.currentPage = this.currentPage;
				paginator.updatePagination();
			}
		}.bind(this));
	}
};

var commentPaginator = new Paginator(commentOptions);


/*
	Class CommentSubmitter
*/
var CommentSubmitter = Class.create();
CommentSubmitter.prototype = {
	initialize: function (multimedia, mcn) {
		this.options = commentOptions;
		this.multimedia = multimedia;
		this.mcn = mcn;
		this.maxCharCount = multimedia ? this.options.multimediaMaxCharCount : this.options.maxCharCount;

		var logged = Get_Login_Cookie('TSauthcookie');
		if (logged != null) {
			$(this.options.idStartDiv).hide();
			$(this.mcn ? this.options.idForm : this.options.idDiv).show();
			this.start();
		}
		
		var params = document.location.href.toQueryParams();
		if (params.cdo) {
			if (params.cdo == 'ok') {
				this.showStatus(false, 'Grazie!<br/>Il tuo commento \u00E8 stato inviato correttamente<br/>e sar\u00E0 pubblicato a breve');
			} else if (params.cdo == 'login') {
				this.showStatus(true, 'Per inviare messaggi occorre effettuare la login');
			} else if (params.cdo == 'missing') {
				this.showStatus(true, 'Campo "' + status.what + '" non valorizzato');
			} else if (params.cdo == 'spam') {
				this.showStatus(false, 'Grazie!<br/>Il tuo commento \u00E8 stato inviato correttamente<br/>e sar\u00E0 pubblicato a breve');
				//this.showStatus(true, 'Il tuo messaggio \u00E8 stato considerato spam e non sar\u00E0 pubblicato');
			} else if (params.cdo == 'blacklist') {
				this.showStatus(false, 'Grazie!<br/>Il tuo commento \u00E8 stato inviato correttamente<br/>e sar\u00E0 pubblicato a breve');
				//this.showStatus(true, 'Il tuo messaggio \u00E8 continene parole non accettate e non sar\u00E0 pubblicato');
			} else if (params.cdo == 'filesize') {
				this.showStatus(true, 'Il tuo messaggio contiene un file troppo grande e non sar\u00E0 pubblicato');
			} else if (params.cdo == 'filetype') {
				this.showStatus(true, 'Il tuo messaggio contiene un file di un formato non consentito e non sar\u00E0 pubblicato');
			} else if (params.cdo == 'error') {
				this.showStatus(true, 'Errore nel salvataggio del commento. Riprova pi\u00F9 tardi.');
			}
		}
	},
	
	start: function () {
		this.overMax = false;

		var myForm = $(this.options.idForm);
		myForm.enable();
		
		var trgUrl = document.location.href;
		var paramsIndex = trgUrl.indexOf("?");
		if (paramsIndex >= 0) {
			trgUrl = trgUrl.substring(0, paramsIndex);
		}
		myForm['trg'].value = trgUrl;
		
		Event.observe(myForm['invia'], 'click', this.salvaCommento.bind(this));
		
		Event.observe(myForm['commento'], 'keyup', this.onCommentChange.bind(this));
		Event.observe(myForm['commento'], 'change', this.onCommentChange.bind(this));
		Event.observe(myForm['commento'], 'mouseover', this.onCommentChange.bind(this));
		if (myForm.getElementsByClassName('char_count').length > 0) {
			this.charCountElm = myForm.getElementsByClassName('char_count')[0];
			this.onCommentChange(); 
		}				
	},

	salvaCommento: function () {
		this.hideStatus();
	
		var myForm = $(this.options.idForm);
		myForm.disable();
		
		if ($F(myForm['commento']) == '') {
			this.showError('commento', 'Campo "commento" non valorizzato');
			myForm.enable();
			myForm['commento'].focus();
			return;
		}
		
		this.onCommentChange();
		if (this.overMax) {
			myForm.enable();
			myForm['commento'].focus();
			return;
		} else {
			this.hideError('commento');
		}
		
		if (this.multimedia) {
			if ($F(myForm['titolo']) == '') {
				this.showError('titolo', 'Campo "titolo" non valorizzato');
				myForm.enable();
				myForm['titolo'].focus();
				return;
			} else {
				this.hideError('titolo');
			} 
		}
	
		this.showStatus(false, 'Invio del commento in corso...');
	
		myForm.action = this.options.submitUrl;
		myForm.enable();
		myForm.submit();
		myForm['invia'].disable();
	},
	
	onCommentChange: function () {
		var myForm = $(this.options.idForm);
		var text = $F(myForm['commento']);		
		var textLength = dbStringLength(text);
		
		if (textLength > this.maxCharCount) {
			if (this.charCountElm) {
				this.charCountElm.innerHTML = '0';
			}			
			this.showError('commento', "Attenzione, hai inserito " + (textLength - this.maxCharCount) + " caratteri oltre il massimo");
			this.overMax = true;
		} else {							
			if (this.charCountElm) {
				this.charCountElm.innerHTML = this.maxCharCount - textLength;
			}
			if (this.overMax) {
				this.hideError('commento');
			}
			this.overMax = false;
		}						
	},
	
	showStatus: function (error, message) {
		$(this.options.idStatusBar).className = error ? 'txt_Error' : 'txt_Info';
		$(this.options.idStatusBar).innerHTML = message;
		$(this.options.idStatusBar).show();
		$(this.options.idStatusBar).scrollTo();
	},
	
	hideStatus: function () {
		$(this.options.idStatusBar).hide();
	},

	showError: function (where, message) {
		$('error_' + where).innerHTML = message;
		$('error_' + where).show();
		$('error_' + where).up().addClassName('input_Error');
		$('error_' + where).up().scrollTo();
	},
	
	hideError: function (where) {
		$('error_' + where).hide();
		$('error_' + where).up().removeClassName('input_Error');
	}
}


/*
	Class ArticoloSubmitter
*/
var ArticoloSubmitter = Class.create();
ArticoloSubmitter.prototype = {
	initialize: function (multimedia, mcn) {
		this.options = articoloOptions;
		this.multimedia = multimedia;
		this.mcn = mcn;
		this.maxCharCount = multimedia ? this.options.multimediaMaxCharCount : this.options.maxCharCount;

		var logged = Get_Login_Cookie('TSauthcookie');
		if (logged != null) {
			$(this.options.idStartDiv).hide();
			$(this.mcn ? this.options.idForm : this.options.idDiv).show();
			this.start();
		}
		
		var params = document.location.href.toQueryParams();
		if (params.cdo) {
			if (params.cdo == 'ok') {
				this.showStatus(false, 'Grazie!<br/>Il tuo articolo \u00E8 stato inviato correttamente');
			} else if (params.cdo == 'login') {
				this.showStatus(true, 'Per inviare un articolo occorre effettuare la login');
			} else if (params.cdo == 'missing') {
				this.showStatus(true, 'Campo "' + status.what + '" non valorizzato');
			} else if (params.cdo == 'spam') {
				this.showStatus(false, 'Grazie!<br/>Il tuo articolo \u00E8 stato inviato correttamente');
				//this.showStatus(true, 'Il tuo messaggio \u00E8 stato considerato spam e non sar\u00E0 pubblicato');
			} else if (params.cdo == 'blacklist') {
				this.showStatus(false, 'Grazie!<br/>Il tuo articolo \u00E8 stato inviato correttamente.');
				//this.showStatus(true, 'Il tuo messaggio \u00E8 continene parole non accettate e non sar\u00E0 pubblicato');
			} else if (params.cdo == 'filesize') {
				this.showStatus(true, 'Il tuo messaggio contiene un file troppo grande e non sar\u00E0 pubblicato');
			} else if (params.cdo == 'filetype') {
				this.showStatus(true, 'Il tuo messaggio contiene un file di un formato non consentito e non sar\u00E0 pubblicato');
			} else if (params.cdo == 'error') {
				this.showStatus(true, 'Errore nel salvataggio dell\'articolo. Riprova pi\u00F9 tardi.');
			}
		}
	},
	
	start: function () {
		this.overMax = false;

		var myForm = $(this.options.idForm);
		myForm.enable();
		
		var trgUrl = document.location.href;
		var paramsIndex = trgUrl.indexOf("?");
		if (paramsIndex >= 0) {
			trgUrl = trgUrl.substring(0, paramsIndex);
		}
		myForm['trg'].value = trgUrl;
		
		Event.observe(myForm['invia'], 'click', this.salvaCommento.bind(this));
		
		Event.observe(myForm['commento'], 'keyup', this.onCommentChange.bind(this));
		Event.observe(myForm['commento'], 'change', this.onCommentChange.bind(this));
		Event.observe(myForm['commento'], 'mouseover', this.onCommentChange.bind(this));
		if (myForm.getElementsByClassName('char_count').length > 0) {
			this.charCountElm = myForm.getElementsByClassName('char_count')[0];
			this.onCommentChange(); 
		}				
	},

	salvaCommento: function () {
		this.hideStatus();
	
		var myForm = $(this.options.idForm);
		myForm.disable();
		
		if ($F(myForm['commento']) == '') {
			this.showError('commento', 'Campo "commento" non valorizzato');
			myForm.enable();
			myForm['commento'].focus();
			return;
		}
		
		if ($F(myForm['nome_utente']) == '') {
			this.showError('nome_utente', 'Campo "nome utente" non valorizzato');
			myForm.enable();
			myForm['nome_utente'].focus();
			return;
		}
		
		if ($F(myForm['cognome_utente']) == '') {
			this.showError('cognome_utente', 'Campo "cognome utente" non valorizzato');
			myForm.enable();
			myForm['cognome_utente'].focus();
			return;
		}
		
		if ($F(myForm['email_utente']) == '') {
			this.showError('email_utente', 'Campo "email utente" non valorizzato');
			myForm.enable();
			myForm['email_utente'].focus();
			return;
		}
		
		if ($F(myForm['indirizzo_utente']) == '') {
			this.showError('indirizzo_utente', 'Campo "indirizzo" non valorizzato');
			myForm.enable();
			myForm['indirizzo_utente'].focus();
			return;
		}
		
		if ($F(myForm['citta_utente']) == '') {
			this.showError('citta_utente', 'Campo "citt&nbsp;" non valorizzato');
			myForm.enable();
			myForm['citta_utente'].focus();
			return;
		}
		
		if ($F(myForm['provincia_utente']) == '') {
			this.showError('provincia_utente', 'Campo "provincia" non valorizzato');
			myForm.enable();
			myForm['provincia_utente'].focus();
			return;
		}
		
		if ($F(myForm['telefono_utente']) == '') {
			this.showError('telefono_utente', 'Campo "telefono" non valorizzato');
			myForm.enable();
			myForm['telefono_utente'].focus();
			return;
		}		
		
		if ($F(myForm['accetto_utente']) != "on") {
			this.showError('accetto_utente', 'Attenzione: se non hai preso visione del regolamento e dell\'informativa sulla privacy non puoi partecipare al concorso');
			myForm.enable();
			myForm['accetto_utente'].focus();
			return;
		}
		
		
		this.onCommentChange();
		if (this.overMax) {
			myForm.enable();
			myForm['commento'].focus();
			return;
		} else {
			this.hideError('commento');
		}
		
		if (this.multimedia) {
			if ($F(myForm['titolo']) == '') {
				this.showError('titolo', 'Campo "titolo" non valorizzato');
				myForm.enable();
				myForm['titolo'].focus();
				return;
			} else {
				this.hideError('titolo');
			} 
		}
	
		this.showStatus(false, 'Invio del commento in corso...');
	
		myForm.action = this.options.submitUrl;
		myForm.enable();
		myForm.submit();
		myForm['invia'].disable();
	},
	
	onCommentChange: function () {
		var myForm = $(this.options.idForm);
		var text = $F(myForm['commento']);		
		var textLength = dbStringLength(text);
		
		if (textLength > this.maxCharCount) {
			if (this.charCountElm) {
				this.charCountElm.innerHTML = '0';
			}			
			this.showError('commento', "Attenzione, hai inserito " + (textLength - this.maxCharCount) + " caratteri oltre il massimo");
			this.overMax = true;
		} else {							
			if (this.charCountElm) {
				this.charCountElm.innerHTML = this.maxCharCount - textLength;
			}
			if (this.overMax) {
				this.hideError('commento');
			}
			this.overMax = false;
		}						
	},
	
	showStatus: function (error, message) {
		$(this.options.idStatusBar).className = error ? 'txt_Error' : 'txt_Info';
		$(this.options.idStatusBar).innerHTML = message;
		$(this.options.idStatusBar).show();
		$(this.options.idStatusBar).scrollTo();
	},
	
	hideStatus: function () {
		$(this.options.idStatusBar).hide();
	},

	showError: function (where, message) {
		$('error_' + where).innerHTML = message;
		$('error_' + where).show();
		$('error_' + where).up().addClassName('input_Error');
		$('error_' + where).up().scrollTo();
	},
	
	hideError: function (where) {
		$('error_' + where).hide();
		$('error_' + where).up().removeClassName('input_Error');
	}
}


function PopolaCampiConcorso(){
	new Ajax.Request("/dinamiche/getData.jsp", {
		onSuccess: function call_back(transport){
						PopolaCampiConcorso_onSuccess(transport)
					}	
	});
}


function PopolaCampiConcorso_onSuccess(transport) {
	eval(transport.responseText);
	$A(datiUtente).each(function (elm) {
		if(elm.nome != null && elm.nome != '' )
			$('formInvioCommento')['nome_utente'].value = elm.nome
		if(elm.cognome != null && elm.cognome != '' )
			$('formInvioCommento')['cognome_utente'].value = elm.cognome						
		if(elm.email != null && elm.email != '' )
			$('formInvioCommento')['email_utente'].value = elm.email
		if(elm.indirizzo != null && elm.indirizzo != '' )
			$('formInvioCommento')['indirizzo_utente'].value = elm.indirizzo
		if(elm.citta != null && elm.citta != '' )
			$('formInvioCommento')['citta_utente'].value = elm.citta
		if(elm.provincia != null && elm.provincia != '' )
			$('formInvioCommento')['provincia_utente'].value = elm.provincia
		});
}



// String length for db saving
// char count: & -> 5; <, > -> 4; \n -> 5
function dbStringLength(string) {
	var stringLength = string.length;
	string.replace(/[\n&]/g, function () { stringLength += 4 });
	string.replace(/[<>]/g, function () { stringLength += 3 });
	return stringLength;
};

/**
* initFileUploads
*/
function initFileUploads() {
	var W3CDOM = (document.createElement && document.getElementsByTagName);
	if (!W3CDOM) return;
		var fakeFileUpload = document.createElement('div');
		fakeFileUpload.className = 'fakefile';
		var fakeInput = document.createElement('input');
		fakeInput.className = 'inp_Text';
		fakeFileUpload.appendChild(fakeInput);
		var image = document.createElement('img');
		image.src='/res/imgs/imgs_mcn/btn_Browse.png';
		fakeFileUpload.appendChild(image);
		var x = document.getElementsByTagName('input');
		for (var i=0;i<x.length;i++) {
		if (x[i].type != 'file') continue;
		if (x[i].parentNode.className != 'fileinputs') continue;
		x[i].className = 'file hidden';
		var clone = fakeFileUpload.cloneNode(true);
		x[i].parentNode.appendChild(clone);
		x[i].relatedElement = clone.getElementsByTagName('input')[0];
		x[i].onchange = x[i].onmouseout = function () {
		this.relatedElement.value = this.value;
		}
	}
} 
