// JavaScript Document

var	Lang = {
	Search: 'Rechercher',
	Add: 'Ajouter',
	Remove: 'Retirer',
	OK: 'OK',
	Cancel: 'Cancel',
	Searching: 'Recherche en cours ...'
};

var RelationsTypes = {
	Contact: {
		WindowTitle1: 'Selectionnez un contact',
		WindowTitleN: 'Recherche de contacts',
		SearchClasses: ['Contact'],
		DisplayFields: ['firstname','lastname','email'],
		NewInputName: 'Nouveau contact',
		LinkConcatFields: ['firstname','lastname'],
		LinkSeparator: "; ",
		LinkEmpty1: '<i>Ajouter un contact</i>',
		LinkEmptyN: '<i>Ajouter un/des contact(s)</i>'
	},
	Company: {
		WindowTitle1: 'Selectionnez un partenaire',
		WindowTitleN: 'Recherche de partenaires',
		SearchClasses: ['Company'],
		DisplayFields: ['name','site'],
		NewInputName: 'Nouvel organisme',
		LinkConcatFields: ['name'],
		LinkSeparator: "<br /><br />",
		LinkEmpty1: '<i>Ajouter un partenaire</i>',
		LinkEmptyN: '<i>Ajouter un/des partenaire(s)</i>'
	},
	Theme: {
		WindowWidth: 400,
		WindowHeight: 300,
		WindowTitle1: 'Selectionnez un theme',
		WindowTitleN: 'Selectionnez un/des theme(s)',
		SearchClasses: ['Theme', 'Folder'],
		DisplayFields: 'Treeview',
		LinkConcatFields: ['name'],
		LinkSeparator: "<br />",
		LinkEmpty1: '<i>Selectionnez un theme</i>',
		LinkEmptyN: '<i>Selectionnez un/des theme(s)</i>'
	}
};



