function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  newwindow=window.open(theURL,winName,features);
  
  if (window.focus) {newwindow.focus()}

}

/*function voce(cosa, authority, poscampo)
{
	//alert("voce:"+cosa+"\n aut:"+authority+"\n"+poscampo);
	//if(voce=="")
		document.getElementById('aut_autori').src = "../../cgi-bin/wxis.exe?IsisScript=napoli/napoli.xis&dbaf="+authority+"&option=voce&autore_principale_p=a"+"&poscampo="+poscampo;
	
	else
		parent.frames.aut_autori.location.href="http://localhost/cgi-bin/wxis.exe?IsisScript=napoli/napoli.xis&dbaf="+authority+"&option=voce&autore_principale_p="+cosa+"&poscampo="+poscampo;
	
}*/

/*function insvoce(autorisel, ritcampo)
{
	//alert("1"+autorisel+"\n2"+ritcampo);
	
	if (eval("parent.document.inte."+ritcampo+".type == 'textarea'"))
		eval("parent.document.inte."+ritcampo+".value += autorisel");
	else
		eval("parent.document.inte."+ritcampo+".value = autorisel");
}*/
function insvoce(autorisel, ritcampo)
{
	//alert("1"+autorisel+"\n2"+ritcampo); //solo per debug
	if (eval("parent.document.inte."+ritcampo+".type == 'textarea'"))
		eval("parent.document.inte."+ritcampo+".value += autorisel +'\\r\\n'");
	else
		eval("parent.document.inte."+ritcampo+".value = autorisel");
}


if (document.images) {
offButton = new Image;
onButton = new Image;

offButton.src = "img/bt_authority.gif";
onButton.src = "img/bt_authority_hi.gif";
}
else {
offButton = "" ;
onButton = "";

document.myButton = "";
}

function chibussa()
{
	window.open('login.php','login', 'resizable=no,width=300,height=450,top=0,left=0,noresize,scrollbars=no');
}

function addOptions(ritcampo, scelto) {//inserisci opzione
    //alert(scelto+"\n"+ritcampo);
	
	
	if(ritcampo == 'autore_principale_p' || ritcampo == 'autore_ente' || ritcampo =='titolo_uniforme'){
			
			if(ritcampo == 'autore_principale_p'){
				document.inte.autore_ente.value = '';
				document.inte.titolo_uniforme.value = '';
			}
			else if(ritcampo == 'autore_ente'){
				document.inte.autore_principale_p.value = '';
				document.inte.titolo_uniforme.value = '';
			}
			else if(ritcampo == 'titolo_uniforme'){
				document.inte.autore_principale_p.value = '';
				document.inte.autore_ente.value = '';
			}


	}
	
	
    if (eval("parent.document.inte."+ritcampo+".type == 'select-multiple'")){//campo ripetibile
        if(confirm("Vuoi aggiungere questo record?\n\n"+scelto)){
            //var selbox = parent.document.inte.autore_ente;
            var selbox = eval("parent.document.inte."+ritcampo);
            if (selbox.options[0].value == " ")
                selbox.options.length = 0;
            var fnd = 0;
            for (n=0;n<selbox.length;n++){
                if(selbox.options[n].text == scelto)
                    fnd = 1;
            }
            if (!fnd){
                selbox.options[selbox.options.length] = new Option(scelto, scelto);
               for(var i = 0;i < selbox.length;i++){
                    selbox.options[i].selected = true;
               }
			   ritcampoHID=ritcampo.replace("mat", "");
			   eval("parent.document.inte."+ritcampoHID+".value += scelto+'@#@'");
            }
        }
    }
    else if (eval("parent.document.inte."+ritcampo+".type == 'textarea'")){
		eval("parent.document.inte."+ritcampo+".value += scelto");
    }
    else //campo non ripetibile
    {
        if(confirm("Vuoi inserire questo record?\n\n"+scelto))
            eval("parent.document.inte."+ritcampo+".value = scelto");
    }

    newwindow.close();

}

