Subversion Repositories eFlore/Applications.cel

Compare Revisions

Ignore whitespace Rev 2327 → Rev 2328

/trunk/widget/modules/saisie/squelettes/ambrosia/js/bootstrap-modalmanager.js
New file
0,0 → 1,423
/* ===========================================================
* bootstrap-modalmanager.js v2.2.5
* ===========================================================
* Copyright 2012 Jordan Schroter.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ========================================================== */
 
!function ($) {
 
"use strict"; // jshint ;_;
 
/* MODAL MANAGER CLASS DEFINITION
* ====================== */
 
var ModalManager = function (element, options) {
this.init(element, options);
};
 
ModalManager.prototype = {
 
constructor: ModalManager,
 
init: function (element, options) {
this.$element = $(element);
this.options = $.extend({}, $.fn.modalmanager.defaults, this.$element.data(), typeof options == 'object' && options);
this.stack = [];
this.backdropCount = 0;
 
if (this.options.resize) {
var resizeTimeout,
that = this;
 
$(window).on('resize.modal', function(){
resizeTimeout && clearTimeout(resizeTimeout);
resizeTimeout = setTimeout(function(){
for (var i = 0; i < that.stack.length; i++){
that.stack[i].isShown && that.stack[i].layout();
}
}, 10);
});
}
},
 
createModal: function (element, options) {
$(element).modal($.extend({ manager: this }, options));
},
 
appendModal: function (modal) {
this.stack.push(modal);
 
var that = this;
 
modal.$element.on('show.modalmanager', targetIsSelf(function (e) {
 
var showModal = function(){
modal.isShown = true;
 
var transition = $.support.transition && modal.$element.hasClass('fade');
 
that.$element
.toggleClass('modal-open', that.hasOpenModal())
.toggleClass('page-overflow', $(window).height() < that.$element.height());
 
modal.$parent = modal.$element.parent();
 
modal.$container = that.createContainer(modal);
 
modal.$element.appendTo(modal.$container);
 
that.backdrop(modal, function () {
modal.$element.show();
 
if (transition) {
//modal.$element[0].style.display = 'run-in';
modal.$element[0].offsetWidth;
//modal.$element.one($.support.transition.end, function () { modal.$element[0].style.display = 'block' });
}
modal.layout();
 
modal.$element
.addClass('in')
.attr('aria-hidden', false);
 
var complete = function () {
that.setFocus();
modal.$element.trigger('shown');
};
 
transition ?
modal.$element.one($.support.transition.end, complete) :
complete();
});
};
 
modal.options.replace ?
that.replace(showModal) :
showModal();
}));
 
modal.$element.on('hidden.modalmanager', targetIsSelf(function (e) {
that.backdrop(modal);
// handle the case when a modal may have been removed from the dom before this callback executes
if (!modal.$element.parent().length) {
that.destroyModal(modal);
} else if (modal.$backdrop){
var transition = $.support.transition && modal.$element.hasClass('fade');
 
// trigger a relayout due to firebox's buggy transition end event
if (transition) { modal.$element[0].offsetWidth; }
$.support.transition && modal.$element.hasClass('fade') ?
modal.$backdrop.one($.support.transition.end, function () { modal.destroy(); }) :
modal.destroy();
} else {
modal.destroy();
}
 
}));
 
modal.$element.on('destroyed.modalmanager', targetIsSelf(function (e) {
that.destroyModal(modal);
}));
},
 
getOpenModals: function () {
var openModals = [];
for (var i = 0; i < this.stack.length; i++){
if (this.stack[i].isShown) openModals.push(this.stack[i]);
}
 
return openModals;
},
 
hasOpenModal: function () {
return this.getOpenModals().length > 0;
},
 
setFocus: function () {
var topModal;
 
for (var i = 0; i < this.stack.length; i++){
if (this.stack[i].isShown) topModal = this.stack[i];
}
 
if (!topModal) return;
 
topModal.focus();
},
 
destroyModal: function (modal) {
modal.$element.off('.modalmanager');
if (modal.$backdrop) this.removeBackdrop(modal);
this.stack.splice(this.getIndexOfModal(modal), 1);
 
var hasOpenModal = this.hasOpenModal();
 
this.$element.toggleClass('modal-open', hasOpenModal);
 
if (!hasOpenModal){
this.$element.removeClass('page-overflow');
}
 
this.removeContainer(modal);
 
this.setFocus();
},
 
getModalAt: function (index) {
return this.stack[index];
},
 
getIndexOfModal: function (modal) {
for (var i = 0; i < this.stack.length; i++){
if (modal === this.stack[i]) return i;
}
},
 
replace: function (callback) {
var topModal;
 
for (var i = 0; i < this.stack.length; i++){
if (this.stack[i].isShown) topModal = this.stack[i];
}
 
if (topModal) {
this.$backdropHandle = topModal.$backdrop;
topModal.$backdrop = null;
 
callback && topModal.$element.one('hidden',
targetIsSelf( $.proxy(callback, this) ));
 
topModal.hide();
} else if (callback) {
callback();
}
},
 
removeBackdrop: function (modal) {
modal.$backdrop.remove();
modal.$backdrop = null;
},
 
createBackdrop: function (animate, tmpl) {
var $backdrop;
 
if (!this.$backdropHandle) {
$backdrop = $(tmpl)
.addClass(animate)
.appendTo(this.$element);
} else {
$backdrop = this.$backdropHandle;
$backdrop.off('.modalmanager');
this.$backdropHandle = null;
this.isLoading && this.removeSpinner();
}
 
return $backdrop;
},
 
removeContainer: function (modal) {
modal.$container.remove();
modal.$container = null;
},
 
createContainer: function (modal) {
var $container;
 
$container = $('<div class="modal-scrollable">')
.css('z-index', getzIndex('modal', this.getOpenModals().length))
.appendTo(this.$element);
 
if (modal && modal.options.backdrop != 'static') {
$container.on('click.modal', targetIsSelf(function (e) {
modal.hide();
}));
} else if (modal) {
$container.on('click.modal', targetIsSelf(function (e) {
modal.attention();
}));
}
 
return $container;
 
},
 
backdrop: function (modal, callback) {
var animate = modal.$element.hasClass('fade') ? 'fade' : '',
showBackdrop = modal.options.backdrop &&
this.backdropCount < this.options.backdropLimit;
 
if (modal.isShown && showBackdrop) {
var doAnimate = $.support.transition && animate && !this.$backdropHandle;
 
modal.$backdrop = this.createBackdrop(animate, modal.options.backdropTemplate);
 
modal.$backdrop.css('z-index', getzIndex( 'backdrop', this.getOpenModals().length ));
 
if (doAnimate) modal.$backdrop[0].offsetWidth; // force reflow
 
modal.$backdrop.addClass('in');
 
this.backdropCount += 1;
 
doAnimate ?
modal.$backdrop.one($.support.transition.end, callback) :
callback();
 
} else if (!modal.isShown && modal.$backdrop) {
modal.$backdrop.removeClass('in');
 
this.backdropCount -= 1;
 
var that = this;
 
$.support.transition && modal.$element.hasClass('fade')?
modal.$backdrop.one($.support.transition.end, function () { that.removeBackdrop(modal) }) :
that.removeBackdrop(modal);
 
} else if (callback) {
callback();
}
},
 
removeSpinner: function(){
this.$spinner && this.$spinner.remove();
this.$spinner = null;
this.isLoading = false;
},
 
removeLoading: function () {
this.$backdropHandle && this.$backdropHandle.remove();
this.$backdropHandle = null;
this.removeSpinner();
},
 
loading: function (callback) {
callback = callback || function () { };
 
this.$element
.toggleClass('modal-open', !this.isLoading || this.hasOpenModal())
.toggleClass('page-overflow', $(window).height() < this.$element.height());
 
if (!this.isLoading) {
 
this.$backdropHandle = this.createBackdrop('fade', this.options.backdropTemplate);
 
this.$backdropHandle[0].offsetWidth; // force reflow
 
var openModals = this.getOpenModals();
 
this.$backdropHandle
.css('z-index', getzIndex('backdrop', openModals.length + 1))
.addClass('in');
 
var $spinner = $(this.options.spinner)
.css('z-index', getzIndex('modal', openModals.length + 1))
.appendTo(this.$element)
.addClass('in');
 
this.$spinner = $(this.createContainer())
.append($spinner)
.on('click.modalmanager', $.proxy(this.loading, this));
 
this.isLoading = true;
 
$.support.transition ?
this.$backdropHandle.one($.support.transition.end, callback) :
callback();
 
} else if (this.isLoading && this.$backdropHandle) {
this.$backdropHandle.removeClass('in');
 
var that = this;
$.support.transition ?
this.$backdropHandle.one($.support.transition.end, function () { that.removeLoading() }) :
that.removeLoading();
 
} else if (callback) {
callback(this.isLoading);
}
}
};
 
/* PRIVATE METHODS
* ======================= */
 
// computes and caches the zindexes
var getzIndex = (function () {
var zIndexFactor,
baseIndex = {};
 
return function (type, pos) {
 
if (typeof zIndexFactor === 'undefined'){
var $baseModal = $('<div class="modal hide" />').appendTo('body'),
$baseBackdrop = $('<div class="modal-backdrop hide" />').appendTo('body');
 
baseIndex['modal'] = +$baseModal.css('z-index');
baseIndex['backdrop'] = +$baseBackdrop.css('z-index');
zIndexFactor = baseIndex['modal'] - baseIndex['backdrop'];
 
$baseModal.remove();
$baseBackdrop.remove();
$baseBackdrop = $baseModal = null;
}
 
return baseIndex[type] + (zIndexFactor * pos);
 
}
}());
 
// make sure the event target is the modal itself in order to prevent
// other components such as tabsfrom triggering the modal manager.
// if Boostsrap namespaced events, this would not be needed.
function targetIsSelf(callback){
return function (e) {
if (e && this === e.target){
return callback.apply(this, arguments);
}
}
}
 
 
/* MODAL MANAGER PLUGIN DEFINITION
* ======================= */
 
$.fn.modalmanager = function (option, args) {
return this.each(function () {
var $this = $(this),
data = $this.data('modalmanager');
 
if (!data) $this.data('modalmanager', (data = new ModalManager(this, option)));
if (typeof option === 'string') data[option].apply(data, [].concat(args))
})
};
 
$.fn.modalmanager.defaults = {
backdropLimit: 999,
resize: true,
spinner: '<div class="loading-spinner fade" style="width: 200px; margin-left: -100px;"><div class="progress progress-striped active"><div class="bar" style="width: 100%;"></div></div></div>',
backdropTemplate: '<div class="modal-backdrop" />'
};
 
$.fn.modalmanager.Constructor = ModalManager
 
// ModalManager handles the modal-open class so we need
// to remove conflicting bootstrap 3 event handlers
$(function () {
$(document).off('show.bs.modal').off('hidden.bs.modal');
});
 
}(jQuery);
/trunk/widget/modules/saisie/squelettes/ambrosia/js/bootstrap-modal.js
New file
0,0 → 1,378
/* ===========================================================
* bootstrap-modal.js v2.2.5
* ===========================================================
* Copyright 2012 Jordan Schroter
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ========================================================== */
 
 
!function ($) {
 
"use strict"; // jshint ;_;
 
/* MODAL CLASS DEFINITION
* ====================== */
 
var Modal = function (element, options) {
this.init(element, options);
};
 
Modal.prototype = {
 
constructor: Modal,
 
init: function (element, options) {
var that = this;
 
this.options = options;
 
this.$element = $(element)
.delegate('[data-dismiss="modal"]', 'click.dismiss.modal', $.proxy(this.hide, this));
 
this.options.remote && this.$element.find('.modal-body').load(this.options.remote, function () {
var e = $.Event('loaded');
that.$element.trigger(e);
});
 
var manager = typeof this.options.manager === 'function' ?
this.options.manager.call(this) : this.options.manager;
 
manager = manager.appendModal ?
manager : $(manager).modalmanager().data('modalmanager');
 
manager.appendModal(this);
},
 
toggle: function () {
return this[!this.isShown ? 'show' : 'hide']();
},
 
show: function () {
var e = $.Event('show');
 
if (this.isShown) return;
 
this.$element.trigger(e);
 
if (e.isDefaultPrevented()) return;
 
this.escape();
 
this.tab();
 
this.options.loading && this.loading();
},
 
hide: function (e) {
e && e.preventDefault();
 
e = $.Event('hide');
 
this.$element.trigger(e);
 
if (!this.isShown || e.isDefaultPrevented()) return;
 
this.isShown = false;
 
this.escape();
 
this.tab();
 
this.isLoading && this.loading();
 
$(document).off('focusin.modal');
 
this.$element
.removeClass('in')
.removeClass('animated')
.removeClass(this.options.attentionAnimation)
.removeClass('modal-overflow')
.attr('aria-hidden', true);
 
$.support.transition && this.$element.hasClass('fade') ?
this.hideWithTransition() :
this.hideModal();
},
 
layout: function () {
var prop = this.options.height ? 'height' : 'max-height',
value = this.options.height || this.options.maxHeight;
 
if (this.options.width){
this.$element.css('width', this.options.width);
 
var that = this;
this.$element.css('margin-left', function () {
if (/%/ig.test(that.options.width)){
return -(parseInt(that.options.width) / 2) + '%';
} else {
return -($(this).width() / 2) + 'px';
}
});
} else {
this.$element.css('width', '');
this.$element.css('margin-left', '');
}
 
this.$element.find('.modal-body')
.css('overflow', '')
.css(prop, '');
 
if (value){
this.$element.find('.modal-body')
.css('overflow', 'auto')
.css(prop, value);
}
 
var modalOverflow = $(window).height() - 10 < this.$element.height();
if (modalOverflow || this.options.modalOverflow) {
this.$element
.css('margin-top', 0)
.addClass('modal-overflow');
} else {
this.$element
.css('margin-top', 0 - this.$element.height() / 2)
.removeClass('modal-overflow');
}
},
 
tab: function () {
var that = this;
 
if (this.isShown && this.options.consumeTab) {
this.$element.on('keydown.tabindex.modal', '[data-tabindex]', function (e) {
if (e.keyCode && e.keyCode == 9){
var elements = [],
tabindex = Number($(this).data('tabindex'));
 
that.$element.find('[data-tabindex]:enabled:visible:not([readonly])').each(function (ev) {
elements.push(Number($(this).data('tabindex')));
});
elements.sort(function(a,b){return a-b});
var arrayPos = $.inArray(tabindex, elements);
if (!e.shiftKey){
arrayPos < elements.length-1 ?
that.$element.find('[data-tabindex='+elements[arrayPos+1]+']').focus() :
that.$element.find('[data-tabindex='+elements[0]+']').focus();
} else {
arrayPos == 0 ?
that.$element.find('[data-tabindex='+elements[elements.length-1]+']').focus() :
that.$element.find('[data-tabindex='+elements[arrayPos-1]+']').focus();
}
e.preventDefault();
}
});
} else if (!this.isShown) {
this.$element.off('keydown.tabindex.modal');
}
},
 
escape: function () {
var that = this;
if (this.isShown && this.options.keyboard) {
if (!this.$element.attr('tabindex')) this.$element.attr('tabindex', -1);
 
this.$element.on('keyup.dismiss.modal', function (e) {
e.which == 27 && that.hide();
});
} else if (!this.isShown) {
this.$element.off('keyup.dismiss.modal')
}
},
 
hideWithTransition: function () {
var that = this
, timeout = setTimeout(function () {
that.$element.off($.support.transition.end);
that.hideModal();
}, 500);
 
this.$element.one($.support.transition.end, function () {
clearTimeout(timeout);
that.hideModal();
});
},
 
hideModal: function () {
var prop = this.options.height ? 'height' : 'max-height';
var value = this.options.height || this.options.maxHeight;
 
if (value){
this.$element.find('.modal-body')
.css('overflow', '')
.css(prop, '');
}
 
this.$element
.hide()
.trigger('hidden');
},
 
removeLoading: function () {
this.$loading.remove();
this.$loading = null;
this.isLoading = false;
},
 
loading: function (callback) {
callback = callback || function () {};
 
var animate = this.$element.hasClass('fade') ? 'fade' : '';
 
if (!this.isLoading) {
var doAnimate = $.support.transition && animate;
 
this.$loading = $('<div class="loading-mask ' + animate + '">')
.append(this.options.spinner)
.appendTo(this.$element);
 
if (doAnimate) this.$loading[0].offsetWidth; // force reflow
 
this.$loading.addClass('in');
 
this.isLoading = true;
 
doAnimate ?
this.$loading.one($.support.transition.end, callback) :
callback();
 
} else if (this.isLoading && this.$loading) {
this.$loading.removeClass('in');
 
var that = this;
$.support.transition && this.$element.hasClass('fade')?
this.$loading.one($.support.transition.end, function () { that.removeLoading() }) :
that.removeLoading();
 
} else if (callback) {
callback(this.isLoading);
}
},
 
focus: function () {
var $focusElem = this.$element.find(this.options.focusOn);
 
$focusElem = $focusElem.length ? $focusElem : this.$element;
 
$focusElem.focus();
},
 
attention: function (){
// NOTE: transitionEnd with keyframes causes odd behaviour
 
if (this.options.attentionAnimation){
this.$element
.removeClass('animated')
.removeClass(this.options.attentionAnimation);
 
var that = this;
 
setTimeout(function () {
that.$element
.addClass('animated')
.addClass(that.options.attentionAnimation);
}, 0);
}
 
 
this.focus();
},
 
 
destroy: function () {
var e = $.Event('destroy');
 
this.$element.trigger(e);
 
if (e.isDefaultPrevented()) return;
 
this.$element
.off('.modal')
.removeData('modal')
.removeClass('in')
.attr('aria-hidden', true);
if (this.$parent !== this.$element.parent()) {
this.$element.appendTo(this.$parent);
} else if (!this.$parent.length) {
// modal is not part of the DOM so remove it.
this.$element.remove();
this.$element = null;
}
 
this.$element.trigger('destroyed');
}
};
 
 
/* MODAL PLUGIN DEFINITION
* ======================= */
 
$.fn.modal = function (option, args) {
return this.each(function () {
var $this = $(this),
data = $this.data('modal'),
options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option);
 
if (!data) $this.data('modal', (data = new Modal(this, options)));
if (typeof option == 'string') data[option].apply(data, [].concat(args));
else if (options.show) data.show()
})
};
 
