window.onload = function () { jTorbalizeMe(); }
var editorToUse = 'tiny_mce';


 /*- dropdown.js -*/ 

$(document).ready(function() {

$('#attivita_li').hover(
	function(){ $('#show_hide_attivita').fadeIn("fast"); },
	function(){ $('#show_hide_attivita').fadeOut("slow");});

$('#pubblicazioni_li').hover(
	function(){ $('#show_hide_pubblicazioni').fadeIn("fast"); },
	function(){ $('#show_hide_pubblicazioni').fadeOut("slow");});

});


 /*- callback.js -*/ 

// JavaScript Document

//COMMON
function redirect(uri){
	window.location.replace(uri);
}

function reloadPage(id, response, formId, domainId){
		//alert(response);
                window.location.reload();
}

function showResponse(id, response, formId, domainId, targetDiv){
        informationBox(false, false, targetDiv, response, 'reloadPage');
}

//CUSTOM
function showResponseNl(id, response, formId, domainId, targetDiv){
        informationBox(false, false, targetDiv, response, 'gotoNlList');
}

function addAttachment(fileName){
	alert("ciao");
	html = "<div>" + fileName + "</div>";
	
	$('#allegati_newsletter').append(html);
}

function leavePostedId(id, response, formId, domainId){
	//alert("in callback: " + response);
	document.getElementById("zcfor").value = response;	
}

function gotoNlList(){
		//alert("-> " + response);
                //alert(id);
		redirect("annuncia.php");
}

function gotoNewsList(){
		//alert("-> " + response);
                //alert(id);
		redirect("elenco_news.php");
}

function gotoNewsDetail(id, response, formId, domainId){
		//alert("-> " + response);
                //alert(id);
		redirect("news.php?zcid=" + response);
}

function goToNewsletter(){
	redirect("annuncia.php");
}

function gotoCategory(id, response, formId, domainId){
		//alert("-> " + response);
                //alert(id);
		redirect("categoria.php?zcid=" + id);
}

function gotoGallery(id, response, formId, domainId){
		//alert("-> " + response);
		redirect("gallery.php?zcid=" + response);
}

function reloadGallery(id, response, formId, domainId, targetDiv, contentId, page) {
	var uri = "./TORBA/custom/Common/ContenitorBox.php?";
	if(contentId)	uri += "zcfor=" + contentId;
	uri += "&zdid=" + domainId;
	if(!page) page = 1;
	uri += "&zcpag=" + page;
        uri += "&targetDiv=" + targetDiv;
//alert("id:" + id + ", response:" + response + ", formId:" + formId + ", domainId:" + domainId + ", targetDiv:" + targetDiv + ", contentId:" + contentId + ", page:" + page + "\nuri:" + uri);
	var callback = function(id, response) {
		var obj = document.getElementById(id);
		obj.innerHTML = response;

		jTorbalizeMe();
	}

	ajaxGet(id, uri, callback);
}

function setProductImage(formId, imageId, imageValue, relationType){
	form = document.getElementById(formId);
	
	form.zcval.value = imageValue;
	form.zcfor.value = imageId;
	form.zcrty.value = relationType;
	
	imageDiv = document.getElementById("imageDiv");
		
	var uri = "./TORBA/custom/Common/LoadImage.php?";
	uri += "imageValue=" + imageValue;

	var callback = function(id, response) {
		var obj = document.getElementById(id);
		obj.innerHTML = response;
	}
	
	ajaxGet('imageDiv', uri, callback);
}

function setLogo(imageDivId, imageId, domainId/*, imageValue, relationType*/){

	var uri = "./TORBA/custom/Common/LoadImage.php?";
	uri += "imageId=" + imageId;
        uri += "&zdid=" + domainId;

	var callback = function(id, response) {
		var obj = document.getElementById(id);
		//obj.innerHTML = response;
		obj.innerHTML = "Logo Salvato!";
	}

	ajaxGet(imageDivId, uri, callback);
}

function newActivity(id, response, formId, domainId, value){
        editContent('body', response, domainId, 'inputBox', false, false, false, false, value);
}

function newNewsletter(id, response, formId, domainId, value){
        loadEdit('newsletter_div', response, domainId);
}

function newOption(id, response, formId, domainId, value){
		// creare form con campi necessari "form_idValue"
		// value = content_foreign
}

// VERY CUSTOM //
function datesToValue(){
    value = document.getElementById('zcval');

    time_from = document.getElementById('time_hour_from').value + ":" + document.getElementById('time_minutes_from').value;
    time_to   = document.getElementById('time_hour_to').value + ":" + document.getElementById('time_minutes_to').value;

    value.value = time_from + "-" + time_to;
}

function setExpireDate(id, lang){

    var year, month, day, hours, minutes;

    field = document.getElementById(id);

    //date[2] = YYYY, date[1] = MM, date[0] = dd
    tmp = document.getElementById("expire");

    if(tmp && (tmp.value != "")){
        date    = tmp.value.split(" ");
        year    = date[2];
        month   = parseMonth(date[1], lang);
        if(month < 10) month = "0" + month;

        day     = date[0];
    }

    //tmp = document.getElementById("time_hour");
    //if(tmp) hours   = tmp.value;

    //tmp = document.getElementById("time_minutes");
    //if(tmp) minutes = tmp.value;

    //formato MySql "2009-09-23 16:19:10"
    field.value = formatDatetime(year, month, day, hours, minutes);

    //alert("--> " + document.getElementById(id).value);
}

function setDate(id){

    var year, month, day, hours, minutes;

    field = document.getElementById(id);

    //date[2] = YYYY, date[1] = MM, date[0] = dd
    tmp = document.getElementById("date");

    if(tmp && (tmp.value != "")){
         date = tmp.value.split("-");

//alert("date length: " + tmp.value.length);

	switch(tmp.value.length){
		// aaaa
		case 4:{
			day	= '01';
        		month   = '01';
			year    = date[0];
			break;
		}
		// mm-aaaa
		case 7:{
			day	= '01';
        		month   = date[0];
			year    = date[1];
			break;
		}
		// gg-mm-aaaa
		case 10:{
			day	= date[0]
        		month   = date[1];
			year    = date[2];
			break;
		}
	}

        if(month.length < 2) month = "0" + month;
    }

    //formato MySql "2009-09-23 16:19:10"
    field.value = formatDatetime(year, month, day, hours, minutes);

//alert(field.value);
}



 /*- framework.js -*/ 

// JavaScript Document

function jTorbalizeMe(){
    var tmp, code, obj;
    for(var i = 0; i < document.links.length; i++){
        obj = document.links[i];
        tmp = obj.getAttribute('rel');
        if(tmp){
            code = tmp.substr(3);
            if(code) parseAction(obj, code);
        }
    }
}