function delOptions(ritcampo, scelto) {//cancella opzione
    //var selbox = document.inte.autore_ente;
     if (eval("document.inte."+ritcampo+".type == \'select-multiple\'")){//campo ripetibile
        var selbox = eval("document.inte."+ritcampo);
		ritcampoHID=ritcampo.replace("mat", "");
        if (selbox.options[0].value != " ") {
            nomatch = new Array();
            for (n=0;n<selbox.length;n++){
                if(selbox.options[n].text != scelto)
                    nomatch[nomatch.length] = new Array(selbox.options[n].value, selbox.options[n].text);
            }
            selbox.options.length = 0;
            if (nomatch.length == 0){
                selbox.options[0]= new Option("Selezionare da AF"," ");
				eval("parent.document.inte."+ritcampoHID+".value = ''");
			}
            else{
				eval("parent.document.inte."+ritcampoHID+".value = ''");
                for (n=0;n<nomatch.length;n++){
                    selbox.options[n] = new Option(nomatch[n][1], nomatch[n][0]);
					//alert(nomatch[n][0]);
					eval("parent.document.inte."+ritcampoHID+".value += nomatch[n][0]+'@#@'");
				}
            }
        }
    } 
    else{
        eval("parent.document.inte."+ritcampo+".value = ''");
    }
}

function beddamatrix(campomat){
    splitcampomat = campomat.split(",")
    var matrice = "";
    for(var x = 0;x < splitcampomat.length;x++){
        var quanti = (splitcampomat[x].length-3);
        var campohid = splitcampomat[x].substring(0, quanti);
        var selbox =  eval("document.inte."+splitcampomat[x]);
        for(var i = 0;i < selbox.length;i++){
            selbox.options[i].selected = true;
        }
        for (n=0;n<selbox.length;n++){
            matrice += selbox.options[n].value+"@taglia@";
        }
        //alert(campohid+"--"+x);
        var matricetot = matrice.length;
        var matricequanti = (matrice.length-8);
        matrice = matrice.substring(0, matricequanti);
        eval("document.inte."+campohid+".value=matrice");
        var matrice = "";
    }
}

function setCheckBox(bCheck) {
  // ciclo su tutti i controlli del modulo
  for (var i = 0; i < document.mioform.length; i++) {
  	// se il nome del controllo inizia con "chk"
    if (document.mioform.elements[i].type == "checkbox") {
      // imposto il valore = parametro bCheck
      document.mioform.elements[i].checked = bCheck;
    }
  }
}


function Popup(apri) 
		{
        window.open(apri, '', 'top=10, left=10, width=500, height=400, resizable=no, scrollbars=yes, toolbar=no, status=no, menubar=no');
	    }



function sendSC(poscampo, note, valore) {
	
	eval("var noteRE = /\\^"+note+"/g");
	
	eval("var campo = document.inte."+poscampo+"mat");
	
	
	if (campo){
		
		if(eval("document.inte."+poscampo+"mat.options[0].value") != ' '){
			
			eval("var selOpt = document.inte."+poscampo+"mat.options[document.inte."+poscampo+"mat.selectedIndex].text");

			var res = selOpt.search(noteRE);

			if ( res == -1) {

				eval("document.inte."+poscampo+"mat.options[document.inte."+poscampo+"mat.selectedIndex].text += '^"+note+valore+"'");

				eval("document.inte."+poscampo+".value = ''");

				eval("var len = document.inte."+poscampo+"mat.options.length");

				for (n=0;n<len;n++){
					eval("document.inte."+poscampo+".value += document.inte."+poscampo+"mat.options["+n+"].text+'@#@'");
				}

			}
			else{
				alert('Attenzione!\n^'+note+' già presente');
			}
		}
		else{
		
			alert("Campo "+poscampo+" vuoto\nImpossibile aggiugere un sottocampo");
		
		}
		
	}
	else{
		eval("var valCampo = document.inte."+poscampo+".value");
	
		if(eval("document.inte."+poscampo+".value != ''")) {
			
			var res = valCampo.search(noteRE);

			if ( res == -1) {
				
				eval("document.inte."+poscampo+".value += '^"+note+valore+"'");
			}
			else{
			
				alert('Attenzione!\n^'+note+' già presente');
			
			}
		}
		else {
			alert("Campo "+poscampo+" vuoto\nImpossibile aggiugere un sottocampo");
		}

	}

}


function confirm_del_auth(voce) {
	
	var answer = confirm ("Premi OK per cancellare la voce "+voce+"\n dall'authority o CANCEL per annullare l'operazione");
	
	if (answer)
		return true;
	else
		return false;


}
 
 
var TINY={};