$.fn.modal.defaults = {
keyboard: true,
backdrop: true,
loading: false,
show: true,
width: null,
height: null,
maxHeight: null,
modalOverflow: false,
consumeTab: true,
focusOn: null,
replace: false,
resize: false,
attentionAnimation: 'shake',
manager: 'body',
spinner: '<div class="loading-spinner" style="width: 200px; margin-left: -100px;"><div class="progress progress-striped active"><div class="bar" style="width: 100%;"></div></div></div>',
backdropTemplate: '<div class="modal-backdrop" />'
};
 
$.fn.modal.Constructor = Modal;
 
 
/* MODAL DATA-API
* ============== */
 
$(function () {
$(document).off('click.modal').on('click.modal.data-api', '[data-toggle="modal"]', function ( e ) {
var $this = $(this),
href = $this.attr('href'),
$target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))), //strip for ie7
option = $target.data('modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data());
 
e.preventDefault();
$target
.modal(option)
.one('hide', function () {
$this.focus();
})
});
});
 
}(window.jQuery);
/trunk/widget/modules/saisie/squelettes/ambrosia/js/ambrosia.js
New file
0,0 → 1,1220
//+---------------------------------------------------------------------------------------------------------+
// GÉNÉRAL
$(document).ready(function() {
if (DEBUG == false) {
$(window).on('beforeunload', function(event) {
return 'Êtes vous sûr de vouloir quiter la page?\nLes observations saisies mais non transmises seront perdues.';
});
}
});
//+----------------------------------------------------------------------------------------------------------+
// FONCTIONS GÉNÉRIQUES
/**
* Stope l'évènement courrant quand on clique sur un lien.
* Utile pour Chrome, Safari...
* @param evenement
* @return
*/
function arreter(evenement) {
if (evenement.stopPropagation) {
evenement.stopPropagation();
}
if (evenement.preventDefault) {
evenement.preventDefault();
}
return false;
}
 
