// ====================================
// Tools
// ====================================
var leTools = {
init: function(){
// initiate prototype settings
leTools.prototype();
// -- AUTOS --
// initate what is suppose to run after loading tools
// the function is called after
var component = $('#site_token').data('component');
if(!!component){
component = component.capitalizeFirstLetter();
// dynamically execute the component function
leTools.dynamicScript(component);
}
leTools.getToday();
setInterval(leTools.getToday,1000);
leTools.underspace();
leTools.datedify();
leTools.timefromnow();
leTools.numberWithCommas();
leTools.ordinal_suffix_of();
leTools.scrollFind();
leTools.autoSelect();
leTools.autoEditableSelect();
leTools.autoTooltip();
leTools.autoRadio();
leTools.autoInputComma();
leTools.autoCheckboxContainer();
},
// all prototype function libraries
// - capitalize first letter
// - hash code
prototype: function(){
// capitalize first word
String.prototype.capitalizeFirstLetter = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
String.prototype.hashCode = function() {
var hash = 0, i, chr, len;
if (this.length == 0) return hash;
for (i = 0, len = this.length; i < len; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
},
// ===== AUTOS =====
// only runs a component with the function "after". This is loaded once the leTools is initiated
// Example: Example.after();
// reason is that leTools is loaded using ajax. and component might be initated first before leTools
// therefore all the functions in leTools used in component script might be undefined
// this fixes the problem
dynamicScript: function(component){
var codeToExecute = component+".after()";
try {
var tmpFunc = new Function(codeToExecute);
tmpFunc();
}
catch(err) {
// console.log('No such object function: '+ err.message);
}
},
// start bootstrap tooltip automatically
autoTooltip: function(){
if($('[data-toggle="tooltip"]').length){
$('[data-toggle="tooltip"]').tooltip();
}
},
// auto select all selectable that has the attribute data-select
autoSelect: function(container){
if(!container) container = "";
$(container+' select[data-select]').each(function(){
var selectedVal = $(this).data('select');
//$(this).find('option[value="'+selectedVal+'"]').attr('selected',true);
$(this).val(selectedVal);
leAdvanceSelect.init(this);
});
},
// auto select all multiple selectable that has the attribute data-select and multiple
autoSelectMultiple: function(container){
if(!container) container = "";
$(container+' select[data-select][multiple]').each(function(){
if($(this).data('select').toString().trim() != ''){
var selectedVal = $(this).data('select').toString().split(',');
$(this).find('option').each(function(i,el){
if($.inArray($(el).attr('value'),selectedVal) != -1){
$(el).attr('selected','selected');
}
});
}
var select = $(this), values = {};
$('option',select).each(function(i, option){
$(option).css({
'padding-top': '5px',
'padding-bottom': '5px'
});
values[option.value] = option.selected;
}).click(function(event){
values[this.value] = !values[this.value];
$('option',select).each(function(i, option){
option.selected = values[option.value];
});
});
});
},
// use this if the option value is exactly the same as the option text
autoEditableSelect: function(container){
if(!container) container = "";
$(container+' select.editableSelect').each(function(){
var selectedVal = $(this).data('select');
if(!!selectedVal && selectedVal != ""){
$(this).find('option[value='+selectedVal+']').attr('selected','selected');
}
$(this).editableSelect();
});
},
// it will find all div with a class radio with a value of data-radio and go through all inputs in that div and check the value.
autoRadio: function(container){
if(!container) container = "";
$(container+ ' div.radio').each(function(){
var selectedVal = $(this).data('radio');
$(this).find('input[value="'+selectedVal+'"]').prop('checked',true);
});
},
// it will find all div with a class autoComma and create comma for numbers automatically
autoInputComma: function(container){
if(!container) container = "";
$(container+ ' input.autoComma').each(function(){
var $input = $(this);
$input.val(leTools.numberComa($input.val()))
$input.on('blur',function(){$input.val(leTools.numberComa($input.val()))});
$input.on('focus',function(){$input.val(leTools.numberNoComa($input.val()))});
});
},
autoSummernote: function(container){
// fix the modal locking problem
$(container+' .summernote').each(function(){
var content = $(this).attr('data-content');
$(this).summernote({
dialogsInBody: true
});
if(content != ""){
$(this).summernote('code',content);
}
});
},
// replace _ with empty string
underspace: function(){
$('.underspace').each(function(){
$(this).text($(this).text().replace(/_/g,' '));
})
},
// this is used for the clock in sidebar
getToday: function(){
$('.getToday').each(function(){
// check first if it has already processed
if($(this).hasClass('getToday_complete')) return;
// make it like a clock
if($(this).hasClass('withTime'))
time = true;
else
time = false;
if($(this).is('input')){
if(time)
$(this).attr('value',moment().format("YYYY/MM/DD, hh:mm:ss"));
else
$(this).attr('value',moment().format("YYYY/MM/DD"));
}
else{
if(time)
$(this).text(moment().format("MMM Do YYYY, h:mm:ss a"));
else
$(this).text(moment().format("MMM Do YYYY"));
}
$(this).addClass('getToday_complete');
});
},
// add the suffix to bare date, 21st, 22nd, 23rd
ordinal_suffix_of: function(){
function fix_it(i) {
var j = i % 10,
k = i % 100;
if (j == 1 && k != 11) {
return i + "st";
}
if (j == 2 && k != 12) {
return i + "nd";
}
if (j == 3 && k != 13) {
return i + "rd";
}
return i + "th";
}
var val;
$('.ordinal_suffix_of').each(function(){
val = $(this).text();
$(this).text(fix_it(val));
});
},
// trigger event as your scroll by adding class name
scrollFind: function(){
// dont do his if mobile
if(leTools.isMobile()){
return;
}
// find the element and put it in array
var findMe = $('[data-letrigger]');
var item, le_window;
$(window).scroll(function() {
le_window = this;
findMe.each(function(){
item = $(this).offset().top;
itemH = $(this).outerHeight();
wH = $(window).height();
wS = $(le_window).scrollTop();
if (wS > (item+itemH-wH)){
$(this).addClass($(this).data('letrigger'));
}
});
});
},
datedify: function(){
var format = false;
$('.datedify').each(function(){
// check first if it is already processed
if($(this).hasClass('datedify_complete')) return;
if(!!$(this).data('format')) format = $(this).data('format');
if(!format) format = "ddd, hA, MMM Do YYYY";
if($(this).is('input')){
$(this).val(moment($(this).val(),'YYYY-MM-DD HH:mm:ss').format(format));
}
else{
$(this).text(moment($(this).text()).format(format));
}
$(this).addClass('datedify_complete');
});
},
timefromnow: function(){
$('.timefromnow').each(function(){
$(this).text(moment($(this).text()).fromNow());
});
},
numberWithCommas: function(){
$('.numberWithCommas').each(function(){
if($(this).is("input")){
$(this).val($(this).val().toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
}else{
$(this).text($(this).text().toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
}
});
},
// Creates a container of multiple checkbox with a search input at the top
autoCheckboxContainer: function(){
var checkboxContainers = $('.checkbox-container-limit');
if(checkboxContainers.length > 0){
checkboxContainers.each(function(i, el){
var theInputSearch = $('');
$(el).prepend(theInputSearch);
theInputSearch.on('keyup',function(){
// hide the checkbox
$(el).find('label').each(function(ii,ell){
if($(ell).text().trim().toLowerCase().search(theInputSearch.val().trim().toLowerCase()) < 0){
if(!$(ell).find('input').is(':checked')){
$(ell).addClass('imGone');
}
}else{
$(ell).removeClass('imGone');
}
});
});
});
}
},
// ===== FUNCTION =====
setCookie: function(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
},
getCookie: function(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i") // Make in memory copy of image to avoid css issues
.attr("src", $(img).attr("src"))
.load(function() {
pic_real_width = this.width; // Note: $(this).width() will not
pic_real_height = this.height; // work for in memory images.
var obj = {
height: pic_real_height,
width: pic_real_width
};
if(callback)
callback(obj);
});
},
isMobile: function(){
var isMobile = {
Android: function() {
return navigator.userAgent.match(/Android/i);
},
BlackBerry: function() {
return navigator.userAgent.match(/BlackBerry/i);
},
iOS: function() {
return navigator.userAgent.match(/iPhone|iPad|iPod/i);
},
Opera: function() {
return navigator.userAgent.match(/Opera Mini/i);
},
Windows: function() {
return navigator.userAgent.match(/IEMobile/i) || navigator.userAgent.match(/WPDesktop/i);
},
any: function() {
return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
}
};
if( isMobile.any() ){
return true;
};
return false;
},
// ===== NUMBERS =====
// create the animation of counting number from 0 to the original number
countUpNumber: function(alltarget,duration){
$(alltarget).each(function(i,el){
var target = el;
var maxNumber = parseInt($(target).text());
var timer = 0;
if(!duration) duration = 30;
$(target).text(timer);
var intervalTimer = setInterval(function(){
if(timer >= maxNumber){
clearInterval(intervalTimer);
return false;
}
timer = timer + 1;
$(target).text(timer);
},duration);
});
},
numberComa: function(x){
var toConvert = x.toString().split('.');
toConvert[0] = toConvert[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return toConvert.join('.');
},
numberNoComa: function(x){
return x.toString().split(',').join('');
},
// ===== HTML =====
// the col height distribution in bootstrap is shit. this is to make all of the target to have the same height as it's siblings.
syncSiblingHeight: function(targetGroup){
var heighestHeight = 0;
var curHeight = 0;
var containers = $(targetGroup);
containers.height('');
containers.each(function(){
curHeight = $(this).height();
if(curHeight > heighestHeight)
heighestHeight = curHeight;
})
containers.height(heighestHeight);
return heighestHeight;
},
modalObject: false,
// this is just the event for window resize for modal
modalInitiateMaxResize: function(){
$(window).resize(function(){
if(leTools.modalObject){
if($(window).width() > 750){
leTools.modalObject.find('.modal-dialog').css('width','99%');
}else{
leTools.modalObject.find('.modal-dialog').css('width','initial');
}
}
});
},
// name the success button class as "modalProceedTrigger" and it will duplicate it and put in the modal footer
// force large: leTools.modalObject.find('.modal-dialog').css('width','90%');
modal: function(title,body,callback,hide,state,size,max){
if(!state) state = "default";
if(!size) size = "";
else if(size.toLowerCase() == "s" || size.toLowerCase() == "small")
size = "modal-sm";
else if(size.toLowerCase() == "m" || size.toLowerCase() == "medium")
size = "modal-md";
else if(size.toLowerCase() == "l" || size.toLowerCase() == "large")
size = "modal-lg";
var labelColor = 'default';
if(title.toLowerCase().trim() == 'error'){
labelColor = 'danger';
}
var count = $('div.modal').length;
var html_modal = '
'+title+'
'+body+'
';
var html_fake_buton = '';
$('body').append(html_modal);
$('body').append(html_fake_buton);
$('#modalFakeButton'+count).click();
$('.modal-backdrop').last().attr('data-dismiss',"modal").css('z-index',1050+count);
if(callback){
$('#okModalButton'+count).click(function(){
callback();
$('#cancelModalButton'+count).click();
});
}else{
$('#okModalButton'+count).click(function(){
$('#cancelModalButton'+count).click();
});
}
if(hide){
$('#'+hide+'ModalButton'+count).css('display','none');
}
// remove modal if dismiss
$(document).on('hide.bs.modal','#leCMSModal'+count, function () {
// if success and has callback
if(state == 'success' && !!callback){
callback();
}
setTimeout(function(){
$('#leCMSModal'+count).remove();
$('#modalFakeButton'+count).remove();
},500);
});
leTools.modalObject = $('#leCMSModal'+count);
// maximum width
if(max){
if($(window).width() > 750){
if(leTools.modalObject){
leTools.modalObject.find('.modal-dialog').css('width','99%');
leTools.modalInitiateMaxResize();
}
}
}
// create a duplicate button at the modal footer, class name = "modalProceedTrigger"
var modalProceedTriggerButton = leTools.modalObject.find('.modalProceedTrigger');
if(modalProceedTriggerButton.length > 0){
modalProceedTriggerButton.each(function(i){
var triggerText = $(this).text();
if($(this).is('input')) triggerText = $(this).val();
var triggerClass = "primary";
if($(this).attr('class').indexOf('btn-danger') !== -1){
triggerClass = "danger";
}
else if($(this).attr('class').indexOf('btn-warning') !== -1){
triggerClass = "warning";
}
else if($(this).attr('class').indexOf('btn-success') !== -1){
triggerClass = "success";
}
var leButton = $(this);
var leButtonID = i+'MTB';
leButton.attr('data-mtb',leButtonID);
leButton.attr('data-modalid','leCMSModal'+count);
var duplicateButton = $('')
.click(function(){
if(leButton.hasClass('areYouSure')){
var modalCallback = function(){
leButton.click();
};
leTools.modal('Confirmation',"Are you sure?",modalCallback,null,'warning');
}else{
leButton.click();
}
})
.appendTo(leTools.modalObject.find('.modal-footer'));
$(this).addClass('imGone');
});
}
// remove attachment individually
var fileDocuments = leTools.modalObject.find('#fileDocuments');
if(leTools.modalObject.find('.linkerContainer').length > 0){
fileDocuments = leTools.modalObject.find('.linkerContainer');
}
if(fileDocuments.length > 0 ){
fileDocuments.each(function(i,el){
leTools.fileDocumentAttachmentEventRemove(el);
});
}
return 'leCMSModal'+count;
},
// attach event to file documents attachment remove
// internal function usage, used by add attachments and modal above
fileDocumentAttachmentEventRemove: function(container){
container = $(container);
var attachments = container.find('a');
if(attachments.length > 0){
attachments.css('position','relative');
// add the remove button if not exists
if(!container.prev().hasClass('removeAttachmentButton')){
container.before('');
}
attachments.off('mouseenter').on('mouseenter',function(){
if($(this).hasClass('toRemove')){
var cancelButton = $('').css({
"top": 0,
"left": 0,
"z-index": "99999",
"position": "absolute"
}).on('click', function(){
// change parent opacity
$(this).parent().removeClass('toRemove');
$(this).parent().children().eq(0).css('opacity','1');
// add class to the input
var link = $(this).parent().attr('href');
container.find('input').each(function(){
if($(this).val() == link){
$(this).removeClass('removeMe');
}
});
$(this).trigger('mouseout');
});
$(this).append(cancelButton);
}else{
var removeButton = $('').css({
"top": 0,
"left": 0,
"z-index": "99999",
"position": "absolute"
}).on('click', function(){
// change parent opacity
$(this).parent().addClass('toRemove');
$(this).parent().children().eq(0).css('opacity','0.3');
// add class to the input
var link = $(this).parent().attr('href');
container.find('input').each(function(){
if($(this).val() == link){
$(this).addClass('removeMe');
}
});
$(this).trigger('mouseout');
});
$(this).append(removeButton);
}
});
attachments.off('mouseleave').on('mouseleave',function(){
$(this).children('button').remove();
});
}
},
/*
OR
*/
add_attachments: function(media_data){
if(media_data == undefined) return;
// decide what is the identifier (must support backward compatibility)
var linkerContainer = $('#fileDocuments');
var nameAttribute = 'image_link[]';
if(!!leTools.oFilesLastLinker){
if($(leTools.oFilesLastLinker).parent().find('.linkerContainer').length > 0){
linkerContainer = $(leTools.oFilesLastLinker).parent().find('.linkerContainer');
nameAttribute = linkerContainer.attr('data-nameAttr');
}
}
// append hidden input to form
linkerContainer.append('');
// add the image to linkerContainer
var img = ' ';
linkerContainer.append(img);
leTools.fileDocumentAttachmentEventRemove(linkerContainer);
// add the remove attachments button if not exist
if(!linkerContainer.prev().hasClass('removeAttachmentButton')){
linkerContainer.before('');
}
},
remove_attachments: function(button){
var linkerContainer = $('#fileDocuments');
var nameAttribute = 'image_link';
if($(button).parent().find('.linkerContainer').length > 0){
linkerContainer = $(button).parent().find('.linkerContainer');
nameAttribute = linkerContainer.attr('data-nameAttr').replace('[]','');
}
// get the links
var sources = [];
linkerContainer.find('input[name^='+nameAttribute+']').each(function(){
if(!$(this).hasClass('removeMe')) return true;
sources.push($(this).val());
});
if(sources.length == 0){
leTools.modal("Error","Please select attachent to remove first.",null,'cancel','danger');
return false;
}
var settings = {
data: {
ajax: true,
token: leAjax.getToken(),
image_sources: sources,
component: 'main',
task: 'remove_attachments'
},
url: leAjax.getUrl(),
callback: function(results){
leAjax.buttonLoad(button);
if(results.success == true){
var title = "Completed";
var message = results.message;
var modalCallback = function(){
// location.reload();
};
leTools.modal(title,message,modalCallback,'cancel','success');
}
else{
leTools.modal("Error",results.message,null,'cancel','danger');
}
linkerContainer.find('input.removeMe, a.toRemove').remove();
if(linkerContainer.children().length == 0){
linkerContainer.prev('.removeAttachmentButton').remove();
}
}
}
var modalCallback = function(){
leAjax.buttonLoad(button);
leAjax.push(settings);
};
leTools.modal('Confirmation',"Are you sure? File[s] will be deleted and cannot be recovered.",modalCallback,null,'warning');
},
// THIS ONLY OPEN ANOTHER WINDOW TO UPLOAD A FILE, IT WILL SUPPLY A CALLBACK TO THAT NEW WINDOW (IF ONLY container IS NOT SUPPLIED - refer to le_cms_main.js under openMailer function)
// UPLOAD FILES AND RETURN THE URL LINKS TO THOSE FILES
// leTools.oFiles(this,'User.changeProfilePic');
// the return will be the media result
// only one file per upload
// EXAMPLE:
// Click here to upload your receipt
oFilesModalID: false,
oFilesLastLinker: false,
oFiles: function(linker,file_callback,category,container){
leTools.oFilesLastLinker = linker;
// get the data first
var token = leAjax.getToken();
var data = {
callback: file_callback,
component: 'main',
task: 'getMediaTemplate',
token: token,
category: category
};
// remove linker target class id where ever exists -- reset
$('.oFilesTarget').removeClass('oFilesTarget');
var settings = {
data: data,
url: $('#site_token').attr('data-url') + $(linker).data('path') + "/master.proc.php",
callback: function(results){
$(linker).addClass('oFilesTarget');
if(results.success == true){
var title = results.rdata;
var html = results.message;
if(!container){
var modalID = leTools.modal(title,html,null,'cancel','success','s');
leTools.oFilesModalID = modalID;
}
else{
$('#'+container).html(html);
}
}
else{
leTools.modal("Error",results.message,null,'cancel','danger');
}
}
}
leAjax.push(settings);
return;
},
openGallery: function(category, uploadOnly){
if(!category) category = "";
var mediaType = 'gallery';
var options = '';
if(uploadOnly){
mediaType = 'upload';
options = ',width=400,height=200';
}
window.open($('#site_token').attr('data-url')+'media/'+mediaType+'?toolmode=true&category='+category,'Media','location=no,menubar=no,titlebar=no,toolbar=no,scrollbars=yes,resizable=yes'+options);
},
nl2br: function(str, is_xhtml){
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? ' ' : ' ';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
},
// add text at cursor
insertAtCursor: function(myField, myValue) {
//IE support
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
}
//MOZILLA and others
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos)
+ myValue
+ myField.value.substring(endPos, myField.value.length);
myField.selectionStart = startPos + myValue.length;
myField.selectionEnd = startPos + myValue.length;
} else {
myField.value += myValue;
}
},
// find all the group input of the calendar with class .date and display it when clicked
// container is a id string eg: #the_form
/*
*/
// Reverse .val() to MySQL format:
// .split("/").reverse().join("-");
// Set new date:
// .data("DateTimePicker").date(new Date(woDate));
handleDatepickerAndTimepicker: function(container){
if(!container)
container = "";
setTimeout(function(){
// handle datepicker first
var objects = $(container+' .date input');
var date = moment(); // default today
var minDate;
var maxDate;
var oriVal;
objects.each(function(i,el){
minDate = false;
maxDate = false;
oriVal = $(this).val();
if($(this).val() != ""){
date = moment($(this).val(),'YYYY-MM-DD');
$(this).val(date.format('DD/MM/YYYY').toString());
}
if($(this).attr('data-min') !== undefined){
if($(this).attr('data-min') != 'false'){
minDate = moment($(this).attr('data-min'),'YYYY-MM-DD');
}
}
if($(this).attr('data-max') !== undefined){
if($(this).attr('data-max') != 'false'){
maxDate = moment($(this).attr('data-max'),'YYYY-MM-DD');
}
}
if($(this).attr('data-monthyearonly') !== undefined){
$(this).parent('.date').datetimepicker({
format: "MM/YYYY",
defaultDate: date,
minDate: minDate,
maxDate: maxDate,
viewMode: 'months'
});
}else{
$(this).parent('.date').datetimepicker({
format: "DD/MM/YYYY",
defaultDate: date,
minDate: minDate,
maxDate: maxDate
});
}
// if disabled, clear the input
if($(this).is('[disabled]') && oriVal.trim() == ""){
$(this).val("");
}
});
// handle timepicker
var objects = $(container+' .bootstrap-timepicker input');
var time = "10:00 AM";
objects.each(function(){
if($(this).val() != ""){
var timeString = $(this).val();
var H = +timeString.substr(0, 2);
var h = H % 12 || 12;
var ampm = (H < 12 || H === 24) ? "AM" : "PM";
timeString = h + timeString.substr(2, 3) +' '+ ampm;
time = timeString;
}
$(this).timepicker('setTime',time);
});
},300);
},
// display glyphicon if it's not a file
isItFile: function(img){
var src = $(img).attr('src');
var parent = $(img).parent();
parent.prepend('');
$(img).remove();
},
// copyToClipboard: function(text) {
// window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
// },
copyToClipboard: function(obj,text){
if(navigator.mimeTypes ["application/x-shockwave-flash"] == undefined){
var body = '
You do not have flash installed to use this function.
';
leTools.modal('Ooops..',body,false,'cancel','danger');
}
var client = new ZeroClipboard( obj );
client.on( "ready", function( readyEvent ) {
// alert( "ZeroClipboard SWF is ready!" );
client.on( 'copy', function(event) {
event.clipboardData.setData('text/plain', text);
} );
client.on( "aftercopy", function( event ) {
var target = $(event.target);
var text = target.text();
target.text('Copied!!');
if(target.hasClass('btn')){
target.removeClass('btn-success').addClass('btn-info');
}
setTimeout(function(){
if(target.hasClass('btn')){
target.removeClass('btn-info').addClass('btn-success');
}
target.text(text);
},500);
// alert("Copied text to clipboard: " + event.data['text/plain'] );
} );
} );
$(obj).click(function(e){
e.preventDefault();
});
},
// scroll to the id under what container
scrollTo: function(id,container){
var isWebkit = 'WebkitAppearance' in document.documentElement.style;
var padder = 120;
if(!container) container = 'html, body';
if(id && $("#"+id).length){
if(isWebkit){
$(container).animate({
scrollTop: $("#"+id).offset().top - padder
}, 800);
return true;
}else{
$(container).animate({
scrollTop: $("#"+id).offset().top + $('body').scrollTop() -padder
}, 800);
return true;
}
}else{ // id is class
if(isWebkit){
$(container).animate({
scrollTop: $("."+id).offset().top - padder
}, 800);
return true;
}else{
$(container).animate({
scrollTop: $("."+id).offset().top + $('body').scrollTop() -padder
}, 800);
return true;
}
}
return false;
},
// open all glypicon in a modal, then return the value picked with the one chosen to the point element
// TO USE:
/*
* leTools.callbackGlyphicon = function(picked){
* some routine to handle the icon on component based scope
* };
* leTools.openGlyphicon();
*/
callbackGlyphicon: false,
openGlyphicon: function(){
// get all the list
var url = $('#site_token').data('url');
var picked = null;
var data = {};
var url = url + "vendor/font-awesome/font_awesome.xml";
$.ajax({
url: url,
data: data,
dataType: "xml",
success: function(result, textStatus, jqxhr){
result = $.xml2json(result);
var json_glyphs = result.icon;
var the_count = $('.glyphicons_list').length;
body = "
";
// console.log(json_glyphs);
$(json_glyphs).each(function(i,el){
body += '
';
body += '';
body += '
';
});
body += "
";
var the_callback = function(){
if(leTools.callbackGlyphicon == false){
leTools.modal('System Error','Please set the callback after choosing an icon',false,'cancel','danger');
}
else{
picked = $('#mainGlyphList_'+the_count+' .pickMe');
picked = picked.children('i').attr('class').replace('fa ','');
leTools.callbackGlyphicon(picked);
}
}
leTools.modal('Pick an icon',body,the_callback,null,null,'l');
}
});
},
// find this in the data table searchbar if the request is asked
dataFind: function(){
var value = leTools.getParameterByName('data_find');
if(!value) return value;
var searchInput = $('.dataTables_wrapper input[type=search]').val(value);
leTools.trigger(searchInput);
},
// create a nest listed from a json string
// container is the #id
// data-json must consist
// 1. either "on-click" or "link" keys
// 2. content
// 3. object that consists 1,2 or/and 3
// $data_array = array(
// title => 'Item 1',
// button_click => array(
// 'title' => 'a title',
// 'component' => 'some_component',
// 'task' => 'some_task',
// 'callback' => 'function(){};',
// 'id' => 'some_id',
// 'href=' => 'http://wwww.somewhere.com'
// ),
// content => repeat_of_$data_array() OR anything
// );
// https://stackoverflow.com/questions/29063244/consistent-styling-for-nested-lists-with-bootstrap
transformToNestedList: function(container){
var container = $(container);
var jsonData = $.parseJSON(container.attr('data-json'));
var takenNames = [];
// function to create list
function createList(i, obj, tier){
var idName = tier + i;
var marginCount = idName.split("-").length - 1;
marginCount = marginCount * 30;
// console.log(idName, obj);
var html = '';
if($.isArray(obj.content)){
html += ' ';
}
html += obj.title;
if("button_click" in obj){
html += ' ';
}
html += ' ';
if($.isArray(obj.content)){
html += '
';
$.each(obj.content, function(i, el){
html += createList(i, el, idName+'-');
});
html += '
';
}
return html;
}
// end function to create list
var html = '
';
$.each(jsonData, function(i,el){
html += createList(i,el,'');
});
html += '
';
$(container).append(html);
$('.list-group-item').on('click', function() {
$('.glyphicon', this).toggleClass('glyphicon-chevron-right').toggleClass('glyphicon-chevron-down');
});
},
// make sure the container position is relative;
addLoader: function(container,size,zIndex){
// if there is already a loader, don't do anything
if($(container).find('.le_loader_container').length > 0){
return false;
}
if(!size){
size = 100;
}
var loader = $('');
loader.css({
width: size+'px',
height: size+'px',
margin: '-'+(size/2)+'px 0 0 -'+(size/2)+'px'
});
// loader css are in main_global.css
var loaderContainer = $('');
if(zIndex){
loaderContainer.css('z-index',zIndex);
}
if(container == 'body'){
loaderContainer.css('position','fixed');
}
loaderContainer.append(loader);
$(container).append(loaderContainer);
},
// if no container provided, it will remove all loader
removeLoader: function(container){
if(container){
$(container).find('.le_loader_container').remove();
}else{
$('.le_loader_container').remove();
}
},
prettyJsonString: function(stringContainer){
var string = $(stringContainer).text().trim();
if(string == ""){
return;
}
string = JSON.parse(string);
string = JSON.stringify(string, undefined, 2);
$(stringContainer).html(string);
}
}
$(document).ready(function(){
leTools.init();
});
// ===== BELOW ARE ALL EXTEND JQUERY =====
// Wait till exists
;(function ($, window) {
var intervals = {};
var removeListener = function(selector) {
if (intervals[selector]) {
window.clearInterval(intervals[selector]);
intervals[selector] = null;
}
};
var found = 'waitUntilExists.found';
$.fn.waitUntilExists = function(handler, shouldRunHandlerOnce, isChild) {
var selector = this.selector;
var $this = $(selector);
var $elements = $this.not(function() { return $(this).data(found); });
if (handler === 'remove') {
// Hijack and remove interval immediately if the code requests
removeListener(selector);
}
else {
// Run the handler on all found elements and mark as found
$elements.each(handler).data(found, true);
if (shouldRunHandlerOnce && $this.length) {
// Element was found, implying the handler already ran for all
// matched elements
removeListener(selector);
}
else if (!isChild) {
// If this is a recurring search or if the target has not yet been
// found, create an interval to continue searching for the target
intervals[selector] = window.setInterval(function () {
$this.waitUntilExists(handler, shouldRunHandlerOnce, true);
}, 500);
}
}
return $this;
};
}(jQuery, window));
// XML TO JSON
if(window.jQuery) (function($){
// Add function to jQuery namespace
$.extend({
// converts xml documents and xml text to json object
xml2json: function(xml, extended) {
if(!xml) return {}; // quick fail
//### PARSER LIBRARY
// Core function
function parseXML(node, simple){
if(!node) return null;
var txt = '', obj = null, att = null;
var nt = node.nodeType, nn = jsVar(node.localName || node.nodeName);
var nv = node.text || node.nodeValue || '';
/*DBG*/ //if(window.console) console.log(['x2j',nn,nt,nv.length+' bytes']);
if(node.childNodes){
if(node.childNodes.length>0){
/*DBG*/ //if(window.console) console.log(['x2j',nn,'CHILDREN',node.childNodes]);
$.each(node.childNodes, function(n,cn){
var cnt = cn.nodeType, cnn = jsVar(cn.localName || cn.nodeName);
var cnv = cn.text || cn.nodeValue || '';
/*DBG*/ //if(window.console) console.log(['x2j',nn,'node>a',cnn,cnt,cnv]);
if(cnt == 8){
/*DBG*/ //if(window.console) console.log(['x2j',nn,'node>b',cnn,'COMMENT (ignore)']);
return; // ignore comment node
}
else if(cnt == 3 || cnt == 4 || !cnn){
// ignore white-space in between tags
if(cnv.match(/^\s+$/)){
/*DBG*/ //if(window.console) console.log(['x2j',nn,'node>c',cnn,'WHITE-SPACE (ignore)']);
return;
};
/*DBG*/ //if(window.console) console.log(['x2j',nn,'node>d',cnn,'TEXT']);
txt += cnv.replace(/^\s+/,'').replace(/\s+$/,'');
// make sure we ditch trailing spaces from markup
}
else{
/*DBG*/ //if(window.console) console.log(['x2j',nn,'node>e',cnn,'OBJECT']);
obj = obj || {};
if(obj[cnn]){
/*DBG*/ //if(window.console) console.log(['x2j',nn,'node>f',cnn,'ARRAY']);
// http://forum.jquery.com/topic/jquery-jquery-xml2json-problems-when-siblings-of-the-same-tagname-only-have-a-textnode-as-a-child
if(!obj[cnn].length) obj[cnn] = myArr(obj[cnn]);
obj[cnn] = myArr(obj[cnn]);
obj[cnn][ obj[cnn].length ] = parseXML(cn, true/* simple */);
obj[cnn].length = obj[cnn].length;
}
else{
/*DBG*/ //if(window.console) console.log(['x2j',nn,'node>g',cnn,'dig deeper...']);
obj[cnn] = parseXML(cn);
};
};
});
};//node.childNodes.length>0
};//node.childNodes
if(node.attributes){
if(node.attributes.length>0){
/*DBG*/ //if(window.console) console.log(['x2j',nn,'ATTRIBUTES',node.attributes])
att = {}; obj = obj || {};
$.each(node.attributes, function(a,at){
var atn = jsVar(at.name), atv = at.value;
att[atn] = atv;
if(obj[atn]){
/*DBG*/ //if(window.console) console.log(['x2j',nn,'attr>',atn,'ARRAY']);
// http://forum.jquery.com/topic/jquery-jquery-xml2json-problems-when-siblings-of-the-same-tagname-only-have-a-textnode-as-a-child
//if(!obj[atn].length) obj[atn] = myArr(obj[atn]);//[ obj[ atn ] ];
obj[cnn] = myArr(obj[cnn]);
obj[atn][ obj[atn].length ] = atv;
obj[atn].length = obj[atn].length;
}
else{
/*DBG*/ //if(window.console) console.log(['x2j',nn,'attr>',atn,'TEXT']);
obj[atn] = atv;
};
});
//obj['attributes'] = att;
};//node.attributes.length>0
};//node.attributes
if(obj){
obj = $.extend( (txt!='' ? new String(txt) : {}),/* {text:txt},*/ obj || {}/*, att || {}*/);
//txt = (obj.text) ? (typeof(obj.text)=='object' ? obj.text : [obj.text || '']).concat([txt]) : txt;
txt = (obj.text) ? ([obj.text || '']).concat([txt]) : txt;
if(txt) obj.text = txt;
txt = '';
};
var out = obj || txt;
//console.log([extended, simple, out]);
if(extended){
if(txt) out = {};//new String(out);
txt = out.text || txt || '';
if(txt) out.text = txt;
if(!simple) out = myArr(out);
};
return out;
};// parseXML
// Core Function End
// Utility functions
var jsVar = function(s){ return String(s || '').replace(/-/g,"_"); };
// NEW isNum function: 01/09/2010
// Thanks to Emile Grau, GigaTecnologies S.L., www.gigatransfer.com, www.mygigamail.com
function isNum(s){
// based on utility function isNum from xml2json plugin (http://www.fyneworks.com/ - diego@fyneworks.com)
// few bugs corrected from original function :
// - syntax error : regexp.test(string) instead of string.test(reg)
// - regexp modified to accept comma as decimal mark (latin syntax : 25,24 )
// - regexp modified to reject if no number before decimal mark : ".7" is not accepted
// - string is "trimmed", allowing to accept space at the beginning and end of string
var regexp=/^((-)?([0-9]+)(([\.\,]{0,1})([0-9]+))?$)/
return (typeof s == "number") || regexp.test(String((s && typeof s == "string") ? jQuery.trim(s) : ''));
};
// OLD isNum function: (for reference only)
//var isNum = function(s){ return (typeof s == "number") || String((s && typeof s == "string") ? s : '').test(/^((-)?([0-9]*)((\.{0,1})([0-9]+))?$)/); };
var myArr = function(o){
// http://forum.jquery.com/topic/jquery-jquery-xml2json-problems-when-siblings-of-the-same-tagname-only-have-a-textnode-as-a-child
//if(!o.length) o = [ o ]; o.length=o.length;
if(!$.isArray(o)) o = [ o ]; o.length=o.length;
// here is where you can attach additional functionality, such as searching and sorting...
return o;
};
// Utility functions End
//### PARSER LIBRARY END
// Convert plain text to xml
if(typeof xml=='string') xml = $.text2xml(xml);
// Quick fail if not xml (or if this is a node)
if(!xml.nodeType) return;
if(xml.nodeType == 3 || xml.nodeType == 4) return xml.nodeValue;
// Find xml root node
var root = (xml.nodeType == 9) ? xml.documentElement : xml;
// Convert xml to json
var out = parseXML(root, true /* simple */);
// Clean-up memory
xml = null; root = null;
// Send output
return out;
},
// Convert text to XML DOM
text2xml: function(str) {
return $.parseXML(str);
}
}); // extend $
})(jQuery);
// Create :icontains which is a case insensitive for :contains
jQuery.expr[':'].icontains = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};