var filterCount = 0;
var criteria = new Array();
var relations = new Array();
criteria[0] = new Array('Nom d\'organisation', 'CompanyName');
criteria[1] = new Array('Recherche plein texte', 'full');
criteria[2] = new Array('Texte', 'body.content');
criteria[3] = new Array('Titre', 'title');
criteria[4] = new Array('Date', 'FirstCreated');
criteria[5] = new Array('Symbol boursier', 'StockSymbol');
criteria[6] = new Array('Lieu', 'GeographyCode');
criteria[7] = new Array('Secteur d\'activit&#233;', 'IndustryCode');
criteria[8] = new Array('Sujet', 'SubjectCode');
relations['full'] =				new Array(new Array('contenant l\'expression exacte', 'in'), new Array('contenant tous les mots', 'and'), new Array('contenant l\'un des mots', 'or'));
relations['body.content'] =	new Array(new Array('contenant l\'expression exacte', 'in'), new Array('contenant tous les mots', 'and'), new Array('contenant l\'un des mots', 'or'));
relations['title'] =				new Array(new Array('contenant l\'expression exacte', 'in'), new Array('contenant tous les mots', 'and'), new Array('contenant l\'un des mots', 'or'));
relations['CompanyName'] =		new Array(new Array('contenant', 'in'), new Array('est', 'matches'), new Array('commen&ccedil;ant par', 'starts'), new Array('finissant par', 'ends'));
relations['FirstCreated'] =	new Array(new Array('le', '='), new Array('le ou apr&#232;s le', '>='), new Array('le ou avant le', '<='));
relations['StockSymbol'] =		new Array(new Array('dont le nom est', 'in'));
relations['GeographyCode'] =	new Array(new Array('dont le nom est', 'in'));
relations['IndustryCode'] = 	new Array(new Array('dont le nom est', 'in'));
relations['SubjectCode'] = 	new Array(new Array('dont le nom est', 'in'));

var cal = new CalendarPopup("calendarDiv");

// Set the month names to be used. Default are English month names
cal.setMonthNames('January','February','March','April','May','June','July','August','September','October','November','December');

// Set the month abbreviations to be used. Default are English month
// abbreviations
cal.setMonthAbbreviations('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');

// Show navigation for changing by the year, not just one month at a time
//cal.showYearNavigation();

// Show month and year dropdowns, for quicker selection of month of dates
cal.showNavigationDropdowns();

// Set the text to be used above each day column. The days start with 
// sunday regardless of the value of WeekStartDay
//cal.setDayHeaders("S","M","T",...);

// Pass null as the first parameter to mean "anything up to and including" the
// passed date:
//cal.addDisabledDates(null, "01/02/03");
// Pass null as the second parameter to mean "including the passed date and
// anything after it:
//cal.addDisabledDates("Jan 01, 2003", null);
// Pass two dates to disable all dates inbetween and including the two
//cal.addDisabledDates("January 01, 2003", "Dec 31, 2003");

// When the 'year' select is displayed, set the number of years back from the 
// current year to start listing years. Default is 2.
// This is also used for year drop-down, to decide how many years +/- to
// display
//cal.setYearSelectStartOffset(2);

// Text for the word "Today" appearing on the calendar
cal.setTodayText("Today");

function CreateFilterHTML(i, c, r, v)
{
	// Creates the HTML for a filter line
	// First sort out the pre-existing values if set or passed in as a
	// parameter
	c = (c) ? c : getValueOf('c'+i);
	r = (r) ? r : getValueOf('r'+i);
	v = (v) ? v : getValueOf('v'+i);
	// start constructing the necessary HTML
	var html = "<table id=\"filter"+i+"\" class=\"inputs\">\n\t<tr>\n";
	// open the c select field
	html += "\t\t<td class=\"filter\"><select class=\"searchField\" id=\"c"+i+"\" name=\"c"+i+"\" onChange=\"PopulateRelations("+i+", '"+c+"', '"+r+"')\">\n";
	//html += "\t\t\t<option value=\"\">Recherche par :</option>\n";
	// fill with the available search criteria (global array criteria)
	for (var j in criteria) {
		// if the c has been previously set, select it
		if (criteria[j][1] == c) {html += "\t\t\t<option value=\""+criteria[j][1]+"\" selected=\"true\">"+criteria[j][0]+"</option>\n";}
		else{html += "\t\t\t<option value=\""+criteria[j][1]+"\">"+criteria[j][0]+"</option>\n";}
		}
	// close c select field
	html += "\t\t</select></td>\n";
	
	// stub out r select box
	html += "\t\t<td class=\"filter\">";
	// if the r has been previously set, populate and select it
	html += CreateRelationHTML(i, c, r);
	html += "</td>\n";
	
	// stub out the value field
	html += "\t\t<td class=\"filter\">";
    html += CreateQueryHTML(i, c, r, v);
	html += "</td>\n";
	// add the add/remove buttons
	html += "\t\t<td class=\"filter\"><input id=\"add"+i+"\" class=\"add\" type=\"button\" name=\"Add\" value=\"+\" onClick=\"AddFilter()\" />&nbsp;";
	html += "<input id=\"remove"+i+"\" class=\"remove\" type=\"button\" name=\"Remove\" value=\"x\" onClick=\"RemoveFilter("+i+")\" /></td>\n";
  	html += "\t</tr>\n</table>\n";
	return html;
}


