// JavaScript Document
var App; if (!App) App = {};
var Init; if (!Init) Init = {};
var Options; if (!Options) Options = {};

if (!App.UI) App.UI = {};


if (!App.UI.Dialogs) App.UI.Dialogs = {};
App.UI.Dialogs.Error = function(msg,_opts) {
	new App.UI.Dialogs.Alert(msg,jQuery.extend({
		'type' : 'alert'
	}, _opts));
};

App.UI.Dialogs.Success = function(msg,_opts) {
	new App.UI.Dialogs.Alert(msg,jQuery.extend({
		'type' : 'info'
	}, _opts));
};

App.UI.Dialogs.Alert = function(msg,_opts) {
	
	this.settings = jQuery.extend({
		'close' : function() {
			$(this).dialog("destroy");
			$(this).remove();
		},
		'type' : 'alert',
		'block' : true
	}, _opts);
	
	var self = this;
	
	$("<div align='center'><span class='ui-icon ui-icon-"+self.settings.type+"' style='float: left; margin-right: 0.3em;'></span>"+msg+"</div>").dialog({
			"draggable":false,
			"resizable":false,
			"width":500,
			"minHeight":100,
			"modal":self.settings.block,
			"dialogClass":"dialog",
			"bgiframe":true,
			"buttons":{
				"Ok" : function() { self.settings.close.call(this); }
			},
			'close' : function() { self.settings.close.call(this); }
	});
	
};

App.UI.Dialogs.Login = function(_opts) {
	
	this.settings = jQuery.extend({
		'title' : 'Veuillez vous connecter',
		'success' : function(user) {  },
		'error' : function(data) { new App.UI.Dialogs.Error(data.error); },
		'load' : function() { },
		'cancel' : function() { },
		'close' : function() {
			$(this).dialog("destroy");
			$(this).remove();
		}
	}, _opts);
	
	var self = this;
	
	function login() {
		
		var $dlg = $(this);
		var $form = $dlg.find("form.login");
		
		$dlg.block();
		
		if(!$.trim($form.find("input[name=username]").val()).length || !$.trim($form.find("input[name=pwd]").val()).length) {
			self.settings.error.call($dlg,{'error':'Vous devez entrer votre nom d\'utilisateur et mot de passe'});
			$dlg.unblock();
			return;
		}
		
		App.Init.AjaxLogin($form.serialize(),{
			'success' : function(data) {
				$dlg.unblock();
				$dlg.dialog("close");
				self.settings.success.call($dlg,data);
			},
			'error' : function(data) {
				$dlg.unblock();
				self.settings.error.call($dlg,data);
			}
		});
	}
	
	$("<div class='dialogLogin'></div>").dialog({
			"draggable":false,
			"resizable":false,
			"width":600,
			"height":300,
			"minHeight":300,
			"modal":true,
			"dialogClass":"dialog",
			"bgiframe":true,
			"title":self.settings.title,
			"close":self.settings.close,
			"buttons" : {
				"Connexion" : function() {
					var $dlg = $(this);
					$dlg.find("form.login").submit();
				},
				"Annuler" : function() {
					self.settings.cancel.call($(this));
					$(this).remove();
				}
			}
	}).load("/"+App.lang+"/login.tmpl",function() {
		var $dlg = $(this);
		$dlg.find("h1, .buttons").hide();
		//$dlg.find("form.register").submit(function(e) { e.preventDefault(); register.call($dlg); });
		$dlg.find("form.login").submit(function(e) { e.preventDefault(); login.call($dlg); });
		self.settings.load.call($dlg);
	});
	
};

if (!App.UI.Autocomplete) App.UI.Autocomplete = {};
App.UI.Autocomplete.Tags = function(selector,_opts) {

	var $el = $(selector);
	if(!$el || !$el.length) { return; }

	function load() {

		$(this).each(function() {
			if(!$(this).data("fbck_initialized")) {
				$(this).fcbkcomplete(jQuery.extend({
					json_url: "/ajax/tags.fbck",
					cache:false,
					filter_case: false,
					filter_hide: false,
					firstselected: true,
					filter_selected: false,
					newel: true,
					maxshownitems: 15,
					complete_text: "Entrez des tags..."
				},_opts));
				$(this).data("fbck_initialized",true);
			}
		});
	}

	if(!$el.fcbkcomplete) {
		$(window).load(function() { load.call($el); });
	} else { load.call($el); }

};


