//-------------------------------------------------
//
//	Thread.js
//
//	Funzioni per admin e view dei post
//
//-------------------------------------------------



function TogglePanel(vElementId, vAnimate){
	
	var objElement = $(vElementId);

	var duration = 0;

	if(vAnimate){
		duration  = 1.0;
	}

	
	Effect.toggle(objElement, 'slide', { duration: duration });
	
	return false;
}

function ToggleAdminPanel(vLinkElementId, vElementId){
	
	var objElement = $(vElementId);
	var objLinkElement = $(vLinkElementId);

	var duration = 1.0;

	if(!objElement.hasClassName("closedPanel")){
		objLinkElement.update('[open]');
		Effect.SlideUp(objElement, { duration: duration,
						afterFinish: function(e){
							objElement.addClassName("closedPanel");
						}
					}
				);
	}else{
		objLinkElement.update('[close]');
		Effect.SlideDown(objElement, { duration: duration,
						beforeStart: function(e){
							objElement.setStyle({display: 'none'});
							objElement.removeClassName("closedPanel");
						}
					}
				);
	}
	return false;
}


//-------------------------------------------------------------------
//
//	Visualizzazione dello pseudo-percorso a destra del titolo
//
//-------------------------------------------------------------------
function SetPathTitle(vThreadDetailsPathWrapper,vJsonData){
	var newHTML = "";

	if (vJsonData) {
		vJsonData = vJsonData.evalJSON();
		
		if (vJsonData.bRoot != "") {
			tmp = unescape(vJsonData.bRoot).evalJSON();
			newHTML += '<a href="' + tmp.url + '">' + tmp.label + '</a>';
		}
		if (vJsonData.bRoot != "" && vJsonData.b1lvl != "") {
			tmp = unescape(vJsonData.b1lvl).evalJSON();	
			newHTML += '&nbsp;&gt;&nbsp;<a href="' + tmp.url + '">' + tmp.label + '</a>';
		}
		if (vJsonData.bRoot != "" && vJsonData.b1lvl != "" && vJsonData.b2lvl != "") {
			tmp = unescape(vJsonData.b2lvl).evalJSON();	
			newHTML += '&nbsp;&gt;&nbsp;<a href="' + tmp.url + '">' + tmp.label + '</a>';
		}
	}

	$(vThreadDetailsPathWrapper).update(newHTML);
}



//-------------------------------------------------
//
//	Geatione del meta Categories
//
//	Visualizzazione ad albero delle categorie
//	utilizzate come menu
//
//	Visualizzazione flat delle categorie
//	escluse dal menu
//
//-------------------------------------------------

