/*******************************************************************
		GESTIONE ASSOCIAZIONI
		@author: Adriano Di Pasquale, Mauro Villani, Elio Malizia
		
		Moduli vincolanti:
//@prototype.js 
//@overlib.js
//@directory images
//@tmplbase.js
//@ajaxpages.js
*******************************************************************/

//--------------------------------------------------------------------
//			OGGETTO CON DATI GLOBALI ALLA ASSOCIATION
//--------------------------------------------------------------------


var assoc = {
	rowNumber : '0',
	
	asCampi : {},

	//src=Source
	asRigheSrc : null,
	divSrc : 'assocSrc',
	templateFileSrc : 'association.tmpl',
	templateFileSrcError : "association_error.tmpl",
	linkSrcSelected : {},
	linkSrcUnselected : {},
	
	allSelected : false,
		   	
	//dst=Destination
	asRigheDst : null,
	divDst : 'assocDst',
	templateFileDst : 'associationDst.tmpl',
	linkDst : {},
	
	asOperazioni : {},
	strTabellaHtml : '',

	//configurazioni
	//dir base per le immagini
    dirImg : '',			
    //dir base per i template javascript
    dirJst : '',		
	
    
	tagCfg : 'assocCfg',
	tagDati : 'assocDati',
	tagSchema : 'assocSchema',
	
	classType : 'Object'		//classe per la conversione json-xml-java Object	
};


//====================================================================
//				XML e JSON
//====================================================================

assoc.stringToXmlObject = function( xmlstring ) {
	// convert the string to an XML object.
	if (window.ActiveXObject)	{		// code for IE
		var doc=new ActiveXObject("Microsoft.XMLDOM");
		doc.async="false";
		doc.loadXML(xmlstring);
	} else {							// code for Mozilla, Firefox, Opera, etc.
		var parser=new DOMParser();
		var doc=parser.parseFromString(xmlstring,"text/xml");
	}
	//var x=doc.documentElement;
	return doc;
}
//--------------------------------------------------------------------

//
//		GESTIONE XML DI SPECIFICHE DEI CAMPI
//
assoc.initHashSchema = function ( xmlString ) {
	var xmlobject = this.stringToXmlObject( xmlString );

	var newAsCampi = this.asCampi;
	var cells = xmlobject.getElementsByTagName('cell');
	for (var i = 0 ; i < cells.length ; i++) {
		var h = {};
		var cell = cells[i];
		h['name'] = cell.getAttribute("name");
		h['type'] = cell.getAttribute("type");
		h['style'] = cell.getAttribute("style");
		h['title'] = cell.getAttribute("title");
		h['key'] = cell.getAttribute("key");
		newAsCampi[h['name']] = h;
	}
	//this.asCampi = newAsCampi;
}


//--------------------------------------------------------------------
//		XML DI INTERSCAMBIO CON LA PARTE SERVER
//--------------------------------------------------------------------
assoc.hash2Xml=function () {
	var titoli = '<?xml version="1.0"?><result state="assoc">';
	var chiusura= '</result>';

	var strCampi = '';

	this.strTabellaHtml = '';	//alert (this.asRigheSrc.inspect());
	
	var i=0;
	for (id in this.asRigheDst ) {
		this.hash2XmlRow( id, i++ );
	};

	this.strTabellaHtml = titoli + this.strTabellaHtml +	chiusura;

	$(this.tagDati).value = this.strTabellaHtml;
}

assoc.hash2XmlRow=function ( id, index ) {
	var op = '';
	var h = this.asRigheDst[id];
	var str = '<row operation="'+ op +'">';

	var asCampi= this.asCampi;
	for (nome in asCampi){
		var c = asCampi[nome];
		var strKey =( c['key'] == 'true' )? 'key="true"': ''; 
		str += '<cell '+ strKey +' name="'+ nome +'" value="'+ h[nome] +'"/>';		
	};
	this.strTabellaHtml += str + '</row>';
}
//--------------------------------------------------------------------

//====================================================================
//		JSON DI INTERSCAMBIO CON LA PARTE SERVER
//====================================================================

/*
{"root" :
	{"assoc.name": [
		  {
		    "crcId": "",
		    "codice": "IT021FE987",
		    "denominazione": "CIRCO DI S.AGOSTINO",
		    "operation":'insert',
		    "errors":''
		  },
		  {...
		  }
	]}
}
*/

