// --------------------- funzioni generali

function test() {
	SelectLineByCode("events", 4);
}

function trace() {
	// scrive in un alert tutti gli argomenti passati separati da a-capo
	alert(Array.prototype.join.call(arguments,"\n"));
}

function UTF8Encode(theString) {
  return unescape(encodeURIComponent(theString));
}

function UTF8Decode(theString) {
  return decodeURIComponent(escape(theString));
}

function $$(theId) {
	// scorciatoia per non scrivere tutte le volte la solfa document.getElementById ($$ per non impastarsi con jQuery)
	return document.getElementById(theId);
}

function GetObject(theObj) {
	// torna l'oggetto sia che theObj sia una stringa o un oggetto
	if (typeof(theObj) == "string")
		return $$(theObj);
	else return theObj;
}

function XHRCreate() {
	// crea un oggetto XMLHttpRequest
	if (window.XMLHttpRequest) // IE7+, Firefox, Chrome, Opera, Safari
		return new XMLHttpRequest();
	else // IE6, IE5
		return new ActiveXObject("Microsoft.XMLHTTP");
}

function CollectChildrenByTag() {
	// genera un array degli elementi del genitore corrispondenti alla lista di tag passati
	// parametri (in arguments)
	//		0 	 --> il genitore (node element)
	//		1..n --> i tag (string)
	var tagInd, elemInd; // indici per tag ed elementi
	var theParent = arguments[0]; // il genitore
	var tagList; // contenitore per i tag trovati
	var result = Array(); // output
	for (tagInd = 1; tagInd < arguments.length; tagInd++) {
		tagList = theParent.getElementsByTagName(arguments[tagInd]);
		for (elemInd = 0; elemInd < tagList.length; elemInd++)
			result.push(tagList[elemInd]);
	}
	return result;
}

function CollectFormData(theForm) {
	var i;
	theForm = $$(theForm);
	var input = CollectChildrenByTag(theForm, "input", "textarea", "select");
	var output = new Array();
	for (i = 0; i < input.length; i++) {
		// trace("input.type: " + input[i].type, "input.checked: " + input[i].checked);
		if ((input[i].type != "radio" && input[i].type != "checkbox") || ((input[i].type == "radio" || input[i].type == "checkbox") && input[i].checked))
			output.push(input[i].name + "=" + UTF8Encode(input[i].value));
	}
	return output.join("&");
}

function JSONPopulateForm(theForm, theData) {
	// popola con theData (JSON string) i campi del form theForm
	// NOTE
	//	- i nomi degli elementi del form devono corrispondere ai nomi dei campi nel DB
	//	- gli ID degli elem. mutlipli (option e radio) devono avere la forma nome+valore
	
	var fldName;
	var theFld;
	var radioGroup;

	eval ("theData = " + theData); // trasformo la stringa JSON in oggetto
	for (fldName in theData) {
		if ((theFld = $$(fldName)) || (theFld = $$(fldName + theData[fldName]))) {
			switch (theFld.type) {
				// imposto i campi per il value
				case "text":
				case "textarea":
				case "password":
				case "hidden":
					if (fldName == "descrizione") // caso speciale per tinyMCE
						tinyMCE.get('descrizione').setContent(theData[fldName]);
					else
						theFld.value = theData[fldName];
					break;
				// imposto il checked per i checkbox
				case "checkbox":
					theFld.checked = theData[fldName] == 1;
					break;
				// imposto il checked per i radio
				case "radio":
					// trace(fldName + theData[fldName], theData[fldName], theFld.type);
					$$(fldName + theData[fldName]).checked = true;
					$$(fldName + theData[fldName]).onclick();
					break
				// imposto il selected per i select
				case "select-one":
					$$(fldName + theData[fldName]).selected = true;
					break;
			}
		}
	}
}

function FadeOut(theDiv) {
	theDiv = $$(theDiv);
	if (theDiv.style.opacity <= 0.1) { // fadeout finito
		theDiv.style.visibility = "hidden";
		theDiv.style.opacity = 0;
		clearInterval(tipDelay);
	} else { // fadeout in corso
		theDiv.style.opacity -= 0.05;
	}
}

function ShowTip(theText) {
	var tipDiv = $$("tip");
	tipDiv.innerHTML = theText;
	tipDiv.style.opacity = 1;
	tipDiv.style.visibility = "visible";
	tipDelay = setInterval("FadeOut('tip')", 100);
}

// --------------------- AJAX File Uploader

function CreateUploader(upObj, targetPage) {
	var upObj = $$(upObj);
	var uploader = new qq.FileUploader({
		element: upObj,
		action: targetPage,
		debug: true
	});
	// trace(typeof(uploader), upObj + "-->" + uploader['element'], targetPage + "-->" + uploader['action']);
}

