var Paginator = Class.extend({
	// configuration
	pageUrl: '/notizie/commenti/#{shortItemId}/commenti_#{contentItemId}_#{pageIndex}.html',
	anchorUrl: 'anchorCommenti',
	elmTotalLinkSel: null,
	elmPaginazione: '#comment-pagination',
	elmList: '#commenti_list_',
	pageGroup: 3, /* usato per la visualizzazione dei "..." nell'elenco delle pagine */
	startAtLast: false,
	firstPageName: 'first',
	invert: true,

	// fields
	contentTypeId: null,
	contentItemId: null,
	totalCount: 0,
	itemsPerPage: 10,
	itemsFirstPage: 15,
	
	// internal fields
	urlTemplate: null,
	totalPages: 1,
	firstPageCount: 0,
	currentPage: 1,
	handlers: $A(),

	// methods
	init: function (options) {
		$.extend(this, options);

		if (this.totalCount > this.itemsFirstPage) {
       		this.totalPages = 1 + 
       			Math.floor((this.totalCount - this.itemsFirstPage + this.itemsPerPage - 1) / this.itemsPerPage);
       		this.firstPageCount = this.totalCount - (this.totalPages - 1) * this.itemsPerPage;
        }
        if (this.startAtLast) {
        	this.currentPage = this.totalPages;
        }
		
		this.urlTemplate = new Template(this.pageUrl);
        
        if (this.elmTotalLinkSel && $(this.elmTotalLinkSel).length > 0) {
			if (totalCount == 1) {
				$(this.elmTotalLinkSel).html(totalCount + ' commento');
			} else if (totalCount > 1) {
				$(this.elmTotalLinkSel).html(totalCount + ' commenti');
			}
        }
        
        this.updatePagination();
	},
	
	updatePagination: function () {
		// unregistering previous event handlers
		for (var i = 0; i < this.handlers.length; i++) {
			$(this.handlers[i].target).unbind('click', this.handlers[i].fnct);
		}		
		this.handlers.length = 0;
	
		$(this.elmPaginazione).html(''); 
		
		this.updateNumberComment();
		
		//$(this.elmPaginazione).append('<li class="li_Previous"><a href="javascript:;" title="Precedente">&laquo; Precedente</a></li>');
		var target = $(this.elmPaginazione + ' li.li_Previous a');
		var fnct = this.switchTo.bind(this, this.currentPage > 1 ? (this.currentPage - 1) : 1);
		$(target).bind('click', fnct);
		this.handlers.push({ target: target, fnct: fnct });
		
		var dots = false;
		for (var i = 1; i <= this.totalPages; i++) {
			if ((i > 1) && (this.totalPages - i > 0) && (Math.abs(i - this.currentPage) > this.pageGroup)) {
				if (!dots) {
					$(this.elmPaginazione).append('<li><span>...</span></li>');
					dots = true;
				}
				continue;
			}
			dots = false;
			
			var lastPage = (i == this.totalPages);
		
			if (i == this.currentPage) {
				$(this.elmPaginazione).append('<li class="selected' + (lastPage ? ' last' : '') + '"><strong>' + i + '</strong></li>');
			} else {
				$(this.elmPaginazione).append('<li class="' + (lastPage ? 'last' : '') + '"><a href="javascript:;" title="" class="pag_btn_' + i + '">' + i + '</a></li>');
					
				var target = $(this.elmPaginazione + ' li a.pag_btn_' + i);
				var fnct = this.switchTo.bind(this, i);
				$(target).bind('click', fnct);
				this.handlers.push({ target: target, fnct: fnct });
			}
		}

		//$(this.elmPaginazione).append('<li class="li_Next"><a href="javascript:;" title="Successiva">Successiva &raquo;</a></li>');
		var target = $(this.elmPaginazione + ' li.li_Next a');
		var fnct = this.switchTo.bind(this, this.currentPage < this.totalPages ? (this.currentPage + 1) : this.totalPages);
		$(target).bind('click', fnct);
		this.handlers.push({ target: target, fnct: fnct });
	},
	
	updateNumberComment: function () {
		var pageIndexComment = this.currentPage == 1 ? "first" : (this.totalPages + 1 - this.currentPage);
		var totCommenti = this.totalCount;
		firstPageCount = this.currentPage == 1 ? 0 : this.firstPageCount;
		totCommentiPage = this.currentPage == 1 ? 0 : (this.itemsPerPage * (this.currentPage - 2))
		
	    $(this.elmList + (pageIndexComment)).find("li").each(function(i) {
			$(this).find("span").html((totCommenti - i - firstPageCount - totCommentiPage));
		});
	},
	
	switchTo: function (page) {
		if (page == this.currentPage) {
			return;
		}
		
		var pageIndex = this.invert ? (this.totalPages + 1 - page) : page;
		var currentPageIndex = this.invert ? (this.totalPages + 1 - this.currentPage) : this.currentPage;
		
		if (this.firstPageName) {
			if (pageIndex == this.totalPages) {
				pageIndex = this.firstPageName;
			}
			if (currentPageIndex == this.totalPages) {
				currentPageIndex = this.firstPageName;
			}
		}
		
		if ($(this.elmList + pageIndex).length > 0) {
			// page already downloaded
			$(this.elmList + currentPageIndex).hide();
			$(this.elmList + pageIndex).show();
			this.currentPage = page;
			this.updatePagination();
		} else {
			// page to be downloaded
			var url = this.urlTemplate.evaluate({ 
				pageIndex: pageIndex, 
				contentTypeId: this.contentTypeId,
				contentItemId: this.contentItemId,
				shortItemId: (this.contentItemId % 100) 
			});
			
			$.ajax({
				url: url,
				success: function (data) {
					$(this.elmList + currentPageIndex).hide().after(data);
					this.currentPage = page;
					this.updatePagination();
				}.bind(this)
			}); 
		}
		
		if (this.anchorUrl) {
			document.location.href = '#' + this.anchorUrl;
		}
	}
});