function T$(i){return document.getElementById(i)}
function T$$(e,p){return p.getElementsByTagName(e)}

TINY.accordion=function(){
	function slider(n){this.n=n; this.h=[]; this.c=[]}
	slider.prototype.init=function(t,e,m,o,k){
		var a=T$(t), i=x=0; this.s=k||'', w=[], n=a.childNodes, l=n.length; this.m=m||false;
		for(i;i<l;i++){if(n[i].nodeType!=3){w[x]=n[i]; x++}} this.l=x;
		for(i=0;i<this.l;i++){
			var v=w[i]; this.h[i]=h=T$$(e,v)[0]; this.c[i]=c=T$$('div',v)[0]; h.onclick=new Function(this.n+'.pr(false,this)');
			if(o==i){h.className=this.s; c.style.height='auto'; c.d=1}else{c.style.height=0; c.d=-1}
		}
	};
	slider.prototype.pr=function(f,d){
		for(var i=0;i<this.l;i++){
			var h=this.h[i], c=this.c[i], k=c.style.height; k=k=='auto'?1:parseInt(k); clearInterval(c.t);
			if((k!=1&&c.d==-1)&&(f==1||h==d)){
				c.style.height=''; c.m=c.offsetHeight; c.style.height=k+'px'; c.d=1; h.className=this.s; su(c,1)
			}else if(k>0&&(f==-1||this.m||h==d)){
				c.d=-1; h.className=''; su(c,-1)
			}
		}
	};
	function su(c){c.t=setInterval(function(){sl(c)},10)};
	function sl(c){
		var h=c.offsetHeight, d=c.d==1?c.m-h:h; c.style.height=h+(Math.ceil(d/10)*c.d)+'px';
		c.style.opacity=h/c.m; c.style.filter='alpha(opacity='+h*100/c.m+')';
		if((c.d==1&&h>=c.m)||(c.d!=1&&h==1)){if(c.d==1){c.style.height='auto'} clearInterval(c.t)}
	};
	return{slider:slider}
}();


function getJsonRFIDAttrib() {
	
	$('#loading-placeholder').html('<img src="/img/loading.gif" width="16px" height="16px" />');

	var url = "http://localhost/dba_nedap/webservice.php?op=readlabel&callback=?";
	$.ajax({
		url: url,
		type: "GET",
		async: false,
		cache: false,
		dataType: "jsonp",
		cache: false,
		timeout: 5000,
      		error: function() {          					
			alert("Errore! Impossibile contattare il lettore RFID.");
      		},
		success: function(data) {

			if (data == '') {
				alert('Nessun libro presente sul lettore RFID!');
			} else if (data.length > 1) {
				alert('Sul lettore sono presenti più RFID, mettere solo un RFID durante l\'attribuzione all\'inventario');
			} else {
				$('#rfid_uid').val(data[0].UID);
			}

      		}
	});

	$('#loading-placeholder').html('');

}


function sendJsonRFIDList(url_redir, div_id) {
	
	if(url_redir == null){
		url_redir = "documenti_search_results.php";
	}
	
	if(div_id == null){
		div_id = "#documenti_search_results";
	}
	
	var url = "http://localhost/dba_nedap/webservice.php?op=readlabel&callback=?";
	$.ajax({
			url: url,
			type: "GET",
			async: false,
			cache: false,
			dataType: "jsonp",

			success: function(data) {

				if (data == '') {
					alert('Nessun libro presente sul lettore RFID!');
				} else {
					
					//alert(data[0].UID);
					//alert("var_json: " + json.toString());
					json_string = $.toJSON(data);
					$.ajax({
						type: "POST",
						url: url_redir,
						//url: "documenti_search_results.php",
						//url: "../test_ajax.php", 
						data: {'search_type':'rfid_uid','rfid_uid_data_json': json_string},
						cache: false,
						success: function(html){
							$(div_id).html(html);
						}
					});
					

				}

			},
			error: function() {
					alert('Errore! Impossibile contattare il lettore RFID.');
			}	
	});

}