function	SearchPopup(relation, param, input, link) {
	//////////////////////////////////////////////////////////////////
	//
	//	Begining of the contructor
	//
	//////////////////////////////////////////////////////////////////
	
	this.hiddeninput = input;
	this.relation = relation;
	this.param = ''+param;
	this.link = link;
	this.Relation = RelationsTypes[relation];
	this.ListSelected = [];
	this.ListResult = [];
	this.Ajax = new XmlRequest();
	this.Ajax.popup = this;
	var title = this.param.indexOf('n') == -1? this.Relation.WindowTitle1: this.Relation.WindowTitleN;
	var width = this.Relation.WindowWidth? this.Relation.WindowWidth: 600;
	var height = this.Relation.WindowHeight? this.Relation.WindowHeight: 40;
	this.Window = new Popup(title, width, height, this);
	this.Window.ContentObject = this;
	this.content = this.Window.content;
	this.colnames = [];
	if (typeof(this.Relation.DisplayFields) == 'string' && this.Relation.DisplayFields == 'Treeview') {
		this.mode = 'tree';
	}
	else
		this.mode = 'list';
	for (i in this.Relation.DisplayFields)
		this.colnames.push(this.Relation.DisplayFields[i]);
	
	//! local variable
	var tr, td, head, body, div, maintable;
	
	this.hide = function(){this.Window.visibility(false);}
	this.show = function(){this.Window.visibility(true);}

	//////////////////////////////////////////////////////////////////
	//
	//	Function requested by Buttons and/or list click
	//
	//////////////////////////////////////////////////////////////////
	this.AddDeleteButton = function() {
		var img = dc('img');
		img.src = GLOBALS.ROOT+GLOBALS.PICT_FOLDER+'delete.gif';
		img.style.cursor = 'pointer';
		if (this.link.nextSibling) img = this.link.parentNode.insertBefore(img, this.link.nextSibling);
		else img = this.link.parentNode.appendChild(img);
		this.link.parentNode.insertBefore(dt('   '), img);
		img.theinput = this.hiddeninput;
		img.thelink = this.link;
		img.onclick = function() {
			this.theinput.value = '';
			this.thelink.innerHTML = '<i>Ajouter un contact</i>';
			this.parentNode.removeChild(this.previousSibling);
			this.parentNode.removeChild(this);
		}
	}
	this.ListXml = function(xml) {
		return (ParseXmlObjectList(xml).list);
	}
	this.Search = function() {
		while (this.result.firstChild) this.result.removeChild(this.result.firstChild);
		var tr = this.result.appendChild(dc('tr'));
		var td = tr.appendChild(dc('td'));td.appendChild(dc('br'));td.appendChild(dt(Lang.Searching));
		this.Ajax.popup = this;
		this.Ajax.onReceive=function(status,xml,text){
			this.popup.ListResult=this.popup.ListXml(xml);
//			alert('result: '+this.popup.ListResult+"\nlen: "+this.popup.ListResult.length);
			this.popup.ShowResult(this.popup.result,this.popup.colnames,this.popup.ListResult);
			this.popup.Window.resize();
			this.popup.search_input.focus();
		}
		var q = escape(this.search_input.value);var query='&list='+this.relation+(q?'&q='+q:'');
//		alert('query: '+query);
		this.Ajax.query('GET','?xml'+query,true);
	}
	this.DefaultAction = function(tbody, tr, id, ClassType) {
		if (tbody != this.result) return ;
		for (td = tr.firstChild; td; td = td.nextSibling)
			td.style.backgroundColor = '#FFFFCC';
		var obj;
		for (i in this.ListResult) if (this.ListResult[i].id == id && this.ListResult[i].ClassType == ClassType) {
			obj = this.ListResult[i];
			break ;
		}
		if (this.param.indexOf('n') == -1) {
			var str = obj.firstname+(obj.firstname && obj.lastname?' ': '')+obj.lastname;
			var t = tr.firstChild.ClassType && tr.firstChild.itemId? tr.firstChild.ClassType+':'+tr.firstChild.itemId: '';
			this.hiddeninput.value = t;
			if (this.link)
				this.link.innerHTML = str? str: (this.param.indexOf('n')==-1? this.Relation.LinkEmpty1: this.Relation.LinkEmptyN);
			if (this.link && this.hiddeninput.value)
				this.AddDeleteButton();
			this.Window.Close();
			this.hiddeninput.row = obj;
			jQuery(this.hiddeninput).change();
			return ;
		}
		for (i in this.ListSelected) if (this.ListSelected[i].id == id && this.ListSelected[i].ClassType == ClassType)
			return ;
		if (!obj)
			return ;
		var tr = this.AddRow(this.selected, this.colnames, obj, true);
		if (tr.previousSibling.previousSibling)
			for (td=tr.previousSibling.firstChild;td;td=td.nextSibling) {
				td.style.borderBottomStyle = 'dashed';
				td.style.borderBottomColor = '#CCCCCC';
				td.style.borderBottomWidth = '1px';
			}
		this.ListSelected.push(obj);
	}
	this.Remove = function(id, ClassType) {
		var found = false;
		for (i in this.ListSelected)
			for (tr = this.selected.firstChild; tr; tr = tr.nextSibling)
				if (this.ListSelected[i].id == id && this.ListSelected[i].ClassType == ClassType && tr.firstChild.itemId == id && tr.firstChild.ClassType == ClassType) {
					this.ListSelected.splice(i, 1);
					if (!tr.nextSibling && tr.previousSibling.previousSibling)
						for (td = tr.previousSibling.firstChild; td; td = td.nextSibling)
							td.style.borderBottomWidth = '0px';
					this.selected.removeChild(tr);
					found = true;
					break ;
				}
		if (!this.CheckSelected(this.ListSelected))
			this.buttonremove.disabled = true;
		return (found);
	}
	this.onCreate = function(info, url) {
		var str = info.firstname+(info.firstname && info.lastname? ' ': '')+info.lastname;
		if (this.searchpopup.param.indexOf('n') == -1) {
			this.searchpopup.hiddeninput.value = info.ClassType+':'+info.id;
			if (this.searchpopup.link)
				this.searchpopup.link.innerHTML = str? str: (this.searchpopup.param.indexOf('n')==-1? this.searchpopup.Relation.LinkEmpty1: this.searchpopup.Relation.LinkEmptyN);
	//		alert(nmode);
			if (this.searchpopup.link && this.searchpopup.hiddeninput.value)
				this.searchpopup.AddDeleteButton();
			this.searchpopup.Window.Close();
			
		}
		else {
			this.searchpopup.ListSelected[this.searchpopup.ListSelected.length] = info;
			this.searchpopup.AddRow(this.searchpopup.selected, this.searchpopup.colnames, info, true);
			this.searchpopup.show();
		}
	}
	
	//////////////////////////////////////////////////////////////////
	//
	//	Function to draw LISTS
	//
	//////////////////////////////////////////////////////////////////
	this.AddCol = function(tr, colname, bstyle, bcolor, bwidth, rwidth, padding) {
		var td = tr.appendChild(dc('td'));
		td.appendChild(dt(colname));
		td.style.borderBottomStyle = bstyle;
		td.style.borderBottomColor = bcolor;
		td.style.borderBottomWidth = bwidth;
		td.style.borderRightWidth = rwidth;
		with(td.style){borderRightStyle='dashed';borderRightColor='#CCCCCC';paddingLeft=paddingRight='1px';cursor='pointer';}
		td.unselectable = 'on';
		return (td);
	}
	this.AddRow = function(tbody, col_names, obj, islast) {
		var tr = tbody.appendChild(dc('tr'));
		for (j in col_names) {
			var text = '';
			if (obj[col_names[j]]) {
				text = obj[col_names[j]];
				if (text.length >= 20)
					text = text.substr(0, 16)+' ...';
			}
			var td = this.AddCol(tr, text, 'dashed', '#AAAAAA', islast? '0px': '1px', j == col_names.length-1? '0px': '1px');
			td.style.whiteSpace = 'pre';
			td.popup = this;
			td.itemId = obj.id;
			td.ClassType = obj.ClassType;
			td.unselectable = 'on';
			td.style.textAlign = 'left';
			td.style.cursor = 'pointer';
			td.onclick = function() {this.popup.Toggle(this.parentNode.parentNode, this);}
			td.ondblclick = function() {this.popup.DefaultAction(this.parentNode.parentNode, this.parentNode, this.itemId, this.ClassType);}
		}
		return (tr);
	}
	this.ShowResult = function(div, col_names, list) {
		while (div.firstChild)
			div.removeChild(div.firstChild);
		var tr = div.appendChild(dc('tr'));
		for (i in col_names)
			this.AddCol(tr, col_names[i], 'solid', '#555555', '1px', i == col_names.length-1? '0px': '1px');
		for (i in list)
			this.AddRow(div, col_names, list[i], i==list.length-1? true: false);
		var height = div.parentNode.clientHeight;
		height = height > 400? 400: height;
		this.overflow.style.height = height+'px';
		if (tr.clientWidth > parseInt(this.overflow.style.width))
			this.overflow.style.height = (parseInt(this.overflow.style.height)+20)+'px';
	}
	//////////////////////////////////////////////////////////////////
	//
	//	Function to check / unckeck / get status of selected fields
	//
	//////////////////////////////////////////////////////////////////
	this.CheckSelected = function(tbody) {
		for (tr=tbody.firstChild;tr;tr=tr.nextSibling)if(tr.firstChild.style.backgroundColor!='')return(true);return false;
	}
	this.Toggle = function(tbody, cell) {
		if(this.param.indexOf('n')==-1){for(tr=tbody.firstChild;tr;tr=tr.nextSibling)if(tr!=cell.parentNode)for(td=tr.firstChild;td;td=td.nextSibling)td.style.backgroundColor='';}
		var tr = cell.parentNode;
		for (td = tr.firstChild; td; td = td.nextSibling)
			td.style.backgroundColor = td.style.backgroundColor == ''? '#FFFFCC': '';
		if (tr.firstChild.style.backgroundColor == '') {
			var checked = this.CheckSelected(tbody);
			if (!checked && tbody == this.result && this.buttonadd) this.buttonadd.disabled = true;
			else if (!checked && tbody == this.selected && this.buttonremove) this.buttonremove.disabled = true;
		}
		else {
			if (tbody == this.result && this.buttonadd) this.buttonadd.disabled = false;
			else if (tbody == this.selected && this.buttonremove) this.buttonremove.disabled = false;
		}
	}
	this.focus = function() {
		if (this.search_input) this.search_input.focus();
	}
	
	
	
	if (this.mode == 'tree') {
		var divtree = this.content.appendChild(dc('div'));
		divtree.style.width = (width-5)+'px';
		divtree.style.height = (height-5)+'px';
		divtree.style.textAlign = 'center';
		divtree.style.verticalAlign = 'middle';
		divtree.style.overflow = 'auto';
		this.tree = new TreeView(divtree, IconList, IconDefault, 'Themes/', this.Relation.SearchClasses);
		this.tree.EnableCheckboxes = true;
		this.tree.HiddenInput = this.hiddeninput.value;
//		var rootchild = this.tree.AddChild(false,{link:'Themes/',name:'Themes',type:'Folder',childs:[]});
	}
	else if (this.mode == 'list') {
		//!
		//! Main table (2 cols)
		//!
		maintable = this.content.appendChild(dc('table'));
		maintable.style.width = '100%';
		
		//! First Row (1 cell: label, 1 cell: input)
		head = maintable.appendChild(dc('thead'));
		tr = head.appendChild(dc('tr'));
		td = tr.appendChild(dc('td'));
		td.style.width = '95px';
		td.appendChild(dt(Lang.Search));
		td = tr.appendChild(dc('td'));
		td.style.textAlign = 'left';
		this.search_input = td.appendChild(dc('input'));
		this.search_input.style.width = '280px';
		this.search_input.value = '';
		this.search_input.popup = this;
		this.search_input.onkeypress=function(e){if(GetKeyCode(e)==13)this.popup.search_button.onclick();}
		
		//!
		//! Second Row (type of query select)
		//!
	/*	tr = head.appendChild(dc('tr'));
		td = tr.appendChild(dc('td'));		
		td.appendChild(dt('Type: '));
		td = tr.appendChild(dc('td'));
		td.style.textAlign = 'left';
		var selec = td.appendChild(dc('select'));
		var option = selec.appendChild(dc('option'));
			option.value = '';
			option.selected = true;
			option.appendChild(dt('tous'));
		for (i in types) {
			var option = selec.appendChild(dc('option'));
			option.value = types[i];
			option.appendChild(dt(types[i]));
		}*/
		
	
		//!
		//! Third Row (1 cell spanned over 2 cols: search button)
		//!
		tr = head.appendChild(dc('tr'));
		td = tr.appendChild(dc('td'));
		td.colSpan = 2;
		td.style.textAlign = 'right';
		if (this.param.indexOf('n') == -1) {
			this.buttoncreate = td.appendChild(MakeInput({type:'button', value:this.Relation.NewInputName, searchpopup: this}));
			td.appendChild(dt('  '));
		}
		this.search_button = td.appendChild(MakeInput({type: 'button', value:Lang.Search, popup:this}));
		this.search_button.style.fontSize = '11px';
		this.search_button.onclick = function() {
			this.popup.Search();
		}
	
		/////////////////////////////////////////////////////////////////////
		//
		//	Begin of SELECTED ITEMS list
		//
		/////////////////////////////////////////////////////////////////////
		body = maintable.appendChild(dc('tbody'));
	
		if (this.param.indexOf('n') != -1) {
			td = body.appendChild(dc('tr')).appendChild(dc('td'));
			td.colSpan = 2;
			td.style.textAlign = 'left';
			td.appendChild(dt('Elements selectionne:'));
			td = body.appendChild(dc('tr')).appendChild(dc('td'));
			td.colSpan = 2;
			with (td.style){backgroundColor='white';borderColor='#EEEEEE';borderStyle='ridge';borderWidth='2px';padding='2px';}
			var tbl = td.appendChild(dc('table'));
			tbl.style.width = '100%';
			this.selected = tbl.appendChild(dc('tbody'));
		}
		
		/////////////////////////////////////////////////////////////////////
		//
		//	Begin of SEARCH RESULT ITEMS list
		//
		/////////////////////////////////////////////////////////////////////
		tr = body.appendChild(dc('tr'));
		td = tr.appendChild(dc('td'));
		with (td.style) {textAlign='left';verticalAlign='bottom';}
		td.appendChild(dt('Resultats de la recherche:'));
		if (this.param.indexOf('n') == -1)
			td.colSpan = 2;
		else {
			td.style.width = '150px';
			td = tr.appendChild(dc('td'));
			td.popup = this;
			with (td.style) {
				textAlign = 'right';
				paddingTop = '1px';
			}
			this.buttoncreate=td.appendChild(MakeInput({type:'button',value:this.Relation.NewInputName?this.Relation.NewInputName:'Nouveau '+this.relation,searchpopup:this}));
			td.appendChild(dt('  '));
			this.buttonadd = td.appendChild(MakeInput({type:'button',value:'Ajouter',disabled:'disabled'}));
			this.buttonadd.onclick = function() {
				for (tr = this.parentNode.popup.result.firstChild; tr; tr = tr.nextSibling)
					if (tr.firstChild.style.backgroundColor != '')
						this.parentNode.popup.DefaultAction(this.parentNode.popup.result, tr, tr.firstChild.itemId, tr.firstChild.ClassType);
			};
			
			td.appendChild(dt('  '));
			this.buttonremove = td.appendChild(MakeInput({type: 'button', value:'Retirer', disabled:'disabled'}));
			this.buttonremove.onclick = function() {
				for (exists=true; exists;) {
					exists=false;
					for (tr=this.parentNode.popup.selected.firstChild;tr;tr=tr.nextSibling)
						if (tr.firstChild.style.backgroundColor != '') {exists=tr.firstChild;break;}
					if (exists) if (!this.parentNode.popup.Remove(exists.itemId, exists.ClassType)) return ;
				}
			}
		}
		this.buttoncreate.onclick = function() {
			if (this.searchpopup.CreateFile) {
				this.searchpopup.CreateFile.focus();
				return;
			}
	//		alert('Creating new contact');
			this.searchpopup.hide();
			this.searchpopup.CreateFile = new Wizard('L\'iddri/', this.searchpopup.onCreate, 'Creation de contact/partenaire', [BrowsePage,ChooseType,ConfirmPage], 500, 250, this.searchpopup.Relation.SearchClasses);
			this.searchpopup.CreateFile.onClose = function() {
				this.searchpopup.CreateFile = false;
				this.searchpopup.show();
			}
			this.searchpopup.CreateFile.searchpopup = this.searchpopup;
		}
		/////////////////////////////////////////////////////////////////////
		//
		//	Begin of SEARCH RESULT ITEMS list
		//
		/////////////////////////////////////////////////////////////////////
	
		//! Fifth Row (selected, 1 cell spanned over 2 cols)
		td = body.appendChild(dc('tr')).appendChild(dc('td'));
		td.colSpan = 2;
		this.overflow = td.appendChild(dc('div'));
		this.overflow.style.width = (td.clientWidth-4)+'px';
		with (this.overflow.style){backgroundColor='white';overflow='auto';borderColor='#EEEEEE';borderStyle='ridge';borderWidth='2px';padding='2px';}
		var tbl = this.overflow.appendChild(dc('table'));
		tbl.style.width = '100%';
		tbl.style.height = '0px';
		
		this.result = tbl.appendChild(dc('tbody'));
		var tr = this.result.appendChild(dc('tr'));
		var td = tr.appendChild(dc('td'));
		td.style.height = '0px';
	}	// end of if (mode == 'list')
	
	/////////////////////////////////////////////////////////////////////
	//
	//	Begin of FOOTER button row
	//
	/////////////////////////////////////////////////////////////////////

	this.Apply = function() {
		if (this.mode == 'tree') {
			this.hiddeninput.value = this.tree.HiddenInput;
			
		}
		else if (this.mode == 'list') {
			var nmode = this.param.indexOf('n')!=-1? true: false;
			var str = '';
			var t = '';
			if (nmode) {
				var list = this.ListSelected;var types = [];
				for (i in list) {
					if (!types[list[i].ClassType])types[list[i].ClassType]=[];types[list[i].ClassType].push(list[i].id);
					var p = '';for(g in this.Relation.LinkConcatFields)p+=(p?' ':'')+list[i][this.Relation.LinkConcatFields[g]];
					str += (str? this.Relation.LinkSeparator: '')+p;
				}
				for(i in types)if(types[i].length){t+=(t? '|': '')+i+':'+types[i].join(',');}
			}
			else {
				for (tr=this.result.firstChild;tr;tr=tr.nextSibling) if (tr.firstChild.style.backgroundColor != '') {
					var obj=false;
					for(i in this.ListResult)if(this.ListResult[i].id==tr.firstChild.itemId&&this.ListResult[i].ClassType==tr.firstChild.ClassType){obj=this.ListResult[i];break;}
					str='';for(i in this.Relation.LinkConcatFields)str+=(str?' ':'')+obj[this.Relation.LinkConcatFields[i]];
					t=tr.firstChild.ClassType+':'+tr.firstChild.itemId;
					this.hiddeninput.row = obj;
					break ;
				}
			}
			this.hiddeninput.value = t;
			if(this.link){var node=this.link;node.innerHTML=str?str:(this.param.indexOf('n')==-1?this.Relation.LinkEmpty1:this.Relation.LinkEmptyN);}
			if (!nmode && this.link && this.hiddeninput.value)this.AddDeleteButton();
		}
		this.Window.Close();
		jQuery(this.hiddeninput).change();
	}
	this.okbutton = this.Window.AddButton('OK');
	this.okbutton.onclick = function() {
		this.popup.Apply();
	}
	this.cancelbutton = this.Window.AddButton('Annuler');
	this.cancelbutton.onclick = function() {
		this.popup.Window.Close();if(typeof(this.popup.onClose)=='function')this.popup.onClose();
	}
	this.Window.visibility(true);
	if (this.mode == 'list' && this.param.indexOf('n')!=-1) {
		if (this.hiddeninput.value) {
			this.Ajax.onReceive = function(status, xml, text) {
				this.popup.ListSelected = this.popup.ListXml(xml);
				this.popup.ShowResult(this.popup.selected, this.popup.colnames, this.popup.ListSelected);
				this.popup.Window.resize();
			}
			var query = '?xml&list='+this.Relation.SearchClasses.join('|')+'&filter='+this.hiddeninput.value;
			this.Ajax.query('GET', query, true);
		}
		else {
			this.ShowResult(this.selected, this.colnames, []);
			this.Window.resize();
		}
	}
	this.focus();
}