function extraireEnteteDebug(jqXHR) {
var msgDebug = '';
if (jqXHR.getResponseHeader("X-DebugJrest-Data") != '') {
var debugInfos = jQuery.parseJSON(jqXHR.getResponseHeader("X-DebugJrest-Data"));
if (debugInfos != null) {
$.each(debugInfos, function (cle, valeur) {
msgDebug += valeur + "\n";
});
}
}
return msgDebug;
}
 
function afficherPanneau(selecteur) {
$(selecteur).fadeIn("slow").delay(DUREE_MESSAGE).fadeOut("slow");
}
 
//+----------------------------------------------------------------------------------------------------------+
//UPLOAD PHOTO : Traitement de l'image
$(document).ready(function() {
 
$(".effacer-miniature").click(function () {
supprimerMiniatures($(this));
});
 
$("#fichier").bind('change', function (e) {
arreter(e);
var options = {
success: afficherMiniature, // post-submit callback
dataType: 'xml', // 'xml', 'script', or 'json' (expected server response type)
resetForm: true // reset the form after successful submit
};
$("#miniature").append('<img id="miniature-chargement" class="miniature" alt="chargement" src="'+CHARGEMENT_IMAGE_URL+'"/>');
$("#ajouter-obs").attr('disabled', 'disabled');
if(verifierFormat($("#fichier").val())) {
$("#form-upload").ajaxSubmit(options);
} else {
$('#form-upload')[0].reset();
window.alert("Le format de fichier n'est pas supporté, les formats acceptés sont "+ $("#fichier").attr("accept"));
}
return false;
});
 
if(ESPECE_IMPOSEE) {
$("#taxon").attr("disabled", "disabled");
$("#taxon-input-groupe").attr("title","");
var infosAssociee = new Object();
infosAssociee.label = INFOS_ESPECE_IMPOSEE.nom_sci_complet;
infosAssociee.value = INFOS_ESPECE_IMPOSEE.nom_sci_complet;
infosAssociee.nt = INFOS_ESPECE_IMPOSEE.num_taxonomique;
infosAssociee.nomSel = INFOS_ESPECE_IMPOSEE.nom_sci;
infosAssociee.nomSelComplet = INFOS_ESPECE_IMPOSEE.nom_sci_complet;
infosAssociee.numNomSel = INFOS_ESPECE_IMPOSEE.id;
infosAssociee.nomRet = INFOS_ESPECE_IMPOSEE["nom_retenu.libelle"];
infosAssociee.numNomRet = INFOS_ESPECE_IMPOSEE["nom_retenu.id"];
infosAssociee.famille = INFOS_ESPECE_IMPOSEE.famille;
infosAssociee.retenu = (INFOS_ESPECE_IMPOSEE.retenu == 'false') ? false : true;
$("#taxon").data(infosAssociee);
}
 
$('.effacer-miniature').live('click', function() {
$(this).parent().remove();
});
});
 