assoc.datiJsonPerServer = function () {	
	$(this.tagDati).value = this.hash2Json( 'jstable', this.classType );
}

assoc.hash2Json = function (rootName, entityName) {
	if( rootName == undefined ) 	{ rootName="jstable";}
	if( entityName == undefined ) 	{ entityName=this.classType;}

	var obj = {};
	obj[rootName]={"list-type-list" : {} };
	var arr = new Array();

	var i=0;
	for (id in this.asRigheDst){
		i++;
		var h = this.hash2JsonRow( id );
		if( h != null ) {
			arr.push(h);
		}
	};
	obj[rootName]["recordsNumber"] = i;
	obj[rootName]["list-type-list"][entityName] = arr;
	var str = Object.toJSON(obj);
	
	return str;
}

assoc.hash2Json_OOOOOOOOOLLLLLDDDD = function (rootName, entityName) {
	if( rootName == null ) 	{ rootName="root";}
	if( entityName == null ) 	{		
		entityName=( this.name != null )? this.name: "entity";
	}

	var obj = {};
	obj[rootName]={};
	var arr = new Array();

	for (id in this.asRigheDst){
		var h = this.hash2JsonRow( id );
		if( h != null ) {
			arr.push(h);
		}
	};
	obj[rootName][entityName] = arr;
	var str = Object.toJSON(obj);
	
	return str;
}

assoc.hash2JsonRow = function ( elem, index ) {
	var h = this.asRigheDst[elem];
	var op = h['operation'];
	if( global.isEmpty( h['operation'] )){
		h['operation']='';		
	}	
	h['error']='';	//non viene re-inviato nuovamente l'errore.	
	var obj = {};	
	for( nome in this.asCampi ) {
		obj[nome] = h[nome];
	}
	return obj;
}
//--------------------------------------------------------------------

//====================================================================
//
//				OPERAZIONI
//
//====================================================================

assoc.DEBUG=function ( type ) {
	var asRighe=( type == 'src' )?this.asRigheSrc: this.asRigheDst;
	var s='';
	for (k in asRighe){
		var h = asRighe[k];
		s+= k +':'+h['id']+'\n';
		s+='========================\n';		
	}
	return s;
}

/**
 * @param hashSearchFields: hash di campi da usare per il filtro dei dati {nome:value ...} 
 * @param orderFields:		stringa dei campi da usare per l'ordinamento
 * @param da:				DA quale record tornare i dati
 * @param recordxp:			quantitą di dati da ritornare
 * @return
 */
assoc.dataFunctionName=function( hashSearchFields, orderFields, da, recordxp) {
	if( hashSearchFields == null ) {
		this.lovSrc.dataFunctionNameSchema( orderFields, da, recordxp );
	}else{
		this.lovSrc.dataFunctionName( hashSearchFields, orderFields, da, recordxp);
	}
}


assoc.selectedElement=function ( id ) {
	return( this.asRigheDst[id] != undefined );
}

assoc.ins=function ( id ) {
	if( this.selectedElement( id )){
		alert('elemento gią selezionato');
		return;
	}
	this.insertInHash(id);
	this.showAllTables();//( 'dst' );
}

assoc.del=function ( id ) {
	if( this.selectedElement( id ) == false ){
		alert('ERRORE: elemento con codice '+id+'non presente fra gli elementi selezionati');
		return;
	}
	this.deleteFromHash(id);
	this.showAllTables();//( 'dst' );
}

assoc.insAll=function () {
	for( id in this.lovSrc.asRighe) {this.insertInHash(id);}
	this.allSelected=true; 
	this.showAllTables();//( 'dst' );
}

assoc.delAll=function () {
	for( id in this.asRigheDst ) {	this.deleteFromHash(id);}
	this.allSelected=false; 
	this.showAllTables();//( 'dst' );
}


assoc.insertInHash=function (id) {
	var h = this.lovSrc.asRighe[id];
	//copia elemento selezionato
	var elem = {};
	for( var k in h ) {elem[k] = h[k];}
	//elem.merge( h );

	this.asRigheDst[id]=elem;	
}

assoc.deleteFromHash=function (id) {
	delete this.asRigheDst[id];
	//this.asRigheDst.remove(id);
}

//====================================================================
//
//		RENDERING HTML: DALL' HASH ALLA TABELLA HTML
//
//====================================================================
assoc.showAllTables = function () {
	this.lovSrc.hash2Html();
	this.lovDst.hash2Html( this.asRigheDst );
}
//--------------------------------------------------------------------

