');
return this.each(function () {
//if a source is specified
if (settings.source === "") {
if (window.console) {
window.console.log("Please specify a source first - boxRefresh()");
}
return;
}
//the box
var box = $(this);
//the button
var rBtn = box.find(settings.trigger).first();
//On trigger click
rBtn.on('click', function (e) {
e.preventDefault();
//Add loading overlay
start(box);
//Perform ajax call
box.find(".box-body").load(settings.source, function () {
done(box);
});
});
});
function start(box) {
//Add overlay and loading img
box.append(overlay);
settings.onLoadStart.call(box);
}
function done(box) {
//Remove overlay and loading img
box.find(overlay).remove();
settings.onLoadDone.call(box);
}
};
})(jQuery);
/*
* EXPLICIT BOX CONTROLS
* -----------------------
* This is a custom plugin to use with the component BOX. It allows you to activate
* a box inserted in the DOM after the app.js was loaded, toggle and remove box.
*
* @type plugin
* @usage $("#box-widget").activateBox();
* @usage $("#box-widget").toggleBox();
* @usage $("#box-widget").removeBox();
*/
(function ($) {
'use strict';
$.fn.activateBox = function () {
$.AdminLTE.boxWidget.activate(this);
};
$.fn.toggleBox = function () {
var button = $($.AdminLTE.boxWidget.selectors.collapse, this);
$.AdminLTE.boxWidget.collapse(button);
};
$.fn.removeBox = function () {
var button = $($.AdminLTE.boxWidget.selectors.remove, this);
$.AdminLTE.boxWidget.remove(button);
};
})(jQuery);
/*
* TODO LIST CUSTOM PLUGIN
* -----------------------
* This plugin depends on iCheck plugin for checkbox and radio inputs
*
* @type plugin
* @usage $("#todo-widget").todolist( options );
*/
(function ($) {
'use strict';
$.fn.todolist = function (options) {
// Render options
var settings = $.extend({
//When the user checks the input
onCheck: function (ele) {
return ele;
},
//When the user unchecks the input
onUncheck: function (ele) {
return ele;
}
}, options);
return this.each(function () {
if (typeof $.fn.iCheck != 'undefined') {
$('input', this).on('ifChecked', function () {
var ele = $(this).parents("li").first();
ele.toggleClass("done");
settings.onCheck.call(ele);
});
$('input', this).on('ifUnchecked', function () {
var ele = $(this).parents("li").first();
ele.toggleClass("done");
settings.onUncheck.call(ele);
});
} else {
$('input', this).on('change', function () {
var ele = $(this).parents("li").first();
ele.toggleClass("done");
if ($('input', ele).is(":checked")) {
settings.onCheck.call(ele);
} else {
settings.onUncheck.call(ele);
}
});
}
});
};
}(jQuery));
================================================
FILE: public/adminlte/js/demo.js
================================================
/**
* AdminLTE Demo Menu
* ------------------
* You should not use this file in production.
* This file is for demo purposes only.
*/
(function ($, AdminLTE) {
"use strict";
/**
* List of all the available skins
*
* @type Array
*/
var my_skins = [
"skin-blue",
"skin-black",
"skin-red",
"skin-yellow",
"skin-purple",
"skin-green",
"skin-blue-light",
"skin-black-light",
"skin-red-light",
"skin-yellow-light",
"skin-purple-light",
"skin-green-light"
];
//Create the new tab
var tab_pane = $("", {
"id": "control-sidebar-theme-demo-options-tab",
"class": "tab-pane active"
});
//Create the tab button
var tab_button = $("", {"class": "active"})
.html(""
+ ""
+ "");
//Add the tab button to the right sidebar tabs
$("[href='#control-sidebar-home-tab']")
.parent()
.before(tab_button);
//Create the menu
var demo_settings = $("");
//Layout options
demo_settings.append(
"
"
+ "Layout Options"
+ "
"
//Fixed layout
+ "
"
+ ""
+ "
Activate the fixed layout. You can't use fixed and boxed layouts together
"
+ "
"
//Boxed layout
+ "
"
+ ""
+ "
Activate the boxed layout
"
+ "
"
//Sidebar Toggle
+ "
"
+ ""
+ "
Toggle the left sidebar's state (open or collapse)
"
+ "
"
//Sidebar mini expand on hover toggle
+ "
"
+ ""
+ "
Let the sidebar mini expand on hover
"
+ "
"
//Control Sidebar Toggle
+ "
"
+ ""
+ "
Toggle between slide over content and push content effects
"
+ "
"
//Control Sidebar Skin Toggle
+ "
"
+ ""
+ "
Toggle between dark and light skins for the right sidebar
");
demo_settings.append(skins_list);
tab_pane.append(demo_settings);
$("#control-sidebar-home-tab").after(tab_pane);
setup();
/**
* Toggles layout classes
*
* @param String cls the layout class to toggle
* @returns void
*/
function change_layout(cls) {
$("body").toggleClass(cls);
AdminLTE.layout.fixSidebar();
//Fix the problem with right sidebar and layout boxed
if (cls == "layout-boxed")
AdminLTE.controlSidebar._fix($(".control-sidebar-bg"));
if ($('body').hasClass('fixed') && cls == 'fixed') {
AdminLTE.pushMenu.expandOnHover();
AdminLTE.layout.activate();
}
AdminLTE.controlSidebar._fix($(".control-sidebar-bg"));
AdminLTE.controlSidebar._fix($(".control-sidebar"));
}
/**
* Replaces the old skin with the new skin
* @param String cls the new skin class
* @returns Boolean false to prevent link's default action
*/
function change_skin(cls) {
$.each(my_skins, function (i) {
$("body").removeClass(my_skins[i]);
});
$("body").addClass(cls);
store('skin', cls);
return false;
}
/**
* Store a new settings in the browser
*
* @param String name Name of the setting
* @param String val Value of the setting
* @returns void
*/
function store(name, val) {
if (typeof (Storage) !== "undefined") {
localStorage.setItem(name, val);
} else {
window.alert('Please use a modern browser to properly view this template!');
}
}
/**
* Get a prestored setting
*
* @param String name Name of of the setting
* @returns String The value of the setting | null
*/
function get(name) {
if (typeof (Storage) !== "undefined") {
return localStorage.getItem(name);
} else {
window.alert('Please use a modern browser to properly view this template!');
}
}
/**
* Retrieve default settings and apply them to the template
*
* @returns void
*/
function setup() {
var tmp = get('skin');
if (tmp && $.inArray(tmp, my_skins))
change_skin(tmp);
//Add the change skin listener
$("[data-skin]").on('click', function (e) {
if($(this).hasClass('knob'))
return;
e.preventDefault();
change_skin($(this).data('skin'));
});
//Add the layout manager
$("[data-layout]").on('click', function () {
change_layout($(this).data('layout'));
});
$("[data-controlsidebar]").on('click', function () {
change_layout($(this).data('controlsidebar'));
var slide = !AdminLTE.options.controlSidebarOptions.slide;
AdminLTE.options.controlSidebarOptions.slide = slide;
if (!slide)
$('.control-sidebar').removeClass('control-sidebar-open');
});
$("[data-sidebarskin='toggle']").on('click', function () {
var sidebar = $(".control-sidebar");
if (sidebar.hasClass("control-sidebar-dark")) {
sidebar.removeClass("control-sidebar-dark")
sidebar.addClass("control-sidebar-light")
} else {
sidebar.removeClass("control-sidebar-light")
sidebar.addClass("control-sidebar-dark")
}
});
$("[data-enable='expandOnHover']").on('click', function () {
$(this).attr('disabled', true);
AdminLTE.pushMenu.expandOnHover();
if (!$('body').hasClass('sidebar-collapse'))
$("[data-layout='sidebar-collapse']").click();
});
// Reset options
if ($('body').hasClass('fixed')) {
$("[data-layout='fixed']").attr('checked', 'checked');
}
if ($('body').hasClass('layout-boxed')) {
$("[data-layout='layout-boxed']").attr('checked', 'checked');
}
if ($('body').hasClass('sidebar-collapse')) {
$("[data-layout='sidebar-collapse']").attr('checked', 'checked');
}
}
})(jQuery, $.AdminLTE);
================================================
FILE: public/adminlte/js/main.js
================================================
$(document).ready(function () {
var activeSub = $(document).find('.active-sub');
if (activeSub.length > 0) {
activeSub.parent().show();
activeSub.parent().parent().find('.arrow').addClass('open');
activeSub.parent().parent().addClass('open');
}
window.dtDefaultOptions = {
retrieve: true,
dom: 'lBfrtip<"actions">',
columnDefs: [],
"iDisplayLength": 100,
"aaSorting": [],
buttons: [
{
extend: 'copy',
text: window.copyButtonTrans,
exportOptions: {
columns: ':visible'
}
},
{
extend: 'csv',
text: window.csvButtonTrans,
exportOptions: {
columns: ':visible'
}
},
{
extend: 'excel',
text: window.excelButtonTrans,
exportOptions: {
columns: ':visible'
}
},
{
extend: 'pdf',
text: window.pdfButtonTrans,
exportOptions: {
columns: ':visible'
}
},
{
extend: 'print',
text: window.printButtonTrans,
exportOptions: {
columns: ':visible'
}
},
{
extend: 'colvis',
text: window.colvisButtonTrans,
exportOptions: {
columns: ':visible'
}
},
]
};
$('.datatable').each(function () {
if ($(this).hasClass('dt-select')) {
window.dtDefaultOptions.select = {
style: 'multi',
selector: 'td:first-child'
};
window.dtDefaultOptions.columnDefs.push({
orderable: false,
className: 'select-checkbox',
targets: 0
});
}
$(this).dataTable(window.dtDefaultOptions);
});
$(document).on( 'init.dt', function ( e, settings ) {
if (typeof window.route_mass_crud_entries_destroy != 'undefined') {
$('.datatable, .ajaxTable').siblings('.actions').html(''+window.deleteButtonTrans+'');
}
});
$(document).on('click', '.js-delete-selected', function () {
if (confirm('Are you sure')) {
var ids = [];
$(this).closest('.actions').siblings('.datatable, .ajaxTable').find('tbody tr.selected').each(function () {
console.log("selected", $(this).data('entry-id'));
ids.push($(this).data('entry-id'));
});
$.ajax({
method: 'POST',
url: $(this).attr('href'),
data: {
_token: _token,
ids: ids
}
}).done(function () {
location.reload();
});
}
return false;
});
$(document).on('click', '#select-all', function () {
var selected = $(this).is(':checked');
$(this).closest('table.datatable, table.ajaxTable').find('td:first-child').each(function () {
if (selected != $(this).closest('tr').hasClass('selected')) {
$(this).click();
}
});
});
$('.mass').click(function () {
if ($(this).is(":checked")) {
$('.single').each(function () {
if ($(this).is(":checked") == false) {
$(this).click();
}
});
} else {
$('.single').each(function () {
if ($(this).is(":checked") == true) {
$(this).click();
}
});
}
});
$('.page-sidebar').on('click', 'li > a', function (e) {
if ($('body').hasClass('page-sidebar-closed') && $(this).parent('li').parent('.page-sidebar-menu').size() === 1) {
return;
}
var hasSubMenu = $(this).next().hasClass('sub-menu');
if ($(this).next().hasClass('sub-menu always-open')) {
return;
}
var parent = $(this).parent().parent();
var the = $(this);
var menu = $('.page-sidebar-menu');
var sub = $(this).next();
var autoScroll = menu.data("auto-scroll");
var slideSpeed = parseInt(menu.data("slide-speed"));
var keepExpand = menu.data("keep-expanded");
if (keepExpand !== true) {
parent.children('li.open').children('a').children('.arrow').removeClass('open');
parent.children('li.open').children('.sub-menu:not(.always-open)').slideUp(slideSpeed);
parent.children('li.open').removeClass('open');
}
var slideOffeset = -200;
if (sub.is(":visible")) {
$('.arrow', $(this)).removeClass("open");
$(this).parent().removeClass("open");
sub.slideUp(slideSpeed, function () {
if (autoScroll === true && $('body').hasClass('page-sidebar-closed') === false) {
if ($('body').hasClass('page-sidebar-fixed')) {
menu.slimScroll({
'scrollTo': (the.position()).top
});
}
}
});
} else if (hasSubMenu) {
$('.arrow', $(this)).addClass("open");
$(this).parent().addClass("open");
sub.slideDown(slideSpeed, function () {
if (autoScroll === true && $('body').hasClass('page-sidebar-closed') === false) {
if ($('body').hasClass('page-sidebar-fixed')) {
menu.slimScroll({
'scrollTo': (the.position()).top
});
}
}
});
}
if (hasSubMenu == true || $(this).attr('href') == '#') {
e.preventDefault();
}
});
$('.select2').select2();
});
function processAjaxTables() {
$('.ajaxTable').each(function () {
window.dtDefaultOptions.processing = true;
window.dtDefaultOptions.serverSide = true;
if ($(this).hasClass('dt-select')) {
window.dtDefaultOptions.select = {
style: 'multi',
selector: 'td:first-child'
};
window.dtDefaultOptions.columnDefs.push({
orderable: false,
className: 'select-checkbox',
targets: 0
});
}
$(this).DataTable(window.dtDefaultOptions);
if (typeof window.route_mass_crud_entries_destroy != 'undefined') {
$(this).siblings('.actions').html(''+window.deleteButtonTrans+'');
}
});
}
================================================
FILE: public/adminlte/js/mapInput.js
================================================
function initialize() {
$('form').on('keyup keypress', function(e) {
var keyCode = e.keyCode || e.which;
if (keyCode === 13) {
e.preventDefault();
return false;
}
});
const locationInputs = document.getElementsByClassName("map-input");
const autocompletes = [];
const geocoder = new google.maps.Geocoder;
for (let i = 0; i < locationInputs.length; i++) {
const input = locationInputs[i];
const fieldKey = input.id.replace("-input", "");
const isEdit = document.getElementById(fieldKey + "-latitude").value != '' && document.getElementById(fieldKey + "-longitude").value != '';
const latitude = parseFloat(document.getElementById(fieldKey + "-latitude").value) || -33.8688;
const longitude = parseFloat(document.getElementById(fieldKey + "-longitude").value) || 151.2195;
const map = new google.maps.Map(document.getElementById(fieldKey + '-map'), {
center: {lat: latitude, lng: longitude},
zoom: 13
});
const marker = new google.maps.Marker({
map: map,
position: {lat: latitude, lng: longitude},
});
marker.setVisible(isEdit);
const autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.key = fieldKey;
autocompletes.push({input: input, map: map, marker: marker, autocomplete: autocomplete});
}
for (let i = 0; i < autocompletes.length; i++) {
const input = autocompletes[i].input;
const autocomplete = autocompletes[i].autocomplete;
const map = autocompletes[i].map;
const marker = autocompletes[i].marker;
google.maps.event.addListener(autocomplete, 'place_changed', function () {
marker.setVisible(false);
const place = autocomplete.getPlace();
geocoder.geocode({'placeId': place.place_id}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
const lat = results[0].geometry.location.lat();
const lng = results[0].geometry.location.lng();
setLocationCoordinates(autocomplete.key, lat, lng);
}
});
if (!place.geometry) {
window.alert("No details available for input: '" + place.name + "'");
input.value = "";
return;
}
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
marker.setPosition(place.geometry.location);
marker.setVisible(true);
});
}
}
function setLocationCoordinates(key, lat, lng) {
const latitudeField = document.getElementById(key + "-" + "latitude");
const longitudeField = document.getElementById(key + "-" + "longitude");
latitudeField.value = lat;
longitudeField.value = lng;
}
================================================
FILE: public/adminlte/js/pages/dashboard.js
================================================
/*
* Author: Abdullah A Almsaeed
* Date: 4 Jan 2014
* Description:
* This is a demo file used only for the main dashboard (index.html)
**/
$(function () {
"use strict";
//Make the dashboard widgets sortable Using jquery UI
$(".connectedSortable").sortable({
placeholder: "sort-highlight",
connectWith: ".connectedSortable",
handle: ".box-header, .nav-tabs",
forcePlaceholderSize: true,
zIndex: 999999
});
$(".connectedSortable .box-header, .connectedSortable .nav-tabs-custom").css("cursor", "move");
//jQuery UI sortable for the todo list
$(".todo-list").sortable({
placeholder: "sort-highlight",
handle: ".handle",
forcePlaceholderSize: true,
zIndex: 999999
});
//bootstrap WYSIHTML5 - text editor
$(".textarea").wysihtml5();
$('.daterange').daterangepicker({
ranges: {
'Today': [moment(), moment()],
'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'Last 7 Days': [moment().subtract(6, 'days'), moment()],
'Last 30 Days': [moment().subtract(29, 'days'), moment()],
'This Month': [moment().startOf('month'), moment().endOf('month')],
'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
},
startDate: moment().subtract(29, 'days'),
endDate: moment()
}, function (start, end) {
window.alert("You chose: " + start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
});
/* jQueryKnob */
$(".knob").knob();
//jvectormap data
var visitorsData = {
"US": 398, //USA
"SA": 400, //Saudi Arabia
"CA": 1000, //Canada
"DE": 500, //Germany
"FR": 760, //France
"CN": 300, //China
"AU": 700, //Australia
"BR": 600, //Brazil
"IN": 800, //India
"GB": 320, //Great Britain
"RU": 3000 //Russia
};
//World map by jvectormap
$('#world-map').vectorMap({
map: 'world_mill_en',
backgroundColor: "transparent",
regionStyle: {
initial: {
fill: '#e4e4e4',
"fill-opacity": 1,
stroke: 'none',
"stroke-width": 0,
"stroke-opacity": 1
}
},
series: {
regions: [{
values: visitorsData,
scale: ["#92c1dc", "#ebf4f9"],
normalizeFunction: 'polynomial'
}]
},
onRegionLabelShow: function (e, el, code) {
if (typeof visitorsData[code] != "undefined")
el.html(el.html() + ': ' + visitorsData[code] + ' new visitors');
}
});
//Sparkline charts
var myvalues = [1000, 1200, 920, 927, 931, 1027, 819, 930, 1021];
$('#sparkline-1').sparkline(myvalues, {
type: 'line',
lineColor: '#92c1dc',
fillColor: "#ebf4f9",
height: '50',
width: '80'
});
myvalues = [515, 519, 520, 522, 652, 810, 370, 627, 319, 630, 921];
$('#sparkline-2').sparkline(myvalues, {
type: 'line',
lineColor: '#92c1dc',
fillColor: "#ebf4f9",
height: '50',
width: '80'
});
myvalues = [15, 19, 20, 22, 33, 27, 31, 27, 19, 30, 21];
$('#sparkline-3').sparkline(myvalues, {
type: 'line',
lineColor: '#92c1dc',
fillColor: "#ebf4f9",
height: '50',
width: '80'
});
//The Calender
$("#calendar").datepicker();
//SLIMSCROLL FOR CHAT WIDGET
$('#chat-box').slimScroll({
height: '250px'
});
/* Morris.js Charts */
// Sales chart
var area = new Morris.Area({
element: 'revenue-chart',
resize: true,
data: [
{y: '2011 Q1', item1: 2666, item2: 2666},
{y: '2011 Q2', item1: 2778, item2: 2294},
{y: '2011 Q3', item1: 4912, item2: 1969},
{y: '2011 Q4', item1: 3767, item2: 3597},
{y: '2012 Q1', item1: 6810, item2: 1914},
{y: '2012 Q2', item1: 5670, item2: 4293},
{y: '2012 Q3', item1: 4820, item2: 3795},
{y: '2012 Q4', item1: 15073, item2: 5967},
{y: '2013 Q1', item1: 10687, item2: 4460},
{y: '2013 Q2', item1: 8432, item2: 5713}
],
xkey: 'y',
ykeys: ['item1', 'item2'],
labels: ['Item 1', 'Item 2'],
lineColors: ['#a0d0e0', '#3c8dbc'],
hideHover: 'auto'
});
var line = new Morris.Line({
element: 'line-chart',
resize: true,
data: [
{y: '2011 Q1', item1: 2666},
{y: '2011 Q2', item1: 2778},
{y: '2011 Q3', item1: 4912},
{y: '2011 Q4', item1: 3767},
{y: '2012 Q1', item1: 6810},
{y: '2012 Q2', item1: 5670},
{y: '2012 Q3', item1: 4820},
{y: '2012 Q4', item1: 15073},
{y: '2013 Q1', item1: 10687},
{y: '2013 Q2', item1: 8432}
],
xkey: 'y',
ykeys: ['item1'],
labels: ['Item 1'],
lineColors: ['#efefef'],
lineWidth: 2,
hideHover: 'auto',
gridTextColor: "#fff",
gridStrokeWidth: 0.4,
pointSize: 4,
pointStrokeColors: ["#efefef"],
gridLineColor: "#efefef",
gridTextFamily: "Open Sans",
gridTextSize: 10
});
//Donut Chart
var donut = new Morris.Donut({
element: 'sales-chart',
resize: true,
colors: ["#3c8dbc", "#f56954", "#00a65a"],
data: [
{label: "Download Sales", value: 12},
{label: "In-Store Sales", value: 30},
{label: "Mail-Order Sales", value: 20}
],
hideHover: 'auto'
});
//Fix for charts under tabs
$('.box ul.nav a').on('shown.bs.tab', function () {
area.redraw();
donut.redraw();
line.redraw();
});
/* The todo list plugin */
$(".todo-list").todolist({
onCheck: function (ele) {
window.console.log("The element has been checked");
return ele;
},
onUncheck: function (ele) {
window.console.log("The element has been unchecked");
return ele;
}
});
});
================================================
FILE: public/adminlte/js/pages/dashboard2.js
================================================
$(function () {
'use strict';
/* ChartJS
* -------
* Here we will create a few charts using ChartJS
*/
//-----------------------
//- MONTHLY SALES CHART -
//-----------------------
// Get context with jQuery - using jQuery's .get() method.
var salesChartCanvas = $("#salesChart").get(0).getContext("2d");
// This will get the first returned node in the jQuery collection.
var salesChart = new Chart(salesChartCanvas);
var salesChartData = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "Electronics",
fillColor: "rgb(210, 214, 222)",
strokeColor: "rgb(210, 214, 222)",
pointColor: "rgb(210, 214, 222)",
pointStrokeColor: "#c1c7d1",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgb(220,220,220)",
data: [65, 59, 80, 81, 56, 55, 40]
},
{
label: "Digital Goods",
fillColor: "rgba(60,141,188,0.9)",
strokeColor: "rgba(60,141,188,0.8)",
pointColor: "#3b8bba",
pointStrokeColor: "rgba(60,141,188,1)",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(60,141,188,1)",
data: [28, 48, 40, 19, 86, 27, 90]
}
]
};
var salesChartOptions = {
//Boolean - If we should show the scale at all
showScale: true,
//Boolean - Whether grid lines are shown across the chart
scaleShowGridLines: false,
//String - Colour of the grid lines
scaleGridLineColor: "rgba(0,0,0,.05)",
//Number - Width of the grid lines
scaleGridLineWidth: 1,
//Boolean - Whether to show horizontal lines (except X axis)
scaleShowHorizontalLines: true,
//Boolean - Whether to show vertical lines (except Y axis)
scaleShowVerticalLines: true,
//Boolean - Whether the line is curved between points
bezierCurve: true,
//Number - Tension of the bezier curve between points
bezierCurveTension: 0.3,
//Boolean - Whether to show a dot for each point
pointDot: false,
//Number - Radius of each point dot in pixels
pointDotRadius: 4,
//Number - Pixel width of point dot stroke
pointDotStrokeWidth: 1,
//Number - amount extra to add to the radius to cater for hit detection outside the drawn point
pointHitDetectionRadius: 20,
//Boolean - Whether to show a stroke for datasets
datasetStroke: true,
//Number - Pixel width of dataset stroke
datasetStrokeWidth: 2,
//Boolean - Whether to fill the dataset with a color
datasetFill: true,
//String - A legend template
legendTemplate: "
-legend\"><% for (var i=0; i
\"><%=datasets[i].label%>
<%}%>
",
//Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
maintainAspectRatio: true,
//Boolean - whether to make the chart responsive to window resizing
responsive: true
};
//Create the line chart
salesChart.Line(salesChartData, salesChartOptions);
//---------------------------
//- END MONTHLY SALES CHART -
//---------------------------
//-------------
//- PIE CHART -
//-------------
// Get context with jQuery - using jQuery's .get() method.
var pieChartCanvas = $("#pieChart").get(0).getContext("2d");
var pieChart = new Chart(pieChartCanvas);
var PieData = [
{
value: 700,
color: "#f56954",
highlight: "#f56954",
label: "Chrome"
},
{
value: 500,
color: "#00a65a",
highlight: "#00a65a",
label: "IE"
},
{
value: 400,
color: "#f39c12",
highlight: "#f39c12",
label: "FireFox"
},
{
value: 600,
color: "#00c0ef",
highlight: "#00c0ef",
label: "Safari"
},
{
value: 300,
color: "#3c8dbc",
highlight: "#3c8dbc",
label: "Opera"
},
{
value: 100,
color: "#d2d6de",
highlight: "#d2d6de",
label: "Navigator"
}
];
var pieOptions = {
//Boolean - Whether we should show a stroke on each segment
segmentShowStroke: true,
//String - The colour of each segment stroke
segmentStrokeColor: "#fff",
//Number - The width of each segment stroke
segmentStrokeWidth: 1,
//Number - The percentage of the chart that we cut out of the middle
percentageInnerCutout: 50, // This is 0 for Pie charts
//Number - Amount of animation steps
animationSteps: 100,
//String - Animation easing effect
animationEasing: "easeOutBounce",
//Boolean - Whether we animate the rotation of the Doughnut
animateRotate: true,
//Boolean - Whether we animate scaling the Doughnut from the centre
animateScale: false,
//Boolean - whether to make the chart responsive to window resizing
responsive: true,
// Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
maintainAspectRatio: false,
//String - A legend template
legendTemplate: "
",
//String - A tooltip template
tooltipTemplate: "<%=value %> <%=label%> users"
};
//Create pie or douhnut chart
// You can switch between pie and douhnut using the method below.
pieChart.Doughnut(PieData, pieOptions);
//-----------------
//- END PIE CHART -
//-----------------
/* jVector Maps
* ------------
* Create a world map with markers
*/
$('#world-map-markers').vectorMap({
map: 'world_mill_en',
normalizeFunction: 'polynomial',
hoverOpacity: 0.7,
hoverColor: false,
backgroundColor: 'transparent',
regionStyle: {
initial: {
fill: 'rgba(210, 214, 222, 1)',
"fill-opacity": 1,
stroke: 'none',
"stroke-width": 0,
"stroke-opacity": 1
},
hover: {
"fill-opacity": 0.7,
cursor: 'pointer'
},
selected: {
fill: 'yellow'
},
selectedHover: {}
},
markerStyle: {
initial: {
fill: '#00a65a',
stroke: '#111'
}
},
markers: [
{latLng: [41.90, 12.45], name: 'Vatican City'},
{latLng: [43.73, 7.41], name: 'Monaco'},
{latLng: [-0.52, 166.93], name: 'Nauru'},
{latLng: [-8.51, 179.21], name: 'Tuvalu'},
{latLng: [43.93, 12.46], name: 'San Marino'},
{latLng: [47.14, 9.52], name: 'Liechtenstein'},
{latLng: [7.11, 171.06], name: 'Marshall Islands'},
{latLng: [17.3, -62.73], name: 'Saint Kitts and Nevis'},
{latLng: [3.2, 73.22], name: 'Maldives'},
{latLng: [35.88, 14.5], name: 'Malta'},
{latLng: [12.05, -61.75], name: 'Grenada'},
{latLng: [13.16, -61.23], name: 'Saint Vincent and the Grenadines'},
{latLng: [13.16, -59.55], name: 'Barbados'},
{latLng: [17.11, -61.85], name: 'Antigua and Barbuda'},
{latLng: [-4.61, 55.45], name: 'Seychelles'},
{latLng: [7.35, 134.46], name: 'Palau'},
{latLng: [42.5, 1.51], name: 'Andorra'},
{latLng: [14.01, -60.98], name: 'Saint Lucia'},
{latLng: [6.91, 158.18], name: 'Federated States of Micronesia'},
{latLng: [1.3, 103.8], name: 'Singapore'},
{latLng: [1.46, 173.03], name: 'Kiribati'},
{latLng: [-21.13, -175.2], name: 'Tonga'},
{latLng: [15.3, -61.38], name: 'Dominica'},
{latLng: [-20.2, 57.5], name: 'Mauritius'},
{latLng: [26.02, 50.55], name: 'Bahrain'},
{latLng: [0.33, 6.73], name: 'São Tomé and Príncipe'}
]
});
/* SPARKLINE CHARTS
* ----------------
* Create a inline charts with spark line
*/
//-----------------
//- SPARKLINE BAR -
//-----------------
$('.sparkbar').each(function () {
var $this = $(this);
$this.sparkline('html', {
type: 'bar',
height: $this.data('height') ? $this.data('height') : '30',
barColor: $this.data('color')
});
});
//-----------------
//- SPARKLINE PIE -
//-----------------
$('.sparkpie').each(function () {
var $this = $(this);
$this.sparkline('html', {
type: 'pie',
height: $this.data('height') ? $this.data('height') : '90',
sliceColors: $this.data('color')
});
});
//------------------
//- SPARKLINE LINE -
//------------------
$('.sparkline').each(function () {
var $this = $(this);
$this.sparkline('html', {
type: 'line',
height: $this.data('height') ? $this.data('height') : '90',
width: '100%',
lineColor: $this.data('linecolor'),
fillColor: $this.data('fillcolor'),
spotColor: $this.data('spotcolor')
});
});
});
================================================
FILE: public/adminlte/js/textext.core.js
================================================
/**
* jQuery TextExt Plugin
* http://textextjs.com
*
* @version 1.3.1
* @copyright Copyright (C) 2011 Alex Gorbatchev. All rights reserved.
* @license MIT License
*/
(function($, undefined)
{
/**
* TextExt is the main core class which by itself doesn't provide any functionality
* that is user facing, however it has the underlying mechanics to bring all the
* plugins together under one roof and make them work with each other or on their
* own.
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExt
*/
function TextExt() {};
/**
* ItemManager is used to seamlessly convert between string that come from the user input to whatever
* the format the item data is being passed around in. It's used by all plugins that in one way or
* another operate with items, such as Tags, Filter, Autocomplete and Suggestions. Default implementation
* works with `String` type.
*
* Each instance of `TextExt` creates a new instance of default implementation of `ItemManager`
* unless `itemManager` option was set to another implementation.
*
* To satisfy requirements of managing items of type other than a `String`, different implementation
* if `ItemManager` should be supplied.
*
* If you wish to bring your own implementation, you need to create a new class and implement all the
* methods that `ItemManager` has. After, you need to supply your pass via the `itemManager` option during
* initialization like so:
*
* $('#input').textext({
* itemManager : CustomItemManager
* })
*
* @author agorbatchev
* @date 2011/08/19
* @id ItemManager
*/
function ItemManager() {};
/**
* TextExtPlugin is a base class for all plugins. It provides common methods which are reused
* by majority of plugins.
*
* All plugins must register themselves by calling the `$.fn.textext.addPlugin(name, constructor)`
* function while providing plugin name and constructor. The plugin name is the same name that user
* will identify the plugin in the `plugins` option when initializing TextExt component and constructor
* function will create a new instance of the plugin. *Without registering, the core won't
* be able to see the plugin.*
*
* new in 1.2.0 You can get instance of each plugin from the core
* via associated function with the same name as the plugin. For example:
*
* $('#input').textext()[0].tags()
* $('#input').textext()[0].autocomplete()
* ...
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExtPlugin
*/
function TextExtPlugin() {};
var stringify = (JSON || {}).stringify,
slice = Array.prototype.slice,
p,
UNDEFINED = 'undefined',
/**
* TextExt provides a way to pass in the options to configure the core as well as
* each plugin that is being currently used. The jQuery exposed plugin `$().textext()`
* function takes a hash object with key/value set of options. For example:
*
* $('textarea').textext({
* enabled: true
* })
*
* There are multiple ways of passing in the options:
*
* 1. Options could be nested multiple levels deep and accessed using all lowercased, dot
* separated style, eg `foo.bar.world`. The manual is using this style for clarity and
* consistency. For example:
*
* {
* item: {
* manager: ...
* },
*
* html: {
* wrap: ...
* },
*
* autocomplete: {
* enabled: ...,
* dropdown: {
* position: ...
* }
* }
* }
*
* 2. Options could be specified using camel cased names in a flat key/value fashion like so:
*
* {
* itemManager: ...,
* htmlWrap: ...,
* autocompleteEnabled: ...,
* autocompleteDropdownPosition: ...
* }
*
* 3. Finally, options could be specified in mixed style. It's important to understand that
* for each dot separated name, its alternative in camel case is also checked for, eg for
* `foo.bar.world` it's alternatives could be `fooBarWorld`, `foo.barWorld` or `fooBar.world`,
* which translates to `{ foo: { bar: { world: ... } } }`, `{ fooBarWorld: ... }`,
* `{ foo : { barWorld : ... } }` or `{ fooBar: { world: ... } }` respectively. For example:
*
* {
* itemManager : ...,
* htmlWrap: ...,
* autocomplete: {
* enabled: ...,
* dropdownPosition: ...
* }
* }
*
* Mixed case is used through out the code, wherever it seems appropriate. However in the code, all option
* names are specified in the dot notation because it works both ways where as camel case is not
* being converted to its alternative dot notation.
*
* @author agorbatchev
* @date 2011/08/17
* @id TextExt.options
*/
/**
* Default instance of `ItemManager` which takes `String` type as default for tags.
*
* @name item.manager
* @default ItemManager
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.options.item.manager
*/
OPT_ITEM_MANAGER = 'item.manager',
/**
* List of plugins that should be used with the current instance of TextExt. The list could be
* specified as array of strings or as comma or space separated string.
*
* @name plugins
* @default []
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.options.plugins
*/
OPT_PLUGINS = 'plugins',
/**
* TextExt allows for overriding of virtually any method that the core or any of its plugins
* use. This could be accomplished through the use of the `ext` option.
*
* It's possible to specifically target the core or any plugin, as well as overwrite all the
* desired methods everywhere.
*
* 1. Targeting the core:
*
* ext: {
* core: {
* trigger: function()
* {
* console.log('TextExt.trigger', arguments);
* $.fn.textext.TextExt.prototype.trigger.apply(this, arguments);
* }
* }
* }
*
* 2. Targeting individual plugins:
*
* ext: {
* tags: {
* addTags: function(tags)
* {
* console.log('TextExtTags.addTags', tags);
* $.fn.textext.TextExtTags.prototype.addTags.apply(this, arguments);
* }
* }
* }
*
* 3. Targeting `ItemManager` instance:
*
* ext: {
* itemManager: {
* stringToItem: function(str)
* {
* console.log('ItemManager.stringToItem', str);
* return $.fn.textext.ItemManager.prototype.stringToItem.apply(this, arguments);
* }
* }
* }
*
* 4. And finally, in edge cases you can extend everything at once:
*
* ext: {
* '*': {
* fooBar: function() {}
* }
* }
*
* @name ext
* @default {}
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.options.ext
*/
OPT_EXT = 'ext',
/**
* HTML source that is used to generate elements necessary for the core and all other
* plugins to function.
*
* @name html.wrap
* @default '
'
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.options.html.wrap
*/
OPT_HTML_WRAP = 'html.wrap',
/**
* HTML source that is used to generate hidden input value of which will be submitted
* with the HTML form.
*
* @name html.hidden
* @default ''
* @author agorbatchev
* @date 2011/08/20
* @id TextExt.options.html.hidden
*/
OPT_HTML_HIDDEN = 'html.hidden',
/**
* Hash table of key codes and key names for which special events will be created
* by the core. For each entry a `[name]KeyDown`, `[name]KeyUp` and `[name]KeyPress` events
* will be triggered along side with `anyKeyUp` and `anyKeyDown` events for every
* key stroke.
*
* Here's a list of default keys:
*
* {
* 8 : 'backspace',
* 9 : 'tab',
* 13 : 'enter!',
* 27 : 'escape!',
* 37 : 'left',
* 38 : 'up!',
* 39 : 'right',
* 40 : 'down!',
* 46 : 'delete',
* 108 : 'numpadEnter'
* }
*
* Please note the `!` at the end of some keys. This tells the core that by default
* this keypress will be trapped and not passed on to the text input.
*
* @name keys
* @default { ... }
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.options.keys
*/
OPT_KEYS = 'keys',
/**
* The core triggers or reacts to the following events.
*
* @author agorbatchev
* @date 2011/08/17
* @id TextExt.events
*/
/**
* Core triggers `preInvalidate` event before the dimensions of padding on the text input
* are set.
*
* @name preInvalidate
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.events.preInvalidate
*/
EVENT_PRE_INVALIDATE = 'preInvalidate',
/**
* Core triggers `postInvalidate` event after the dimensions of padding on the text input
* are set.
*
* @name postInvalidate
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.events.postInvalidate
*/
EVENT_POST_INVALIDATE = 'postInvalidate',
/**
* Core triggers `getFormData` on every key press to collect data that will be populated
* into the hidden input that will be submitted with the HTML form and data that will
* be displayed in the input field that user is currently interacting with.
*
* All plugins that wish to affect how the data is presented or sent must react to
* `getFormData` and populate the data in the following format:
*
* {
* input : {String},
* form : {Object}
* }
*
* The data key must be a numeric weight which will be used to determine which data
* ends up being used. Data with the highest numerical weight gets the priority. This
* allows plugins to set the final data regardless of their initialization order, which
* otherwise would be impossible.
*
* For example, the Tags and Autocomplete plugins have to work side by side and Tags
* plugin must get priority on setting the data. Therefore the Tags plugin sets data
* with the weight 200 where as the Autocomplete plugin sets data with the weight 100.
*
* Here's an example of a typical `getFormData` handler:
*
* TextExtPlugin.prototype.onGetFormData = function(e, data, keyCode)
* {
* data[100] = self.formDataObject('input value', 'form value');
* };
*
* Core also reacts to the `getFormData` and updates hidden input with data which will be
* submitted with the HTML form.
*
* @name getFormData
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.events.getFormData
*/
EVENT_GET_FORM_DATA = 'getFormData',
/**
* Core triggers and reacts to the `setFormData` event to update the actual value in the
* hidden input that will be submitted with the HTML form. Second argument can be value
* of any type and by default it will be JSON serialized with `TextExt.serializeData()`
* function.
*
* @name setFormData
* @author agorbatchev
* @date 2011/08/22
* @id TextExt.events.setFormData
*/
EVENT_SET_FORM_DATA = 'setFormData',
/**
* Core triggers and reacts to the `setInputData` event to update the actual value in the
* text input that user is interacting with. Second argument must be of a `String` type
* the value of which will be set into the text input.
*
* @name setInputData
* @author agorbatchev
* @date 2011/08/22
* @id TextExt.events.setInputData
*/
EVENT_SET_INPUT_DATA = 'setInputData',
/**
* Core triggers `postInit` event to let plugins run code after all plugins have been
* created and initialized. This is a good place to set some kind of global values before
* somebody gets to use them. This is not the right place to expect all plugins to finish
* their initialization.
*
* @name postInit
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.events.postInit
*/
EVENT_POST_INIT = 'postInit',
/**
* Core triggers `ready` event after all global configuration and prepearation has been
* done and the TextExt component is ready for use. Event handlers should expect all
* values to be set and the plugins to be in the final state.
*
* @name ready
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.events.ready
*/
EVENT_READY = 'ready',
/**
* Core triggers `anyKeyUp` event for every key up event triggered within the component.
*
* @name anyKeyUp
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.events.anyKeyUp
*/
/**
* Core triggers `anyKeyDown` event for every key down event triggered within the component.
*
* @name anyKeyDown
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.events.anyKeyDown
*/
/**
* Core triggers `[name]KeyUp` event for every key specifid in the `keys` option that is
* triggered within the component.
*
* @name [name]KeyUp
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.events.[name]KeyUp
*/
/**
* Core triggers `[name]KeyDown` event for every key specified in the `keys` option that is
* triggered within the component.
*
* @name [name]KeyDown
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.events.[name]KeyDown
*/
/**
* Core triggers `[name]KeyPress` event for every key specified in the `keys` option that is
* triggered within the component.
*
* @name [name]KeyPress
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.events.[name]KeyPress
*/
DEFAULT_OPTS = {
itemManager : ItemManager,
plugins : [],
ext : {},
html : {
wrap : '
',
hidden : ''
},
keys : {
8 : 'backspace',
9 : 'tab',
13 : 'enter!',
27 : 'escape!',
37 : 'left',
38 : 'up!',
39 : 'right',
40 : 'down!',
46 : 'delete',
108 : 'numpadEnter'
}
}
;
// Freak out if there's no JSON.stringify function found
if(!stringify)
throw new Error('JSON.stringify() not found');
/**
* Returns object property by name where name is dot-separated and object is multiple levels deep.
* @param target Object Source object.
* @param name String Dot separated property name, ie `foo.bar.world`
* @id core.getProperty
*/
function getProperty(source, name)
{
if(typeof(name) === 'string')
name = name.split('.');
var fullCamelCaseName = name.join('.').replace(/\.(\w)/g, function(match, letter) { return letter.toUpperCase() }),
nestedName = name.shift(),
result
;
if(typeof(result = source[fullCamelCaseName]) != UNDEFINED)
result = result;
else if(typeof(result = source[nestedName]) != UNDEFINED && name.length > 0)
result = getProperty(result, name);
// name.length here should be zero
return result;
};
/**
* Hooks up specified events in the scope of the current object.
* @author agorbatchev
* @date 2011/08/09
*/
function hookupEvents()
{
var args = slice.apply(arguments),
self = this,
target = args.length === 1 ? self : args.shift(),
event
;
args = args[0] || {};
function bind(event, handler)
{
target.bind(event, function()
{
// apply handler to our PLUGIN object, not the target
return handler.apply(self, arguments);
});
}
for(event in args)
bind(event, args[event]);
};
function formDataObject(input, form)
{
return { 'input' : input, 'form' : form };
};
//--------------------------------------------------------------------------------
// ItemManager core component
p = ItemManager.prototype;
/**
* Initialization method called by the core during instantiation.
*
* @signature ItemManager.init(core)
*
* @param core {TextExt} Instance of the TextExt core class.
*
* @author agorbatchev
* @date 2011/08/19
* @id ItemManager.init
*/
p.init = function(core)
{
};
/**
* Filters out items from the list that don't match the query and returns remaining items. Default
* implementation checks if the item starts with the query.
*
* @signature ItemManager.filter(list, query)
*
* @param list {Array} List of items. Default implementation works with strings.
* @param query {String} Query string.
*
* @author agorbatchev
* @date 2011/08/19
* @id ItemManager.filter
*/
p.filter = function(list, query)
{
var result = [],
i, item
;
for(i = 0; i < list.length; i++)
{
item = list[i];
if(this.itemContains(item, query))
result.push(item);
}
return result;
};
/**
* Returns `true` if specified item contains another string, `false` otherwise. In the default implementation
* `String.indexOf()` is used to check if item string begins with the needle string.
*
* @signature ItemManager.itemContains(item, needle)
*
* @param item {Object} Item to check. Default implementation works with strings.
* @param needle {String} Search string to be found within the item.
*
* @author agorbatchev
* @date 2011/08/19
* @id ItemManager.itemContains
*/
p.itemContains = function(item, needle)
{
return this.itemToString(item).toLowerCase().indexOf(needle.toLowerCase()) == 0;
};
/**
* Converts specified string to item. Because default implemenation works with string, input string
* is simply returned back. To use custom objects, different implementation of this method could
* return something like `{ name : {String} }`.
*
* @signature ItemManager.stringToItem(str)
*
* @param str {String} Input string.
*
* @author agorbatchev
* @date 2011/08/19
* @id ItemManager.stringToItem
*/
p.stringToItem = function(str)
{
return str;
};
/**
* Converts specified item to string. Because default implemenation works with string, input string
* is simply returned back. To use custom objects, different implementation of this method could
* for example return `name` field of `{ name : {String} }`.
*
* @signature ItemManager.itemToString(item)
*
* @param item {Object} Input item to be converted to string.
*
* @author agorbatchev
* @date 2011/08/19
* @id ItemManager.itemToString
*/
p.itemToString = function(item)
{
return item;
};
/**
* Returns `true` if both items are equal, `false` otherwise. Because default implemenation works with
* string, input items are compared as strings. To use custom objects, different implementation of this
* method could for example compare `name` fields of `{ name : {String} }` type object.
*
* @signature ItemManager.compareItems(item1, item2)
*
* @param item1 {Object} First item.
* @param item2 {Object} Second item.
*
* @author agorbatchev
* @date 2011/08/19
* @id ItemManager.compareItems
*/
p.compareItems = function(item1, item2)
{
return item1 == item2;
};
//--------------------------------------------------------------------------------
// TextExt core component
p = TextExt.prototype;
/**
* Initializes current component instance with work with the supplied text input and options.
*
* @signature TextExt.init(input, opts)
*
* @param input {HTMLElement} Text input.
* @param opts {Object} Options.
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.init
*/
p.init = function(input, opts)
{
var self = this,
hiddenInput,
itemManager,
container
;
self._defaults = $.extend({}, DEFAULT_OPTS);
self._opts = opts || {};
self._plugins = {};
self._itemManager = itemManager = new (self.opts(OPT_ITEM_MANAGER))();
input = $(input);
container = $(self.opts(OPT_HTML_WRAP));
hiddenInput = $(self.opts(OPT_HTML_HIDDEN));
input
.wrap(container)
.keydown(function(e) { return self.onKeyDown(e) })
.keyup(function(e) { return self.onKeyUp(e) })
.data('textext', self)
;
// keep references to html elements using jQuery.data() to avoid circular references
$(self).data({
'hiddenInput' : hiddenInput,
'wrapElement' : input.parents('.text-wrap').first(),
'input' : input
});
// set the name of the hidden input to the text input's name
hiddenInput.attr('name', input.attr('name'));
// remove name attribute from the text input
input.attr('name', null);
// add hidden input to the DOM
hiddenInput.insertAfter(input);
$.extend(true, itemManager, self.opts(OPT_EXT + '.item.manager'));
$.extend(true, self, self.opts(OPT_EXT + '.*'), self.opts(OPT_EXT + '.core'));
self.originalWidth = input.outerWidth();
self.invalidateBounds();
itemManager.init(self);
self.initPatches();
self.initPlugins(self.opts(OPT_PLUGINS), $.fn.textext.plugins);
self.on({
setFormData : self.onSetFormData,
getFormData : self.onGetFormData,
setInputData : self.onSetInputData,
anyKeyUp : self.onAnyKeyUp
});
self.trigger(EVENT_POST_INIT);
self.trigger(EVENT_READY);
self.getFormData(0);
};
/**
* Initialized all installed patches against current instance. The patches are initialized based on their
* initialization priority which is returned by each patch's `initPriority()` method. Priority
* is a `Number` where patches with higher value gets their `init()` method called before patches
* with lower priority value.
*
* This facilitates initializing of patches in certain order to insure proper dependencies
* regardless of which order they are loaded.
*
* By default all patches have the same priority - zero, which means they will be initialized
* in rorder they are loaded, that is unless `initPriority()` is overriden.
*
* @signature TextExt.initPatches()
*
* @author agorbatchev
* @date 2011/10/11
* @id TextExt.initPatches
*/
p.initPatches = function()
{
var list = [],
source = $.fn.textext.patches,
name
;
for(name in source)
list.push(name);
this.initPlugins(list, source);
};
/**
* Creates and initializes all specified plugins. The plugins are initialized based on their
* initialization priority which is returned by each plugin's `initPriority()` method. Priority
* is a `Number` where plugins with higher value gets their `init()` method called before plugins
* with lower priority value.
*
* This facilitates initializing of plugins in certain order to insure proper dependencies
* regardless of which order user enters them in the `plugins` option field.
*
* By default all plugins have the same priority - zero, which means they will be initialized
* in the same order as entered by the user.
*
* @signature TextExt.initPlugins(plugins)
*
* @param plugins {Array} List of plugin names to initialize.
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.initPlugins
*/
p.initPlugins = function(plugins, source)
{
var self = this,
ext, name, plugin, initList = [], i
;
if(typeof(plugins) == 'string')
plugins = plugins.split(/\s*,\s*|\s+/g);
for(i = 0; i < plugins.length; i++)
{
name = plugins[i];
plugin = source[name];
if(plugin)
{
self._plugins[name] = plugin = new plugin();
self[name] = (function(plugin) {
return function(){ return plugin; }
})(plugin);
initList.push(plugin);
$.extend(true, plugin, self.opts(OPT_EXT + '.*'), self.opts(OPT_EXT + '.' + name));
}
}
// sort plugins based on their priority values
initList.sort(function(p1, p2)
{
p1 = p1.initPriority();
p2 = p2.initPriority();
return p1 === p2
? 0
: p1 < p2 ? 1 : -1
;
});
for(i = 0; i < initList.length; i++)
initList[i].init(self);
};
/**
* Returns true if specified plugin is was instantiated for the current instance of core.
*
* @signature TextExt.hasPlugin(name)
*
* @param name {String} Name of the plugin to check.
*
* @author agorbatchev
* @date 2011/12/28
* @id TextExt.hasPlugin
* @version 1.1
*/
p.hasPlugin = function(name)
{
return !!this._plugins[name];
};
/**
* Allows to add multiple event handlers which will be execued in the scope of the current object.
*
* @signature TextExt.on([target], handlers)
*
* @param target {Object} **Optional**. Target object which has traditional `bind(event, handler)` method.
* Handler function will still be executed in the current object's scope.
* @param handlers {Object} Key/value pairs of event names and handlers, eg `{ event: handler }`.
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.on
*/
p.on = hookupEvents;
/**
* Binds an event handler to the input box that user interacts with.
*
* @signature TextExt.bind(event, handler)
*
* @param event {String} Event name.
* @param handler {Function} Event handler.
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.bind
*/
p.bind = function(event, handler)
{
this.input().bind(event, handler);
};
/**
* Triggers an event on the input box that user interacts with. All core events are originated here.
*
* @signature TextExt.trigger(event, ...args)
*
* @param event {String} Name of the event to trigger.
* @param ...args All remaining arguments will be passed to the event handler.
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.trigger
*/
p.trigger = function()
{
var args = arguments;
this.input().trigger(args[0], slice.call(args, 1));
};
/**
* Returns instance of `itemManager` that is used by the component.
*
* @signature TextExt.itemManager()
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.itemManager
*/
p.itemManager = function()
{
return this._itemManager;
};
/**
* Returns jQuery input element with which user is interacting with.
*
* @signature TextExt.input()
*
* @author agorbatchev
* @date 2011/08/10
* @id TextExt.input
*/
p.input = function()
{
return $(this).data('input');
};
/**
* Returns option value for the specified option by name. If the value isn't found in the user
* provided options, it will try looking for default value.
*
* @signature TextExt.opts(name)
*
* @param name {String} Option name as described in the options.
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.opts
*/
p.opts = function(name)
{
var result = getProperty(this._opts, name);
return typeof(result) == 'undefined' ? getProperty(this._defaults, name) : result;
};
/**
* Returns HTML element that was created from the `html.wrap` option. This is the top level HTML
* container for the text input with which user is interacting with.
*
* @signature TextExt.wrapElement()
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.wrapElement
*/
p.wrapElement = function()
{
return $(this).data('wrapElement');
};
/**
* Updates container to match dimensions of the text input. Triggers `preInvalidate` and `postInvalidate`
* events.
*
* @signature TextExt.invalidateBounds()
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.invalidateBounds
*/
p.invalidateBounds = function()
{
var self = this,
input = self.input(),
wrap = self.wrapElement(),
container = wrap.parent(),
width = self.originalWidth + 'px',
height
;
self.trigger(EVENT_PRE_INVALIDATE);
height = input.outerHeight() + 'px';
// using css() method instead of width() and height() here because they don't seem to do the right thing in jQuery 1.8.x
// https://github.com/alexgorbatchev/jquery-textext/issues/74
input.css({ 'width' : width });
wrap.css({ 'width' : width, 'height' : height });
container.css({ 'height' : height });
self.trigger(EVENT_POST_INVALIDATE);
};
/**
* Focuses user input on the text box.
*
* @signature TextExt.focusInput()
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.focusInput
*/
p.focusInput = function()
{
this.input()[0].focus();
};
/**
* Serializes data for to be set into the hidden input field and which will be submitted
* with the HTML form.
*
* By default simple JSON serialization is used. It's expected that `JSON.stringify`
* method would be available either through built in class in most modern browsers
* or through JSON2 library.
*
* @signature TextExt.serializeData(data)
*
* @param data {Object} Data to serialize.
*
* @author agorbatchev
* @date 2011/08/09
* @id TextExt.serializeData
*/
p.serializeData = stringify;
/**
* Returns the hidden input HTML element which will be submitted with the HTML form.
*
* @signature TextExt.hiddenInput()
*
* @author agorbatchev
* @date 2011/08/09
* @id TextExt.hiddenInput
*/
p.hiddenInput = function(value)
{
return $(this).data('hiddenInput');
};
/**
* Abstracted functionality to trigger an event and get the data with maximum weight set by all
* the event handlers. This functionality is used for the `getFormData` event.
*
* @signature TextExt.getWeightedEventResponse(event, args)
*
* @param event {String} Event name.
* @param args {Object} Argument to be passed with the event.
*
* @author agorbatchev
* @date 2011/08/22
* @id TextExt.getWeightedEventResponse
*/
p.getWeightedEventResponse = function(event, args)
{
var self = this,
data = {},
maxWeight = 0
;
self.trigger(event, data, args);
for(var weight in data)
maxWeight = Math.max(maxWeight, weight);
return data[maxWeight];
};
/**
* Triggers the `getFormData` event to get all the plugins to return their data.
*
* After the data is returned, triggers `setFormData` and `setInputData` to update appopriate values.
*
* @signature TextExt.getFormData(keyCode)
*
* @param keyCode {Number} Key code number which has triggered this update. It's impotant to pass
* this value to the plugins because they might return different values based on the key that was
* pressed. For example, the Tags plugin returns an empty string for the `input` value if the enter
* key was pressed, otherwise it returns whatever is currently in the text input.
*
* @author agorbatchev
* @date 2011/08/22
* @id TextExt.getFormData
*/
p.getFormData = function(keyCode)
{
var self = this,
data = self.getWeightedEventResponse(EVENT_GET_FORM_DATA, keyCode || 0)
;
self.trigger(EVENT_SET_FORM_DATA , data['form']);
self.trigger(EVENT_SET_INPUT_DATA , data['input']);
};
//--------------------------------------------------------------------------------
// Event handlers
/**
* Reacts to the `anyKeyUp` event and triggers the `getFormData` to change data that will be submitted
* with the form. Default behaviour is that everything that is typed in will be JSON serialized, so
* the end result will be a JSON string.
*
* @signature TextExt.onAnyKeyUp(e)
*
* @param e {Object} jQuery event.
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.onAnyKeyUp
*/
p.onAnyKeyUp = function(e, keyCode)
{
this.getFormData(keyCode);
};
/**
* Reacts to the `setInputData` event and populates the input text field that user is currently
* interacting with.
*
* @signature TextExt.onSetInputData(e, data)
*
* @param e {Event} jQuery event.
* @param data {String} Value to be set.
*
* @author agorbatchev
* @date 2011/08/22
* @id TextExt.onSetInputData
*/
p.onSetInputData = function(e, data)
{
this.input().val(data);
};
/**
* Reacts to the `setFormData` event and populates the hidden input with will be submitted with
* the HTML form. The value will be serialized with `serializeData()` method.
*
* @signature TextExt.onSetFormData(e, data)
*
* @param e {Event} jQuery event.
* @param data {Object} Data that will be set.
*
* @author agorbatchev
* @date 2011/08/22
* @id TextExt.onSetFormData
*/
p.onSetFormData = function(e, data)
{
var self = this;
self.hiddenInput().val(self.serializeData(data));
};
/**
* Reacts to `getFormData` event triggered by the core. At the bare minimum the core will tell
* itself to use the current value in the text input as the data to be submitted with the HTML
* form.
*
* @signature TextExt.onGetFormData(e, data)
*
* @param e {Event} jQuery event.
*
* @author agorbatchev
* @date 2011/08/09
* @id TextExt.onGetFormData
*/
p.onGetFormData = function(e, data)
{
var val = this.input().val();
data[0] = formDataObject(val, val);
};
//--------------------------------------------------------------------------------
// User mouse/keyboard input
/**
* Triggers `[name]KeyUp` and `[name]KeyPress` for every keystroke as described in the events.
*
* @signature TextExt.onKeyUp(e)
*
* @param e {Object} jQuery event.
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.onKeyUp
*/
/**
* Triggers `[name]KeyDown` for every keystroke as described in the events.
*
* @signature TextExt.onKeyDown(e)
*
* @param e {Object} jQuery event.
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.onKeyDown
*/
$(['Down', 'Up']).each(function()
{
var type = this.toString();
p['onKey' + type] = function(e)
{
var self = this,
keyName = self.opts(OPT_KEYS)[e.keyCode],
defaultResult = true
;
if(keyName)
{
defaultResult = keyName.substr(-1) != '!';
keyName = keyName.replace('!', '');
self.trigger(keyName + 'Key' + type);
// manual *KeyPress event fimplementation for the function keys like Enter, Backspace, etc.
if(type == 'Up' && self._lastKeyDown == e.keyCode)
{
self._lastKeyDown = null;
self.trigger(keyName + 'KeyPress');
}
if(type == 'Down')
self._lastKeyDown = e.keyCode;
}
self.trigger('anyKey' + type, e.keyCode);
return defaultResult;
};
});
//--------------------------------------------------------------------------------
// Plugin Base
p = TextExtPlugin.prototype;
/**
* Allows to add multiple event handlers which will be execued in the scope of the current object.
*
* @signature TextExt.on([target], handlers)
*
* @param target {Object} **Optional**. Target object which has traditional `bind(event, handler)` method.
* Handler function will still be executed in the current object's scope.
* @param handlers {Object} Key/value pairs of event names and handlers, eg `{ event: handler }`.
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExtPlugin.on
*/
p.on = hookupEvents;
/**
* Returns the hash object that `getFormData` triggered by the core expects.
*
* @signature TextExtPlugin.formDataObject(input, form)
*
* @param input {String} Value that will go into the text input that user is interacting with.
* @param form {Object} Value that will be serialized and put into the hidden that will be submitted
* with the HTML form.
*
* @author agorbatchev
* @date 2011/08/22
* @id TextExtPlugin.formDataObject
*/
p.formDataObject = formDataObject;
/**
* Initialization method called by the core during plugin instantiation. This method must be implemented
* by each plugin individually.
*
* @signature TextExtPlugin.init(core)
*
* @param core {TextExt} Instance of the TextExt core class.
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExtPlugin.init
*/
p.init = function(core) { throw new Error('Not implemented') };
/**
* Initialization method wich should be called by the plugin during the `init()` call.
*
* @signature TextExtPlugin.baseInit(core, defaults)
*
* @param core {TextExt} Instance of the TextExt core class.
* @param defaults {Object} Default plugin options. These will be checked if desired value wasn't
* found in the options supplied by the user.
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExtPlugin.baseInit
*/
p.baseInit = function(core, defaults)
{
var self = this;
core._defaults = $.extend(true, core._defaults, defaults);
self._core = core;
self._timers = {};
};
/**
* Allows starting of multiple timeout calls. Each time this method is called with the same
* timer name, the timer is reset. This functionality is useful in cases where an action needs
* to occur only after a certain period of inactivity. For example, making an AJAX call after
* user stoped typing for 1 second.
*
* @signature TextExtPlugin.startTimer(name, delay, callback)
*
* @param name {String} Timer name.
* @param delay {Number} Delay in seconds.
* @param callback {Function} Callback function.
*
* @author agorbatchev
* @date 2011/08/25
* @id TextExtPlugin.startTimer
*/
p.startTimer = function(name, delay, callback)
{
var self = this;
self.stopTimer(name);
self._timers[name] = setTimeout(
function()
{
delete self._timers[name];
callback.apply(self);
},
delay * 1000
);
};
/**
* Stops the timer by name without resetting it.
*
* @signature TextExtPlugin.stopTimer(name)
*
* @param name {String} Timer name.
*
* @author agorbatchev
* @date 2011/08/25
* @id TextExtPlugin.stopTimer
*/
p.stopTimer = function(name)
{
clearTimeout(this._timers[name]);
};
/**
* Returns instance of the `TextExt` to which current instance of the plugin is attached to.
*
* @signature TextExtPlugin.core()
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExtPlugin.core
*/
p.core = function()
{
return this._core;
};
/**
* Shortcut to the core's `opts()` method. Returns option value.
*
* @signature TextExtPlugin.opts(name)
*
* @param name {String} Option name as described in the options.
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExtPlugin.opts
*/
p.opts = function(name)
{
return this.core().opts(name);
};
/**
* Shortcut to the core's `itemManager()` method. Returns instance of the `ItemManger` that is
* currently in use.
*
* @signature TextExtPlugin.itemManager()
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExtPlugin.itemManager
*/
p.itemManager = function()
{
return this.core().itemManager();
};
/**
* Shortcut to the core's `input()` method. Returns instance of the HTML element that represents
* current text input.
*
* @signature TextExtPlugin.input()
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExtPlugin.input
*/
p.input = function()
{
return this.core().input();
};
/**
* Shortcut to the commonly used `this.input().val()` call to get or set value of the text input.
*
* @signature TextExtPlugin.val(value)
*
* @param value {String} Optional value. If specified, the value will be set, otherwise it will be
* returned.
*
* @author agorbatchev
* @date 2011/08/20
* @id TextExtPlugin.val
*/
p.val = function(value)
{
var input = this.input();
if(typeof(value) === UNDEFINED)
return input.val();
else
input.val(value);
};
/**
* Shortcut to the core's `trigger()` method. Triggers specified event with arguments on the
* component core.
*
* @signature TextExtPlugin.trigger(event, ...args)
*
* @param event {String} Name of the event to trigger.
* @param ...args All remaining arguments will be passed to the event handler.
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExtPlugin.trigger
*/
p.trigger = function()
{
var core = this.core();
core.trigger.apply(core, arguments);
};
/**
* Shortcut to the core's `bind()` method. Binds specified handler to the event.
*
* @signature TextExtPlugin.bind(event, handler)
*
* @param event {String} Event name.
* @param handler {Function} Event handler.
*
* @author agorbatchev
* @date 2011/08/20
* @id TextExtPlugin.bind
*/
p.bind = function(event, handler)
{
this.core().bind(event, handler);
};
/**
* Returns initialization priority for this plugin. If current plugin depends upon some other plugin
* to be initialized before or after, priority needs to be adjusted accordingly. Plugins with higher
* priority initialize before plugins with lower priority.
*
* Default initialization priority is `0`.
*
* @signature TextExtPlugin.initPriority()
*
* @author agorbatchev
* @date 2011/08/22
* @id TextExtPlugin.initPriority
*/
p.initPriority = function()
{
return 0;
};
//--------------------------------------------------------------------------------
// jQuery Integration
/**
* TextExt integrates as a jQuery plugin available through the `$(selector).textext(opts)` call. If
* `opts` argument is passed, then a new instance of `TextExt` will be created for all the inputs
* that match the `selector`. If `opts` wasn't passed and TextExt was already intantiated for
* inputs that match the `selector`, array of `TextExt` instances will be returned instead.
*
* // will create a new instance of `TextExt` for all elements that match `.sample`
* $('.sample').textext({ ... });
*
* // will return array of all `TextExt` instances
* var list = $('.sample').textext();
*
* The following properties are also exposed through the jQuery `$.fn.textext`:
*
* * `TextExt` -- `TextExt` class.
* * `TextExtPlugin` -- `TextExtPlugin` class.
* * `ItemManager` -- `ItemManager` class.
* * `plugins` -- Key/value table of all registered plugins.
* * `addPlugin(name, constructor)` -- All plugins should register themselves using this function.
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.jquery
*/
var cssInjected = false;
var textext = $.fn.textext = function(opts)
{
var css;
if(!cssInjected && (css = $.fn.textext.css) != null)
{
$('head').append('');
cssInjected = true;
}
return this.map(function()
{
var self = $(this);
if(opts == null)
return self.data('textext');
var instance = new TextExt();
instance.init(self, opts);
self.data('textext', instance);
return instance.input()[0];
});
};
/**
* This static function registers a new plugin which makes it available through the `plugins` option
* to the end user. The name specified here is the name the end user would put in the `plugins` option
* to add this plugin to a new instance of TextExt.
*
* @signature $.fn.textext.addPlugin(name, constructor)
*
* @param name {String} Name of the plugin.
* @param constructor {Function} Plugin constructor.
*
* @author agorbatchev
* @date 2011/10/11
* @id TextExt.addPlugin
*/
textext.addPlugin = function(name, constructor)
{
textext.plugins[name] = constructor;
constructor.prototype = new textext.TextExtPlugin();
};
/**
* This static function registers a new patch which is added to each instance of TextExt. If you are
* adding a new patch, make sure to call this method.
*
* @signature $.fn.textext.addPatch(name, constructor)
*
* @param name {String} Name of the patch.
* @param constructor {Function} Patch constructor.
*
* @author agorbatchev
* @date 2011/10/11
* @id TextExt.addPatch
*/
textext.addPatch = function(name, constructor)
{
textext.patches[name] = constructor;
constructor.prototype = new textext.TextExtPlugin();
};
textext.TextExt = TextExt;
textext.TextExtPlugin = TextExtPlugin;
textext.ItemManager = ItemManager;
textext.plugins = {};
textext.patches = {};
})(jQuery);
(function($)
{
function TextExtIE9Patches() {};
$.fn.textext.TextExtIE9Patches = TextExtIE9Patches;
$.fn.textext.addPatch('ie9',TextExtIE9Patches);
var p = TextExtIE9Patches.prototype;
p.init = function(core)
{
if(navigator.userAgent.indexOf('MSIE 9') == -1)
return;
var self = this;
core.on({ postInvalidate : self.onPostInvalidate });
};
p.onPostInvalidate = function()
{
var self = this,
input = self.input(),
val = input.val()
;
// agorbatchev :: IE9 doesn't seem to update the padding if box-sizing is on until the
// text box value changes, so forcing this change seems to do the trick of updating
// IE's padding visually.
input.val(Math.random());
input.val(val);
};
})(jQuery);
================================================
FILE: public/adminlte/js/textext.plugin.tags.js
================================================
/**
* jQuery TextExt Plugin
* http://textextjs.com
*
* @version 1.3.1
* @copyright Copyright (C) 2011 Alex Gorbatchev. All rights reserved.
* @license MIT License
*/
(function($)
{
/**
* Tags plugin brings in the traditional tag functionality where user can assemble and
* edit list of tags. Tags plugin works especially well together with Autocomplete, Filter,
* Suggestions and Ajax plugins to provide full spectrum of features. It can also work on
* its own and just do one thing -- tags.
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExtTags
*/
function TextExtTags() {};
$.fn.textext.TextExtTags = TextExtTags;
$.fn.textext.addPlugin('tags', TextExtTags);
var p = TextExtTags.prototype,
CSS_DOT = '.',
CSS_TAGS_ON_TOP = 'text-tags-on-top',
CSS_DOT_TAGS_ON_TOP = CSS_DOT + CSS_TAGS_ON_TOP,
CSS_TAG = 'text-tag',
CSS_DOT_TAG = CSS_DOT + CSS_TAG,
CSS_TAGS = 'text-tags',
CSS_DOT_TAGS = CSS_DOT + CSS_TAGS,
CSS_LABEL = 'text-label',
CSS_DOT_LABEL = CSS_DOT + CSS_LABEL,
CSS_REMOVE = 'text-remove',
CSS_DOT_REMOVE = CSS_DOT + CSS_REMOVE,
/**
* Tags plugin options are grouped under `tags` when passed to the
* `$().textext()` function. For example:
*
* $('textarea').textext({
* plugins: 'tags',
* tags: {
* items: [ "tag1", "tag2" ]
* }
* })
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExtTags.options
*/
/**
* This is a toggle switch to enable or disable the Tags plugin. The value is checked
* each time at the top level which allows you to toggle this setting on the fly.
*
* @name tags.enabled
* @default true
* @author agorbatchev
* @date 2011/08/19
* @id TextExtTags.options.tags.enabled
*/
OPT_ENABLED = 'tags.enabled',
/**
* Allows to specify tags which will be added to the input by default upon initialization.
* Each item in the array must be of the type that current `ItemManager` can understand.
* Default type is `String`.
*
* @name tags.items
* @default null
* @author agorbatchev
* @date 2011/08/19
* @id TextExtTags.options.tags.items
*/
OPT_ITEMS = 'tags.items',
/**
* HTML source that is used to generate a single tag.
*
* @name html.tag
* @default ''
* @author agorbatchev
* @date 2011/08/19
* @id TextExtTags.options.html.tag
*/
OPT_HTML_TAG = 'html.tag',
/**
* HTML source that is used to generate container for the tags.
*
* @name html.tags
* @default '
'
* @author agorbatchev
* @date 2011/08/19
* @id TextExtTags.options.html.tags
*/
OPT_HTML_TAGS = 'html.tags',
/**
* Tags plugin dispatches or reacts to the following events.
*
* @author agorbatchev
* @date 2011/08/17
* @id TextExtTags.events
*/
/**
* Tags plugin triggers the `isTagAllowed` event before adding each tag to the tag list. Other plugins have
* an opportunity to interrupt this by setting `result` of the second argument to `false`. For example:
*
* $('textarea').textext({...}).bind('isTagAllowed', function(e, data)
* {
* if(data.tag === 'foo')
* data.result = false;
* })
*
* The second argument `data` has the following format: `{ tag : {Object}, result : {Boolean} }`. `tag`
* property is in the format that the current `ItemManager` can understand.
*
* @name isTagAllowed
* @author agorbatchev
* @date 2011/08/19
* @id TextExtTags.events.isTagAllowed
*/
EVENT_IS_TAG_ALLOWED = 'isTagAllowed',
/**
* Tags plugin triggers the `tagClick` event when user clicks on one of the tags. This allows to process
* the click and potentially change the value of the tag (for example in case of user feedback).
*
* $('textarea').textext({...}).bind('tagClick', function(e, tag, value, callback)
* {
* var newValue = window.prompt('New value', value);
* if(newValue)
* callback(newValue, true);
* })
*
* Callback argument has the following signature:
*
* function(newValue, refocus)
* {
* ...
* }
*
* Please check out [example](/manual/examples/tags-changing.html).
*
* @name tagClick
* @version 1.3.0
* @author s.stok
* @date 2011/01/23
* @id TextExtTags.events.tagClick
*/
EVENT_TAG_CLICK = 'tagClick',
DEFAULT_OPTS = {
tags : {
enabled : true,
items : null
},
html : {
tags : '',
tag : '
'
}
}
;
/**
* Initialization method called by the core during plugin instantiation.
*
* @signature TextExtTags.init(core)
*
* @param core {TextExt} Instance of the TextExt core class.
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExtTags.init
*/
p.init = function(core)
{
this.baseInit(core, DEFAULT_OPTS);
var self = this,
input = self.input(),
container
;
if(self.opts(OPT_ENABLED))
{
container = $(self.opts(OPT_HTML_TAGS));
input.after(container);
$(self).data('container', container);
self.on({
enterKeyPress : self.onEnterKeyPress,
backspaceKeyDown : self.onBackspaceKeyDown,
preInvalidate : self.onPreInvalidate,
postInit : self.onPostInit,
getFormData : self.onGetFormData
});
self.on(container, {
click : self.onClick,
mousemove : self.onContainerMouseMove
});
self.on(input, {
mousemove : self.onInputMouseMove
});
}
self._originalPadding = {
left : parseInt(input.css('paddingLeft') || 0),
top : parseInt(input.css('paddingTop') || 0)
};
self._paddingBox = {
left : 0,
top : 0
};
self.updateFormCache();
};
/**
* Returns HTML element in which all tag HTML elements are residing.
*
* @signature TextExtTags.containerElement()
*
* @author agorbatchev
* @date 2011/08/15
* @id TextExtTags.containerElement
*/
p.containerElement = function()
{
return $(this).data('container');
};
//--------------------------------------------------------------------------------
// Event handlers
/**
* Reacts to the `postInit` event triggered by the core and sets default tags
* if any were specified.
*
* @signature TextExtTags.onPostInit(e)
*
* @param e {Object} jQuery event.
*
* @author agorbatchev
* @date 2011/08/09
* @id TextExtTags.onPostInit
*/
p.onPostInit = function(e)
{
var self = this;
self.addTags(self.opts(OPT_ITEMS));
};
/**
* Reacts to the [`getFormData`][1] event triggered by the core. Returns data with the
* weight of 200 to be *greater than the Autocomplete plugin* data weight. The weights
* system is covered in greater detail in the [`getFormData`][1] event documentation.
*
* [1]: /manual/textext.html#getformdata
*
* @signature TextExtTags.onGetFormData(e, data, keyCode)
*
* @param e {Object} jQuery event.
* @param data {Object} Data object to be populated.
* @param keyCode {Number} Key code that triggered the original update request.
*
* @author agorbatchev
* @date 2011/08/22
* @id TextExtTags.onGetFormData
*/
p.onGetFormData = function(e, data, keyCode)
{
var self = this,
inputValue = keyCode === 13 ? '' : self.val(),
formValue = self._formData
;
data[200] = self.formDataObject(inputValue, formValue);
};
/**
* Returns initialization priority of the Tags plugin which is expected to be
* *less than the Autocomplete plugin* because of the dependencies. The value is
* 100.
*
* @signature TextExtTags.initPriority()
*
* @author agorbatchev
* @date 2011/08/22
* @id TextExtTags.initPriority
*/
p.initPriority = function()
{
return 100;
};
/**
* Reacts to user moving mouse over the text area when cursor is over the text
* and not over the tags. Whenever mouse cursor is over the area covered by
* tags, the tags container is flipped to be on top of the text area which
* makes all tags functional with the mouse.
*
* @signature TextExtTags.onInputMouseMove(e)
*
* @param e {Object} jQuery event.
*
* @author agorbatchev
* @date 2011/08/08
* @id TextExtTags.onInputMouseMove
*/
p.onInputMouseMove = function(e)
{
this.toggleZIndex(e);
};
/**
* Reacts to user moving mouse over the tags. Whenever the cursor moves out
* of the tags and back into where the text input is happening visually,
* the tags container is sent back under the text area which allows user
* to interact with the text using mouse cursor as expected.
*
* @signature TextExtTags.onContainerMouseMove(e)
*
* @param e {Object} jQuery event.
*
* @author agorbatchev
* @date 2011/08/08
* @id TextExtTags.onContainerMouseMove
*/
p.onContainerMouseMove = function(e)
{
this.toggleZIndex(e);
};
/**
* Reacts to the `backspaceKeyDown` event. When backspace key is pressed in an empty text field,
* deletes last tag from the list.
*
* @signature TextExtTags.onBackspaceKeyDown(e)
*
* @param e {Object} jQuery event.
*
* @author agorbatchev
* @date 2011/08/02
* @id TextExtTags.onBackspaceKeyDown
*/
p.onBackspaceKeyDown = function(e)
{
var self = this,
lastTag = self.tagElements().last()
;
if(self.val().length == 0)
self.removeTag(lastTag);
};
/**
* Reacts to the `preInvalidate` event and updates the input box to look like the tags are
* positioned inside it.
*
* @signature TextExtTags.onPreInvalidate(e)
*
* @param e {Object} jQuery event.
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExtTags.onPreInvalidate
*/
p.onPreInvalidate = function(e)
{
var self = this,
lastTag = self.tagElements().last(),
pos = lastTag.position()
;
if(lastTag.length > 0)
pos.left += lastTag.innerWidth();
else
pos = self._originalPadding;
self._paddingBox = pos;
self.input().css({
paddingLeft : pos.left,
paddingTop : pos.top
});
};
/**
* Reacts to the mouse `click` event.
*
* @signature TextExtTags.onClick(e)
*
* @param e {Object} jQuery event.
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExtTags.onClick
*/
p.onClick = function(e)
{
var self = this,
core = self.core(),
source = $(e.target),
focus = 0,
tag
;
if(source.is(CSS_DOT_TAGS))
{
focus = 1;
}
else if(source.is(CSS_DOT_REMOVE))
{
self.removeTag(source.parents(CSS_DOT_TAG + ':first'));
focus = 1;
}
else if(source.is(CSS_DOT_LABEL))
{
tag = source.parents(CSS_DOT_TAG + ':first');
self.trigger(EVENT_TAG_CLICK, tag, tag.data(CSS_TAG), tagClickCallback);
}
function tagClickCallback(newValue, refocus)
{
tag.data(CSS_TAG, newValue);
tag.find(CSS_DOT_LABEL).text(self.itemManager().itemToString(newValue));
self.updateFormCache();
core.getFormData();
core.invalidateBounds();
if(refocus)
core.focusInput();
}
if(focus)
core.focusInput();
};
/**
* Reacts to the `enterKeyPress` event and adds whatever is currently in the text input
* as a new tag. Triggers `isTagAllowed` to check if the tag could be added first.
*
* @signature TextExtTags.onEnterKeyPress(e)
*
* @param e {Object} jQuery event.
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExtTags.onEnterKeyPress
*/
p.onEnterKeyPress = function(e)
{
var self = this,
val = self.val(),
tag = self.itemManager().stringToItem(val)
;
if(self.isTagAllowed(tag))
{
self.addTags([ tag ]);
// refocus the textarea just in case it lost the focus
self.core().focusInput();
}
};
//--------------------------------------------------------------------------------
// Core functionality
/**
* Creates a cache object with all the tags currently added which will be returned
* in the `onGetFormData` handler.
*
* @signature TextExtTags.updateFormCache()
*
* @author agorbatchev
* @date 2011/08/09
* @id TextExtTags.updateFormCache
*/
p.updateFormCache = function()
{
var self = this,
result = []
;
self.tagElements().each(function()
{
result.push($(this).data(CSS_TAG));
});
// cache the results to be used in the onGetFormData
self._formData = result;
};
/**
* Toggles tag container to be on top of the text area or under based on where
* the mouse cursor is located. When cursor is above the text input and out of
* any of the tags, the tags container is sent under the text area. If cursor
* is over any of the tags, the tag container is brought to be over the text
* area.
*
* @signature TextExtTags.toggleZIndex(e)
*
* @param e {Object} jQuery event.
*
* @author agorbatchev
* @date 2011/08/08
* @id TextExtTags.toggleZIndex
*/
p.toggleZIndex = function(e)
{
var self = this,
offset = self.input().offset(),
mouseX = e.clientX - offset.left,
mouseY = e.clientY - offset.top,
box = self._paddingBox,
container = self.containerElement(),
isOnTop = container.is(CSS_DOT_TAGS_ON_TOP),
isMouseOverText = mouseX > box.left && mouseY > box.top
;
if(!isOnTop && !isMouseOverText || isOnTop && isMouseOverText)
container[(!isOnTop ? 'add' : 'remove') + 'Class'](CSS_TAGS_ON_TOP);
};
/**
* Returns all tag HTML elements.
*
* @signature TextExtTags.tagElements()
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExtTags.tagElements
*/
p.tagElements = function()
{
return this.containerElement().find(CSS_DOT_TAG);
};
/**
* Wrapper around the `isTagAllowed` event which triggers it and returns `true`
* if `result` property of the second argument remains `true`.
*
* @signature TextExtTags.isTagAllowed(tag)
*
* @param tag {Object} Tag object that the current `ItemManager` can understand.
* Default is `String`.
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExtTags.isTagAllowed
*/
p.isTagAllowed = function(tag)
{
var opts = { tag : tag, result : true };
this.trigger(EVENT_IS_TAG_ALLOWED, opts);
return opts.result === true;
};
/**
* Adds specified tags to the tag list. Triggers `isTagAllowed` event for each tag
* to insure that it could be added. Calls `TextExt.getFormData()` to refresh the data.
*
* @signature TextExtTags.addTags(tags)
*
* @param tags {Array} List of tags that current `ItemManager` can understand. Default
* is `String`.
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExtTags.addTags
*/
p.addTags = function(tags)
{
if(!tags || tags.length == 0)
return;
var self = this,
core = self.core(),
container = self.containerElement(),
i, tag
;
for(i = 0; i < tags.length; i++)
{
tag = tags[i];
if(tag && self.isTagAllowed(tag))
container.append(self.renderTag(tag));
}
self.updateFormCache();
core.getFormData();
core.invalidateBounds();
};
/**
* Returns HTML element for the specified tag.
*
* @signature TextExtTags.getTagElement(tag)
*
* @param tag {Object} Tag object in the format that current `ItemManager` can understand.
* Default is `String`.
* @author agorbatchev
* @date 2011/08/19
* @id TextExtTags.getTagElement
*/
p.getTagElement = function(tag)
{
var self = this,
list = self.tagElements(),
i, item
;
for(i = 0; i < list.length; i++) {
item = $(list[i]);
if(self.itemManager().compareItems(item.data(CSS_TAG), tag))
return item;
}
return null;
};
/**
* Removes specified tag from the list. Calls `TextExt.getFormData()` to refresh the data.
*
* @signature TextExtTags.removeTag(tag)
*
* @param tag {Object} Tag object in the format that current `ItemManager` can understand.
* Default is `String`.
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExtTags.removeTag
*/
p.removeTag = function(tag)
{
var self = this,
core = self.core(),
element
;
if(tag instanceof $)
{
element = tag;
tag = tag.data(CSS_TAG);
}
else
{
element = self.getTagElement(tag);
if (element === null) {
//Tag does not exist
return;
}
}
element.remove();
self.updateFormCache();
core.getFormData();
core.invalidateBounds();
};
/**
* Creates and returns new HTML element from the source code specified in the `html.tag` option.
*
* @signature TextExtTags.renderTag(tag)
*
* @param tag {Object} Tag object in the format that current `ItemManager` can understand.
* Default is `String`.
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExtTags.renderTag
*/
p.renderTag = function(tag)
{
var self = this,
node = $(self.opts(OPT_HTML_TAG))
;
node.find('.text-label').text(self.itemManager().itemToString(tag));
node.data(CSS_TAG, tag);
return node;
};
})(jQuery);
================================================
FILE: public/adminlte/js/timepicker.js
================================================
/*! jQuery Timepicker Addon - v1.6.1 - 2015-11-14
* http://trentrichardson.com/examples/timepicker
* Copyright (c) 2015 Trent Richardson; Licensed MIT */
(function (factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery', 'jquery-ui'], factory);
} else {
factory(jQuery);
}
}(function ($) {
/*
* Lets not redefine timepicker, Prevent "Uncaught RangeError: Maximum call stack size exceeded"
*/
$.ui.timepicker = $.ui.timepicker || {};
if ($.ui.timepicker.version) {
return;
}
/*
* Extend jQueryUI, get it started with our version number
*/
$.extend($.ui, {
timepicker: {
version: "1.6.1"
}
});
/*
* Timepicker manager.
* Use the singleton instance of this class, $.timepicker, to interact with the time picker.
* Settings for (groups of) time pickers are maintained in an instance object,
* allowing multiple different settings on the same page.
*/
var Timepicker = function () {
this.regional = []; // Available regional settings, indexed by language code
this.regional[''] = { // Default regional settings
currentText: 'Now',
closeText: 'Done',
amNames: ['AM', 'A'],
pmNames: ['PM', 'P'],
timeFormat: 'HH:mm',
timeSuffix: '',
timeOnlyTitle: 'Choose Time',
timeText: 'Time',
hourText: 'Hour',
minuteText: 'Minute',
secondText: 'Second',
millisecText: 'Millisecond',
microsecText: 'Microsecond',
timezoneText: 'Time Zone',
isRTL: false
};
this._defaults = { // Global defaults for all the datetime picker instances
showButtonPanel: true,
timeOnly: false,
timeOnlyShowDate: false,
showHour: null,
showMinute: null,
showSecond: null,
showMillisec: null,
showMicrosec: null,
showTimezone: null,
showTime: true,
stepHour: 1,
stepMinute: 1,
stepSecond: 1,
stepMillisec: 1,
stepMicrosec: 1,
hour: 0,
minute: 0,
second: 0,
millisec: 0,
microsec: 0,
timezone: null,
hourMin: 0,
minuteMin: 0,
secondMin: 0,
millisecMin: 0,
microsecMin: 0,
hourMax: 23,
minuteMax: 59,
secondMax: 59,
millisecMax: 999,
microsecMax: 999,
minDateTime: null,
maxDateTime: null,
maxTime: null,
minTime: null,
onSelect: null,
hourGrid: 0,
minuteGrid: 0,
secondGrid: 0,
millisecGrid: 0,
microsecGrid: 0,
alwaysSetTime: true,
separator: ' ',
altFieldTimeOnly: true,
altTimeFormat: null,
altSeparator: null,
altTimeSuffix: null,
altRedirectFocus: true,
pickerTimeFormat: null,
pickerTimeSuffix: null,
showTimepicker: true,
timezoneList: null,
addSliderAccess: false,
sliderAccessArgs: null,
controlType: 'slider',
oneLine: false,
defaultValue: null,
parse: 'strict',
afterInject: null
};
$.extend(this._defaults, this.regional['']);
};
$.extend(Timepicker.prototype, {
$input: null,
$altInput: null,
$timeObj: null,
inst: null,
hour_slider: null,
minute_slider: null,
second_slider: null,
millisec_slider: null,
microsec_slider: null,
timezone_select: null,
maxTime: null,
minTime: null,
hour: 0,
minute: 0,
second: 0,
millisec: 0,
microsec: 0,
timezone: null,
hourMinOriginal: null,
minuteMinOriginal: null,
secondMinOriginal: null,
millisecMinOriginal: null,
microsecMinOriginal: null,
hourMaxOriginal: null,
minuteMaxOriginal: null,
secondMaxOriginal: null,
millisecMaxOriginal: null,
microsecMaxOriginal: null,
ampm: '',
formattedDate: '',
formattedTime: '',
formattedDateTime: '',
timezoneList: null,
units: ['hour', 'minute', 'second', 'millisec', 'microsec'],
support: {},
control: null,
/*
* Override the default settings for all instances of the time picker.
* @param {Object} settings object - the new settings to use as defaults (anonymous object)
* @return {Object} the manager object
*/
setDefaults: function (settings) {
extendRemove(this._defaults, settings || {});
return this;
},
/*
* Create a new Timepicker instance
*/
_newInst: function ($input, opts) {
var tp_inst = new Timepicker(),
inlineSettings = {},
fns = {},
overrides, i;
for (var attrName in this._defaults) {
if (this._defaults.hasOwnProperty(attrName)) {
var attrValue = $input.attr('time:' + attrName);
if (attrValue) {
try {
inlineSettings[attrName] = eval(attrValue);
} catch (err) {
inlineSettings[attrName] = attrValue;
}
}
}
}
overrides = {
beforeShow: function (input, dp_inst) {
if ($.isFunction(tp_inst._defaults.evnts.beforeShow)) {
return tp_inst._defaults.evnts.beforeShow.call($input[0], input, dp_inst, tp_inst);
}
},
onChangeMonthYear: function (year, month, dp_inst) {
// Update the time as well : this prevents the time from disappearing from the $input field.
// tp_inst._updateDateTime(dp_inst);
if ($.isFunction(tp_inst._defaults.evnts.onChangeMonthYear)) {
tp_inst._defaults.evnts.onChangeMonthYear.call($input[0], year, month, dp_inst, tp_inst);
}
},
onClose: function (dateText, dp_inst) {
if (tp_inst.timeDefined === true && $input.val() !== '') {
tp_inst._updateDateTime(dp_inst);
}
if ($.isFunction(tp_inst._defaults.evnts.onClose)) {
tp_inst._defaults.evnts.onClose.call($input[0], dateText, dp_inst, tp_inst);
}
}
};
for (i in overrides) {
if (overrides.hasOwnProperty(i)) {
fns[i] = opts[i] || this._defaults[i] || null;
}
}
tp_inst._defaults = $.extend({}, this._defaults, inlineSettings, opts, overrides, {
evnts: fns,
timepicker: tp_inst // add timepicker as a property of datepicker: $.datepicker._get(dp_inst, 'timepicker');
});
tp_inst.amNames = $.map(tp_inst._defaults.amNames, function (val) {
return val.toUpperCase();
});
tp_inst.pmNames = $.map(tp_inst._defaults.pmNames, function (val) {
return val.toUpperCase();
});
// detect which units are supported
tp_inst.support = detectSupport(
tp_inst._defaults.timeFormat +
(tp_inst._defaults.pickerTimeFormat ? tp_inst._defaults.pickerTimeFormat : '') +
(tp_inst._defaults.altTimeFormat ? tp_inst._defaults.altTimeFormat : ''));
// controlType is string - key to our this._controls
if (typeof(tp_inst._defaults.controlType) === 'string') {
if (tp_inst._defaults.controlType === 'slider' && typeof($.ui.slider) === 'undefined') {
tp_inst._defaults.controlType = 'select';
}
tp_inst.control = tp_inst._controls[tp_inst._defaults.controlType];
}
// controlType is an object and must implement create, options, value methods
else {
tp_inst.control = tp_inst._defaults.controlType;
}
// prep the timezone options
var timezoneList = [-720, -660, -600, -570, -540, -480, -420, -360, -300, -270, -240, -210, -180, -120, -60,
0, 60, 120, 180, 210, 240, 270, 300, 330, 345, 360, 390, 420, 480, 525, 540, 570, 600, 630, 660, 690, 720, 765, 780, 840];
if (tp_inst._defaults.timezoneList !== null) {
timezoneList = tp_inst._defaults.timezoneList;
}
var tzl = timezoneList.length, tzi = 0, tzv = null;
if (tzl > 0 && typeof timezoneList[0] !== 'object') {
for (; tzi < tzl; tzi++) {
tzv = timezoneList[tzi];
timezoneList[tzi] = { value: tzv, label: $.timepicker.timezoneOffsetString(tzv, tp_inst.support.iso8601) };
}
}
tp_inst._defaults.timezoneList = timezoneList;
// set the default units
tp_inst.timezone = tp_inst._defaults.timezone !== null ? $.timepicker.timezoneOffsetNumber(tp_inst._defaults.timezone) :
((new Date()).getTimezoneOffset() * -1);
tp_inst.hour = tp_inst._defaults.hour < tp_inst._defaults.hourMin ? tp_inst._defaults.hourMin :
tp_inst._defaults.hour > tp_inst._defaults.hourMax ? tp_inst._defaults.hourMax : tp_inst._defaults.hour;
tp_inst.minute = tp_inst._defaults.minute < tp_inst._defaults.minuteMin ? tp_inst._defaults.minuteMin :
tp_inst._defaults.minute > tp_inst._defaults.minuteMax ? tp_inst._defaults.minuteMax : tp_inst._defaults.minute;
tp_inst.second = tp_inst._defaults.second < tp_inst._defaults.secondMin ? tp_inst._defaults.secondMin :
tp_inst._defaults.second > tp_inst._defaults.secondMax ? tp_inst._defaults.secondMax : tp_inst._defaults.second;
tp_inst.millisec = tp_inst._defaults.millisec < tp_inst._defaults.millisecMin ? tp_inst._defaults.millisecMin :
tp_inst._defaults.millisec > tp_inst._defaults.millisecMax ? tp_inst._defaults.millisecMax : tp_inst._defaults.millisec;
tp_inst.microsec = tp_inst._defaults.microsec < tp_inst._defaults.microsecMin ? tp_inst._defaults.microsecMin :
tp_inst._defaults.microsec > tp_inst._defaults.microsecMax ? tp_inst._defaults.microsecMax : tp_inst._defaults.microsec;
tp_inst.ampm = '';
tp_inst.$input = $input;
if (tp_inst._defaults.altField) {
tp_inst.$altInput = $(tp_inst._defaults.altField);
if (tp_inst._defaults.altRedirectFocus === true) {
tp_inst.$altInput.css({
cursor: 'pointer'
}).focus(function () {
$input.trigger("focus");
});
}
}
if (tp_inst._defaults.minDate === 0 || tp_inst._defaults.minDateTime === 0) {
tp_inst._defaults.minDate = new Date();
}
if (tp_inst._defaults.maxDate === 0 || tp_inst._defaults.maxDateTime === 0) {
tp_inst._defaults.maxDate = new Date();
}
// datepicker needs minDate/maxDate, timepicker needs minDateTime/maxDateTime..
if (tp_inst._defaults.minDate !== undefined && tp_inst._defaults.minDate instanceof Date) {
tp_inst._defaults.minDateTime = new Date(tp_inst._defaults.minDate.getTime());
}
if (tp_inst._defaults.minDateTime !== undefined && tp_inst._defaults.minDateTime instanceof Date) {
tp_inst._defaults.minDate = new Date(tp_inst._defaults.minDateTime.getTime());
}
if (tp_inst._defaults.maxDate !== undefined && tp_inst._defaults.maxDate instanceof Date) {
tp_inst._defaults.maxDateTime = new Date(tp_inst._defaults.maxDate.getTime());
}
if (tp_inst._defaults.maxDateTime !== undefined && tp_inst._defaults.maxDateTime instanceof Date) {
tp_inst._defaults.maxDate = new Date(tp_inst._defaults.maxDateTime.getTime());
}
tp_inst.$input.bind('focus', function () {
tp_inst._onFocus();
});
return tp_inst;
},
/*
* add our sliders to the calendar
*/
_addTimePicker: function (dp_inst) {
var currDT = $.trim((this.$altInput && this._defaults.altFieldTimeOnly) ? this.$input.val() + ' ' + this.$altInput.val() : this.$input.val());
this.timeDefined = this._parseTime(currDT);
this._limitMinMaxDateTime(dp_inst, false);
this._injectTimePicker();
this._afterInject();
},
/*
* parse the time string from input value or _setTime
*/
_parseTime: function (timeString, withDate) {
if (!this.inst) {
this.inst = $.datepicker._getInst(this.$input[0]);
}
if (withDate || !this._defaults.timeOnly) {
var dp_dateFormat = $.datepicker._get(this.inst, 'dateFormat');
try {
var parseRes = parseDateTimeInternal(dp_dateFormat, this._defaults.timeFormat, timeString, $.datepicker._getFormatConfig(this.inst), this._defaults);
if (!parseRes.timeObj) {
return false;
}
$.extend(this, parseRes.timeObj);
} catch (err) {
$.timepicker.log("Error parsing the date/time string: " + err +
"\ndate/time string = " + timeString +
"\ntimeFormat = " + this._defaults.timeFormat +
"\ndateFormat = " + dp_dateFormat);
return false;
}
return true;
} else {
var timeObj = $.datepicker.parseTime(this._defaults.timeFormat, timeString, this._defaults);
if (!timeObj) {
return false;
}
$.extend(this, timeObj);
return true;
}
},
/*
* Handle callback option after injecting timepicker
*/
_afterInject: function() {
var o = this.inst.settings;
if ($.isFunction(o.afterInject)) {
o.afterInject.call(this);
}
},
/*
* generate and inject html for timepicker into ui datepicker
*/
_injectTimePicker: function () {
var $dp = this.inst.dpDiv,
o = this.inst.settings,
tp_inst = this,
litem = '',
uitem = '',
show = null,
max = {},
gridSize = {},
size = null,
i = 0,
l = 0;
// Prevent displaying twice
if ($dp.find("div.ui-timepicker-div").length === 0 && o.showTimepicker) {
var noDisplay = ' ui_tpicker_unit_hide',
html = '
' + '
' + o.timeText + '
' +
'';
// Create the markup
for (i = 0, l = this.units.length; i < l; i++) {
litem = this.units[i];
uitem = litem.substr(0, 1).toUpperCase() + litem.substr(1);
show = o['show' + uitem] !== null ? o['show' + uitem] : this.support[litem];
// Added by Peter Medeiros:
// - Figure out what the hour/minute/second max should be based on the step values.
// - Example: if stepMinute is 15, then minMax is 45.
max[litem] = parseInt((o[litem + 'Max'] - ((o[litem + 'Max'] - o[litem + 'Min']) % o['step' + uitem])), 10);
gridSize[litem] = 0;
html += '
' + o[litem + 'Text'] + '
' +
'
';
if (show && o[litem + 'Grid'] > 0) {
html += '
';
if (litem === 'hour') {
for (var h = o[litem + 'Min']; h <= max[litem]; h += parseInt(o[litem + 'Grid'], 10)) {
gridSize[litem]++;
var tmph = $.datepicker.formatTime(this.support.ampm ? 'hht' : 'HH', {hour: h}, o);
html += '
' + tmph + '
';
}
}
else {
for (var m = o[litem + 'Min']; m <= max[litem]; m += parseInt(o[litem + 'Grid'], 10)) {
gridSize[litem]++;
html += '
' + ((m < 10) ? '0' : '') + m + '
';
}
}
html += '
';
}
html += '
';
}
// Timezone
var showTz = o.showTimezone !== null ? o.showTimezone : this.support.timezone;
html += '
' + o.timezoneText + '
';
html += '';
// Create the elements from string
html += '
';
var $tp = $(html);
// if we only want time picker...
if (o.timeOnly === true) {
$tp.prepend('
' + '
' + o.timeOnlyTitle + '
' + '
');
$dp.find('.ui-datepicker-header, .ui-datepicker-calendar').hide();
}
// add sliders, adjust grids, add events
for (i = 0, l = tp_inst.units.length; i < l; i++) {
litem = tp_inst.units[i];
uitem = litem.substr(0, 1).toUpperCase() + litem.substr(1);
show = o['show' + uitem] !== null ? o['show' + uitem] : this.support[litem];
// add the slider
tp_inst[litem + '_slider'] = tp_inst.control.create(tp_inst, $tp.find('.ui_tpicker_' + litem + '_slider'), litem, tp_inst[litem], o[litem + 'Min'], max[litem], o['step' + uitem]);
// adjust the grid and add click event
if (show && o[litem + 'Grid'] > 0) {
size = 100 * gridSize[litem] * o[litem + 'Grid'] / (max[litem] - o[litem + 'Min']);
$tp.find('.ui_tpicker_' + litem + ' table').css({
width: size + "%",
marginLeft: o.isRTL ? '0' : ((size / (-2 * gridSize[litem])) + "%"),
marginRight: o.isRTL ? ((size / (-2 * gridSize[litem])) + "%") : '0',
borderCollapse: 'collapse'
}).find("td").click(function (e) {
var $t = $(this),
h = $t.html(),
n = parseInt(h.replace(/[^0-9]/g), 10),
ap = h.replace(/[^apm]/ig),
f = $t.data('for'); // loses scope, so we use data-for
if (f === 'hour') {
if (ap.indexOf('p') !== -1 && n < 12) {
n += 12;
}
else {
if (ap.indexOf('a') !== -1 && n === 12) {
n = 0;
}
}
}
tp_inst.control.value(tp_inst, tp_inst[f + '_slider'], litem, n);
tp_inst._onTimeChange();
tp_inst._onSelectHandler();
}).css({
cursor: 'pointer',
width: (100 / gridSize[litem]) + '%',
textAlign: 'center',
overflow: 'hidden'
});
} // end if grid > 0
} // end for loop
// Add timezone options
this.timezone_select = $tp.find('.ui_tpicker_timezone').append('').find("select");
$.fn.append.apply(this.timezone_select,
$.map(o.timezoneList, function (val, idx) {
return $("").val(typeof val === "object" ? val.value : val).text(typeof val === "object" ? val.label : val);
}));
if (typeof(this.timezone) !== "undefined" && this.timezone !== null && this.timezone !== "") {
var local_timezone = (new Date(this.inst.selectedYear, this.inst.selectedMonth, this.inst.selectedDay, 12)).getTimezoneOffset() * -1;
if (local_timezone === this.timezone) {
selectLocalTimezone(tp_inst);
} else {
this.timezone_select.val(this.timezone);
}
} else {
if (typeof(this.hour) !== "undefined" && this.hour !== null && this.hour !== "") {
this.timezone_select.val(o.timezone);
} else {
selectLocalTimezone(tp_inst);
}
}
this.timezone_select.change(function () {
tp_inst._onTimeChange();
tp_inst._onSelectHandler();
tp_inst._afterInject();
});
// End timezone options
// inject timepicker into datepicker
var $buttonPanel = $dp.find('.ui-datepicker-buttonpane');
if ($buttonPanel.length) {
$buttonPanel.before($tp);
} else {
$dp.append($tp);
}
this.$timeObj = $tp.find('.ui_tpicker_time_input');
this.$timeObj.change(function () {
var timeFormat = tp_inst.inst.settings.timeFormat;
var parsedTime = $.datepicker.parseTime(timeFormat, this.value);
var update = new Date();
if (parsedTime) {
update.setHours(parsedTime.hour);
update.setMinutes(parsedTime.minute);
update.setSeconds(parsedTime.second);
$.datepicker._setTime(tp_inst.inst, update);
} else {
this.value = tp_inst.formattedTime;
this.blur();
}
});
if (this.inst !== null) {
var timeDefined = this.timeDefined;
this._onTimeChange();
this.timeDefined = timeDefined;
}
// slideAccess integration: http://trentrichardson.com/2011/11/11/jquery-ui-sliders-and-touch-accessibility/
if (this._defaults.addSliderAccess) {
var sliderAccessArgs = this._defaults.sliderAccessArgs,
rtl = this._defaults.isRTL;
sliderAccessArgs.isRTL = rtl;
setTimeout(function () { // fix for inline mode
if ($tp.find('.ui-slider-access').length === 0) {
$tp.find('.ui-slider:visible').sliderAccess(sliderAccessArgs);
// fix any grids since sliders are shorter
var sliderAccessWidth = $tp.find('.ui-slider-access:eq(0)').outerWidth(true);
if (sliderAccessWidth) {
$tp.find('table:visible').each(function () {
var $g = $(this),
oldWidth = $g.outerWidth(),
oldMarginLeft = $g.css(rtl ? 'marginRight' : 'marginLeft').toString().replace('%', ''),
newWidth = oldWidth - sliderAccessWidth,
newMarginLeft = ((oldMarginLeft * newWidth) / oldWidth) + '%',
css = { width: newWidth, marginRight: 0, marginLeft: 0 };
css[rtl ? 'marginRight' : 'marginLeft'] = newMarginLeft;
$g.css(css);
});
}
}
}, 10);
}
// end slideAccess integration
tp_inst._limitMinMaxDateTime(this.inst, true);
}
},
/*
* This function tries to limit the ability to go outside the
* min/max date range
*/
_limitMinMaxDateTime: function (dp_inst, adjustSliders) {
var o = this._defaults,
dp_date = new Date(dp_inst.selectedYear, dp_inst.selectedMonth, dp_inst.selectedDay);
if (!this._defaults.showTimepicker) {
return;
} // No time so nothing to check here
if ($.datepicker._get(dp_inst, 'minDateTime') !== null && $.datepicker._get(dp_inst, 'minDateTime') !== undefined && dp_date) {
var minDateTime = $.datepicker._get(dp_inst, 'minDateTime'),
minDateTimeDate = new Date(minDateTime.getFullYear(), minDateTime.getMonth(), minDateTime.getDate(), 0, 0, 0, 0);
if (this.hourMinOriginal === null || this.minuteMinOriginal === null || this.secondMinOriginal === null || this.millisecMinOriginal === null || this.microsecMinOriginal === null) {
this.hourMinOriginal = o.hourMin;
this.minuteMinOriginal = o.minuteMin;
this.secondMinOriginal = o.secondMin;
this.millisecMinOriginal = o.millisecMin;
this.microsecMinOriginal = o.microsecMin;
}
if (dp_inst.settings.timeOnly || minDateTimeDate.getTime() === dp_date.getTime()) {
this._defaults.hourMin = minDateTime.getHours();
if (this.hour <= this._defaults.hourMin) {
this.hour = this._defaults.hourMin;
this._defaults.minuteMin = minDateTime.getMinutes();
if (this.minute <= this._defaults.minuteMin) {
this.minute = this._defaults.minuteMin;
this._defaults.secondMin = minDateTime.getSeconds();
if (this.second <= this._defaults.secondMin) {
this.second = this._defaults.secondMin;
this._defaults.millisecMin = minDateTime.getMilliseconds();
if (this.millisec <= this._defaults.millisecMin) {
this.millisec = this._defaults.millisecMin;
this._defaults.microsecMin = minDateTime.getMicroseconds();
} else {
if (this.microsec < this._defaults.microsecMin) {
this.microsec = this._defaults.microsecMin;
}
this._defaults.microsecMin = this.microsecMinOriginal;
}
} else {
this._defaults.millisecMin = this.millisecMinOriginal;
this._defaults.microsecMin = this.microsecMinOriginal;
}
} else {
this._defaults.secondMin = this.secondMinOriginal;
this._defaults.millisecMin = this.millisecMinOriginal;
this._defaults.microsecMin = this.microsecMinOriginal;
}
} else {
this._defaults.minuteMin = this.minuteMinOriginal;
this._defaults.secondMin = this.secondMinOriginal;
this._defaults.millisecMin = this.millisecMinOriginal;
this._defaults.microsecMin = this.microsecMinOriginal;
}
} else {
this._defaults.hourMin = this.hourMinOriginal;
this._defaults.minuteMin = this.minuteMinOriginal;
this._defaults.secondMin = this.secondMinOriginal;
this._defaults.millisecMin = this.millisecMinOriginal;
this._defaults.microsecMin = this.microsecMinOriginal;
}
}
if ($.datepicker._get(dp_inst, 'maxDateTime') !== null && $.datepicker._get(dp_inst, 'maxDateTime') !== undefined && dp_date) {
var maxDateTime = $.datepicker._get(dp_inst, 'maxDateTime'),
maxDateTimeDate = new Date(maxDateTime.getFullYear(), maxDateTime.getMonth(), maxDateTime.getDate(), 0, 0, 0, 0);
if (this.hourMaxOriginal === null || this.minuteMaxOriginal === null || this.secondMaxOriginal === null || this.millisecMaxOriginal === null) {
this.hourMaxOriginal = o.hourMax;
this.minuteMaxOriginal = o.minuteMax;
this.secondMaxOriginal = o.secondMax;
this.millisecMaxOriginal = o.millisecMax;
this.microsecMaxOriginal = o.microsecMax;
}
if (dp_inst.settings.timeOnly || maxDateTimeDate.getTime() === dp_date.getTime()) {
this._defaults.hourMax = maxDateTime.getHours();
if (this.hour >= this._defaults.hourMax) {
this.hour = this._defaults.hourMax;
this._defaults.minuteMax = maxDateTime.getMinutes();
if (this.minute >= this._defaults.minuteMax) {
this.minute = this._defaults.minuteMax;
this._defaults.secondMax = maxDateTime.getSeconds();
if (this.second >= this._defaults.secondMax) {
this.second = this._defaults.secondMax;
this._defaults.millisecMax = maxDateTime.getMilliseconds();
if (this.millisec >= this._defaults.millisecMax) {
this.millisec = this._defaults.millisecMax;
this._defaults.microsecMax = maxDateTime.getMicroseconds();
} else {
if (this.microsec > this._defaults.microsecMax) {
this.microsec = this._defaults.microsecMax;
}
this._defaults.microsecMax = this.microsecMaxOriginal;
}
} else {
this._defaults.millisecMax = this.millisecMaxOriginal;
this._defaults.microsecMax = this.microsecMaxOriginal;
}
} else {
this._defaults.secondMax = this.secondMaxOriginal;
this._defaults.millisecMax = this.millisecMaxOriginal;
this._defaults.microsecMax = this.microsecMaxOriginal;
}
} else {
this._defaults.minuteMax = this.minuteMaxOriginal;
this._defaults.secondMax = this.secondMaxOriginal;
this._defaults.millisecMax = this.millisecMaxOriginal;
this._defaults.microsecMax = this.microsecMaxOriginal;
}
} else {
this._defaults.hourMax = this.hourMaxOriginal;
this._defaults.minuteMax = this.minuteMaxOriginal;
this._defaults.secondMax = this.secondMaxOriginal;
this._defaults.millisecMax = this.millisecMaxOriginal;
this._defaults.microsecMax = this.microsecMaxOriginal;
}
}
if (dp_inst.settings.minTime!==null) {
var tempMinTime=new Date("01/01/1970 " + dp_inst.settings.minTime);
if (this.hourtempMaxTime.getHours()) {
this.hour=this._defaults.hourMax=tempMaxTime.getHours();
this.minute=this._defaults.minuteMax=tempMaxTime.getMinutes();
} else if (this.hour===tempMaxTime.getHours() && this.minute>tempMaxTime.getMinutes()) {
this.minute=this._defaults.minuteMax=tempMaxTime.getMinutes();
} else {
if (this._defaults.hourMax>tempMaxTime.getHours()) {
this._defaults.hourMax=tempMaxTime.getHours();
this._defaults.minuteMax=tempMaxTime.getMinutes();
} else if (this._defaults.hourMax===tempMaxTime.getHours()===this.hour && this._defaults.minuteMax>tempMaxTime.getMinutes()) {
this._defaults.minuteMax=tempMaxTime.getMinutes();
} else {
this._defaults.minuteMax=59;
}
}
}
if (adjustSliders !== undefined && adjustSliders === true) {
var hourMax = parseInt((this._defaults.hourMax - ((this._defaults.hourMax - this._defaults.hourMin) % this._defaults.stepHour)), 10),
minMax = parseInt((this._defaults.minuteMax - ((this._defaults.minuteMax - this._defaults.minuteMin) % this._defaults.stepMinute)), 10),
secMax = parseInt((this._defaults.secondMax - ((this._defaults.secondMax - this._defaults.secondMin) % this._defaults.stepSecond)), 10),
millisecMax = parseInt((this._defaults.millisecMax - ((this._defaults.millisecMax - this._defaults.millisecMin) % this._defaults.stepMillisec)), 10),
microsecMax = parseInt((this._defaults.microsecMax - ((this._defaults.microsecMax - this._defaults.microsecMin) % this._defaults.stepMicrosec)), 10);
if (this.hour_slider) {
this.control.options(this, this.hour_slider, 'hour', { min: this._defaults.hourMin, max: hourMax, step: this._defaults.stepHour });
this.control.value(this, this.hour_slider, 'hour', this.hour - (this.hour % this._defaults.stepHour));
}
if (this.minute_slider) {
this.control.options(this, this.minute_slider, 'minute', { min: this._defaults.minuteMin, max: minMax, step: this._defaults.stepMinute });
this.control.value(this, this.minute_slider, 'minute', this.minute - (this.minute % this._defaults.stepMinute));
}
if (this.second_slider) {
this.control.options(this, this.second_slider, 'second', { min: this._defaults.secondMin, max: secMax, step: this._defaults.stepSecond });
this.control.value(this, this.second_slider, 'second', this.second - (this.second % this._defaults.stepSecond));
}
if (this.millisec_slider) {
this.control.options(this, this.millisec_slider, 'millisec', { min: this._defaults.millisecMin, max: millisecMax, step: this._defaults.stepMillisec });
this.control.value(this, this.millisec_slider, 'millisec', this.millisec - (this.millisec % this._defaults.stepMillisec));
}
if (this.microsec_slider) {
this.control.options(this, this.microsec_slider, 'microsec', { min: this._defaults.microsecMin, max: microsecMax, step: this._defaults.stepMicrosec });
this.control.value(this, this.microsec_slider, 'microsec', this.microsec - (this.microsec % this._defaults.stepMicrosec));
}
}
},
/*
* when a slider moves, set the internal time...
* on time change is also called when the time is updated in the text field
*/
_onTimeChange: function () {
if (!this._defaults.showTimepicker) {
return;
}
var hour = (this.hour_slider) ? this.control.value(this, this.hour_slider, 'hour') : false,
minute = (this.minute_slider) ? this.control.value(this, this.minute_slider, 'minute') : false,
second = (this.second_slider) ? this.control.value(this, this.second_slider, 'second') : false,
millisec = (this.millisec_slider) ? this.control.value(this, this.millisec_slider, 'millisec') : false,
microsec = (this.microsec_slider) ? this.control.value(this, this.microsec_slider, 'microsec') : false,
timezone = (this.timezone_select) ? this.timezone_select.val() : false,
o = this._defaults,
pickerTimeFormat = o.pickerTimeFormat || o.timeFormat,
pickerTimeSuffix = o.pickerTimeSuffix || o.timeSuffix;
if (typeof(hour) === 'object') {
hour = false;
}
if (typeof(minute) === 'object') {
minute = false;
}
if (typeof(second) === 'object') {
second = false;
}
if (typeof(millisec) === 'object') {
millisec = false;
}
if (typeof(microsec) === 'object') {
microsec = false;
}
if (typeof(timezone) === 'object') {
timezone = false;
}
if (hour !== false) {
hour = parseInt(hour, 10);
}
if (minute !== false) {
minute = parseInt(minute, 10);
}
if (second !== false) {
second = parseInt(second, 10);
}
if (millisec !== false) {
millisec = parseInt(millisec, 10);
}
if (microsec !== false) {
microsec = parseInt(microsec, 10);
}
if (timezone !== false) {
timezone = timezone.toString();
}
var ampm = o[hour < 12 ? 'amNames' : 'pmNames'][0];
// If the update was done in the input field, the input field should not be updated.
// If the update was done using the sliders, update the input field.
var hasChanged = (
hour !== parseInt(this.hour,10) || // sliders should all be numeric
minute !== parseInt(this.minute,10) ||
second !== parseInt(this.second,10) ||
millisec !== parseInt(this.millisec,10) ||
microsec !== parseInt(this.microsec,10) ||
(this.ampm.length > 0 && (hour < 12) !== ($.inArray(this.ampm.toUpperCase(), this.amNames) !== -1)) ||
(this.timezone !== null && timezone !== this.timezone.toString()) // could be numeric or "EST" format, so use toString()
);
if (hasChanged) {
if (hour !== false) {
this.hour = hour;
}
if (minute !== false) {
this.minute = minute;
}
if (second !== false) {
this.second = second;
}
if (millisec !== false) {
this.millisec = millisec;
}
if (microsec !== false) {
this.microsec = microsec;
}
if (timezone !== false) {
this.timezone = timezone;
}
if (!this.inst) {
this.inst = $.datepicker._getInst(this.$input[0]);
}
this._limitMinMaxDateTime(this.inst, true);
}
if (this.support.ampm) {
this.ampm = ampm;
}
// Updates the time within the timepicker
this.formattedTime = $.datepicker.formatTime(o.timeFormat, this, o);
if (this.$timeObj) {
var sPos = this.$timeObj[0].selectionStart;
var ePos = this.$timeObj[0].selectionEnd;
if (pickerTimeFormat === o.timeFormat) {
this.$timeObj.val(this.formattedTime + pickerTimeSuffix);
}
else {
this.$timeObj.val($.datepicker.formatTime(pickerTimeFormat, this, o) + pickerTimeSuffix);
}
this.$timeObj[0].setSelectionRange(sPos, ePos);
}
this.timeDefined = true;
if (hasChanged) {
this._updateDateTime();
//this.$input.focus(); // may automatically open the picker on setDate
}
},
/*
* call custom onSelect.
* bind to sliders slidestop, and grid click.
*/
_onSelectHandler: function () {
var onSelect = this._defaults.onSelect || this.inst.settings.onSelect;
var inputEl = this.$input ? this.$input[0] : null;
if (onSelect && inputEl) {
onSelect.apply(inputEl, [this.formattedDateTime, this]);
}
},
/*
* update our input with the new date time..
*/
_updateDateTime: function (dp_inst) {
dp_inst = this.inst || dp_inst;
var dtTmp = (dp_inst.currentYear > 0?
new Date(dp_inst.currentYear, dp_inst.currentMonth, dp_inst.currentDay) :
new Date(dp_inst.selectedYear, dp_inst.selectedMonth, dp_inst.selectedDay)),
dt = $.datepicker._daylightSavingAdjust(dtTmp),
//dt = $.datepicker._daylightSavingAdjust(new Date(dp_inst.selectedYear, dp_inst.selectedMonth, dp_inst.selectedDay)),
//dt = $.datepicker._daylightSavingAdjust(new Date(dp_inst.currentYear, dp_inst.currentMonth, dp_inst.currentDay)),
dateFmt = $.datepicker._get(dp_inst, 'dateFormat'),
formatCfg = $.datepicker._getFormatConfig(dp_inst),
timeAvailable = dt !== null && this.timeDefined;
this.formattedDate = $.datepicker.formatDate(dateFmt, (dt === null ? new Date() : dt), formatCfg);
var formattedDateTime = this.formattedDate;
// if a slider was changed but datepicker doesn't have a value yet, set it
if (dp_inst.lastVal === "") {
dp_inst.currentYear = dp_inst.selectedYear;
dp_inst.currentMonth = dp_inst.selectedMonth;
dp_inst.currentDay = dp_inst.selectedDay;
}
/*
* remove following lines to force every changes in date picker to change the input value
* Bug descriptions: when an input field has a default value, and click on the field to pop up the date picker.
* If the user manually empty the value in the input field, the date picker will never change selected value.
*/
//if (dp_inst.lastVal !== undefined && (dp_inst.lastVal.length > 0 && this.$input.val().length === 0)) {
// return;
//}
if (this._defaults.timeOnly === true && this._defaults.timeOnlyShowDate === false) {
formattedDateTime = this.formattedTime;
} else if ((this._defaults.timeOnly !== true && (this._defaults.alwaysSetTime || timeAvailable)) || (this._defaults.timeOnly === true && this._defaults.timeOnlyShowDate === true)) {
formattedDateTime += this._defaults.separator + this.formattedTime + this._defaults.timeSuffix;
}
this.formattedDateTime = formattedDateTime;
if (!this._defaults.showTimepicker) {
this.$input.val(this.formattedDate);
} else if (this.$altInput && this._defaults.timeOnly === false && this._defaults.altFieldTimeOnly === true) {
this.$altInput.val(this.formattedTime);
this.$input.val(this.formattedDate);
} else if (this.$altInput) {
this.$input.val(formattedDateTime);
var altFormattedDateTime = '',
altSeparator = this._defaults.altSeparator !== null ? this._defaults.altSeparator : this._defaults.separator,
altTimeSuffix = this._defaults.altTimeSuffix !== null ? this._defaults.altTimeSuffix : this._defaults.timeSuffix;
if (!this._defaults.timeOnly) {
if (this._defaults.altFormat) {
altFormattedDateTime = $.datepicker.formatDate(this._defaults.altFormat, (dt === null ? new Date() : dt), formatCfg);
}
else {
altFormattedDateTime = this.formattedDate;
}
if (altFormattedDateTime) {
altFormattedDateTime += altSeparator;
}
}
if (this._defaults.altTimeFormat !== null) {
altFormattedDateTime += $.datepicker.formatTime(this._defaults.altTimeFormat, this, this._defaults) + altTimeSuffix;
}
else {
altFormattedDateTime += this.formattedTime + altTimeSuffix;
}
this.$altInput.val(altFormattedDateTime);
} else {
this.$input.val(formattedDateTime);
}
this.$input.trigger("change");
},
_onFocus: function () {
if (!this.$input.val() && this._defaults.defaultValue) {
this.$input.val(this._defaults.defaultValue);
var inst = $.datepicker._getInst(this.$input.get(0)),
tp_inst = $.datepicker._get(inst, 'timepicker');
if (tp_inst) {
if (tp_inst._defaults.timeOnly && (inst.input.val() !== inst.lastVal)) {
try {
$.datepicker._updateDatepicker(inst);
} catch (err) {
$.timepicker.log(err);
}
}
}
}
},
/*
* Small abstraction to control types
* We can add more, just be sure to follow the pattern: create, options, value
*/
_controls: {
// slider methods
slider: {
create: function (tp_inst, obj, unit, val, min, max, step) {
var rtl = tp_inst._defaults.isRTL; // if rtl go -60->0 instead of 0->60
return obj.prop('slide', null).slider({
orientation: "horizontal",
value: rtl ? val * -1 : val,
min: rtl ? max * -1 : min,
max: rtl ? min * -1 : max,
step: step,
slide: function (event, ui) {
tp_inst.control.value(tp_inst, $(this), unit, rtl ? ui.value * -1 : ui.value);
tp_inst._onTimeChange();
},
stop: function (event, ui) {
tp_inst._onSelectHandler();
}
});
},
options: function (tp_inst, obj, unit, opts, val) {
if (tp_inst._defaults.isRTL) {
if (typeof(opts) === 'string') {
if (opts === 'min' || opts === 'max') {
if (val !== undefined) {
return obj.slider(opts, val * -1);
}
return Math.abs(obj.slider(opts));
}
return obj.slider(opts);
}
var min = opts.min,
max = opts.max;
opts.min = opts.max = null;
if (min !== undefined) {
opts.max = min * -1;
}
if (max !== undefined) {
opts.min = max * -1;
}
return obj.slider(opts);
}
if (typeof(opts) === 'string' && val !== undefined) {
return obj.slider(opts, val);
}
return obj.slider(opts);
},
value: function (tp_inst, obj, unit, val) {
if (tp_inst._defaults.isRTL) {
if (val !== undefined) {
return obj.slider('value', val * -1);
}
return Math.abs(obj.slider('value'));
}
if (val !== undefined) {
return obj.slider('value', val);
}
return obj.slider('value');
}
},
// select methods
select: {
create: function (tp_inst, obj, unit, val, min, max, step) {
var sel = '';
obj.children('select').remove();
$(sel).appendTo(obj).change(function (e) {
tp_inst._onTimeChange();
tp_inst._onSelectHandler();
tp_inst._afterInject();
});
return obj;
},
options: function (tp_inst, obj, unit, opts, val) {
var o = {},
$t = obj.children('select');
if (typeof(opts) === 'string') {
if (val === undefined) {
return $t.data(opts);
}
o[opts] = val;
}
else { o = opts; }
return tp_inst.control.create(tp_inst, obj, $t.data('unit'), $t.val(), o.min>=0 ? o.min : $t.data('min'), o.max || $t.data('max'), o.step || $t.data('step'));
},
value: function (tp_inst, obj, unit, val) {
var $t = obj.children('select');
if (val !== undefined) {
return $t.val(val);
}
return $t.val();
}
}
} // end _controls
});
$.fn.extend({
/*
* shorthand just to use timepicker.
*/
timepicker: function (o) {
o = o || {};
var tmp_args = Array.prototype.slice.call(arguments);
if (typeof o === 'object') {
tmp_args[0] = $.extend(o, {
timeOnly: true
});
}
return $(this).each(function () {
$.fn.datetimepicker.apply($(this), tmp_args);
});
},
/*
* extend timepicker to datepicker
*/
datetimepicker: function (o) {
o = o || {};
var tmp_args = arguments;
if (typeof(o) === 'string') {
if (o === 'getDate' || (o === 'option' && tmp_args.length === 2 && typeof (tmp_args[1]) === 'string')) {
return $.fn.datepicker.apply($(this[0]), tmp_args);
} else {
return this.each(function () {
var $t = $(this);
$t.datepicker.apply($t, tmp_args);
});
}
} else {
return this.each(function () {
var $t = $(this);
$t.datepicker($.timepicker._newInst($t, o)._defaults);
});
}
}
});
/*
* Public Utility to parse date and time
*/
$.datepicker.parseDateTime = function (dateFormat, timeFormat, dateTimeString, dateSettings, timeSettings) {
var parseRes = parseDateTimeInternal(dateFormat, timeFormat, dateTimeString, dateSettings, timeSettings);
if (parseRes.timeObj) {
var t = parseRes.timeObj;
parseRes.date.setHours(t.hour, t.minute, t.second, t.millisec);
parseRes.date.setMicroseconds(t.microsec);
}
return parseRes.date;
};
/*
* Public utility to parse time
*/
$.datepicker.parseTime = function (timeFormat, timeString, options) {
var o = extendRemove(extendRemove({}, $.timepicker._defaults), options || {}),
iso8601 = (timeFormat.replace(/\'.*?\'/g, '').indexOf('Z') !== -1);
// Strict parse requires the timeString to match the timeFormat exactly
var strictParse = function (f, s, o) {
// pattern for standard and localized AM/PM markers
var getPatternAmpm = function (amNames, pmNames) {
var markers = [];
if (amNames) {
$.merge(markers, amNames);
}
if (pmNames) {
$.merge(markers, pmNames);
}
markers = $.map(markers, function (val) {
return val.replace(/[.*+?|()\[\]{}\\]/g, '\\$&');
});
return '(' + markers.join('|') + ')?';
};
// figure out position of time elements.. cause js cant do named captures
var getFormatPositions = function (timeFormat) {
var finds = timeFormat.toLowerCase().match(/(h{1,2}|m{1,2}|s{1,2}|l{1}|c{1}|t{1,2}|z|'.*?')/g),
orders = {
h: -1,
m: -1,
s: -1,
l: -1,
c: -1,
t: -1,
z: -1
};
if (finds) {
for (var i = 0; i < finds.length; i++) {
if (orders[finds[i].toString().charAt(0)] === -1) {
orders[finds[i].toString().charAt(0)] = i + 1;
}
}
}
return orders;
};
var regstr = '^' + f.toString()
.replace(/([hH]{1,2}|mm?|ss?|[tT]{1,2}|[zZ]|[lc]|'.*?')/g, function (match) {
var ml = match.length;
switch (match.charAt(0).toLowerCase()) {
case 'h':
return ml === 1 ? '(\\d?\\d)' : '(\\d{' + ml + '})';
case 'm':
return ml === 1 ? '(\\d?\\d)' : '(\\d{' + ml + '})';
case 's':
return ml === 1 ? '(\\d?\\d)' : '(\\d{' + ml + '})';
case 'l':
return '(\\d?\\d?\\d)';
case 'c':
return '(\\d?\\d?\\d)';
case 'z':
return '(z|[-+]\\d\\d:?\\d\\d|\\S+)?';
case 't':
return getPatternAmpm(o.amNames, o.pmNames);
default: // literal escaped in quotes
return '(' + match.replace(/\'/g, "").replace(/(\.|\$|\^|\\|\/|\(|\)|\[|\]|\?|\+|\*)/g, function (m) { return "\\" + m; }) + ')?';
}
})
.replace(/\s/g, '\\s?') +
o.timeSuffix + '$',
order = getFormatPositions(f),
ampm = '',
treg;
treg = s.match(new RegExp(regstr, 'i'));
var resTime = {
hour: 0,
minute: 0,
second: 0,
millisec: 0,
microsec: 0
};
if (treg) {
if (order.t !== -1) {
if (treg[order.t] === undefined || treg[order.t].length === 0) {
ampm = '';
resTime.ampm = '';
} else {
ampm = $.inArray(treg[order.t].toUpperCase(), $.map(o.amNames, function (x,i) { return x.toUpperCase(); })) !== -1 ? 'AM' : 'PM';
resTime.ampm = o[ampm === 'AM' ? 'amNames' : 'pmNames'][0];
}
}
if (order.h !== -1) {
if (ampm === 'AM' && treg[order.h] === '12') {
resTime.hour = 0; // 12am = 0 hour
} else {
if (ampm === 'PM' && treg[order.h] !== '12') {
resTime.hour = parseInt(treg[order.h], 10) + 12; // 12pm = 12 hour, any other pm = hour + 12
} else {
resTime.hour = Number(treg[order.h]);
}
}
}
if (order.m !== -1) {
resTime.minute = Number(treg[order.m]);
}
if (order.s !== -1) {
resTime.second = Number(treg[order.s]);
}
if (order.l !== -1) {
resTime.millisec = Number(treg[order.l]);
}
if (order.c !== -1) {
resTime.microsec = Number(treg[order.c]);
}
if (order.z !== -1 && treg[order.z] !== undefined) {
resTime.timezone = $.timepicker.timezoneOffsetNumber(treg[order.z]);
}
return resTime;
}
return false;
};// end strictParse
// First try JS Date, if that fails, use strictParse
var looseParse = function (f, s, o) {
try {
var d = new Date('2012-01-01 ' + s);
if (isNaN(d.getTime())) {
d = new Date('2012-01-01T' + s);
if (isNaN(d.getTime())) {
d = new Date('01/01/2012 ' + s);
if (isNaN(d.getTime())) {
throw "Unable to parse time with native Date: " + s;
}
}
}
return {
hour: d.getHours(),
minute: d.getMinutes(),
second: d.getSeconds(),
millisec: d.getMilliseconds(),
microsec: d.getMicroseconds(),
timezone: d.getTimezoneOffset() * -1
};
}
catch (err) {
try {
return strictParse(f, s, o);
}
catch (err2) {
$.timepicker.log("Unable to parse \ntimeString: " + s + "\ntimeFormat: " + f);
}
}
return false;
}; // end looseParse
if (typeof o.parse === "function") {
return o.parse(timeFormat, timeString, o);
}
if (o.parse === 'loose') {
return looseParse(timeFormat, timeString, o);
}
return strictParse(timeFormat, timeString, o);
};
/**
* Public utility to format the time
* @param {string} format format of the time
* @param {Object} time Object not a Date for timezones
* @param {Object} [options] essentially the regional[].. amNames, pmNames, ampm
* @returns {string} the formatted time
*/
$.datepicker.formatTime = function (format, time, options) {
options = options || {};
options = $.extend({}, $.timepicker._defaults, options);
time = $.extend({
hour: 0,
minute: 0,
second: 0,
millisec: 0,
microsec: 0,
timezone: null
}, time);
var tmptime = format,
ampmName = options.amNames[0],
hour = parseInt(time.hour, 10);
if (hour > 11) {
ampmName = options.pmNames[0];
}
tmptime = tmptime.replace(/(?:HH?|hh?|mm?|ss?|[tT]{1,2}|[zZ]|[lc]|'.*?')/g, function (match) {
switch (match) {
case 'HH':
return ('0' + hour).slice(-2);
case 'H':
return hour;
case 'hh':
return ('0' + convert24to12(hour)).slice(-2);
case 'h':
return convert24to12(hour);
case 'mm':
return ('0' + time.minute).slice(-2);
case 'm':
return time.minute;
case 'ss':
return ('0' + time.second).slice(-2);
case 's':
return time.second;
case 'l':
return ('00' + time.millisec).slice(-3);
case 'c':
return ('00' + time.microsec).slice(-3);
case 'z':
return $.timepicker.timezoneOffsetString(time.timezone === null ? options.timezone : time.timezone, false);
case 'Z':
return $.timepicker.timezoneOffsetString(time.timezone === null ? options.timezone : time.timezone, true);
case 'T':
return ampmName.charAt(0).toUpperCase();
case 'TT':
return ampmName.toUpperCase();
case 't':
return ampmName.charAt(0).toLowerCase();
case 'tt':
return ampmName.toLowerCase();
default:
return match.replace(/'/g, "");
}
});
return tmptime;
};
/*
* the bad hack :/ override datepicker so it doesn't close on select
// inspired: http://stackoverflow.com/questions/1252512/jquery-datepicker-prevent-closing-picker-when-clicking-a-date/1762378#1762378
*/
$.datepicker._base_selectDate = $.datepicker._selectDate;
$.datepicker._selectDate = function (id, dateStr) {
var inst = this._getInst($(id)[0]),
tp_inst = this._get(inst, 'timepicker'),
was_inline;
if (tp_inst && inst.settings.showTimepicker) {
tp_inst._limitMinMaxDateTime(inst, true);
was_inline = inst.inline;
inst.inline = inst.stay_open = true;
//This way the onSelect handler called from calendarpicker get the full dateTime
this._base_selectDate(id, dateStr);
inst.inline = was_inline;
inst.stay_open = false;
this._notifyChange(inst);
this._updateDatepicker(inst);
} else {
this._base_selectDate(id, dateStr);
}
};
/*
* second bad hack :/ override datepicker so it triggers an event when changing the input field
* and does not redraw the datepicker on every selectDate event
*/
$.datepicker._base_updateDatepicker = $.datepicker._updateDatepicker;
$.datepicker._updateDatepicker = function (inst) {
// don't popup the datepicker if there is another instance already opened
var input = inst.input[0];
if ($.datepicker._curInst && $.datepicker._curInst !== inst && $.datepicker._datepickerShowing && $.datepicker._lastInput !== input) {
return;
}
if (typeof(inst.stay_open) !== 'boolean' || inst.stay_open === false) {
this._base_updateDatepicker(inst);
// Reload the time control when changing something in the input text field.
var tp_inst = this._get(inst, 'timepicker');
if (tp_inst) {
tp_inst._addTimePicker(inst);
}
}
};
/*
* third bad hack :/ override datepicker so it allows spaces and colon in the input field
*/
$.datepicker._base_doKeyPress = $.datepicker._doKeyPress;
$.datepicker._doKeyPress = function (event) {
var inst = $.datepicker._getInst(event.target),
tp_inst = $.datepicker._get(inst, 'timepicker');
if (tp_inst) {
if ($.datepicker._get(inst, 'constrainInput')) {
var ampm = tp_inst.support.ampm,
tz = tp_inst._defaults.showTimezone !== null ? tp_inst._defaults.showTimezone : tp_inst.support.timezone,
dateChars = $.datepicker._possibleChars($.datepicker._get(inst, 'dateFormat')),
datetimeChars = tp_inst._defaults.timeFormat.toString()
.replace(/[hms]/g, '')
.replace(/TT/g, ampm ? 'APM' : '')
.replace(/Tt/g, ampm ? 'AaPpMm' : '')
.replace(/tT/g, ampm ? 'AaPpMm' : '')
.replace(/T/g, ampm ? 'AP' : '')
.replace(/tt/g, ampm ? 'apm' : '')
.replace(/t/g, ampm ? 'ap' : '') +
" " + tp_inst._defaults.separator +
tp_inst._defaults.timeSuffix +
(tz ? tp_inst._defaults.timezoneList.join('') : '') +
(tp_inst._defaults.amNames.join('')) + (tp_inst._defaults.pmNames.join('')) +
dateChars,
chr = String.fromCharCode(event.charCode === undefined ? event.keyCode : event.charCode);
return event.ctrlKey || (chr < ' ' || !dateChars || datetimeChars.indexOf(chr) > -1);
}
}
return $.datepicker._base_doKeyPress(event);
};
/*
* Fourth bad hack :/ override _updateAlternate function used in inline mode to init altField
* Update any alternate field to synchronise with the main field.
*/
$.datepicker._base_updateAlternate = $.datepicker._updateAlternate;
$.datepicker._updateAlternate = function (inst) {
var tp_inst = this._get(inst, 'timepicker');
if (tp_inst) {
var altField = tp_inst._defaults.altField;
if (altField) { // update alternate field too
var altFormat = tp_inst._defaults.altFormat || tp_inst._defaults.dateFormat,
date = this._getDate(inst),
formatCfg = $.datepicker._getFormatConfig(inst),
altFormattedDateTime = '',
altSeparator = tp_inst._defaults.altSeparator ? tp_inst._defaults.altSeparator : tp_inst._defaults.separator,
altTimeSuffix = tp_inst._defaults.altTimeSuffix ? tp_inst._defaults.altTimeSuffix : tp_inst._defaults.timeSuffix,
altTimeFormat = tp_inst._defaults.altTimeFormat !== null ? tp_inst._defaults.altTimeFormat : tp_inst._defaults.timeFormat;
altFormattedDateTime += $.datepicker.formatTime(altTimeFormat, tp_inst, tp_inst._defaults) + altTimeSuffix;
if (!tp_inst._defaults.timeOnly && !tp_inst._defaults.altFieldTimeOnly && date !== null) {
if (tp_inst._defaults.altFormat) {
altFormattedDateTime = $.datepicker.formatDate(tp_inst._defaults.altFormat, date, formatCfg) + altSeparator + altFormattedDateTime;
}
else {
altFormattedDateTime = tp_inst.formattedDate + altSeparator + altFormattedDateTime;
}
}
$(altField).val( inst.input.val() ? altFormattedDateTime : "");
}
}
else {
$.datepicker._base_updateAlternate(inst);
}
};
/*
* Override key up event to sync manual input changes.
*/
$.datepicker._base_doKeyUp = $.datepicker._doKeyUp;
$.datepicker._doKeyUp = function (event) {
var inst = $.datepicker._getInst(event.target),
tp_inst = $.datepicker._get(inst, 'timepicker');
if (tp_inst) {
if (tp_inst._defaults.timeOnly && (inst.input.val() !== inst.lastVal)) {
try {
$.datepicker._updateDatepicker(inst);
} catch (err) {
$.timepicker.log(err);
}
}
}
return $.datepicker._base_doKeyUp(event);
};
/*
* override "Today" button to also grab the time and set it to input field.
*/
$.datepicker._base_gotoToday = $.datepicker._gotoToday;
$.datepicker._gotoToday = function (id) {
var inst = this._getInst($(id)[0]);
this._base_gotoToday(id);
var tp_inst = this._get(inst, 'timepicker');
var tzoffset = $.timepicker.timezoneOffsetNumber(tp_inst.timezone);
var now = new Date();
now.setMinutes(now.getMinutes() + now.getTimezoneOffset() + tzoffset);
this._setTime(inst, now);
this._setDate(inst, now);
tp_inst._onSelectHandler();
};
/*
* Disable & enable the Time in the datetimepicker
*/
$.datepicker._disableTimepickerDatepicker = function (target) {
var inst = this._getInst(target);
if (!inst) {
return;
}
var tp_inst = this._get(inst, 'timepicker');
$(target).datepicker('getDate'); // Init selected[Year|Month|Day]
if (tp_inst) {
inst.settings.showTimepicker = false;
tp_inst._defaults.showTimepicker = false;
tp_inst._updateDateTime(inst);
}
};
$.datepicker._enableTimepickerDatepicker = function (target) {
var inst = this._getInst(target);
if (!inst) {
return;
}
var tp_inst = this._get(inst, 'timepicker');
$(target).datepicker('getDate'); // Init selected[Year|Month|Day]
if (tp_inst) {
inst.settings.showTimepicker = true;
tp_inst._defaults.showTimepicker = true;
tp_inst._addTimePicker(inst); // Could be disabled on page load
tp_inst._updateDateTime(inst);
}
};
/*
* Create our own set time function
*/
$.datepicker._setTime = function (inst, date) {
var tp_inst = this._get(inst, 'timepicker');
if (tp_inst) {
var defaults = tp_inst._defaults;
// calling _setTime with no date sets time to defaults
tp_inst.hour = date ? date.getHours() : defaults.hour;
tp_inst.minute = date ? date.getMinutes() : defaults.minute;
tp_inst.second = date ? date.getSeconds() : defaults.second;
tp_inst.millisec = date ? date.getMilliseconds() : defaults.millisec;
tp_inst.microsec = date ? date.getMicroseconds() : defaults.microsec;
//check if within min/max times..
tp_inst._limitMinMaxDateTime(inst, true);
tp_inst._onTimeChange();
tp_inst._updateDateTime(inst);
}
};
/*
* Create new public method to set only time, callable as $().datepicker('setTime', date)
*/
$.datepicker._setTimeDatepicker = function (target, date, withDate) {
var inst = this._getInst(target);
if (!inst) {
return;
}
var tp_inst = this._get(inst, 'timepicker');
if (tp_inst) {
this._setDateFromField(inst);
var tp_date;
if (date) {
if (typeof date === "string") {
tp_inst._parseTime(date, withDate);
tp_date = new Date();
tp_date.setHours(tp_inst.hour, tp_inst.minute, tp_inst.second, tp_inst.millisec);
tp_date.setMicroseconds(tp_inst.microsec);
} else {
tp_date = new Date(date.getTime());
tp_date.setMicroseconds(date.getMicroseconds());
}
if (tp_date.toString() === 'Invalid Date') {
tp_date = undefined;
}
this._setTime(inst, tp_date);
}
}
};
/*
* override setDate() to allow setting time too within Date object
*/
$.datepicker._base_setDateDatepicker = $.datepicker._setDateDatepicker;
$.datepicker._setDateDatepicker = function (target, _date) {
var inst = this._getInst(target);
var date = _date;
if (!inst) {
return;
}
if (typeof(_date) === 'string') {
date = new Date(_date);
if (!date.getTime()) {
this._base_setDateDatepicker.apply(this, arguments);
date = $(target).datepicker('getDate');
}
}
var tp_inst = this._get(inst, 'timepicker');
var tp_date;
if (date instanceof Date) {
tp_date = new Date(date.getTime());
tp_date.setMicroseconds(date.getMicroseconds());
} else {
tp_date = date;
}
// This is important if you are using the timezone option, javascript's Date
// object will only return the timezone offset for the current locale, so we
// adjust it accordingly. If not using timezone option this won't matter..
// If a timezone is different in tp, keep the timezone as is
if (tp_inst && tp_date) {
// look out for DST if tz wasn't specified
if (!tp_inst.support.timezone && tp_inst._defaults.timezone === null) {
tp_inst.timezone = tp_date.getTimezoneOffset() * -1;
}
date = $.timepicker.timezoneAdjust(date, tp_inst.timezone);
tp_date = $.timepicker.timezoneAdjust(tp_date, tp_inst.timezone);
}
this._updateDatepicker(inst);
this._base_setDateDatepicker.apply(this, arguments);
this._setTimeDatepicker(target, tp_date, true);
};
/*
* override getDate() to allow getting time too within Date object
*/
$.datepicker._base_getDateDatepicker = $.datepicker._getDateDatepicker;
$.datepicker._getDateDatepicker = function (target, noDefault) {
var inst = this._getInst(target);
if (!inst) {
return;
}
var tp_inst = this._get(inst, 'timepicker');
if (tp_inst) {
// if it hasn't yet been defined, grab from field
if (inst.lastVal === undefined) {
this._setDateFromField(inst, noDefault);
}
var date = this._getDate(inst);
var currDT = $.trim((tp_inst.$altInput && tp_inst._defaults.altFieldTimeOnly) ? tp_inst.$input.val() + ' ' + tp_inst.$altInput.val() : tp_inst.$input.val());
if (date && tp_inst._parseTime(currDT, !inst.settings.timeOnly)) {
date.setHours(tp_inst.hour, tp_inst.minute, tp_inst.second, tp_inst.millisec);
date.setMicroseconds(tp_inst.microsec);
// This is important if you are using the timezone option, javascript's Date
// object will only return the timezone offset for the current locale, so we
// adjust it accordingly. If not using timezone option this won't matter..
if (tp_inst.timezone != null) {
// look out for DST if tz wasn't specified
if (!tp_inst.support.timezone && tp_inst._defaults.timezone === null) {
tp_inst.timezone = date.getTimezoneOffset() * -1;
}
date = $.timepicker.timezoneAdjust(date, tp_inst.timezone);
}
}
return date;
}
return this._base_getDateDatepicker(target, noDefault);
};
/*
* override parseDate() because UI 1.8.14 throws an error about "Extra characters"
* An option in datapicker to ignore extra format characters would be nicer.
*/
$.datepicker._base_parseDate = $.datepicker.parseDate;
$.datepicker.parseDate = function (format, value, settings) {
var date;
try {
date = this._base_parseDate(format, value, settings);
} catch (err) {
// Hack! The error message ends with a colon, a space, and
// the "extra" characters. We rely on that instead of
// attempting to perfectly reproduce the parsing algorithm.
if (err.indexOf(":") >= 0) {
date = this._base_parseDate(format, value.substring(0, value.length - (err.length - err.indexOf(':') - 2)), settings);
$.timepicker.log("Error parsing the date string: " + err + "\ndate string = " + value + "\ndate format = " + format);
} else {
throw err;
}
}
return date;
};
/*
* override formatDate to set date with time to the input
*/
$.datepicker._base_formatDate = $.datepicker._formatDate;
$.datepicker._formatDate = function (inst, day, month, year) {
var tp_inst = this._get(inst, 'timepicker');
if (tp_inst) {
tp_inst._updateDateTime(inst);
return tp_inst.$input.val();
}
return this._base_formatDate(inst);
};
/*
* override options setter to add time to maxDate(Time) and minDate(Time). MaxDate
*/
$.datepicker._base_optionDatepicker = $.datepicker._optionDatepicker;
$.datepicker._optionDatepicker = function (target, name, value) {
var inst = this._getInst(target),
name_clone;
if (!inst) {
return null;
}
var tp_inst = this._get(inst, 'timepicker');
if (tp_inst) {
var min = null,
max = null,
onselect = null,
overrides = tp_inst._defaults.evnts,
fns = {},
prop,
ret,
oldVal,
$target;
if (typeof name === 'string') { // if min/max was set with the string
if (name === 'minDate' || name === 'minDateTime') {
min = value;
} else if (name === 'maxDate' || name === 'maxDateTime') {
max = value;
} else if (name === 'onSelect') {
onselect = value;
} else if (overrides.hasOwnProperty(name)) {
if (typeof (value) === 'undefined') {
return overrides[name];
}
fns[name] = value;
name_clone = {}; //empty results in exiting function after overrides updated
}
} else if (typeof name === 'object') { //if min/max was set with the JSON
if (name.minDate) {
min = name.minDate;
} else if (name.minDateTime) {
min = name.minDateTime;
} else if (name.maxDate) {
max = name.maxDate;
} else if (name.maxDateTime) {
max = name.maxDateTime;
}
for (prop in overrides) {
if (overrides.hasOwnProperty(prop) && name[prop]) {
fns[prop] = name[prop];
}
}
}
for (prop in fns) {
if (fns.hasOwnProperty(prop)) {
overrides[prop] = fns[prop];
if (!name_clone) { name_clone = $.extend({}, name); }
delete name_clone[prop];
}
}
if (name_clone && isEmptyObject(name_clone)) { return; }
if (min) { //if min was set
if (min === 0) {
min = new Date();
} else {
min = new Date(min);
}
tp_inst._defaults.minDate = min;
tp_inst._defaults.minDateTime = min;
} else if (max) { //if max was set
if (max === 0) {
max = new Date();
} else {
max = new Date(max);
}
tp_inst._defaults.maxDate = max;
tp_inst._defaults.maxDateTime = max;
} else if (onselect) {
tp_inst._defaults.onSelect = onselect;
}
// Datepicker will override our date when we call _base_optionDatepicker when
// calling minDate/maxDate, so we will first grab the value, call
// _base_optionDatepicker, then set our value back.
if(min || max){
$target = $(target);
oldVal = $target.datetimepicker('getDate');
ret = this._base_optionDatepicker.call($.datepicker, target, name_clone || name, value);
$target.datetimepicker('setDate', oldVal);
return ret;
}
}
if (value === undefined) {
return this._base_optionDatepicker.call($.datepicker, target, name);
}
return this._base_optionDatepicker.call($.datepicker, target, name_clone || name, value);
};
/*
* jQuery isEmptyObject does not check hasOwnProperty - if someone has added to the object prototype,
* it will return false for all objects
*/
var isEmptyObject = function (obj) {
var prop;
for (prop in obj) {
if (obj.hasOwnProperty(prop)) {
return false;
}
}
return true;
};
/*
* jQuery extend now ignores nulls!
*/
var extendRemove = function (target, props) {
$.extend(target, props);
for (var name in props) {
if (props[name] === null || props[name] === undefined) {
target[name] = props[name];
}
}
return target;
};
/*
* Determine by the time format which units are supported
* Returns an object of booleans for each unit
*/
var detectSupport = function (timeFormat) {
var tf = timeFormat.replace(/'.*?'/g, '').toLowerCase(), // removes literals
isIn = function (f, t) { // does the format contain the token?
return f.indexOf(t) !== -1 ? true : false;
};
return {
hour: isIn(tf, 'h'),
minute: isIn(tf, 'm'),
second: isIn(tf, 's'),
millisec: isIn(tf, 'l'),
microsec: isIn(tf, 'c'),
timezone: isIn(tf, 'z'),
ampm: isIn(tf, 't') && isIn(timeFormat, 'h'),
iso8601: isIn(timeFormat, 'Z')
};
};
/*
* Converts 24 hour format into 12 hour
* Returns 12 hour without leading 0
*/
var convert24to12 = function (hour) {
hour %= 12;
if (hour === 0) {
hour = 12;
}
return String(hour);
};
var computeEffectiveSetting = function (settings, property) {
return settings && settings[property] ? settings[property] : $.timepicker._defaults[property];
};
/*
* Splits datetime string into date and time substrings.
* Throws exception when date can't be parsed
* Returns {dateString: dateString, timeString: timeString}
*/
var splitDateTime = function (dateTimeString, timeSettings) {
// The idea is to get the number separator occurrences in datetime and the time format requested (since time has
// fewer unknowns, mostly numbers and am/pm). We will use the time pattern to split.
var separator = computeEffectiveSetting(timeSettings, 'separator'),
format = computeEffectiveSetting(timeSettings, 'timeFormat'),
timeParts = format.split(separator), // how many occurrences of separator may be in our format?
timePartsLen = timeParts.length,
allParts = dateTimeString.split(separator),
allPartsLen = allParts.length;
if (allPartsLen > 1) {
return {
dateString: allParts.splice(0, allPartsLen - timePartsLen).join(separator),
timeString: allParts.splice(0, timePartsLen).join(separator)
};
}
return {
dateString: dateTimeString,
timeString: ''
};
};
/*
* Internal function to parse datetime interval
* Returns: {date: Date, timeObj: Object}, where
* date - parsed date without time (type Date)
* timeObj = {hour: , minute: , second: , millisec: , microsec: } - parsed time. Optional
*/
var parseDateTimeInternal = function (dateFormat, timeFormat, dateTimeString, dateSettings, timeSettings) {
var date,
parts,
parsedTime;
parts = splitDateTime(dateTimeString, timeSettings);
date = $.datepicker._base_parseDate(dateFormat, parts.dateString, dateSettings);
if (parts.timeString === '') {
return {
date: date
};
}
parsedTime = $.datepicker.parseTime(timeFormat, parts.timeString, timeSettings);
if (!parsedTime) {
throw 'Wrong time format';
}
return {
date: date,
timeObj: parsedTime
};
};
/*
* Internal function to set timezone_select to the local timezone
*/
var selectLocalTimezone = function (tp_inst, date) {
if (tp_inst && tp_inst.timezone_select) {
var now = date || new Date();
tp_inst.timezone_select.val(-now.getTimezoneOffset());
}
};
/*
* Create a Singleton Instance
*/
$.timepicker = new Timepicker();
/**
* Get the timezone offset as string from a date object (eg '+0530' for UTC+5.5)
* @param {number} tzMinutes if not a number, less than -720 (-1200), or greater than 840 (+1400) this value is returned
* @param {boolean} iso8601 if true formats in accordance to iso8601 "+12:45"
* @return {string}
*/
$.timepicker.timezoneOffsetString = function (tzMinutes, iso8601) {
if (isNaN(tzMinutes) || tzMinutes > 840 || tzMinutes < -720) {
return tzMinutes;
}
var off = tzMinutes,
minutes = off % 60,
hours = (off - minutes) / 60,
iso = iso8601 ? ':' : '',
tz = (off >= 0 ? '+' : '-') + ('0' + Math.abs(hours)).slice(-2) + iso + ('0' + Math.abs(minutes)).slice(-2);
if (tz === '+00:00') {
return 'Z';
}
return tz;
};
/**
* Get the number in minutes that represents a timezone string
* @param {string} tzString formatted like "+0500", "-1245", "Z"
* @return {number} the offset minutes or the original string if it doesn't match expectations
*/
$.timepicker.timezoneOffsetNumber = function (tzString) {
var normalized = tzString.toString().replace(':', ''); // excuse any iso8601, end up with "+1245"
if (normalized.toUpperCase() === 'Z') { // if iso8601 with Z, its 0 minute offset
return 0;
}
if (!/^(\-|\+)\d{4}$/.test(normalized)) { // possibly a user defined tz, so just give it back
return tzString;
}
return ((normalized.substr(0, 1) === '-' ? -1 : 1) * // plus or minus
((parseInt(normalized.substr(1, 2), 10) * 60) + // hours (converted to minutes)
parseInt(normalized.substr(3, 2), 10))); // minutes
};
/**
* No way to set timezone in js Date, so we must adjust the minutes to compensate. (think setDate, getDate)
* @param {Date} date
* @param {string} toTimezone formatted like "+0500", "-1245"
* @return {Date}
*/
$.timepicker.timezoneAdjust = function (date, toTimezone) {
var toTz = $.timepicker.timezoneOffsetNumber(toTimezone);
if (!isNaN(toTz)) {
date.setMinutes(date.getMinutes() + -date.getTimezoneOffset() - toTz);
}
return date;
};
/**
* Calls `timepicker()` on the `startTime` and `endTime` elements, and configures them to
* enforce date range limits.
* n.b. The input value must be correctly formatted (reformatting is not supported)
* @param {Element} startTime
* @param {Element} endTime
* @param {Object} options Options for the timepicker() call
* @return {jQuery}
*/
$.timepicker.timeRange = function (startTime, endTime, options) {
return $.timepicker.handleRange('timepicker', startTime, endTime, options);
};
/**
* Calls `datetimepicker` on the `startTime` and `endTime` elements, and configures them to
* enforce date range limits.
* @param {Element} startTime
* @param {Element} endTime
* @param {Object} options Options for the `timepicker()` call. Also supports `reformat`,
* a boolean value that can be used to reformat the input values to the `dateFormat`.
* @param {string} method Can be used to specify the type of picker to be added
* @return {jQuery}
*/
$.timepicker.datetimeRange = function (startTime, endTime, options) {
$.timepicker.handleRange('datetimepicker', startTime, endTime, options);
};
/**
* Calls `datepicker` on the `startTime` and `endTime` elements, and configures them to
* enforce date range limits.
* @param {Element} startTime
* @param {Element} endTime
* @param {Object} options Options for the `timepicker()` call. Also supports `reformat`,
* a boolean value that can be used to reformat the input values to the `dateFormat`.
* @return {jQuery}
*/
$.timepicker.dateRange = function (startTime, endTime, options) {
$.timepicker.handleRange('datepicker', startTime, endTime, options);
};
/**
* Calls `method` on the `startTime` and `endTime` elements, and configures them to
* enforce date range limits.
* @param {string} method Can be used to specify the type of picker to be added
* @param {Element} startTime
* @param {Element} endTime
* @param {Object} options Options for the `timepicker()` call. Also supports `reformat`,
* a boolean value that can be used to reformat the input values to the `dateFormat`.
* @return {jQuery}
*/
$.timepicker.handleRange = function (method, startTime, endTime, options) {
options = $.extend({}, {
minInterval: 0, // min allowed interval in milliseconds
maxInterval: 0, // max allowed interval in milliseconds
start: {}, // options for start picker
end: {} // options for end picker
}, options);
// for the mean time this fixes an issue with calling getDate with timepicker()
var timeOnly = false;
if(method === 'timepicker'){
timeOnly = true;
method = 'datetimepicker';
}
function checkDates(changed, other) {
var startdt = startTime[method]('getDate'),
enddt = endTime[method]('getDate'),
changeddt = changed[method]('getDate');
if (startdt !== null) {
var minDate = new Date(startdt.getTime()),
maxDate = new Date(startdt.getTime());
minDate.setMilliseconds(minDate.getMilliseconds() + options.minInterval);
maxDate.setMilliseconds(maxDate.getMilliseconds() + options.maxInterval);
if (options.minInterval > 0 && minDate > enddt) { // minInterval check
endTime[method]('setDate', minDate);
}
else if (options.maxInterval > 0 && maxDate < enddt) { // max interval check
endTime[method]('setDate', maxDate);
}
else if (startdt > enddt) {
other[method]('setDate', changeddt);
}
}
}
function selected(changed, other, option) {
if (!changed.val()) {
return;
}
var date = changed[method].call(changed, 'getDate');
if (date !== null && options.minInterval > 0) {
if (option === 'minDate') {
date.setMilliseconds(date.getMilliseconds() + options.minInterval);
}
if (option === 'maxDate') {
date.setMilliseconds(date.getMilliseconds() - options.minInterval);
}
}
if (date.getTime) {
other[method].call(other, 'option', option, date);
}
}
$.fn[method].call(startTime, $.extend({
timeOnly: timeOnly,
onClose: function (dateText, inst) {
checkDates($(this), endTime);
},
onSelect: function (selectedDateTime) {
selected($(this), endTime, 'minDate');
}
}, options, options.start));
$.fn[method].call(endTime, $.extend({
timeOnly: timeOnly,
onClose: function (dateText, inst) {
checkDates($(this), startTime);
},
onSelect: function (selectedDateTime) {
selected($(this), startTime, 'maxDate');
}
}, options, options.end));
checkDates(startTime, endTime);
selected(startTime, endTime, 'minDate');
selected(endTime, startTime, 'maxDate');
return $([startTime.get(0), endTime.get(0)]);
};
/**
* Log error or data to the console during error or debugging
* @param {Object} err pass any type object to log to the console during error or debugging
* @return {void}
*/
$.timepicker.log = function () {
if (window.console) {
window.console.log.apply(window.console, Array.prototype.slice.call(arguments));
}
};
/*
* Add util object to allow access to private methods for testability.
*/
$.timepicker._util = {
_extendRemove: extendRemove,
_isEmptyObject: isEmptyObject,
_convert24to12: convert24to12,
_detectSupport: detectSupport,
_selectLocalTimezone: selectLocalTimezone,
_computeEffectiveSetting: computeEffectiveSetting,
_splitDateTime: splitDateTime,
_parseDateTimeInternal: parseDateTimeInternal
};
/*
* Microsecond support
*/
if (!Date.prototype.getMicroseconds) {
Date.prototype.microseconds = 0;
Date.prototype.getMicroseconds = function () { return this.microseconds; };
Date.prototype.setMicroseconds = function (m) {
this.setMilliseconds(this.getMilliseconds() + Math.floor(m / 1000));
this.microseconds = m % 1000;
return this;
};
}
/*
* Keep up with the version
*/
$.timepicker.version = "1.6.1";
}));
================================================
FILE: public/adminlte/js/vue.js
================================================
/*!
* Vue.js v1.0.24
* (c) 2016 Evan You
* Released under the MIT License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.Vue = factory());
}(this, function () { 'use strict';
function set(obj, key, val) {
if (hasOwn(obj, key)) {
obj[key] = val;
return;
}
if (obj._isVue) {
set(obj._data, key, val);
return;
}
var ob = obj.__ob__;
if (!ob) {
obj[key] = val;
return;
}
ob.convert(key, val);
ob.dep.notify();
if (ob.vms) {
var i = ob.vms.length;
while (i--) {
var vm = ob.vms[i];
vm._proxy(key);
vm._digest();
}
}
return val;
}
/**
* Delete a property and trigger change if necessary.
*
* @param {Object} obj
* @param {String} key
*/
function del(obj, key) {
if (!hasOwn(obj, key)) {
return;
}
delete obj[key];
var ob = obj.__ob__;
if (!ob) {
if (obj._isVue) {
delete obj._data[key];
obj._digest();
}
return;
}
ob.dep.notify();
if (ob.vms) {
var i = ob.vms.length;
while (i--) {
var vm = ob.vms[i];
vm._unproxy(key);
vm._digest();
}
}
}
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* Check whether the object has the property.
*
* @param {Object} obj
* @param {String} key
* @return {Boolean}
*/
function hasOwn(obj, key) {
return hasOwnProperty.call(obj, key);
}
/**
* Check if an expression is a literal value.
*
* @param {String} exp
* @return {Boolean}
*/
var literalValueRE = /^\s?(true|false|-?[\d\.]+|'[^']*'|"[^"]*")\s?$/;
function isLiteral(exp) {
return literalValueRE.test(exp);
}
/**
* Check if a string starts with $ or _
*
* @param {String} str
* @return {Boolean}
*/
function isReserved(str) {
var c = (str + '').charCodeAt(0);
return c === 0x24 || c === 0x5F;
}
/**
* Guard text output, make sure undefined outputs
* empty string
*
* @param {*} value
* @return {String}
*/
function _toString(value) {
return value == null ? '' : value.toString();
}
/**
* Check and convert possible numeric strings to numbers
* before setting back to data
*
* @param {*} value
* @return {*|Number}
*/
function toNumber(value) {
if (typeof value !== 'string') {
return value;
} else {
var parsed = Number(value);
return isNaN(parsed) ? value : parsed;
}
}
/**
* Convert string boolean literals into real booleans.
*
* @param {*} value
* @return {*|Boolean}
*/
function toBoolean(value) {
return value === 'true' ? true : value === 'false' ? false : value;
}
/**
* Strip quotes from a string
*
* @param {String} str
* @return {String | false}
*/
function stripQuotes(str) {
var a = str.charCodeAt(0);
var b = str.charCodeAt(str.length - 1);
return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
}
/**
* Camelize a hyphen-delmited string.
*
* @param {String} str
* @return {String}
*/
var camelizeRE = /-(\w)/g;
function camelize(str) {
return str.replace(camelizeRE, toUpper);
}
function toUpper(_, c) {
return c ? c.toUpperCase() : '';
}
/**
* Hyphenate a camelCase string.
*
* @param {String} str
* @return {String}
*/
var hyphenateRE = /([a-z\d])([A-Z])/g;
function hyphenate(str) {
return str.replace(hyphenateRE, '$1-$2').toLowerCase();
}
/**
* Converts hyphen/underscore/slash delimitered names into
* camelized classNames.
*
* e.g. my-component => MyComponent
* some_else => SomeElse
* some/comp => SomeComp
*
* @param {String} str
* @return {String}
*/
var classifyRE = /(?:^|[-_\/])(\w)/g;
function classify(str) {
return str.replace(classifyRE, toUpper);
}
/**
* Simple bind, faster than native
*
* @param {Function} fn
* @param {Object} ctx
* @return {Function}
*/
function bind(fn, ctx) {
return function (a) {
var l = arguments.length;
return l ? l > 1 ? fn.apply(ctx, arguments) : fn.call(ctx, a) : fn.call(ctx);
};
}
/**
* Convert an Array-like object to a real Array.
*
* @param {Array-like} list
* @param {Number} [start] - start index
* @return {Array}
*/
function toArray(list, start) {
start = start || 0;
var i = list.length - start;
var ret = new Array(i);
while (i--) {
ret[i] = list[i + start];
}
return ret;
}
/**
* Mix properties into target object.
*
* @param {Object} to
* @param {Object} from
*/
function extend(to, from) {
var keys = Object.keys(from);
var i = keys.length;
while (i--) {
to[keys[i]] = from[keys[i]];
}
return to;
}
/**
* Quick object check - this is primarily used to tell
* Objects from primitive values when we know the value
* is a JSON-compliant type.
*
* @param {*} obj
* @return {Boolean}
*/
function isObject(obj) {
return obj !== null && typeof obj === 'object';
}
/**
* Strict object type check. Only returns true
* for plain JavaScript objects.
*
* @param {*} obj
* @return {Boolean}
*/
var toString = Object.prototype.toString;
var OBJECT_STRING = '[object Object]';
function isPlainObject(obj) {
return toString.call(obj) === OBJECT_STRING;
}
/**
* Array type check.
*
* @param {*} obj
* @return {Boolean}
*/
var isArray = Array.isArray;
/**
* Define a property.
*
* @param {Object} obj
* @param {String} key
* @param {*} val
* @param {Boolean} [enumerable]
*/
function def(obj, key, val, enumerable) {
Object.defineProperty(obj, key, {
value: val,
enumerable: !!enumerable,
writable: true,
configurable: true
});
}
/**
* Debounce a function so it only gets called after the
* input stops arriving after the given wait period.
*
* @param {Function} func
* @param {Number} wait
* @return {Function} - the debounced function
*/
function _debounce(func, wait) {
var timeout, args, context, timestamp, result;
var later = function later() {
var last = Date.now() - timestamp;
if (last < wait && last >= 0) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null;
}
};
return function () {
context = this;
args = arguments;
timestamp = Date.now();
if (!timeout) {
timeout = setTimeout(later, wait);
}
return result;
};
}
/**
* Manual indexOf because it's slightly faster than
* native.
*
* @param {Array} arr
* @param {*} obj
*/
function indexOf(arr, obj) {
var i = arr.length;
while (i--) {
if (arr[i] === obj) return i;
}
return -1;
}
/**
* Make a cancellable version of an async callback.
*
* @param {Function} fn
* @return {Function}
*/
function cancellable(fn) {
var cb = function cb() {
if (!cb.cancelled) {
return fn.apply(this, arguments);
}
};
cb.cancel = function () {
cb.cancelled = true;
};
return cb;
}
/**
* Check if two values are loosely equal - that is,
* if they are plain objects, do they have the same shape?
*
* @param {*} a
* @param {*} b
* @return {Boolean}
*/
function looseEqual(a, b) {
/* eslint-disable eqeqeq */
return a == b || (isObject(a) && isObject(b) ? JSON.stringify(a) === JSON.stringify(b) : false);
/* eslint-enable eqeqeq */
}
var hasProto = ('__proto__' in {});
// Browser environment sniffing
var inBrowser = typeof window !== 'undefined' && Object.prototype.toString.call(window) !== '[object Object]';
// detect devtools
var devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__;
// UA sniffing for working around browser-specific quirks
var UA = inBrowser && window.navigator.userAgent.toLowerCase();
var isIE9 = UA && UA.indexOf('msie 9.0') > 0;
var isAndroid = UA && UA.indexOf('android') > 0;
var isIos = UA && /(iphone|ipad|ipod|ios)/i.test(UA);
var isWechat = UA && UA.indexOf('micromessenger') > 0;
var transitionProp = undefined;
var transitionEndEvent = undefined;
var animationProp = undefined;
var animationEndEvent = undefined;
// Transition property/event sniffing
if (inBrowser && !isIE9) {
var isWebkitTrans = window.ontransitionend === undefined && window.onwebkittransitionend !== undefined;
var isWebkitAnim = window.onanimationend === undefined && window.onwebkitanimationend !== undefined;
transitionProp = isWebkitTrans ? 'WebkitTransition' : 'transition';
transitionEndEvent = isWebkitTrans ? 'webkitTransitionEnd' : 'transitionend';
animationProp = isWebkitAnim ? 'WebkitAnimation' : 'animation';
animationEndEvent = isWebkitAnim ? 'webkitAnimationEnd' : 'animationend';
}
/**
* Defer a task to execute it asynchronously. Ideally this
* should be executed as a microtask, so we leverage
* MutationObserver if it's available, and fallback to
* setTimeout(0).
*
* @param {Function} cb
* @param {Object} ctx
*/
var nextTick = (function () {
var callbacks = [];
var pending = false;
var timerFunc;
function nextTickHandler() {
pending = false;
var copies = callbacks.slice(0);
callbacks = [];
for (var i = 0; i < copies.length; i++) {
copies[i]();
}
}
/* istanbul ignore if */
if (typeof MutationObserver !== 'undefined' && !(isWechat && isIos)) {
var counter = 1;
var observer = new MutationObserver(nextTickHandler);
var textNode = document.createTextNode(counter);
observer.observe(textNode, {
characterData: true
});
timerFunc = function () {
counter = (counter + 1) % 2;
textNode.data = counter;
};
} else {
// webpack attempts to inject a shim for setImmediate
// if it is used as a global, so we have to work around that to
// avoid bundling unnecessary code.
var context = inBrowser ? window : typeof global !== 'undefined' ? global : {};
timerFunc = context.setImmediate || setTimeout;
}
return function (cb, ctx) {
var func = ctx ? function () {
cb.call(ctx);
} : cb;
callbacks.push(func);
if (pending) return;
pending = true;
timerFunc(nextTickHandler, 0);
};
})();
var _Set = undefined;
/* istanbul ignore if */
if (typeof Set !== 'undefined' && Set.toString().match(/native code/)) {
// use native Set when available.
_Set = Set;
} else {
// a non-standard Set polyfill that only works with primitive keys.
_Set = function () {
this.set = Object.create(null);
};
_Set.prototype.has = function (key) {
return this.set[key] !== undefined;
};
_Set.prototype.add = function (key) {
this.set[key] = 1;
};
_Set.prototype.clear = function () {
this.set = Object.create(null);
};
}
function Cache(limit) {
this.size = 0;
this.limit = limit;
this.head = this.tail = undefined;
this._keymap = Object.create(null);
}
var p = Cache.prototype;
/**
* Put into the cache associated with .
* Returns the entry which was removed to make room for
* the new entry. Otherwise undefined is returned.
* (i.e. if there was enough room already).
*
* @param {String} key
* @param {*} value
* @return {Entry|undefined}
*/
p.put = function (key, value) {
var removed;
if (this.size === this.limit) {
removed = this.shift();
}
var entry = this.get(key, true);
if (!entry) {
entry = {
key: key
};
this._keymap[key] = entry;
if (this.tail) {
this.tail.newer = entry;
entry.older = this.tail;
} else {
this.head = entry;
}
this.tail = entry;
this.size++;
}
entry.value = value;
return removed;
};
/**
* Purge the least recently used (oldest) entry from the
* cache. Returns the removed entry or undefined if the
* cache was empty.
*/
p.shift = function () {
var entry = this.head;
if (entry) {
this.head = this.head.newer;
this.head.older = undefined;
entry.newer = entry.older = undefined;
this._keymap[entry.key] = undefined;
this.size--;
}
return entry;
};
/**
* Get and register recent use of . Returns the value
* associated with or undefined if not in cache.
*
* @param {String} key
* @param {Boolean} returnEntry
* @return {Entry|*}
*/
p.get = function (key, returnEntry) {
var entry = this._keymap[key];
if (entry === undefined) return;
if (entry === this.tail) {
return returnEntry ? entry : entry.value;
}
// HEAD--------------TAIL
// <.older .newer>
// <--- add direction --
// A B C E
if (entry.newer) {
if (entry === this.head) {
this.head = entry.newer;
}
entry.newer.older = entry.older; // C <-- E.
}
if (entry.older) {
entry.older.newer = entry.newer; // C. --> E
}
entry.newer = undefined; // D --x
entry.older = this.tail; // D. --> E
if (this.tail) {
this.tail.newer = entry; // E. <-- D
}
this.tail = entry;
return returnEntry ? entry : entry.value;
};
var cache$1 = new Cache(1000);
var filterTokenRE = /[^\s'"]+|'[^']*'|"[^"]*"/g;
var reservedArgRE = /^in$|^-?\d+/;
/**
* Parser state
*/
var str;
var dir;
var c;
var prev;
var i;
var l;
var lastFilterIndex;
var inSingle;
var inDouble;
var curly;
var square;
var paren;
/**
* Push a filter to the current directive object
*/
function pushFilter() {
var exp = str.slice(lastFilterIndex, i).trim();
var filter;
if (exp) {
filter = {};
var tokens = exp.match(filterTokenRE);
filter.name = tokens[0];
if (tokens.length > 1) {
filter.args = tokens.slice(1).map(processFilterArg);
}
}
if (filter) {
(dir.filters = dir.filters || []).push(filter);
}
lastFilterIndex = i + 1;
}
/**
* Check if an argument is dynamic and strip quotes.
*
* @param {String} arg
* @return {Object}
*/
function processFilterArg(arg) {
if (reservedArgRE.test(arg)) {
return {
value: toNumber(arg),
dynamic: false
};
} else {
var stripped = stripQuotes(arg);
var dynamic = stripped === arg;
return {
value: dynamic ? arg : stripped,
dynamic: dynamic
};
}
}
/**
* Parse a directive value and extract the expression
* and its filters into a descriptor.
*
* Example:
*
* "a + 1 | uppercase" will yield:
* {
* expression: 'a + 1',
* filters: [
* { name: 'uppercase', args: null }
* ]
* }
*
* @param {String} s
* @return {Object}
*/
function parseDirective(s) {
var hit = cache$1.get(s);
if (hit) {
return hit;
}
// reset parser state
str = s;
inSingle = inDouble = false;
curly = square = paren = 0;
lastFilterIndex = 0;
dir = {};
for (i = 0, l = str.length; i < l; i++) {
prev = c;
c = str.charCodeAt(i);
if (inSingle) {
// check single quote
if (c === 0x27 && prev !== 0x5C) inSingle = !inSingle;
} else if (inDouble) {
// check double quote
if (c === 0x22 && prev !== 0x5C) inDouble = !inDouble;
} else if (c === 0x7C && // pipe
str.charCodeAt(i + 1) !== 0x7C && str.charCodeAt(i - 1) !== 0x7C) {
if (dir.expression == null) {
// first filter, end of expression
lastFilterIndex = i + 1;
dir.expression = str.slice(0, i).trim();
} else {
// already has filter
pushFilter();
}
} else {
switch (c) {
case 0x22:
inDouble = true;break; // "
case 0x27:
inSingle = true;break; // '
case 0x28:
paren++;break; // (
case 0x29:
paren--;break; // )
case 0x5B:
square++;break; // [
case 0x5D:
square--;break; // ]
case 0x7B:
curly++;break; // {
case 0x7D:
curly--;break; // }
}
}
}
if (dir.expression == null) {
dir.expression = str.slice(0, i).trim();
} else if (lastFilterIndex !== 0) {
pushFilter();
}
cache$1.put(s, dir);
return dir;
}
var directive = Object.freeze({
parseDirective: parseDirective
});
var regexEscapeRE = /[-.*+?^${}()|[\]\/\\]/g;
var cache = undefined;
var tagRE = undefined;
var htmlRE = undefined;
/**
* Escape a string so it can be used in a RegExp
* constructor.
*
* @param {String} str
*/
function escapeRegex(str) {
return str.replace(regexEscapeRE, '\\$&');
}
function compileRegex() {
var open = escapeRegex(config.delimiters[0]);
var close = escapeRegex(config.delimiters[1]);
var unsafeOpen = escapeRegex(config.unsafeDelimiters[0]);
var unsafeClose = escapeRegex(config.unsafeDelimiters[1]);
tagRE = new RegExp(unsafeOpen + '((?:.|\\n)+?)' + unsafeClose + '|' + open + '((?:.|\\n)+?)' + close, 'g');
htmlRE = new RegExp('^' + unsafeOpen + '.*' + unsafeClose + '$');
// reset cache
cache = new Cache(1000);
}
/**
* Parse a template text string into an array of tokens.
*
* @param {String} text
* @return {Array