function verifierFormat(nom) {
var parts = nom.split('.');
extension = parts[parts.length - 1];
return (extension.toLowerCase() == 'jpeg' || extension.toLowerCase() == 'jpg');
}
 
function afficherMiniature(reponse) {
if (DEBUG) {
var debogage = $("debogage", reponse).text();
//console.log("Débogage upload : "+debogage);
}
var message = $("message", reponse).text();
if (message != '') {
$("#miniature-msg").append(message);
} else {
$("#miniatures").append(creerWidgetMiniature(reponse));
}
$('#ajouter-obs').removeAttr('disabled');
}
 
function creerWidgetMiniature(reponse) {
var miniatureUrl = $("miniature-url", reponse).text();
var imgNom = $("image-nom", reponse).text();
var html =
'<div class="miniature">'+
'<img class="miniature-img" class="miniature" alt="'+imgNom+'" src="'+miniatureUrl+'"/>'+
'<button class="effacer-miniature" type="button">Effacer</button>'+
'</div>'
return html;
}
 
function supprimerMiniatures() {
$("#miniatures").empty();
$("#miniature-msg").empty();
}
 
//Initialise l'autocomplétion de la commune, en fonction du référentiel
function initialiserAutocompleteCommune() {
var geocoderOptions = {
};
var addressSuffix = '';
 
switch(NOM_SCI_PROJET) {
case 'isfan':
// Si des résultats se trouvent dans ce rectangle, ils apparaîtront en premier.
// Ça marche moyen...
geocoderOptions.bounds = new google.maps.LatLngBounds(
new google.maps.LatLng(20.756114, -22.023927),
new google.maps.LatLng(38.065392, 33.78662)
);
break;
case 'apd':
geocoderOptions.bounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-6.708254, -26.154786),
new google.maps.LatLng(27.488781, 30.490722)
);
break;
case 'bdtfx':
case 'bdtxa':
geocoderOptions.region = 'fr';
addressSuffix = ', France';
}
 
$("#carte-recherche").autocomplete({
//Cette partie utilise geocoder pour extraire des valeurs d'adresse
source: function(request, response) {
geocoderOptions.address = request.term + addressSuffix;
console.log('Geocoder options', geocoderOptions);
geocoder.geocode( geocoderOptions, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
response($.map(results, function(item) {
var retour = {
label: item.formatted_address,
value: item.formatted_address,
latitude: item.geometry.location.lat(),
longitude: item.geometry.location.lng()
};
return retour;
}));
} else {
afficherErreurGoogleMap(status);
}
});
},
// Cette partie est executee a la selection d'une adresse
select: function(event, ui) {
var latLng = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
deplacerMarker(latLng);
}
});
 
// Autocompletion du champ adresse
$("#carte-recherche").on('focus', function() {
$(this).select();
});
$("#carte-recherche").on('mouseup', function(event) {// Pour Safari...
event.preventDefault();
});
 
$("#carte-recherche").keypress(function(e) {
if (e.which == 13) {
e.preventDefault();
}
});
};
 
//+----------------------------------------------------------------------------------------------------------+
// GOOGLE MAP
var map;
var marker;
var latLng;
var geocoder;
 
$(document).ready(function() {
initialiserGoogleMap();
initialiserAutocompleteCommune();
});
 
function afficherErreurGoogleMap(status) {
if (DEBUG) {
$('#dialogue-google-map .contenu').empty().append(
'<pre class="msg-erreur">'+
"Le service de Géocodage de Google Map a échoué à cause de l'erreur : "+status+
'</pre>');
afficherPanneau('#dialogue-google-map');
}
}
 
function surDeplacementMarker() {
trouverCommune(marker.getPosition());
mettreAJourMarkerPosition(marker.getPosition());
}
 
function surClickDansCarte(event) {
deplacerMarker(event.latLng);
}
 
function geolocaliser() {
var latitude = $('#latitude').val();
var longitude = $('#longitude').val();
latLng = new google.maps.LatLng(latitude, longitude);
deplacerMarker(latLng);
}
 
function initialiserGoogleMap(){
// Carte
if(NOM_SCI_PROJET == 'bdtxa') {
var latLng = new google.maps.LatLng(14.6, -61.08334);// Fort-De-France
var zoomDefaut = 8;
} else if(NOM_SCI_PROJET == 'isfan') {
var latLng = new google.maps.LatLng(29.28358, 10.21884);// Afrique du Nord
var zoomDefaut = 4;
} else if(NOM_SCI_PROJET == 'apd') {
var latLng = new google.maps.LatLng(8.75624, 1.80176);// Afrique de l'Ouest et du Centre
var zoomDefaut = 4;
} else {
var latLng = new google.maps.LatLng(46.30871, 2.54395);// Centre de la France
var zoomDefaut = 5;
}
 
var options = {
zoom: zoomDefaut,
center: latLng,
mapTypeId: google.maps.MapTypeId.HYBRID,
mapTypeControlOptions: {
mapTypeIds: ['OSM', google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.HYBRID, google.maps.MapTypeId.SATELLITE, google.maps.MapTypeId.TERRAIN]}
};
 
// Ajout de la couche OSM à la carte
osmMapType = new google.maps.ImageMapType({
getTileUrl: function(coord, zoom) {
return "http://tile.openstreetmap.org/" +
zoom + "/" + coord.x + "/" + coord.y + ".png";
},
tileSize: new google.maps.Size(256, 256),
isPng: true,
alt: 'OpenStreetMap',
name: 'OSM',
maxZoom: 19
});
 
// Création de la carte Google
map = new google.maps.Map(document.getElementById('map-canvas'), options); //affiche la google map dans la div map_canvas
map.mapTypes.set('OSM', osmMapType);
 
// Création du Geocoder
geocoder = new google.maps.Geocoder();
 
// Marqueur google draggable
marker = new google.maps.Marker({
map: map,
draggable: true,
title: 'Ma station',
icon: GOOGLE_MAP_MARQUEUR_URL,
position: latLng
});
 
initialiserMarker(latLng);
 
// Tentative de geocalisation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
latLng = new google.maps.LatLng(latitude, longitude);
deplacerMarker(latLng);
});
}
 
// intéraction carte
$("#geolocaliser").on('click', geolocaliser);
google.maps.event.addListener(marker, 'dragend', surDeplacementMarker);
google.maps.event.addListener(map, 'click', surClickDansCarte);
}
 
function initialiserMarker(latLng) {
if (marker != undefined) {
marker.setPosition(latLng);
map.setCenter(latLng);
}
}
 
function deplacerMarker(latLng) {
if (marker != undefined) {
marker.setPosition(latLng);
map.setCenter(latLng);
mettreAJourMarkerPosition(latLng);
trouverCommune(latLng);
}
}
 
