HXRpage = 'query.php';
markers = [];
infowindows = [];
filters = [];
mc = null;
showMarketClusterer = false;

// array_unique function from http://www.wait-till-i.com/2007/08/08/simulating-array_unique-in-javascript/
function array_unique(ar) {
	if(ar.length && typeof ar!=='string'){
		var sorter = {};
		var out = [];
		for(var i=0,j=ar.length;i<j;i++){
			if(!sorter[ar[i]+typeof ar[i]]){
				out.push(ar[i]);
				sorter[ar[i]+typeof ar[i]]=true;
			}
		}
	}
	return out || ar;
}

function g41Menu() {

	this.menuID = '#map_menu';
	this.groupID = '#map_submenu_group';
	this.orderID = '#map_submenu_order';
	this.legendID = '#map_submenu_legend';
	this.itemsID = '#map_submenu_items';
	this.itemslistID = '#map_submenu_items_list';
	this.itemslegendID = '#map_submenu_items_legend';

	this.clients = [];
	this.projects = [];
	this.groups = [];
	this.orders = [];
	this.items = [];

	this.setProjects = function(data) {
		this.projects = data;
		this.buildMenu(data, {'id':'g41_project_id', 'label':'g41_project_name'}, 'select', this.menuID, {'label':'Projet'});
		return this;
	};

	this.setOrders = function(data) {
		this.orders = data;
		this.buildMenu(data, {'id':'id', 'label':'label'}, 'select', this.orderID, {'label':'Ordre'});
		return this;
	};

	this.setGroups = function(data) {
		this.groups = data;
		this.buildMenu(data, {'id':'id', 'label':'label'}, 'select', this.groupID, {'label':'Groupe'});
		return this;
	};

	this.setItems = function(data, groups) {
		if (data!=null) {

			if (data.length==0) {
				jQuery(this.itemsID).hide('slow', function() {
					jQuery(this.itemslegendID).hide('slow');
				});
			} else {
				this.items = data;

				switch (this.items.length) {
					case 1:
						jQuery(this.itemslegendID).html('Un seul élément à afficher:');
					break;
					default:
						jQuery(this.itemslegendID).html(this.items.length+' éléments à afficher:');
					break;
				}

				html = '<ul>';
				//console.log(groups);
				groups.count = [];
				var globcount = 0;

				for (d in data) {
					var vern = data[d].nom_vern;

					for (g in groups.values) {
						if (groups.values[g] == vern) {
							if (typeof groups.count[g] == 'undefined') {
								groups.count[g] = 1;
							} else {
								groups.count[g]++;
							}
							globcount++;
						}
					}
				}

				//console.log(groups, globcount);

				for (g in groups.values) {
					var name = groups.values[g];
					if (name=="") name = "Non-renseigné";
					html += '<li><input type="checkbox" id="'+encodeURIComponent(groups.field+groups.values[g])+'" value="'+groups.values[g]+'" />&nbsp;<label for="'+encodeURIComponent(groups.field+groups.values[g])+'">'+name+' ('+groups.count[g]+')</label></li>';
				}

				html += '</ul>';

/*
				this.buildMenu(
					this.items,
					{'id':'markerlegend', 'label':'nom_scie'},
					'list',
					this.itemslistID,
					{}
				);
*/
				jQuery(this.itemslistID).html(html);

				jQuery(this.itemslistID+' input[type="checkbox"]').live('change', function() {

					switch (jQuery(this).attr('checked')) {
						case true:
							g41Map.showPoints(data, {'field': groups.field, 'value':jQuery(this).val()});
						break;

						case false:
							g41Map.clearPoints({'field': groups.field, 'value':jQuery(this).val()});
						break;
					}
				});

				//jQuery(this.itemslegendID).show('slow');
				jQuery(this.itemsID).show('slow').removeClass('hidden');
			}
		} else {
			// data is null
			this.items = [];
			jQuery(this.itemsID).hide('slow');
		}

		return this;
	};

	this.buildMenu = function(list, fields, el, id, o) {

		switch (el) {
			case 'select':
				el = {'parent':'select', 'child':'option'};
			break;

			case 'list':
			default:
				el = {'parent':'ul', 'child':'li'};
			break;

			case 'checkbox':
				el = {'parent':'ul', 'child':'li'};
			break;
		}

		jQuery(id).html(
			this.buildList(
				list,
				fields,
				el,
				o
			)
		);
		this.clearLegend();

		// sélectionner automatiquement un élément de menu si il est unique... pas encore au point
		/*
		if (list.length==1) {
			jQuery(id).children('option:last').select();
		}
		*/

		return this;
	};

	/**
	 * param list is an array of objects
	 * param fields is a descriptive object containing field names to read from the list
	 * param el defines the html elements to use: {'parent':'ul', 'child':'li'}
	**/
	this.buildList = function(list, fields, el, o) {

		if (list==null || fields.id == null || fields.label == null || el == null) return false;
		if (o==null || !o) o = {'label':null};

		html = '<' + el.parent + ' id="' + fields.id + '">' + "\r\n";

		label = (o.label==null)? 'Sélection...': o.label;
		if (el.parent=='select') {
			html += '<option>'+label+'</option>' + "\r\n";
			html += '<option id="'+fields.id+'_0">TOUS</option>' + "\r\n";
		}
		for (i in list) {
			var id = i;
			html += '<' + el.child + ' id="' + fields.id + '_' + list[i][fields.id] +'">' + list[i][fields.label] + '</' + el.child + '>' + "\r\n";
		}

		html += '</' + el.parent + '>' + "\r\n";

		return html;
	};

	this.clearLegend = function() {
		jQuery(this.legendID).html('');
	};

}


