//valore del mese e dell'anno, e l'oggetto dei giorni

//questa inoltre mi aggiorna un campo hidden dove c'� il parametro,cosi da nn dover ogni volta impazzire!
/**formato gg/mm/aaaa 
*/
function findObj(theObj, theDoc)
{
  var p, i, foundObj;
  
  if(!theDoc) theDoc = document;
  if( (p = theObj.indexOf("?")) > 0 && parent.frames.length)
  {
    theDoc = parent.frames[theObj.substring(p+1)].document;
    theObj = theObj.substring(0,p);
  }
  if(!(foundObj = theDoc[theObj]) && theDoc.all) foundObj = theDoc.all[theObj];
  for (i=0; !foundObj && i < theDoc.forms.length; i++) 
    foundObj = theDoc.forms[i][theObj];
  for(i=0; !foundObj && theDoc.layers && i < theDoc.layers.length; i++) 
    foundObj = findObj(theObj,theDoc.layers[i].document);
  if(!foundObj && document.getElementById) foundObj = document.getElementById(theObj);
  
  return foundObj;
}


function checkArray(){
var j;
var k=0;

for (j=0;j<3;j++){
	if (array[j]!='images/spacer.gif \" height=\"100'){
		nuovo[k]=array[j];
		k++;
		}
	}
	if(nuovo[0]==undefined)
		return false;
	else {
		//array[]=nuovo;
		return true;
	}
}
function ruota(){
	//alert(i);
	var ogg=findObj('immagine');
	if(checkArray()){ //se c'� almeno un'immagine
		if(nuovo[i-1]==undefined) 
			i=1;
		ogg.src=nuovo[i-1];
		i++;
		if(i==4)i=1;
		}
	else {
			window.clearInterval();
			return false;
		}
	}

var ref
function openwin(url,x,y)
 {
 ref=window.open(url,'url','width='+x+',height='+y+',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,copyhistory=no,resizable=yes,screenX=0,screenY=0,top=0,left=0');
 ref.focus();
 }


function aggiornaText(label,value){
label.value=value;
}


function aggiornaData(giorniSel,mese,anno){
	giorno=giorniSel.value;
	var data=new Date(anno,mese-1,giorno);
	//getMonth
	//giorni del mese.
	var data1=new Date(anno,mese,0);
	//parte da zero..
	var giorniCorrenti=giorniSel.length; //quanti giorni ho adesso
	var giorni=data1.getDate();//giorno del mese selezionato..
	while(giorni<giorniCorrenti){ //devo togliere giorni..
		giorniSel.options[giorniCorrenti-1]=null;//lo tolgo
		giorniCorrenti--;//adesso ho meno giorni.
	}
	while(giorni>giorniCorrenti){ //devo aggiungere giorni..
		giorniSel.options[giorniCorrenti]=new Option(giorniCorrenti+1);//lo tolgo
		giorniSel.options[giorniCorrenti].value=giorniCorrenti+1;
		giorniCorrenti++;//adesso ho meno giorni..
	}
	if(giorno >giorni){
		giorniSel.options[giorni-1].selected=true;
	}
}
//funzione che controlla una mail data
function controllaMail(mail){
	n=mail.lastIndexOf("@");
if(n>0 && (mail.lastIndexOf(".")>n) && mail.lenght()>7)
	return true;
return false;
}

//ritorna l'oggetto che vogliamo vedere dall'id (per vari browser
function getObj(name)
{
	var obj;
  if (document.getElementById)
  {
    	obj = document.getElementById(name);
  }
  else if (document.all)
  {
    obj = document.all[name];
  }
  else if (document.layers)
  {
   	obj = document.layers[name];
  }
	return obj;
}

function prendiColore(nome_oggetto,link){
oggetto=getObj(nome_oggetto);
var cp2=new ColorPicker('window');
cp2.select(oggetto,link);
}