// --------------------- ShadowBox

function SBOpen(thePage) {
    Shadowbox.open({
		player: "iframe",
        content: thePage,
        width: 400,
		height: 600
    });
}

// --------------------- gestione interfaccia

function ShowOneDiv(theDiv, hideClass, showClass) {
	// mostra (se invisibile) o nasconde (se visibile) il div specificato
	// sono richieste due classi nei CSS: hideClass e showClass
	var title =  theDiv.substr(0, theDiv.length - 4);
	if (window.prevOpen) { // esiste un div aperto
		$$(prevOpen).className = hideClass; // lo chiudo
		if (window.prevOpen == theDiv) // quello cliccato era quello aperto prima
			window.prevOpen = null; // quindi non ce n'è nessuno aperto
		else { // quello cliccato non era quello aperto prima
			$$(theDiv).className = showClass; // lo apro
			window.prevOpen = theDiv; // e lo registro
		}
	} else { // non c'erano div aperti
		$$(theDiv).className = showClass; // lo apro
		window.prevOpen = theDiv; // e lo registro
	}
}

function OpenArg(theArg) {
	// apre l'argomento theArg al load nella sottopagina
	if (theArg)
		$$(theArg).onclick(); // invio un clik al link
}

// --------------------- gestione eventi

function SelectFirstLine(theList) {
	// selezione la prima linea dalla lista applicandole selClass
	// e disattivando l'eventuale selezione precedente
	theList = GetObject(theList);
	var evtList = theList.getElementsByTagName("li");
	// invio un click alla prima linea
	if (evtList.length > 0)
		evtList[0].onclick();
	else theList.selLine = "";
	theList.scrollTop = 0;
}

function SelectLine(theList, theLine, selClass) {
	// selezione una linea dalla lista applicandole selClass
	// e disattivando l'eventuale selezione precedente
	theList = GetObject(theList);
	if ($$(theList.selLine)) // se esiste una selezione precedente
		$$(theList.selLine).className = ""; // la spengo
	theList.selLine = theLine; // salvo la selezione attuale
	$$(theLine).className = selClass; // e la accendo
}

function SelectLineByCode(theList, theCode) {
	// a partire dal codice theCode selezione una linea dalla lista applicandole selClass
	// e disattivando l'eventuale selezione precedente
	theList = GetObject(theList);
	// invio un click alla linea col codice theCode
	$$(theCode).onclick();
}

function FormEnable(theForm, enabled) {
	// abilita/disabilita un form, allineando allo stato enabled (t/f) tutti i suoi elementi
	// e cambiando lo stile in modo corrispondente
	var i;
	theForm = $$(theForm);
	var formElems = CollectChildrenByTag(theForm, "input", "textarea", "label");
	for (i = 0; i < formElems.length; i++) {
		formElems[i].disabled = !enabled;
		formElems[i].readOnly = !enabled;
		if (enabled)
			formElems[i].className = "";
		else
			formElems[i].className = "disabled";
	}
}

function CreateListElement(codice, origDate, formDate, titolo) {
	// crea il nuovo nodo di lista li per un insert
	// target html --> <li id='$$codice' onclick='SelectLine(\"events\",\"$$codice\", \"selLine\"); DetailEvent($$codice, \"eventDetail\");' linedate='$$date'><img title='cancella questo evento' src='../img/delete_icon.png' alt='cancella evento' class='deleteIcon' onclick='DeleteEvent($$codice)' />[$$date] $$titolo</li>
	// creo l'elemento di lista
	// trace(codice, origDate, formDate, titolo);
	var newLi = document.createElement('li');
	// riempio gli attributi
	newLi.setAttribute("id", codice);
	//SelectLine(\"events\",\"$codice\", \"selLine\"); ShowAttachments($codice, \"filelist\"); DetailEvent($codice, \"eventDetail\");
	newLi.setAttribute("onclick", 'SelectLine("events","' + codice + '", "selLine"); ShowAttachments(' + codice + ', "filelist"); DetailEvent(' + codice + ', "eventDetail");');
	newLi.setAttribute("linedate", origDate);
	// creo l'immagine per delete
	var newImg = document.createElement('img');
	// riempio gli attributi
	newImg.setAttribute("title", 'cancella questo evento');
	newImg.setAttribute("src", '../img/delete_icon.png');
	newImg.setAttribute("class", 'deleteIcon');
	newImg.setAttribute("onclick", 'DeleteEvent(' + codice + ');');
	// creo il testo base
	// tolgo i backslash dalla stringa del titolo (g: globale)
	titolo = titolo.replace(/\\/g,'');
	var newText = document.createTextNode('[' + formDate + '] ' + titolo.replace(/\\/g,''));
	// aggiungo il nodo immagine e il testo al tag li
	newLi.appendChild(newImg);
	newLi.appendChild(newText);
	return newLi;
}