function g41Map() {

	this.hasMap = false;

	this.mapID = 'map_canvas';
	this.latlng = [45.058001, 2.812500];
	this.zoom = 8;
	this.mapType = google.maps.MapTypeId.TERRAIN;
	this.bounds = new google.maps.LatLngBounds();
	
	this.map; // objet map
	this.mc; // objet cluster

	this.protectdata;


	// Initialisation du fond de carte
	this.setupMap = function() {
		if (this.hasMap) return this;

		var myLatlng = new google.maps.LatLng(this.latlng[0], this.latlng[1]);
		var myOptions = {
			zoom: this.zoom,
			center: myLatlng,
			mapTypeId: this.mapType,
			disableDefaultUI: true
		};
		this.map = new google.maps.Map(document.getElementById(this.mapID), myOptions);

		this.hasMap = true;
		this.setupCustomControls();
		return this;
	};

	// supprimer les contrôles par défaut et ajouter les contrôles personnalisés
	this.setupCustomControls = function() {
		var map = this.map;
		var that = this;

		var controls = {
			'zoom_in': document.getElementById('map_control_zoom_in'),
			'zoom_out': document.getElementById('map_control_zoom_out'),
			'maptype_satellite': document.getElementById('map_control_maptype_satellite'),
			'maptype_terrain': document.getElementById('map_control_maptype_terrain'),
			'maptype_hybrid': document.getElementById('map_control_maptype_hybrid'),
			'maptype_roadmap': document.getElementById('map_control_maptype_roadmap')
		};

		google.maps.event.addDomListener(controls.zoom_in, 'click', function() {
			var zoom = map.getZoom();
			zoom++;
			map.setZoom(zoom);
		});

		google.maps.event.addDomListener(controls.zoom_out, 'click', function() {
			var zoom = map.getZoom();
			zoom--;
			map.setZoom(zoom);
		});
		
		google.maps.event.addDomListener(controls.maptype_satellite, 'click', function() {
			map.setMapTypeId(google.maps.MapTypeId.SATELLITE);
		});

		google.maps.event.addDomListener(controls.maptype_terrain, 'click', function() {
			map.setMapTypeId(google.maps.MapTypeId.TERRAIN);
		});

		google.maps.event.addDomListener(controls.maptype_hybrid, 'click', function() {
			map.setMapTypeId(google.maps.MapTypeId.HYBRID);
		});

		google.maps.event.addDomListener(controls.maptype_roadmap, 'click', function() {
			map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
		});

		jQuery('#map_control_maptype span').live('click', function() {
			jQuery('#map_control_maptype span').removeClass('highlight');
			jQuery(this).addClass('highlight');
		});
	};

	this.clearPoints = function(filter) {
		if (!filter) {
			if (markers) {
				for (i in markers) {
					markers[i].setMap(null);
					infowindows[i] = null;
					markers[i].active = false;
				}
				markers.length = 0;
				infowindows.length = 0;
			}
			this.bounds = new google.maps.LatLngBounds();
		} else {
			for (i in markers) {
				if (markers[i][filter.field]!=filter.value) continue;
				markers[i].setMap(null);
				infowindows[i] = null;
				markers[i].active = false;
			}
		}

		return this;
	};

	this.setPoints = function(data, field) {
		var f = field || 'nom_vern';
		this.points = data;
		g41Menu.setItems(
			data,
			{'field': f, 'values':this.groupBy(this.points, f)}
		);
		return this;
	};


	this.groupBy = function (data, field) {
		var out = [];
		for (d in data) out.push(data[d][field]);
		return array_unique(out);
	};


	this.showPoints = function(data, filter) {
		this.setupMap();
		var map = this.map;
		var bounds = this.bounds;
		//var mcOptions = { gridSize: 50, maxZoom: 15};

		for(var i=0; i < data.length; i++) {

			if (data[i][filter.field] != filter.value) continue;

			data[i].markerlegend = i;

			var point = new google.maps.LatLng(data[i].geo.latitude, data[i].geo.longitude);
			var info = this.formatInfo(data[i]);
			var datamarker = data[i];

			this.addListItem(data[i]);
			bounds.extend(point);

			var marker = new google.maps.Marker({
				'data': datamarker,
				'position': point,
				'map': map,
				'animation': google.maps.Animation.DROP,
				'icon': this.getIcon(data[i].nom_scie)//,
				/*'title': title*/
			});

			marker['infowindow'] = new google.maps.InfoWindow({
				content: info,
				item_id: data._id
			});
			marker['opened'] = false;
			marker[filter.field] = filter.value;
			marker.active = true;

			google.maps.event.addListener(marker,'mouseover', function() {
				if (!this['opened']) this['infowindow'].open(map,this);
				//jQuery('#markerlegend li#markerlegend_'+i).addClass('highlight');
			});

			google.maps.event.addListener(marker,'mouseout', function() {
				if (!this['opened']) this['infowindow'].close(map,this);
				//jQuery('#markerlegend li#markerlegend_'+i).removeClass('highlight');
			});

			google.maps.event.addListener(marker,'click', function() {
				switch (this['opened']) {
					case false:
						this['infowindow'].open(map,this);
						this['opened'] = true;
					break;
					case true:
						this['infowindow'].close(map,this);
						this['opened'] = false;
					break;
				}
			});

			markers.push(marker);
			//this.filterPoints();
		}

		//g41Menu.setItems(data);

		this.map.fitBounds(bounds);
		this.filterPoints();
	};

	this.formatInfo = function(data) {
		var html = '';
		html += '<div class="infowindow">';
		// @TODO améliorer la gestion des champs absents
		if (typeof data.nom_vern!='undefined' && data.nom_vern && data.nom_vern!="") html += '<strong>' + data.nom_vern + '</strong><br />';
		if (typeof data.nom_scie!='undefined' && data.nom_scie && data.nom_scie!="") html += '<em>' + data.nom_scie + '</em><br />';
		if (typeof data.famille!='undefined' && data.famille && data.famille!="") html += data.famille + '<br />';
		if (typeof data.date!='undefined' && data.date && data.date!="") html += 'Observé le ' + this.formatDate(data.date);
		if (typeof data.observateur!='undefined' && data.observateur && data.observateur!={} && data.observateur.nom!="") html += '<br />par ' + data.observateur.nom;
		if (typeof data.observateur_assoc!='undefined' && data.observateur_assoc && data.observateur_assoc!={} && typeof data.observateur_assoc.nom!='undefined') html += ' et ' + data.observateur_assoc.nom;
		if (typeof data.age!='undefined' && data.age && data.age!='Indéterminé') html += '<br />Âge: ' + data.age;
		if (typeof data.reprod!='undefined' && data.reprod && data.reprod!='nul') html += '<br />Statut reproduction: ' + data.reprod;
		if (typeof data.commentaire!='undefined' && data.commentaire && data.commentaire!='') html += '<br />Commentaire: ' + data.commentaire;
		html += '<br />'+this.formatProtectinfo(data.nom_scie);
		html += '</div>';
		return html;
	};

	this.formatProtectinfo = function(nom_scie) {
		if (nom_scie==null || nom_scie=="") return false;
		var html = "";
		for (p in this.protectdata) {
			if (this.protectdata[p]['nom_scie']!=nom_scie) continue;
			
			if (this.protectdata[p]['NAT']=='1') html += 'Protection Nationale; ';
			if (this.protectdata[p]['EU1']=='1') html += 'Annexe EU1; ';
			if (this.protectdata[p]['EU2']=='1') html += 'Annexe EU2; ';
			if (this.protectdata[p]['EU4']=='1') html += 'Annexe EU4; ';
			if (this.protectdata[p]['INV']=='1') html += 'INVASIVE';
		}

		if (html != "" && html != 'INVASIVE') html = 'Sous '+html;
		return html;
	};

	this.formatDate = function (date) {
		var parts = date.split('-');
		html = parts[1]+'/'+parts[0];
		return html;
	};

	this.formatTitle = function(data) {
		html = '';
		return html;
	};

	this.addListItem = function(data) {
		html = '';
		return html;
	};

	this.showLayer = function(id) {
		if (id=="Herault") { 
			KMLLayer = new google.maps.KmlLayer('http://biodata.gaiadomo.com/kml/Herault.kml');
			//KMLLayer2 = new google.maps.KmlLayer('http://biodata.dev.maellio.com/kml');
			
			KMLLayer.setMap(this.map);
			//KMLLayer2.setMap(this.map);
			//console.log(KMLLayer2);
		} else {
			if (typeof KMLLayer == "object") {
				KMLLayer.setMap(null);
			}
		}
	};

	this.toggleMarkerClusterer = function() {
		showMarketClusterer = !showMarketClusterer;
		if (showMarketClusterer) {
			if (mc) {
				mc.addMarkers(markers);
			} else {
				mc = new MarkerClusterer(this.map, markers, {maxZoom: 17});
			}
		} else {
			for (m in markers) {
				console.log(markers[m], this.map);
				markers[m].setMap(this.map);
			}
			mc.clearMarkers();
		}
	};

	this.setProtect = function(data) {
		this.protectdata = data;
		return this;
	};

	this.getIcon = function(nom_scie) {
		var ico = 'Lightgreen';
		var baseurl = 'img/';

		for (p in this.protectdata) {
			if (this.protectdata[p]['nom_scie']!=nom_scie) continue;
			
			if (this.protectdata[p]['NAT']=='1') ico = 'Blue';
			if (this.protectdata[p]['EU1']=='1') ico = 'Yellow';
			if (this.protectdata[p]['EU2']=='1') ico = 'Orange';
			if (this.protectdata[p]['EU4']=='1') ico = 'Red';
			if (this.protectdata[p]['INV']=='1') ico += 'INV';
		}

		ico += '.png';
		return baseurl+'marker'+ico;
	};

	this.filterPoints = function() {
		// o = {'field':'INV', 'status':true};
		this.updateFilters();
		//console.log(filters);

		var fc = 0;
		for (pfc in filters) {
			if (filters[pfc].value=='1') fc++;
		}
		//console.log(fc);
		if (fc==0) {
			for (m in markers) {
				if (markers[m].active) {
					markers[m].setMap(this.map);
				} else {
					markers[m].setMap(null);
					//console.log(markers[m].data.nom_vern);
					continue;
				}
			}
			return this;
		}

		for (m in markers) {

			var data = markers[m].data;
			var marker = markers[m];

			for (p in this.protectdata) {
				if (this.protectdata[p]['nom_scie']!=data.nom_scie) continue;
				//console.log(data.nom_scie, this.protectdata[p]['nom_scie']);
				var c = 0;

				for (f in filters) {
					var filter = filters[f];
					if (filter.value!='1') continue;
					//console.log(data.nom_scie, this.protectdata[p][filter.field]==filter.value);
					if (this.protectdata[p][filter.field]==filter.value) c++;
				}

				if (c>0 && marker.active) {
					marker.setMap(this.map);
					//marker.active = true;
				} else {
					marker.setMap(null);
					//marker.active = false;
				}

			}
		}

	};

	this.updateFilters = function() {
		filters = [];
		jQuery('#map_submenu_filter_prot input').each(function() {
			var val = jQuery(this).attr('checked')? '1': '0';
			filters.push({'field':jQuery(this).val(), 'value':val});
		});
	};


}


