window.onload = function () { jTorbalizeMe(); }



 /*- content.js -*/ 

// ZDOMAIN_NEWS

// GET \\
function getMonths(year){
	var uri = "./custom/News/ArchivedMonths.php?year=" + year;
	var id = "year" + year;

	var callback = function(id, response) {
		var obj = document.getElementById(id);
		
		var check = document.getElementById(id + "#box");
		if(!check) openBox2(obj, response);
	}
		
	ajaxGet(id, uri, callback);
}

function getContents(year, month){
	var uri = "./custom/News/ArchivedNews.php?year=" + year + "&month=" + month;
	var id = "month" + month + year;
	
	var callback = function(id, response) {
		var obj = document.getElementById(id);

		var check = document.getElementById(id + "#box");
		if(!check) openBox2(obj, response);
	}
	
	ajaxGet(id, uri, callback);
}


 /*- callback.js -*/ 

// JavaScript Document

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

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

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

function reloadContainedContents(id, response, formId, domainId, foreignId, page){
	var uri = "./custom/Common/ContenitorBox.php?";
	if(foreignId)	uri += "zcfor=" + foreignId;
	if(page) 		uri += "&zcpag=" + page;

	uri += "&zdid=" + domainId;
	
	var callback = function(id, response) {
		var obj = document.getElementById(id);
		obj.innerHTML = response;
	}

	ajaxGet('body#box', uri, callback);	
}


 /*- 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('_',4);
	
	//code[0] = codice azione
	//code[1] = id dominio
	//code[2] = id content
	//alert(code[0] + " - " + code[1] + " - " + code[2]); 
	var postBack_code	= code[3];
	var id_content		= code[2];
	var id_domain 		= code[1];
	var action_code		= code[0];
	
	switch(action_code)
				{
					//Inserimento/Aggiornamento News
					case '1':
					{
						//alert("jT_1_" + code[1]);
						
						switch(id_domain)
						{
							case '1':
							{
								switch(postBack_code){
									case '1':{
											obj.onclick = function() {
																//confirmBox("postContent('editForm'," + code[1] + ",redirectToNews)","Salvare?");
																postContent('editForm_' + id_content, id_domain, reloadContainedContents);
																return false;
														}
											break;

									}
									default:{
											obj.onclick = function() {
																//confirmBox("postContent('editForm'," + code[1] + ",redirectToNews)","Salvare?");
																postContent('editForm_' + id_content, id_domain, reloadPage);
																return false;
														}
											break;
									}
								}
								break;
							}
/*							case '3':
							{
								obj.onclick = function() {
													//confirmBox("postContent('editForm'," + code[1] + ",reloadPage)","Salvare?");
													postContent('editForm_' + id_content, id_domain, reloadPage);
													return false;
											}
								break;
							}*/
							case '2':
							{
								obj.onclick = function() {
											//confirmBox("postContent('editForm'," + code[1] + ",reloadPage)","Salvare?");
											postContent('editForm_' + id_content, id_domain, reloadPage);
											return false;
									}
								break;
							}
							
/*							case '7':
							{
								obj.onclick = function() {
											//confirmBox("postContent('editForm'," + code[1] + ",reloadPage)","Salvare?");
											postContent('editForm_' + id_content, id_domain, reloadPage);
											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)
						{
							case '1':
							{
								//alert("jT_6_"+code[2]);
								obj.onclick = function() {
													//alert("id: " + id_content + " - domain: " + id_domain);
													confirmBox("dropContent(" + id_content + "," + id_domain + ",reloadPage);","Delete?");
													return false;
											}
								//alert("in jT_6_"+code[2]+" -- "+obj.onclick);
								break;
							}
						}
						break;
					}
				}
}

// JavaScript Document

// GUI
function loadUploadWidget(id_content_foreign, id_content_relation, id_domain, id_node, targetDiv, postBack){
	var uri = "./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;
	if(postBack) uri += "&postBack=" + postBack;
	
/*	var callback = function(id, response) {
		var obj = document.getElementById(id);
		
		var box = openBox2(obj, response, 'none');
		
		setBoxPosition(box, "fixed", calculateWindowY(getHeight(box), 0.45), calculateWindowX(getWidth(box), 0.5));
	}

	ajaxGet(targetDiv, uri, callback);*/	
	
	messageBox(targetDiv, uri, 'confirmationBox');
	
	return false;
}

