application = {
	//application URL
	baseUrl : '',
	
	//Is the init search
	isFirstSearch : true,
	
	//Total number of data
	total : 0,
	
	//List of the lexique
	lexiqueList : [],
	
	//themeTree
	themeTree : [],
	isThemeFill: false,
	
	//placeTree
	placeTree: [],
	isPlaceFill: false,
	
	//is a admin connected ?
	isAdmin : false,
	adh_id: '',
	adh_isApproved: false,
	
	//id list to search (come from an import)
	initIdList: [],
	
	//default Values
	defaultValues : null,
	
	init: function() {
		application.getDefaultValues();
		application.getThemeTree();
		application.getPlaceTree();

		application.mapping.init();
		application.select.init();
		application.harvest.init();
		application.search.init();
		application.display.init();

		application.display.closeLoading();
		
		setInterval('application.getConservSession()', 600000);
		
	},
	
	getDefaultValues: function() {
		application.defaultValues = new application.result.Row();
	
		var defaults;
		
		var result = $.ajax({
			url:application.baseUrl + '/getDefault', 
			async: false,
			type: "GET",
			error: function (request, status, error) {
				application.display.dialog.errorDialog(request.status);
		    },
		    success: function (data, text) {
		    	defaults = eval("(" + data + ")");
		    	
		    }
			}).responseText;
		
		application.defaultValues.data.themes.values = defaults.themes;
		application.defaultValues.data.themes.isDefaultValue = true;
		application.defaultValues.data.geographie.values = defaults.geog;
		application.defaultValues.data.geographie.isDefaultValue = true;
		application.defaultValues.data.nature.values = defaults.nature;
		application.defaultValues.data.nature.isDefaultValue = true;
		application.defaultValues.data.niveauLecture.values = defaults.level;
		application.defaultValues.data.niveauLecture.isDefaultValue = true;
		
		application.defaultValues.data.owner.value = defaults.owner;
		application.defaultValues.data.owner.isDefaultValue = true;
		application.defaultValues.data.originator.value = defaults.originator;
		application.defaultValues.data.originator.isDefaultValue = true;
		application.defaultValues.data.publisher.value = defaults.publisher;
		application.defaultValues.data.publisher.isDefaultValue = true;
		application.defaultValues.data.contributor.value = defaults.contributor;
		application.defaultValues.data.contributor.isDefaultValue = true;
		application.defaultValues.data.contact.value = defaults.contact;
		application.defaultValues.data.contact.isDefaultValue = true;
		application.defaultValues.data.pointOfContact.value = defaults.pointOfContact;
		application.defaultValues.data.pointOfContact.isDefaultValue = true;
		application.defaultValues.data.portail.value = defaults.portail;
		application.defaultValues.data.portail.isDefaultValue = true;
		application.defaultValues.data.rights.value = defaults.rights;
		application.defaultValues.data.rights.isDefaultValue = true;
		application.defaultValues.data.lang.value = defaults.lang;
		application.defaultValues.data.lang.isDefaultValue = true;
		application.defaultValues.data.isMoissonnable = defaults.moissonnable;
		
		application.defaultValues.data.otherplaceNames.values = defaults.otherPlace;
		application.defaultValues.data.otherplaceNames.isDefaultValue = true;
		application.defaultValues.data.codeCommune.value = defaults.codeCommune;
		application.defaultValues.data.codeCommune.isDefaultValue = true;
		application.defaultValues.data.nomCommune.value = defaults.nomCommune;
		application.defaultValues.data.nomCommune.isDefaultValue = true;
	},
	
	getConservSession: function() {
		
		var defaults="";
		var result = $.ajax({
			url:application.baseUrl + '/admin/conservSession', 
			async: false,
			type: "GET",
			error: function (request, status, error) {
				defaults = "";
		    },
		    success: function (data, text) {
		    	defaults = "";
		    	
		    }
			}).responseText;

		
	},
	
	//return a lexique, init it if empty
	getLexique: function(lexiqueName) {
		var values = application.lexiqueList[lexiqueName];
		if (!values) {
			values = application.fillLexique(lexiqueName);
		}
		
		return values;
	},
	
	//fill a lexique
	fillLexique: function(lexiqueName) {
		var result = $.ajax({
			url:application.baseUrl + '/getLexique', 
			async: false,
			type: "GET",
			data: {lexiqueName: lexiqueName},
			error: function (request, status, error) {
				application.display.dialog.errorDialog(request.status);
		    },
		    success: function (result, text) {
				var data = eval('('+result+')')
				application.lexiqueList[data.name] = data.data;
		    	
			}}).responseText;
		
		return application.lexiqueList[lexiqueName];
	},
	
	getLexiqueItemFromKey: function(lexiqueName, key) {
		var lexique = application.getLexique(lexiqueName);
		for (var i=0; i<lexique.length; i++) {
			if (lexique[i].key == key) {
				return lexique[i];
			}
		}
		return {key:'',value:''};
	},
	
	getThemeTree: function() {
		if (!application.isThemeFill) {
			var result = $.ajax({
				url:application.baseUrl + '/getLexique', 
				async: false,
				type: "GET",
				data: {getTheme: 'true'},
				error: function (request, status, error) {
				application.display.dialog.errorDialog(request.status);
				},
				success: function (result, text) {
					var data = eval('('+result+')');
					application.lexiqueList[data.name] = data.data;
					
					var entries = data.data;
					
					for (var i=0; i< entries.length; i++) {
						 var entry = entries[i];
						 var themesPath = entry.key.split('.'); 
						 var rank = themesPath.length-1;
						 
						 if (rank == 0) {
						 	application.themeTree[entry.key] = [];
						 } else if (rank == 1) {
						 	application.themeTree[themesPath[0]][themesPath[1]] = [];
						 } else if (rank == 2) {
						 	application.themeTree[themesPath[0]][themesPath[1]].push(themesPath[2]);
						 }
					}
					
					application.isThemeFill = true;
		    	}}).responseText;
		}
		
		return application.themeTree;
	},
	
	getThemeLabel: function(themeKey) {
		return application.getLexiqueItemFromKey('themeTree', themeKey).value;
	},
	
	getThemeKey: function(themeLabel) {
		var themeLexique = application.getLexique('themeTree');
		for (var i=0; i<themeLexique.length; i++) {
			if (themeLexique[i].value == themeLabel) {
				return themeLexique[i].key;
			}
		}
		return '';
	},
	
	getThemePath: function(themeKey) {
		var path = themeKey.split('.');
		var result = application.getThemeLabel(path[0]);
		if (path.length > 1)
			result += "/" + application.getThemeLabel(path[0]+"."+path[1]);
		if (path.length > 2)
			result += "/" + application.getThemeLabel(path[0]+"."+path[1]+"."+path[2]);
			
		return result;
	},
	
	getPlaceTree: function() {
		if (!application.isPlaceFill) {
			var result = $.ajax({
				url:application.baseUrl + '/getLexique', 
				async: false,
				type: "GET",
				data: {getPlace: 'true'},
				error: function (request, status, error) {
					application.display.dialog.errorDialog(request.status);
			    },
			    success: function (result, text) {
					var data = eval('('+result+')');
					application.lexiqueList[data.name] = data.data;

					var entries = data.data;
					for (var i=0; i< entries.length; i++) {
						 var entry = entries[i];
						 var placePath = entry.key.split('/'); 
						 var rank = placePath.length-1;
						 
						 if (rank == 0) {
						 	application.placeTree[entry.key] = [];
						 } else if (rank == 1) {
						 	application.placeTree[placePath[0]][placePath[1]] = [];
						 } else if (rank == 2) {
						 	application.placeTree[placePath[0]][placePath[1]].push(placePath[2]);
						 }
					}
				}
				}).responseText;
			
				application.isPlaceFill = true;
		}
		return application.placeTree;
	},
	
	getPlaceLabel: function(placeKey) {
		if (placeKey == 'no_geog') return "Sans objet";
		return application.getLexiqueItemFromKey('placeTree', placeKey.replace('2a','2A').replace('2b','2B')).value;
	},
	
	getRow: function(rowRank) {
		if (rowRank == -2)
			return application.defaultValues;
		if (rowRank == -1)
			return application.display.table.formRow;
		return application.result.rowList[rowRank];
		
	},
	
	exportAll: function() {
		window.location.href=application.baseUrl + '/exportAll';
	},
	
	valideModification: function() {
		var toSend = "";
		
		var toDeleteAtTotal = 0;
		var toAddAtTotal = 0;
		
		for (var i=0; i<application.action.actionsToSave.length; i++) {
			if (application.action.actionsToSave[i].indexOf("delete") > -1) {
				toDeleteAtTotal++;
			}
		
			toSend += application.action.actionsToSave[i];
			if (i < application.action.actionsToSave.length-1)
				toSend += "--!!--";
		}
		
		for (var i=0; i<application.result.rowList.length; i++) {
			if (application.result.rowList[i].isEdited) {
				if (!application.result.rowList[i].data.id || application.result.rowList[i].data.id.length == 0) {
					toAddAtTotal++;
				}
				toSend += application.result.rowList[i].serialize() + "--!!--";
			}
		}
		
		$("#Attente").show();
		$.ajax({
			url:application.baseUrl + '/validAction', 
			async: false,
			type: "POST",
			cache: false,
			data: {actionList: toSend},
			error: function (request, status, error) {
				application.display.dialog.errorDialog(request.status);
		    },
		    success: function (result, text) {
				application.search.launch(0);
				var nbDeleted = 0;
				var nbAdded = 0;
				var infos = result.split("--!!--");
				for (var i=0; i<infos.length; i++) {
					if (infos[i].indexOf("[deleted]") == 0)
						nbDeleted++;
					if (infos[i].indexOf("[updated]") == 0)
						nbAdded++;
				}
				
				var text = "Les donn&eacute;es ont &eacute;t&eacute; mises &agrave; jour avec succ&egrave;s";
				application.display.dialog.alertDialog("Validation",text);
				
				application.action.actionsToSave = [];
				
				application.total += toAddAtTotal;
				application.total -= toDeleteAtTotal;
				
			}
		});
		$("#Attente").hide();
	},
	
	isUrlUnique: function(urlToTest) {
		var isUnique = "unique";
	
		$.ajax({
			url:application.baseUrl + '/testUrlUnicity', 
			async: false,
			type: "POST",
			data: {url: encodeURIComponent(urlToTest)},
			error: function (request, status, error) {
				application.display.dialog.errorDialog(request.status);
		    },
		    success: function (result, text) {
				var data = eval("(" + result + ")");
				if (data) {
					if (data.result == "KO") {
						var isCurrentAdh = false;

						var previousAdhNames = "";
						var previousAdh = data.adhList;
						for (var i=0; i<previousAdh.length; i++) {
							if (previousAdh[i].adh_id == application.adh_id) {
								isCurrentAdh = true;
							}
							previousAdhNames += previousAdh[i].adh_name;
							if (i < previousAdh.length-1)
								previousAdhNames += " et par ";
						}
							
						if (isCurrentAdh) {
							application.display.dialog.alertDialog("Validation d'URL", "Le lien <b>'" + urlToTest + "'</b> est d&eacute;j&agrave; pr&eacute;sente.<br>Vous ne pouvez la saisir deux fois");
							isUnique = "multi_sameUser";
						} else {
							application.display.dialog.alertDialog("Validation d'URL", "Le lien <b>'" + urlToTest + "'</b> est d&eacute;j&agrave; saisie par l'adhérent :<br>" + previousAdhNames + ".");
							isUnique = "multi_otherUser";
						}
					}
				}
			}
			});
	
		return isUnique;
	},
	
	searchCommune: function() {
		var value = $("#communeSearch").val();
		
		if (value) {
			$("#Attente").show();
			$.ajax({
				url:application.baseUrl + '/searchCommune', 
				async: false,
				type: "POST",
				data: {search: value},
				error: function (request, status, error) {
					application.display.dialog.errorDialog(request.status);
			    },
			    success: function (result, text) {
					var data = eval("(" + result + ")");
					if (data) {
						var selectHTML = "";
						for (var i=0; i<data.length; i++) {
							var comId = data[i].code;
							var comName = data[i].name;
							
							selectHTML += "<option value='" + comId + "'>"
								+ comName + " - " + comId
								+ "</option>"; 
						}
						
						$("#communeChoice").html(selectHTML);
						application.display.showSelectedCommune();
					}
				}
			});
			$("#Attente").hide();
		}
	},
	
	serializeArray: function(table) {
		var result = '[';
		if (table) {
			for (var i=0; i<table.length; i++) {
				var current = table[i];
				
				if (i > 0)
					result += ",";
				
				if (typeof current == 'string')
					result += "'";
				
				result += current; 
	
				if (typeof current == 'string')
					result += "'";
			}
		}
		
		result += ']';
		return result;
	},
	
	serializeDate: function(date) {
		if (date) {
			var day = date.getDate();
			var month = date.getMonth()+1;
			var year = date.getFullYear();
			
			var strDay = (day < 10) ? "0" + day : "" + day;
			var strMonth = (month < 10) ? "0" + month : "" + month;
			
			return strDay + "/" + strMonth + "/" + year;
		}
		return date;
	},
	
	appendPrefix: function(table, prefix) {
		var result = new Array();
		
		for (var i=0; i<table.length; i++) {
			result.push(prefix + table[i]);
		}
		
		return result;
	},
	
	disconnect: function() {
		window.location.href = application.baseUrl + '/disconnect.do';
	}
};
