/* inclusione dinamica javascript */

var js_includes = new Array();

function JSManager(){
	this.included = js_includes;
	this.include = js_include_once;
	this.remove = js_remove_include;
}

function js_include_dom(script_filename) {
    var html_doc = document.getElementsByTagName('head').item(0);
    var js = document.createElement('script');
    js.setAttribute('language', 'javascript');
    js.setAttribute('type', 'text/javascript');
    js.setAttribute('src', script_filename);
    html_doc.appendChild(js);
    return false;
}

function js_include_once(script_filename) {
    if (!in_array(script_filename, js_includes)) {
        js_includes[js_includes.length] = script_filename;
        js_include_dom(script_filename);
    }
}

function js_remove_include(scriptname){
	var docScripts = document.getElementsByTagName('script');
	for(var i=0;i<docScripts.length; i++){
		if(docScripts[i].getAttribute("src") && docScripts[i].getAttribute("src").toLowerCase() == scriptname.toLowerCase()){
			var tmpID = create_unique_id();
			docScripts[i].setAttribute('id',tmpID);
			yank_node(tmpID);
			js_array_splice(scriptname);
		}
	}
}

function js_array_splice(scriptname){
	for(var i=0;i<js_includes.length;++i){
		if(js_includes[i].toLowerCase() == scriptname.toLowerCase()){
			js_includes.splice(i,1);
		}
	}
}

//css

//holds the currently loaded .css files
//holds same Idiot Note as js version
var css_includes = new Array();

//use this manager to keep things simple
function CSSManager(){
	this.included = css_includes;
	this.include = css_include_once;
	this.remove = css_remove_include;
}
function css_include(css_file) {
	var html_doc = document.getElementsByTagName('head').item(0);
	var css = document.createElement('link');
	css.setAttribute('rel', 'stylesheet');
	css.setAttribute('type', 'text/css');
	css.setAttribute('href', css_file);
	html_doc.appendChild(css);
	return false;
}
function css_include_once(script_filename) {
    if (!in_array(script_filename, css_includes)) {
        css_includes[css_includes.length] = script_filename;
        css_include(script_filename);
    }
}
//"un-includes" the included css file from the document
//use sparingly, as it's a memory whore
function css_remove_include(scriptname){
	var scripts = document.getElementsByTagName('link');
	for(var i=0;i<scripts.length; i++){
		if(scripts[i].getAttribute("href") && scripts[i].getAttribute("href").toLowerCase() == scriptname.toLowerCase()){
			var tmpID = create_unique_id();
			scripts[i].setAttribute('id',tmpID);
			yank_node(tmpID);
			css_array_splice(scriptname);
		}
	}
}
function css_array_splice(scriptname){
	for(var i=0;i<css_includes.length;++i){
		if(css_includes[i].toLowerCase() == scriptname.toLowerCase()){
			css_includes.splice(i,1);
		}
	}
}

//utility functions
//returns bool of whether a value exists in array
//used here to reference the includes
function in_array(needle, haystack) {
    for (var i = 0; i < haystack.length; i++) {
        if (haystack[i] == needle) return true;
    }
    return false;
}
//returns a random id
function create_unique_id(){
	return "id_" + Math.floor(Math.random() * (1000000 + 1)).toString();
}
//yanks a node with a given ID out of the DOM
//fall out: cascades, so all children are yanked as well 
function yank_node(nodeId){
	var toYank = document.getElementById(nodeId);
	if(toYank){
		var container = toYank.parentNode;
		container.removeChild(toYank);
	}
	return (toYank)?false:true;
}

/* inclusione dinamica javascript - fine -*/        