function parseAction(obj, fullCode){
    var code = fullCode.split('_',6);
	
    //code[0] = codice azione
    //code[1] = id dominio
    //code[2] = id content
    var general_value       = code[5];
    var supported_langs     = code[4];
    var postBack_code	= code[3];
    var id_content		= code[2];
    var id_domain 		= code[1];
    var action_code		= code[0];
    //alert(code[0] + " - " + code[1] + " - " + code[2] + " - " + code[3]);
    switch(action_code)
    {
        //Inserimento/Aggiornamento
        case '1':
        {						
            switch(id_domain)
            {
                // DISTINZIONE DOMINI

                case '12':
                {
                    switch(postBack_code){
                        case '1':
                        {
                            obj.onclick = function() {
                                //confirmBox("postContent('editForm'," + code[1] + ",reloadPage)","Salvare?");
                                postContent('editForm_' + id_content, id_domain, reloadPage, false, supported_langs);
                                return false;
                            }
                            break;
                        }
                        default:
                        {
                            obj.onclick = function() {
                                //confirmBox("postContent('editForm'," + code[1] + ",reloadPage)","Salvare?");
                                postContent('editForm_' + id_content, id_domain, reloadPage, false, supported_langs);
                                return false;
                            }
                            break;
                        }
									
                    }
                    break;
                }
                case '9':
                {
                    obj.onclick = function() {
                        //confirmBox("postContent('editForm'," + code[1] + ",reloadPage)","Salvare?");
                        postContent('editForm_' + id_content, id_domain, reloadPage, false, supported_langs);
                        return false;
                    }
                    break;
                }
                case '#ZDOMAIN_PSEUDONEWS#':
                {
                    obj.onclick = function() {
                        //confirmBox("postContent('editForm'," + code[1] + ",reloadPage)","Salvare?");
                        postContent('editForm_' + id_content, id_domain, reloadPage, false, supported_langs);
                        return false;
                    }
                    break;
                }
                case '19':
                {
                    obj.onclick = function() {
                        if(checkNewsTitle()){
                            //confirmBox("postContent('editForm'," + code[1] + ",reloadPage)","Salvare?");
                            setExpireDate("zcdat", "IT");
                            postContent('editForm_' + id_content, id_domain, reloadPage);
                        }
                        return false;
                    }
                    break;
                }

                case '17':
                {
                    obj.onclick = function() {
                        //confirmBox("postContent('editForm'," + code[1] + ",reloadPage)","Salvare?");
                        setDate("zcval");
                        postContent('editForm_' + id_content, id_domain, reloadPage);
                        return false;
                    }
                    break;
                }

                case '13':
                {
                    obj.onclick = function() {
                        //confirmBox("postContent('editForm'," + code[1] + ",reloadPage)","Salvare?");
                        postContent('editForm_' + id_content, id_domain, reloadPage);
                        return false;
                    }
                    break;
                }
                case '14':
                {
                    obj.onclick = function() {
                        //confirmBox("postContent('editForm'," + code[1] + ",reloadPage)","Salvare?");
                        checkUnderlineSelection('zcval');
                        postContent('editForm_' + id_content, id_domain, reloadPage);
                        return false;
                    }
                    break;
                }
                case '15':
                {
                    obj.onclick = function() {
                        //confirmBox("postContent('editForm'," + code[1] + ",reloadPage)","Salvare?");
                        if(checkEvento()){
                            datesToValue();
                            mergeDateTime("zcdat", "IT");
                            setExpireDate("zcexp", "IT");
                            postContent('editForm_' + id_content, id_domain, reloadPage);
                        }
                        return false;
                    }
                    break;
                }
                case '16':
                {
                    obj.onclick = function() {
                        //confirmBox("postContent('editForm'," + code[1] + ",reloadPage)","Salvare?");
                        //mergeDateTime("zcdat", "IT");
                        postContent('editForm_' + id_content, id_domain, reloadPage);
                        return false;
                    }
                    break;
                }
                default:
                {
                    obj.onclick = function() {
                        //confirmBox("postContent('editForm'," + code[1] + ",reloadPage)","Salvare?");
                        //alert(id_content + " - " + id_domain + " - " + supported_langs);
                        postContent('editForm_' + id_content, id_domain, reloadPage, false, supported_langs);
                        return false;
                    }
                    break;
                }	
            }
            break;
        }
        //Inserimento/Aggiornamento Content in Bozza
        case '2':
        {
            //alert("jT_2");
            obj.onclick = function() {
                //confirmBox("changeFieldValue('zcsta','1'); postContent('editForm_" + code[2] + "'," + code[1] + ",reloadPage);","Bozza?");
                changeFieldValue('zcsta','1');
                postContent("editForm_" + id_content, id_domain, reloadPage);
                return false;
            }
            break;
        }
        //CAMBIA STATO -- to Archived
        case '3':
        {
            //alert("jT_3");
            obj.onclick = function() {
                confirmBox("setContentState(" + id_content + "," + id_domain + ",3,reloadPage)","Archive this News?");
                return false;
            }
            break;
        }
        //CAMBIA STATO -- to Draft
        case '4':
        {
            //alert("jT_4");
            obj.onclick = function() {
                confirmBox("setContentState(" + id_content + "," + id_domain + ",1,reloadPage)","Rendere Bozza?");
                return false;
            }
            break;
        }
        //CAMBIA STATO -- to Published
        case '5':
        {
            //alert("jT_5");
            obj.onclick = function() {
                confirmBox("setContentState(" + id_content + "," + id_domain + ",2,reloadPage)","Publish this News?");
                return false;
            }
            break;
        }
        //Elimina Content
        case '6':
        {
            switch(id_domain)
            {
                // DISTINZIONE DOMINI
							
							
                case '12':
                {
                    switch(postBack_code){
                        case '1':
                        {
                            obj.onclick = function() {
                                //alert("reloadGallery('body#box', false, false, 12, 'body', "+ supported_langs +", "+ general_value +")");
                                confirmBox("dropContent(" + id_content + "," + id_domain + "); reloadGallery('body#box', false, false, 12, 'body', "+ supported_langs +", "+ general_value +"); closeBox('body#box#box');","ATTENZIONE: Eliminare la foto?","body#box");
                                return false;
                            }
                            break;
                        }
                        default:
                        {
                            obj.onclick = function() {
                                //alert("id: " + id_content + " - domain: " + id_domain);
                                confirmBox("dropContent(" + id_content + "," + id_domain + ",reloadPage);","Eliminare?","body");
                                return false;
                            }
                            break;
                        }

                    }
								
                    break;
                }
                case '#ZDOMAIN_CUSTOMERGALLERY#':
                {
                    //alert("jT_6_"+code[2]);
                    obj.onclick = function() {
                        //alert("id: " + id_content + " - domain: " + id_domain);
                        confirmBox("dropContent(" + id_content + "," + id_domain + ",reloadPage);","Vuoi davvero eliminare l'immagine?","body");
                        return false;
                    }
                    //alert("in jT_6_"+code[2]+" -- "+obj.onclick);
                    break;
                }
                case '13':
                {
                    //alert("jT_6_"+code[2]);
                    obj.onclick = function() {
                        //alert("id: " + id_content + " - domain: " + id_domain);
                        confirmBox("dropContent(" + id_content + "," + id_domain + ",reloadPage);","Eliminare?", "body");
                        return false;
                    }
                    //alert("in jT_6_"+code[2]+" -- "+obj.onclick);
                    break;
                }

                case '14':
                {
                    if(postBack_code == 0){
                        obj.onclick = function() {
                            confirmBox("dropContent(" + id_content + "," + id_domain + "); reloadPage();","Cancellare?", "body");
                            return false;
                        }
                    }
                    else {
                        obj.onclick = function() {
                            //alert("id: " + id_content + " - domain: " + id_domain);
                            confirmBox("dropContent(" + id_content + "," + id_domain + "); gotoCategory("+ postBack_code +");","Vuoi Cancellare l'Attivit&agrave; selezionata?", "body");
                            return false;
                        }
                    }
                    break;
                }

                case '15':
                {
                    //alert("jT_6_"+code[2]);
                    obj.onclick = function() {
                        //alert("id: " + id_content + " - domain: " + id_domain);
                        confirmBox("dropContent(" + id_content + "," + id_domain + ", reloadPage);","Vuoi Cancellare l'Evento selezionato?", "body");
                        return false;
                    }
                    //alert("in jT_6_"+code[2]+" -- "+obj.onclick);
                    break;
                }

                case '19':
                {
                    //alert("jT_6_"+code[2]);
                    obj.onclick = function() {
                        //alert("id: " + id_content + " - domain: " + id_domain);
                        tmp = document.getElementById('body#box');
                        if(tmp) target='body#box'; else target='body';
                        confirmBox("dropContent(" + id_content + "," + id_domain + ", reloadPage);","Vuoi Cancellare la Notizia selezionata?", target);
                        return false;
                    }
                    //alert("in jT_6_"+code[2]+" -- "+obj.onclick);
                    break;
                }

                default:
                {
                    //alert("jT_6_"+code[2]);
                    obj.onclick = function() {
                        //alert("id: " + id_content + " - domain: " + id_domain);
                        confirmBox("dropContent(" + id_content + "," + id_domain + ",reloadPage);","Eliminare?","body");
                        return false;
                    }
                    //alert("in jT_6_"+code[2]+" -- "+obj.onclick);
                    break;
                }
            }
            break;
        }

        case '7':{
            obj.onclick = function() {
                confirmBox("dropContentRelation(" + id_content + "," + id_domain + ",reloadPage,"+ postBack_code + ");","Eliminare la Relazione?","body");
                return false;
            }
            break;
        }
    }
}



 /*- form_validators.js -*/ 

// MAIL
function checkFormMail(targetDiv, lang) {
	var valid = true;
        var message = "";
        var target = targetDiv ? targetDiv : 'body';

        var mailto_address = "";
        var mailto_name = "";

        var mail_contacts = "CONTATTI RICHIEDENTE<br />";
        var mail_message = "<br/><br/>MESSAGGIO RICHIEDENTE<br />";

        tmp = checkNameSyntax('mail_name');
        valid = valid && tmp;
        if(!tmp) message += "name-";
        else {
            mailto_name = getValue('mail_name');
            mail_contacts += "Nome: " + mailto_name + "<br />";
        }

// mail OR telephone
        tmp = checkMailSyntax('mail_mail');
        tel = checkTelephoneSyntax('mail_tel');
        //valid = valid && tmp;
        if(!(tmp || tel)) message += "mail-";
        if(tmp) {
            mailto_address = getValue('mail_mail');
            mail_contacts += "email: " + mailto_address + "<br />";
        }

        //if(!(tel || tmp)) message += "tel-";
        if(tel) mail_contacts += "Numero di telefono: " + getValue('mail_tel') + "<br />";

        valid = valid && (tel || tmp);
// mail OR telephone END

        tmp = isEmpty('mail_message');
        valid = valid && tmp;
        if(!tmp) message += "message-";
        else mail_message += getValue('mail_message') + "<br />";

	if(valid){
            email = mail_contacts + "-----------------------------------------------------------------" + mail_message;
           
            sendMail(email, mailto_name, mailto_address, showResponse, target);
        }
        else{
            message = message.substring(0, (message.length) - 1);
            message = formatMessage(message, lang);
            informationBox(false, false, target, message);
        }
}

function formatMessage(message, lang){
    fields = message.split('-');

    message = "";

    for(i=0; i<fields.length; i++){
        switch(fields[i]){
            case 'name':
                message += getPhrase('error_name', lang) + "<br />";
                break;

            case 'mail':
                message += getPhrase('error_mail', lang) + "<br />";
                break;

            case 'tel':
                message += getPhrase('error_tel', lang) + "<br />";
                break;

            case 'message':
                message += getPhrase('error_message', lang) + "<br />";
                break;
        }
    }

    return message;
}
// MAIL - end

// UploadWidget
function checkUploadFields(theme, target){
    var check = true;
    var tmp;
    var message = "";

    var type = document.getElementById("zctyp").value;
    if(type == "") return false;

    switch(theme){
        case 'pic_n_vid':
            switch(type){
                case "3":
                    tmp = document.getElementById("zcval");
                    if(!tmp || (tmp.value == "")) check = false;
                    message += getPhrase('error_upload_emb', 'IT') + "<br />";
                    break;

                case "2":
                    tmp = document.getElementById("file");
                    if(!tmp || (tmp.value == "")) check = false;
                    message += getPhrase('error_upload_pic', 'IT') + "<br />";
                    break;
            }
            break;
    }
    if(check) return true;

    //!check
    informationBox(message, target);
    return false;
}
// UploadWidget - end

//COCCHETTI - Evento
function checkEvento(){
    message = "";
    empty = false;

    tmp = document.getElementById("zctit");
    if(tmp)
        if(tmp.value == "") {empty = true; message = "Inserire il TITOLO dell&acute;Evento"; }

    tmp = document.getElementById("date");
    if(tmp)
        if(tmp.value == "") {empty = true; message += "<br/>Inserire la DATA dell&acute;Evento"; }

    if(empty){ informationBox(false, false, 'body#box', message, false); return false; }
    return true;
}
// end

// NEWS
function checkNewsTitle(){
	   message = "";
    empty = false;

    tmp = document.getElementById("zctit");
    if(tmp)
        if(tmp.value == "") {empty = true; message = "Inserire il TITOLO della Notizia!"; }

    if(empty){ informationBox(false, false, 'body#box', message, false); return false; }
    return true;
}
//



 /*- dictionary.js -*/ 

//recupera la frase per codice e lingua
function getPhrase(code, lang){
    switch(code + "_" + lang){
        //MonoLingua
        case 'error_upload_emb_IT': return "Inserire codice embedded.";
        case 'error_upload_pic_IT': return "Selezionare una immagine.";
        //

        case 'error_name_IT': return "Inserire nome e cognome.";
        case 'error_name_EN': return "Please insert first and last name.";
        case 'error_name_FR': return "Insérer prénom et nom.";

        case 'error_mail_IT': return "Inserire un indirizzo email o un numero di telefono validi.";
        case 'error_mail_EN': return "Please insert a valid email address or a valid telephone number.";
        case 'error_mail_FR': return "L&acute;adresse email n&acute;est pas valide.";

        case 'error_tel_IT': return "Inserire un indirizzo email o un numero di telefono validi.";
        case 'error_tel_EN': return "Please insert a valid email address or a valid telephone number.";
        case 'error_tel_FR': return "Le numéro de téléphone n&acute;est pas valide.";

        case 'error_message_IT': return "Inserire un messaggio.";
        case 'error_message_EN': return "Please insert a message.";
        case 'error_message_FR': return "Insérer un message.";
    }
}


 /*- audio/audio-player.js -*/ 

var ap_instances = new Array();