//-----------------------------------------------------------------------------
//
//	Legge la struttura <ul><li>... del menu dal div firstMenu.
//
//	Scorre ricorsivamente la struttura <ul><li>..., inserisce le relative
//	checkbox nel div (usedCategories).
//
//	Inserisce nel div (unusedCategories) le category non utilizzate nel menu.
//
//-----------------------------------------------------------------------------
function InitCategoriesTool(){

	var strCurrentMenuStructureHiddenDivName = 'firstMenu';
	var strCurrentMenuCheckboxListDivName = 'usedCategories';
	var strUnusedCategoriesCheckboxListDivName = 'unusedCategories';
	var strCurrentMenuStructureUrl = '/it/interface/menu-structure';
	
	var objCurrentMenu;
	var objCurrentMenuDiv;
	var objCurrentMenuCheckboxesDiv;
	var objUnusedCategoriesCheckboxesDiv;
	
	//questo array viene popolato al interno della funzione RecurseUl
	var arrUsedCategories = new Array();
			
	//div firstMenu, contenente il menu completo
	objCurrentMenuDiv = $(strCurrentMenuStructureHiddenDivName);
	
	//div che conterra'  le checkbox relative al menu corrente
	objCurrentMenuCheckboxesDiv = $(strCurrentMenuCheckboxListDivName);
	
	//div che conterra'  le checkbox non utilizzate come menu
	objUnusedCategoriesCheckboxesDiv = $(strUnusedCategoriesCheckboxListDivName);

	objCurrentMenu = objCurrentMenuDiv.firstDescendant();
	RecurseUl(objCurrentMenu, objCurrentMenuCheckboxesDiv, arrUsedCategories, 0);
	
	
	//rimpimento del availableCategoriesRoot
	var arrAvailableCategories;  //tutte le categorie disponibili
	var arrUnsusedCategories;  //tutte le categorie gia' utilizzate

	//inizializzo array delle categorie disponibili con il risultato della
	//macro ^GetMetaPossibleValues
	arrAvailableCategories = [{id:"94",text:"Abbigliamento"},{id:"96",text:"Accessori"},{id:"164",text:"Addio al celibato"},{id:"172",text:"Addio al nubilato"},{id:"13",text:"Aiuto"},{id:"189",text:"Amore"},{id:"171",text:"Anniversario"},{id:"150",text:"Assistenza"},{id:"168",text:"Battesimo"},{id:"175",text:"Befana"},{id:"178",text:"Carnevale"},{id:"152",text:"Chi siamo"},{id:"15",text:"Chi siamo"},{id:"190",text:"Community"},{id:"163",text:"Compleanno"},{id:"169",text:"Comunione"},{id:"151",text:"Consigli utili"},{id:"61",text:"Contatti"},{id:"149",text:"Cos'è MyComposer?"},{id:"170",text:"Cresima"},{id:"97",text:"Cuscini"},{id:"162",text:"Eventi speciali"},{id:"158",text:"Famiglia"},{id:"191",text:"Festa del papà"},{id:"166",text:"Festa del papà"},{id:"167",text:"Festa della mamma"},{id:"182",text:"FotoAuguri"},{id:"57",text:"FotoCalendari"},{id:"60",text:"FotoIdee"},{id:"58",text:"FotoLibri"},{id:"188",text:"Gli animali"},{id:"22",text:"Gli eventi da ricordare"},{id:"183",text:"Hai gia' il volantino del Fotografo?"},{id:"11",text:"Home"},{id:"17",text:"I viaggi"},{id:"16",text:"Idee per..."},{id:"157",text:"Il mio FotoLibro"},{id:"27",text:"Il mondo bimbi"},{id:"47",text:"Il tempo libero"},{id:"37",text:"La scuola"},{id:"42",text:"La tua casa"},{id:"165",text:"Laurea"},{id:"160",text:"Lavoro e Hobby"},{id:"32",text:"Le idee regalo"},{id:"186",text:"Matrimonio"},{id:"154",text:"Newsletter"},{id:"95",text:"Oggetti per la casa"},{id:"177",text:"Pasqua"},{id:"181",text:"Peluche"},{id:"174",text:"Pensione"},{id:"12",text:"Prodotti"},{id:"14",text:"Promozioni"},{id:"179",text:"Puzzle"},{id:"180",text:"Quadri"},{id:"161",text:"Regali di Natale"},{id:"173",text:"Amore"},{id:"148",text:"Scarica il software"},{id:"155",text:"Scooby-Doo"},{id:"52",text:"Scooby-Doo"},{id:"187",text:"Sport"},{id:"59",text:"Stampe"},{id:"185",text:"Termini e Condizioni"},{id:"184",text:"Trova il tuo Fotografo"},{id:"156",text:"Utilizzo di MyComposer"},{id:"159",text:"Viaggi"},{id:"153",text:"Video Tutorial"}];

	//se non ci sono categorie già  utilizzate nella struttura del menu,
	//unusedCategories = availableCategories
	if(arrUsedCategories.size() > 0){
		//ottengo le categorie non utilizzate rimuovendo le Used Categories
  		//dal array arrAvailableCategories
  		arrUnsusedCategories = ArrayWithout(arrAvailableCategories, arrUsedCategories);
  	}else{
  		arrUnsusedCategories = arrAvailableCategories.clone();
  	}

  	arrUnsusedCategories.each(function(item){
  		var strItemText;
  		var strItemId;
  		var strMetaId;
  		var objUnusedDiv = objUnusedCategoriesCheckboxesDiv;
  		
  		strItemText = item.text;
  		strItemId = item.id;
  		strMetaId = 'metadata_mNHkaIaAnfvpjJRe3QS3-A';

  		AddCategoryItem(strItemId, strMetaId, strItemText, 0, objUnusedDiv, false);
  		
  	});
  	
  	objUnusedCategoriesCheckboxesDiv.appendChild(new Element('div', { 'class': 'clearBoth'}));
  	
  	//checka le categorie selezionate
  	CheckSelectedCategories();

  	//aggiorna la combo sub menu
	updateSubMenuCombo();	

	//Aggancia evento click di ogni checkbox category
	$$("div.CategoryItem input").each(function(cb){
		cb.observe("click",function(){
			updateSubMenuCombo();
		});
	});
  	
  	//seleziona valori correnti dei meta utilizzati in editing
        try{
  	    $$('#cbSubMenu option[value="' + subMenuForCategory + '"]')[0].selected=true;
        }catch(e){
            //alert(subMenuForCategory);
        }
}