function mettreAJourMarkerPosition(latLng) {
var lat = latLng.lat().toFixed(5);
var lng = latLng.lng().toFixed(5);
remplirChampLatitude(lat);
remplirChampLongitude(lng);
}
 
function remplirChampLatitude(latDecimale) {
var lat = Math.round(latDecimale * 100000) / 100000;
$('#latitude').val(lat);
}
 
function remplirChampLongitude(lngDecimale) {
var lng = Math.round(lngDecimale * 100000) / 100000;
$('#longitude').val(lng);
}
 
function trouverCommune(pos) {
$(function() {
 
var url_service = SERVICE_NOM_COMMUNE_URL;
 
var urlNomCommuneFormatee = url_service.replace('{lat}', pos.lat()).replace('{lon}', pos.lng());
$.ajax({
url : urlNomCommuneFormatee,
type : "GET",
dataType : "jsonp",
beforeSend : function() {
$(".commune-info").empty();
$("#dialogue-erreur .alert-txt").empty();
},
success : function(data, textStatus, jqXHR) {
$(".commune-info").empty();
$("#commune-nom").append(data.nom);
$("#commune-code-insee").append(data.codeINSEE);
$("#marqueur-commune").data('commune', {'nom' : data.nom, 'codeInsee' : data.codeINSEE});
},
statusCode : {
500 : function(jqXHR, textStatus, errorThrown) {
if (DEBUG) {
$("#dialogue-erreur .alert-txt").append('<p id="msg">Un problème est survenu lors de l\'appel au service fournissante le nom des communes.</p>');
reponse = jQuery.parseJSON(jqXHR.responseText);
var erreurMsg = "";
if (reponse != null) {
$.each(reponse, function (cle, valeur) {
erreurMsg += valeur + "<br />";
});
}
 
$("#dialogue-erreur .alert-txt").append('<p class="msg-erreur">Erreur 500 : '+errorThrown+"<br />"+erreurMsg+'</p>');
}
}
},
error : function(jqXHR, textStatus, errorThrown) {
if (DEBUG) {
$("#dialogue-erreur .alert-txt").append('<p class="msg">Une erreur Ajax est survenue lors de la transmission de vos observations.</p>');
reponse = jQuery.parseJSON(jqXHR.responseText);
var erreurMsg = "";
if (reponse != null) {
$.each(reponse, function (cle, valeur) {
erreurMsg += valeur + "<br />";
});
}
 
$("#dialogue-erreur .alert-txt").append('<p class="msg-erreur">Erreur Ajax : '+errorThrown+' (type : '+textStatus+') <br />'+erreurMsg+'</p>');
}
},
complete : function(jqXHR, textStatus) {
var debugMsg = extraireEnteteDebug(jqXHR);
if (debugMsg != '') {
if (DEBUG) {
$("#dialogue-erreur .alert-txt").append('<pre class="msg-debug msg">Débogage : '+debugMsg+'</pre>');
}
}
if ($("#dialogue-erreur .msg").length > 0) {
$("#dialogue-erreur").show();
}
}
});
});
}
//+---------------------------------------------------------------------------------------------------------+
// IDENTITÉ
$(document).ready(function() {
$("#courriel").on('blur', requeterIdentite);
$("#courriel").on('keypress', testerLancementRequeteIdentite);
});
 
function testerLancementRequeteIdentite(event) {
if (event.which == 13) {
requeterIdentite();
event.preventDefault();
event.stopPropagation();
}
}
 
function requeterIdentite() {
var courriel = $("#courriel").val();
//TODO: mettre ceci en paramètre de config
var urlAnnuaire = SERVICE_ANNUAIRE_ID_URL+courriel;
$.ajax({
url : urlAnnuaire,
type : "GET",
success : function(data, textStatus, jqXHR) {
//console.log('SUCCESS:'+textStatus);
if (data != undefined && data[courriel] != undefined) {
var infos = data[courriel];
$("#id_utilisateur").val(infos.id);
$("#prenom").val(infos.prenom);
$("#nom").val(infos.nom);
$("#courriel_confirmation").val(courriel);
$("#prenom, #nom, #courriel_confirmation").attr('disabled', 'disabled');
$("#date").focus();
} else {
surErreurCompletionCourriel();
}
},
error : function(jqXHR, textStatus, errorThrown) {
//console.log('ERREUR :'+textStatus);
surErreurCompletionCourriel();
},
complete : function(jqXHR, textStatus) {
//console.log('COMPLETE :'+textStatus);
$("#zone-prenom-nom").removeClass("hidden");
$("#zone-courriel-confirmation").removeClass("hidden");
}
});
}
 
function surErreurCompletionCourriel() {
$("#prenom, #nom, #courriel_confirmation").val('');
$("#prenom, #nom, #courriel_confirmation").removeAttr('disabled');
afficherPanneau("#dialogue-courriel-introuvable");
}
//+---------------------------------------------------------------------------------------------------------+
//FORMULAIRE
$(document).ready(function() {
if (OBS_ID != '') {
chargerInfoObs();
}
});
 
function chargerInfoObs() {
var urlObs = SERVICE_OBS_URL + '/' + OBS_ID;
$.ajax({
url: urlObs,
type: 'GET',
success: function(data, textStatus, jqXHR) {
if (data != undefined && data != "") {
prechargerForm(data);
}
// TODO: voir s'il est pertinent d'indiquer quelque chose en cas d'erreur ou d'obs
// inexistante
},
error: function(jqXHR, textStatus, errorThrown) {
// TODO: cf TODO ci-dessus
}
});
}
 
function prechargerForm(data) {
 
$("#milieu").val(data.milieu);
 
$("#carte-recherche").val(data.zoneGeo);
$("#commune-nom").text(data.zoneGeo);
 
if(data.hasOwnProperty("codeZoneGeo")) {
// TODO: trouver un moyen qui fonctionne lorsqu'on aura d'autres référentiels que INSEE
$("#commune-code-insee").text(data.codeZoneGeo.replace('INSEE-C:', ''));
}
 
if(data.hasOwnProperty("latitude") && data.hasOwnProperty("longitude")) {
var latLng = new google.maps.LatLng(data.latitude, data.longitude);
mettreAJourMarkerPosition(latLng);
marker.setPosition(latLng);
map.setCenter(latLng);
map.setZoom(16);
}
}
 
var obsNbre = 0;
 
$(document).ready(function() {
$(".alert .close").on('click', fermerPanneauAlert);
 
$("body").on('click', ".fermer", function(event) {
event.preventDefault();
basculerOuvertureFermetureCadre($(this).find('.icone'));
});
 
$('.has-tooltip').tooltip('enable');
$("#btn-aide").on('click', basculerAffichageAide);
 
$("#prenom").on("change", formaterPrenom);
 
$("#nom").on("change", formaterNom);
 
configurerDatePicker();
 
ajouterAutocompletionNoms();
 
configurerFormValidator();
definirReglesFormValidator();
 
$("#courriel_confirmation").on('paste', bloquerCopierCollerCourriel);
 
$("a.afficher-coord").on('click', basculerAffichageCoord);
 
$("#ajouter-obs").on('click', ajouterObs);
 
$(".obs-nbre").on('changement', surChangementNbreObs);
 
$("body").on('click', ".supprimer-obs", supprimerObs);
 
$("#transmettre-obs").on('click', transmettreObs);
 
$("#referentiel").on('change', surChangementReferentiel);
 
$("body").on('click', ".defilement-miniatures-gauche", function(event) {
event.preventDefault();
defilerMiniatures($(this));
});
 
$("body").on('click', ".defilement-miniatures-droite", function(event) {
event.preventDefault();
defilerMiniatures($(this));
});
});
 
