////////////////////////////////////////////////////////////////////////////////////////////////////////
//			           Libreria di funzioni e classi javascript                              //
//		                            del sito O-Soft.org                                         //
//														    //
//						All Rights Reserved						    //
//	js_mylibrary is exclusive property of Luca Jervasi, It CANNOT be copied or distribute	    //
//					without the licence of is owner.					    //
////////////////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////////////////
//						struct semaphore						    //
////////////////////////////////////////////////////////////////////////////////////////////////////////

function sem(){
	this.value = false;
	this.stack = new Array();
	this.wait = function(val){
		if(this.value){
			this.stack.push(val);
		}else{
			this.value = true;
			eval(val);
			this.signal();
		}
	};
	this.signal = function(){
		var len = this.stack.length;
		if(len){
			var next = this.stack.shift();
			eval(next);
		}else{
			this.value = false;
		}
	};
}

ajaxSem = new sem();		


////////////////////////////////////////////////////////////////////////////////////////////////////////
//					Funzione isset() (simile a PHP)				           //
////////////////////////////////////////////////////////////////////////////////////////////////////////

function isset(variable){
	return (typeof(window[variable]) == "undefined") ? false : true;
}

function strpos(haystack, needle, offset){
    var i = (haystack+'').indexOf(needle, (offset || 0));
    return i === -1 ? false : i;
}