function cambia_hidden(name){
	obj=this.getObj(name);
	obj.style.visibility=(obj.style.visibility=='visible')?'hidden':'visible';

}

function check(field)
{
for (i = 0; i < field.length; i++)
{
field[i].checked = true;
}
}

function decheck(field)
{
for (i = 0; i < field.length; i++)
{
field[i].checked = false;
}
}

/**
 * Checks/unchecks all tables
 *
 * @param   string   the form name
 * @param   boolean  whether to check or to uncheck the element
 *
 * @return  boolean  always true
 */
function setAllRadio(the_form,the_element,value_check)
{
	if(typeof(the_form)!='object'){
		var obj=getObj(the_form);//adesso ho l'oggetto form
	}else{
		obj=the_form;
	}
	while(obj!=null && obj.tagName!='FORM'){//salgo in qualsiasi caso
		obj=obj.parentNode;
		}
	if(obj==null)return;
	for(var i=0;i<obj.elements.length;i++){//tutti gli input del form
		oggetto=obj.elements[i];
		if(oggetto.tagName=='INPUT'){
			if(oggetto.name.indexOf(the_element+'[')==0 && oggetto.disabled==false){//quelli disabilitati li lascio stare
				if(oggetto.value==value_check)oggetto.checked=true;
				}
			}		
	}
	return;
} // end of the 'setCheckboxes()' function

function showObject(obj, level) {
	var l = '';
	var tmp = '';
	for(var a = 0; a < level; a++)
		l += '[_]';
	for(var a in obj) {
		var type = typeof(obj[a]);
		if(type == 'object')
			tmp += showObject(obj[a], (level + 1));
		else
			tmp += l + ' [' + typeof(a) + '] ' + a + ' = value: ' +
			obj[a] + ' < ' + type + '\n';
	}
	return tmp;
}