function confirmBox(confirmation, message, targetDiv){
	var uri = "./custom/Common/ConfirmBox.php?";
	uri += "confirmation=" + encodeURIComponent(confirmation);
	uri += "&message=" + encodeURIComponent(message);
	
	if(!targetDiv) targetDiv = 'body';

	uri += "&targetDiv=" + encodeURIComponent(targetDiv);
	
	var callback = function(id, response) {
		var obj = document.getElementById(id);
		
		var box = openBox2(obj, response, 'confirmationBox');

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

	ajaxGet(targetDiv, uri, callback);	
}

function contenitorBox(contentId, domainId, styleClass, page) {

	var uri = "./custom/Common/ContenitorBox.php?";
	if(contentId)	uri += "zcfor=" + contentId;
	uri += "&zdid=" + domainId;
	
	if(!page) page = 1;
	uri += "&zcpag=" + page;
	
	var callback = function(id, response) {
		var obj = document.getElementById(id);
		
		var box = openBox2(obj, response, styleClass);

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

	ajaxGet('body', uri, callback);		
}

// SET&GET
function setContenitorValue(id_contenitor, id_domain, value, postBack){
	var uri = "./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 = "./custom/Common/SetContentState.php?";
	uri += "zdid=" + domainId;
	uri += "&zcid=" + contentId;

	uri += "&zcact=" + action;
	uri += "&zcexe=go";
	
	var callback = function(id, response){
		postBack(id, response, 'none', domainId);
	}
	
	ajaxGet(false, uri, callback);	
}

// CONTENT ACTIONS
function dropContent(contentId, domainId, postBack, foreignId) {

	var uri = "./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) {

	var form = document.getElementById(formId);
		
	if(!(form.zctit == undefined)){
		if(!(tinyMCE.get('zctit') == undefined)) var title = encodeURIComponent(tinyMCE.get('zctit').getContent());
		else{var title = encodeURIComponent(form.zctit.value);}
	}
		
	if(!(form.zcsub == undefined)){
		if(!(tinyMCE.get('zcsub') == undefined)) var subtitle = encodeURIComponent(tinyMCE.get('zcsub').getContent());
		else{var subtitle = encodeURIComponent(form.zcsub.value);}
	}
	
	if(!(form.zctxt == undefined)){
		if(!(tinyMCE.get('zctxt') == undefined)) var text = encodeURIComponent(tinyMCE.get('zctxt').getContent());
		else{var text = encodeURIComponent(form.zctxt.value);}
	}
	
	if(!(form.zcabs == undefined)){
		if(!(tinyMCE.get('zcabs') == undefined)) var abstract = encodeURIComponent(tinyMCE.get('zcabs').getContent());
		else{var abstract = encodeURIComponent(form.zcabs.value);}
	}
		
	if(!(form.zcsta == undefined))	var state		= form.zcsta.value;

	if(!(form.zcval == undefined))	var value		= encodeURIComponent(form.zcval.value);

	if(!(form.zctyp == undefined))	var type		= form.zctyp.value;
	
	var contentId	= form.zcid.value;
	
	if(!(form.zcfor == undefined))	var foreignId	= form.zcfor.value;
	if(!(form.zcrty == undefined))var relationId	= form.zcrty.value;

	var uri = "./custom/Common/PostContent.php?";
	uri += "zdid=" + domainId;
	if(contentId) uri += "&zcid=" + contentId;

	if(title)		uri += "&zctit=" + title;
	if(subtitle)	uri += "&zcsub=" + subtitle;
	if(text)		uri += "&zctxt=" + text;
	if(abstract)	uri += "&zcabs=" + abstract;

	if(type)		uri += "&zctyp=" + type;
	if(value)		uri += "&zcval=" + value;
	if(state)		uri += "&zcsta=" + state;

	if(foreignId) uri += "&zcfor=" + foreignId;
	if(relationId)uri += "&zcrty=" + relationId;

	uri += "&zcact=zcpost";
	uri += "&zcexe=go";

	var callback = function(id, response){
		postBack(id, response, formId, domainId, foreignId);
	}
	
	ajaxGet(false, uri, callback);	
}
*/

/** NEW POST CONTENT **/
function postContent(formId, domainId, postBack, action, supported_langs, contentType, state, value) {

        //tinyMCE.triggerSave();
        var text = tinyMCE.get('zctxt').getContent();
				document.getElementById('zctxt').value = text;
/*
        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 = "./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){
                //alert(response);
		if(postBack) postBack(id, response, formId, domainId, value);
	}

        var values = getFormValues(formId);

        ajaxPost(false, uri, values, callback);
}
/** end - new post content **/

function editContent(targetDiv, contentId, domainId, styleClass, value, contentType, postBack) {
	var uri = "./custom/Common/EditContent.php?";
	if(contentId)	uri += "zcid=" + contentId;
	if(contentType)	uri += "&zctyp=" + contentType;
	if(value) 		uri += "&zcval=" + value;
	if(postBack) 	uri += "&postBack=" + postBack;
	uri += "&zdid=" + domainId;
	
	uri += "&targetDiv=" + encodeURIComponent(targetDiv);

	var callback = function(id, response) {
		var obj = document.getElementById(targetDiv);
		
		var box = openBox2(obj, response, styleClass);
				
		setBoxPosition(box, "fixed", calculateWindowY(getHeight(box), 0.45), calculateWindowX(getWidth(box), 0.5));

		jTorbalizeMe();
		
		if(domainId != 2) loadTinyMce();
	}

	ajaxGet(targetDiv, uri, callback);		
}

/*
function loadingIcon(loadingId, display) {
	var obj = document.getElementById(loadingId);
	obj.style.display = display;
}

function dropContent(itemId) {
	if(confirm("Eliminare definitivamente l'articolo e i commenti?")) {
		var uri = "?#CONTENT_ACTION#=#ACTION_DROP#&#CONTENT_ID#="+itemId;
		window.location.href = uri;
	}
}
function archiveContent(itemId) {
	if(confirm("Archiviare l'articolo e i commenti?")) {
		var uri = "?#CONTENT_ACTION#=#ACTION_ARCHIVE#&#CONTENT_ID#="+itemId;
		window.location.href = uri;
	}	
}
function publishContent(itemId) {
	if(confirm("Ripubblicare l'articolo e i commenti?")) {
		var uri = "?#CONTENT_ACTION#=#ACTION_PUBLISH#&#CONTENT_ID#="+itemId;
		window.location.href = uri;
	}	
}

function closeContentInput(itemId) {
	var id = 'item'+itemId;
	var detailId = 'itemDetail'+itemId;
	
	closeBox(id);
	show(detailId);	
}

function checkContent(domainId, itemId) {
	var suffix = '_'+domainId;	
	if(itemId)suffix = suffix+'_'+itemId;

	var formId = 'contentForm'+suffix;			
	var formValues = getFormValues(formId);
	var valid = false;
	
	var buttonId = 'button'+suffix;
	var loadingId = 'loading'+suffix;		

	if(formValues['#CONTENT_ACTION#']) {
		formValues['#CONTENT_ACTION#'] = '#ACTION_CHECK#';
		
		loadingIcon(loadingId, 'block');
		hide(buttonId);		
		
		var uri = '#ENGINE_PATH#ContentCheck.php';
		var xml = ajaxPost(formId, uri, formValues, false, true);

		if(!xml)
			return false;
		
		var response = xml.getElementsByTagName("contentcheck");

		if(response.length == 1) {
			var check = response[0].getElementsByTagName("check");
			check = check[0].firstChild.nodeValue;

			if(check == 1)
				return true;
			else {
				var errors = response[0].getElementsByTagName("errors");
				
				for(var i = 0; i < errors.item(0).childNodes.length; i++) {
					error = errors.item(0).childNodes[i]
					
					if(error.nodeType == 1) {
						boxId = error.nodeName+suffix;
						errorValue = error.firstChild.nodeValue;
						
						if(errorValue == 'ok')
							closeBox(boxId);
						else
							openBox(boxId, '* '+errorValue, 'error');
					}
				}				
			}
		} else
			valid = false;
		
		loadingIcon(loadingId, 'none');	
		show(buttonId);		
	}
	
	return valid;
}

function checkObject(type, contentId) {
	var suffix = '_'+type+'_'+contentId;
	var formId = 'objectForm'+suffix;
	
	var formValues = getFormValues(formId);
	var valid = false;
	
	var buttonId = 'button'+suffix;
	var loadingId = 'loading'+suffix;	
	
	if(formValues['#OBJECT_ACTION#']) {
		formValues['#OBJECT_ACTION#'] = '#ACTION_CHECK#';
		
		loadingIcon(loadingId, 'block');
		hide(buttonId);		
		
		var uri = '#ENGINE_PATH#ObjectCheck.php';
		var xml = ajaxPost(formId, uri, formValues, false, true);
		
		if(!xml)
			return false;
		
		var response = xml.getElementsByTagName("objectcheck");

		if(response.length == 1) {
			var check = response[0].getElementsByTagName("check");
			check = check[0].firstChild.nodeValue;

			if(check == 1)
				return true;
			else {
				loadingIcon(loadingId, 'none');
				show(buttonId);				
				var errors = response[0].getElementsByTagName("errors");
				
				for(var i = 0; i < errors.item(0).childNodes.length; i++) {
					error = errors.item(0).childNodes[i]
					
					if(error.nodeType == 1) {
						boxId = error.nodeName+suffix;
						errorValue = error.firstChild.nodeValue;
						
						if(errorValue == 'ok')
							closeBox(boxId);
						else
							openBox(boxId, '* '+errorValue, 'error');
					}
				}				
			}
		} else
			valid = false;		
	}
	
	return valid;
}
*/
// SHOW & HIDE \\
function show(id) {
	var obj = document.getElementById(id);
	
	if(obj) {
		obj.style.display="block";
	}
}
function hide(id) {
	var obj = document.getElementById(id);
	
	if(obj)
		obj.style.display="none";
}
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) var width = box.clientWidth;
	else var width = box.offsetWidth;

	return width;
}

function getHeight(box){
	if(box.clientHeight != 0) var height = box.clientHeight;
	else var height = box.offsetHeight;

	return height;
}

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

	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;

	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].name] = form.elements[i].value;
		}	
		
		return values;
	} else
		return false;
}
*/
/** NEW **/
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;
}
/** end -new **/

