//----------Varie funzioni js di electroportal

// Namespace di base
var epjs = {

//--- Espande
espandiContraiCorrelati: function(event){
	Event.stop(event);
	var box = $(Event.element(event)).up('.argomentiCorrelati');
	var img = box.down('.piu img');
	var overflow = box.getElementsByClassName('overflow');
	var puntini = box.down('.puntini');
	if (box.hasClassName('ridotto')){
		box.removeClassName('ridotto');
		puntini.addClassName('nascosto');
		img.src = "/stili/imageset/meno.gif";
		img.alt = "Riduci";
		for (var i=0; i<overflow.length; i++){
			overflow[i].removeClassName('nascosto');
		}
	}
	else {
		box.addClassName('ridotto');
		img.src = "/stili/imageset/piu.gif";
		img.alt = "Espandi e vedi tutti gli argomenti correlati";
		puntini.removeClassName('nascosto');
		for (var i=0; i<overflow.length; i++){
			overflow[i].addClassName('nascosto');
		}
	}
},

espandiContraiDettagliArtCorso: function(event){
	Event.stop(event);
	var link = $(Event.findElement(event, 'a'));
	var gabba = $(Event.findElement(event, 'p')).next('ul');
	if (gabba.hasClassName('ridotto')){
		gabba.removeClassName('ridotto');
		link.removeClassName('piu');
		link.addClassName('meno');
		link.update('Nascondi dettagli');
	}
	else {
		gabba.addClassName('ridotto');
		link.removeClassName('meno');
		link.addClassName('piu');
		link.update('Espandi dettagli');
	}
	
},

popupNota: function(event){
	Event.stop(event);
  
	var link = $(Event.findElement(event, 'a'));
		
	document.win_nota = new nzWindow(document.body, $('invia_nota'), 
		{offset: "center", position: "fixed", className: "testoWindow"});
	document.win_nota.show();
},

vota: function(event){
	event.stop();
	var link = event.findElement( 'a');
	var form = $('frm_vota');
	nzw = form.up('.nzWindow').nzWindow;
	if (link.id == "cmd_voto_pos"){
		$('radioVotoPos').checked="checked";
	} else {
		$('radioVotoNeg').checked="checked";
	}
	new Ajax.Request('/ajax/vota.php',
	{
		method: 'post',
		parameters: Form.serialize('frm_vota'),
		onComplete: function(transport){
				/*if (this.responseIsSuccess()){
						
						
				} */
				var messaggio;
				resp = transport.responseJSON;
				
				if ("OK" == resp.esito) {
					messaggio = 'Votazione effettuata con successo.';
				}
				else messaggio = "Votazione già effettuata per questo documento.";
				nzw.setContent(messaggio);
				$$('#voti1 .n_voti')[0].update(resp.num_voti);
				
			}	
	});
},

popupVota: function(event){
	Event.stop(event);
  	
	var link = $(Event.findElement(event, 'a'));
		
	document.win_vota = new nzWindow('asasas', $('frm_vota'), 
		{offset: "center", className: "testoWindow"});
	document.win_vota.show();
},

inviaNota: function(event){
	Event.stop(event);
	var form = $('invia_nota');
	//nzw = form.up('.nzWindow').nzWindow;
	new Ajax.Request('/ajax/invia_nota.php',
	{
		method: 'post',
		parameters: form.serialize(),
		onComplete: function(requester){
				/*if (this.responseIsSuccess()){
						
						
				} */
				var messaggio;
				if ("OK" == requester.responseText) {
					messaggio = 'Commento inserito con successo. Esso verrà pubblicato dopo che lo staff avrà verificato la sua pertinenza.';
				} else if("OK_PUBLISHED"){
					messaggio = 'Commento inserito con successo. Ricaricare la pagina per visualizzarlo.';
				}
				else messaggio = "Ci sono stati errori nell'inserimento della nota. Riprovare più tardi";
				$('invia_nota').up().insert({
					'top': new Element('p', { 'class': 'messageWin'}).update(messaggio)
				});
				$('invia_nota').remove();
			}	
	});
},


countClick: function(section, id){
	new Ajax.Request('/ajax/click.php',
	{
		method: 'post',
		parameters: $H({'section': section, 'id': id}).toQueryString(),
		onComplete: function(requester){
				/*if (this.responseIsSuccess()){
						
						
				} */
		}
	});
},

topBoxBtnClick: function(e){
	e.stop();
	btn = e.element();
	libtn = e.findElement("li");
	active = $$("#topBox .tabs .active")[0];
	active.removeClassName("active");
	libtn.addClassName("active");
	
	activeol =$$("#topBox .topindirs.active")[0];
	activeol.removeClassName("active");
	
	if (btn.hasClassName("_0")){
		$$("#topBox .topindirs._0")[0].addClassName("active");
	} else if (btn.hasClassName("_1")){
		$$("#topBox .topindirs._1")[0].addClassName("active");
	} else if (btn.hasClassName("_2")){
		$$("#topBox .topindirs._2")[0].addClassName("active");
	}
		
},

initAutocompleter: function(){
	new Ajax.Autocompleter('search_text', 'suggestions', '/ajax/getSuggestionAll.php', 
			{	indicator: "indicator", 
			afterUpdateElement: 
			function(text,li){
				if (li.hasClassName("sugPrimo")) return;
				arr = li.id.split("_");
				if ("Directory" == arr[1]){
					url = "/vis_directory.php?id="+arr[2];
				} else {
					url = "/vis_resource.php?section=" +arr[1]+"&id="+arr[2];
				}
				top.location = url;
			} ,
			onShow: //leggera modifica all'onshow di default in controls.js
			function(element, update){
				if(!update.style.position || update.style.position=='absolute') {
		          update.style.position = 'absolute';
		          Position.clone(element, update, {
		          setHeight: false, 
		          offsetTop: element.offsetHeight,
				  offsetLeft: -500 + element.offsetWidth
          });
        }
        Effect.Appear(update,{duration:0.15});
			}
		});
	$('indicator').clonePosition('search_text', {
            setHeight: false, 
            offsetTop: $('search_text').offsetHeight
          });
},

initAutocompleterDir: function(iddir){
	new Ajax.Autocompleter('search_text_dir', 'suggestions_dir', '/ajax/getSuggestionDir.php',
	{parameters: "iddir="+iddir});
},

ultimiVisti: function(pe) {
			new Ajax.Request('/ajax/getUltimiVisti.php' ,
			{ method: 'get', contentType: "text/html",
			onSuccess: function(req){
				//alert("asdad");
				$('boxUltimiVisti').update(req.responseText);
				first = $('boxUltimiVisti').down('._0');
				//first.setOpacity(0);
				//first.toggle();
				first.setStyle({visibility: 'visible'});
				width = first.getWidth();
				first.setStyle({left: -width + "px"});
				first.next().setStyle({left: -width + "px"});
				first.next().next().setStyle({left: -width + "px"});
				first.next().next().next().setStyle({left: -width + "px"});
				first.next().next().next().next().setStyle({left: -width + "px"});
				//first.toggle();
				
				new Effect.Parrallel([
					new Effect.Move (first,{ x: width, y: 0, mode: 'relative'}),
					new Effect.Move (first.next(),{ x: width, y: 0, mode: 'relative'}),
					new Effect.Move (first.next().next(),{ x: width, y: 0, mode: 'relative'}),
					new Effect.Move (first.next().next().next(),{ x: width, y: 0, mode: 'relative'}),
					new Effect.Move (first.next().next().next().next(),{ x: width, y: 0, mode: 'relative'})
				]);
				
				//new Effect.Appear(first);
				//new Effect.SlideRight(first);
			}});
},

startUpload: function() {
            // make something useful before submit (onStart)
            return true;
},

completeUpload: function(response) {
            // make something useful after (onComplete)
            document.getElementById('fileList').innerHTML = response;
			var files = $$('#fileList a.inserisci');
			files.each(function(file){
				file.observe('click', epjs.linkFileClick.bindAsEventListener(this));
			});
			var files = $$('#fileList a.delete');
			files.each(function(file){
				file.observe('click', epjs.linkDeleteClick.bindAsEventListener(this));
			});
      var files = $$('#fileList a.setimage');
			files.each(function(file){
				file.observe('click', epjs.linkSetImageClick.bindAsEventListener(this));
			});
},

linkFileClick: function(e) {
	e.stop();
	var linkCliccato = Event.findElement(e,'a');
	var url = linkCliccato.getAttribute('href');
	var params = linkCliccato.getAttribute('href').toQueryParams();
	var id = params['id'];
    insertTags('<immagine id='+id+' name=\''+linkCliccato.previous('span.nome').title+'\'>', '</immagine>', linkCliccato.previous('span.nome').title);
},

linkDeleteClick: function(e) {
	e.stop();
	if (confirm('Sei sicuro di voler cancellare l\'immagine?')){
		var linkCliccato = Event.findElement(e,'a');
		var url = linkCliccato.getAttribute('href');
		var params = linkCliccato.getAttribute('href').toQueryParams();
		var id = params['id'];
		var section = params['Section'];
		var idresource = params['ID_Resource'];
		new Ajax.Request('/ajax/upload.php',
		{
			method: 'get',
			parameters: $H({'id':id, 'delete':'yes', 'Section': section, 'ID_Resource': idresource}).toQueryString(),
			onComplete: function(requester){
					/*if (this.responseIsSuccess()){
							
							
					} */
					epjs.completeUpload(requester.responseText);
				}	
		});
	}
    
},

linkSetImageClick: function(e) {
	e.stop();
	var linkCliccato = Event.findElement(e,'a');
	var url = linkCliccato.getAttribute('href');
	var params = linkCliccato.getAttribute('href').toQueryParams();
	var id = params['id'];
	var section = params['Section'];
	var idresource = params['ID_Resource'];
	new Ajax.Request('/ajax/upload.php',
	{
		method: 'get',
		parameters: $H({'id':id, 'action':'setimage', 'Section': section, 'ID_Resource': idresource}).toQueryString(),
		onComplete: function(requester){
				/*if (this.responseIsSuccess()){
						
						
				} */
				epjs.completeUpload(requester.responseText);
			}	
	});
},

toggleUseExcerpt: function(e) {
	var div = $('edtSummary').up('div');
	var checkBox = $('noExcerpt');
	if (checkBox.checked)
	{
	 div.hide();
	}
	else
	{
	 div.show();
	}
	div.toggle();
},

//Inizializzazione Event Listener e iniettamento del codice nel DOM
inizializza: function() {
	var correlati = $$('.argomentiCorrelati .piu');
	for (var j = 0; j < correlati.length; j++){
		Event.observe(correlati[j], 'click', this.espandiContraiCorrelati.bindAsEventListener(this));
	}
	var puntini = $$('.argomentiCorrelati .puntini');
	for (var j = 0; j < puntini.length; j++){
		Event.observe(puntini[j], 'click', this.espandiContraiCorrelati.bindAsEventListener(this));
	}
	
	var espandi = $$('#lista_articoli .espandi');
	for (var j = 0; j < espandi.length; j++){
		Event.observe(espandi[j], 'click', this.espandiContraiDettagliArtCorso.bindAsEventListener(this));
	}
	
	//var cmdNote = $$(".cmdAggiungiNota, #box_invia_nota .chiudi");
	//for (var j = 0; j < cmdNote.length; j++){
	//	Event.observe(cmdNote[j], 'click', this.popupNota.bindAsEventListener(this));
	//}
	
	var inviaNotaForm = $('invia_nota');
	if (inviaNotaForm) Event.observe(inviaNotaForm, 'submit', this.inviaNota.bindAsEventListener(this));
	
	var votaButton = $$("#voti .vota")[0];
	if (votaButton) Event.observe(votaButton, 'click', this.popupVota.bindAsEventListener(this));
	
	var cmd_voto_pos = $('cmd_voto_pos');
	var cmd_voto_neg = $('cmd_voto_neg');
	
	if (cmd_voto_pos) Event.observe(cmd_voto_pos, 'click', this.vota.bindAsEventListener(this));
	if (cmd_voto_neg) Event.observe(cmd_voto_neg, 'click', this.vota.bindAsEventListener(this));
	
	var search_text = $('search_text');
	if (search_text) { this.initAutocompleter(); }
	
	var search_text_dir = $('search_text_dir');
	var body = $$("body")[0];
	if (search_text_dir) {
		var body = $$("body")[0];
		this.initAutocompleterDir(body.id.substring(10));
		
	}
	
	var topbox = $('topBox');
	if (topbox){
		$$('#topBox .tabs .btn').each(function(element){
				element.observe('click',epjs.topBoxBtnClick.bindAsEventListener(this))});
	}
  
  var noExcerpt = $('noExcerpt');
	if (noExcerpt){
    noExcerpt.observe('change', epjs.toggleUseExcerpt.bindAsEventListener(this));
	}
	
	var frmUpload = $('frmUpload');
	if (frmUpload){
		frmUpload.observe('submit', function(){
			return AIM.submit(this, {'onStart' : epjs.startUpload, 'onComplete' : epjs.completeUpload});
		});
		var files = $$('#fileList a.inserisci');
		files.each(function(file){
			file.observe('click', epjs.linkFileClick.bindAsEventListener(this));
		});
		var files = $$('#fileList a.delete');
		files.each(function(file){
			file.observe('click', epjs.linkDeleteClick.bindAsEventListener(this));
		});
    var files = $$('#fileList a.setimage');
		files.each(function(file){
			file.observe('click', epjs.linkSetImageClick.bindAsEventListener(this));
		});
	}
	
	/*var boxUltimiVisti = $('boxUltimiVisti');
	if (boxUltimiVisti){
		this.ultimiVisti();
		new PeriodicalExecuter(this.ultimiVisti, 5);
	}*/
	
	//Input con valore a scomparsa
	$$('.initialValueAsLabel').each(function(element){
		element.setStyle({'color': '#999'});
		element.initialValue = element.getValue();
		element.hasInitialValue = true;
		form = element.up('form');
		form.observe('submit', function(e){
			if (element.hasInitialValue){
				element.focus();
				//element.value = '';
				//element.hasInitialValue = false;
				e.stop();
			}
		});
		element.observe('focus', function(){if (element.hasInitialValue) {
			element.value = '';
			element.setStyle({'color': 'Black'});
			element.hasInitialValue = false;
		}});
		element.observe('blur', function(){if (element.getValue()=='') {
			element.setStyle({'color': '#aaa'});
			element.value = element.initialValue;
			element.hasInitialValue = true;
		}});
	});
	
	//preloading images
	img1 = new Image(); 
	img1.src = "/stili/imageset/sfondobox.png";
	img2 = new Image(); 
	img2.src = "/stili/imageset/sfondobox_.png";
		
}

}

$(document).observe('dom:loaded', epjs.inizializza.bindAsEventListener(epjs));