function RecurseUl(vUlNode, vCkbNode, vArrNodeList, vLevel){
	var arrLiNodes;
 	var strMetaId = 'metadata_mNHkaIaAnfvpjJRe3QS3-A';
 	var intIndentStep = 20;


  	//li figli del vUlNode corrente
  	arrLiNodes = vUlNode.childElements();

  	//controllo che vUlNode abbia almeno un figlio (li)
  	if(arrLiNodes.length > 0){

    		//variabili per inizializzazione dei nodi Tree
    		var strText;
		var strId;
		
	  	var objSubMenu;  //eventuali sottonodo ul del li corrente
	  	
	  	//prototype elements per il popolamento del elenco delle categories
		var objInput;
		var objLabel;
		var objDivContainer;
	
	
		var i;
	
	  	//ciclo tutti gli li figli di vUlNode
	  	arrLiNodes.each(function(objMenuItem, index){
		    if (objMenuItem.classNames() != "qmclear") {
	                strText = objMenuItem.firstDescendant().firstChild.nodeValue;
	        	strId = objMenuItem.id.replace('metaCategory_', '');
	

                        if(strId != ''){
	        	    AddCategoryItem(strId, strMetaId, strText, vLevel, vCkbNode, true);
	                    		
	        	    //inserisco il text di ogni nodo nel array vArrNodeList, i suo elementi
	        	    //verranno eliminati dal elenco dei nodi disponibili prima del
	        	    //popolamento del treePanel availableCategories
	        	    vArrNodeList[vArrNodeList.size()] = {id:strId,text:strText};
	        		
	        	    //ogni li ha almeno un sottonodo a con il link se ha piÃ¹ di un sottonodo
			    //.length > 1 significa che il secondo Ã¨ un ul
			    if(vLevel < 2 && objMenuItem.childElements().length > 1){
			        //ricorsione sul UL
			        objSubMenu = objMenuItem.childElements()[1];
			
			        RecurseUl(objSubMenu, vCkbNode, vArrNodeList, vLevel + 1);
			    } 	
                        }
	            }     		        		
    		});
	}
	
}

function AddCategoryItem(v_strItemId, v_strMetaId, v_strItemText, v_intLevel, vContainer, vLevelizeItemClass){

	var intLevelIndent = 1;
	var strId = v_strItemId;
	var strMetaId = v_strMetaId;
	var strText = v_strItemText;
	var strItemStyleClass = 'CategoryItem';
	var strHtmlTagId = 'metaCategory_' + strId;
	var intIndentStep = 20;
	

	
	var objDivContainer;
	var objInput;
	var objLabel;
	
	
	intLevelIndent += v_intLevel;
	
	
	if(vLevelizeItemClass == true){
		strItemStyleClass += ' CategoryItemLevel' + intLevelIndent;
	}
	
	
	//inizializzo il div contenitore della coppia checkbox/label per la voce di menu corrente
	objDivContainer = new Element('div',
		{ 'class': strItemStyleClass,
		'style': 'padding-left:' + (intLevelIndent * intIndentStep)  + 'px'});
                	
                	
	//checkbox
        objInput = new Element('input',
		{ 'type': 'checkbox',
		'value': strId,
		'id': strHtmlTagId,
		'name': strMetaId });
                	
	//label della checkbox	
	objLabel = new Element('label',
		{ 'for': strHtmlTagId }).update(strText);
		
	//inserisco elemento (div contenitore) dentro il div predisposto (vCkbNode)
	objDivContainer.appendChild(objInput);
	objDivContainer.appendChild(objLabel);
	vContainer.appendChild(objDivContainer);
	
	
}