function ap_stopAll(playerID) {
	for(var i = 0;i<ap_instances.length;i++) {
		try {
			if(ap_instances[i] != playerID) document.getElementById("audioplayer" + ap_instances[i].toString()).SetVariable("closePlayer", 1);
			else document.getElementById("audioplayer" + ap_instances[i].toString()).SetVariable("closePlayer", 0);
		} catch( errorObject ) {
			// stop any errors
		}
	}
}

function ap_registerPlayers() {
	var objectID;
	var objectTags = document.getElementsByTagName("object");
	for(var i=0;i<objectTags.length;i++) {
		objectID = objectTags[i].id;
		if(objectID.indexOf("audioplayer") == 0) {
			ap_instances[i] = objectID.substring(11, objectID.length);
		}
	}
}

var ap_clearID = setInterval( ap_registerPlayers, 100 );


 /*- lightbox_jquery/jquery.lightbox-0.5.js -*/ 

/**
 * jQuery lightBox plugin
 * This jQuery plugin was inspired and based on Lightbox 2 by Lokesh Dhakar (http://www.huddletogether.com/projects/lightbox2/)
 * and adapted to me for use like a plugin from jQuery.
 * @name jquery-lightbox-0.5.js
 * @author Leandro Vieira Pinho - http://leandrovieira.com
 * @version 0.5
 * @date April 11, 2008
 * @category jQuery plugin
 * @copyright (c) 2008 Leandro Vieira Pinho (leandrovieira.com)
 * @license CC Attribution-No Derivative Works 2.5 Brazil - http://creativecommons.org/licenses/by-nd/2.5/br/deed.en_US
 * @example Visit http://leandrovieira.com/projects/jquery/lightbox/ for more informations about this jQuery plugin
 */