if (!App.UI.Uploader) App.UI.Uploader = {};
App.UI.Uploader.Photos = function(selector,_opts) {
	
	var $el = $(selector);
	if(!$el || !$el.length || !AjaxUpload) { return; }
	
	_opts = jQuery.extend({
		'width' : 576,
		'height' : 300,
		'id' : 'uploader',
		'fileCompleted' : function(filename) {},
		'stateChange' : function(state) {}
	}, _opts);
	
	$el.flash({
		'src' : '/statics/flash/imgUpload.swf',
		'width' : _opts.width,
		'height' : _opts.height,
		'id' : _opts.id,
		'name' : _opts.id,
		'allowScriptAccess' : 'always',
		'wmode' : 'transparent',
		'flashvars' : { path : 'http://'+window.location.hostname+'/' }
	});
	
	window.uploader_fileCompleted = function(filename) {
		if(_opts.fileCompleted && typeof(_opts.fileCompleted) == "function") { _opts.fileCompleted(filename); }
	}
	
	window.uploader_stateChange =  function(state) {
		if(_opts.stateChange && typeof(_opts.stateChange) == "function") { _opts.stateChange(state); }
	}
};

/**************************************************************************
*
*		Objet pour les cartes Google Maps
*
***************************************************************************/
App.UI.Gmap = function(selector,_opts) {
		
	// Options
	this.opts = jQuery.extend({
		'center' : [45.5,-73.583333],
		'zoom' : 7,
		'dragstart' : function(map,marker) {},
		'drag' : function(map,marker) {},
		'dragend' : function(map,marker) {},
		'click' : function(map,marker) {},
		'init' : function(map,marker) {}
	}, _opts);
	
	var $el = $(selector);
	
	if(!$el.length) { return; }
	
	this.init = function(el) {
	
		var container = el.get(0);
		el = $("<div>"+el.html()+"</div>");
		
		this.geocoder = new GClientGeocoder();
		this.map = new GMap2(container);
		
		this.map.setUIToDefault();
		
		this.center = new google.maps.LatLng(this.opts.center[0], this.opts.center[1]);
		
		if($(selector).attr("rel") && $(selector).attr("rel").length > 2) {
			
			var latlong = $(selector).attr("rel").split("|");
			this.center = new google.maps.LatLng(parseFloat(latlong[0]), parseFloat(latlong[1]));
			this.opts.zoom = 15;
		}
		
		this.map.setCenter(this.center, this.opts.zoom);
		
		this.initMarkers.call(this,el);
		
		
	};
	
	/////Ajoute des marqueurs
	this.initMarkers = function(el) {
		
		var self = this;
		
		el.find(".marker").each(function() {
										  
			var point = self.center;
			if($(this).attr("rel") && $(this).attr("rel").length > 2) {
				var latlong = $(this).attr("rel").split("|");
				point = new google.maps.LatLng(parseFloat(latlong[0]), parseFloat(latlong[1]));
			}
			
			if($(this).is(".draggable")) {
				self.marker = self.addDragMarker.call(self,point,{
					'infoWindow' : ( ($(this).find(".infoWindow").length) ? $(this).find(".infoWindow").html():"" )
				});
			} else {
				self.marker = self.addMarker.call(self,point,{
					'infoWindow' : ( ($(this).find(".infoWindow").length) ? $(this).find(".infoWindow").html():"" )
				});
			}
		});
	};
	///////////////////////////////	
	//////////////////////////////////////////
	if(google) {
		var self = this;
		google.load("maps", "2", {"callback" : function() { self.init.call(self,$el); } });
	}
	
};
App.UI.Gmap.prototype.opts = {};
App.UI.Gmap.prototype.gmap = null;
App.UI.Gmap.prototype.geocoder = null;
App.UI.Gmap.prototype.addDragMarker = function(point,opts) {

	var self = this;
	
	opts = jQuery.extend(self.opts, opts);
	
	if(!point.lat) {
		point = new google.maps.LatLng(point[0], point[1]);
	}
	
	var marker = new GMarker(point, {draggable: true});
	
	if(!opts.dragstart) {}
	else { GEvent.addListener(marker, "dragstart",function(){ opts.dragstart.call(self,self.map,marker); }); }
	if(!opts.dragend) {}
	else { GEvent.addListener(marker, "dragend",function(){ opts.dragend.call(self,self.map,marker); }); }
	if(!opts.drag) {}
	else { GEvent.addListener(marker, "drag",function(){ opts.drag.call(self,self.map,marker); }); }
	if(!opts.click) {}
	else { GEvent.addListener(marker, "click",function(){ opts.click.call(self,self.map,marker); }); }
	
	self.map.addOverlay(marker);
	
	//if(!opts.init) {}
	//else { opts.init(self.map,marker); }
	
	return marker;
};
App.UI.Gmap.prototype.addMarker = function(point,opts) {

	var self = this;
	
	opts = jQuery.extend(self.opts, opts);
	
	if(!point.lat) {
		point = new google.maps.LatLng(point[0], point[1]);
	}
	
	var marker = new GMarker(point);

	if(!opts.click) {}
	else { GEvent.addListener(marker, "click",function(){ opts.click(self.map,marker); }); }
	
	self.map.addOverlay(marker);
	
	if(!opts.infoWindow) {}
	else { marker.openInfoWindowHtml(opts.infoWindow); }
	
	/*if(!opts.init) {}
	else { opts.init.call(self,self.map,marker); }*/
	
	return marker;
};
App.UI.Gmap.prototype.findAddressCoords = function(address,callback) {
	var self = this;
	self.geocoder.getLatLng(address, function(point) { callback.call(self,(point || null),address); });
};
App.UI.Gmap.prototype.findAddress = function(address,callback) {
	$.getJSON("/ajax/locations.json?address="+escape(address)+"&types=all",function(data) {
		callback(data,address);
	});
}