//-------------------------------------------------------
//
//	restituisce vArray - vWithout
//
//-------------------------------------------------------
function ArrayWithout(vArray, vWithout){
	var arrResult = new Array;
    var blnFound;


	//tutte le categorie disponibili
	vArray.each(function(item){
		blnFound = false;
	
		//categorie già  utilizzate
		vWithout.each(function(toRemove){
		
		    	//alert(toRemove.id);
			if(item.id == toRemove.id){
				blnFound = true;
			}
		
		});
	
		//dategorie disponibili non ancora utilizzate
		if(!blnFound){
		    arrResult[arrResult.size()] = item;
		}
	});
	
	return arrResult;
}

//-------------------------------------------------------
//
//	Inizializza la combo a seleziona multipla utilizzata
//	per la gestione della FrontPageCategory.
//
//	
//
//-------------------------------------------------------
function InitFrontPageMultiSelect(v_strWhereToRender, v_strInitValuesId, v_strPossibleValuesPath, v_strMetaName){
	//
	//namespace dedicato alla gestione della FrontPageCategory
	//dove inserisco gli oggetti globali utilizzati da diverse funzioni
	//
	Ext.namespace('Ext.frontpage');
	
	//variabili globali
	Ext.frontpage.WhereToRender = v_strWhereToRender;	//id del div dentro il quale renderizzare il controllo multiselect
	Ext.frontpage.PossibleValuesPath = v_strPossibleValuesPath;	//percorso degli elementi da ciclare per popolare la combo
	Ext.frontpage.InitValues = v_strInitValuesId;	//id del campo da cui leggere i valori selezionati nella combo multiselect (diverso per B2C e B2B)
	Ext.frontpage.MetaName = v_strMetaName;	//nome del campo con cui postare i valori selezionati per il salvataggio (diverso per B2C e B2B)
	Ext.frontpage.FrontPageRecordType = null;
	Ext.frontpage.DataStore = null;	//store con i possible values della combo multiselect
      	
      	//creo lo store che conterrà elenco delle categorie disponibili
      	Ext.frontpage.DataStore = new Ext.data.SimpleStore({
        	fields: ['id', 'name']
      	});
      	Ext.frontpage.FrontPageRecordType = Ext.data.Record.create(Ext.frontpage.DataStore.recordType);
      	
      	//Riempio lo store leggendo le categorie selezionate
	getFrontPageStoreData();
	
	//
	//creo il componente Multiselect
      	//
      	
      	//costruttore
      	Ext.frontpage.StateMultiSelect = function(config) {
      		//custom configs
      		//	none
      		
      		//richiamo il costruttore della classe base
        	Ext.frontpage.StateMultiSelect.superclass.constructor.call(this, config);
      	};
      	
      	//definizione della nuova classe multiselect
      	Ext.extend(Ext.frontpage.StateMultiSelect, Ext.form.MultiSelectField, {
      		store: Ext.frontpage.DataStore,
      		valueField:'id',
      		displayField:'name',
      		mode: 'local'
      	});
      	
      	//renderizzo il componente multiselect nel div indicato
      	var FrontPageMultiSelect=null;
	Ext.onReady(function(){
		Ext.frontpage.FrontPageMultiSelect = new Ext.frontpage.StateMultiSelect({
	          	renderTo: Ext.frontpage.WhereToRender,
	          	containerHeight: 200,
	          	containerWidth: 400
	        });
	
	
		if($F(Ext.frontpage.InitValues)){
		        //
		        //leggo i valori salvati su db letti da template e setto i valori selezionati nel controllo multiselect
		        //
		        //	NON passare al componente una stringa separata da virgole perche si incasina, fai lo split
		        //
		        Ext.frontpage.FrontPageMultiSelect.setValues($F(Ext.frontpage.InitValues).split(','));
		}
	});
	
	
	//Aggancia evento click di ogni checkbox category
	$$(Ext.frontpage.PossibleValuesPath).each(function(cb){
		cb.observe("click",function(){
			updateFrontPageMultiSelect(this);
		});
	});
}