// Offering a Custom Alias suport - More info: http://docs.jquery.com/Plugins/Authoring#Custom_Alias
(function($) {
	/**
	 * $ is an alias to jQuery object
	 *
	 */
	$.fn.lightBox = function(settings) {
		// Settings to configure the jQuery lightBox plugin how you like
		settings = jQuery.extend({
			// Configuration related to overlay
			overlayBgColor: 		'#000',		// (string) Background color to overlay; inform a hexadecimal value like: #RRGGBB. Where RR, GG, and BB are the hexadecimal values for the red, green, and blue values of the color.
			overlayOpacity:			0.8,		// (integer) Opacity value to overlay; inform: 0.X. Where X are number from 0 to 9
			// Configuration related to navigation
			fixedNavigation:		false,		// (boolean) Boolean that informs if the navigation (next and prev button) will be fixed or not in the interface.
			// Configuration related to images
			imageLoading:			'./TORBA/js/lightbox_jquery/images/lightbox-ico-loading.gif',		// (string) Path and the name of the loading icon
			imageBtnPrev:			'./TORBA/js/lightbox_jquery/images/lightbox-btn-prev.gif',			// (string) Path and the name of the prev button image
			imageBtnNext:			'./TORBA/js/lightbox_jquery/images/lightbox-btn-next.gif',			// (string) Path and the name of the next button image
			imageBtnClose:			'./TORBA/js/lightbox_jquery/images/lightbox-btn-close.gif',		// (string) Path and the name of the close btn
			imageBlank:				'./TORBA/js/lightbox_jquery/images/lightbox-blank.gif',			// (string) Path and the name of a blank image (one pixel)
			// Configuration related to container image box
			containerBorderSize:	10,			// (integer) If you adjust the padding in the CSS for the container, #lightbox-container-image-box, you will need to update this value
			containerResizeSpeed:	400,		// (integer) Specify the resize duration of container image. These number are miliseconds. 400 is default.
			// Configuration related to texts in caption. For example: Image 2 of 8. You can alter either "Image" and "of" texts.
			txtImage:				'Image',	// (string) Specify text "Image"
			txtOf:					'of',		// (string) Specify text "of"
			// Configuration related to keyboard navigation
			keyToClose:				'c',		// (string) (c = close) Letter to close the jQuery lightBox interface. Beyond this letter, the letter X and the SCAPE key is used to.
			keyToPrev:				'p',		// (string) (p = previous) Letter to show the previous image
			keyToNext:				'n',		// (string) (n = next) Letter to show the next image.
			// Don�t alter these variables in any way
			imageArray:				[],
			activeImage:			0
		},settings);
		// Caching the jQuery object with all elements matched
		var jQueryMatchedObj = this; // This, in this context, refer to jQuery object
		/**
		 * Initializing the plugin calling the start function
		 *
		 * @return boolean false
		 */
		function _initialize() {
			_start(this,jQueryMatchedObj); // This, in this context, refer to object (link) which the user have clicked
			return false; // Avoid the browser following the link
		}
		/**
		 * Start the jQuery lightBox plugin
		 *
		 * @param object objClicked The object (link) whick the user have clicked
		 * @param object jQueryMatchedObj The jQuery object with all elements matched
		 */
		function _start(objClicked,jQueryMatchedObj) {
			// Hime some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
			$('embed, object, select').css({ 'visibility' : 'hidden' });
			// Call the function to create the markup structure; style some elements; assign events in some elements.
			_set_interface();
			// Unset total images in imageArray
			settings.imageArray.length = 0;
			// Unset image active information
			settings.activeImage = 0;
			// We have an image set? Or just an image? Let�s see it.
			if ( jQueryMatchedObj.length == 1 ) {
				settings.imageArray.push(new Array(objClicked.getAttribute('href'),objClicked.getAttribute('title')));
			} else {
				// Add an Array (as many as we have), with href and title atributes, inside the Array that storage the images references		
				for ( var i = 0; i < jQueryMatchedObj.length; i++ ) {
					settings.imageArray.push(new Array(jQueryMatchedObj[i].getAttribute('href'),jQueryMatchedObj[i].getAttribute('title')));
				}
			}
			while ( settings.imageArray[settings.activeImage][0] != objClicked.getAttribute('href') ) {
				settings.activeImage++;
			}
			// Call the function that prepares image exibition
			_set_image_to_view();
		}
		/**
		 * Create the jQuery lightBox plugin interface
		 *
		 * The HTML markup will be like that:
			<div id="jquery-overlay"></div>
			<div id="jquery-lightbox">
				<div id="lightbox-container-image-box">
					<div id="lightbox-container-image">
						<img src="../fotos/XX.jpg" id="lightbox-image">
						<div id="lightbox-nav">
							<a href="#" id="lightbox-nav-btnPrev"></a>
							<a href="#" id="lightbox-nav-btnNext"></a>
						</div>
						<div id="lightbox-loading">
							<a href="#" id="lightbox-loading-link">
								<img src="../images/lightbox-ico-loading.gif">
							</a>
						</div>
					</div>
				</div>
				<div id="lightbox-container-image-data-box">
					<div id="lightbox-container-image-data">
						<div id="lightbox-image-details">
							<span id="lightbox-image-details-caption"></span>
							<span id="lightbox-image-details-currentNumber"></span>
						</div>
						<div id="lightbox-secNav">
							<a href="#" id="lightbox-secNav-btnClose">
								<img src="../images/lightbox-btn-close.gif">
							</a>
						</div>
					</div>
				</div>
			</div>
		 *
		 */
		function _set_interface() {
			// Apply the HTML markup into body tag
			$('body').append('<div id="jquery-overlay"></div><div id="jquery-lightbox"><div id="lightbox-container-image-box"><div id="lightbox-container-image"><img id="lightbox-image"><div style="" id="lightbox-nav"><a href="#" id="lightbox-nav-btnPrev"></a><a href="#" id="lightbox-nav-btnNext"></a></div><div id="lightbox-loading"><a href="#" id="lightbox-loading-link"><img src="' + settings.imageLoading + '"></a></div></div></div><div id="lightbox-container-image-data-box"><div id="lightbox-container-image-data"><div id="lightbox-image-details"><span id="lightbox-image-details-caption"></span><span id="lightbox-image-details-currentNumber"></span></div><div id="lightbox-secNav"><a href="#" id="lightbox-secNav-btnClose"><img src="' + settings.imageBtnClose + '"></a></div></div></div></div>');	
			// Get page sizes
			var arrPageSizes = ___getPageSize();
			// Style overlay and show it
			$('#jquery-overlay').css({
				backgroundColor:	settings.overlayBgColor,
				opacity:			settings.overlayOpacity,
				width:				arrPageSizes[0],
				height:				arrPageSizes[1]
			}).fadeIn();
			// Get page scroll
			var arrPageScroll = ___getPageScroll();
			// Calculate top and left offset for the jquery-lightbox div object and show it
			$('#jquery-lightbox').css({
				top:	arrPageScroll[1] + (arrPageSizes[3] / 10),
				left:	arrPageScroll[0]
			}).show();
			// Assigning click events in elements to close overlay
			$('#jquery-overlay,#jquery-lightbox').click(function() {
				_finish();									
			});
			// Assign the _finish function to lightbox-loading-link and lightbox-secNav-btnClose objects
			$('#lightbox-loading-link,#lightbox-secNav-btnClose').click(function() {
				_finish();
				return false;
			});
			// If window was resized, calculate the new overlay dimensions
			$(window).resize(function() {
				// Get page sizes
				var arrPageSizes = ___getPageSize();
				// Style overlay and show it
				$('#jquery-overlay').css({
					width:		arrPageSizes[0],
					height:		arrPageSizes[1]
				});
				// Get page scroll
				var arrPageScroll = ___getPageScroll();
				// Calculate top and left offset for the jquery-lightbox div object and show it
				$('#jquery-lightbox').css({
					top:	arrPageScroll[1] + (arrPageSizes[3] / 10),
					left:	arrPageScroll[0]
				});
			});
		}
		/**
		 * Prepares image exibition; doing a image�s preloader to calculate it�s size
		 *
		 */
		function _set_image_to_view() { // show the loading
			// Show the loading
			$('#lightbox-loading').show();
			if ( settings.fixedNavigation ) {
				$('#lightbox-image,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide();
			} else {
				// Hide some elements
				$('#lightbox-image,#lightbox-nav,#lightbox-nav-btnPrev,#lightbox-nav-btnNext,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide();
			}
			// Image preload process
			var objImagePreloader = new Image();
			objImagePreloader.onload = function() {
				$('#lightbox-image').attr('src',settings.imageArray[settings.activeImage][0]);
				// Perfomance an effect in the image container resizing it
				_resize_container_image_box(objImagePreloader.width,objImagePreloader.height);
				//	clear onLoad, IE behaves irratically with animated gifs otherwise
				objImagePreloader.onload=function(){};
			};
			objImagePreloader.src = settings.imageArray[settings.activeImage][0];
		};
		/**
		 * Perfomance an effect in the image container resizing it
		 *
		 * @param integer intImageWidth The image�s width that will be showed
		 * @param integer intImageHeight The image�s height that will be showed
		 */
		function _resize_container_image_box(intImageWidth,intImageHeight) {
			// Get current width and height
			var intCurrentWidth = $('#lightbox-container-image-box').width();
			var intCurrentHeight = $('#lightbox-container-image-box').height();
			// Get the width and height of the selected image plus the padding
			var intWidth = (intImageWidth + (settings.containerBorderSize * 2)); // Plus the image�s width and the left and right padding value
			var intHeight = (intImageHeight + (settings.containerBorderSize * 2)); // Plus the image�s height and the left and right padding value
			// Diferences
			var intDiffW = intCurrentWidth - intWidth;
			var intDiffH = intCurrentHeight - intHeight;
			// Perfomance the effect
			$('#lightbox-container-image-box').animate({ width: intWidth, height: intHeight },settings.containerResizeSpeed,function() { _show_image(); });
			if ( ( intDiffW == 0 ) && ( intDiffH == 0 ) ) {
				if ( $.browser.msie ) {
					___pause(250);
				} else {
					___pause(100);	
				}
			} 
			$('#lightbox-container-image-data-box').css({ width: intImageWidth });
			$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({ height: intImageHeight + (settings.containerBorderSize * 2) });
		};
		/**
		 * Show the prepared image
		 *
		 */
		function _show_image() {
			$('#lightbox-loading').hide();
			$('#lightbox-image').fadeIn(function() {
				_show_image_data();
				_set_navigation();
			});
			_preload_neighbor_images();
		};
		/**
		 * Show the image information
		 *
		 */
		function _show_image_data() {
			$('#lightbox-container-image-data-box').slideDown('fast');
			$('#lightbox-image-details-caption').hide();
			if ( settings.imageArray[settings.activeImage][1] ) {
				$('#lightbox-image-details-caption').html(settings.imageArray[settings.activeImage][1]).show();
			}
			// If we have a image set, display 'Image X of X'
			if ( settings.imageArray.length > 1 ) {
				$('#lightbox-image-details-currentNumber').html(settings.txtImage + ' ' + ( settings.activeImage + 1 ) + ' ' + settings.txtOf + ' ' + settings.imageArray.length).show();
			}		
		}
		/**
		 * Display the button navigations
		 *
		 */
		function _set_navigation() {
			$('#lightbox-nav').show();

			// Instead to define this configuration in CSS file, we define here. And it�s need to IE. Just.
			$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({ 'background' : 'transparent url(' + settings.imageBlank + ') no-repeat' });
			
			// Show the prev button, if not the first image in set
			if ( settings.activeImage != 0 ) {
				if ( settings.fixedNavigation ) {
					$('#lightbox-nav-btnPrev').css({ 'background' : 'url(' + settings.imageBtnPrev + ') left 15% no-repeat' })
						.unbind()
						.bind('click',function() {
							settings.activeImage = settings.activeImage - 1;
							_set_image_to_view();
							return false;
						});
				} else {
					// Show the images button for Next buttons
					$('#lightbox-nav-btnPrev').unbind().hover(function() {
						$(this).css({ 'background' : 'url(' + settings.imageBtnPrev + ') left 15% no-repeat' });
					},function() {
						$(this).css({ 'background' : 'transparent url(' + settings.imageBlank + ') no-repeat' });
					}).show().bind('click',function() {
						settings.activeImage = settings.activeImage - 1;
						_set_image_to_view();
						return false;
					});
				}
			}
			
			// Show the next button, if not the last image in set
			if ( settings.activeImage != ( settings.imageArray.length -1 ) ) {
				if ( settings.fixedNavigation ) {
					$('#lightbox-nav-btnNext').css({ 'background' : 'url(' + settings.imageBtnNext + ') right 15% no-repeat' })
						.unbind()
						.bind('click',function() {
							settings.activeImage = settings.activeImage + 1;
							_set_image_to_view();
							return false;
						});
				} else {
					// Show the images button for Next buttons
					$('#lightbox-nav-btnNext').unbind().hover(function() {
						$(this).css({ 'background' : 'url(' + settings.imageBtnNext + ') right 15% no-repeat' });
					},function() {
						$(this).css({ 'background' : 'transparent url(' + settings.imageBlank + ') no-repeat' });
					}).show().bind('click',function() {
						settings.activeImage = settings.activeImage + 1;
						_set_image_to_view();
						return false;
					});
				}
			}
			// Enable keyboard navigation
			_enable_keyboard_navigation();
		}
		/**
		 * Enable a support to keyboard navigation
		 *
		 */
		function _enable_keyboard_navigation() {
			$(document).keydown(function(objEvent) {
				_keyboard_action(objEvent);
			});
		}
		/**
		 * Disable the support to keyboard navigation
		 *
		 */
		function _disable_keyboard_navigation() {
			$(document).unbind();
		}
		/**
		 * Perform the keyboard actions
		 *
		 */
		function _keyboard_action(objEvent) {
			// To ie
			if ( objEvent == null ) {
				keycode = event.keyCode;
				escapeKey = 27;
			// To Mozilla
			} else {
				keycode = objEvent.keyCode;
				escapeKey = objEvent.DOM_VK_ESCAPE;
			}
			// Get the key in lower case form
			key = String.fromCharCode(keycode).toLowerCase();
			// Verify the keys to close the ligthBox
			if ( ( key == settings.keyToClose ) || ( key == 'x' ) || ( keycode == escapeKey ) ) {
				_finish();
			}
			// Verify the key to show the previous image
			if ( ( key == settings.keyToPrev ) || ( keycode == 37 ) ) {
				// If we�re not showing the first image, call the previous
				if ( settings.activeImage != 0 ) {
					settings.activeImage = settings.activeImage - 1;
					_set_image_to_view();
					_disable_keyboard_navigation();
				}
			}
			// Verify the key to show the next image
			if ( ( key == settings.keyToNext ) || ( keycode == 39 ) ) {
				// If we�re not showing the last image, call the next
				if ( settings.activeImage != ( settings.imageArray.length - 1 ) ) {
					settings.activeImage = settings.activeImage + 1;
					_set_image_to_view();
					_disable_keyboard_navigation();
				}
			}
		}
		/**
		 * Preload prev and next images being showed
		 *
		 */
		function _preload_neighbor_images() {
			if ( (settings.imageArray.length -1) > settings.activeImage ) {
				objNext = new Image();
				objNext.src = settings.imageArray[settings.activeImage + 1][0];
			}
			if ( settings.activeImage > 0 ) {
				objPrev = new Image();
				objPrev.src = settings.imageArray[settings.activeImage -1][0];
			}
		}
		/**
		 * Remove jQuery lightBox plugin HTML markup
		 *
		 */
		function _finish() {
			$('#jquery-lightbox').remove();
			$('#jquery-overlay').fadeOut(function() { $('#jquery-overlay').remove(); });
			// Show some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
			$('embed, object, select').css({ 'visibility' : 'visible' });
		}
		/**
		 / THIRD FUNCTION
		 * getPageSize() by quirksmode.com
		 *
		 * @return Array Return an array with page width, height and window width, height
		 */
		function ___getPageSize() {
			var xScroll, yScroll;
			if (window.innerHeight && window.scrollMaxY) {	
				xScroll = window.innerWidth + window.scrollMaxX;
				yScroll = window.innerHeight + window.scrollMaxY;
			} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
				xScroll = document.body.scrollWidth;
				yScroll = document.body.scrollHeight;
			} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
				xScroll = document.body.offsetWidth;
				yScroll = document.body.offsetHeight;
			}
			var windowWidth, windowHeight;
			if (self.innerHeight) {	// all except Explorer
				if(document.documentElement.clientWidth){
					windowWidth = document.documentElement.clientWidth; 
				} else {
					windowWidth = self.innerWidth;
				}
				windowHeight = self.innerHeight;
			} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
				windowWidth = document.documentElement.clientWidth;
				windowHeight = document.documentElement.clientHeight;
			} else if (document.body) { // other Explorers
				windowWidth = document.body.clientWidth;
				windowHeight = document.body.clientHeight;
			}	
			// for small pages with total height less then height of the viewport
			if(yScroll < windowHeight){
				pageHeight = windowHeight;
			} else { 
				pageHeight = yScroll;
			}
			// for small pages with total width less then width of the viewport
			if(xScroll < windowWidth){	
				pageWidth = xScroll;		
			} else {
				pageWidth = windowWidth;
			}
			arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
			return arrayPageSize;
		};
		/**
		 / THIRD FUNCTION
		 * getPageScroll() by quirksmode.com
		 *
		 * @return Array Return an array with x,y page scroll values.
		 */
		function ___getPageScroll() {
			var xScroll, yScroll;
			if (self.pageYOffset) {
				yScroll = self.pageYOffset;
				xScroll = self.pageXOffset;
			} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
				yScroll = document.documentElement.scrollTop;
				xScroll = document.documentElement.scrollLeft;
			} else if (document.body) {// all other Explorers
				yScroll = document.body.scrollTop;
				xScroll = document.body.scrollLeft;	
			}
			arrayPageScroll = new Array(xScroll,yScroll);
			return arrayPageScroll;
		};
		 /**
		  * Stop the code execution from a escified time in milisecond
		  *
		  */
		 function ___pause(ms) {
			var date = new Date(); 
			curDate = null;
			do { var curDate = new Date(); }
			while ( curDate - date < ms);
		 };
		// Return the jQuery object for chaining. The unbind method is used to avoid click conflict when the plugin is called more than once
		return this.unbind('click').click(_initialize);
	};
})(jQuery); // Call and execute the function immediately passing the jQuery object


 /*- custom_functions.js -*/ 

// SONDAGGIO
var options_count = 0;

function appendOption() {
	if(options_count < 4){
	options_count++;

	html = "<div id ='div_option_" + options_count + "'>";
	html += "Opzione ";
	if(options_count < 10) html += "0";
	html += options_count + ": ";
	html += "<input id='zctit_" + options_count + "' type='text'style='width:522px;' maxlength='85' />";
	html += "</div>";

	$("#question_div").append(html);
	}
}
function saveSurvey(formId){
	var uri = "./TORBA/custom/Common/SurveySave.php?";
	uri += "&options_count=" + options_count;
	
	var callback = function(id, response) {
		reloadPage();
	}

	var values = getFormValues(formId);

	ajaxPost(false, uri, values, callback);
}

/*
function saveSurvey(relation_id, domainId, answer_type){
	//POST question
	question = $("#question").val();
	
	//SET question TITLE
	tmp = document.getElementById("zctit").value = question;

	postContent('form_0', domainId, leavePostedId, false, false, false, false, false, true);

	//SET relation INFOs for OPTIONS
	document.getElementById("zcrty").value = relation_id;
	document.getElementById("zctyp").value = answer_type;
	
	document.getElementById("zcfor").value;
	
	//POST answers
	var real_count = 1;
	var delay=0;
		
	for(var i = 1; i <= options_count; i++){		
		option = $("#option_" + i).val();

		if(trim(option) == "") continue;

		document.getElementById("zctit").value = option;

		postContent('form_0', domainId, false, false, false, false, false, false, true);

		real_count++;
	}

	//reloadPage();
}
*/