App.UI.Gmap.prototype.findLocations = function(address,callback) {
	var self = this;
	self.geocoder.getLocations(address, function(response) {
		if(!response || response.Status.code != 200) {
			callback.call(self,null,address);
		} else {
			if(response.Placemark && response.Placemark.length) {
				var place = response.Placemark[0];
				response.place = {};
				response.place.point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
				response.place.countryCode = (place.AddressDetails.Country) ? place.AddressDetails.Country.CountryNameCode:null;
				response.place.country = (place.AddressDetails.Country) ? place.AddressDetails.Country.CountryName:null;
				response.place.region = (place.AddressDetails.Country && place.AddressDetails.Country.AdministrativeArea) ? place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName:null;
				response.place.addressFull = (place.address || null);
				response.place.address = (place.AddressDetails.Country && place.AddressDetails.Country.AdministrativeArea && place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea && place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality && place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare) ? place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName:null;
				response.place.postalcode = (place.AddressDetails.Country && place.AddressDetails.Country.AdministrativeArea && place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea && place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality && place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode) ? place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber:null;
				response.place.city = (place.AddressDetails.Country && place.AddressDetails.Country.AdministrativeArea && place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea && place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality) ? place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName:null;
				if(!response.place.address) {
					response.place.address = (place.AddressDetails.Country && place.AddressDetails.Country.AdministrativeArea && place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea && place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality && place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.DependentLocality && place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.DependentLocality.Thoroughfare) ? place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.DependentLocality.Thoroughfare.ThoroughfareName:null;
				}
				if(!response.place.postalcode) {
					response.place.postalcode = (place.AddressDetails.Country && place.AddressDetails.Country.AdministrativeArea && place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea && place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality && place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.DependentLocality && place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.DependentLocality.PostalCode) ? place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.DependentLocality.PostalCode.PostalCodeNumber:null;
				}
			}
			callback.call(self,response,address);
		}
	});
};
App.UI.Gmap.prototype.setCenter = function(lat,lng,zoom) {
	var self = this;
	self.center = new google.maps.LatLng(parseFloat(lat), parseFloat(lng));
	self.opts.zoom = (zoom || 14);
	self.map.setCenter(self.center, self.opts.zoom);
};
App.UI.Gmap.prototype.clearMarkers = function() {
	var self = this;
	self.map.clearOverlays();
};
App.UI.Gmap.prototype.refresh = function() {
	var self = this;
	self.map.checkResize();
};
App.UI.Gmap.degToDec = function(deg,min,sec) {
	deg = parseFloat(deg);
	min = parseFloat(min);
	sec = parseFloat(sec);
	
	if(!(deg+0)){ deg = 0 };
	if(!(min+0)){ min = 0 };
	if(!(sec+0)){ sec = 0 };
	
	// Convert to Decimal Degrees Representation
	var dec = deg + (min/60) + (sec / 60 / 60);
	return Math.round(parseFloat(dec)*1000000000)/1000000000;
};
App.UI.Gmap.decToDeg = function(dec) {
	dec = dec + "";
	vars = dec.split(".");
	deg = vars[0];
	tempma = "0."+vars[1];
	tempma = tempma * 3600;
	min = Math.floor(tempma / 60);
	sec = tempma - (min*60);
	return {"deg":deg,"min":min,"sec":sec.toPrecision(8)};
};
/**************************************************************************/