function configurerFormValidator() {
$.validator.addMethod(
"dateCel",
function (value, element) {
return value == "" || (/^[0-9]{2}[-\/][0-9]{2}[-\/][0-9]{4}$/.test(value));
},
"Format : jj/mm/aaaa. Date incomplète, utiliser 0, exemple : 00/12/2011.");
 
$.extend($.validator.defaults, {
ignore: [],// Forcer Jquery Validate à examiner les éléments avec en display:none;
highlight: function(element) {
$(element).closest('.control-group').removeClass('success').addClass('error');
},
success: function(element) {
element.text('OK!').addClass('valid');
element.closest('.control-group').removeClass('error').addClass('success');
 
if (element.attr('id') == 'taxon' && $('#taxon').val() != '') {
// Si le taxon n'est pas lié au référentiel, on vide le data associé
if ($('#taxon').data('value') != $('#taxon').val()) {
$('#taxon').data('numNomSel', '');
$('#taxon').data('nomRet', '');
$('#taxon').data('numNomRet', '');
$('#taxon').data('nt', '');
$('#taxon').data('famille', '');
}
}
}
});
}
 
function definirReglesFormValidator() {
$('#form-observateur').validate({
rules: {
courriel : {
required : true,
email : true},
courriel_confirmation : {
required : true,
equalTo: '#courriel'}
}
});
$('#form-station').validate({
rules: {
latitude : {
range: [-90, 90],
required: true},
longitude : {
range: [-180, 180],
required: true},
stationSurface: 'required',
milieu: 'required'
}
});
$('#form-obs').validate({
rules: {
date: {
required: true,
'dateCel' : true},
taxon: 'required',
recouvrement: 'required'
},
errorPlacement: function(error, element) {
if (element.attr('name') == 'date') {
element.parent('.input-prepend').after(error);
} else {
error.insertAfter(element);
}
}
});
}
 
function configurerDatePicker() {
$.datepicker.setDefaults($.datepicker.regional["fr"]);
$("#date").datepicker({
dateFormat: "dd/mm/yy",
maxDate: new Date,
showOn: "button",
buttonImageOnly: true,
buttonImage: CALENDRIER_ICONE_URL,
buttonText: "Afficher le calendrier pour saisir la date.",
showButtonPanel: true,
onSelect: function(date) {
$(this).valid();
}
});
$("img.ui-datepicker-trigger").appendTo("#date-icone");
}
 
function fermerPanneauAlert() {
$(this).parentsUntil(".zone-alerte", ".alert").hide();
}
 
function formaterNom() {
$(this).val($(this).val().toUpperCase());
}
 
function formaterPrenom() {
var prenom = new Array();
var mots = $(this).val().split(' ');
for (var i = 0; i < mots.length; i++) {
var mot = mots[i];
if (mot.indexOf('-') >= 0) {
var prenomCompose = new Array();
var motsComposes = mot.split('-');
for (var j = 0; j < motsComposes.length; j++) {
var motSimple = motsComposes[j];
var motMajuscule = motSimple.charAt(0).toUpperCase() + motSimple.slice(1);
prenomCompose.push(motMajuscule);
}
prenom.push(prenomCompose.join('-'));
} else {
var motMajuscule = mot.charAt(0).toUpperCase() + mot.slice(1);
prenom.push(motMajuscule);
}
}
$(this).val(prenom.join(' '));
}
 
function basculerOuvertureFermetureCadre(element) {
if (element.hasClass('icon-plus-sign')) {
element.removeClass('icon-plus-sign').addClass('icon-minus-sign');
} else {
element.removeClass('icon-minus-sign').addClass('icon-plus-sign');
}
}
 
function basculerAffichageAide() {
if ($(this).hasClass('btn-warning')) {
$('.has-tooltip').tooltip('enable');
$(this).removeClass('btn-warning').addClass('btn-success');
$('#btn-aide-txt', this).text("Désactiver l'aide");
} else {
$('.has-tooltip').tooltip('disable');
$(this).removeClass('btn-success').addClass('btn-warning');
$('#btn-aide-txt', this).text("Activer l'aide");
}
}
 
function bloquerCopierCollerCourriel() {
afficherPanneau("#dialogue-bloquer-copier-coller");
return false;
}
 
function basculerAffichageCoord() {
$("a.afficher-coord").toggle();
$("#coordonnees-geo").toggle('slow');
//valeur false pour que le lien ne soit pas suivi
return false;
}
 
function ajouterObs() {
if (validerFormulaire() == true) {
obsNbre = obsNbre + 1;
$(".obs-nbre").text(obsNbre);
$(".obs-nbre").triggerHandler('changement');
afficherObs();
stockerObsData();
supprimerMiniatures();
if(!ESPECE_IMPOSEE) {
$("#taxon").val("");
$("#taxon").data("numNomSel",undefined);
}
$('#barre-progression-upload').attr('aria-valuemax', obsNbre);
$('#barre-progression-upload .sr-only').text('0/'+obsNbre+" observations transmises");
} else {
afficherPanneau('#dialogue-form-invalide');
}
}
 
function afficherObs() {
$("#liste-obs").prepend(
'<div id="obs'+obsNbre+'" class="row-fluid obs obs'+obsNbre+'">'+
'<div class="span12">'+
'<div class="well">'+
'<div class="obs-action pull-right has-tooltip" data-placement="bottom" '+
'title="Supprimer cette observation de la liste à transmettre">'+
'<button class="btn btn-danger supprimer-obs" value="'+obsNbre+'" title="'+obsNbre+'">'+
'<i class="icon-trash icon-white"></i>'+
'</button>'+
'</div> '+
'<div class="row-fluid">'+
'<div class="thumbnail span2">'+
ajouterImgMiniatureAuTransfert()+
'</div>'+
'<div class="span9">'+
'<ul class="unstyled">'+
'<li>'+
'<span class="nom-sci">'+$("#taxon").val()+'</span> '+
ajouterNumNomSel()+'<span class="referentiel-obs">'+
($("#taxon").data("numNomSel") == undefined ? '' : '['+NOM_SCI_PROJET+']')+'</span>'+
' observé à '+
'<span class="commune">'+$('#commune-nom').text()+'</span> '+
'('+$('#commune-code-insee').text()+') ['+$("#latitude").val()+' / '+$("#longitude").val()+']'+
' le '+
'<span class="date">'+$("#date").val()+'</span>'+
'</li>'+
'<li>'+
'<span>Lieu-dit :</span> '+$('#lieudit').val()+' '+
'<span>Station :</span> '+$('#station').val()+' '+
'<span>Milieu :</span> '+$('#milieu').val()+' '+
'</li>'+
'<li>'+
'Commentaires : <span class="discretion">'+$("#notes").val()+'</span>'+
'</li>'+
'</ul>'+
'</div>'+
'</div>'+
'</div>'+
'</div>'+
'</div>');
}
 