function publishSurvey(domainId, old){
	var select_question = document.getElementById("select_question");

	var new_survey = select_question.options[select_question.selectedIndex].value;

	//archive OLD
	//if(old) setContentState(old, domainId, 3);

	ids = old + "-" + new_survey;

	//publish NEW
	setContentState(ids, domainId, 2, reloadPage)
}

function surveyVote(option, domainId){
	var uri = "./TORBA/custom/Common/SurveyVote.php?";
	uri += "&zcid=" + option;

	var callback = function(id, response) {
		closeBox('survey#box');
		informationBox(false, domainId, 'body', response);
	}

	ajaxGet(false, uri, callback);
}

function surveyView(survey, targetDiv){
	var uri = "./TORBA/custom/Common/SurveyView.php?";
	uri += "zcid=" + survey;
	if(!targetDiv) targetDiv = 'body';

	uri += "&targetDiv=" + encodeURIComponent(targetDiv);

	var callback = function(id, response) {
		var obj = document.getElementById(id);

		var box = openBox2(obj, response, 'informationBox');

		setBoxPosition(box, "fixed", calculateWindowY(getHeight(box), 0.4), calculateWindowX(getWidth(box), 0.5));
      //setBoxPosition(box, "fixed", 200, calculateWindowX(getWidth(box), 0.5));
		run_animation();
	}

	ajaxGet(targetDiv, uri, callback);
}

// END - SONDAGGIO

// NEWSLETTER - !CANDIDATE TO BE OFFICIAL!
function formatMail(formId, confirmation, domainId, target, skip_sync, send){
	/* sync textareas! */
  if(!skip_sync) if(document.getElementById(formId)) tinyMCE.triggerSave();

	var uri = "./TORBA/custom/Common/ConfirmBox.php?";
	uri += "zdid=" + domainId;
	uri += "&confirmation=" + encodeURIComponent(confirmation);
	uri += "&targetDiv=" + target;
	if(send) uri += "&send=" + send;
		
	var callback = function(id, response){
		var obj = document.getElementById(id);
		
		var box = openBox2(obj, response, 'confirmBox');

		//setBoxPosition(box, "fixed", calculateWindowY(box.clientHeight, 0.5), calculateWindowX(box.clientWidth, 0.5));
		setBoxPosition(box, "fixed", 250, calculateWindowX(box.clientWidth, 0.5));
	}

	var values = getFormValues(formId);

	ajaxPost(target, uri, values, callback);
}

function loadEdit(targetDiv, contentId, domainId, editorFree) {
	var uri = "./TORBA/custom/Common/EditContent.php?";
	uri += "zdid=" + domainId;
	uri += "&targetDiv=" + encodeURIComponent(targetDiv);
	uri += "&zcid=" + contentId;

	var callback = function(id, response) {
		var obj = document.getElementById(targetDiv);
		obj.innerHTML = response;

		jTorbalizeMe();

        if(!editorFree) loadEditor();
		
		$("#toolbox").html("Creazione nuova Newsletter");
	}

	ajaxGet(targetDiv, uri, callback);		
}

function dropMailEntry(){
        
	var uri = "./TORBA/custom/Newsletter/DropMailEntry.php?";
	uri += "&zcid=" + $('#mail_to_drop').val();

	var callback = function(id, response) {
		   $('#response_div').html("<span style='color:green'>" + response + "</span>");
	}

	ajaxGet(false, uri, callback);
}

function loadMailForm(targetDiv, domainId){
        
	var uri = "./TORBA/custom/Common/MailForm.php?";
	if(domainId) uri += "&zdid=" + domainId;
	uri += "&targetDiv=" + targetDiv;

	var callback = function(id, response) {
		var obj = document.getElementById(id);

		var box = openBox2(obj, response, 'mailForm');

		setBoxPosition(box, "fixed", calculateWindowY(getHeight(box), 0.5), calculateWindowX(getWidth(box), 0.5));
	}

	ajaxGet(targetDiv, uri, callback);
}

var sends = 0;
var done = false;

function sendMail(form, target, domainId, postBack){
	var uri = "./TORBA/custom/Common/SendMail.php?";
	uri += "zdid=" + domainId;
	
	var callback = function(id, response){
		sends++;
		
		done = parseInt(response);
		
		if(done != 0) $('div#send_message').html("<b>Mail inviate: "+response+"</b>");
		else $('div#send_message').html("<b>INVIO COMPLETATO!</b>");
	
		
		/* LIMITE A 5000 INVII, mettere (sends < xxx) per regolarlo - "1 sends" = "10 invii"!*/
		if((done != 0)&&(sends < 510)) sendMail(form, target, domainId, postBack);
		else postBack(id, '@nnuncia inviata con successo!', 'none', domainId, target);
	}
	
	var values = getFormValues(form);
	
	ajaxPost(target, uri, values, callback);	
}
// END - NEWSLETTER


// JavaScript Document

function domainAction(formId, domainId, actionId, postBack){
	var uri = "./TORBA/custom/Common/DomainAction.php?";
	uri += "&zdid=" + domainId;

	var callback = function(id, response) {
		if(postBack) postBack(id, response, 'none', domainId);
	}

	var values = getFormValues(formId);

    ajaxPost(false, uri, values, callback);
}

// GUI
function loadEmbeddedBox(embeddedId, domainId, targetDiv){
	var uri = "./TORBA/custom/Common/EmbeddedBox.php?";
	uri += "zcid=" + embeddedId;
	uri += "&zdid=" + domainId;
	uri += "&targetDiv=" + targetDiv;

	var callback = function(id, response) {
		var obj = document.getElementById(id);
		
		var box = openBox2(obj, response, 'embeddedBox');
		
		setBoxPosition(box, "fixed", calculateWindowY(box.clientHeight, 0.45), calculateWindowX(box.clientWidth, 0.675));
	}

	ajaxGet(targetDiv, uri, callback);	
}

function loadUploadWidget(id_content_foreign, id_content_relation, id_domain, id_node, targetDiv, theme, postBack_profile){
	var uri = "./TORBA/custom/Common/LoadUploadWidget.php?";
	uri += "zcfor=" + id_content_foreign;
	uri += "&zcrty=" + id_content_relation;
	uri += "&zdid=" + id_domain;
	uri += "&zcrno=" + id_node;

	uri += "&targetDiv=" + targetDiv;
	uri += "&theme=" + theme;
	if(postBack_profile) uri += "&postBack_profile=" + postBack_profile;
	
	/*if(postBack) uri += "&postBack=" + postBack;*/

	var callback = function(id, response) {

		var obj = document.getElementById(id);
		
		var box = openBox2(obj, response, 'generalBox');
		
		setBoxPosition(box, "fixed", calculateWindowY(getHeight(box), 0.3), calculateWindowX(getWidth(box), 0.5));

	}

	ajaxGet(targetDiv, uri, callback);	
}

function confirmBox(confirmation, message, targetDiv, style){
	var uri = "./TORBA/custom/Common/ConfirmBox.php?";
	uri += "confirmation=" + encodeURIComponent(confirmation);
	uri += "&message=" + encodeURIComponent(message);
	
	if(!targetDiv) targetDiv = 'body';
	if(!style) style = 'confirmBox';
		
	uri += "&targetDiv=" + encodeURIComponent(targetDiv);
	
	var callback = function(id, response) {
		var obj = document.getElementById(id);
		
		var box = openBox2(obj, response, style);

		//setBoxPosition(box, "fixed", calculateWindowY(box.clientHeight, 0.5), calculateWindowX(box.clientWidth, 0.5));
		if(style == 'survey_popup') setBoxPosition(box, "absolute", -1, 0);
		else setBoxPosition(box, "fixed", 250, calculateWindowX(box.clientWidth, 0.5));
	}

	ajaxGet(targetDiv, uri, callback);	
}

function informationBox(contentId, domainId, targetDiv, message, postBack, style, no_position, position_type){
	if(!style) style = 'informationBox';

	var uri = "./TORBA/custom/Common/InformationBox.php?";
	uri += "zcid=" + contentId;
	uri += "&zdid=" + domainId;
        uri += "&message=" + encodeURIComponent(message);
        if(postBack) uri += "&postBack=" + postBack;

	if(!targetDiv) targetDiv = 'body';

	uri += "&targetDiv=" + encodeURIComponent(targetDiv);

	var callback = function(id, response) {
		var obj = document.getElementById(id);

		var box = openBox2(obj, response, style);

		if(!no_position) { 
                    if(!position_type) position_type = 'fixed';
                    setBoxPosition(box, position_type, calculateWindowY(getHeight(box), 0.4), calculateWindowX(getWidth(box), 0.5));
                }
                //setBoxPosition(box, "fixed", 200, calculateWindowX(getWidth(box), 0.5));
		jTorbalizeMe();
	}

	ajaxGet(targetDiv, uri, callback);
}

function contenitorBox(targetDiv, contentId, domainId, styleClass, page) {
	var uri = "./TORBA/custom/Common/ContenitorBox.php?";
	if(contentId)	uri += "zcfor=" + contentId;
	uri += "&zdid=" + domainId;
	
	if(!page) page = 1;
	uri += "&zcpag=" + page;
        uri += "&targetDiv=" + targetDiv;
	
	var callback = function(id, response) {
		var obj = document.getElementById(id);
		
		var box = openBox2(obj, response, styleClass);

		setBoxPosition(box, "fixed", calculateWindowY(getHeight(box), 0.4), calculateWindowX(getWidth(box), 0.425));
		
		jTorbalizeMe();
	}

	ajaxGet(targetDiv, uri, callback);
}

// SET&GET
//formatta una serie di "id_content".checked in "id_content-id_content-id_content"
function formatSelectedFields(id_form, id_target){
    form = document.getElementById(id_form);

    string = "";
    for(i=0; i<form.id_content.length; i++){
        if(form.id_content[i].checked) string += form.id_content[i].value + "-";
    }
    string = string.substring(0, (string.length - 1));
    
    target = document.getElementById(id_target);

    target.value = string;
}

function setContenitorValue(id_contenitor, id_domain, value, postBack){
	var uri = "./TORBA/custom/Common/SetContenitorValue.php?";
	uri += "zcid=" + id_contenitor;
	uri += "&zdid=" + id_domain;
	uri += "&zcval=" + encodeURIComponent(value);
	
	uri += "&zcact=zcpost";
	uri += "&zcexe=go";

	var callback = function(id, response) {
		if(postBack) postBack(id, response);
	}

	ajaxGet(false, uri, callback);		
}

function changeFieldValue(fieldId, value){
	document.getElementById(fieldId).value = value;
}