function login(){
 	var form=$('loginForm');
    if (form.user.value == "") {
    form.user.focus(); 
    $('userreq').update('<font color="#FF6600">Per favore digita la username</font>')
	new Effect.Appear('userreq'); 
	new Effect.Pulsate('userreq',{duration:1.5, from:0.5, pulses:3});   
    return false ;
  } 
    if (form.pass.value == "") {
    form.pass.focus(); 
    $('pwdreq').update('<font color="#FF6600">Per favore digita la password</font>')
	new Effect.Appear('pwdreq'); 
	new Effect.Pulsate('pwdreq',{duration:1.5, from:0.5, pulses:3});   
    return false ;
  } 
	var params = Form.serialize($('loginForm')); 
    $('loginbox').update('<p align="center"><br><img src="img/loading.gif" alt="attendere..." align="absmidle" /> <b>Verifica dei dati...</b></p>');
	new Ajax.Updater(
		'loginbox', 
		'auth.php', {
		parameters: params,
		asynchronous:true, evalScripts:true
		}
	);	
	//new Effect.Appear('panel');
}
function nascondireq(name,req) {
  var form=$('loginForm');
  if (form[name].value != "") {
	new Effect.Fade(req);   
    return false ;
  }
} 

function msg(){
	if((ind = navigator.appVersion.indexOf("MSIE")) > -1 && navigator.userAgent.indexOf("Opera") == -1) {
		alert("explorer");
	} else {
		alert("firefox");
	}
}

/* sotto pannello */
function subpanelOpen(idpanel){
	if (document.getElementById(idpanel).style.display == 'none') {
		new Effect.Appear(idpanel);
	}
}
function subpanelClose(idpanel){
	if (document.getElementById(idpanel).style.display != 'none') {
		new Effect.Fade(idpanel);
	}
}
function menuorderpage(lang){
    aggiornamento();
	var pars = 'lang=' + lang;
	new Ajax.Updater(
		'content',
		'menuorder.php', {
		 parameters: pars,
		 onComplete:function(){
		 showResponse;
		 },
		asynchronous:true, evalScripts:true
		}
	);
	new Ajax.Updater(
		'navigation',
		'menu.php', {
		 parameters: pars,
		 asynchronous:true, evalScripts:true
		}
	);	
}

function panelpage(action){
    subpanelClose('textsubPanel');
    aspetta('bodyPanel');
	var pars = 'action=' + action;
	new Ajax.Updater(
		'bodyPanel',
		'bodyPanel.php', {
		parameters: pars,
		asynchronous:true, evalScripts:true
		}
	);
	if (action == 'newPage') {
		menuorderpage('ita');
	}
}
function emptyPage() { // carica una pagina vuota nel corpo
  var url = "empty.php";
  var myAjax = new Ajax.Request(url,{onComplete: responso_pagina});
}
function subpanelpage(page,variabili){
 	new emptyPage();
	var pars = variabili;
    new subpanelOpen('textsubPanel'); /* apertura box sub panel */
    aspetta('textsubPanel');
	new Ajax.Updater(
		'textsubPanel',
		page+'.php', {
		parameters: pars,
		asynchronous:true, evalScripts:true
		}
	);
}