function initEditor(testo,width,height) {
var editor=null;
obj=getObj(testo);
if(obj==null){
	return;
	}
  editor = new HTMLArea(testo);
  //editor.registerPlugin(ContextMenu);
 editor.registerPlugin(TableOperations);
config=editor.config;
if(this.user != null && this.order!=null){
if(this.prima!=null && this.dopo!=null){
config.registerButton({
  id        : "carrello",
  tooltip   : "Parte relativa al carrello",
  image     : "icone/carrello.gif",
  textMode  : false,
  action    : function(editor, id) {
                editor.surroundHTML('[%carrello%]', '[%/carrello%]');
              }
});
}
config.registerDropdown({
    id: "user",
    options: this.user, // new way, new style, array allows options with the same text
    tooltip: "user.",
        action:function(e){
                selectbox=e._toolbarObjects["user"].element;
                editor.surroundHTML(selectbox.value,'');
                },
        refresh:function(e){
                }
  });

config.registerDropdown({
    id: "address",
    options: this.address, // new way, new style, array allows options with the same text
    tooltip: "address.",
        action:function(e){
                selectbox=e._toolbarObjects["address"].element;
                editor.surroundHTML(selectbox.value,'');
                },
        refresh:function(e){
                }
  });

config.registerDropdown({
    id: "order",
    options: this.order, // new way, new style, array allows options with the same text
    tooltip: "order.",
        action:function(e){
                selectbox=e._toolbarObjects["order"].element;
                editor.surroundHTML(selectbox.value,'');
                },
        refresh:function(e){
                }
  });

config.registerDropdown({
    id: "order_detail",
    options: this.order_detail, // new way, new style, array allows options with the same text
    tooltip: "order_detail.",
        action:function(e){
                selectbox=e._toolbarObjects["order_detail"].element;
                editor.surroundHTML(selectbox.value,'');
                },
        refresh:function(e){
                }
  });

}
if(this.user){
config.toolbar = [
[ "fontname", "space",
  "fontsize", "space",
  "formatblock", "space",
  "copy", "cut", "paste", "space"
 ],

["justifyleft", "justifycenter", "justifyright", "justifyfull", "separator",
 "insertorderedlist", "insertunorderedlist", "outdent", "indent", "separator",
 "subscript", "superscript","separator",
 "bold", "italic", "underline",   "strikethrough"],

[
 "TO-cell-delete","TO-cell-insert-after","TO-cell-insert-before","TO-cell-merge","separator",
	"TO-cell-split","TO-col-delete","TO-col-insert-after","TO-col-insert-before","TO-col-split","separator",
	"TO-row-delete","TO-row-insert-above","TO-row-insert-under","TO-row-prop","TO-row-split",
],
[ "inserttable","TO-table-prop","TO-cell-prop","separator",
  "forecolor", "hilitecolor", "textindicator", "separator",
  "inserthorizontalrule", "createlink", "insertimage",  "htmlmode", "separator", "undo", "redo" ,
],['user','address','order_detail','order','carrello']
];
}else{
config.toolbar = [
[ "fontname", "space",
  "fontsize", "space",
  "formatblock", "space",
  "copy", "cut", "paste", "space"
 ],

["justifyleft", "justifycenter", "justifyright", "justifyfull", "separator",
 "insertorderedlist", "insertunorderedlist", "outdent", "indent", "separator",
 "subscript", "superscript","separator",
 "bold", "italic", "underline",   "strikethrough"],

[
 "TO-cell-delete","TO-cell-insert-after","TO-cell-insert-before","TO-cell-merge","separator",
	"TO-cell-split","TO-col-delete","TO-col-insert-after","TO-col-insert-before","TO-col-split","separator",
	"TO-row-delete","TO-row-insert-above","TO-row-insert-under","TO-row-prop","TO-row-split",
],
[ "inserttable","TO-table-prop","TO-cell-prop","separator",
  "forecolor", "hilitecolor", "textindicator", "separator",
  "inserthorizontalrule", "createlink", "insertimage",  "htmlmode", "separator", "undo", "redo" ,
]
];

}
config.width = height+'px';
config.height = height+'px';
config.pageStyle =
  'body { background-color:#FFFFFF; color: black; width:100%;}';

  // comment the following two lines to see how customization works
  editor.generate();
  return false;
  }


function checkForm(){
		if(!getObj('tratt_dati').checked){
		alert('Autorizzare il trattamento dei dati personali per inviare la richiesta');
		getObj('tratt_dati').style.borderColor='red';
		return false;
	}
	obj=getObj('email');
	if((getObj('nome')).value==''){
		alert('Nome non inserito');
		return false;
	}
	if((getObj('cognome')).value==''){
		alert('Cognome non inserito');
		return false;
	}
	if((getObj('citta')).value==''){
		alert('Citta\' non inserito');
		return false;
	}
	if((getObj('indirizzo')).value==''){
		alert('Indirizzo non inserito');
		return false;
	}
	if((getObj('cap')).value==''){
		alert('CAP non inserito');
		return false;
	}


	if((getObj('provincia')).value==''){
		alert('Provincia non inserito');
		return false;
	}

	if(!controllaMail(obj.value)){
		alert('Mail non valida');
		return false;
		}
		return true;
}

function aggiungiSottomenu(id){
	parent=getObj('id_parent_new');
	bottone=getObj('id_text_new');
	parent.value=id;
	bottone.focus();
	bottone.style.border='1px solid red';
	alert('Scrivere il nome del sottomenu e premere invio o \'ok\'');
}


function login_md5(){
var md5=getObj('login_password');
var md51=md5.value;
md51=hex_md5(md51);
var md5_str=getObj('md5_password');
md5_str.value=md51;
(getObj('login_type')).value=1;
md5.value='';
return true;
}