App.UI.Multidatepicker = function(selector, selected) {
    	if(!$(selector).length) { return; }
	var $el = $(selector);
        var $selected_dates = $(selected);

    $el.mouseleave(function(e){
          e.preventDefault();
          var dates = $el.multiDatesPicker('getDates');
          var dates_in_string = '';
          for(d in dates) dates_in_string+= dates[d]+' ';
          $selected_dates.val(dates_in_string);
    });
  };

App.UI.Datepicker = function(selector,_opts) {
	if(!$(selector).length) { return; }
	var $el = $(selector);
	
	$el.each(function() {
		// Options
		_opts = jQuery.extend({
			'range' : 'normal',
			'datepickerOptions' : Options.datepicker
		}, _opts);
		
		if(_opts.range == 'future' || $(this).is(".future")) {
			_opts.datepickerOptions.minDate = new Date();
			_opts.datepickerOptions.maxDate = '+50y';
			_opts.datepickerOptions.yearRange = '-50:+50';
		}
		else if(_opts.range == 'past' || $(this).is(".past")) {
			_opts.datepickerOptions.minDate = new Date(1900, 1 - 1, 1);
			_opts.datepickerOptions.maxDate = new Date();
			_opts.datepickerOptions.yearRange = '-120:+1';
		}
		$(this).datepicker(_opts.datepickerOptions);
	});
};

App.UI.Scroller = function(selector,_opts) {
	
	var $el = $(selector);
	if(!$el.length) { return; }
	
	// Options
	_opts = jQuery.extend({
		'url' : ($el.attr("rel")) ? $el.attr("rel"):"",
		'startIndex' : 0
	}, _opts);
	
	var _currentIndex = _opts.startIndex;
	var _items = [];
	var _interval = null;
	
	function next() {
		_currentIndex = (_currentIndex == (_items.length-1)) ? 0:(_currentIndex+1);	
		var $next = $el.find(".text").clone();
		$el.find(".text").after($next.css("zIndex",5));
		$next.hide();
		update($next,_items[_currentIndex]);
		$el.find(".text:eq(0)").fadeOut(300,function() {
			$(this).remove();
			$el.find(".text:eq(0)").fadeIn(500,function() {
				$(this).css("zIndex",6);
			});
		});
	}
	
	function update(el,data) {
		//alert($.toJSON(data));
		el.html("<a href='/"+App.lang+"/"+((App.lang == "en") ? "events":"evenements")+"/"+((data["cpermalink_"+App.lang]) ? data["cpermalink_"+App.lang]+"/":"")+data.permalink+".html'>"+data.title+" - "+data.venue+", "+data.gcname+" - "+DateFormat(data.date)+"</a>");
	}
	
	//First load
	$el.find(".frame").css("position","relative");
	$el.find(".text").css("position","relative").html("Chargement...");
	$.getJSON(_opts.url,function(data) {
		
		_items = data;
		update($el.find(".text"),data[_currentIndex]);
		_interval = window.setInterval(function() {
			next();									
		},6000);
	});
	
	
}