function responso(originalRequest){
	document.getElementById('bodyPanel').innerHTML = '<p align="left">'+originalRequest.responseText+'</p>';
}
/* galleria immagini */
function newAlbum(){
    aspetta_gall();
	var params = Form.serialize($('newalbumForm'));
	new Ajax.Updater('photomsg', 'galleria/newAlbum.php', {asynchronous:true, parameters:params, evalScripts:true, encoding:'UTF-8'});
}
function crea_album(elemento,contenuto){
	if(!$('obj'+elemento)){
		newitem=Builder.node( 
		'li', 
		{className:'items',id:'elemento_'+elemento},[
		//Builder.node( 'div', {className:'handle'},''),
		//Builder.node( 'div', {className:'delete delalb', id:elemento, onclick:"delAlbum('" + elemento + "')"},''),
		//Builder.node( 'div', {className:'entra', id:elemento, onclick:"foto('" + elemento + "')"},''),
		Builder.node( 'div', {className:'ghandle', onMouseOver:"showmessage('<b>Trascina questo album nella posizione desiderata</b>')", onMouseOut:"showmessage('Elenco Album Fotografici.')"},''),
		Builder.node( 'div', {className:'gdelete delalb', id:elemento, onclick:"delAlbum('" + elemento + "')", onMouseOver:"showmessage('<b>Clicca per eliminare questo album</b>')", onMouseOut:"showmessage('Elenco Album Fotografici.')"},''),
		Builder.node( 'div', {className:'gentra', id:elemento, onclick:"foto('" + elemento + "')", onMouseOver:"showmessage('<b>Clicca per entrare in questo album</b>')", onMouseOut:"showmessage('Elenco Album Fotografici.')"},''),		
		Builder.node( 'div', {className:'separatore'},''),
		Builder.node( 'span', {id:'item_'+elemento},contenuto)
		] 
		);
		//$('items_list').appendChild(newitem); //inserisce il nuovo nodo alla fine
  		$('items_list').insertBefore(newitem, $('items_list').firstChild); //inserisce il nuovo nodo all'inizio
		makesortable_albums();
		new Ajax.InPlaceEditor('item_'+elemento, 'galleria/editAlbum.php',{
		 callback: function(form, value){ return 'nome=' + value +'&idalbum='+elemento}
		});
		Effect.Appear('elemento_'+elemento, { duration: 1.5, from:0.5, to:1.0});
		document.getElementById('input_newalbum').value='nuovo album';
	}
}	
function makesortable_albums(){
// <![CDATA[
   Sortable.create("items_list",
   {
    dropOnEmpty:true,
	handle:'ghandle',
	containment:["items_list"],
	constraint:false,
	scroll:window,
	scrollSensitivity: 20,
	scrollSpeed: 25,
	onUpdate : saveOrder_album
	});	
// ]]>
}
function makesortableFoto(){
 // <![CDATA[
   Sortable.create("foto_list",
   {
    tag:'li',
	overlap:'horizontal',
	handle:'items',
	containment:["foto_list"],
	constraint: false,
	scroll:window,
	scrollSensitivity: 20,
	scrollSpeed: 25,
	onUpdate : saveOrderFoto
	});
 // ]]>
}
function saveOrder_album() {
  aspetta_gall();
  listorder = Sortable.serialize("items_list");
  var url = "galleria/ordinaAlbum.php";
  var pars = listorder; 
	var myAjax = new Ajax.Updater( 
		'photomsg', 
		url, 
		{ 
		method: 'post', 
		parameters: pars,
		asynchronous:true, 
		evalScripts:true
		}
	);    
} 
function saveOrderFoto() {
  aspetta_gall();
  listorder = Sortable.serialize("foto_list");
  var url = "galleria/ordinaFoto.php";
  var pars = listorder; 
	var myAjax = new Ajax.Updater( 
		'photomsg', 
		url, 
		{ 
		method: 'post', 
		parameters: pars,
	 	onLoading: aspetta_gall,
     	onComplete: sortedPics,
		asynchronous:true, 
		evalScripts:true
		}
	);    
} 
function delAlbum(deleteid){
  if (confirm('Sei sicuro di voler eliminare questo album?')) {
    aspetta_gall();
    Effect.Pulsate('elemento_'+deleteid,{duration:1.5, from:0.5, pulses:3});
	var url = 'galleria/deleteAlbum.php';
	var pars = 'deleteid=' + deleteid;
		var myAjax = new Ajax.Updater( 
			'photomsg', 
			url, 
			{ 
			method: 'get', 
			parameters: pars,
			asynchronous:true, evalScripts:true
			}
		); 
	}
}
function delFoto(deleteid){
  if (confirm('Sei sicuro di voler eliminare questa foto?')) {
    aspetta_gall();
    Effect.Pulsate('elemento_'+deleteid,{duration:1.5, from:0.5, pulses:3});
	var url = 'galleria/deleteFoto.php';
	var pars = 'deleteid=' + deleteid;
		var myAjax = new Ajax.Updater( 
			'photomsg', 
			url, 
			{ 
			method: 'get', 
			parameters: pars,
			asynchronous:true, evalScripts:true
			}
		); 
	}
}
function fotoInfo(id){
    aspetta_gall();
	var url = 'galleria/fotoInfo.php';
	var pars = 'idf=' + id;
		var myAjax = new Ajax.Updater( 
			'photomsg', 
			url, 
			{ 
			method: 'get', 
			parameters: pars,
			asynchronous:true, evalScripts:true
			}
		); 
	}