function setContentState(contentId, domainId, stateId, postBack) {
	var action;

	switch(stateId)
	{
		case 1:{
			action = "zcdft";
			break;
		}
		case 2:{
			action = "zcpub";
			break;
		}
		case 3:{
			action = "zcarc";
			break;
		}
	}

	var uri = "./TORBA/custom/Common/SetContentState.php?";
	uri += "zdid=" + domainId;
	uri += "&zcid=" + contentId;

	uri += "&zcact=" + action;
	uri += "&zcexe=go";

	var callback = function(id, response){
            postBack(id, response, false, domainId);
            
	}

	ajaxGet(false, uri, callback);	
}

function getLangInput(id, lang){
     var tmp_id = id + '_' + lang;

     if(document.getElementById(tmp_id))
        return trim(document.getElementById(tmp_id).value) + ".EasyDelimiter.";

    return false;

}

// CONTENT ACTIONS
function dropContentRelation(contentId, domainId, postBack, foreignId){
    	var uri = "./TORBA/custom/Common/DropContent.php?";
	uri += "zdid=" + domainId;
	uri += "&zcid=" + contentId;
        uri += "&zcfor=" + foreignId;

	uri += "&zcact=zcdrel";
	uri += "&zcexe=go";

	var callback = function(id, response){
		if(postBack) postBack(id, response, 'none', domainId, foreignId);
	}
	ajaxGet(false, uri, callback);
}

function dropContent(contentId, domainId, postBack, foreignId) {

	var uri = "./TORBA/custom/Common/DropContent.php?";
	uri += "zdid=" + domainId;
	uri += "&zcid=" + contentId;

	uri += "&zcact=zcdrop";
	uri += "&zcexe=go";
	
	var callback = function(id, response){            
            if(postBack) postBack(id, response, 'none', domainId, foreignId);
	}

	ajaxGet(false, uri, callback);	
}

function postContent(formId, domainId, postBack, action, supported_langs, contentType, state, value) {
        //sync nicEdit textareas!
        
        if(document.getElementById(formId)) syncTextareas(supported_langs);
        
        //if(document.getElementById(formId)) document.getElementById(formId).submit();

        if(supported_langs){
            var title = "";
            var subtitle = "";
            var text = "";
            var abs = "";
            var langs = supported_langs.split("-");

            for(i = 0; i < langs.length; i++){
                title +=        getLangInput('zctit', langs[i]);
                subtitle +=     getLangInput('zcsub', langs[i]);
                text +=         getLangInput('zctxt', langs[i]);
                abs +=          getLangInput('zcabs', langs[i]);
            }
            
            title = title.substring(0, (title.length) - 15);
            //title = encodeURIComponent(title);
            tmp = document.getElementById('zctit');
            if(tmp) tmp.value = title;

            subtitle = subtitle.substring(0, (subtitle.length) - 15);
            //subtitle = encodeURIComponent(subtitle);
            tmp = document.getElementById('zcsub');
            if(tmp) tmp.value = subtitle;

            text = text.substring(0, (text.length) - 15);
            //text = encodeURIComponent(text);
            tmp = document.getElementById('zctxt');
            if(tmp) tmp.value = text;
            
            abs = abs.substring(0, (abs.length) - 15);
            //abs = encodeURIComponent(abs);
            tmp = document.getElementById('zcabs');
            if(tmp) tmp.value = abs;
        }

	var uri = "./TORBA/custom/Common/PostContent.php?";
	uri += "zdid=" + domainId;

        if(contentType) uri += "&zctyp=" + contentType;
        if(state) uri += "&zcsta=" + state;

	if(action) uri += "&zcact=" + action;
        else uri += "&zcact=zcpost";
        
	uri += "&zcexe=go";

	var callback = function(id, response){
		if(postBack) postBack(id, response, formId, domainId, value);
	}

        var values = getFormValues(formId);

        ajaxPost(false, uri, values, callback);
}

function editContentRelations(targetDiv, contentId, domainId, styleClass, value, postBack) {
	var uri = "./TORBA/custom/Common/EditContentRelations.php?";
	uri += "zdid=" + domainId;
	uri += "&targetDiv=" + encodeURIComponent(targetDiv);

	if(contentId)	uri += "&zcid=" + contentId;
	if(value) 	uri += "&zcval=" + value;
	if(postBack) 	uri += "&postBack=" + postBack;

	var callback = function(id, response) {
		var obj = document.getElementById(targetDiv);
		var box = openBox2(obj, response, styleClass);
		
		setBoxPosition(box, "fixed", calculateWindowY(box.clientHeight, 0.45), calculateWindowX(box.clientWidth, 0.5));

		jTorbalizeMe();                
	}

	ajaxGet(targetDiv, uri, callback);
}

function editContent(targetDiv, contentId, domainId, styleClass, value, contentType, postBack, editorFree, foreign) {
	var uri = "./TORBA/custom/Common/EditContent.php?";
	uri += "zdid=" + domainId;
	uri += "&targetDiv=" + encodeURIComponent(targetDiv);

	if(contentId)	uri += "&zcid=" + contentId;
	if(contentType)	uri += "&zctyp=" + contentType;
	if(value) 		uri += "&zcval=" + value;
	if(postBack) 	uri += "&postBack=" + postBack;
        if(foreign)     uri += "&zcfor=" + foreign;
        
	var callback = function(id, response) {
		var obj = document.getElementById(targetDiv);
		var box = openBox2(obj, response, styleClass);
		
		//setBoxPosition(box, "fixed", calculateWindowY(box.clientHeight, 0.5), calculateWindowX(box.clientWidth, 0.5));
                setBoxPosition(box, "fixed", 20, calculateWindowX(getWidth(box), 0.5));
                
                //alert("BoxHeight: " + box.clientHeight + "BoxWidth: " + box.clientWidth + ", Y: " + calculateWindowY(box.clientHeight, 0.45) + ", X: " + calculateWindowX(box.clientWidth, 0.5));
		jTorbalizeMe();

                if(!editorFree) loadEditor();

                if(postBack) postBack(id, response);
	}

	ajaxGet(targetDiv, uri, callback);		
}

//sincronizza le textarea nicEdit di un content con quelle html
function syncTextareas(langs){
    if(langs){
         lang = langs.split("-");
         var tmp = false;
         for(i = 0; i < lang.length; i++){
               switch(editorToUse){
                   case 'nicedit':  id = 'zcsub_' + lang[i];
                                    tmp = nicEditors.findEditor(id);
                                    if(tmp) tmp.saveContent();
                                    tmp = false;

                                    id = 'zctxt_' + lang[i];
                                    tmp = nicEditors.findEditor(id);
                                    if(tmp) tmp.saveContent();
                                    tmp = false;

                                    id = 'zcabs_' + lang[i];
                                    tmp = nicEditors.findEditor(id);
                                    if(tmp) tmp.saveContent();
                                    tmp = false;
                                    break;

                    case 'tiny_mce': tinyMCE.triggerSave();
                                     break;
               }
        }
    }
    else
        {
            switch(editorToUse){
                   case 'nicedit':  var text = nicEditors.findEditor('zctxt');
                                    if(text) text.saveContent();

                                    var abs = nicEditors.findEditor('zcabs');
                                    if(abs) abs.saveContent();

                                    var subtitle = nicEditors.findEditor('zcsub');
                                    if(subtitle) subtitle.saveContent();
                                    break;
                                    
                   case 'tiny_mce': tinyMCE.triggerSave();
                                    break;
            }
        }
}
// SHOW & HIDE \\
function showElement(id) {
	var obj = document.getElementById(id);
	
	if(obj) {
		//obj.style.display="block";
                obj.style.visibility = 'visible';
	}
}
function hideElement(id) {
	var obj = document.getElementById(id);
	
	if(obj)
		//obj.style.display="none";
                obj.style.visibility = 'hidden';
}
function showOrHide(id) {
	var obj = document.getElementById(id);
	
	if(obj.style.display == "block")
		hide(id);
	else
		show(id);	
}

/// MOUSE \\
function mouseX(e) {
	if(document.all)e = event;
	var vDoc=(document.documentElement && document.documentElement.scrollTop)?document.documentElement:document.body;
	var mouseX=(e.pageX)?e.pageX:e.clientX+vDoc.scrollLeft;	
	
	return mouseX;
}

function mouseY(e) {
	if(document.all)e = event;
	var vDoc=(document.documentElement && document.documentElement.scrollTop)?document.documentElement:document.body;
	var mouseY=(e.pageY)?e.pageY:e.clientY+vDoc.scrollTop;
	
	return mouseY;
}

// BOX \\
function getWidth(box){
	if(box.clientWidth != 0) return box.clientWidth;
	return box.offsetWidth;s
}

function getHeight(box){
	if(box.clientHeight != 0)return box.clientHeight;
	return box.offsetHeight;
}

function calculateWindowY(boxHeight, index){
	var height = document.documentElement.clientHeight;

	if(index) height = height*index;
	if(boxHeight) boxHeight = boxHeight/2; else boxHeight = 0;
	
	return Math.round(height - boxHeight);
}

function calculateWindowX(boxWidth, index){
	var width = document.body.clientWidth;

	if(index) width = width*index;
	if(boxWidth) boxWidth = boxWidth/2; else boxWidth = 0;

	return Math.round(width - boxWidth);
}

function setBoxPosition(obj, position, top, left){
	if(top)	obj.style.top = top + "px";
	if(left)obj.style.left = left + "px";

	obj.style.position = position;
}

function openBox(id, content, boxClass, tag) {
	obj = document.getElementById(id);
	
	if(!tag)
		tag = 'div';
	
	if(obj) {
		var boxId = id+'Box';
		var box = document.getElementById(boxId);		

		if(!box) {
			box = document.createElement(tag);
			box.id = boxId;
			box.className = boxClass;
			
			obj.appendChild(box);
		}
		
		box.innerHTML = content;
		return true;
	} else {
		return false;
	}
}
function openBox2(parent, content, boxClass, tag, before) {
	if(typeof(parent) != 'object') return false;	
	if(!tag) tag = 'div';
	
	box = document.createElement(tag);
	
	if(parent.id) box.id = parent.id+'#box';
	box.className = boxClass;		
	box.innerHTML = content;	
	
	if(parent.hasChildNodes())
		for(var i=0; i < parent.childNodes.length; i++) {
			if(parent.childNodes[i].className == boxClass) {
				parent.childNodes[i].innerHTML = content;
				return parent.childNodes[i];
			}
		}

	if(before) {
		before = document.getElementById(before);
		parent.insertBefore(box, before);
	} else
		parent.appendChild(box);	

	return box;
}

function closeBox(id) {	
	box = document.getElementById(id);	
	
	if(box) {
		box.parentNode.removeChild(box);
		return true;
	} else {
		return false;
	}
}