function DeleteLineFromList(theList, theCode, selFirst) {
	// cancella l'evento con coice theCode dalla lista e seleziona il primo li
	$$(theList).removeChild($$(theCode));
	if (selFirst)
		SelectFirstLine(theList);
}

function InsertLineInList(targetList, theData) {
	// inserisce nella lista degli eventi una linea con dati theData (JSON) mantenendo l'ordinamento per data
	var i = 0;
	var tmpElem;
	// trace(theData.codice, theData.origDate, theData.formDate, UTF8Decode(theData.titolo));
	var newLi = CreateListElement(theData.codice, theData.origDate, theData.formDate, UTF8Decode(theData.titolo));
	// percorro gli eventi fino a trovare il posto giusto per l'inserimento
	var evtList = $$(targetList).getElementsByTagName("li");
	do {
		tmpElem = evtList[i++];
		// trace(tmpElem.getAttribute("linedate"), theData.origDate);
	} while (tmpElem.getAttribute("linedate") > theData.origDate);																																																																																																																																																																																																																																																																																																																																																																																																																																																																																							
	$$(targetList).insertBefore(newLi, tmpElem);
	SelectLineByCode(targetList, theData.codice)
}

function NewEvent(targetForm) {
	// prepara il form vuoto per l'inserimento di un nuovo evento
	var i;
	targetForm = $$(targetForm);
	var childElems = targetForm.getElementsByTagName("*");
	for (i = 0; i < childElems.length; i++) {
		switch (childElems[i].type) {
			case "radio":
			case "checkbox":
				childElems[i].checked = false;
				break;
			case "hidden":
			case "text":
			case "password":
			case "textarea":
				childElems[i].value = "";
				break;
		}
	}
	targetForm.elements['codice'].value = "";
	targetForm.elements['tipoData1'].checked = true;
	tinyMCE.get('descrizione').setContent("");
}

function RecordEvent(targetForm) {
	// registra i dati dell'evento contenuti nel form specificato
	// ============== VIPPPPPPPPP ---> devo usare GET perché POST mi dà un sacco di problemi con le accentate !!!!!!!!
	var xmlhttp = XHRCreate();
	var vars = CollectFormData(targetForm);
	xmlhttp.open("GET", "_recordevent.php?" + vars);
	// gestisco la funzione di rientro
	xmlhttp.onreadystatechange = function () {
		if (xmlhttp.readyState == 4) {
			if (xmlhttp.responseText != "") {
				var theData;
				eval("theData = " + xmlhttp.responseText + ";"); // trasformo il JSON in oggetto js
				switch (theData.op) {
					case 2: // update = delete + insert
						DeleteLineFromList("events", theData.codice, false);
						InsertLineInList("events", theData);
						ShowTip("aggiornamento completato");
						break;
					case 1: // insert
						InsertLineInList("events", theData);
						ShowTip("inserimento completato");
						break;
					case 0: // errore
						ShowTip("registrazione fallita");
						break;
				}
			}
		}
	}
	// invio la richiesta
	xmlhttp.send();	
}

function ShowAttachments(evCode, targetFrame) {
	// carica l'elenco degli attachment per un evento nel frame/iframe targetFrame
	$$(targetFrame).src = "_materiale.php?id=" + evCode;
}

function DetailEvent(evCode, targetForm) {
	// genera il dettaglio di un evento e riempie con i dati ricevuti il form theForm (string)
	var xmlhttp = XHRCreate();
	xmlhttp.open("POST", "_detailevent.php");
	var vars = "evtcode=" + evCode;
	// preparo gli header
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.setRequestHeader("Content-length", vars.length);
	// gestisco la funzione di rientro
	xmlhttp.onreadystatechange = function () {
		if (xmlhttp.readyState == 4) {
			JSONPopulateForm(targetForm, xmlhttp.responseText);
		}
	}
	// invio la richiesta
	xmlhttp.send(vars);	
}

function DeleteEvent(evCode) {
	// cancella un evento su conferma
	if (confirm("Vuoi davvero cancellare questo evento?")) {
		var xmlhttp = XHRCreate();
		xmlhttp.open("POST", "_deleteevent.php");
		var vars = "evtcode=" + evCode;
		// preparo gli header
		xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xmlhttp.setRequestHeader("Content-length", vars.length);
		// gestisco la funzione di rientro
		xmlhttp.onreadystatechange = function () {
			if (xmlhttp.readyState == 4) {
				DeleteLineFromList("events", evCode, true);
				ShowTip(xmlhttp.responseText);
			}
		}
		// invio la richiesta
		xmlhttp.send(vars);	
	}
}