function stockerObsData() {
$("#liste-obs").data('obsId'+obsNbre, {
'date' : $("#date").val(),
'notes' : $("#notes").val(),
 
'nom_sel' : $("#taxon").val(),
'num_nom_sel' : $("#taxon").data("numNomSel"),
'nom_ret' : $("#taxon").data("nomRet"),
'num_nom_ret' : $("#taxon").data("numNomRet"),
'num_taxon' : $("#taxon").data("nt"),
'famille' : $("#taxon").data("famille"),
'referentiel' : ($("#taxon").data("numNomSel") == undefined ? '' : NOM_SCI_PROJET),
 
'latitude' : $("#latitude").val(),
'longitude' : $("#longitude").val(),
'commune_nom' : $("#commune-nom").text(),
'commune_code_insee' : $("#commune-code-insee").text(),
'lieudit' : $("#lieudit").val(),
'station' : $("#station").val(),
'milieu' : $("#milieu").val(),
 
//Ajout des champs images
'image_nom' : getNomsImgsOriginales(),
'image_b64' : getB64ImgsOriginales(),
 
// Ajout des champs étendus de l'obs
'obs_etendue': getObsChpEtendus()
});
console.log($("#liste-obs").data('obsId'+obsNbre));
}
 
function getObsChpEtendus() {
var champs = [];
 
$('.obs-chp-etendu').each(function() {
var valeur = $(this).val(),
cle = $(this).attr('name'),
label = $(this).data('label');
if (valeur != '') {
var chpEtendu = {cle: cle, label: label, valeur: valeur};
champs.push(chpEtendu);
}
});
return champs;
}
 
function surChangementReferentiel() {
NOM_SCI_PROJET = $('#referentiel').val();
NOM_SCI_REFERENTIEL = NOM_SCI_PROJET+':'+PROJETS_VERSIONS[NOM_SCI_PROJET];
$('#taxon').val('');
initialiserAutocompleteCommune();
initialiserGoogleMap();
}
 
function surChangementNbreObs() {
if (obsNbre == 0) {
$("#transmettre-obs").attr('disabled', 'disabled');
$("#ajouter-obs").removeAttr('disabled');
} else if (obsNbre > 0 && obsNbre < OBS_MAX_NBRE) {
$("#transmettre-obs").removeAttr('disabled');
$("#ajouter-obs").removeAttr('disabled');
} else if (obsNbre >= OBS_MAX_NBRE) {
$("#ajouter-obs").attr('disabled', 'disabled');
afficherPanneau("#dialogue-bloquer-creer-obs");
}
}
 
var nbObsEnCours = 1;
var totalObsATransmettre = 0;
function transmettreObs() {
var observations = $("#liste-obs").data();
if (observations == undefined || jQuery.isEmptyObject(observations)) {
afficherPanneau("#dialogue-zero-obs");
} else {
nbObsEnCours = 1;
nbObsTransmises = 0;
totalObsATransmettre = $.map(observations, function(n, i) { return i; }).length;
depilerObsPourEnvoi();
}
return false;
}
 
function depilerObsPourEnvoi() {
var observations = $("#liste-obs").data();
// la boucle est factice car on utilise un tableau
// dont on a besoin de n'extraire que le premier élément
// or javascript n'a pas de méthode cross browsers pour extraire les clés
// TODO: utiliser var.keys quand ça sera plus répandu
// ou bien utiliser un vrai tableau et pas un objet
for (var obsNum in observations) {
obsATransmettre = new Object();
 
obsATransmettre['projet'] = TAG_PROJET;
obsATransmettre['tag-obs'] = TAG_OBS;
obsATransmettre['tag-img'] = TAG_IMG;
 
var utilisateur = new Object();
utilisateur.id_utilisateur = $("#id_utilisateur").val();
utilisateur.prenom = $("#prenom").val();
utilisateur.nom = $("#nom").val();
utilisateur.courriel = $("#courriel").val();
obsATransmettre['utilisateur'] = utilisateur;
obsATransmettre[obsNum] = observations[obsNum];
var idObsNumerique = obsNum.replace('obsId', '');
if(idObsNumerique != "") {
envoyerObsAuCel(idObsNumerique, obsATransmettre);
}
 
break;
}
}
 
var nbObsTransmises = 0;
function mettreAJourProgression() {
nbObsTransmises++;
var pct = (nbObsTransmises/totalObsATransmettre)*100;
$('#barre-progression-upload').attr('aria-valuenow', nbObsTransmises);
$('#barre-progression-upload').attr('style', "width: "+pct+"%");
$('#barre-progression-upload .sr-only').text(nbObsTransmises+"/"+totalObsATransmettre+" observations transmises");
 
if(obsNbre == 0) {
$('.progress').removeClass('active');
$('.progress').removeClass('progress-striped');
}
}
 
function envoyerObsAuCel(idObs, observation) {
var erreurMsg = "";
$.ajax({
url : SERVICE_SAISIE_URL,
type : "POST",
data : observation,
dataType : "json",
beforeSend : function() {
$("#dialogue-obs-transaction-ko").hide();
$("#dialogue-obs-transaction-ok").hide();
$(".alert-txt .msg").remove();
$(".alert-txt .msg-erreur").remove();
$(".alert-txt .msg-debug").remove();
$("#chargement").show();
},
success : function(data, textStatus, jqXHR) {
// mise à jour du nombre d'obs à transmettre
// et suppression de l'obs
supprimerObsParId(idObs);
nbObsEnCours++;
// mise à jour du statut
mettreAJourProgression();
if(obsNbre > 0) {
// dépilement de la suivante
depilerObsPourEnvoi();
}
},
statusCode : {
500 : function(jqXHR, textStatus, errorThrown) {
erreurMsg += "Erreur 500 :\ntype : "+textStatus+' '+errorThrown+"\n";
}
},
error : function(jqXHR, textStatus, errorThrown) {
erreurMsg += "Erreur Ajax :\ntype : "+textStatus+' '+errorThrown+"\n";
try {
reponse = jQuery.parseJSON(jqXHR.responseText);
if (reponse != null) {
$.each(reponse, function (cle, valeur) {
erreurMsg += valeur + "\n";
});
}
} catch(e) {
erreurMsg += "L'erreur n'était pas en JSON.";
}
},
complete : function(jqXHR, textStatus) {
var debugMsg = extraireEnteteDebug(jqXHR);
 
if (erreurMsg != '') {
if (DEBUG) {
$("#dialogue-obs-transaction-ko .alert-txt").append('<pre class="msg-erreur">'+erreurMsg+'</pre>');
$("#dialogue-obs-transaction-ko .alert-txt").append('<pre class="msg-debug">Débogage : '+debugMsg+'</pre>');
}
var hrefCourriel = "mailto:cel_remarques@tela-botanica.org?"+
"subject=Dysfonctionnement du widget de saisie "+TAG_PROJET+
"&body="+erreurMsg+"%0D%0ADébogage :%0D%0A"+debugMsg;
 
// mise en valeur de l'obs en erreur + scroll vers celle ci en changeant le hash
$('#obs'+idObs+' div div').addClass('obs-erreur');
window.location.hash = "obs"+idObs;
 
$('#dialogue-obs-transaction-ko .alert-txt').append($("#tpl-transmission-ko").clone()
.find('.courriel-erreur')
.attr('href', hrefCourriel)
.end()
.html());
$("#dialogue-obs-transaction-ko").show();
$("#chargement").hide();
initialiserBarreProgression();
} else {
if (DEBUG) {
$("#dialogue-obs-transaction-ok .alert-txt").append('<pre class="msg-debug">Débogage : '+debugMsg+'</pre>');
}
if(obsNbre == 0) {
setTimeout(function() {
$("#chargement").hide();
$('#dialogue-obs-transaction-ok .alert-txt').append($('#tpl-transmission-ok').clone().html());
$("#dialogue-obs-transaction-ok").show();
window.location.hash = "dialogue-obs-transaction-ok";
initialiserObs();
}, 1500);
 
}
}
}
});
}
 