function initEditor(name,width,height) {
	if(getObj(name)==null)return;
	var oFCKeditor = new FCKeditor(name) ;
	this.nome_combo=new Array();
	this.arrComboItems=new Array();
	if(this.user){
		//nome_combo='personalizza';
/*		nome_combo=new Array('personalizza','pippo');
		etichette_combo=new Array('Utenti','Tag');*/
		valori_combo=new Array();
		nome_combo.push('Utente');
		for(x in this.user){
			valori_combo.push(new Array(this.user[x],x));
			//	alert(x);		//Nome
			//	alert(this.select[x]);	//Tag

			}
		this.arrComboItems.push(valori_combo);
	}

	if(this.vendor){
		valori_combo=new Array();
		nome_combo.push('fornitore');
		for(x in this.vendor){
			valori_combo.push(new Array(this.vendor[x],x));
		}
		this.arrComboItems.push(valori_combo);
	}
	if(this.address){
		valori_combo=new Array();
		nome_combo.push('indirizzo');
		for(x in this.address){
			valori_combo.push(new Array(this.address[x],x));
		}
		this.arrComboItems.push(valori_combo);
	}

	if(this.order){
		valori_combo=new Array();
		nome_combo.push('ordine');
		for(x in this.order){
			valori_combo.push(new Array(this.order[x],x));
		}
		this.arrComboItems.push(valori_combo);
	}
	if(this.order_detail){
		valori_combo=new Array();
		nome_combo.push('carrello');
		for(x in this.order_detail){
			valori_combo.push(new Array(this.order_detail[x],x));
		}
		this.arrComboItems.push(valori_combo);
	}
	if(this.attribute_product){
		valori_combo=new Array();
		nome_combo.push('attributi');
		for(x in this.attribute_product){
			valori_combo.push(new Array(this.attribute_product[x],x));
		}
		this.arrComboItems.push(valori_combo);
	}
	if(this.vari){
		valori_combo=new Array();
		nome_combo.push('vari');
		for(x in this.vari){
			valori_combo.push(new Array(this.vari[x],x));
		}
		this.arrComboItems.push(valori_combo);
	}



	//this.arrComboItems=new Array(valori_combo,new Array(new Array('prova1','pipo1'),new Array('prova2','ciccio')));
	this.baseurl=document.URL.substring(0,document.URL.lastIndexOf("/")+1);
        oFCKeditor.BasePath = "/FCKeditor/" ;
	oFCKeditor.Config[ "DefaultLanguage" ] = "it-IT";
	oFCKeditor.Height =height;
	oFCKeditor.Width =width;
	oFCKeditor.Config['CustomConfigurationsPath'] = 'myconfig.js';
	oFCKeditor.ToolbarSet = 'prova' ;
	oFCKeditor.Config['SkinPath']='skins/office2003/'
	oFCKeditor.ReplaceTextarea() ;
}

function nascondiVarianti(variante){
	oggetto=getObj(variante);
	oggetto.style.visibility=(oggetto.style.visibility=='hidden')?'visible':'hidden';
	oggetto.style.position=(oggetto.style.position=='absolute')?'relative':'absolute';
}


/*
 *
 *
 * Funzioni per nascondere/mettere le destinazioni
 */