function browser(){
	var browser = {
	'Lynx'		: 'Lynx',
	'Opera'	: 'Opera',
	'WebTV'	: 'WebTV',
	'Konqueror'	: 'Konqueror',
	'Chrome'	: 'Chrome',
	'Safari'	: 'Safari',
	'bot'		: 'Bot',
	'Google'	: 'Bot',
	'slurp'	: 'Bot',
	'scooter'	: 'Bot',
	'spider'	: 'Bot',
	'infoseek'	: 'Bot',
	'MSIE'		: 'MSIE',
	'Firefox'	: 'FireFox',
	'Nav'		: 'Netscape',
	'Gold'		: 'Netscape',
	'x11'		: 'Netscape',
	'Netscape'	: 'Netscape'
	};
	for (var chiave in browser) {
		if(strpos(navigator.userAgent, chiave )){
			return browser[chiave];
		}
	}
	return 'Altro';
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
// 			Funzioni per caricare un'immagine per il visualizzatore di foto		    //
////////////////////////////////////////////////////////////////////////////////////////////////////////

// Funzione per modificare il campo src del tag immagine nel visualizzatore di immagini
// Parametri:
// id = id del tag immagine dove caricare le immagini
// url = url dell'immagine da caricare

function imgview(id, url){
	var e = document.getElementById(id);
	e.src = url;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////
// 					Funzioni per valutare input	  	   				    //
////////////////////////////////////////////////////////////////////////////////////////////////////////

// Funzione per valutare gli input di un form
// Parametri:
// value = valore di paragone, può essere un valore numerico, un valore indicativo o un altro campo input
// action = definisce il tipo di valutazione da effettuare:
//	- upto = blocca il submit fino a che la lunghezza dell'imput non arriva al valore numerico value
//	- thenof = blocca il submit se la lunghezza dell'input supera il valore numerico value
//	- equalto = blocca il submit fino a che il valore inserito in un campo non è uguale a quello inserito
//	  nel campo indicato da value
//	- 
// id = id dell'input da considerare
// res_id = id del box dove lasciare il risultato della valutazione
// submit = id del input submit da bloccare fino a che non si ha la valutazione positiva

function valutate(action, id, value, res_id, submit){
	var toval = document.getElementById(id);
	var resval = document.getElementById(res_id);
	switch(action){
	case 'thenof':
	var max = value;
	if(toval.value.length > max){
		resval.innerHTML = "<img class='pass right' src='http://www.msonline.it/immagini/struttura/wrong.png'>";
		if(isset(submit)){
			document.getElementById(submit).disabled = true;
			document.getElementById(submit).onselect = 'return false';
		}
		return 0;
	}else{
		resval.innerHTML = "<img class='pass right' src='http://www.msonline.it//immagini/struttura/ok.png'>";
		if(isset(submit)){
			document.getElementById(submit).disabled = '';
			document.getElementById(submit).onselect = '';
		}
		return 0;
	}
	case 'upto':
	var min = value;
	if(toval.value.length < min){
		resval.innerHTML = "<img class='pass right' src='http://www.msonline.it/immagini/struttura/wrong.png'>";
		if(isset(submit)){
			document.getElementById(submit).disabled = true;
			document.getElementById(submit).onselect = 'return false';
		}
		return 0;
	}else{
		resval.innerHTML = "<img class='pass right' src='http://www.msonline.it/immagini/struttura/ok.png'>";
		if(isset(submit)){
			document.getElementById(submit).disabled = '';
			document.getElementById(submit).onselect = '';
		}
		return 0;
	}
	break;
	case 'equalto':
	var toval2 = document.getElementById(value);
	if(toval.value == toval2.value){
		resval.innerHTML = "<img class='pass right' src='http://www.msonline.it/immagini/struttura/ok.png'>";
		if(isset(submit)){
			document.getElementById(submit).disabled = '';
			document.getElementById(submit).onselect = '';
		}
		return 0;
	}else{
		resval.innerHTML = "<img class='pass right' src='http://www.msonline.it/immagini/struttura/wrong.png'>";
		if(isset(submit)){
			document.getElementById(submit).disabled = true;
			document.getElementById(submit).onselect = 'return false';
		}
		return 0;
	}
	break;
	}
}

////////////////////////////////////////////////////////////////////////////////////////////////////////
// 			 	  Funzioni per nascondere elementi staticamente				    //
////////////////////////////////////////////////////////////////////////////////////////////////////////

function show(id){
	var a = document.getElementById(id);
	a.style.visibility="visible";
	a.style.display="block";
}

function hide(id){
	var a = document.getElementById(id);
	a.style.visibility="hidden";
	a.style.display="none";
}

////////////////////////////////////////////////////////////////////////////////////////////////////////
// 		     Funzione che apre e chiude le icone cartella ed il loro contenuto		    //
////////////////////////////////////////////////////////////////////////////////////////////////////////

function open_folder(id1,id2){
	var a= document.getElementById(id1);
	if(a.style.visibility==""){
		a.style.visibility="visible";
		a.style.display="block";
		document.getElementById(id2).src="http://opens.altervista.org/Immagini/Icone_sito/open_folder.bmp";
	}else{
		a.style.visibility="";
		a.style.display="none";
		document.getElementById(id2).src="http://opens.altervista.org/Immagini/Icone_sito/close_folder.bmp";
	}
}

////////////////////////////////////////////////////////////////////////////////////////////////////////
// 				  	Funzione per l'utilizzo di AJAX			  		    //
////////////////////////////////////////////////////////////////////////////////////////////////////////

// Funzione per le chiamate http con javascript
// Parametri:
// id = id del contenitore che ospiterà il codice proveniente dalla chiamata http
// url = url della pagina carica nella chiamata http
// opt = parametri opzionali passati come array o stringa da poter passare via GET o POST alla pagina 
//	  PHP chiamata via http
// method = GET/POST metodo di invio dei dati
// var ajxact = false;

function ajax(id,url,opt,method){
	var param = "";
	if(opt != null){
		var ai = 0;
		var array = new Array();
		if(typeof(opt) == 'string'){ //se il parametro è una stringa
			opt = opt.split(',');
			for(var ide in opt){
				array[ai] = "attr"+ide+"="+encodeURIComponent(opt[ide]);
				ai++;
			}
		}else{ //se il parametro è un array
			for(var ide in opt){
				array[ai] = ide+"="+encodeURIComponent(opt[ide]);
				ai++;
			}
		}
		param = array.join('&');
	}else{
		param = null;
	}
	if(method == null){
		method = "GET";
	}
	if(window.XMLHttpRequest){	// per IE7+, Firefox, Chrome, Opera, Safari
		http = new XMLHttpRequest();
	}else{	// per IE6, IE5
		http = new ActiveXObject("Microsoft.XMLHTTP");
	}
	if(method == "POST" || method == "post"){
		http.open(method,url,true);
		http.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
		http.setRequestHeader("Content-length", param.length);
		http.setRequestHeader("Connection", "close");
	}else if(method == "GET" || method == "get"){
		param = "?"+param;
		url += param;
		param = null;
		http.open(method,url,true);
	}
	http.onreadystatechange=function(){
		if(http.readyState == 4 && http.status == 200){
			document.getElementById(id).innerHTML = http.responseText;
			EvalJS(id);
		}
	}
	http.send(param);
}
EvalJS = function(elementId){ //permette di eseguire codice javascript interno ad una chiamata http
	var scripts = document.getElementById(elementId).getElementsByTagName('script');
	var code;
	for(var i = 0; i < scripts.length; i++) {
		code = scripts[i].innerHTML ? scripts[i].innerHTML : 
			scripts[i].text ? scripts[i].text : 
			scripts[i].textContent;
		try{
			eval(code);
		}catch(e){
			alert(e);
		}
	}
}
function ajaxEx(id,url,opt,method){
	var func = "ajax('"+id+"','"+url+"'"; //,'"+opt+"','"+method+"');";
	if(opt != undefined){
		func += ",'"+opt+"'";
	}
	if(method != undefined){
		func += ",'"+method+"'";
	}
	func += ");";
	ajaxSem.wait(func);
}

////////////////////////////////////////////////////////////////////////////////////////////////////////
// 			  Classe di effetti chiusura/apertura a slide e drag&drop   			    //
////////////////////////////////////////////////////////////////////////////////////////////////////////

// Funzione per la creazione di effetti di chiusura/apertura a slide e drag6drop di contenitori usando 
// la programmazione ad oggetti
// Parametri:
// id = id dell'elemento cui applicare l'effetto.
// hide = true/false : se true chiude, se false apre.
// fade = true/false : se true scompare, se false appare.

function effect(id, hide, fade){
	this.action = false;
	if(hide == null){
		this.hi = true;
	}else{
		this.hi = hide;
	}
	if(fade == null){
		this.fa = true;
	}else{
		this.fa = fade;
	}
	this.i = 1;
	this.w = 0;
	this.v = 0;
	this.element = document.getElementById(id);
	this.element.style.visibility = 'visible';
	this.element.style.display = 'block';
	this.element.style.overflow = 'hidden';
	this.he = this.element.offsetHeight;
	this.move = false;
	this.z;
	if(this.fa){
		if(browser() == "MSIE"){
			this.element.style.filter = "alpha(opacity = 100)";
			this.MSIEOpacity = 100;
		}else{
			this.element.style.opacity = "1.0";
		}
	}else{
		if(browser() == "MSIE"){
			this.element.style.filter = "alpha(opacity = 0)";
			this.MSIEOpacity = 0;
		}else{
			this.element.style.opacity = "0.0";
		}
	}
	if(!this.hi){
		this.element.style.height = "0px";
	}

// Funzione per l'effetto drag&drop
	// Annulla il drag in alcune zone dell'elemento
	this.setMove = function(bval){
		this.move = bval;
	};
	
	// Avvia il drag ed attua il drop
	this.start = function(){
		var elem_start = this.element;	
		var difx = (elem_start.style.left.replace(/px/g,'')) - cx;
		var dify = (elem_start.style.top.replace(/px/g,'')) - cy;
		if(this.move){
			window.clearInterval(this.z);
			this.move = false;
		}else{
			this.move = true;
			this.z = window.setInterval(function foo(){elem_start.style.left = (cx+difx)+"px"; elem_start.style.top = (cy+dify)+"px";}, 30);
		}
	};
	
	// Avvia la cattura delle coordinate del cursore del mouse in caso sia avviato il drag
	document.onmousemove = mouseMove;
// -------

// Funzione per l'effetto hider-slide
	// Diminuisce i px visibili
	this.dec = function(){
		var h = this.element.offsetHeight;
		if((h - this.i) < 0){
			this.element.style.height = "0px"
			this.i = 1;
			this.hi = false;
			window.clearInterval(this.w);
			this.action = false;
		}else{
			this.i++;
			h = h - this.i;
			this.element.style.height = h+"px";
		}
	};
	
	// Aumenta i px visibili
	this.inc = function(){
		var h = this.element.offsetHeight;
		if((h + this.i) > this.he){
			this.element.style.height = this.he+"px"
			this.i = 1;
			this.hi = true;
			window.clearInterval(this.w);
			this.action = false;
		}else{
			this.i++;
			h = h + this.i;
			this.element.style.height = h+"px";
		}
	};
	
	// Avvia la chiusura-apertura a slide
	this.hider = function(){
		this.action = true;
		var me = this;		// questa riga serve per un problema di "scope" per IE
		if(this.hi){
			this.w = window.setInterval(function(){ me.dec(); }, 10);
		}else{
			this.w = window.setInterval(function(){ me.inc(); }, 10);
		}
	};
// -------

// Funzione per l'effetto fade-appear
	// diminuisce l'opacity
		this.MSIEfadeoff = function(){
		if(this.MSIEOpacity == 10){
			this.element.style.filter = "alpha(opacity = 0)";
			this.fa = false;
			window.clearInterval(this.v);
			this.action = false;
		}else{
			this.MSIEOpacity = this.MSIEOpacity - 10;
			this.element.style.filter = "alpha(opacity = "+this.MSIEOpacity+")";
		}
	};
	// aumenta l'opacity
	this.MSIEappear = function(){
		if(this.MSIEOpacity == 90){
			this.element.style.filter = "alpha(opacity = 100)";
			this.fa = true;
			window.clearInterval(this.v);
			this.action = false;
		}else{
			this.MSIEOpacity = this.MSIEOpacity + 10;
			this.element.style.filter = "alpha(opacity = "+this.MSIEOpacity+")";
		}
	};
	this.fadeoff = function(){
		var o = this.element.style.opacity;
		if(o == 0.1){
			this.element.style.opacity = "0.0";
			this.fa = false;
			window.clearInterval(this.v);
			this.action = false;
		}else{
			o = o - 0.1;
			this.element.style.opacity = o;
		}
	};
	// aumenta l'opacity
	this.appear = function(){
		o = this.element.style.opacity;
		o = parseFloat(o);
		if(o == 0.9){
			this.element.style.opacity = "1.0";
			this.fa = true;
			window.clearInterval(this.v);
			this.action = false;
		}else{
			o = o + 0.1;
			this.element.style.opacity = o;
		}
	};
	this.fade = function(){
		this.element.style.height = this.he;
		var me = this;		// questa riga serve per un problema di "scope" per IE
		if(browser() == "MSIE"){
			if(!this.action){
				this.action = true;
				if(this.fa){
					this.v = window.setInterval(function(){ me.MSIEfadeoff(); }, 100);
				}else{
					this.v = window.setInterval(function(){ me.MSIEappear(); }, 100);
				}
			}
		}else{
			if(!this.action){
				this.action = true;
				if(this.fa){
					this.v = window.setInterval(function(){ me.fadeoff(); }, 100);
				}else{
					this.v = window.setInterval(function(){ me.appear(); }, 100);
				}
			}
		}
	};
}

function mouseMove(e){
	// compatibilità crossbrowser
	if (e == undefined) var e = window.event;
	cx = (e.clientX != undefined) ? e.clientX : e.client.x;
	cy = (e.clientY != undefined) ? e.clientY : e.client.y;
	return false;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
// 		    	Funzione per cambiare classe a uno dei tag figli di un tag principale		    //
////////////////////////////////////////////////////////////////////////////////////////////////////////

function appClass(id, tag, classe){
	this.element = document.getElementById(id);
	this.vet = this.element.getElementsByTagName(tag);
	this.len = this.vet.length -1;
	this.classe = classe;
	this.a_class = this.vet[0].className;

	this.action = function(id){
		var n = id;
		var i = 0;
		while(i <= this.len){
			if(i == n){
				this.vet[i].className = this.classe;
			}else{
				this.vet[i].className = this.a_class;
			}
			i++;
		}
	};
}

////////////////////////////////////////////////////////////////////////////////////////////////////////
// 		     			 Funzione per cambiare immagine  					    //
////////////////////////////////////////////////////////////////////////////////////////////////////////

function changeImg(id,url1,url2,testo1,testo2){
	var e = document.getElementById(id);
	if(e.src == url2){
		e.src = url1;
		e.alt = testo1;
		e.title = testo1;
		prova = false;
	}else{
		e.src = url2;
		e.alt = testo2;
		e.title = testo2;
		prova = true;
	}
}

////////////////////////////////////////////////////////////////////////////////////////////////////////
// 		     				Funzione per il redirect	   				    //
////////////////////////////////////////////////////////////////////////////////////////////////////////

function redirect(url,time){
	var t = time * 1000;
	this.redir = function(){
		location.href = url;
	}
	window.setTimeout(function(){ this.redir(); }, t);
}

////////////////////////////////////////////////////////////////////////////////////////////////////////
// 		     			Funzione realizzare un contenuto editabile			    //
////////////////////////////////////////////////////////////////////////////////////////////////////////

function edit(objToEdit){
	objToEdit.contentEditable ='true';
	objToEdit.designMode ='on';
}

function appChange(url, tab, id, area, testo){
	if(confirm("Confermi le modifiche?")){
		var array = new Array();
		array['tab'] = tab;
		array['id'] = id;
		array['area'] = area;
		array['testo'] = testo;
		ajax('res',url,array,'POST');
	}
}

function appDelete(ide, url, tab, id, titolo){
	if(confirm("Confermi la cancellazione?")){
		var array = new Array();
		array['tab'] = tab;
		array['id'] = id;
		array['titolo'] = titolo;
		ajax(ide, url, array, 'POST');
	}
}

function getValue(ide){
	var form = (document.forms[ide])?document.forms[ide]:document.getElementById(ide);
	var value = new Array();
	var elements = form.elements;
	var numeroElementi = elements.length;
	for(var i = 0; i < numeroElementi; i++){
		if(elements[i].type == 'radio'){
			if(elements[i].checked){
				value[elements[i].name] = elements[i].value;
			}
		}else{
			value[elements[i].name] = elements[i].value;
		}
	}
	return value;
}
function postValue(url, ide, res_id){
	var value = getValue(ide);
	ajax(res_id, url, value, 'post');
}

function blank(url, name) {
	var newWindow = window.open(url, name);
	newWindow.focus();
	return false;
}