/*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 messageBox(id, uri, className, owner, postBack) {
	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;	

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

		if(postBack) {
			postBack(id);
		} else
			loadTinyMce();		
	}	

	ajaxGet(id, uri, callback);
}

// TINY MCE
function loadTinyMce() {

    tinyMCE.init({
        mode : "specific_textareas",
        language : 'en',
        theme_advanced_buttons1 : ",newdocument,|,cut,copy,paste,pastetext,pasteword,|,undo,redo,|,search,replace,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,",
        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",
        theme_advanced_blockformats : "h1,h2,h3,blockquote",
        skin : "o2k7",
        theme : "advanced"
    });
}
// JavaScript Document

function startUpload(){
 	   /*document.getElementById('loading').style.visibility = 'visible';*/
	document.getElementById('uploadButton').disabled = true;
	show('loadingIcon');
	return true;
}
function stopUpload(message){
/*		document.getElementById('result').innerHTML = message;
		document.getElementById('result').style.visibility = 'visible';
	    document.getElementById('loading').style.visibility = 'hidden';
		closeFileDiv();
		document.getElementById('file').value = '';*/
	alert(message);		
	hide('loadingIcon');
	closeFileDiv();
}

function closeUpload(targetDiv, message) {
	closeBox(targetDiv);
	reloadPage();	
}