//Initialise un champ de sélection d'un item
App.UI.ItemField = function(selector,_opts) {

	if(!$(selector).length) { return; }
	var $el = $(selector);
	
	if(!$el.is(".itemField")) { $el.addClass("itemField"); }
	
	// Options
	_opts = jQuery.extend({
		'onSelect' : function() { },
		'onRemove' : function() { },
		'listClass' : 'items',
		'selectedClass' : 'item',
		'inputName' : 'iid',
		'inputKey' : 'iid',
		'url' : '/admin/items.json',
		'params' : '',
		'paramName' : 'autocomplete',
		'label' : function(data) { return (data.name) ? data.name:"Item"; },
		'onLoading' : function() { },
		'onEmpty' : function() { },
		'onLoad' : function(data) { }
	}, _opts);
	
	//Initialise le champ de recherche
	new Autocomplete($el.find("input.search"),{
		"url" : _opts.url,
		"paramName" : _opts.paramName,
		"params" : _opts.params,
		"method" : "GET",
		"waitDelay" : 100,
		"minChars" : 2,
		"format" : "json",
		"onLoading" : function() {
			if(_opts.onLoading) { _opts.onLoading.apply(this); }
			$el.find(".results .spinner").remove();
			if(!$el.find(".results ul").length || $el.find(".results ul li.noresult").length) {
				$el.find(".results").show().html("<div align='center' class='spinner'><img src='/statics/img/loading_block.gif' /></div>");
			} else {
				$el.find(".results ul").after("<div align='center' class='spinner'><img src='/statics/img/loading_block.gif' /></div>");
			}
		},
		"onEmpty" : function() {
			if(_opts.onEmpty) { _opts.onEmpty.apply(this); }
			$el.find(".results").html("").hide();
		},
		"onLoad" : function(data) {
			if(_opts.onLoad) {
				if(_opts.onLoad.apply(this,data) == false) { return false; }
			}
			$el.find(".results").show().html("<ul class='list "+_opts.listClass+"'></ul>");
			if(data.length) {
				if(jQuery.trim($(this).val()).length) {
					$(data).each(function() {
						var item = "<span class='label'>"+_opts.label(this)+"</span>";
						item += '<input type="hidden" name="'+_opts.inputName+'" value="'+this[_opts.inputKey]+'" />';
						item += '<input type="hidden" class="data" value="'+escape($.toJSON(this))+'" />';
						$el.find(".results ul").append("<li>"+item+"</li>");
					});
					if(data.length > 10) {
						$el.find(".results").css({'overflow':'auto','height':'200px'});
					} else {
						$el.find(".results").css({'overflow':'visible','height':'auto'});
					}
					$el.find(".results ul li").click(function(e) {
						var data = $.evalJSON(unescape($(this).find("input.data").val()));
						
						if(_opts.onSelect) { if(_opts.onSelect.call($el,$(this),data) == false) { return false; } }
						
						$el.find(".selected").html("<div class='"+_opts.selectedClass+"'>"+$(this).html()+" - <a href='#' class='rem'>X</a></div>").show();
						$el.find(".selected ."+_opts.selectedClass).show();
						$el.find("input.search").hide();
						$el.find(".selected a.rem").click(function(e) {
							e.preventDefault();
							
							if(_opts.onRemove) { if(_opts.onRemove.call($el,$(this)) == false) { return false; } }
							
							$(this).parent().hide().html("<input type='hidden' name='"+_opts.inputName+"' value='0' />");
							$el.find("input.search").show();
						});
						
						$el.find(".results").html("").hide();
						$el.find("input.search").val($el.find("input.search").attr("title")).addClass("hasHint");
					});
				} else {
					$el.find(".results").html("").hide();
				}
			} else {
				$el.find(".results ul").append("<li class='noresult'>Aucun résultat</li>");
			}
		}
	});
	
	
	
	$(document).click(function(e) {
		if(!$(e.target).isChildOf($el) && $(e.target).get(0) != $el.find("input.search").get(0)) {
			$el.find(".results").slideUp("fast");
		}
	});
	
	$el.find("input.search").attr("autocomplete","off").focus(function(e) {
		if($el.find(".results li").length) { $el.find(".results").slideDown("fast"); }
	});
	
	//Initialise le bouton supprimer du lieu sélectionné
	$el.find(".selected a.rem").click(function(e) {
		e.preventDefault();
		
		_opts.onRemove.call($el,$(this));
		
		$(this).parent().hide().html("<input type='hidden' name='"+_opts.inputName+"' value='0' />");
		$el.find(".top").show();
	});
	
	if($el.find(".selected input[name="+_opts.inputName+"]").length && $el.find(".selected input[name="+_opts.inputName+"]").val().length && $el.find(".selected input[name="+_opts.inputName+"]").val() != "0") {
		$el.find(".top").hide();
	}

};