//-------------------------------------------------------
//
//	svuota lo store dei valori
//	e lo riempie con quelli selezionati dal elenco dei
//	valori possibili
//
//-------------------------------------------------------
function getFrontPageStoreData(){
	
	Ext.frontpage.DataStore.removeAll();
	
	FrontPageRecordType = Ext.frontpage.FrontPageRecordType;
	

	$$(Ext.frontpage.PossibleValuesPath).each(function(cb){
		if (cb.checked){
			
			objRecAux = new FrontPageRecordType ({"id":cb.readAttribute("value"), "name":Ext.util.Format.htmlDecode(cb.parentNode.childElements()[1].innerHTML)});		
			Ext.frontpage.DataStore.add(objRecAux);
		}
	});	
	
	
}

//-------------------------------------------------------
//
//	aggiorna la combo multiselect sia nei
//	possibleValues che nei selectedValues
//
//	viene chiamata ad ogni click sulle checkbox della
//	categorie
//
//-------------------------------------------------------
function updateFrontPageMultiSelect(obj){
	//
	//	aggiorno i possibleValues selezionabili nella combo multiselect
	//
	getFrontPageStoreData();	//aggiorno lo store
	Ext.frontpage.FrontPageMultiSelect.buildMenu();	//refresh della combo
	
	//
	//	se è appena stato dececcata una checkbox che compariva tra i
	//	valori selezionati nella multiselect, dobbiamo aggiornare il
	//	suo campo values ed eliminare quello appena cliccato
	//
	
	// id e value della checkbox appena cliccata
	var objValue = obj.readAttribute("value");
	var objLabel = obj.parentNode.childElements()[1].innerHTML;
	
	//valori selezionati nella combo multiselect
	var oldSelectedValues = Ext.frontpage.FrontPageMultiSelect.getValue();
	
	var arrOldSelectedValues = new Array();
	
	if(oldSelectedValues){
		arrOldSelectedValues = oldSelectedValues.split(',');
		
		//ciclo array dei valori selezionati e quando incontro
		//il valore appena cliccato lo rimuovo
		var i = 0;
		arrOldSelectedValues.each(function(item){
				
			if(item == objValue){
				arrOldSelectedValues.splice(i,1);
			}
			
			i++;
		});
				
		//setto i valori selezionati della combo multiselect con elenco appena aggiornato
		Ext.frontpage.FrontPageMultiSelect.setValues(arrOldSelectedValues);
	}
}

function FrontPageSelectedValues(){
	return Ext.frontpage.FrontPageMultiSelect.getValue();
}

//funzione richiamata al submit della form
function setFrontPageField(){
	//valori selezionati nella multiselect
	var strFrontPage = FrontPageSelectedValues();
	var strMetaName = Ext.frontpage.MetaName;
	var hidd;
	
	strFrontPage.split(',').each(function(item){
		hidd = new Element('input',{type: 'hidden', name: strMetaName, value: item});
		$(Ext.frontpage.WhereToRender).insert(hidd);
	});
}


//-------------------------------------------------------
//
//	Aggiorna la combo con le categorie di primo livello
//
//-------------------------------------------------------
function updateRelatedMenu(){

	var opt = new Element('option',{value: '', style: 'font-style:italic; color: #555555'});
	opt.insert('&lt;&lt;None&gt;&gt;');
	
	$('cbRelatedMenu').options.add(opt);
	
	$$("div.CategoryItemLevel1 input").each(function(cb){
		var opt = new Element('option',{value: cb.readAttribute("value")});
		opt.insert(cb.parentNode.childElements()[1].innerHTML);
		$('cbRelatedMenu').options.add(opt);
		
	});	

}


//---------------------------------------------------------------------------------------------
//
//	Combo sub-menu
//
//---------------------------------------------------------------------------------------------
function updateSubMenuCombo(){
	//old value
	var oldValue = $F('cbSubMenu');
	$$('#cbSubMenu option').each(function(opt){opt.remove()});
	var opt = new Element('option',{value: '', style: 'font-style:italic; color: #555555'});
	opt.insert('&lt;&lt;None&gt;&gt;');
	$('cbSubMenu').options.add(opt);
	$$("div.CategoryItemLevel2 input").each(function(cb){
		if (cb.checked){
			var opt = new Element('option',{value: cb.readAttribute("value")});
			opt.insert(cb.parentNode.childElements()[1].innerHTML);
			if (oldValue==cb.getValue()) opt.selected=true;
			$('cbSubMenu').options.add(opt);
		}
	});	
}