// SET & GET \\
function setValue(id, value) {
	var obj = document.getElementById(id);
	
	if(obj)
		obj.value = value;
}
function getValue(id) {
	var obj = document.getElementById(id);
	
	if(obj)
		return obj.value;
	else
		return false;
}
function setHtml(id, html) {
	var obj = document.getElementById(id);
	
	if(obj)
		obj.innerHTML = html;
}
function getHtml(id) {
	var obj = document.getElementById(id);
	
	if(obj)
		return obj.innerHTML;
	else
		return false;
}

// AJAX \\

var oXmlHttp = null;

function ajaxGet(id, uri, callback) {
	if(!oXmlHttp)		
		oXmlHttp = zXmlHttp.createRequest();
	else if(oXmlHttp.readyState != 0)
		oXmlHttp.abort();

	oXmlHttp.open("get", uri, true);	
	
	oXmlHttp.onreadystatechange = function() {			
		if(oXmlHttp.readyState == 4) {
			if(oXmlHttp.status == 200) {
				var response = oXmlHttp.responseText;				

				if(callback)
					callback(id, response);
			}
		}
	}	
	
	oXmlHttp.send(null);	
}

function ajaxPost(id, uri, values, callback, xml) {
	var async = true;
	
	if(!callback || callback == 'undefined')
		async = false;
		
	
	if(!oXmlHttp)		
		oXmlHttp = zXmlHttp.createRequest();
	else if(oXmlHttp.readyState != 0)
		oXmlHttp.abort();
		
	oXmlHttp.open("post", uri, async);		
	oXmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	
	if(callback) {
		oXmlHttp.onreadystatechange = function() {			
			if(oXmlHttp.readyState == 4) {
				if(oXmlHttp.status == 200) {
					if(xml)											
						callback(id, oXmlHttp.responseXML);					
					else
						callback(id, oXmlHttp.responseText);										
				} else {
					alert("impossibile contattare il server: "+uri);
				}
			}
		}	
	}
	
	var query = new Array ();
	for (var name in values) {
		query.push(name+"="+encodeURIComponent(values[name]));
	};
		
	oXmlHttp.send(query.join("&"));	
	
	if(!async) {
		if(xml)
			return oXmlHttp.responseXML;		
		else
			return oXmlHttp.responseText;
	}
}

function getFormValues(formId) {
	var form = document.getElementById(formId);

	if(form) {
		var values = new Array(form.elements.length);
		
		for(var i=0; i < form.elements.length; i++){
			values[form.elements[i].id] = form.elements[i].value;
		}	
		
		return values;
	} else
		return false;
}

function messageBox(id, script, className, left, top, owner) {
	if(!owner)
		var owner = document.getElementsByTagName('body')[0];

	var callback = function(id, response) {
		var box = document.getElementById(id);

		if(!box) {
			box = document.createElement('div');
			box.id = id;
			owner.appendChild(box);					
		}
			
		box.className = className;		
		box.innerHTML = response;	
		box.style.position = "absolute";

		if(left) box.style.left = left+'px';
		if(top) box.style.top = top+'px';
		
		loadTinyMce();
	}	

	ajaxGet(id, script, callback);
}

function loadEditor(){
    //textareas = nicEditors.allTextAreas();
    switch(editorToUse){
        case 'nicedit': nicEditors.allTextAreas({buttonList : ['bold','italic','link','unlink'], maxHeight : 300});
                        break;

        case 'tiny_mce':$('textarea').tinymce({
                            script_url : 'TORBA/js/tiny_mce/tiny_mce.js',
                            
                            mode : "exact",
                            elements : "fulltext",
                            language : 'it',
                            theme_advanced_buttons1 : ",newdocument,|,cut,copy,paste,pastetext,pasteword,|,undo,redo,|,search,replace,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,",
                            theme_advanced_buttons2 : "bullist,numlist,|,outdent,indent,blockquote,|,table,|,hr,removeformat,visualaid,|,link,unlink,anchor,image,media,|,cleanup,code",
                            theme_advanced_buttons3 : "",
                            theme_advanced_toolbar_location : "top",
                            theme_advanced_toolbar_align : "left",
                            plugins: "advlink,safari,table,paste,searchreplace,wordcount,fullscreen,insertdatetime,preview,media,save",
                            theme_advanced_blockformats : "h1,h2,h3,blockquote",
                            skin : "o2k7",
                            //content_css : "./Styles/TextStyle.css",
                            theme : "advanced"
                        });
                        break;
    }

}/* useful functions */
function getValue(id){
    var obj = document.getElementById(id);

    if(obj) return obj.value;

    return false;
}

function trim(string){
     while (string.substring(0,1) == ' '){
        string = string.substring(1, string.length);
    }
    while (string.substring(string.length-1, string.length) == ' '){
        string = string.substring(0,string.length-1);
    }
    return string;
}

//controlla mail nel formato "xxxx@xxxx.xxx"
function checkMailSyntax(id) {
    var email = document.getElementById(id);
    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if (!filter.test(email.value)) return false;
    return true;
}

//controlla:
//. se vi è almeno uno spazio all'interno della string
function checkNameSyntax(id) {
    var name = trim(document.getElementById(id).value);
    if(name.indexOf(" ") != -1) return true;
    return false;

}

//controlla numeri di telefono nel formato "1234567890"
function checkTelephoneSyntax(id) {
    var tel = document.getElementById(id);
    var filter = /^([0-9])+$/;
    if (!filter.test(tel.value)) return false;

    return true;
}

//controlla se un campo è vuoto
function isEmpty(id){
    var field = document.getElementById(id);

    if (field == null || field.value == "") return false;

    return true;
}

//unisce i campi DATA e ORA nel campo indicato
function mergeDateTime(id, lang){
   
    var year, month, day, hours, minutes;
    
    field = document.getElementById(id);

    //date[2] = YYYY, date[1] = MM, date[0] = dd
    tmp = document.getElementById("date");
    if(tmp){
        date    = tmp.value.split(" ");
        year    = date[2];
        month   = parseMonth(date[1], lang);
        if(month < 10) month = "0" + month;

        day     = date[0];
    }

    tmp = document.getElementById("time_hour");
    if(tmp) hours   = tmp.value;

    tmp = document.getElementById("time_minutes");
    if(tmp) minutes = tmp.value;

    //formato MySql "2009-09-23 16:19:10"
    field.value = formatDatetime(year, month, day, hours, minutes);

    //alert("--> " + document.getElementById(id).value);
}

function formatDatetime(year, month, day, hours, minutes, seconds){
    if(!year)       year    = "0000";
    if(!month)      month   = "00";
    if(!day)        day     = "00";
    if(!hours)      hours   = "00";
    if(!minutes)    minutes = "00";
    if(!seconds)    seconds = "00";
    
    return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
}

function parseMonth(month, lang){
    month = month.toLowerCase();

    month_it = new Array("gennaio","febbraio","marzo","aprile","maggio","giugno","luglio","agosto","settembre","ottobre","novembre","dicembre");

    month_to_use = new Array();

    switch(lang){
        case "IT":  month_to_use = month_to_use.concat(month_it);
                    break;
    }


    for(i = 0; i <= month_to_use.length; i++){
        if(month_to_use[i] == month) break;
    }
    
    return (i + 1);
}

//se la checkbox è selezionata abilità l'evidenzia del content
//(es. gestione news "in evidenzia" in homepage
function checkUnderlineSelection(id){
    var field = document.getElementById(id);

    if(!field.checked) field.value = "not_underlined";
}// JavaScript Document

function startUpload(langs, theme, target){
        document.getElementById('loading').style.visibility = 'visible';

        setDefaultFields(langs);
        if(!checkUploadFields(theme, target)){
            document.getElementById('loading').style.visibility = 'hidden';
            return false;
        }
        
    	return true;
}
function stopUpload(message){
		if(document.getElementById('result') != null){
				document.getElementById('result').innerHTML = message;
				document.getElementById('result').style.visibility = 'visible';
		}
	    if(document.getElementById('loading') != null) document.getElementById('loading').style.visibility = 'hidden';
		closeFileDiv();
		if(document.getElementById('file') != null) document.getElementById('file').value = '';
}

function selectType(typeId){
	document.getElementById('uploadForm').zctyp.value = typeId;
	
	switch(typeId)
	{
		case 2: {
			if(document.getElementById('fileLabel') != null) document.getElementById('fileLabel').innerHTML = "Seleziona immagine &raquo;";
			if(document.getElementById('fileDiv') != null)   document.getElementById('fileDiv').style.visibility = 'visible';
			if(document.getElementById('uriDiv') != null)    document.getElementById('uriDiv').style.visibility = 'hidden';
			break;
			}
		case 4: {
			if(document.getElementById('fileLabel') != null) document.getElementById('fileLabel').innerHTML = "File &raquo;";
			if(document.getElementById('fileDiv') != null)   document.getElementById('fileDiv').style.visibility = 'visible';
			if(document.getElementById('uriDiv') != null)    document.getElementById('uriDiv').style.visibility = 'hidden';
			break;
			}
		case 5: {
			if(document.getElementById('fileLabel') != null) document.getElementById('fileLabel').innerHTML = "URL &raquo;";
			if(document.getElementById('fileDiv') != null)   document.getElementById('fileDiv').style.visibility = 'hidden';
			if(document.getElementById('uriDiv') != null)    document.getElementById('uriDiv').style.visibility = 'visible';
			break;
			}
		case 3: {
			if(document.getElementById('fileLabel') != null) document.getElementById('fileLabel').innerHTML = "Inserisci Embedded Code &raquo;";
			if(document.getElementById('fileDiv') != null)   document.getElementById('fileDiv').style.visibility = 'hidden';
			if(document.getElementById('uriDiv') != null)    document.getElementById('uriDiv').style.visibility = 'visible';
			break;
			}
	}
	openFileDiv();
}

function closeFileDiv(){
	if(document.getElementById('fileDiv') != null) 		document.getElementById('fileDiv').style.visibility = 'hidden';
	if(document.getElementById('uriDiv') != null) 		document.getElementById('uriDiv').style.visibility = 'hidden';
	if(document.getElementById('uploadButton') != null)     document.getElementById('uploadButton').style.visibility = 'hidden';
	if(document.getElementById('closeMe') != null) 		document.getElementById('closeMe').style.visibility = 'hidden';
	if(document.getElementById('fileLabel') != null) 	document.getElementById('fileLabel').style.visibility = 'hidden';
	if(document.getElementById('typesDiv') != null) 	document.getElementById('typesDiv').style.visibility = 'visible';
}

function openFileDiv(){
	if(document.getElementById('uploadButton') != null)     document.getElementById('uploadButton').style.visibility = 'visible';
	if(document.getElementById('closeMe') != null) 		document.getElementById('closeMe').style.visibility = 'visible';
	if(document.getElementById('fileLabel') != null) 	document.getElementById('fileLabel').style.visibility = 'visible';
	if(document.getElementById('typesDiv') != null) 	document.getElementById('typesDiv').style.visibility = 'hidden';
}