App.UI.ItemsField =  function(selector,_opts) {

	if(!$(selector).length) { return; }
	var $el = $(selector);
	
	if(!$el.is(".itemField")) { $el.addClass("itemField"); }
	if(!$el.is(".itemsField")) { $el.addClass("itemsField"); }
	
	// Options
	_opts = jQuery.extend({
		'onSelect' : function() { },
		'onRemove' : function() { },
		'listClass' : 'items',
		'selectedClass' : 'item',
		'inputName' : 'iid',
		'inputKey' : 'iid',
		'url' : '/admin/items.json',
		'params' : '',
		'paramName' : 'autocomplete',
		'label' : function(data) { return (data.name) ? data.name:"Item"; },
		'onLoading' : function() { },
		'onEmpty' : function() { },
		'onLoad' : function(data) { }
	}, _opts);
	
	//Initialise le champ de recherche
	new Autocomplete($el.find("input.search"),{
		"url" : _opts.url,
		"paramName" : _opts.paramName,
		"params" : _opts.params,
		"method" : "GET",
		"waitDelay" : 100,
		"minChars" : 2,
		"format" : "json",
		"onLoading" : function() {
			if(_opts.onLoading) { _opts.onLoading.apply(this); }
			$el.find(".results .spinner").remove();
			if(!$el.find(".results ul").length || $el.find(".results ul li.noresult").length) {
				$el.find(".results").show().html("<div align='center' class='spinner'><img src='/statics/img/loading_block.gif' /></div>");
			} else {
				$el.find(".results ul").after("<div align='center' class='spinner'><img src='/statics/img/loading_block.gif' /></div>");
			}
		},
		"onEmpty" : function() {
			if(_opts.onEmpty) { _opts.onEmpty.apply(this); }
			$el.find(".results").html("").hide();
		},
		"onLoad" : function(data) {
			if(_opts.onLoad) { _opts.onLoad.apply(this,data); }
			$el.find(".results").show().html("<ul class='list "+_opts.listClass+"'></ul>");
			if(data.length) {
				if(jQuery.trim($(this).val()).length) {
					data = data.slice(0,15);
					$(data).each(function() {
						var item = "<span class='label'>"+_opts.label(this)+"</span>";
						item += '<input type="hidden" name="'+_opts.inputName+'[]" value="'+this[_opts.inputKey]+'" />';
						item += '<input type="hidden" name="'+_opts.inputName+'_data[]" class="data" value="'+escape($.toJSON(this))+'" />';
						$el.find(".results ul").append("<li>"+item+"</li>");
					});
					$el.find(".results ul li").click(function(e) {
						var data = $.evalJSON(unescape($(this).find("input.data").val()));
						
						_opts.onSelect.call($el,$(this),data);
						
						$el.find(".selected").prepend("<div class='"+_opts.selectedClass+"'>"+$(this).html()+" - <a href='#' class='rem'>X</a></div>");
						
						$el.find(".results").html("").hide();
						$el.find(".top input.search").val($el.find(".top input.search").attr("title")).addClass("hasHint");
					});
				} else {
					$el.find(".results").html("").hide();
				}
			} else {
				$el.find(".results ul").append("<li class='noresult'>Aucun résultat</li>");
			}
		}
	});
	
	//Initialise le bouton supprimer du lieu sélectionné
	$el.find(".selected a.rem").live("click",function(e) {
		e.preventDefault();
		
		_opts.onRemove.call($el,$(this));
		
		$(this).parents("div."+_opts.selectedClass).eq(0).remove();
		
		$el.find(".top").show();
	});

};