function CreateQueryHTML(i, c, r, v)
{
	// initialize html
	var html = '';
	// make sure we have a v value
	v = (v) ? v : getValueOf('v'+i);
	// get the list of options for Subject and Industry codes
	if (c == 'SubjectCode' || c == 'IndustryCode' || c == 'GeographyCode') {
		html = "<select name=\"v"+i+"\" id=\"v"+i+"\" class=\"searchField\">\n";
		var optionsList = GetOptionsList(c);
		var string = 'value="'+v+'"';
		var pattern = new RegExp(string);
		optionsList = optionsList.replace(pattern, string+' selected="selected"');
		if(optionsList) {html += optionsList;}
		html += "\t\t</select>\n";
		return html;
	}
	if(c == 'FirstCreated' && !v.match(/^\d{4}\/\d{2}\/\d{2}$/)) { v = '';}
	if (v) {html = "<input class=\"searchField\" id=\"v"+i+"\" name=\"v"+i+"\" type=\"text\" value=\""+v+"\" />"+html;}
	else {html = "<input class=\"searchField\" id=\"v"+i+"\" name=\"v"+i+"\" type=\"text\" value=\"\" />"+html;}
	if (c == 'FirstCreated') {
		html = '<a href="JavaScript:void(0);" onClick="cal.select(document.searchForm.v'+i+',\'v'+i+'\',\'yyyy/MM/dd\'); return false;">'+html+'</a>';
	}
	return html;
}

function getValueOf(id)
{
	// Returns the value of a form element given it's id
	var obj = document.getElementById(id);
	var value;
	if (obj == null) {return value;} // returns undefined if object is not valid
	if (obj.nodeName.match('SELECT')) {
		// returns the value of a select box
		if(obj.selectedIndex > -1) {value = obj.options[obj.selectedIndex].value;}
	}
	else {value = obj.value} // returns the value of an input box
	return value;
}

function AddFilter(c, r, v)
{
	filterCount++;
	var html ='';
	for (var j = 0; j < filterCount; j++) {html += CreateFilterHTML(j, c, r, v);}
	var obj = document.getElementById('filters');
	obj.innerHTML = html;
}

function RemoveFilter(i)
{
	if(filterCount == 1) {alert('Vous ne pouvez supprimer le seul crit&#232;re de recherche restant'); return;}
	var filter = document.getElementById('filter'+i);
	filter.parentNode.removeChild(filter);
	filterCount--;
}

function PopulateRelations(i, c, r)
{
	var obj = document.getElementById('c'+i);
	var c = obj[obj.selectedIndex].value;
	var html = CreateRelationHTML(i, c, r);
	obj = document.getElementById('r'+i);
	var rParent = obj.parentNode;
	rParent.innerHTML = html;
	html = CreateQueryHTML(i, c, r, '');
	obj = document.getElementById('v'+i);
	var vParent = obj.parentNode;
	if(vParent.nodeName == 'A') {vParent = vParent.parentNode;}
	vParent.innerHTML = html;
}

function CreateRelationHTML(i, c, r)
{
	// Returns r option values
	var html = "<select class=\"searchField\" id=\"r"+i+"\" name=\"r"+i+"\">\n";
	c = c || 'CompanyName';
	for (var j in relations[c]) {
		var selected = '';
		if (relations[c][j][1] == r) {selected = ' selected="true"';}
		html += "\t\t<option value=\""+relations[c][j][1]+'"'+selected+'>'+relations[c][j][0]+"</option>\n";
	}
	html += "\t\t</select>";
	return html;
}

function GetOptionsList(type)
{

	var oRequest = AJAXRequest();
	if(oRequest) {
		var sURL = "http://"+self.location.hostname+"/includes/"+type+".fr.list";
		oRequest.open("GET",sURL,false);
		oRequest.setRequestHeader("User-Agent",navigator.userAgent);
		oRequest.send(null)
		if (oRequest.status==200) return (oRequest.responseText);
	}
	return false;
}