function setDefaultFields(supported_langs){
    var langs = supported_langs.split("-");
    var title = "";
    var subtitle = "";
    var text = "";
    var abs = "";

    for(i = 0; i < langs.length; i++){
        title +=        getLangInput('zctit_upload', langs[i]);
        subtitle +=     getLangInput('zcsub_upload', langs[i]);
        text +=         getLangInput('zctxt_upload', langs[i]);
        abs +=          getLangInput('zcabs_upload', langs[i]);
    }

    if(document.getElementById('zctit_upload') && title)
        document.getElementById('zctit_upload').value = title.substring(0, (title.length) - 15);

    if(document.getElementById('zcsub_upload') && subtitle)
        document.getElementById('zcsub_upload').value = subtitle.substring(0, (subtitle.length) - 15);

    if(document.getElementById('zctxt_upload') && text)
        document.getElementById('zctxt_upload').value = text.substring(0, (text.length) - 15);

    if(document.getElementById('zcabs_upload') && abs)
        document.getElementById('zcabs_upload').value = abs.substring(0, (abs.length) - 15);
}

/* Funzioni abilitate per l'utente anonimo
-----------------------------------------------------------------*/
function editComment(e, contentId, commentId) {
	var query = '?#CONTENT_ID#='+contentId;	
	var uri = '#ENGINE_PATH#CommentInput.php'+query;	
	
	var left = mouseX(e)-230;
	var top = mouseY(e)-70;
	
	var id = 'commentbox-'+contentId;
	if(commentId) id = id+'-'+commentId;	
		
	if(e.currentTarget)
		var owner = e.currentTarget;
	else
		var owner = e.srcElement.parentNode;
		
	messageBox(id, uri, 'inputBox', left, top);
}

/*function checkContent(form) {
	if(typeof(form) != 'object') return false;
	
	if(!form.#COMMENT_NAME#.value) {
		alert('...devi inserire il nome');
		form.#COMMENT_NAME#.focus();
		return false;
	}
	
	if(!form.#COMMENT_TEXT#.value) {
		alert('...devi scrivere il commento');
		form.#COMMENT_TEXT#.focus();
		return false;
	}
	
	if(!form.#CONTENT_ACTION#.value) {
		alert('...nessuna azione specificata, probabile tentativo di hack');
		form.#CONTENT_ACTION#.focus();
		return false;
	}	
	
	return true;
}*/var zXml={useActiveX:(typeof ActiveXObject!="undefined"),useDom:document.implementation&&document.implementation.createDocument,useXmlHttp:(typeof XMLHttpRequest!="undefined")};zXml.ARR_XMLHTTP_VERS=["MSXML2.XmlHttp.6.0","MSXML2.XmlHttp.3.0"];zXml.ARR_DOM_VERS=["MSXML2.DOMDocument.6.0","MSXML2.DOMDocument.3.0"];function zXmlHttp(){}zXmlHttp.createRequest=function(){if(zXml.useXmlHttp){return new XMLHttpRequest();}else if(zXml.useActiveX){if(!zXml.XMLHTTP_VER){for(var i=0;i<zXml.ARR_XMLHTTP_VERS.length;i++){try{new ActiveXObject(zXml.ARR_XMLHTTP_VERS[i]);zXml.XMLHTTP_VER=zXml.ARR_XMLHTTP_VERS[i];break;}catch(oError){;}}}if(zXml.XMLHTTP_VER){return new ActiveXObject(zXml.XMLHTTP_VER);}else{throw new Error("Could not create XML HTTP Request.");}}else{throw new Error("Your browser doesn't support an XML HTTP Request.");}};zXmlHttp.isSupported=function(){return zXml.useXmlHttp||zXml.useActiveX;};function zXmlDom(){}zXmlDom.createDocument=function(){if(zXml.useDom){var oXmlDom=document.implementation.createDocument("","",null);oXmlDom.parseError={valueOf:function(){return this.errorCode;},toString:function(){return this.errorCode.toString()}};oXmlDom.__initError__();oXmlDom.addEventListener("load",function(){this.__checkForErrors__();this.__changeReadyState__(4);},false);return oXmlDom;;}else if(zXml.useActiveX){if(!zXml.DOM_VER){for(var i=0;i<zXml.ARR_DOM_VERS.length;i++){try{new ActiveXObject(zXml.ARR_DOM_VERS[i]);zXml.DOM_VER=zXml.ARR_DOM_VERS[i];break;}catch(oError){;}}}if(zXml.DOM_VER){return new ActiveXObject(zXml.DOM_VER);}else{throw new Error("Could not create XML DOM document.");}}else{throw new Error("Your browser doesn't support an XML DOM document.");}};zXmlDom.isSupported=function(){return zXml.useDom||zXml.useActiveX;};var oMozDocument=null;if(typeof XMLDocument!="undefined"){oMozDocument=XMLDocument;}else if(typeof Document!="undefined"){oMozDocument=Document;}if(oMozDocument&&!window.opera){oMozDocument.prototype.readyState=0;oMozDocument.prototype.onreadystatechange=null;oMozDocument.prototype.__changeReadyState__=function(iReadyState){this.readyState=iReadyState;if(typeof this.onreadystatechange=="function"){this.onreadystatechange();}};oMozDocument.prototype.__initError__=function(){this.parseError.errorCode=0;this.parseError.filepos=-1;this.parseError.line=-1;this.parseError.linepos=-1;this.parseError.reason=null;this.parseError.srcText=null;this.parseError.url=null;};oMozDocument.prototype.__checkForErrors__=function(){if(this.documentElement.tagName=="parsererror"){var reError=/>([\s\S]*?)Location:([\s\S]*?)Line Number(\d+),Column(\d+):<sourcetext>([\s\S]*?)(?:\-*\^)/;reError.test(this.xml);this.parseError.errorCode=-999999;this.parseError.reason=RegExp.$1;this.parseError.url=RegExp.$2;this.parseError.line=parseInt(RegExp.$3);this.parseError.linepos=parseInt(RegExp.$4);this.parseError.srcText=RegExp.$5;}};oMozDocument.prototype.loadXML=function(sXml){this.__initError__();this.__changeReadyState__(1);var oParser=new DOMParser();var oXmlDom=oParser.parseFromString(sXml,"text/xml");while(this.firstChild){this.removeChild(this.firstChild);}for(var i=0;i<oXmlDom.childNodes.length;i++){var oNewNode=this.importNode(oXmlDom.childNodes[i],true);this.appendChild(oNewNode);}this.__checkForErrors__();this.__changeReadyState__(4);};oMozDocument.prototype.__load__=oMozDocument.prototype.load;oMozDocument.prototype.load=function(sURL){this.__initError__();this.__changeReadyState__(1);this.__load__(sURL);};Node.prototype.__defineGetter__("xml",function(){var oSerializer=new XMLSerializer();return oSerializer.serializeToString(this,"text/xml");});Node.prototype.__defineGetter__("text",function(){var sText="";for(var i=0;i<this.childNodes.length;i++){if(this.childNodes[i].hasChildNodes()){sText+=this.childNodes[i].text;}else{sText+=this.childNodes[i].nodeValue;}}return sText;});}function zXslt(){}zXslt.transformToText=function(oXml,oXslt){if(typeof XSLTProcessor!="undefined"){var oProcessor=new XSLTProcessor();oProcessor.importStylesheet(oXslt);var oResultDom=oProcessor.transformToDocument(oXml);var sResult=oResultDom.xml;if(sResult.indexOf("<transformiix:result")>-1){sResult=sResult.substring(sResult.indexOf(">")+1,sResult.lastIndexOf("<"));}return sResult;;}else if(zXml.useActiveX){return oXml.transformNode(oXslt);}else{throw new Error("No XSLT engine found.");}};function zXPath(){}zXPath.selectNodes=function(oRefNode,sXPath,oXmlNs){if(typeof XPathEvaluator!="undefined"){oXmlNs=oXmlNs||{};var nsResolver=function(sPrefix){return oXmlNs[sPrefix];};var oEvaluator=new XPathEvaluator();var oResult=oEvaluator.evaluate(sXPath,oRefNode,nsResolver,XPathResult.ORDERED_NODE_ITERATOR_TYPE,null);var aNodes=new Array;if(oResult!=null){var oElement=oResult.iterateNext();while(oElement){aNodes.push(oElement);oElement=oResult.iterateNext();}}return aNodes;}else if(zXml.useActiveX){if(oXmlNs){var sXmlNs="";for(var sProp in oXmlNs){sXmlNs+="xmlns:"+sProp+"=\'"+oXmlNs[sProp]+"\' ";}oRefNode.ownerDocument.setProperty("SelectionNamespaces",sXmlNs);};return oRefNode.selectNodes(sXPath);}else{throw new Error("No XPath engine found.");}};zXPath.selectSingleNode=function(oRefNode,sXPath,oXmlNs){if(typeof XPathEvaluator!="undefined"){;oXmlNs=oXmlNs||{};var nsResolver=function(sPrefix){return oXmlNs[sPrefix];};var oEvaluator=new XPathEvaluator();var oResult=oEvaluator.evaluate(sXPath,oRefNode,nsResolver,XPathResult.FIRST_ORDERED_NODE_TYPE,null);if(oResult!=null){return oResult.singleNodeValue;}else{return null;};}else if(zXml.useActiveX){if(oXmlNs){var sXmlNs="";for(var sProp in oXmlNs){sXmlNs+="xmlns:\'"+sProp+"="+oXmlNs[sProp]+"\' ";}oRefNode.ownerDocument.setProperty("SelectionNamespaces",sXmlNs);};return oRefNode.selectSingleNode(sXPath);}else{throw new Error("No XPath engine found.");}};function zXMLSerializer(){}zXMLSerializer.prototype.serializeToString=function(oNode){var sXml="";switch(oNode.nodeType){case 1:sXml="<"+oNode.tagName;for(var i=0;i<oNode.attributes.length;i++){sXml+=" "+oNode.attributes[i].name+"=\""+oNode.attributes[i].value+"\"";}sXml+=">";for(var i=0;i<oNode.childNodes.length;i++){sXml+=this.serializeToString(oNode.childNodes[i]);}sXml+="</"+oNode.tagName+">";break;case 3:sXml=oNode.nodeValue;break;case 4:sXml="<![CDATA["+oNode.nodeValue+"]]>";break;case 7:sXml="<?"+oNode.nodevalue+"?>";break;case 8:sXml="<!--"+oNode.nodevalue+"-->";break;case 9:for(var i=0;i<oNode.childNodes.length;i++){sXml+=this.serializeToString(oNode.childNodes[i]);}break;};return sXml;};