//====================================================================
//
//		METODI PUBBLICI
//
//====================================================================

//--------------------------------------------------------------------
//			INIT
//--------------------------------------------------------------------
assoc.initSenzaCaricamento1=function (_name, _tagSchema, _urlData, _divSrc, _divDst, _templateFileSrc, _templateFileDst, _tagDati, _classType) {
		this.name = _name;
		this.tagSchema = _tagSchema;
	
		if( global.isNotEmpty(_divSrc) ){this.divSrc = _divSrc;}
		if( global.isNotEmpty(_divDst) ){this.divDst = _divDst;}
		if( global.isNotEmpty(_templateFileSrc) ){this.templateFileSrc = _templateFileSrc;}
		if( global.isNotEmpty(_templateFileDst) ){this.templateFileDst = _templateFileDst;}
		if( global.isNotEmpty(_tagDati) ){this.tagDati = _tagDati;}
		if( global.isNotEmpty(_classType) ){this.classType = _classType;}

		this.dirImg = global.ContextPath + global.IzsLibraryResourcesPath + 'images/';	
		this.dirJst = global.ContextPath + '/layout/jstemplates/';
	
		var strDatiIniziali = $(this.tagDati).value;

		if( strDatiIniziali == '' ) {
			this.asRigheDst={};
		} else {
			var tmpTable= Object.clone(tmpltablepag);
			tmpTable.asRighe={};
			tmpTable.initHashSchema($F(_tagSchema));
			tmpTable.json2Hash( strDatiIniziali );
			this.asRigheDst = tmpTable.asRighe;
		}

		this.initHashSchema($F(_tagSchema));
	
		//tmpltablepag
		var lovTable = Object.clone(tmpltablepag);		
		lovTable.init( _tagSchema, this.divSrc, this.templateFileSrc, this.templateFileSrcError );
		//TODO: templateFileSrcError passato come opzione
		
	    var context=lovTable.getContext(); 
	    context.izslov = this;
	    context.assoc = this;
	    
		this.lovSrc = lovTable;
		this.asCampi = this.lovSrc.asCampi;
	
		this.urlData = lovTable.urlData;
	
		this.linkSrcSelected = new linkOperation(
				this.dirImg + 'checkbox.png',
			   	this.name + '.del',
			   	'-' );
		this.linkSrcUnselected = new linkOperation(
			   	this.dirImg + 'checkbox_unchecked.png',
			   	this.name + '.ins',
			   	'->' );
		this.linkDst = new linkOperation(
			   	this.dirImg + 'undo.gif',
			   	this.name + '.del',
			   	'<-' );

		this.linkDeselectAll = new linkOperation(
			   	this.dirImg + 'checkbox.png',
			   	this.name + '.delAll',
			   	'' );
		this.linkSelectAll = new linkOperation(
				this.dirImg + 'checkbox_unchecked.png',
			   	this.name + '.insAll',
			   	'' );
		this.allSelected = false; 
			   	
		var lovDst = Object.clone(tmpltable);
		lovDst.init( this.asCampi, this.divDst, this.dirImg);
	    lovDst.getContext().assoc = this;
	    this.lovDst = lovDst;
	
	    var ajp1 = new AjaxPages();
	    ajp1.load(this.dirJst + this.templateFileDst );
	    this.lovDst.templateProcessor = ajp1.getProcessor();
	    
}

assoc.initSenzaCaricamento=function (_name, _tagSchema, _urlData, _divSrc, _divDst, _templateFileSrc, _templateFileDst, _tagDati, _classType) {
	if( global[_name] == undefined ){
		var copy = Object.clone(assoc);	
		var globalName = 'global.'+_name;
		copy.localName = _name;
		
		copy.initSenzaCaricamento1( globalName, _tagSchema, _urlData, _divSrc, _divDst, _templateFileSrc, _templateFileDst, _tagDati, _classType) ;
		global[_name] = copy;
	}
}

assoc.init=function ( _name, _tagSchema, _urlData, _divSrc, _divDst, _templateFileSrc, _templateFileDst, _tagDati, _classType) {	
	this.initSenzaCaricamento( _name, _tagSchema, _urlData, _divSrc, _divDst, _templateFileSrc, _templateFileDst, _tagDati, _classType);

	global[_name].showAllTables();
}