function g41UI() {
	
	this.containerID = '#container';
	this.blocks = {};

	this.addBlock = function(html, id) {
		jQuery(this.containerID).append(html);
		this.watchBlock(id);
	};

	this.watchBlock = function(id) {
		jQuery('.blocktitle').live('click', function() {
			g41UI.toggleBlock(jQuery(this).parent('.g41block').attr('id'));
		});
	};

	this.toggleBlock = function(id) {
		var block = jQuery('#'+id);
		var title = block.children('.blocktitle');
		if (title.hasClass('folded')) {
			// unfold
			jQuery(block).animate({
				top: jQuery(block).data('toporigin')
			});
		} else {
			// fold
			jQuery(block).data('toporigin', jQuery(block).css('top'));
			jQuery(block).animate({
				'top': '95%'
			});
		}
	};
}

function g41Import() {

	this.tableID = '#preimportcontainer';
	this.data = [];
	this.o = {
		'header': true
	};

	var that = this;

	this.fields = {
		'groupe':{
			'id': 'groupe',
			'label': 'Groupe',
			'type': 'string',
			'format': null,
			'mandatory': true
		},
		'ordre': {
			'id': 'ordre',
			'label': 'Ordre',
			'type': 'string',
			'format': null,
			'mandatory': true
		},
		'nom_vern':{
			'id': 'nom_vern',
			'label': 'Nom vernaculaire',
			'type': 'string',
			'format': null,
			'mandatory': false
		},
		'nom_scie':{
			'id': 'nom_scie',
			'label': 'Nom binominal',
			'type': 'string',
			'format': null,
			'mandatory': true
		},
		'famille':{
			'id': 'famille',
			'label': 'Famille',
			'type': 'string',
			'format': null,
			'mandatory': false
		},
		'age':{
			'id': 'age',
			'label': 'Âge',
			'type': 'string',
			'format': null,
			'mandatory': false
		},
		'reprod':{
			'id': 'reprod',
			'label': 'Statut reproduction',
			'type': 'string',
			'mandatory': false,
			'format': function (str) {
				if (str=='' || str=='nul' || str=='Indeterminé') {
					return 'Indeterminé';
				} else {
					return str;
				}
			}
		},
		'commentaire':{
			'id': 'commentaire',
			'label': 'Commentaire',
			'type': 'string',
			'format': null,
			'mandatory': false
		},
		'date':{
			'id': 'date',
			'label': 'Date',
			'type': 'string',
			'o': { 'split':'/', 'y':2, 'm':1, 'd':0 },
			'mandatory': false,
			'format': function(str) {
				var p = str.split(that.fields.date.o.split);
				return p[that.fields.date.o.y]+'-'+p[that.fields.date.o.m]+'-'+p[that.fields.date.o.d];
			}
		},
		'nbr':{
			'id': 'nbr',
			'label': 'Quantité',
			'type': 'int',
			'mandatory': false,
			'format': function (str) { return parseInt(str); }
		},/*
		'g41_project_id':{
			'id': 'g41_project_id',
			'label': 'ID du projet',
			'type': 'int',
			'format': null
		},*/
		'geo':{
			'id': 'geo',
			'label': 'Coordonnées géographiques',
			'type': 'object',
			'o': {'split':' ', 'lat':0, 'lng':1},
			'mandatory': false,
			'format': function(str) {
				var parts = str.split(that.fields.geo.o.split);
				for (p in parts) { parts[p] = that.fields.geo.subfields.latitude.format(parts[p]); }
				return {'geo.latitude': parts[that.fields.geo.o.lat], 'geo.longitude': parts[that.fields.geo.o.lng]};
			},
			'mandatory': true,
			'subfields': {
				'latitude':{
					'id': 'geo.latitude',
					'label': 'Latitude',
					'type': 'float',
					'format': function(str) {
						if (str.indexOf(',')!='-1') {
							return str.replace(',','.');
						} else {
							return str;
						}
					}
				},
				'longitude':{
					'id': 'geo.longitude',
					'label': 'Longitude',
					'type': 'float',
					'format': function(str) {
						if (str.indexOf(',')!='-1') {
							return str.replace(',','.');
						} else {
							return str;
						}
					}
				}
			}
		},
		'observateur':{
			'id': 'observateur',
			'label': 'Observateur',
			'type': 'object',
			'mandatory': false,
			'format': function(str) {
				var parts = str.split(' ');
				return {'nom': parts[0], 'prenom': parts[1]};
			},
			'subfields': {
				'nom':{
					'id': 'observateur.nom',
					'label': 'Nom',
					'type': 'string',
					'format': null
				},
				'prenom':{
					'id': 'observateur.prenom',
					'label': 'Prénom',
					'type': 'string',
					'format': null
				}
			}
		},
		'observateur_assoc':{
			'id': 'observateur_assoc',
			'label': 'Observateur associé',
			'type': 'object',
			'mandatory': false,
			'format': function(str) {
				var parts = str.split(' ');
				return {'nom':parts[0], 'prenom':parts[1]};
			},
			'subfields': {
				'nom':{
					'id': 'observateur_assoc.nom',
					'label': 'Nom',
					'type': 'string',
					'format': null
				},
				'prenom':{
					'id': 'observateur_assoc.prenom',
					'label': 'Prénom',
					'type': 'string',
					'format': null
				}
			}
		}
	};

	this.setData = function(data) {
		this.data = data;
		return this;
	};

	this.dump = function() {
		this.saveHeader();
		jQuery(this.tableID).html(this.formatDump());
		this.setupHeader();
		return this;
	};

	this.formatDump = function() {
		var rows = this.data.length;
		var cols = this.data[0].length;
		//console.log(rows, cols);

		html = '<table id="preimport">';

		for (i in this.data) {
			html += '<tr>';

			// première ligne, et contient les entêtes
			if (i == 0 && this.o.header==true) {
				var headers = this.data[i];
				
				for (h in headers) {
					var id = 'preimporth_'+h;
					html += '<th id="'+id+'">'+headers[h]+'</th>';
				}
			// première ligne, ne contient pas les entêtes
			} else if (i==0 && this.o.header==false) {

				for (h=0;h<cols;h++) {
					var id = 'preimporth_'+h;
					html += '<th id="'+id+'">'+h+'</th>';
				}
				html += '<tr>';
				for (j in this.data[i]) {
					html += '<td>'+this.data[i][j]+'</td>';
				}
				html += '</tr>';

			// toute les autres lignes
			} else {

				for (j in this.data[i]) {
					html += '<td>'+this.data[i][j]+'</td>';
				}
			}

			html += '</tr>';
		}

		html += '</table>';
		return html;
	};

	this.saveHeader = function() {
		this.backupSelect = [];
		var that = this;
		jQuery(this.tableID + ' th select').each(function() {
			var id = jQuery(this).attr('id');
			var value = jQuery(this).children('option:selected').attr('value')
			that.backupSelect[id] = value;
		});
	};

	this.setupHeader = function() {
		var that = this;
		jQuery(this.tableID + ' th').each(function() {
			var html = jQuery(this).html();
			jQuery(this).html(
				html+that.headerSelect(
					jQuery(this).attr('id')
				)
			);
		});
	};

	this.headerSelect = function(id) {
		var ids = id+'_select';

		var html = '<select id="'+ids+'">';
		html += '<option value="null">Ignorer</option>';

		for (i in this.fields) {
			
			var lastState = this.backupSelect[ids] || 'null';
			var selected = (this.fields[i].id == lastState)? ' selected': '';
			var mandatory = (typeof this.fields[i].mandatory!='undefined' && this.fields[i].mandatory==true)? ' class="mandatory"' :' ';

			html += '<option'+mandatory+selected+' value="'+this.fields[i].id+'">'+this.fields[i].label+'</option>';

			if (typeof this.fields[i].subfields != 'undefined') {
				for (si in this.fields[i].subfields) {
					var selected = (this.fields[i].subfields[si].id == lastState)? ' selected': '';
					html += '<option'+selected+' value="'+this.fields[i].subfields[si].id+'">&nbsp;&nbsp;-&nbsp;'+this.fields[i].subfields[si].label+'</option>';
				}
			}
		}

		html += '</select>';
		return html;
		
	};

	this.parseTable = function() {
		this.tmpheader = this.parseSelect();
		//console.log(this.tmpheader);
		this.preimportData = this.rebuildData();
	};

	this.parseSelect = function() {
		var tmpheaders = new Array();

		jQuery(this.tableID + ' th select option:selected').each(function() {
			//console.log(jQuery(this).parent('select').attr('id'), jQuery(this).attr('value'));
			var id = jQuery(this).parent('select').attr('id');
			var parts = id.split('_');
			var col = parts[1];

			var tmp = { 'id': id,
						'value': jQuery(this).attr('value'),
						'col': col
					};
			tmpheaders.push(tmp);
		});
		return tmpheaders;
	};

	this.rebuildData = function() {
		var tmpdata = {};
		var field = {};
		//console.log(this.tmpheader);

		for (i in this.tmpheader) {
			if (this.tmpheader[i].value=='null') continue;

			for (f in this.fields) {
				if (this.fields[f].subfields) {
					for (sf in this.fields[f].subfields) {
						if (this.fields[f].subfields[sf].id != this.tmpheader[i].value) continue;
						field = this.fields[f].subfields[sf];
					}
				}
				if (this.fields[f].id != this.tmpheader[i].value) continue;
				field = this.fields[f];
			}


			for (j in this.data) {

				if ((j==0 && this.o.header==false) || j!=0) {

					if (!tmpdata[j]) tmpdata[j] = {};
					if (field.format==null) {
						tmpdata[j][ this.tmpheader[i].value ] = this.data[j][i];
					} else {
						tmpdata[j][ this.tmpheader[i].value ] = field.format(this.data[j][i]);
					}

					// si le nom du champ contient un point '.' on doit reconstruire l'objet qu'il décrit
					if (typeof this.tmpheader[i].value == 'string' && this.tmpheader[i].value.indexOf('.')!='-1') {
						var node = this.tmpheader[i].value.split('.');
						if (typeof tmpdata[j][ node[0] ] == 'undefined') tmpdata[j][ node[0] ] = {};
						tmpdata[j][ node[0] ][ node[1] ] = tmpdata[j][ this.tmpheader[i].value ];
						delete tmpdata[j][ this.tmpheader[i].value ];
					}
				}
			}
		}
		return tmpdata;
	};

	this.createProject = function() {
		var prequery = {
			'func':'createProject',
			'project': g41.import.project
		};

		jQuery.post(HXRpage, {"query":prequery}, function(data, textStatus, jqXHR) {
			var prerep = eval('('+data+')');

			switch(prerep.status) {
				case 'OK':
					console.log(prerep.project_id);
					this.new_project_id = prerep.project_id;
				break;

				case 'NOK':
					// afficher l'erreur
					alert(prerep.text);
				break;
			}
		});
	};

	this.canImport = function() {
		// vérifier les option mandatory
		var tmp = [];

		for (f in this.fields) {
			if (this.fields[f].mandatory==true) tmp.push(this.fields[f]);
		}

		jQuery('#preimport select option.mandatory').each(function() {
			if (jQuery(this).attr('selected')) {
				
				for (f in tmp) {
					if (jQuery(this).attr('id') == tmp[f].id) {}
				}
								
			}
		});

		return false;

		// vérifier le format des données

		// vérifier le reste du fichier de l'import via php
	};

	this.importData = function() {

		//if (g41.import.project.id==0) this.createProject();
		//console.log(g41.import.project.id);

		//if (!this.canImport()) /*console.log(this.error);*/ return false;

		if (g41.import.project.id!=0) {
			var projectid = g41.import.project.id;
			//console.log(projectid);

			var query = {
				'project_id': projectid,
				'func': 'importData',
				'headers': this.tmpheader,
				'file': g41.import.file,
				'ignorefirstline': this.o.header
			};

			jQuery.post(HXRpage, {"query":query}, function(data, textStatus, jqXHR) {
				var rep = eval('('+data+')');

				switch(rep.status) {
					case 'OK':
						alert(rep.text);
						//console.log(rep.test);
					break;

					case 'NOK':
						// afficher l'erreur
						alert(rep.text);
					break;
				}
			});
		}
	};

}