App.UI.Phonenumber =  function(){
        //MAIN PHONE NUMBER ADD NEW FIELDS
        $('#phoneNumberBtnAdd').click(function() {

            var num		= $('.phoneNumber').length;	// how many "duplicatable" input fields we currently have
            var newNum	= new Number(num + 1);		// the numeric ID of the new input field being added

            // create the new element via clone(), and manipulate it's ID using newNum value
            var newElem = $('#phoneNumber' + num).clone().attr('id', 'phoneNumber' + newNum);

            // manipulate the name/id values of the input inside the new element
            newElem.children('input[name*="phonenumber"]').attr('id', 'phonenumber_' + newNum).attr('name', 'phonenumber_' + newNum).val("");
            newElem.children('input[name*="phonenotes"]').attr('id', 'phonenotes_' + newNum).attr('name', 'phonenotes_' + newNum).val("");

            // insert the new element after the last "duplicatable" input field
            $('#phoneNumber' + num).after(newElem);

            // enable the "remove" button
            $('#phoneNumberBtnDel').attr('disabled','');

            // business rule: you can only add 5 names
            if (newNum == 5)
                $('#phoneNumberBtnAdd').attr('disabled','disabled');
        });

       $('#phoneNumberBtnDel').click(function() {
            var num	= $('.phoneNumber').length;	// how many "duplicatable" input fields we currently have
            $('#phoneNumber' + num).remove();		// remove the last element

            // enable the "add" button
            $('#phoneNumberBtnAdd').attr('disabled','');

            // if only one element remains, disable the "remove" button
            if (num-1 == 1)
                $('#phoneNumberBtnDel').attr('disabled','disabled');
        });
        $('#phoneNumberBtnDel').attr('disabled','disabled');

         //TAXI PHONE NUMBER ADD NEW FIELDS
        $('#taxiNumberBtnAdd').click(function() {

            var num		= $('.taxiNumber').length;	// how many "duplicatable" input fields we currently have
            var newNum	= new Number(num + 1);		// the numeric ID of the new input field being added

            // create the new element via clone(), and manipulate it's ID using newNum value
            var newElem = $('#taxiNumber' + num).clone().attr('id', 'taxiNumber' + newNum);

            // manipulate the name/id values of the input inside the new element
            newElem.children(':first').attr('id', 'taxinumber_' + newNum).attr('name', 'taxinumber_' + newNum).val("");
            newElem.children('input[name*="taxinumber"]').attr('id', 'taxinumber_' + newNum).attr('name', 'taxinumber_' + newNum).val("");
            newElem.children('input[name*="taxinotes"]').attr('id', 'taxinotes_' + newNum).attr('name', 'taxinotes_' + newNum).val("");


            // insert the new element after the last "duplicatable" input field
            $('#taxiNumber' + num).after(newElem);

            // enable the "remove" button
            $('#taxiNumberBtnDel').attr('disabled','');

            // business rule: you can only add 5 names
            if (newNum == 5)
                $('#taxiNumberBtnAdd').attr('disabled','disabled');
        });

       $('#taxiNumberBtnDel').click(function() {
            var num	= $('.taxiNumber').length;	// how many "duplicatable" input fields we currently have
            $('#taxiNumber' + num).remove();		// remove the last element

            // enable the "add" button
            $('#taxiNumberBtnAdd').attr('disabled','');

            // if only one element remains, disable the "remove" button
            if (num-1 == 1)
                $('#taxiNumberBtnDel').attr('disabled','disabled');
        });
        $('#taxiNumberBtnDel').attr('disabled','disabled');
    };
