';
},
afterSelect: function(item) {
obj.data('selected',true);
if(o.onClick) o.onClick(item,obj);
obj.trigger("change");
}
}).blur(function(){
if(o.onBlur) o.onBlur(obj);
});
if(o.suggest){
obj.off("click").on("click", function () {
if(typeof o.suggest === 'function' && !o.suggest()) return;
ev = $.Event("keydown");
ev.keyCode = ev.which = 40;
$(this).trigger(ev);
return true
});
}
obj.data('typeahead').next = function (event) {
var active = this.$menu.find('.active').removeClass('active');
var next = active.next();
if (!next.length) {
next = $(this.$menu.find($(this.options.item || this.theme.item).prop('tagName'))[0]);
}
while (next.hasClass('divider') || next.hasClass('dropdown-header')) {
next = next.next();
}
next.addClass('active');
var newVal = this.updater(next.data('value'));
this.$element.val(newVal.name || newVal.label || newVal);
};
obj.data('typeahead').prev = function (event) {
var active = this.$menu.find('.active').removeClass('active');
var prev = active.prev();
if (!prev.length){
prev = this.$menu.find($(this.options.item || this.theme.item).prop('tagName')).last();
}
while (prev.hasClass('divider') || prev.hasClass('dropdown-header')) {
prev = prev.prev();
}
prev.addClass('active');
var newVal = this.updater(prev.data('value'));
if (this.changeInputOnMove) this.$element.val(newVal.name || newVal.label || newVal);
};
});
},
location: function (options){
return this.each(function() {
var obj = $(this);
var o = $.extend({},options);
obj.off('keyup').on('keyup', function(event) {
if(!$(this).val().length) return;
});
obj.autocomplete({
action: 'core_location_search',
delay : 300,
force: (o.force ? o.force : false),
items: (o.items ? o.items : 8),
data: {
maxresults: (o.items ? o.items : 8),
language: (o.language ? o.language : "fr"),
country: (o.country ? o.country : ""),
},
skin : function(item){
var html = '';
var re = new RegExp(obj.val(),"gi");
name = item.label.replace(re, function (x) {
return ''+x+'';
});
html += name+'';
return html;
},
highlight : function(item){
return item;
},
onClick : function(selected,element){
obj.val(selected.label);
if(!is_empty_obj(selected.address)) {
var infos = {
number: selected.address.houseNumber ? selected.address.houseNumber : '',
street: selected.address.street ? selected.address.street : '',
district: selected.address.district ? selected.address.district : '',
city: selected.address.city ? selected.address.city : '',
county: selected.address.county ? selected.address.county : '',
state: selected.address.state ? selected.address.state : '',
country: selected.address.country ? selected.address.country : '',
zip: selected.address.postalCode ? selected.address.postalCode : '',
};
infos.address = (infos.street && infos.street.length && infos.number && infos.number.length) ? infos.number+' '+infos.street : (infos.street ? infos.street : '');
obj.removeData();
obj.data(infos);
if(o.select) o.select(infos);
if(o.geocode) o.geocode(selected);
}
},
onBlur : function(selected,element){
},
onCancel : function(element){
obj.val('');
}
});
});
},
colorInput: function (options) {
return this.each(function () {
var o = $.extend({
choices : [
'#34495e','#9b59b6','#3498db','#2ecc71','#1abc9c',
'#95a5a6','#ecf0f1','#e74c3c','#e67e22','#f1c40f',
'#d35400','#55E6C1','#EAB543','#F8EFBA','#FD7272',
'#3B3B98','#B33771','#6c5ce7','#0984e3','#00cec9',
'#fd79a8','#d63031','#a29bfe','#55efc4'
]
},options);
var input = $(this);
input.hide();
var component = input.data('data-component');
if(component){
//reload
}else{
var component = $('
');
//load
input.data('data-component',component);
input.after(component);
component.append(input.detach());
init_tooltips(component);
}
var picker = $('.component-color-picker',component);
var palette = $('.component-color-palette',component);
var thumb = $('.component-color-thumb',component);
thumb.css('backgroundColor',input.val());
var html = '
';
for(var k in o.choices){
html += '
';
}
html += '
';
html += '
';
picker.html(html);
$('.other-color',component).click( function(){
palette.click();
});
palette.change(function(){
input.val(palette.val()).change();
picker.addClass('hidden');
});
input.change(function(){
thumb.css('backgroundColor',input.val());
});
component.click(function(e){
e.stopPropagation();
if(input.is('[readonly]') || input.is('[disabled]')) return;
if($(e.target).closest('.component-color-picker').length || $(e.target).closest('.component-color-palette').length) return;
picker.removeClass('active');
setTimeout(function(){
picker.removeClass('hidden');
setTimeout(function(){picker.addClass('active')},50);
},150);
});
$('.color-choice',picker).click(function(e){
e.stopPropagation();
picker.removeClass('active');
setTimeout(function(){picker.addClass('hidden')},200);
input.val($(this).attr('data-color')).change();
});
$(document).click(function() {
picker.removeClass('active');
setTimeout(function(){picker.addClass('hidden')},200);
});
if(input.hasAttr('required')) component.attr('required','');
if(input.hasAttr('readonly')) component.attr('readonly','');
});
},
date: function (options){
return this.each(function(){
var obj = $(this);
obj.on('paste', function(e){
is_valid_date(e.originalEvent.clipboardData.getData('Text')) ? obj.val("") : e.preventDefault();
});
//Jours ouvrés
var minDate = options.beginDate;
var beforeShowDay = '';
if(options.workdays){
var minDate = new Date();
var daysToAdd = [0, 0, 2, 2, 2, 2, 1];
minDate.setDate(minDate.getDate()+parseInt(options.beginDate)+daysToAdd[minDate.getDay()]);
beforeShowDay = $.datepicker.noWeekends;
}
obj.datepicker({
dateFormat: options.dateFormat,
dayNames: ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi"],
dayNamesMin: ["Di", "Lu", "Ma", "Me", "Je", "Ve", "Sa"],
dayNamesShort: ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam"],
monthNames: ["Janvier","Février","Mars","Avril","Mai","Juin","Juillet","Aout","Septembre","Octobre","Novembre","Décembre"],
monthNamesShort: ["Jan","Fév","Mars","Avr","Mai","Juin","Juil","Aout","Sept","Oct","Nov","Déc"],
firstDay: 1,
minDate: minDate,
beforeShowDay: beforeShowDay,
maxDate: options.endDate,
changeMonth: true,
yearRange: "-100:+30",
changeYear: true,
onSelect: function(dateText, inst){
obj.trigger("blur");
obj.trigger("change");
},
beforeShow: function(){
if(obj.is('[readonly]')) return false;
}
}).keypress(function(event){
if(event.key=='/') event.preventDefault();
var length = obj.val().length;
if(length == 2 || length == 5) obj.val(obj.val()+'/');
}).blur(function(event){
obj.removeClass('border border-danger');
if(obj.val()=='') return;
var segments = obj.val().split('/');
if(segments.length!=3) return;
if(segments[0] > 31 || segments[1] > 12) obj.addClass('border border-danger');
}).attr('maxlength','10');
obj.attr('placeholder',options.placeholder);
obj.attr('pattern',"^(\\d{2}(?:\\d{2})?)\/(\\d{2})\/(\\d{2}(?:\\d{2})?)$");
obj.attr('title','Format '+options.dateFormat);
});
},
phone: function (options){
return this.each(function(){
var obj = $(this);
options = $.extend({
regex: '^[0-9]{10}$',
emptyField: false,
spacing: true,
typeOnly: '[0-9\+\s]',
invalidClass: 'invalid-value',
},options);
if(options.typeOnly){
obj.keydown(function(event){
if((event.ctrlKey && ['v','a','c','x'].indexOf(event.key) !== -1) || ['Backspace','ArrowLeft','ArrowRight',' '].indexOf(event.key) !== -1) return true;
var regexType = RegExp(options.typeOnly, 'g');
return regexType.test(event.key);
});
}
obj.blur(function(event){
var value = obj.val()
.trim()
.replace(/\s/ig,'')
.replace(/\+33/ig,'0');
if(value=='') return obj.removeClass(options.invalidClass);;
var regex = RegExp(options.regex, 'g');
if(!regex.test(value)){
obj.addClass(options.invalidClass);
if(options.emptyField) value = '';
} else {
if(options.spacing) value = value.match(/.{1,2}/g).join(' ');
obj.val(value);
obj.removeClass(options.invalidClass);
}
if(obj.data('blur')) eval(obj.data('blur'));
});
});
},
hour: function (options){
return this.each(function() {
var obj = $(this);
obj.on('paste', function(e){
is_valid_hour(e.originalEvent.clipboardData.getData('Text')) ? obj.val("") : e.preventDefault();
});
obj.timepicker({
scrollDefault: 'now',
timeFormat: options.timeFormat,
step: options.step,
onSelect: function(timeText, inst) {
obj.trigger("blur");
obj.trigger("change");
}
}).keydown(function(e) {
//Si c'est pas un chiffre ou :
if(!input_number_control(e)) return false;
//Si on efface et qu'on est après les deux points, on les supprime et le chiffre qui précède aussi
if(e.key=='Backspace' && obj.val().substr(obj.val().length-1)==':'){
e.preventDefault();
obj.val(obj.val().substring(0, obj.val().length-2));
//Premier digit avant les deux points supérieur à 2, on ajoute un 0 devant
} else if((obj.val().length==0 || get_selected_text(obj).length == obj.val().length) && e.key>2) {
e.preventDefault();
obj.val('0'+e.key+':');
//Gestion des deux points entre heures et minutes
} else if(obj.val().length==1 && e.key.match(/[0-9:]/)) {
e.preventDefault();
obj.val(obj.val()+e.key+':');
//Si le 1er digit après les deux points est supérieur à 5, on bloque
} else if(obj.val().length==3 && e.key>5 && get_selected_text(obj).length<2) {
e.preventDefault();
}
}).blur(function(event){
obj.removeClass('border border-danger')
if(obj.val()=='') return;
var segments = obj.val().split(':');
if(!segments[1]){
obj.val(obj.val()+'00');
segments[1] = '00';
}
if(segments.length!=2)return;
if(segments[0] > 23 || segments[1] > 59) obj.addClass('border border-danger');
}).attr('maxlength','5');
obj.attr("placeholder",options.placeholder);
obj.attr('title',"Format hh:mm");
});
},
raiseNumber: function(from,to,time) {
return this.each(function(){
var obj = $(this);
obj.text(from);
time = time!=null ? time : 100;
var ratio = (from<=to) ? to/time : from/time;
var increment = Math.round(ratio)<1 ? 1 : Math.round(ratio);
increment = (from<=to) ? increment : increment*-1;
var updateCount = function(obj, increment){
var count = parseInt(obj.text());
if((from<=to && countto && count>=to)) {
obj.text(count + increment);
setTimeout(function(){updateCount(obj,increment);}, 1);
} else {
obj.text(to);
}
};
updateCount(obj,increment);
});
},
component_autocomplete : function(slug,options){
if(!slug) $.message('error','Slug non définis pour un composant autocomplete');
var options = $.extend({
edit : slug+'_by_uid',
autocomplete : slug+'_autocomplete',
force : true,
nullChars : ['0'],
data : function(){
return {};
},
editData : function(){
return {};
}
},options);
return this.each(function(){
var input = $(this);
var container;
if(!input.data("data-component")){
container = $('');
input.before(container);
input.addClass('component-raw-value hidden'); // utilisé par les filtres / etc.. pour dissocier la valeur brute du composant
input.data("data-component", container);
if(input.attr("required")) container.attr("required","");
if(input.attr("disabled")) container.attr("disabled","");
if(input.attr("readonly")) container.attr("readonly","");
} else {
container = input.data("data-component");
}
if(!options.skin){
options.skin = function(item){
var html = '';
var re = new RegExp(container.val(),"gi");
name = item.label.replace(re, function (x) {
return ''+x+'';
});
html += '
'+name+'';
html += '';
return html;
}
}
if(!options.onClick){
options.onClick = function(selected,element){
input.val(selected.id);
container.val(selected.label);
input.trigger('click').trigger('change');
}
}
if(!options.onLoad){
options.onLoad = function(component,item){
component.container.val(item.label);
}
}
//Gestion des champs déja remplis au chargement de la page
if(input.val() !='' && options.nullChars.indexOf(input.val())==-1){
var uid = input.val();
if(!window.componentQueue[slug]) window.componentQueue[slug] = {timeout : null,components : [],uids :{} };
clearTimeout(window.componentQueue[slug].timeout);
var uids = uid.split(',');
for(var k in uids)
window.componentQueue[slug].uids[uids[k]] = 1;
window.componentQueue[slug].components.push({
input : input,
container : container,
values : uids
});
container.val('Chargement...');
window.componentQueue[slug].timeout = setTimeout(function(){
$.action({
action : options.edit,
data : options.editData(slug),
items : Object.keys(window.componentQueue[slug].uids)
},function(r){
if(window.componentQueue[slug]){
for(var key in window.componentQueue[slug].components){
var component = window.componentQueue[slug].components[key];
input = window.componentQueue[slug].components[key].input;
for(var i in component.values){
var value = component.values[i];
if(!r.items[value]) continue;
options.onLoad(component,r.items[value]);
//component.container.val(r.items[value].label);
}
}
delete window.componentQueue[slug];
}
});
},50);
}
container.keyup(function(e){
if (e.ctrlKey ||
e.key == "Control" ||
e.key == "ArrowUp" ||
e.key == "ArrowDown" ||
e.key == "ArrowLeft" ||
e.key == "ArrowRight" ||
e.key == "Shift" ||
e.key == "CapsLock" ||
e.key == "Tab" ||
e.key == "Alt" ||
e.key == "Home" ||
e.key == "End")
return;
input.val('');
});
//autocompletion
container.autocomplete({
action : options.autocomplete,
suggest : function(){ return !input.is('[readonly]') && !input.is('[disabled]')},
dynamicData : options.data,
skin : options.skin,
highlight : function(item){
return item;
},
onClick : function(selected,element){
container.val(selected.label);
options.onClick(selected,element);
},
onBlur : function(selected){
if((input.attr('data-force')!='false' || options.force) && input.val() == ''){
container.val('');
input.trigger('click').trigger('change');
}
input.trigger('blur');
}
});
});
},
//Chargement des images en dynamique au scroll
//Par défaut check sur scroll de window sinon sur celui du parent indiqué
lazyLoad : function(parent, callback) {
var obj = this;
var parent = parent!=null ? $(parent) : $(window);
this.lazyload = function(elem, parent, callback){
var viewportHeight = parent.height();
if(!elem.filter(':not([data-lazy=""])').length) return;
elem.filter(':not([data-lazy=""])').each(function() {
var element = $(this);
var elemOffsetTop = element.offset().top;
//Si parent est $(window) on récupère la valeur du scrollTop, sinon on prend la valeur du offsetTop du parent
var viewportOffset = viewportHeight + ((parent.get(0)===parent.get(0).window) ? parent.scrollTop() : parent.offset().top);
//Check si l'image se situe (en px) à 1/3 de sa taille ou moins du bas du viewport du parent pour le requêter
if(elemOffsetTop - element.height()/3 < viewportOffset && element.attr('data-lazy')){
var srcImg = element.attr('data-lazy');
element.removeAttr('data-lazy');
//Check pour ajouter attribut src (tag IMG) ou mettre en background-image (tag autre)
element.is('img') ? element.attr({src: srcImg}) : element.css({"background-image": 'url('+srcImg+')'});
if(callback!=null) {
elementEvent = !element.is('img') ? $('').attr('src', srcImg) : element;
elementEvent.one("load", function() {
if(!element.is('img')) $(this).remove();
callback(element);
}).each(function() {
if(this.complete) $(this).trigger('load');
});
}
}
});
}
//Initialisation
this.lazyload(obj,parent,callback);
//Appel qd parent scroll
parent.off('scroll').on('scroll', function(){
if(window.scrollTimer) clearTimeout(window.scrollTimer);
//Ajout timeout pour éviter de trigger à
//chaque scroll, on attend que le user stabilise
window.scrollTimer = setTimeout(function(){
obj.lazyload(obj,parent,callback);
}, 25);
});
//Appel sur resize
$(window).resize(function(){
if(window.scrollTimer) clearTimeout(window.scrollTimer);
window.scrollTimer = setTimeout(function(){
obj.lazyload(obj,parent,callback);
}, 25);
});
}
});