function changeType() {
	hide('fileDiv');	
	hide('uriDiv');		
	show('typesDiv');
	hide('uploadButton');
}

function selectType(typeId){
	document.getElementById('uploadForm').zctyp.value = typeId;
	
	switch(typeId)
	{
		case 2: {
/*			document.getElementById('fileLabel').innerHTML = "Image:";
			document.getElementById('fileDiv').style.visibility = 'visible';
			document.getElementById('uriDiv').style.visibility = 'hidden';*/
			var fileType = 'image';	
			show('fileDiv');			
			break;
			}
		case 4: {
/*			document.getElementById('fileLabel').innerHTML = "File:";
			document.getElementById('fileDiv').style.visibility = 'visible';
			document.getElementById('uriDiv').style.visibility = 'hidden';*/
			var fileType = 'file';				
			show('fileDiv');			
			break;
			}
		case 5: {
/*			document.getElementById('fileLabel').innerHTML = "URL:";
			document.getElementById('fileDiv').style.visibility = 'hidden';
			document.getElementById('uriDiv').style.visibility = 'visible';*/
			var fileType = 'image';	
			show('uriDiv');
			break;
			}
	}
	
	setHtml('fileType', fileType);
	hide('typesDiv');	
	show('uploadButton');
	//openFileDiv();
}

function closeFileDiv(){
/*	document.getElementById('fileDiv').style.visibility = 'hidden';
	document.getElementById('uriDiv').style.visibility = 'hidden';
	document.getElementById('uploadButton').style.visibility = 'hidden';
	//document.getElementById('closeMe').style.visibility = 'hidden';
	document.getElementById('fileLabel').style.visibility = 'hidden';
	document.getElementById('typesDiv').style.visibility = 'visible';*/
	
	hide('fileDiv');
	hide('uriDiv');	
	hide('uploadButton');
	show('typesDiv');	
}

function openFileDiv(){
/*	document.getElementById('uploadButton').style.visibility = 'visible';
	//document.getElementById('closeMe').style.visibility = 'visible';
	document.getElementById('fileLabel').style.visibility = 'visible';
	document.getElementById('typesDiv').style.visibility = 'hidden';*/
	
	show('fileDiv');
	show('uploadButton');
	hide('typesDiv');	
}/* 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;};