var CommentSubmitter = Class.extend({
	// configuration
	submitUrl: '/dinamiche/CommentInserter',
	selDiv: '#formInvioCommento .box_Form',
	selStartDiv: '.divStartCommento',
	selForm: '#formInvioCommento',
	selStatusBar: '#submit_status',
	selCharCount: '.char_count',
	maxCharCountSimple: 500,
	maxCharCountMultimedia: 1500,

	// fields
	multimedia: false,
	
	// internal fields
	maxCharCount: null,

	// methods
	init: function (options) {
		$.extend(this, options);

		this.maxCharCount = this.multimedia ? this.maxCharCountMultimedia : this.maxCharCountSimple;

		var logged = Get_Login_Cookie('CDSauthcookie');
		if (logged != null) {
			$(this.selStartDiv).hide();
			$(this.selDiv).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 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(true, 'Il tuo messaggio \u00E8 stato considerato spam e non sar\u00E0 pubblicato');
			} else if (params.cdo == 'blacklist') {
				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.');
			}
		}
	},
	
	disableForm: function () {
		$(this.selForm).find("input, textarea").each(function () { this.disabled = 'disabled'; });
	},
	
	enableForm: function () {
		$(this.selForm).find("input, textarea").each(function () { this.disabled = ''; });
	},
	
	start: function () {
		this.overMax = false;

		this.enableForm();
		
		var trgUrl = document.location.href;
		var paramsIndex = trgUrl.indexOf("?");
		if (paramsIndex >= 0) {
			trgUrl = trgUrl.substring(0, paramsIndex);
		}
		$(this.selForm).find("input[name='trg']").val(trgUrl);
		
		$(this.selForm).find("input[name='invia']").click(this.salvaCommento.bind(this));
		
		$(this.selForm).find("textarea[name='commento']").keyup(this.onCommentChange.bind(this)).change(this.onCommentChange.bind(this)).mouseover(this.onCommentChange.bind(this));
		this.onCommentChange(); 
	},

	salvaCommento: function () {
		this.hideStatus();

		this.disableForm();
		
		if ($(this.selForm).find("textarea[name='commento']").val() == '') {
			this.showError('commento', 'Campo "commento" non valorizzato');
			this.enableForm();
			$(this.selForm).find("textarea[name='commento']").focus();
			return;
		}
		
		this.onCommentChange();
		if (this.overMax) {
			this.enableForm();
			$(this.selForm).find("textarea[name='commento']").focus();
			return;
		} else {
			this.hideError('commento');
		}
	
		if (this.multimedia) {
			if ($(this.selForm).find("input[name='titolo']").val() == '') {
				this.showError('titolo', 'Campo "titolo" non valorizzato');
				this.enableForm();
				$(this.selForm).find("input[name='titolo']").focus();
				return;
			} else {
				this.hideError('titolo');
			} 
		}
	
		this.showStatus(false, 'Invio del commento in corso...');
	
		$(this.selForm).attr('action', this.submitUrl);
		this.enableForm();
		$(this.selForm).submit();
		$(this.selForm).find("input[name='invia']").disabled = 'disabled';
	},
	
	onCommentChange: function () {
		var text = $(this.selForm).find("textarea[name='commento']").val();		
		var textLength = dbStringLength(text);
		
		if (textLength > this.maxCharCount) {
			$(this.selForm).find(this.selCharCount).html('0');
			this.showError('commento', "Attenzione, hai inserito " + (textLength - this.maxCharCount) + " caratteri oltre il massimo");
			this.overMax = true;
		} else {							
			$(this.selForm).find(this.selCharCount).html(this.maxCharCount - textLength);
			if (this.overMax) {
				this.hideError('commento');
			}
			this.overMax = false;
		}						
	},
	
	showStatus: function (error, message) {
		if (error) {
			$(this.selStatusBar).addClass("txt_Error").removeClass("txt_Info");
		} else {
			$(this.selStatusBar).addClass("txt_Info").removeClass("txt_Error");
		}
		$(this.selStatusBar).html(message);
		$(this.selStatusBar).show();
		scrollToElement(this.selStatusBar);
	},
	
	hideStatus: function () {
		$(this.selStatusBar).hide();
	},

	showError: function (where, message) {
		$('#error_' + where).html(message);
		$('#error_' + where).parent(".box_FormElement").addClass("box_Form_Error");
		scrollToElement($('#error_' + where).parent(".box_FormElement"));
	},
	
	hideError: function (where) {
		$('#error_' + where).parent(".box_FormElement").removeClass("box_Form_Error");
	}
});


// 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;
		}
	}
} 