function changeEAS(rfid_list_array, type_operation) {
	
	switch(type_operation) {
		
		case 'disable':
			opRFID = 'disableEAS';
			break;
		case 'enable':
			opRFID = 'enableEAS';
			break;
	}
	
	
	$.each(rfid_list_array, function(index, rfid_uid) {
		
		//alert(rfid_uid); //DEBUG ONLY
		
		//var url = "http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?";
		var url="http://localhost/dba_nedap/webservice.php?op="+opRFID+"&UID="+rfid_uid+"&callback=?";
	
		$.ajax({
			url: url,
			type: "GET",
			async: false,
			cache: false,
			dataType: "jsonp",
			success: function(data) {
				
				$.each(data, function(index, item) {
					//data_clean[n] = item.UID;
					//++n;
					
					//TODO: Controllare risultato , se true non fare niente, se false mandare un alert
					
					if (opRFID == 'disableEAS') {
						if (item.DisableEASResult == 'false') {
							alert('Errore! Disabilitazione del Flag di Sicurezza RFID.');
						}
					} else if (opRFID == 'enableEAS') {
						if (item.EnableEASResult == 'false') {					
							alert('Errore! Disabilitazione del Flag di Sicurezza RFID.');
						}
					}
					//alert(item.EnableEASResult);
				});
				
				//json_string = $.toJSON(data);
				//alert('json_string: ' + json_string);
			},
			error: function(){
				alert('Errore! Impossibile contattare il lettore RFID.');
			}
		});

	});

}


function checkJsonRFIDList(rfid_list_array, type_operation) {

	//rfid_list_array = new Array();
	var data_clean = new Array();
	var msg_op = '';
	//$("#errore").val("true");
	

	switch(type_operation) {
		
		case 'prestito':
			msg_op = 'il prestito';
			break;
		case 'restituzione':
			msg_op = 'la restituzione';
			break;
		case 'cancellazione':
			msg_op = 'la cancellazione';
			break;
	}
	

	//Prima di effettuare la chiamata al lettore RFID controllo che nel carrello ci siano dei libri con etichetta RFID
	if (typeof(rfid_list_array) != "undefined" && rfid_list_array !== null && rfid_list_array != '') {
	
		var url = "http://localhost/dba_nedap/webservice.php?op=readlabel&callback=?";
		$.ajax({
			url: url,
			type: "GET",
			async: false,
			cache: false,
			dataType: "jsonp",
			"success": function(data) {

				if (data == '') {
					//$("#errore").val("false");
					alert('Nessun libro presente sul lettore RFID!');
				} else {
					
					var n = 0;
					var err = 0;
					$.each(data, function(index, item) {
						data_clean[n] = item.UID;
						++n;
					});

					if (typeof(rfid_list_array) != "undefined" && rfid_list_array !== null) {
						$.each(rfid_list_array, function (index, item) {
							var check_flag = $.inArray(item, data_clean);
							//alert(item + ": " + check_flag);
						
							if (check_flag < 0) {
								alert("Errore! Il libro con RFID " + item + " non è sul lettore. Riporre il libro sul lettore RFID prima di effettuare " + msg_op + ".");
								++err;
							}
						});
					}

					//Controllo finale su errori lettore Rfid/Carrello
					/*if (err > 0) {
						$("#errore").val("false");
					}*/


				}
				
				
			},
			"error": function(d,msg) {
					//$("#errore").val("false");
					alert("Errore! Impossibile contattare il lettore RFID.");
			}
		});
	
	}


}

function delInputText(campoid) {
	
	$('#'+campoid).val('');

}


// implement JSON.stringify serialization
/*JSON.stringify = JSON.stringify || function (obj) {
    var t = typeof (obj);
    if (t != "object" || obj === null) {
        // simple data type
        if (t == "string") obj = '"'+obj+'"';
        return String(obj);
    }
    else {
        // recurse array or object
        var n, v, json = [], arr = (obj && obj.constructor == Array);
        for (n in obj) {
            v = obj[n]; t = typeof(v);
            if (t == "string") v = '"'+v+'"';
            else if (t == "object" && v !== null) v = JSON.stringify(v);
            json.push((arr ? "" : '"' + n + '":') + String(v));
        }
        return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
    }
};*/

//var tmp = {one: 1, two: "2"};
//JSON.stringify(tmp); // '{"one":1,"two":"2"}'