function cambia_destinazione(select){
    var numero=select.parentNode.parentNode;//mi tiro su il tr
    var id_tr=numero.id;
    var numero_tr=parseInt(id_tr.substring(7));
    var padre=numero.parentNode;//dovrebbe essere la table o il tbody
    var trovato=0;
    var oggetto=getObj('id_destination');
    oggetto.value=select.value;
    for(var j=0;j<padre.childNodes.length;j++){
        var oggetto=padre.childNodes[j];
        if(oggetto.className=='destination'){
            num=parseInt(oggetto.id.substring(7));
            if(num>numero_tr){

                padre.removeChild(oggetto);
                j--;//non sono sicuro ma dovrebbe far tornare indietro l'array
            }else{
                if(num==numero_tr){
                    trovato=j;
                    abilita(oggetto,true);
                }else{
                    abilita(oggetto,true);
                }
            }
        }
    }
    if((trovato+1)<padre.childNodes.length)
	    tr_vecchio=padre.childNodes[trovato+1];//metto dopo!!!
else
	tr_vecchio=null;
    //mettere la gif etc etc
    if(select.options[0].selected==false){
        var nuovo_tr=document.createElement("tr");
        nuovo_tr.id="numero_"+(numero_tr+1);
        nuovo_tr.className='destination';
	var td=document.createElement('td');
	td.innerHTML='<img src="images/loading.gif">';
	var td1=document.createElement('td');
	nuovo_tr.appendChild(td1);
	nuovo_tr.appendChild(td);
	if(tr_vecchio!=null)
	        padre.insertBefore(nuovo_tr, tr_vecchio);
	else{
		padre.appendChild(nuovo_tr);
		}
        carica_destinazioni(nuovo_tr,select.value);
    }
    
     for(var j=0;j<padre.childNodes.length;j++){
        var oggetto=padre.childNodes[j];
        if(oggetto.className=='destination'){
            abilita(oggetto,false);

        }
     }
}

function abilita(riga,valore){
    for(var i=0;i<riga.childNodes.length;i++){
        if(riga.childNodes[i].className=='dest_name'){
            for(var j=0;j<riga.childNodes[i].childNodes.length;j++){
                if(riga.childNodes[i].childNodes[j].className='entry'){
                    riga.childNodes[i].childNodes[j].disabled=valore;
                    return;
                }
            }
            return;
        }
    }
}


function carica_destinazioni(nuovo_tr,id_destinazione){
    var ajax=assegnaXMLHttpRequest();
    if(!ajax){
        return "";
    }
    ajax.open('GET', 'get_destinazioni.php?id_destination='+id_destinazione, true);
    ajax.send(null);
    ajax.onreadystatechange = function(){
    if (ajax.readyState==4){
            if( ajax.status == 200) {
                if(ajax.responseText.length>0){
		    riempi(nuovo_tr,ajax.responseText);
                }else{
                    nuovo_tr.parentNode.removeChild(nuovo_tr);
                }

            } else {
                nuovo_tr.parentNode.removeChild(nuovo_tr);//se ci son problemi cancello tutto!!!
            }
        }
	};
}


function riempi(oggetto,dati){
	/* 
	oggetto.innerHTML=dati;
	return;
	*/
	var nuovo_tr=document.createElement('tr');
	nuovo_tr.id=oggetto.id;
	nuovo_tr.className=oggetto.className;
	var td=document.createElement('td');
	td.className='dest_class';
	td.innerHTML=dati.substring(0,dati.indexOf('<sel'));
	var td1=document.createElement('td');
	td1.className="dest_name";
	td1.innerHTML=dati.substring(dati.indexOf('<sel'));
	nuovo_tr.appendChild(td);
	nuovo_tr.appendChild(td1);
	oggetto.parentNode.replaceChild(nuovo_tr,oggetto);
}




function assegnaXMLHttpRequest() {

// lista delle variabili locali
var XHR = null,

 // informazioni sul nome del browser
 browserUtente = navigator.userAgent.toUpperCase();


 // browser standard con supporto nativo
 // non importa il tipo di browser
 if(typeof(XMLHttpRequest) === "function" || typeof(XMLHttpRequest) === "object")
  XHR = new XMLHttpRequest();

 // browser Internet Explorer
 // è necessario filtrare la versione 4
 else if(
  window.ActiveXObject &&
  browserUtente.indexOf("MSIE 4") < 0
 ) {

  // la versione 6 di IE ha un nome differente
  // per il tipo di oggetto ActiveX
  if(browserUtente.indexOf("MSIE 5") < 0)
   XHR = new ActiveXObject("Msxml2.XMLHTTP");

  // le versioni 5 e 5.5 invece sfruttano lo stesso nome
  else
   XHR = new ActiveXObject("Microsoft.XMLHTTP");
 }

 return XHR;
}