function showalbumSelect(){
	if (document.getElementById('albumSelect').style.display == 'none') {
		new Effect.Appear('albumSelect', { duration: 0.5 });
		new Effect.Highlight('albumSelect',{duration: 2});
	}
}
function hidealbumSelect(){
	if (document.getElementById('albumSelect').style.display != 'none') {
		new Effect.Fade('albumSelect');
	}
}
function albumTitle(albumname,albumid){
	document.getElementById('buttonmsg').innerHTML = albumname;
	new Effect.Highlight('photomsg');
}
function showmessage(msg){
	    document.getElementById('photomsg').innerHTML = msg;
}
function aspetta_gall(){
	if (document.getElementById('photomsg').style.display == 'none') {
		new Effect.Appear('photomsg', { duration: 1.0 });
	} 
	document.getElementById('photomsg').innerHTML = '<img src="galleria/img/loader.gif" alt="attendere..." align="absmidle" />Aggiornamento in corso...';
}
function sortedPics(){
	document.getElementById('photomsg').innerHTML = '<b>Foto ordinate correttamente!</b>';
	new Effect.Highlight('photomsg',{duration: 2});
}
function banners(){
    subpanelClose('textsubPanel');
    aspetta('bodyPanel');
	var pars = 'action=banners';
	new Ajax.Updater(
		'bodyPanel',
		'bodyPanel.php', {
		parameters: pars,
		asynchronous:true, evalScripts:true
		}
	)
}
/* funzione per mantenere il focus dei link dopo il click */
var currLink = null;
function toggleActive(elm)
{
if(currLink)
currLink.className = currLink.className.replace(/\bactive\b/,'');
currLink = elm;
currLink.className += " link-panelmenu-active";
}
function editadmin(idadminuser){
    //subpanelClose('textsubPanel');
    //aspetta('bodyPanel');
	var pars = 'idadminuser=' + idadminuser;
	new Ajax.Updater(
		'textsubPanel',
		'mydata.php', {
		parameters: pars,
		asynchronous:true, evalScripts:true
		}
	)
}
function saveEditAdmin(){
	var form=$('editAdminForm');
	var invalid = " "; // Invalid character is a space
	var minLength = 6; // Minimum length  
	var checkOK = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
	var checkpwd = form.passwd.value;
	var Validpwd = true;
	for (i = 0;  i < checkpwd.length;  i++){
	    ch = checkpwd.charAt(i);
	        for (j = 0;  j < checkOK.length;  j++)
	            if (ch == checkOK.charAt(j))
	            break;
	            if (j == checkOK.length){
	                Validpwd = false;
	            break;
	            }
	}

  if (form.nome.value == "") {
    form.nome.focus();
	document.getElementById('nomereq').innerHTML = '<font color="#FF6600">Nome Obbligatorio</font>'; 
	new Effect.Pulsate('nomereq',{duration:1.5, from:0.5, pulses:3});   
    return false ;
  }
  if (form.cognome.value == "") {
    form.cognome.focus();
	document.getElementById('cognomereq').innerHTML = '<font color="#FF6600">Cognome Obbligatorio</font>'; 
	new Effect.Pulsate('cognomereq',{duration:1.5, from:0.5, pulses:3});   
    return false ;
  }
  if (form.username.value == "") {
    form.username.focus();
	document.getElementById('usernamereq').innerHTML = '<font color="#FF6600">Username Obbligatoria</font>'; 
	new Effect.Pulsate('usernamereq',{duration:1.5, from:0.5, pulses:3});   
    return false ;
  }
if (!Validpwd){
    form.passwd.focus();
	document.getElementById('passwdreq').innerHTML = '<font color="#FF6600">Spiacente, sono consentiti solo caratteri alfanumerici nella password.</font>'; 
	new Effect.Pulsate('passwdreq',{duration:1.5, from:0.5, pulses:3});  
    return (false);
}  
  if (form.passwd.value != form.passwd2.value) {
	document.getElementById('passwd2req').innerHTML = '<font color="#FF6600">Le Password non coincidono</font>'; 
	new Effect.Pulsate('passwd2req',{duration:1.5, from:0.5, pulses:3});   
    form.passwd2.focus();
    return false ;
  }
	var params = Form.serialize($('editAdminForm'));
	new Ajax.Updater('textsubPanel', 'editAdmin.php', {asynchronous:true, parameters:params, evalScripts:true, encoding:'UTF-8'});
}