function validerFormulaire() {
$observateur = $("#form-observateur").valid();
$station = $("#form-station").valid();
$obs = $("#form-obs").valid();
return ($observateur == true && $station == true && $obs == true) ? true : false;
}
 
function getNomsImgsOriginales() {
var noms = new Array();
$(".miniature-img").each(function() {
noms.push($(this).attr('alt'));
});
return noms;
}
 
function getB64ImgsOriginales() {
var b64 = new Array();
$(".miniature-img").each(function() {
if ($(this).hasClass('b64')) {
b64.push($(this).attr('src'));
} else if ($(this).hasClass('b64-canvas')) {
b64.push($(this).data('b64'));
}
});
 
return b64;
}
 
function supprimerObs() {
var obsId = $(this).val();
// Problème avec IE 6 et 7
if (obsId == "Supprimer") {
obsId = $(this).attr("title");
}
supprimerObsParId(obsId);
}
 
function supprimerObsParId(obsId) {
obsNbre = obsNbre - 1;
$(".obs-nbre").text(obsNbre);
$(".obs-nbre").triggerHandler('changement');
$('.obs'+obsId).remove();
$("#liste-obs").removeData('obsId'+obsId);
}
 
function initialiserBarreProgression() {
$('#barre-progression-upload').attr('aria-valuenow', 0);
$('#barre-progression-upload').attr('style', "width: 0%");
$('#barre-progression-upload .sr-only').text("0/0 observations transmises");
$('.progress').addClass('active');
$('.progress').addClass('progress-striped');
}
 
function initialiserObs() {
obsNbre = 0;
nbObsTransmises = 0;
nbObsEnCours = 0;
totalObsATransmettre = 0;
initialiserBarreProgression();
$(".obs-nbre").text(obsNbre);
$(".obs-nbre").triggerHandler('changement');
$("#liste-obs").removeData();
$('.obs').remove();
$("#dialogue-bloquer-creer-obs").hide();
}
 
function ajouterImgMiniatureAuTransfert() {
var html = '';
var miniatures = '';
var premiere = true;
if ($("#miniatures img").length >= 1) {
$("#miniatures img").each(function() {
var visible = premiere ? 'miniature-selectionnee' : 'miniature-cachee';
premiere = false;
var css = $(this).hasClass('b64') ? 'miniature b64' : 'miniature';
var src = $(this).attr("src");
var alt = $(this).attr("alt");
miniature = '<img class="'+css+' '+visible+'" alt="'+alt+'"src="'+src+'" />';
miniatures += miniature;
});
visible = ($("#miniatures img").length > 1) ? '' : 'defilement-miniatures-cache';
var html =
'<div class="defilement-miniatures">'+
'<a href="#" class="defilement-miniatures-gauche '+visible+'">&#60;</a>'+
miniatures+
'<a href="#" class="defilement-miniatures-droite '+visible+'">&#62;</a>'+
'</div>';
} else {
html = '<img class="miniature" alt="Aucune photo"src="'+PAS_DE_PHOTO_ICONE_URL+'" />';
}
return html;
}
 
function defilerMiniatures(element) {
 
var miniatureSelectionne = element.siblings("img.miniature-selectionnee");
miniatureSelectionne.removeClass('miniature-selectionnee');
miniatureSelectionne.addClass('miniature-cachee');
var miniatureAffichee = miniatureSelectionne;
 
if(element.hasClass('defilement-miniatures-gauche')) {
if(miniatureSelectionne.prev('.miniature').length != 0) {
miniatureAffichee = miniatureSelectionne.prev('.miniature');
} else {
miniatureAffichee = miniatureSelectionne.siblings(".miniature").last();
}
} else {
if(miniatureSelectionne.next('.miniature').length != 0) {
miniatureAffichee = miniatureSelectionne.next('.miniature');
} else {
miniatureAffichee = miniatureSelectionne.siblings(".miniature").first();
}
}
//console.log(miniatureAffichee);
miniatureAffichee.addClass('miniature-selectionnee');
miniatureAffichee.removeClass('miniature-cachee');
}
 
function ajouterNumNomSel() {
var nn = '';
if ($("#taxon").data("numNomSel") == undefined) {
nn = '<span class="alert-error">[non lié au référentiel]</span>';
} else {
nn = '<span class="nn">[nn'+$("#taxon").data("numNomSel")+']</span>';
}
return nn;
}
 
//+---------------------------------------------------------------------------------------------------------+
// AUTO-COMPLÉTION Noms Scientifiques
 
function ajouterAutocompletionNoms() {
$('#taxon').autocomplete({
source: function(requete, add){
// la variable de requête doit être vidée car sinon le parametre "term" est ajouté
requete = "";
var url = getUrlAutocompletionNomsSci();
$.getJSON(url, requete, function(data) {
var suggestions = traiterRetourNomsSci(data);
add(suggestions);
});
},
html: true
});
 
$( "#taxon" ).bind("autocompleteselect", function(event, ui) {
$("#taxon").data(ui.item);
if (ui.item.retenu == true) {
$("#taxon").addClass('ns-retenu');
} else {
$("#taxon").removeClass('ns-retenu');
}
});
}
 
function getUrlAutocompletionNomsSci() {
var mots = $('#taxon').val();
var url = SERVICE_AUTOCOMPLETION_NOM_SCI_URL_TPL.replace('{referentiel}',NOM_SCI_PROJET);
url = url.replace('{masque}', mots);
return url;
}
 
function traiterRetourNomsSci(data) {
var suggestions = [];
if (data.resultat != undefined) {
$.each(data.resultat, function(i, val) {
val.nn = i;
var nom = {label : '', value : '', nt : '', nomSel : '', nomSelComplet : '', numNomSel : '',
nomRet : '', numNomRet : '', famille : '', retenu : false
};
if (suggestions.length >= AUTOCOMPLETION_ELEMENTS_NBRE) {
nom.label = "...";
nom.value = $('#taxon').val();
suggestions.push(nom);
return false;
} else {
nom.label = val.nom_sci_complet;
nom.value = val.nom_sci_complet;
nom.nt = val.num_taxonomique;
nom.nomSel = val.nom_sci;
nom.nomSelComplet = val.nom_sci_complet;
nom.numNomSel = val.nn;
nom.nomRet = val.nom_retenu_complet;
nom.numNomRet = val["nom_retenu.id"];
nom.famille = val.famille;
// Tester dans ce sens, permet de considérer "absent" comme "false" => est-ce opportun ?
// en tout cas c'est harmonisé avec le CeL
nom.retenu = (val.retenu == 'true') ? true : false;
 
suggestions.push(nom);
}
});
}
 
return suggestions;
}
 
/*
* jQuery UI Autocomplete HTML Extension
*
* Copyright 2010, Scott González (http://scottgonzalez.com)
* Dual licensed under the MIT or GPL Version 2 licenses.
*
* http://github.com/scottgonzalez/jquery-ui-extensions
*
* Adaptation par Aurélien Peronnet pour la mise en gras des noms de taxons valides
*/
(function( $ ) {
var proto = $.ui.autocomplete.prototype,
initSource = proto._initSource;
 
function filter( array, term ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
return $.grep( array, function(value) {
return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
});
}
 
$.extend( proto, {
_initSource: function() {
if ( this.options.html && $.isArray(this.options.source) ) {
this.source = function( request, response ) {
response( filter( this.options.source, request.term ) );
};
} else {
initSource.call( this );
}
},
_renderItem: function( ul, item) {
if (item.retenu == true) {
item.label = "<strong>"+item.label+"</strong>";
}
 
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
.appendTo( ul );
}
});
})( jQuery );