/**
 * Funzioni javascript per il frontend.
 * @author Piumatti Daniele <piumaz@hotmail.it>
 */

window.onload = init;

/*
 * Funzioni da richiamare sull'onload
 */
function init() { 

	buttonfix();
	CZ_forms_blockdoublesubmit();
	lex_vote();
}

/* per i button */
function buttonfix() {
    var buttons = document.getElementsByTagName('button');
    for (var i=0; i<buttons.length; i++) {
        if(buttons[i].onclick) continue;
        
        buttons[i].onclick = function () {
            for(j=0; j<this.form.elements.length; j++)
                if( this.form.elements[j].tagName == 'BUTTON' )
                    this.form.elements[j].disabled = true;
            this.disabled=false;
            this.value = this.attributes.getNamedItem("value").nodeValue ;
        }
    }
}

/*
 * Countdown
 */
function countdown(nameelement,anno,mese,giorno,ora,min,sec) { 

	iniData= new Date(anno,(mese-1),giorno,ora,min,sec); // data inizio sequenza mesi-1 es. set=8

	oggi= new Date();
	milDif=(iniData-oggi); // differenza fra la data di arrivo e la data attuale
	giorni=parseInt(milDif/86400000); // giorni
	milDif=milDif-(giorni*86400000); // millisecondi restanti per giorni
	ore=parseInt(milDif/3600000); // ore
	milDif=milDif-(ore*3600000); // millisecondi restanti per ore
	minuti=parseInt(milDif/60000); // minuti
	milDif=milDif-(minuti*60000); //millisecondi restanti per minuti
	secondi=parseInt(milDif/1000); // secondi
	milDif=milDif-(secondi*1000); //millisecondi restanti per secondi

	// è arrivata la data?
	if (giorni <= 0 && ore <= 0 && minuti <= 0 && secondi <= 0) {
		testo="Votazione terminata!";
	} else {
		testo="Tempo residuo: "+giorni+"g "+ore+"h "+minuti+"m "+secondi+"s";
	}

	// compatibilità vari browser 
	if (document.layers) {
		document.layers.nameelement.document.write(testo);
		document.layers.nameelement.document.close();
	} else {
		if (document.getElementById) {
			document.getElementById(nameelement).innerHTML=testo;
		} else {
			document.all.nameelement.innerHTML=testo;
		}
	}


	if (giorni <= 0 && ore <= 0 && minuti <= 0 && secondi <= 0) {
		document.location.reload();
	} else {
		setTimeout("countdown('"+nameelement+"',"+anno+","+mese+","+giorno+","+ora+","+min+","+sec+")",1000);
	}
	
}

/*
 * Apre i popup
 */
function CZ_popup(url,name,features) {
	window.open(url,name,features);
}

/*
 * Chiede conferma
 */
function CZ_confirm(mystring) {
	var ok = window.confirm(mystring);
	return ok;
}

/*
 * Funzioni AJAX
 */
var CZ_http = CZ_createRequestObject();

function CZ_createRequestObject() { 
	
    var ro;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer"){
        ro = new ActiveXObject("Microsoft.XMLHTTP");
    } else {
        ro = new XMLHttpRequest();
    }

    return ro;
}



function CZ_sndReq(idelement, url) {
	if(url) {
		document.getElementById(idelement).innerHTML = "<img src=\"http://www.webarchia.org/view/images/loading.gif\">";
		CZ_http.open('get', url);
		CZ_http.overrideMimeType('text/xml');
		CZ_http.onreadystatechange = function() {CZ_handleResponse(idelement); }
		CZ_http.send(null);	
	
	} else {
		CZ_http.open('get', idelement);
		CZ_http.overrideMimeType('text/xml');
		CZ_http.onreadystatechange = function() {CZ_handleResponse(""); }
		CZ_http.send(null);
	}
	

}

function CZ_handleResponse(idelement) {
    
	if(CZ_http.readyState == 4){
        var response = CZ_http.responseText;
		var param = new Array();
		var update = new Array();
		
        if(response.indexOf('|') != -1) {
			param = response.split('||');
			
			for(n=0; param[n]; n++) {
				update = param[n].split('|');
				if(document.getElementById(update[0])) { 
                    document.getElementById(update[0]).innerHTML = update[1];
				}
			}
			
        } else if(document.getElementById(idelement)) {
			document.getElementById(idelement).innerHTML = response;
		}
    }
}

/*
 * Blocca il multi-invio dei form
 */
function CZ_forms_blockdoublesubmit() {

    function setBlockForm(e) {
		if(!e) {
		    var e = window.event; 
        }

        if(sendform==true) { 
			//e.preventDefault();
			e.cancelBubble = true;
            return false;
        } else {
			sendform = true;
            return true;
        }
    }

	//form
	var sendform = false;

	var formTag = document.getElementsByTagName('form');
	for (var i = 0; i < formTag.length; i++) { 	
        formTag.item(i).onsubmit = setBlockForm;
	}
    
}

/*
 * Votazioni
 */
 function lex_vote() {
	
	if($('btnvotazione')) { 
		
		function ajaxvote(e) {

			if(!e) {
				var e = window.event; 
			}
			
			e.cancelBubble = true;
			

			var url = this.getAttribute('href');
			var params = url.replace('http://www.webarchia.org/index.php','');
			var ajaxurl = "http://www.webarchia.org/ajax.php";

			this.setAttribute('href', 'javascript:void(0);');

			document.getElementById('resultvoto').innerHTML = "<img src=\"http://www.webarchia.org/view/images/loading.gif\">";

			var ajax = new Ajax.Request(
					ajaxurl,
					{
						method: 'get', 
						parameters: params, 
						asynchronous: true,
						onFailure: function(e) {
							ajax_error('resultvoto');
						},
						onComplete: function( response ){
							ajax_replace_response('resultvoto', response );
						}
					}
				)


		}


		var si = $('si');
		var no = $('no');
		var astensione = $('astensione');

		si.onclick = ajaxvote;
		no.onclick = ajaxvote;
		astensione.onclick = ajaxvote;
	}

}

function ajax_error(idelement){
	$(idelement).innerHTML = "Errore del server, ricaricare la pagina.";
}

function ajax_replace_response(idelement, response ){
	$(idelement).innerHTML = response.responseText;
	aggiornaPulsanteProponi();
}

function aggiornaPulsanteProponi() {

	document.getElementById('proponivotazione').innerHTML = "<img src=\"http://www.webarchia.org/view/images/loading.gif\">";

	var params = "plugin=lex&bot=proponivotazioni&action=reload";
	var ajaxurl = "http://www.webarchia.org/ajax.php";

	var ajax = new Ajax.Request(
			ajaxurl,
			{
				method: 'get', 
				parameters: params, 
				asynchronous: true,
				onFailure: function(e) {
					ajax_error('proponivotazione');
				},
				onComplete: function( response ){ 
					$('proponivotazione').innerHTML = response.responseText;
				}
			}
		)


}
