p+e-q&&tk&&tk+o-i?e+K(10,r):tn&&(f=n-r),f!==e)){a.fixedWidth=r;if(!u.ordinalPositions)u.fixedRange=u.max-u.min;e=c.translate(f,!0);u.setExtremes(e,u.fixedRange?e+u.fixedRange:
c.translate(f+r,!0),!0,!1,{trigger:"navigator"})}d.type==="touchstart"&&d.preventDefault()};a.mouseMoveHandler=function(c){var d=a.scrollbarHeight,e=a.navigatorLeft,f=a.navigatorWidth,g=a.scrollerLeft,h=a.scrollerWidth,i=a.range;if(c.pageX!==0)c=b.tracker.normalizeMouseEvent(c),c=c.chartX,cg+h-d&&(c=g+h-d),a.grabbedLeft?(k=!0,a.render(0,0,c-e,a.otherHandlePos)):a.grabbedRight?(k=!0,a.render(0,0,a.otherHandlePos,c-e)):a.grabbedCenter&&(k=!0,cf+j-i&&(c=f+j-i),a.render(0,0,c-j,c-j+
i))};a.mouseUpHandler=function(){var d=a.zoomedMin,e=a.zoomedMax;k&&b.xAxis[0].setExtremes(c.translate(d,!0),c.translate(e,!0),!0,!1,{trigger:"navigator"});a.grabbedLeft=a.grabbedRight=a.grabbedCenter=k=j=null;l.cursor=m||""};a.updatedDataHandler=function(){var c=o.xAxis,d=c.getExtremes(),e=d.min,f=d.max,g=d.dataMin,d=d.dataMax,h=f-e,j,k,l,m,n;j=i.xData;var q=!!c.setExtremes;k=f>=j[j.length-1];j=e<=g;if(!p)i.options.pointStart=o.xData[0],i.setData(o.options.data,!1),n=!0;j&&(m=g,l=m+h);k&&(l=d,j||
(m=w(l-h,i.xData[0])));q&&(j||k)?c.setExtremes(m,l,!0,!1,{trigger:"updatedData"}):(n&&b.redraw(!1),a.render(w(e,g),K(f,d)))};var n=b.xAxis.length,q=b.yAxis.length,s=b.setSize;b.extraBottomMargin=a.outlineHeight+f.margin;a.top=h=a.getAxisTop(b.chartHeight);if(a.navigatorEnabled){var v=o?o.options:{},u=v.data,x=f.series;p=x.data;v.data=x.data=null;a.xAxis=c=new Ta(b,z({ordinal:o&&o.xAxis.options.ordinal},f.xAxis,{isX:!0,type:"datetime",index:n,height:g,top:h,offset:0,offsetLeft:e,offsetRight:-e,startOnTick:!1,
endOnTick:!1,minPadding:0,maxPadding:0,zoomEnabled:!1}));a.yAxis=d=new Ta(b,z(f.yAxis,{alignTicks:!1,height:g,top:h,offset:0,index:q,zoomEnabled:!1}));n=z(v,x,{threshold:null,clip:!1,enableMouseTracking:!1,group:"nav",padXAxis:!1,xAxis:n,yAxis:q,name:"Navigator",showInLegend:!1,isInternal:!0,visible:!0});v.data=u;x.data=p;n.data=p||u;i=b.initSeries(n);f.adaptToUpdatedData!==!1&&C(o,"updatedData",a.updatedDataHandler)}else a.xAxis=c={translate:function(a,c){var d=b.xAxis[0].getExtremes(),f=b.plotWidth-
2*e,g=d.dataMin,d=d.dataMax-g;return c?a*d/f+g:f*(a-g)/d}};a.series=i;b.setSize=function(e,f,g){a.top=h=a.getAxisTop(f);if(c&&d)c.options.top=d.options.top=h;s.call(b,e,f,g)};a.addEvents()},destroy:function(){this.removeEvents();q([this.xAxis,this.yAxis,this.leftShade,this.rightShade,this.outline,this.scrollbarTrack,this.scrollbarRifles,this.scrollbarGroup,this.scrollbar],function(a){a&&a.destroy&&a.destroy()});this.xAxis=this.yAxis=this.leftShade=this.rightShade=this.outline=this.scrollbarTrack=
this.scrollbarRifles=this.scrollbarGroup=this.scrollbar=null;q([this.scrollbarButtons,this.handles,this.elementsToDestroy],function(a){ta(a)})}};Highcharts.Scroller=Sb;tb(Ta.prototype,"zoom",function(a,b,c){var d=this.chart,e=d.options,f=e.chart.zoomType,g=e.navigator,e=e.rangeSelector,h;if(this.isXAxis&&(g&&g.enabled||e&&e.enabled))if(f==="x")d.resetZoomButton="blocked";else if(f==="y")h=!1;else if(f==="xy")d=this.previousZoom,s(b)?this.previousZoom=[this.min,this.max]:d&&(b=d[0],c=d[1],delete this.previousZoom);
return h!==v?h:a.call(this,b,c)});y(P,{rangeSelector:{buttonTheme:{width:28,height:16,padding:1,r:0,zIndex:7},inputPosition:{align:"right"},labelStyle:{color:"#666"}}});P.lang=z(P.lang,{rangeSelectorZoom:"Zoom",rangeSelectorFrom:"From",rangeSelectorTo:"To"});Tb.prototype={clickButton:function(a,b,c){var d=this,e=d.chart,f=d.buttons,g=e.xAxis[0],h=g&&g.getExtremes(),i=e.scroller&&e.scroller.xAxis,j=i&&i.getExtremes&&i.getExtremes(),i=j&&j.dataMin,j=j&&j.dataMax,k=h&&h.dataMin,l=h&&h.dataMax,i=(s(k)&&
s(i)?K:n)(k,i),j=(s(l)&&s(j)?w:n)(l,j),m,o=g&&K(h.max,j),h=new Date(o),l=b.type,k=b.count,p,q,r={millisecond:1,second:1E3,minute:6E4,hour:36E5,day:864E5,week:6048E5};if(!(i===null||j===null||a===d.selected))r[l]?(p=r[l]*k,m=w(o-p,i)):l==="month"?(h.setMonth(h.getMonth()-k),m=w(h.getTime(),i),p=2592E6*k):l==="ytd"?(h=new Date(j),q=h.getFullYear(),m=q=w(i||0,Date.UTC(q,0,1)),h=h.getTime(),o=K(j||h,h)):l==="year"?(h.setFullYear(h.getFullYear()-k),m=w(i,h.getTime()),p=31536E6*k):l==="all"&&g&&(m=i,o=
j),f[a]&&f[a].setState(2),g?setTimeout(function(){g.setExtremes(m,o,n(c,1),0,{trigger:"rangeSelectorButton",rangeSelectorButton:b});d.selected=a},1):(e=e.options.xAxis,e[0]=z(e[0],{range:p,min:q}),d.selected=a)},defaultButtons:[{type:"month",count:1,text:"1m"},{type:"month",count:3,text:"3m"},{type:"month",count:6,text:"6m"},{type:"ytd",text:"YTD"},{type:"year",count:1,text:"1y"},{type:"all",text:"All"}],init:function(a){var b=this,c=a.options.rangeSelector,d=c.buttons||[].concat(b.defaultButtons),
e=b.buttons=[],c=c.selected,f=b.blurInputs=function(){var a=b.minInput,c=b.maxInput;a&&a.blur();c&&c.blur()};b.chart=a;a.extraTopMargin=25;b.buttonOptions=d;C(a.container,"mousedown",f);C(a,"resize",f);c!==v&&d[c]&&this.clickButton(c,d[c],!1);C(a,"load",function(){C(a.xAxis[0],"afterSetExtremes",function(){if(this.fixedRange!==this.max-this.min)e[b.selected]&&!a.renderer.forExport&&e[b.selected].setState(0),b.selected=null;this.fixedRange=null})})},setInputValue:function(a,b){var c=this.chart.options.rangeSelector;
if(b)this[a+"Input"].HCTime=b;this[a+"Input"].value=xa(c.inputEditDateFormat||"%Y-%m-%d",this[a+"Input"].HCTime);this[a+"DateBox"].attr({text:xa(c.inputDateFormat||"%b %e, %Y",this[a+"Input"].HCTime)})},drawInput:function(a){var b=this,c=b.chart,d=c.options.chart.style,e=c.renderer,f=c.options.rangeSelector,g=b.div,h=a==="min",i,j,k,l=this.inputGroup;this[a+"Label"]=j=e.label(P.lang[h?"rangeSelectorFrom":"rangeSelectorTo"],this.inputGroup.offset).attr({padding:1}).css(z(d,f.labelStyle)).add(l);l.offset+=
j.width+5;this[a+"DateBox"]=k=e.label("",l.offset).attr({padding:1,width:90,height:16,stroke:"silver","stroke-width":1}).css(z({textAlign:"center"},d,f.inputStyle)).on("click",function(){b[a+"Input"].focus()}).add(l);l.offset+=k.width+(h?10:0);this[a+"Input"]=i=X("input",{name:a,className:"highcharts-range-selector",type:"text"},y({position:"absolute",border:"2px solid silver",top:"-9999em",textAlign:"center",fontSize:d.fontSize,fontFamily:d.fontFamily},f.inputStyle),g);i.onfocus=function(){H(this,
{left:l.translateX+k.x+"px",top:l.translateY+"px",width:k.width-2+"px",height:k.height-2+"px"})};i.onblur=function(){H(this,{top:"-9999em"});b.setInputValue(a)};i.onchange=function(){var a=i.value,d=Date.parse(a),e=c.xAxis[0].getExtremes();isNaN(d)&&(d=a.split("-"),d=Date.UTC(A(d[0]),A(d[1])-1,A(d[2])));if(!isNaN(d)&&(h&&d>=e.dataMin&&d<=b.maxInput.HCTime||!h&&d<=e.dataMax&&d>=b.minInput.HCTime))c.xAxis[0].setExtremes(h?d:e.min,h?e.max:d,v,v,{trigger:"rangeSelectorInput"})}},render:function(a,b){var c=
this,d=c.chart,e=d.renderer,f=d.container,g=d.options,h=g.exporting&&d.options.navigation.buttonOptions,i=g.rangeSelector,j=c.buttons,k=P.lang,l=c.div,l=c.inputGroup,m=i.buttonTheme,o=i.inputEnabled!==!1,n=m&&m.states,t=d.plotLeft,r;if(!c.rendered&&(c.zoomText=e.text(k.rangeSelectorZoom,t,d.plotTop-10).css(i.labelStyle).add(),r=t+c.zoomText.getBBox().width+5,q(c.buttonOptions,function(a,b){j[b]=e.button(a.text,r,d.plotTop-25,function(){c.clickButton(b,a);c.isActive=!0},m,n&&n.hover,n&&n.select).css({textAlign:"center"}).add();
r+=j[b].width+(i.buttonSpacing||0);c.selected===b&&j[b].setState(2)}),o))c.div=l=X("div",null,{position:"relative",height:0,zIndex:1}),f.parentNode.insertBefore(l,f),c.inputGroup=l=e.g("input-group").add(),l.offset=0,c.drawInput("min"),c.drawInput("max");o&&(f=d.plotTop-35,l.align(y({y:f,width:l.offset,x:h&&f=e){this.compareValue=c[a];break}};za.prototype.tooltipFormatter=function(a){a=a.replace("{point.change}",(this.change>0?"+":"")+Qa(this.change,this.series.tooltipOptions.changeDecimals||2));return mc.apply(this,[a])};(function(){var a=T.init,b=T.getSegments;T.init=function(){var b,d;a.apply(this,arguments);b=this.chart;(d=this.xAxis)&&
d.options.ordinal&&C(this,"updatedData",function(){delete d.ordinalIndex});if(d&&d.options.ordinal&&!d.hasOrdinalExtension){d.hasOrdinalExtension=!0;d.beforeSetTickPositions=function(){var a,b=[],c=!1,e,j=this.getExtremes(),k=j.min,j=j.max,l;if(this.options.ordinal){q(this.series,function(c,d){if(c.visible!==!1&&c.takeOrdinalPosition!==!1&&(b=b.concat(c.processedXData),a=b.length,d&&a)){b.sort(function(a,b){return a-b});for(d=a-1;d--;)b[d]===b[d+1]&&b.splice(d,1)}});a=b.length;if(a>2){e=b[1]-b[0];
for(l=a-1;l--&&!c;)b[l+1]-b[l]!==e&&(c=!0)}c?(this.ordinalPositions=b,c=d.val2lin(k,!0),e=d.val2lin(j,!0),this.ordinalSlope=j=(j-k)/(e-c),this.ordinalOffset=k-c*j):this.ordinalPositions=this.ordinalSlope=this.ordinalOffset=v}};d.val2lin=function(a,b){var c=this.ordinalPositions;if(c){var d=c.length,e,k;for(e=d;e--;)if(c[e]===a){k=e;break}for(e=d-1;e--;)if(a>c[e]||e===0){c=(a-c[e])/(c[e+1]-c[e]);k=e+c;break}return b?k:this.ordinalSlope*(k||0)+this.ordinalOffset}else return a};d.lin2val=function(a,
b){var c=this.ordinalPositions;if(c){var d=this.ordinalSlope,e=this.ordinalOffset,k=c.length-1,l,m;if(b)a<0?a=c[0]:a>k?a=c[k]:(k=W(a),m=a-k);else for(;k--;)if(l=d*k+e,a>=l){d=d*(k+1)+e;m=(a-l)/(d-l);break}return m!==v&&c[k]!==v?c[k]+(m?m*(c[k+1]-c[k]):0):a}else return a};d.getExtendedPositions=function(){var a=d.series[0].currentDataGrouping,e=d.ordinalIndex,h=a?a.count+a.unitName:"raw",i=d.getExtremes(),j,k;if(!e)e=d.ordinalIndex={};if(!e[h])j={series:[],getExtremes:function(){return{min:i.dataMin,
max:i.dataMax}},options:{ordinal:!0}},q(d.series,function(d){k={xAxis:j,xData:d.xData,chart:b,destroyGroupedData:db};k.options={dataGrouping:a?{enabled:!0,forced:!0,approximation:"open",units:[[a.unitName,[a.count]]]}:{enabled:!1}};d.processData.apply(k);j.series.push(k)}),d.beforeSetTickPositions.apply(j),e[h]=j.ordinalPositions;return e[h]};d.getGroupIntervalFactor=function(a,b,c){for(var d=0,e=c.length,k=[];dc;j[o]k*5||x)n=Ya(a,j[m],j[o],e),u=u.concat(n),m=o+1;if(x)break}a=n.info;if(l&&a.unitRange<=G[ra]){o=u.length-1;for(m=1;mc?a-1:a;for(y=void 0;l--;)m=o[l],c=y-m,y&&c1)o&&q(o,function(a){a.setState()}),i<0?(o=t,t=d.ordinalPositions?d:t):o=d.ordinalPositions?d:t,r=t.ordinalPositions,k>r[r.length-1]&&r.push(k),o=n.apply(o,[s.apply(o,[l,!0])+i,!0]),i=n.apply(t,[s.apply(t,[m,!0])+i,!0]),o>K(j.dataMin,l)&&ia.xAxis.closestPointRange*e&&d.splice(g+1,0,b.splice(h+1,b.length-h))})}})();y(Highcharts,{Axis:Ta,CanVGRenderer:rb,Chart:bb,Color:ya,Legend:Db,MouseTracker:Cb,Point:za,Tick:ab,Tooltip:Bb,Renderer:Ua,Series:V,SVGRenderer:oa,VMLRenderer:Na,arrayMin:Ha,arrayMax:sa,charts:Va,dateFormat:xa,pathAnim:Fb,getOptions:function(){return P},
hasBidiBug:bc,isTouchDevice:nb,numberFormat:Qa,seriesTypes:R,setOptions:function(a){P=z(P,a);Qb();return P},addEvent:C,removeEvent:O,createElement:X,discardElement:Sa,css:H,each:q,extend:y,map:Ma,merge:z,pick:n,splat:ka,extendClass:$,pInt:A,wrap:tb,svg:ja,canvas:aa,vml:!ja&&!aa,product:"Highstock",version:"1.2.5"})})();
/**
* @author Alex Shpak #Winterly
* http://winterly.net
*/
(function($)
{
var cache = {};
$.str = function(token)
{
return cache[token] ? cache[token] : token;
}
$.fn.locale = function(options)
{
options = $.extend(
{
selector:"div, span",
key:"token",
load:undefined
}, options);
this.find(options.selector).each(function(index, element)
{
element = $(element);
cache[element.attr(options.key)] = element.html();
});
if(options.load)
options.load();
};
})(jQuery);/**
* @author Alex Shpak #Winterly
* http://winterly.net
*/
(function($)
{
$.fn.mini = function(options)
{
options = $.extend(
{
limits:
[
{width:1024, hide:".no-mobile", show:".mobile", addClass:"mini"},
{width:512, addClass:"micro"},
],
//hideInMini:".no-mobile",
//showwInMini:".mobile",
//addClass:"mini",
//width:1024,
runNow:true,
callback:undefined
}, options);
var bind = this;
$(window).resize(function()
{
for(var limit in options.limits)
{
limit = options.limits[limit];
if($(this).width() <= limit.width)
{
if(limit.hide) bind.find(limit.hide).hide();
if(limit.show) bind.find(limit.show).show();
if(limit.addClass) bind.addClass(limit.addClass);
}
else
{
if(limit.hide) bind.find(limit.hide).show();
if(limit.show) bind.find(limit.show).hide();
if(limit.addClass) bind.removeClass(limit.addClass);
}
}
if(options.callback)
options.callback();
});
if(options.runNow)
$(window).trigger("resize");
};
})(jQuery);/**
* @author Alex Shpak #Winterly
* http://winterly.net
*/
(function($)
{
$.fn.search = function(options)
{
options = $.extend(
{
keys:[],
row:".search",
root:"body",
show:function()
{
this.show();
},
hide:function()
{
this.hide();
}
}, options);
var root = $(options.root);
this.keyup(function()
{
var searchText = $(this).val().toLowerCase();
root.find(options.row).each(function(index, element)
{
element = $(element);
var valuelist = [];
for(var key in options.keys)
{
var type = options.keys[key];
switch(type)
{
case "text":
valuelist.push(element.children(key).text());
break;
case "input":
valuelist.push(element.find(key + " input").val());
break;
case "select":
valuelist.push(element.find(key+" option:selected").text());
break;
default:
valuelist.push(element.find(key+" "+type).text());
break;
}
}
for(var valkey in valuelist)
if(valuelist[valkey].toLowerCase().contains(searchText))
{
options.show.call(element);
return;
}
options.hide.call(element);
});
});
};
})(jQuery);/**
* @author Alex Shpak #Winterly
* http://winterly.net
*/
(function($)
{
$.storage =
{
storage:{},
set:function(name, value)
{
$.cookie(name, value, {expires : 365, path:"/", secure:false});
},
get:function(name, def)
{
try
{
var c = $.cookie(name);
if (c === null || c === undefined)
return def;
return c;
}
catch(e){return def;}
},
saveObject:function(name, object)
{
this.set(name, $.toJSON(object));
},
getObject:function(name, def)
{
return $.parseJSON(this.get(name, def));
},
setField:function(set, name, value)
{
var object = this.getObject(set, "{}");
object[name] = value;
this.saveObject(set, object);
},
setFields:function(set, list)
{
for(var f in list)
this.setField(set, f, list[f]);
},
getField:function(set, name, def)
{
var val = this.getObject(set, "{}")[name];
return val===undefined?def:val;
}
};
})(jQuery);
/*
* jQuery timepicker addon
* By: Trent Richardson [http://trentrichardson.com]
* Version 1.3
* Last Modified: 05/05/2013
*
* Copyright 2013 Trent Richardson
* You may use this project under MIT or GPL licenses.
* http://trentrichardson.com/Impromptu/GPL-LICENSE.txt
* http://trentrichardson.com/Impromptu/MIT-LICENSE.txt
*/
/*jslint evil: true, white: false, undef: false, nomen: false */
(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.3"
}
});
/*
* 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,
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,
onSelect: null,
hourGrid: 0,
minuteGrid: 0,
secondGrid: 0,
millisecGrid: 0,
microsecGrid: 0,
alwaysSetTime: true,
separator: ' ',
altFieldTimeOnly: true,
altTimeFormat: null,
altSeparator: null,
altTimeSuffix: null,
pickerTimeFormat: null,
pickerTimeSuffix: null,
showTimepicker: true,
timezoneList: null,
addSliderAccess: false,
sliderAccessArgs: null,
controlType: 'slider',
defaultValue: null,
parse: 'strict'
};
$.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,
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 settings object - the new settings to use as defaults (anonymous object)
* @return the manager object
*/
setDefaults: function(settings) {
extendRemove(this._defaults, settings || {});
return this;
},
/*
* Create a new Timepicker instance
*/
_newInst: function($input, o) {
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] = o[i] || null;
}
}
tp_inst._defaults = $.extend({}, this._defaults, inlineSettings, o, 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(jQuery.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 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 (o.altField) {
tp_inst.$altInput = $(o.altField).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 = (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();
},
/*
* 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;
}
},
/*
* 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 = ' style="display:none;"',
html = '' + '- ' + o.timeText + '
' +
'';
// Create the markup
for(i=0,l=this.units.length; i' + 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('');
$dp.find('.ui-datepicker-header, .ui-datepicker-calendar').hide();
}
// add sliders, adjust grids, add events
for(i=0,l=tp_inst.units.length; i 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();
});
// 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');
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
}
},
/*
* 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 (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 });
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 });
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 });
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 });
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 });
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() {
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);
}
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 != this.hour || minute != this.minute || second != this.second || millisec != this.millisec || microsec != this.microsec
|| (this.ampm.length > 0 && (hour < 12) != ($.inArray(this.ampm.toUpperCase(), this.amNames) !== -1))
|| (this.timezone !== null && timezone != this.timezone));
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) {
if(pickerTimeFormat === o.timeFormat){
this.$timeObj.text(this.formattedTime + pickerTimeSuffix);
}
else{
this.$timeObj.text($.datepicker.formatTime(pickerTimeFormat, this, o) + pickerTimeSuffix);
}
}
this.timeDefined = true;
if (hasChanged) {
this._updateDateTime();
}
},
/*
* 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 dt = $.datepicker._daylightSavingAdjust(new Date(dp_inst.selectedYear, dp_inst.selectedMonth, dp_inst.selectedDay)),
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) {
formattedDateTime = this.formattedTime;
} else if (this._defaults.timeOnly !== true && (this._defaults.alwaysSetTime || timeAvailable)) {
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 ? this._defaults.altSeparator : this._defaults.separator,
altTimeSuffix = this._defaults.altTimeSuffix ? 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){
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();
});
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 || $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') {
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);
parseRex.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(), o.amNames) !== -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
* format = string format of the time
* time = a {}, not a Date() for timezones
* options = essentially the regional[].. amNames, pmNames, ampm
*/
$.datepicker.formatTime = function(format, time, options) {
options = options || {};
options = $.extend({}, $.timepicker._defaults, options);
time = $.extend({
hour: 0,
minute: 0,
second: 0,
millisec: 0,
timezone: 0
}, 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, "") || "'";
}
});
tmptime = $.trim(tmptime);
return tmptime;
};
/*
* the bad hack :/ override datepicker so it doesnt 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');
if (tp_inst) {
tp_inst._limitMinMaxDateTime(inst, true);
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 = 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
*/
$.datepicker._base_updateAlternate = $.datepicker._updateAlternate;
/* Update any alternate field to synchronise with the main field. */
$.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(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.
*/
$.datepicker._base_gotoToday = $.datepicker._gotoToday;
$.datepicker._gotoToday = function(id) {
var inst = this._getInst($(id)[0]),
$dp = inst.dpDiv;
this._base_gotoToday(id);
var tp_inst = this._get(inst, 'timepicker');
selectLocalTimezone(tp_inst);
var now = new Date();
this._setTime(inst, now);
$('.ui-datepicker-today', $dp).click();
};
/*
* 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) {
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) {
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());
}
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);
if (!inst) {
return;
}
var tp_inst = this._get(inst, 'timepicker'),
tp_date = (date instanceof Date) ? new Date(date.getTime()) : 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_inst.timezone != null){
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);
if (date && tp_inst._parseTime($(target).val(), tp_inst.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){
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;
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;
}
}
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(obj)) {
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('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) {
if (hour > 12) {
hour = hour - 12;
}
if (hour === 0) {
hour = 12;
}
return String(hour);
};
/*
* Splits datetime string into date ans time substrings.
* Throws exception when date can't be parsed
* Returns [dateString, timeString]
*/
var splitDateTime = function(dateFormat, dateTimeString, dateSettings, timeSettings) {
try {
// The idea is to get the number separator occurances 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 = timeSettings && timeSettings.separator ? timeSettings.separator : $.timepicker._defaults.separator,
format = timeSettings && timeSettings.timeFormat ? timeSettings.timeFormat : $.timepicker._defaults.timeFormat,
timeParts = format.split(separator), // how many occurances of separator may be in our format?
timePartsLen = timeParts.length,
allParts = dateTimeString.split(separator),
allPartsLen = allParts.length;
if (allPartsLen > 1) {
return [
allParts.splice(0,allPartsLen-timePartsLen).join(separator),
allParts.splice(0,timePartsLen).join(separator)
];
}
} catch (err) {
$.timepicker.log('Could not split the date from the time. Please check the following datetimepicker options' +
"\nthrown error: " + err +
"\ndateTimeString" + dateTimeString +
"\ndateFormat = " + dateFormat +
"\nseparator = " + timeSettings.separator +
"\ntimeFormat = " + timeSettings.timeFormat);
if (err.indexOf(":") >= 0) {
// 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.
var dateStringLength = dateTimeString.length - (err.length - err.indexOf(':') - 2),
timeString = dateTimeString.substring(dateStringLength);
return [$.trim(dateTimeString.substring(0, dateStringLength)), $.trim(dateTimeString.substring(dateStringLength))];
} else {
throw err;
}
}
return [dateTimeString, ''];
};
/*
* 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;
var splitRes = splitDateTime(dateFormat, dateTimeString, dateSettings, timeSettings);
date = $.datepicker._base_parseDate(dateFormat, splitRes[0], dateSettings);
if (splitRes[1] !== '') {
var timeString = splitRes[1],
parsedTime = $.datepicker.parseTime(timeFormat, timeString, timeSettings);
if (parsedTime === null) {
throw 'Wrong time format';
}
return {
date: date,
timeObj: parsedTime
};
} else {
return {
date: date
};
}
};
/*
* 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 = typeof date !== 'undefined' ? date : new Date();
tp_inst.timezone_select.val(now.getTimezoneOffset()*-1);
}
};
/*
* Create a Singleton Insance
*/
$.timepicker = new Timepicker();
/**
* Get the timezone offset as string from a date object (eg '+0530' for UTC+5.5)
* @param number if not a number this value is returned
* @param boolean if true formats in accordance to iso8601 "+12:45"
* @return string
*/
$.timepicker.timezoneOffsetString = function(tzMinutes, iso8601) {
if(isNaN(tzMinutes) || tzMinutes > 840){
return tzMinutes;
}
var off = tzMinutes,
minutes = off % 60,
hours = (off - minutes) / 60,
iso = iso8601? ':':'',
tz = (off >= 0 ? '+' : '-') + ('0' + (hours * 101).toString()).slice(-2) + iso + ('0' + (minutes * 101).toString()).slice(-2);
if(tz == '+00:00'){
return 'Z';
}
return tz;
};
/**
* Get the number in minutes that represents a timezone string
* @param string formated like "+0500", "-1245"
* @return number
*/
$.timepicker.timezoneOffsetNumber = function(tzString) {
tzString = tzString.toString().replace(':',''); // excuse any iso8601, end up with "+1245"
if(tzString.toUpperCase() === 'Z'){ // if iso8601 with Z, its 0 minute offset
return 0;
}
if(!/^(\-|\+)\d{4}$/.test(tzString)){ // possibly a user defined tz, so just give it back
return tzString;
}
return ((tzString.substr(0,1) =='-'? -1 : 1) * // plus or minus
((parseInt(tzString.substr(1,2),10)*60) + // hours (converted to minutes)
parseInt(tzString.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
* @param string formated like "+0500", "-1245"
* @return date
*/
$.timepicker.timezoneAdjust = function(date, toTimezone) {
var toTz = $.timepicker.timezoneOffsetNumber(toTimezone);
if(!isNaN(toTz)){
var currTz = date.getTimezoneOffset()*-1,
diff = currTz - toTz; // difference in minutes
date.setMinutes(date.getMinutes()+diff);
}
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 obj 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 obj 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 `method` on the `startTime` and `endTime` elements, and configures them to
* enforce date range limits.
* @param Element startTime
* @param Element endTime
* @param obj 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 obj 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);
$.fn[method].call(startTime, $.extend({
onClose: function(dateText, inst) {
checkDates($(this), endTime);
},
onSelect: function(selectedDateTime) {
selected($(this), endTime, 'minDate');
}
}, options, options.start));
$.fn[method].call(endTime, $.extend({
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');
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);
}
}
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(err){
if(window.console){
console.log(err);
}
};
/*
* Rough microsecond support
*/
if(!Date.prototype.getMicroseconds){
Date.microseconds = 0;
Date.prototype.getMicroseconds = function(){ return this.microseconds; };
Date.prototype.setMicroseconds = function(m){ this.microseconds = m; return this; };
}
/*
* Keep up with the version
*/
$.timepicker.version = "1.3";
})(jQuery);(function($)
{
$.isTouch = function()
{
try
{
document.createEvent("TouchEvent");
return true;
}
catch (e)
{
return false;
}
}
$.fn.touchscroll = function()
{
if($.isTouch())
{
this.each(function(index, element)
{
var X = 0, Y = 0;
element.addEventListener("touchstart", function(event)
{
X = this.scrollLeft() + event.touches[0].pageX;
Y = this.scrollTop() + event.touches[0].pageY;
event.stopPropagation();
event.preventDefault();
}, false);
element.addEventListener("touchmove", function(event)
{
this.scrollLeft(X - event.touches[0].pageX);
this.scrollTop(Y - event.touches[0].pageY);
event.stopPropagation();
event.preventDefault();
}, false);
});
}
}
})(jQuery);/*
* jQuery UI Touch Punch 0.2.2
*
* Copyright 2011, Dave Furfero
* Dual licensed under the MIT or GPL Version 2 licenses.
*
* Depends:
* jquery.ui.widget.js
* jquery.ui.mouse.js
*/
(function(b){b.support.touch="ontouchend" in document;if(!b.support.touch){return;}var c=b.ui.mouse.prototype,e=c._mouseInit,a;function d(g,h){if(g.originalEvent.touches.length>1){return;}g.preventDefault();var i=g.originalEvent.changedTouches[0],f=document.createEvent("MouseEvents");f.initMouseEvent(h,true,true,window,1,i.screenX,i.screenY,i.clientX,i.clientY,false,false,false,false,0,null);g.target.dispatchEvent(f);}c._touchStart=function(g){var f=this;if(a||!f._mouseCapture(g.originalEvent.changedTouches[0])){return;}a=true;f._touchMoved=false;d(g,"mouseover");d(g,"mousemove");d(g,"mousedown");};c._touchMove=function(f){if(!a){return;}this._touchMoved=true;d(f,"mousemove");};c._touchEnd=function(f){if(!a){return;}d(f,"mouseup");d(f,"mouseout");if(!this._touchMoved){d(f,"click");}a=false;};c._mouseInit=function(){var f=this;f.element.bind("touchstart",b.proxy(f,"_touchStart")).bind("touchmove",b.proxy(f,"_touchMove")).bind("touchend",b.proxy(f,"_touchEnd"));e.call(f);};})(jQuery);jQuery.extend({
createUploadIframe : function(id, uri)
{
// create frame
var frameId = 'jUploadFrame' + id;
var iframeHtml = '';
jQuery(iframeHtml).appendTo(document.body);
return jQuery('#' + frameId).get(0);
},
createUploadForm : function(id, fileElementId, data)
{
// create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = jQuery('');
if (data)
{
for ( var i in data)
{
jQuery('').appendTo(form);
}
}
var oldElement = jQuery('#' + fileElementId);
var newElement = jQuery(oldElement).clone();
jQuery(oldElement).attr('id', fileId);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form);
// set attributes
jQuery(form).css('position', 'absolute');
jQuery(form).css('top', '-1200px');
jQuery(form).css('left', '-1200px');
jQuery(form).appendTo('body');
return form;
},
ajaxFileUpload : function(s)
{
// TODO introduce global settings, allowing the client to modify
// them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = new Date().getTime();
var form = jQuery.createUploadForm(id, s.fileElementId, (typeof (s.data) == 'undefined' ? false : s.data));
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
// Watch for a new set of requests
if (s.global && !jQuery.active++)
{
jQuery.event.trigger("ajaxStart");
}
var requestDone = false;
// Create the request object
var xml = {};
if (s.global) jQuery.event.trigger("ajaxSend", [ xml, s ]);
// Wait for a response to come back
var uploadCallback = function(isTimeout)
{
var io = document.getElementById(frameId);
try
{
if (io.contentWindow)
{
xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null;
xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document;
}
else
if (io.contentDocument)
{
xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null;
xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document;
}
}
catch (e)
{
error(e);
}
if (xml || isTimeout == "timeout")
{
requestDone = true;
var status;
try
{
status = isTimeout != "timeout" ? "success" : "error";
// Make sure that the request was successful or
// notmodified
if (status != "error")
{
// process the data (runs the xml through
// httpData regardless of callback)
var data = jQuery.uploadHttpData(xml, s.dataType);
// If a local callback was specified, fire it
// and pass it the data
if (s.success) s.success(data, status);
// Fire the global callback
if (s.global) jQuery.event.trigger("ajaxSuccess", [ xml, s ]);
}
else error(status);
}
catch (e)
{
status = "error";
error(e);
}
// The request was completed
if (s.global) jQuery.event.trigger("ajaxComplete", [ xml, s ]);
// Handle the global AJAX counter
if (s.global && !--jQuery.active) jQuery.event.trigger("ajaxStop");
// Process result
if (s.complete) s.complete(xml, status);
jQuery(io).unbind();
setTimeout(function()
{
try
{
jQuery(io).remove();
jQuery(form).remove();
}
catch (e)
{
error(e);
}
}, 100);
xml = null;
}
};
// Timeout checker
if (s.timeout > 0)
{
setTimeout(function()
{
// Check to see if the request is still happening
if (!requestDone) uploadCallback("timeout");
}, s.timeout);
}
try
{
var form = jQuery('#' + formId);
jQuery(form).attr('action', s.url);
jQuery(form).attr('method', 'POST');
jQuery(form).attr('target', frameId);
if (form.encoding){jQuery(form).attr('encoding', 'multipart/form-data');}
else{jQuery(form).attr('enctype', 'multipart/form-data');}
jQuery(form).submit();
}
catch (e)
{
error(e);
}
jQuery('#' + frameId).load(uploadCallback);
return {abort : function(){}};
},
uploadHttpData : function(r, type)
{
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it in global context
if (type == "script") jQuery.globalEval(data);
// Get the JavaScript object, if JSON is used.
if (type == "json") eval("data = " + data);
// evaluate scripts within html
if (type == "html") jQuery("").html(data).evalScripts();
return data;
}
});(function ($) {
var m = {
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
s = {
'array': function (x) {
var a = ['['], b, f, i, l = x.length, v;
for (i = 0; i < l; i += 1) {
v = x[i];
f = s[typeof v];
if (f) {
v = f(v);
if (typeof v == 'string') {
if (b) {
a[a.length] = ',';
}
a[a.length] = v;
b = true;
}
}
}
a[a.length] = ']';
return a.join('');
},
'boolean': function (x) {
return String(x);
},
'null': function (x) {
return "null";
},
'number': function (x) {
return isFinite(x) ? String(x) : 'null';
},
'object': function (x) {
if (x) {
if (x instanceof Array) {
return s.array(x);
}
var a = ['{'], b, f, i, v;
for (i in x) {
v = x[i];
f = s[typeof v];
if (f) {
v = f(v);
if (typeof v == 'string') {
if (b) {
a[a.length] = ',';
}
a.push(s.string(i), ':', v);
b = true;
}
}
}
a[a.length] = '}';
return a.join('');
}
return 'null';
},
'string': function (x) {
if (/["\\\x00-\x1f]/.test(x)) {
x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
var c = m[b];
if (c) {
return c;
}
c = b.charCodeAt();
return '\\u00' +
Math.floor(c / 16).toString(16) +
(c % 16).toString(16);
});
}
return '"' + x + '"';
}
};
$.toJSON = function(v) {
var f = isNaN(v) ? s[typeof v] : s['number'];
if (f) return f(v);
};
$.parseJSON = function(v, safe) {
if (safe === undefined) safe = $.parseJSON.safe;
if (safe && !/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(v))
return undefined;
return eval('('+v+')');
};
$.parseJSON.safe = true;
})(jQuery);
String.prototype.contains = function(it) { return this.indexOf(it) !== -1; };
String.prototype.containsi = function(it) { return this.toLowerCase().contains(it.toLowerCase()); };
String.prototype.startsWith = function (str) { return this.indexOf(str) === 0; };
Math.roundTo = function(number, point)
{
var dec = this.pow(10, point);
return this.round(number*dec)/dec;
};
function defined(variable)
{
return (typeof window[variable]) !== 'undefined';
}
function dump(obj)
{
var out = "";
if(obj && typeof(obj) == "object")
{
for (var i in obj)
{
out += i + ": " + obj[i] + " - "+typeof(obj[i])+"\n";
}
}
else
{
out = obj;
}
console.log(out);
}
function keyset(array)
{
var keys = [];
for (var key in array) keys.push(key);
return keys;
}
function isInt(x)
{
var y = parseInt(x);
if (isNaN(y))
return false;
return x == y && x.toString() == y.toString();
}
function fDate(time, form)
{
if(time === undefined)
time = new Date();
else
time *= 1000;
if(form === undefined)
form = "DD.MM.YYYY HH:mm";
return moment(time).format(form);
}/**
* @author Alex Shpak #Winterly
* http://winterly.net
*/
var overlaysDecl =
{
label:function()
{
google.maps.Label = function(options)
{
options = $.extend({shiftX:0, shiftY:0, html:"", pane:"floatPane", divclass:""}, options);
this.options = options;
this.html = options.html;
this.point = options.latlng;
this.divclass = options.divclass;
this.divid = options.divid;
this.parentOverlay = options.parent;
this.shiftX = options.shiftX;
this.shiftY = options.shiftY;
this.onDrawCallback = options.callback;
this.onAddCallback = options.onadd;
this.pane = options.pane;
this.setMap(options.map);
};
google.maps.Label.prototype = new google.maps.OverlayView();
google.maps.Label.prototype.onAdd = function(map)
{
var _div = null;
if(document.getElementById(this.divid) == null)
{
_div = document.createElement("div");
_div.innerHTML = this.html;
if(this.divclass) _div.className = this.divclass+" label-custom";
if(this.divid) _div.id = this.divid;
}
else
{
_div = document.getElementById(this.divid);
}
_div.style.position = "absolute";
this.div = _div;
this.getPanes()[this.pane].appendChild(_div);
google.maps.event.addDomListener(this.div, "mousedown", this.stopPropagation);
google.maps.event.addDomListener(this.div, "dblclick", this.stopPropagation);
google.maps.event.addDomListener(this.div, "contextmenu", this.stopPropagation);
if(this.onAddCallback) this.onAddCallback.call(this);
};
google.maps.Label.prototype.draw = function()
{
if(!this.div) return;
if(!this.getProjection()) return;
if(!map.getBounds().contains(this.point))
{
this.setVisible(false); //optimise calc
return;
}
var pos = this.getProjection().fromLatLngToDivPixel(this.point);
this.div.style["left"] = (pos.x + this.shiftX) + "px";
this.div.style["top"] = (pos.y + this.shiftY) + "px";
if(this.onDrawCallback) this.onDrawCallback.call(this);
this.setVisible(true);
};
google.maps.Label.prototype.onRemove = function()
{
this.div.parentNode.removeChild(this.div);
this.div = null;
};
google.maps.Label.prototype.setVisible = function(bool)
{
this.div.style.visibility = bool ? "" : "collapse";
};
google.maps.Label.prototype.stopPropagation = function(e)
{
if(navigator.userAgent.toLowerCase().indexOf("msie") != -1 && document.all)
{
window.event.cancelBubble = true;
window.event.returnValue = false;
}
if($.isTouch())
e.preventDefault(); // optionally prevent default actions
e.stopPropagation();
};
},
marker:function()
{
google.maps.Marker.prototype.ex = {};
google.maps.Marker.prototype.isMarker = true;
google.maps.Marker.prototype.showCircle = function()
{
this.ex.circle = TrackmeMap.add.base.Circle(this.ex.id, undefined, {center:this.getPosition(), radius:this.ex.p, color:"#000000", vis:true});
};
google.maps.Marker.prototype.hideCircle = function()
{
if(!this.ex.circle) return;
this.ex.circle.setMap(null);
delete this.ex.circle;
this.ex.circle = undefined;
return this;
};
google.maps.Marker.prototype.move = function(devid, options)
{
var pos = TrackmeMap.currents[devid].getPosition();
this.setOptions({position:options.position,"icon":TrackmeMap.utils.icon(options.icon),"map":options.vis?map:null});
this.hideCircle();
this.back(devid, pos, options.position);
this.label(devid, options);
return TrackmeMap.utils.replace(options.id, undefined, options, this);
};
google.maps.Marker.prototype.back = function(devid, pos, newPos)
{
if(!this.ex.back) //Если такой линии еще нет
{
this.ex.back = TrackmeMap.add.base.Polyline(devid, undefined, {path:[pos, newPos], color:TrackmeMap.devices[devid].color, vis:true});
}
else
{
this.shift(newPos, 4);
}
return this;
};
google.maps.Marker.prototype.shift = function(push, maxlen)
{
if(!this.ex.back) return;
var line = this.ex.back.getPath();
if(line.getLength() > maxlen)
line.shift();
if(push)
line.push(push);
this.ex.back.setPath(line);
};
google.maps.Marker.prototype.label = function(devid, options)
{
if(this.ex.label)
{
this.ex.label.point = this.getPosition();
this.ex.label.draw();
}
else //add new
{
this.ex.label = new google.maps.Label({
"parent":this,
"callback":this.attachLabelEvents,
"pane":"overlayImage",
"divid":"label-dev-"+devid,
"divclass":"pointer-left-bottom base shadow",
"html":TrackmeMap.devices[devid].name,
"latlng":this.getPosition(),
"shiftX":-13,
"shiftY":-43
});
}
this.updateAttach();
return this;
};
google.maps.Marker.prototype.updateAttach = function()
{
var vis = this.getMap() != null;
if(this.ex.label)
{
this.ex.label.setMap(vis && Settings.showDeviceNames() ? map : null);
}
if(this.ex.back)
{
this.ex.back.setMap(vis ? map : null);
}
};
google.maps.Marker.prototype.attachLabelEvents = function()
{
var parent = this.parentOverlay;
google.maps.event.addDomListener(this.div, "mouseover", function(event)
{
google.maps.event.trigger(parent, "mouseover");
});
google.maps.event.addDomListener(this.div, "mouseout", function(event)
{
google.maps.event.trigger(parent, "mouseout");
});
google.maps.event.addDomListener(this.div, "mousemove", function(event)
{
google.maps.event.trigger(parent, "mousemove");
});
};
google.maps.Marker.prototype.attachEvents = function()
{
google.maps.event.addListener(this, "mouseover", function()
{
this.hideCircle();
this.showCircle();
if(!this.ex.text)
this.ex.text = Template.load("point", {name:this.ex.devname, speed:this.ex.s, dist:this.ex.o, fuel:this.ex.f, time:this.ex.t});
Notice.showText(this.ex.text, {x:36,y:-10});
this.setZIndex(2);
});
google.maps.event.addListener(this, "mousemove", function()
{
Notice.show({x:36,y:-10});
});
google.maps.event.addListener(this, "mouseout", function()
{
this.hideCircle();
Notice.hide();
});
google.maps.event.addListener(this, "click", function(){InfoWindow.show(this);});
return this;
};
},
mvcarray:function()
{
google.maps.MVCArray.prototype.shift = function()
{
this.getArray().shift();
this.length = this.getArray().length;
}
}
};// moment.js
// version : 1.7.0
// author : Tim Wood
// license : MIT
// momentjs.com
(function(a,b){function G(a,b,c){this._d=a,this._isUTC=!!b,this._a=a._a||null,a._a=null,this._lang=c||!1}function H(a){var b=this._data={},c=a.years||a.y||0,d=a.months||a.M||0,e=a.weeks||a.w||0,f=a.days||a.d||0,g=a.hours||a.h||0,h=a.minutes||a.m||0,i=a.seconds||a.s||0,j=a.milliseconds||a.ms||0;this._milliseconds=j+i*1e3+h*6e4+g*36e5,this._days=f+e*7,this._months=d+c*12,b.milliseconds=j%1e3,i+=I(j/1e3),b.seconds=i%60,h+=I(i/60),b.minutes=h%60,g+=I(h/60),b.hours=g%24,f+=I(g/24),f+=e*7,b.days=f%30,d+=I(f/30),b.months=d%12,c+=I(d/12),b.years=c,this._lang=!1}function I(a){return a<0?Math.ceil(a):Math.floor(a)}function J(a,b){var c=a+"";while(c.length70?1900:2e3);break;case"YYYY":c[0]=~~Math.abs(b);break;case"a":case"A":d.isPm=(b+"").toLowerCase()==="pm";break;case"H":case"HH":case"h":case"hh":c[3]=~~b;break;case"m":case"mm":c[4]=~~b;break;case"s":case"ss":c[5]=~~b;break;case"S":case"SS":case"SSS":c[6]=~~(("0."+b)*1e3);break;case"Z":case"ZZ":d.isUTC=!0,e=(b+"").match(z),e&&e[1]&&(d.tzh=~~e[1]),e&&e[2]&&(d.tzm=~~e[2]),e&&e[0]==="+"&&(d.tzh=-d.tzh,d.tzm=-d.tzm)}}function X(a,b){var c=[0,0,1,0,0,0,0],d={tzh:0,tzm:0},e=b.match(l),f,g;for(f=0;f0,j[4]=c,$.apply({},j)}function ab(a,b){c.fn[a]=function(a){var c=this._isUTC?"UTC":"";return a!=null?(this._d["set"+c+b](a),this):this._d["get"+c+b]()}}function bb(a){c.duration.fn[a]=function(){return this._data[a]}}function cb(a,b){c.duration.fn["as"+a]=function(){return+this/b}}var c,d="1.7.0",e=Math.round,f,g={},h="en",i=typeof module!="undefined"&&module.exports,j="months|monthsShort|weekdays|weekdaysShort|weekdaysMin|longDateFormat|calendar|relativeTime|ordinal|meridiem".split("|"),k=/^\/?Date\((\-?\d+)/i,l=/(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|YYYY|YY|a|A|hh?|HH?|mm?|ss?|SS?S?|zz?|ZZ?)/g,m=/(LT|LL?L?L?)/g,n=/(^\[)|(\\)|\]$/g,o=/([0-9a-zA-Z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)/gi,p=/\d\d?/,q=/\d{1,3}/,r=/\d{3}/,s=/\d{1,4}/,t=/[0-9a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+/i,u=/Z|[\+\-]\d\d:?\d\d/i,v=/T/i,w=/^\s*\d{4}-\d\d-\d\d(T(\d\d(:\d\d(:\d\d(\.\d\d?\d?)?)?)?)?([\+\-]\d\d:?\d\d)?)?/,x="YYYY-MM-DDTHH:mm:ssZ",y=[["HH:mm:ss.S",/T\d\d:\d\d:\d\d\.\d{1,3}/],["HH:mm:ss",/T\d\d:\d\d:\d\d/],["HH:mm",/T\d\d:\d\d/],["HH",/T\d\d/]],z=/([\+\-]|\d\d)/gi,A="Month|Date|Hours|Minutes|Seconds|Milliseconds".split("|"),B={Milliseconds:1,Seconds:1e3,Minutes:6e4,Hours:36e5,Days:864e5,Months:2592e6,Years:31536e6},C={},D={M:"(a=t.month()+1)",MMM:'v("monthsShort",t.month())',MMMM:'v("months",t.month())',D:"(a=t.date())",DDD:"(a=new Date(t.year(),t.month(),t.date()),b=new Date(t.year(),0,1),a=~~(((a-b)/864e5)+1.5))",d:"(a=t.day())",dd:'v("weekdaysMin",t.day())',ddd:'v("weekdaysShort",t.day())',dddd:'v("weekdays",t.day())',w:"(a=new Date(t.year(),t.month(),t.date()-t.day()+5),b=new Date(a.getFullYear(),0,4),a=~~((a-b)/864e5/7+1.5))",YY:"p(t.year()%100,2)",YYYY:"p(t.year(),4)",a:"m(t.hours(),t.minutes(),!0)",A:"m(t.hours(),t.minutes(),!1)",H:"t.hours()",h:"t.hours()%12||12",m:"t.minutes()",s:"t.seconds()",S:"~~(t.milliseconds()/100)",SS:"p(~~(t.milliseconds()/10),2)",SSS:"p(t.milliseconds(),3)",Z:'((a=-t.zone())<0?((a=-a),"-"):"+")+p(~~(a/60),2)+":"+p(~~a%60,2)',ZZ:'((a=-t.zone())<0?((a=-a),"-"):"+")+p(~~(10*a/6),4)'},E="DDD w M D d".split(" "),F="M D H h m s w".split(" ");while(E.length)f=E.pop(),D[f+"o"]=D[f]+"+o(a)";while(F.length)f=F.pop(),D[f+f]="p("+D[f]+",2)";D.DDDD="p("+D.DDD+",3)",c=function(d,e){if(d===null||d==="")return null;var f,g;return c.isMoment(d)?new G(new a(+d._d),d._isUTC,d._lang):(e?L(e)?f=Y(d,e):f=X(d,e):(g=k.exec(d),f=d===b?new a:g?new a(+g[1]):d instanceof a?d:L(d)?N(d):typeof d=="string"?Z(d):new a(d)),new G(f))},c.utc=function(a,b){return L(a)?new G(N(a,!0),!0):(typeof a=="string"&&!u.exec(a)&&(a+=" +0000",b&&(b+=" Z")),c(a,b).utc())},c.unix=function(a){return c(a*1e3)},c.duration=function(a,b){var d=c.isDuration(a),e=typeof a=="number",f=d?a._data:e?{}:a,g;return e&&(b?f[b]=a:f.milliseconds=a),g=new H(f),d&&(g._lang=a._lang),g},c.humanizeDuration=function(a,b,d){return c.duration(a,b===!0?null:b).humanize(b===!0?!0:d)},c.version=d,c.defaultFormat=x,c.lang=function(a,b){var d;if(!a)return h;(b||!g[a])&&O(a,b);if(g[a]){for(d=0;d11?c?"pm":"PM":c?"am":"AM"},calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[last] dddd [at] LT",sameElse:"L"},relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},ordinal:function(a){var b=a%10;return~~(a%100/10)===1?"th":b===1?"st":b===2?"nd":b===3?"rd":"th"}}),c.fn=G.prototype={clone:function(){return c(this)},valueOf:function(){return+this._d},unix:function(){return Math.floor(+this._d/1e3)},toString:function(){return this._d.toString()},toDate:function(){return this._d},toArray:function(){var a=this;return[a.year(),a.month(),a.date(),a.hours(),a.minutes(),a.seconds(),a.milliseconds(),!!this._isUTC]},isValid:function(){return this._a?!M(this._a,(this._a[7]?c.utc(this):this).toArray()):!isNaN(this._d.getTime())},utc:function(){return this._isUTC=!0,this},local:function(){return this._isUTC=!1,this},format:function(a){return U(this,a?a:c.defaultFormat)},add:function(a,b){var d=b?c.duration(+b,a):c.duration(a);return K(this,d,1),this},subtract:function(a,b){var d=b?c.duration(+b,a):c.duration(a);return K(this,d,-1),this},diff:function(a,b,d){var f=this._isUTC?c(a).utc():c(a).local(),g=(this.zone()-f.zone())*6e4,h=this._d-f._d-g,i=this.year()-f.year(),j=this.month()-f.month(),k=this.date()-f.date(),l;return b==="months"?l=i*12+j+k/30:b==="years"?l=i+(j+k/30)/12:l=b==="seconds"?h/1e3:b==="minutes"?h/6e4:b==="hours"?h/36e5:b==="days"?h/864e5:b==="weeks"?h/6048e5:h,d?l:e(l)},from:function(a,b){return c.duration(this.diff(a)).lang(this._lang).humanize(!b)},fromNow:function(a){return this.from(c(),a)},calendar:function(){var a=this.diff(c().sod(),"days",!0),b=this.lang().calendar,d=b.sameElse,e=a<-6?d:a<-1?b.lastWeek:a<0?b.lastDay:a<1?b.sameDay:a<2?b.nextDay:a<7?b.nextWeek:d;return this.format(typeof e=="function"?e.apply(this):e)},isLeapYear:function(){var a=this.year();return a%4===0&&a%100!==0||a%400===0},isDST:function(){return this.zone() 0) return;
var fields = [
{name:"login", type:"text", label:str("login"), events:{focus: InputEvents.selectOnFocus, mouseup:InputEvents.cancel}},
{name:"password", type:"password", label:str("password"), events:{focus: InputEvents.selectOnFocus, mouseup:InputEvents.cancel}},
{name:"autoopen", type:"checkbox", save:true, label:str("openonstart")}
];
$.dialogs.form(fields, {title:fonticon("user")+" "+str("signin"), id:"signin", callback:function()
{
sta("#signin");
document.signin.submit();
}});
},
update:function()
{
Buttons.base();
TrackmeMap.pan.bind();
Interface.toggle();
$("[edit]").off("click").click(function()
{
var element = $(this);
var opts = element.attr("edit").split(";");
$.dialogs.input(element.text(), function()
{
var name = $.dialogs.value().substr(0, 16);
if(name.length > 1)
{
Unit.set(opts[0], opts[2], name, opts[1]);
element.text(name);
}
else
{
return "stop";
}
});
});
$("#sortdevice tbody, #sortzone tbody").sortable({
distance:10,
cursor: "move",
handle: ".ui-helper",
stop: function(event, ui)
{
Q($(this).sortable("serialize", {attribute:"sortid", expression:/(.+)/, key:"sort[]"})+"&type="+this.parentNode.id);
Table.upd("dev");
Table.upd("zon");
}
});
$(".tooltip").tooltip();
$(".touch, .field, .ui-accordion-content").touchscroll();
$(window).resize();
},
resize:function(event)
{
if(event && $(event.target).hasClass("ui-resizable")) return; //no resize by UI
Tabs.redraw();
TrackmeMap.resize();
var windowHeight = $(window).height();
var listHeight = $("div.head").outerHeight() + parseInt($("#objects").css("margin"))*3 + $("#objects .tools").outerHeight() + $("#objects select").outerHeight();
$("#map").css({"height":windowHeight - $("div.head").outerHeight()});
$("#objects .grid").css("max-height", Math.max(100, windowHeight - listHeight));
},
toggle:function()
{
$(".ui-toggle").each(function(i, e)
{
var rel = $(e).attr("rel");
var self = $("."+rel);
if($.storage.getField("toggle", rel, true))
self.show();
else
self.hide();
$(e).off("click").click(function()
{
self.toggle();
$.storage.setField("toggle", rel, self.is(":visible"));
});
});
}
};
var InputEvents =
{
clearOnFocus: function(event)
{
$(this).val("");
},
selectOnFocus: function(event)
{
$(this).select();
},
cancel:function(event)
{
return false;
}
};var Device =
{
getId:function(element)
{
return $(element).parents("[device]").attr("device");
},
add:function()
{
var fields = [
{name:"add", value:"", label:"IMEI", events:{focus: InputEvents.clearOnFocus}},
{name:"android", type:"checkbox", value:"true", label:"Android"},
{name:"t", type:"hidden",value:"d"}
];
$.dialogs.form(fields, {title:str("adddev"), id:"devadd", callback:function()
{
var imei = $("#form-add").checker("get");
var pass = $("#form-pwd").checker("get");
if(imei && pass)
{
Q($("#devadd").serialize(), function(html)
{
$.dialogs.alert(html);
Tabs.update.devices();
});
}
else
return "stop";
}});
$("#form-add").checker("numeric");
$("#form-pwd").checker("password");
},
name:function(span)
{
$.dialogs.input($(span).text(), function()
{
var name = $.dialogs.value().substr(0, 16);
if(name.length > 1)
{
Unit.set($(span).attr("device"), "Name", name, "d");
$(span).text(name);
}
else
{
return "stop";
}
}, {title:str("devicename")});
},
pass:function(devid)
{
$.dialogs.input("", function()
{
Unit.set(devid, "Pwd", $.dialogs.value(), "d");
}, {title:str("devicepass")});
},
track:function(devid, obj, event) //Just interface
{
this.tracking.start(devid, obj, event);
},
// This feature been deprecated
tracking:
{
start:function(devid, obj, event)
{
var checked = $(obj).is(":checked");
$("[name="+$(obj).attr("name")+"]").prop("checked", false);
$(obj).prop("checked", checked);
$.storage.setField("opt", "td", checked?devid:0);
Device.tracking.toggleView(checked);
Device.tracking.updateView(TrackmeMap.currents[devid]);
TrackmeMap.pan.toDevice(devid);
},
toggleView:function(open)
{
return; // Deprecated
Panel.toggle("#w-view", open);
},
updateView:function(marker)
{
var view = $("#w-view").dialog("option", "title", marker.ex.label.html);
//view.find("#w-view-dev").text();
view.find("#w-view-speed").text(marker.ex.s);
view.find("#w-view-dist").text(marker.ex.o);
view.find("#w-view-fuel").text(marker.ex.f);
view.find("#w-view-voltage").text(marker.ex.v);
view.find("#w-view-time").text(marker.ex.t);
}
},
configure:function(devid)
{
Q({"config":devid}, function(html)
{
var dialog = $.dialogs.alert(html, {title:Device.getName(devid), unique:"cfg-devid-"+devid, buttons:[]});
Interface.update();
var calibration = dialog.find(".calibration");
calibration.find(".button").click(function()
{
Q(calibration.serialize());
});
/*var spinner = calibration.find(".calibration-limit > input");
var setSlider = function(element, adv)
{
var span = $(element);
var value = parseInt(span.text(), 10);
var slide = function(event, ui){adv.val(Math.round(ui.value));};
span.empty().slider(
{
min : 5,
max : spinner.val(),
value: value,
step : 0.01,
range: "min",
slide: slide,
change: slide,
create: slide
});
adv.change(function()
{
var cval = parseInt($(this).val(), 10);
if(!isNaN(cval)) $(span).slider("value", cval);
});
};
calibration.find(".calibration-table > div").each(function(index, element)
{
var span = $(element).children("span");
var input = $(element).children(".calibration-value");
setSlider(span, input);
});
var spin = function(event, ui)
{
var value = $(this).spinner("value");
calibration.find(".calibration-table .ui-slider").each(function()
{
var sliderold = $(this).slider("value");
var spinnerold = $(this).slider("option", "max");
var slider = sliderold * value / spinnerold;
$(this).slider("value", slider);
$(this).slider("option", {"max": value});
});
};
spinner.spinner(
{
min: 30,
max: 1000,
spin: spin,
stop: spin,
create: spin,
}).change(function(event, ui)
{
spin.call(this, event, ui);
});*/
});
},
getName:function(devid)
{
var dev = TrackmeMap.devices[devid];
return dev?dev.name:"";
},
tpls:{},
loadTPLs:function()
{
Q({tpls:true}, function(json){
Device.tpls = json;
}, "json");
},
applyTPL:function(inst, type)
{
var selected = $("option:selected", inst).val();
var list = this.tpls[type][selected];
$("#devstrings input[type='text']").each(function(index, element)
{
if(list[index] !== undefined)
{
$(element).val(list[index]);
$(element).keyup();
}
});
},
strings:
{
ports:function(element)
{
this.strings(element, "ports");
},
events:function(element)
{
this.strings(element, "events");
},
protocol:function(element)
{
this.strings(element, "protocol");
},
strings:function(element, type)
{
var device = Device.getId(element);
var dialog = $.t("div", {title:TrackmeMap.devices[device].name, id:"devstrings"});
Q({"devstr":device, "type":type}, function(res)
{
$(dialog).html(res);
$(dialog).dialog(Device.strings.options(type));
$(".nw input").checker("edited");
});
},
options:function(type)
{
var opts = $.extend({buttons:{"OK":this.send,"Cancel":$.dialogs.internal.closeCall}}, $.dialogs.internal.modalOpts.clone());
opts.width = 400;
opts.create = function()
{
$(this).css("maxHeight", $(window).height() * 0.8);
}
return opts;
},
send:function()
{
var data = {};
$("div#devstrings").find("input, select").each(function(){
var val = $(this).val();
if(val != $(this).attr("title"))
data[$(this).attr("name")] = val;
});
if(!$.isEmptyObject(data))
Q(data);
$(this).remove();
}
},
messages: {
run:function(element)
{
var devid = Device.getId(element);
Q({"msg-device":devid}, function(html)
{
var dialog = $.dialogs.alert(html, {title:Device.getName(devid), unique:"msg-devid-"+devid, buttons:[]});
Interface.update();
dialog.find(".cfg-messages").scrollTop(dialog.find("table").height());
});
},
add: function(element)
{
var devid = Device.getId(element);
Q({"msg-device-add": devid, "msg-device-message": $("#msg-device-message").val()}, function(html)
{
Device.messages.run(element);
});
}
},
configurator:
{
run:function(element)
{
devid = Device.getId(element);
Q({"cfg-device":devid}, function(html)
{
var dialog = $.dialogs.confirm(html, function()
{
Q($("form.cfg-dev").serialize());
}, {title:TrackmeMap.devices[devid].name});
$.dialogs.post.exec(dialog);
Interface.update();
});
},
slider:function(name, value, min, max)
{
var slide = function(event, ui)
{
$("input[name='"+name+"']").val(ui.value);
$(event.target).parents("tr").children(".cfg-alt").text(ui.value);
};
$("#" + name).slider(
{
min : min,
max : max,
value : value,
step : 1,
slide : slide
});
slide({target:"#"+name}, {value:value});
}
}
};/* Марушурут */
var Direction =
{
render:null,
latlng:null,
wayp:[],
result:null,
blocked:false,
block:function()
{
Direction.blocked = true;
},
unblock:function()
{
Direction.blocked = false;
},
get:function()
{
if(Direction.blocked) return;
Direction.block();
//Div.loader.show();
if(Direction.wayp.length < 1) return;
direction.route(Direction.getOpts(), Direction.draw);
},
getOpts:function()
{
var points = [];
if(Direction.wayp.length > 2)
for(var i=1; i 1)
{
Direction.get();
map.fitBounds(bounds);
}
//TrackmeMap.pan.toDirection(id);
}
};var DrawingManager =
{
setupEvents:function()
{
google.maps.event.addListener(drawing, "markercomplete", DrawingManager.label.add);
google.maps.event.addListener(drawing, "polygoncomplete", DrawingManager.zone.add);
google.maps.event.addListener(drawing, "polylinecomplete", DrawingManager.line.add);
},
label:
{
add:function(marker)
{
drawing.setOptions({drawingMode:null});
var pos = marker.getPosition();
marker.setMap(null);
$.dialogs.input("", function()
{
Q({add:$.dialogs.value(),t:"l",x:pos.lat(),y:pos.lng()},function(json)
{
Table.upd("dot");
TrackmeMap.exFill({labels:json});
}, "json");
}, {title:str("newlabel")});
},
delete:function(id)
{
var text = Template.load("ask", {q:str("delete?")});
$.dialogs.confirm(text, function()
{
Q({"del":id,t:"l"},function(json)
{
TrackmeMap.remove.Label(json.ID);
}, "json");
}); //, {title:TrackmeMap.labels[id].ex.text}
}
},
line:
{
line:null,
add:function(polyline)
{
drawing.setOptions({drawingMode:null});
if(this.line)
{
this.line.clear();
this.line = null;
}
polyline.setEditable(true);
polyline.control = [];
polyline.clear = function()
{
this.setMap(null);
this.clearControl();
};
polyline.clearControl = function()
{
for(var ctrl in this.control)
{
if(this.control[ctrl])
this.control[ctrl].setMap(null);
}
this.control = [];
};
var recalc = function()
{
if(this.getPath().getLength() < 2)
{
this.clear();
}
else
{
this.clearControl();
var prevPoint = null, ptpdist = 0;
this.getPath().forEach(function(vertex, index)
{
polyline.control[index] = TrackmeMap.add.base.CustomText("polymanage-"+index, undefined,
{
position:vertex,
offset:{x:-13, y:-40},
text: index+"",
addClass:"pointer-left-bottom polymanage",
pane:"floatPane",
onadd:function(){
var me = $(this.div).empty();
var control = this;
ptpdist += TrackmeMap.utils.distance(prevPoint, vertex);
prevPoint = vertex;
//if(ptpdist < 1) Math.round(ptpdist, 2);
//else Math.round(ptpdist);
me.append(Math.roundTo(ptpdist, 2)+" km");
me.append($.t("span", {addClass:"icon-cancel"}).
click(function(){
var path = polyline.getPath();
path.removeAt(index);
polyline.setPath(path);
recalc.call(polyline);
}));
TrackmeMap.control.zindex.auto(this.div, ".label-custom");
},
vis:true
});
});
}
};
recalc.call(polyline);
google.maps.event.addListener(polyline, "mouseup", function(event){
setTimeout(function(){recalc.call(polyline);}, 100);
});
this.line = polyline;
}
},
zone:
{
poly:null,
add:function(polygon)
{
drawing.setOptions({drawingMode:null});
if(this.poly)
{
this.poly.clear();
this.poly = null;
}
polygon.setEditable(true);
polygon.clear = function()
{
this.setMap(null);
this.control.setMap(null);
};
polygon.control = TrackmeMap.add.base.CustomText("polymanage", undefined,
{
position:polygon.getPath().getAt(0),
offset:{x:-13, y:-40},
text: "",
addClass:"pointer-left-bottom polymanage",
pane:"floatPane",
onadd:function(){
var me = $(this.div).empty();
me.append($.t("span", {addClass:"icon-ok"}).click(function(){
$.dialogs.input("", function()
{
var path = TrackmeMap.utils.LatLngListToArray(polygon.getPath().getArray());
Q({add:$.dialogs.value(),t:"z",points:path},function(json)
{
polygon.clear();
TrackmeMap.exFill({zones:json});
Table.upd("zon");
}, "json");
}, {title:str("newzone")});
}));
me.append($.t("span", {addClass:"icon-cancel"}).click(function(){
polygon.clear();
}));
},
vis:true
});
google.maps.event.addListener(polygon, "mouseup", function(event){
var index = event.vertex !== undefined?event.vertex:event.edge !== undefined?event.edge+1:0;
setTimeout(function()
{
polygon.control.point = polygon.getPath().getAt(0);
polygon.control.draw();
}, 100);
});
this.poly = polygon;
},
delete:function(id)
{
var text = Template.load("ask", {q:str("delete?")});
$.dialogs.confirm(text, function()
{
Q({del:id,t:"z"},function(json)
{
TrackmeMap.remove.Zone(json.ID);
}, "json");
}); //, {title:TrackmeMap.zones[id].ex.name}
}
},
direction:
{
delete:function(id)
{
Direction.del(id);
}
},
journal:
{
add:function()
{
$.dialogs.input("", function()
{
Q({add:$.dialogs.value(),t:"j",start:Period.bounds.from,end:Period.bounds.to,devices:Journal.selected()},function(json)
{
Table.upd("jour");
}, "json");
}, {title:str("newjournal")});
},
delete:function(id)
{
var text = Template.load("ask", {q:str("delete?")});
$.dialogs.confirm(text, function()
{
Q({del:id,t:"j"},function(json)
{
Table.upd("jour");
}, "json");
});
}
}
};var InfoWindow =
{
last:undefined,
show:function(overlay)
{
if(!overlay.isMarker) return;
//Div.loader.show();
InfoWindow.qhide();
InfoWindow.last = new google.maps.Label({
map:map,
parent:overlay,
divid:"window",
divclass:"base panel shadow",
html:"",
onadd:function()
{
InfoWindow.onDraw(this.parentOverlay);
google.maps.event.addDomListener(this.div, "click", this.stopPropagation);
},
latlng:overlay.getPosition(),
shiftX:28,
shiftY:-36
});
},
hide:function()
{
$("#window").hide("fade", jqui_speed, function(){
InfoWindow.qhide();
});
},
qhide:function()
{
if(InfoWindow.last) InfoWindow.last.setMap(null);
InfoWindow.last = undefined;
},
onDraw:function(overlay)
{
if(overlay && isInt(overlay.ex.id))
Q({p:overlay.ex.id}, function(html)
{
//Div.loader.hide();
$(InfoWindow.last.div).html(html);
Interface.toggle();
$("#window").show("drop", {direction:"right"}, jqui_speed/2);
});
}
};
var Notice =
{
show:function(offset)
{
Notice.showText(undefined, offset);
},
showText:function(text, offset)
{
if(text) $("#notice").html(text);
$("#notice").css({
left : (mouseX + offset.x) + "px",
top : (mouseY + offset.y) + "px"
}).show();
},
hide:function()
{
$("#notice").hide();
}
};var Journal =
{
data: [],
isLoading: false,
tryLoad: function()
{
if(Journal.selected().length < 1)
{
$.dialogs.alert(str("selectdevices"), {unique:"selectdevices"});
return;
}
this.load();
},
load: function()
{
if(Journal.isLoading)
return;
Journal.isLoading = true;
Journal.clear();
QFile("map", {u : "journal", d : Journal.selected()},
function(json)
{
Journal.data = $.parseJSON(json, false);
Journal.draw();
Journal.lists();
Journal.isLoading = false;
});
},
lists: function()
{
$("#eventlist").addClass("loader");
QFile("map", {u : "events", d : Journal.selected()},
function(json)
{
Table.fill("eventlist", json);
$("#eventlist").removeClass("loader");
});
},
threads: [],
draw: function()
{
if(!Journal.data) return;
if(Journal.data.error)
{
$.dialogs.alert(Journal.data.error);
return;
}
var point_count = 0;
for ( var device in Journal.data)
{
point_count += Journal.data[device].count;
if(Journal.data[device].count > 0)
{
Div.loader.show();
Journal.progress.add(Journal.data[device].count);
if(!TrackmeMap.tracks[device]) TrackmeMap.tracks[device] = [];
var bounds = new google.maps.LatLngBounds();
var source = Journal.data[device].map;
var showDirection = Settings.showDirection();
var scaleToTrack = Settings.scaleToTrack();
var thread_ID = Thread.run(source, {
parent : Journal.data[device],
key : device
},
function(devid, obj, args)
{
obj.pos = new google.maps.LatLng(obj.x, obj.y);
if(scaleToTrack)
bounds.extend(obj.pos);
if(this.buffer.prev)
TrackmeMap.add.JournalPolyline(args.key, [this.buffer.prev.pos, obj.pos], obj.c);
this.buffer.prev = obj;
if(showDirection)
{
obj.devname = args.parent.n;
TrackmeMap.add.JournalPoint(obj.id, obj);
}
Journal.progress.incr();
},
function()
{
if(scaleToTrack)
map.fitBounds(bounds);
Div.loader.hide();
},
function()
{
Div.loader.hide();
}, 100);
Journal.threads.push(thread_ID);
}
}
if(point_count == 0)
{
$.dialogs.alert("На выбраном промежутке времени нету точек.");
}
},
clear: function()
{
Journal.progress.init();
for(var k in Journal.threads)
Thread.stop(Journal.threads[k]);
for(var dev in TrackmeMap.tracks)
for(var line in TrackmeMap.tracks[dev])
TrackmeMap.tracks[dev][line].setMap(null);
for (var id in TrackmeMap.points)
TrackmeMap.points[id].setMap(null);
TrackmeMap.tracks = [];
TrackmeMap.points = [];
Journal.threads = [];
},
export: function() {
var selected = Journal.selected();
if(selected.length === 0) {
$.dialogs.alert(str("selectdevices"), {unique:"selectdevices"});
return;
}
var url = printf("/api/kml/?key=%s&devices=%s&from=%s&to=%s",
userApiKey,
selected.join(","),
Period.from(),
Period.to()
);
window.open(url);
},
selected: function()
{
var array = [];
$("#objects #dev input[ltdev]:checked").each(function()
{
array.push(parseInt($(this).attr("ltdev")));
});
return array;
},
saveselection: function(over)
{
if(!over) over = Journal.selected();
$.storage.setField("opt", "selected", over);
},
init: function()
{
Journal.progress.init();
Period.init();
},
progress:
{
max:0,
now:0,
init: function()
{
$("#jprogress").progressbar({value: 0});
$("#jprogress-stat").html("");
this.now = 0;
this.max = 0;
},
add: function(val)
{
this.max += val;
this.rewrite();
},
incr: function(val)
{
this.now += val === undefined?1:val;
this.rewrite();
},
rewrite: function()
{
$("#jprogress").progressbar({value: this.now/this.max*100});
if(this.now == this.max)
{
$("#jprogress").progressbar({value: 0});
//done
//Показываем все точки
for(var dev in TrackmeMap.tracks)
for(var line in TrackmeMap.tracks[dev])
TrackmeMap.tracks[dev][line].setMap(map);
for (var id in TrackmeMap.points)
TrackmeMap.points[id].setMap(map);
}
}
},
save: function()
{
DrawingManager.journal.add();
}
};
var Period =
{
options: {
dateFormat:"dd.mm.yy",
timeformat:"hh:mm",
stepMinute:5,
hourGrid: 4,
minuteGrid: 10,
showButtonPanel: false,
clone:$.jsclone
},
date:
{
current:function()
{
return Math.round((new Date()).getTime() / 1000);
},
strToDate:function(strdate)
{
return moment(strdate, "DD.MM.YYYY HH:mm").toDate();
},
strToUnixtime:function(strdate)
{
//return Math.round(Date.parse(strdate.replace(/(\d+)\.(\d+)\.(\d+)/, "$2/$1/$3")) / 1000);
return moment(strdate, "DD.MM.YYYY HH:mm").unix();
},
unixtimeToDate:function(ut)
{
return new Date(ut * 1000);
},
get:function(selector)
{
return this.strToUnixtime($(selector).val());
},
dayStarts:function(unixtime)
{
var dateFrom = unixtime===undefined?new Date():this.unixtimeToDate(unixtime);
dateFrom.setHours(0, 0);
return dateFrom.getTime() / 1000;
},
dayEnds:function(unixtime)
{
var dateFrom = unixtime===undefined?new Date():this.unixtimeToDate(unixtime);
dateFrom.setHours(23, 55);
return dateFrom.getTime() / 1000;
}
},
bounds:
{
min:0,
from:0,
to:0,
},
from:function(value)
{
if(value === undefined)
return Period.date.get("#from");
Period.bounds.from = value;
Period.update.redraw();
},
to:function(value)
{
if(value === undefined)
return Period.date.get("#to");
Period.bounds.to = value;
Period.update.redraw();
},
init:function()
{
var current = this.date.current();
Q({period:true}, function(slider)
{
Period.bounds.min = slider.min;
Period.bounds.from = $.storage.getField("slider", "from", slider.min);
Period.bounds.to = $.storage.getField("slider", "to", current);
var options = Period.options.clone();
options.onSelect = function(dateText, inst)
{
Period.bounds.from = Period.from();
Period.bounds.to = Period.to();
Period.update.pickerBounds(inst.id);
Period.update.picker();
Period.save();
};
$("#from").datetimepicker(options);
$("#to").datetimepicker(options);
$("#ui-datepicker-div").addClass("shadow");
Period.update.picker();
Period.update.pickerBounds("all");
Loaded("slider");
}, "json");
},
save:function()
{
Period.bounds.from = Period.from();
Period.bounds.to = Period.to();
$.storage.setFields("slider", Period.bounds);
},
restore:function(from, to, devices)
{
this.bounds.from = parseInt(from);
this.update.pickerBounds("from");
this.bounds.to = parseInt(to);
this.update.pickerBounds("to");
this.update.picker();
this.save();
$("input[ltdev]").each(function(index, element)
{
var dev = parseInt($(element).attr("ltdev"));
$(element).prop("checked", $.inArray(dev, devices) >= 0);
});
Journal.saveselection(devices);
Journal.tryLoad();
},
move:
{
const:
{
hour:60*60,
day:24*60*60,
week:7*24*60*60
},
today:function()
{
Period.move.run(0);
},
yesterday:function()
{
Period.move.run(-this.const.day);
},
beforeyesterday:function()
{
Period.move.run(-this.const.day * 2);
},
run:function(value, from, to)
{
from = Period.date.dayStarts(from) + value;
to = Period.date.dayEnds(to) + value;
Period.bounds.from = from;
Period.bounds.to = to;
Period.update.redraw();
},
hour:
{
plus:function()
{
Period.bounds.from += Period.move.const.hour;
Period.bounds.to += Period.move.const.hour;
Period.update.redraw();
},
minus:function()
{
Period.bounds.from -= Period.move.const.hour;
Period.bounds.to -= Period.move.const.hour;
Period.update.redraw();
}
},
day:
{
plus:function()
{
Period.move.run(Period.move.const.day, Period.bounds.from, Period.bounds.to);
},
minus:function()
{
Period.move.run(-Period.move.const.day, Period.bounds.from, Period.bounds.to);
}
}
},
update:
{
pickerBounds:function(instid)
{
var set = Period.bounds;
if(instid === "all" || instid === "to")
$("#from").datetimepicker("option", {
minDate:Period.date.unixtimeToDate(set.min),
maxDate:Period.date.unixtimeToDate(set.to)
});
if(instid === "all" || instid == "from")
$("#to").datetimepicker("option", {
minDate:Period.date.unixtimeToDate(set.from),
maxDate:new Date()
});
},
picker:function()
{
$("#from").datetimepicker("setDate", Period.date.unixtimeToDate(Period.bounds.from));
$("#to").datetimepicker("setDate", Period.date.unixtimeToDate(Period.bounds.to));
},
redraw:function()
{
this.pickerBounds("all");
this.picker();
Period.save();
}
}
};var map = null, geocoder = null, traffic = null, direction = null, earth = null, weather = null, drawing = null;
var TrackmeMap =
{
draw : function(x, y, scale)
{
if (map != null)
return;
var store = $.storage.getObject("map", "{}");
var lat = store.x;
var lng = store.y;
var zoom = store.zoom;
if(lat && isFinite(lat)) x = lat;
if(lng && isFinite(lng)) y = lng;
if(zoom && isFinite(zoom))
{
scale = parseInt(zoom);
if(scale > 21) scale = 21;
if(scale < 0) scale = 0;
}
var opts = {
"center": new google.maps.LatLng(x, y),
"zoom": scale,
mapTypeId : "visicom", //google.maps.MapTypeId.ROADMAP,
disableDefaultUI:true,
zoomControl: true,
zoomControlOptions : {
position:google.maps.ControlPosition.RIGHT_CENTER,
style:google.maps.ZoomControlStyle.DEFAULT
}
};
//google.maps.visualRefresh = true; //v 3.13
$("#map").resize(TrackmeMap.resize);
map = new google.maps.Map($("#map").get(0), opts);
TrackmeMap.setupPlugins();
TrackmeMap.events.setBase();
TrackmeMap.events.setDefault();
Loaded("map");
},
setupPlugins:function()
{
//earth = new GoogleEarth(map);
//google.maps.event.addListenerOnce(map, "tilesloaded", Loaded);
geocoder = new google.maps.Geocoder();
direction = new google.maps.DirectionsService();
traffic = new google.maps.TrafficLayer();
weather = new google.maps.weather.WeatherLayer(
{
temperatureUnits: google.maps.weather.TemperatureUnit.CELSIUS,
windSpeedUnits: google.maps.weather.WindSpeedUnit.METERS_PER_SECOND
});
drawing = new google.maps.drawing.DrawingManager(
{
drawingControl : false,
drawingControlOptions : {
position : google.maps.ControlPosition.RIGHT_TOP,
drawingModes : [ google.maps.drawing.OverlayType.MARKER, google.maps.drawing.OverlayType.POLYGON, google.maps.drawing.OverlayType.POLYLINE ]
}
});
DrawingManager.setupEvents();
drawing.setMap(map);
$("[drawing]").each(function(index, element)
{
$(element).click(function(){
drawing.setOptions({drawingMode:$(this).attr("drawing")});
});
});
for(var methodname in MapOverlay)
MapOverlay[methodname].create();
if(Settings.showTraffic()) traffic.setMap(map);
if(Settings.showWeather()) weather.setMap(map);
$("[maptype]").click(function(){
TrackmeMap.control.type(this);
});
this.control.opt({mapTypeId : $.storage.getField("map", "type", "visicom")});
},
resize:function()
{
if(map) google.maps.event.trigger(map, "resize");
},
fill:function()
{
QFile("map",{u:"static"},function(json)
{
TrackmeMap.exFill(json);
Loaded("fill");
}, "json");
},
exFill:function(json)
{
if(!json) return;
if(json.draw)
{
if(json.draw.devices)
TrackmeMap.devices = json.draw.devices;
if(json.draw.markers)
for(var key in json.draw.markers)
TrackmeMap.add.base.Icon(key, json.draw.markers[key]);
}
if(json.zones)
for(var key in json.zones)
{
TrackmeMap.add.Zone(key, json.zones[key]);
}
if(json.labels)
for(var key in json.labels)
{
TrackmeMap.add.Label(key, json.labels[key]);
}
if(json.curr)
for(var key in json.curr)
{
var points = json.curr[key];
for(var pkey in points)
TrackmeMap.add.Current(key, points[pkey]);
}
if(json.dirs)
for(var key in json.dirs)
{
TrackmeMap.add.Direction(key, json.dirs[key]);
}
},
/* lists */
devices:[],
zones:[],
icons:[],
labels:[],
points:[],
directions:[],
currents:[],
tracks:[],
other:[],
/* end */
utils:
{
toRect:function(a, b)
{
var points =
[
new google.maps.LatLng(a.lat(), a.lng()),
new google.maps.LatLng(a.lat(), b.lng()),
new google.maps.LatLng(b.lat(), b.lng()),
new google.maps.LatLng(b.lat(), a.lng())
];
return points;
},
LatLngListToArray:function(array)
{
var list = [];
for(key in array)
list.push([array[key].lat(), array[key].lng()]);
return list;
},
replace:function(id, group, options, object)
{
if(group && group[id]) group[id].setMap(null);
if(group && object) group[id] = object;
object.ex = $.extend({id:id}, object.ex, options);
return object;
},
icon:function(name)
{
return TrackmeMap.icons[name];
},
distance:function(from, to) // latlng x2
{
if(!from) return 0;
var R = 6371, torad = Math.PI / 180; // Radius of the earth in km
var dLat = (to.lat()-from.lat()) * torad;
var dLon = (to.lng()-from.lng()) * torad;
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(from.lat() * torad) * Math.cos(to.lat() * torad) *
Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c; // Distance in km
return d;
}
},
add:
{
base:
{
Icon:function(name, options)
{
TrackmeMap.icons[name] = {
"url":"/img/"+options.file,
"anchor":{x:options.anchor[0],y:options.anchor[1]}
};
},
Polygon:function(id, group, options) // points, color, vis, text
{
var poly = new google.maps.Polygon({
"clickable":false,
"strokeColor":options.color,
"strokeOpacity":Slider.val("opzone"),
"strokeWeight":Slider.val("zonew"),
"fillColor":options.color,
"fillOpacity":Slider.val("opzonefill"),
"paths":options.points,
"map":options.vis?map:null,
});
return TrackmeMap.utils.replace(id, group, options, poly);
},
Marker:function(id, group, options)// x, y, icon, vis, text
{
var marker = new google.maps.Marker({
"icon":TrackmeMap.utils.icon(options.icon),
"position":options.position,
"flat":true,
"optimized":true,
"map":options.vis?map:null,
});
return TrackmeMap.utils.replace(id, group, options, marker);
},
Polyline:function(id, group, options) // path, color, vis, text
{
options = $.extend({color:"#000", vis:true}, options);
var line = new google.maps.Polyline({
"strokeColor":options.color,
"strokeOpacity":Slider.val("optrack"),
"strokeWeight":Slider.val("trackw"),
"path":options.path,
"map":options.vis?map:null,
});
return TrackmeMap.utils.replace(id, group, options, line);
},
Circle:function(id, group, options) //center, radius, color, vis
{
options = $.extend({color:"#000", vis:true}, options);
var circle = new google.maps.Circle({
"clickable":false,
"center":options.center,
"radius":options.radius,
"strokeColor":options.color,
"strokeOpacity":Slider.val("opzone"),
"strokeWeight":Slider.val("zonew"),
"fillColor":options.color,
"fillOpacity":Slider.val("opzonefill"),
"map":options.vis?map:null,
});
return TrackmeMap.utils.replace(id, group, options, circle);
},
CustomText:function(id, group, options) //position, offset, addClass, text, vis
{
options = $.extend({offset:{x:0, y:0}, addClass:"", vis:false, text:""}, options);
var custom = new google.maps.Label({
"map": options.vis?map:null,
"divid":"label-custom-"+id,
"divclass":"base shadow "+options.addClass,
"html":options.text,
"latlng":options.position,
"shiftX":options.offset.x,
"shiftY":options.offset.y,
"callback":options.callback,
"onadd":options.onadd,
"pane":"overlayImage"
});
return TrackmeMap.utils.replace(id, group, options, custom);
}
},
simple:
{
Line:function(points)
{
var line = new google.maps.Polyline({
map:map,
clickable:false,
path:points,
strokeColor:"#000000",
strokeOpacity:Slider.val("opzone"),
strokeWeight:Slider.val("zonew")
});
return line;
},
Poly:function(points)
{
var poly = new google.maps.Polygon({
map:map,
clickable:false,
path:points,
fillColor:"#000000",
fillOpacity:Slider.val("opzonefill"),
strokeColor:"#000000",
strokeOpacity:Slider.val("opzone"),
strokeWeight:Slider.val("zonew")
});
return poly;
},
Circle:function(center, radius)
{
var circle = new google.maps.Circle({
clickable:false,
center:center,
radius:radius,
strokeColor:"#000000",
strokeOpacity:Slider.val("opzone"),
strokeWeight:Slider.val("zonew"),
fillColor:"#000000",
fillOpacity:Slider.val("opzonefill"),
"map":map
});
return circle;
}
},
Zone:function(id, options)
{
for(key in options.points)
options.points[key] = new google.maps.LatLng(options.points[key][0], options.points[key][1]);
var r = TrackmeMap.add.base.Polygon(id, TrackmeMap.zones, options);
},
Current:function(devid, options) //id,s,t,h,x,y,p,vis,event
{
options.icon = options.s == 0 ? "s" : "d"+(Math.round(options.h/10)*10%360);
options.devname = TrackmeMap.devices[devid].name;
options.position = new google.maps.LatLng(options.x, options.y);
var trackIt = devid == $.storage.getField("opt", "td", 0);
if(TrackmeMap.currents[devid])
{
TrackmeMap.currents[devid].move(devid, options);
}
else
{
var marker = TrackmeMap.add.base.Marker(options.id, undefined, options);
TrackmeMap.currents[devid] = marker.label(devid, options).attachEvents();
if(trackIt) //if only start
Device.tracking.toggleView(true);
}
if(trackIt)
{
//if bounds changed
Device.tracking.updateView(TrackmeMap.currents[devid]);
if(map.getBounds() !== undefined && !map.getBounds().contains(options.position))
{
TrackmeMap.pan.toDevice(devid, false);
}
}
},
Label:function(id, options)
{
options.position = new google.maps.LatLng(options.x, options.y);
options.offset = {x:-12, y:-36};
options.addClass = "pointer-left-bottom";
var m = TrackmeMap.add.base.CustomText(id, TrackmeMap.labels, options);
return m;
},
JournalPoint:function(id, options)
{
options.position = new google.maps.LatLng(options.x, options.y);
options.icon = options.i;
TrackmeMap.add.base.Marker(id, TrackmeMap.points, options).attachEvents();
},
JournalPolyline:function(devid, path, color)
{
TrackmeMap.tracks[devid].push(TrackmeMap.add.base.Polyline(0, undefined, {path:path, color:color, vis:false}));
},
Direction:function(id, options)
{
TrackmeMap.directions[id] = {id:id, name:options.name, points:options.points};
}
},
remove:
{
Label:function(id)
{
TrackmeMap.labels[id].setMap(null);
TrackmeMap.labels[id] = undefined;
Table.upd("dot");
},
Zone:function(id)
{
TrackmeMap.zones[id].setMap(null);
TrackmeMap.zones[id] = undefined;
if(TrackmeMap.zones[id+"_lbl"])
{
TrackmeMap.zones[id+"_lbl"].setMap(null);
TrackmeMap.zones[id+"_lbl"] = undefined;
}
Table.upd("zon");
},
Direction:function(id)
{
TrackmeMap.labels[id] = undefined;
Table.upd("dir");
Direction.clrD();
}
},
update:
{
current:function()
{
var qstr = {};
for(var id in TrackmeMap.currents)
qstr[id] = TrackmeMap.currents[id].ex.id;
QFile("map",{u:"current",data:qstr},function(json)
{
if(json.length === undefined)
TrackmeMap.exFill({"curr":json});
}, "json");
}
},
search:function(text)
{
geocoder.geocode({address : text}, function(result, status)
{
map.panTo(result[0].geometry.location);
});
},
pan:
{
toDevice:function(id, open)
{
if(id instanceof HTMLElement)
{
var name = $(id).text();
for(var did in TrackmeMap.devices)
if(TrackmeMap.devices[did].name == name)
{
id = did;
break;
}
}
if(TrackmeMap.currents[id])
{
var marker = TrackmeMap.currents[id];
map.panTo(marker.getPosition());
if(open)
google.maps.event.trigger(marker, "click");
}
},
toPoint:function(id, open)
{
if(TrackmeMap.points[id])
{
map.panTo(TrackmeMap.points[id].getPosition());
if(open)
google.maps.event.trigger(TrackmeMap.points[id], "click");
}
},
toZone:function(id)
{
if(TrackmeMap.zones[id])
map.fitBounds(TrackmeMap.getBounds(TrackmeMap.zones[id].getPath()));
},
toLabel:function(id)
{
if(TrackmeMap.labels[id])
map.panTo(TrackmeMap.labels[id].ex.position);
},
toDirection:function(id)
{
},
toAll:function()
{
var list = new google.maps.MVCArray();
for(var kpoint in TrackmeMap.currents)
{
if(TrackmeMap.currents[kpoint].getMap())
list.push(TrackmeMap.currents[kpoint].getPosition());
}
map.fitBounds(TrackmeMap.getBounds(list));
},
bind:function()
{
$("[goto]").each(function(index, element)
{
$(element).off("click").click(function()
{
var go = $(this).attr("goto").split(":");
var type = go[0];
var id = parseInt(go[1]);
var open = parseInt(go[2]) && true;
switch(type)
{
case "d":
case "device":
TrackmeMap.pan.toDevice(id, open);
break;
case "z":
case "zone":
TrackmeMap.pan.toZone(id);
break;
case "p":
case "point":
TrackmeMap.pan.toPoint(id);
break;
case "l":
case "label":
TrackmeMap.pan.toLabel(id);
break;
}
});
});
}
},
events:
{
/* Events */
mapClickListener:null,
mapRClickListener:null,
mapMouseMoveListener:null,
clickListener:function(func)
{
if (this.mapClickListener)
google.maps.event.removeListener(this.mapClickListener);
if (func != null)
this.mapClickListener = google.maps.event.addListener(map, "click", func);
},
rClickListener:function(func)
{
if (this.mapRClickListener)
google.maps.event.removeListener(this.mapRClickListener);
if (func != null)
this.mapRClickListener = google.maps.event.addListener(map, "rightclick", func);
},
mouseMoveListener: function(func)
{
if (this.mapMouseMoveListener)
google.maps.event.removeListener(this.mapMouseMoveListener);
if (func != null)
this.mapMouseMoveListener = google.maps.event.addListener(map, "mousemove", func);
},
setDefault:function()
{
this.clickListener(function(event)
{
InfoWindow.hide();
});
this.rClickListener(null);
this.mouseMoveListener(null);
},
setBase:function()
{
google.maps.event.addListener(map, "dragstart", function()
{
$(".label-custom").hide();
});
google.maps.event.addListener(map, "dragend", function()
{
$(".label-custom").show();
});
google.maps.event.addListener(map, "zoom_changed", function()
{
TrackmeMap.saveState();
});
google.maps.event.addListener(map, "center_changed", function()
{
TrackmeMap.saveState();
for(var id in TrackmeMap.currents)
TrackmeMap.currents[id].ex.label.draw();
});
}
},
saveState:function()
{
var center = map.getCenter();
$.storage.setFields("map", {"x":center.lat(),"y":center.lng(),"zoom":map.getZoom()});
},
getBounds:function(path)
{
path = path.getArray();
var bounds = new google.maps.LatLngBounds();
for(var k in path)
bounds.extend(path[k]);
return bounds;
},
control:
{
plus:function()
{
TrackmeMap.control.opt({zoom : map.getZoom()+1});
},
minus:function()
{
TrackmeMap.control.opt({zoom : map.getZoom()-1});
},
type:function(instance)
{
var type = google.maps.MapTypeId.ROADMAP;
var select = $(instance).attr("maptype");
switch(select)
{
case "gmap":
type = google.maps.MapTypeId.ROADMAP;
break;
case "gsat":
type = google.maps.MapTypeId.SATELLITE;
break;
default:
type = select;
break;
}
$.storage.setField("map", "type", type);
this.opt({mapTypeId : type});
},
opt:function(opts)
{
map.setOptions(opts);
},
zindex:
{
auto:function(actor, selector)
{
$(actor).mouseover(function(){
TrackmeMap.control.zindex.down(selector);
TrackmeMap.control.zindex.up(this);
});
},
down:function(selector)
{
$(selector).each(function(index, e){
$(e).css({"z-index":Math.max(0,$(e).css("z-index")-1)});
});
},
up:function(actor)
{
$(actor).css({"z-index":100});
}
}
}
};var MapOverlay =
{
yandex:
{
ID:"yandex",
create:function()
{
function YandexProjection()
{
this.pixelOrigin_ = new google.maps.Point(128,128);
var MERCATOR_RANGE = 256;
this.pixelsPerLonDegree_ = MERCATOR_RANGE / 360;
this.pixelsPerLonRadian_ = MERCATOR_RANGE / (2 * Math.PI);
this.fromLatLngToPoint = function(latLng)
{
function atanh(x)
{
return 0.5*Math.log((1+x)/(1-x));
}
function degreesToRadians(deg)
{
return deg * (Math.PI / 180);
}
function bound(value, opt_min, opt_max)
{
if (opt_min != null) value = Math.max(value, opt_min);
if (opt_max != null) value = Math.min(value, opt_max);
return value;
}
var origin = this.pixelOrigin_;
var exct = 0.0818197;
var z = Math.sin(latLng.lat()/180*Math.PI);
return new google.maps.Point(origin.x + latLng.lng() *this.pixelsPerLonDegree_,
Math.abs(origin.y - this.pixelsPerLonRadian_*(atanh(z)-exct*atanh(exct*z))));
};
this.fromPointToLatLng = function(point)
{
var origin = this.pixelOrigin_;
var lng = (point.x - origin.x) / this.pixelsPerLonDegree_;
var latRadians = (point.y - origin.y) / -this.pixelsPerLonRadian_;
var lat = Math.abs((2*Math.atan(Math.exp(latRadians))-Math.PI/2)*180/Math.PI);
var Zu = lat/(180/Math.PI);
var Zum1 = Zu+1;
var exct = 0.0818197;
var yy = -Math.abs(((point.y)-128));
while(Math.abs(Zum1-Zu)>0.0000001)
{
Zum1 = Zu;
Zu = Math.asin(1-((1+Math.sin(Zum1))*Math.pow(1-exct*Math.sin(Zum1),exct))
/ (Math.exp((2*yy)/-(256/(2*Math.PI)))*Math.pow(1+exct*Math.sin(Zum1),exct)));
}
if(point.y>256/2)
{
lat=-Zu*180/Math.PI;
}
else
{
lat=Zu*180/Math.PI;
}
return new google.maps.LatLng(lat, lng);
};
return this;
};
var ytype =
{
tileSize: new google.maps.Size(256, 256),
maxZoom:17,
minZoom:0,
name:this.ID,
alt:this.ID,
projection: new YandexProjection(),
getTile:function(tileCoord, zoom, ownerDocument)
{
return $.t("img", {"src":MapOverlay.yandex.getURL(tileCoord, zoom)}).get(0);
}
};
map.mapTypes.set(this.ID, ytype);
},
getURL:function(coord, zoom)
{
return "https://vec0"+(coord.x%4 + 1)+".maps.yandex.net/tiles?l=map&x="+coord.x+"&y="+coord.y+"&z="+zoom;
}
},
visicom:
{
ID:"visicom",
create:function()
{
var vtype =
{
tileSize: new google.maps.Size(256, 256),
maxZoom:18,
minZoom:0,
name:this.ID,
alt:this.ID,
//projection:this.projection,
getTile:function(tileCoord, zoom, ownerDocument)
{
return $.t("img", {"src":MapOverlay.visicom.getURL(tileCoord, zoom)}).get(0);
}
};
map.mapTypes.set(this.ID, vtype);
},
getURL:function(coord, zoom)
{
var version = "1.0.3";
var lang = "ru";
return "https://tms"+(coord.x%4)+".visicom.ua/"+version+"/world_"+lang+"/" + zoom + "/" + coord.x + "/" + ((1 << zoom) - (coord.y + 1)) + ".png";
}
},
osmoffline:
{
ID:"osmoffline",
create:function()
{
var osmtype =
{
tileSize: new google.maps.Size(256, 256),
maxZoom:18,
minZoom:0,
name:this.ID,
alt:this.ID,
getTile:function(coord, zoom, ownerDocument)
{
//using local proxy for OSM tiles
var src = "/tiles/osm/"+zoom+"/"+coord.x+"/"+coord.y+".png";
return $.t("img", {"src":src}).get(0);
}
};
map.mapTypes.set(this.ID, osmtype);
}
}
};var Notify =
{
step:2,
maxID:0,
loading:false,
requestPermission:function() {
if(!window.Notification) {
return;
}
Notification.requestPermission();
},
native:function(names) {
if(!window.Notification) {
return;
}
var options = {
body: names.join(", "),
icon: "/img/logo/logo_128.png",
}
try {
var notification = new Notification("У вас есть новые уведомления", options);
notification.onclick = function(e) {
window.focus();
notification.close();
}
} catch(e) {
//Not supported or mobile
}
},
synchronize:function()
{
if(!Settings.notify() || this.loading) return;
this.loading = true;
Notify.requestPermission();
/*$("#notifylist .msg").each(function(index, element)
{
Notify.maxID = Math.max(Notify.maxID, parseInt($(element).attr("point"), 10));
});*/
Q({notify:true, maxID:this.maxID}, function(json)
{
for(var msgId in json)
{
Notify.add(msgId, json[msgId]);
}
var deviceNames = [];
for(var msgId in json)
{
var event = json[msgId];
if(event.level >= Slider.val("notifylevel"))
{
if(deviceNames.indexOf(event.name) < 0)
deviceNames.push(event.name);
}
}
if(deviceNames.length) {
Notify.native(deviceNames);
}
Notify.loading = false;
}, "json");
},
add:function(msgId, data)
{
Notify.maxID = Math.max(Notify.maxID, msgId);
$("#notifylist").append(Template.load("notify", data));
Notify.redraw();
TrackmeMap.pan.bind();
if(data.level < Slider.val("notifylevel"))
{
setTimeout(function(){
Notify.remove($("div[point="+msgId+"]"));
}, 10*1000);
}
},
redraw:function()
{
$("#notifylist .msg").each(function(index, element) {
$(element).css({top:(Notify.step * index)+"em"})
});
},
remove:function(object)
{
var msg = $(object).closest(".msg");
msg.hide("drop", {direction: "right"}, jqui_speed/4, function()
{
$(this).remove();
Notify.redraw();
});
Q({"confirm":msg.attr("point")});
}
};var Panel =
{
init:function()
{
$("[window]").click(function(event)
{
Panel.toggle("#"+$(this).attr("window"));
});
$(".box").each(function(index, dialog)
{
dialog = $(dialog);
var resizable = dialog.attr("resizable") == "true";
var save = function(event, ui)
{
var pos = dialog.dialog("option", "position");
var h = dialog.dialog("option", "height");
var w = dialog.dialog("option", "width");
dialog.saved = {
x:pos[0],
y:pos[1],
h:h,
w:w
};
$.storage.setField("position", dialog.attr("id"), dialog.saved);
};
var pos = $.storage.getField("position", dialog.attr("id"), {h:200, w:400});
var effect = {effect: "drop", direction: "up", duration:jqui_speed};
if(!resizable)
pos.h = pos.w = "auto";
dialog.dialog({
autoOpen:false,
dialogClass:"base shadow",
buttons:[],
draggable:true,
modal:false,
resizable:resizable,
minHeight:200,
minWidth: 400,
height: pos.h,
width: pos.w,
position:[pos.x, pos.y],
show:Settings.useEffects() ? effect : undefined,
hide:Settings.useEffects() ? effect : undefined,
dragStop:save,
resizeStop:save
}).saved = pos;
if(resizable)
{
dialog.parent().find(".ui-dialog-titlebar").dblclick(function()
{
var uiClass = "ui-max";
if(dialog.hasClass(uiClass))
{
dialog.dialog("option", {height: dialog.saved.h, width: dialog.saved.w});//
dialog.dialog("option", {position:[dialog.saved.x, dialog.saved.y]});
dialog.removeClass(uiClass);
}
else
{
var head = $("div.head").outerHeight();
dialog.dialog("option", {position:[0, head], height:$(window).height() - head, width: $(window).width()}).addClass(uiClass);
}
});
}
});
},
toggle:function(win, open)
{
win = $(win);
open = open !== undefined ? open : !win.dialog("isOpen");
win.dialog(open ? "open" : "close");
}
};var Reports =
{
init:function()
{
var options = Period.options.clone();
var begin = $("#report-begin-dp");
var end = $("#report-end-dp");
options.onSelect = function(dateText, inst)
{
var date = Period.date.strToDate(dateText);
if(inst.id == "report-end-dp")
begin.datetimepicker("option",
{
maxDate:date
});
if(inst.id == "report-begin-dp")
end.datetimepicker("option",
{
minDate:date
});
};
options.minDate = Period.date.unixtimeToDate(Period.bounds.min);
begin.datetimepicker(options).datetimepicker("setDate", Period.date.strToDate(begin.val()));
end.datetimepicker(options).datetimepicker("setDate", Period.date.strToDate(end.val()));
},
create:function()
{
$("#report-begin").val(Period.date.get("#report-begin-dp"));
$("#report-end").val(Period.date.get("#report-end-dp"));
$(document.newreport).attr("target", Settings.newWindow() || $("body").hasClass("mini") ? "_blank" : "report").submit();
},
print:function()
{
var title = document.title;
document.title = window.report.document.title;
window.report.print();
document.title = title;
},
check:function()
{
var list = $("#tabs-reports").find(".buttonset input");
list.prop("checked", !list.prop("checked")).button("refresh");
event.preventDefault();
}
};var Search =
{
bind:function()
{
var box = $("#searchbox");
var results = box.find(".results");
var input = box.find("input");
var devices = box.find(".devices");
var zones = box.find(".zones");
var markers = box.find(".markers");
var nav = box.find(".nav");
var find = function(search, array, container, getContent, action)
{
container.children("a").remove();
for(var k in array)
{
var name = getContent.call(array[k]);
if(name && (search == "" || name.containsi(search)))
{
!function(target)
{
container.append($.t("a", {html:name, href:"#"}).click(function()
{
action.call(target);
box.hide();
}));
}(array[k]);
}
}
container.children("a").size() == 0 ? container.hide() : container.show();
}
var selected = 0;
var action = function(event)
{
var pointer = function(up)
{
var a = $(box.selector).find("a:visible").removeClass("hover");
selected = Math.min(Math.max(up ? --selected : ++selected, 0), a.size()-1);
$(a.get(selected)).addClass("hover");
/*var top = $(a.get(selected)).addClass("hover").position().top;
if(results.scrollTop() < top)
results.scrollTop(top);*/
event.stopPropagation();
event.preventDefault();
};
switch(event.which)
{
case 27:
box.hide();
return;
case 13:
box.find("a.hover").get(0).click();
return;
case 38:
pointer(true);
return;
case 40:
pointer(false);
return;
}
var search = input.val();
find(search, TrackmeMap.devices, devices,
function()
{
var point = TrackmeMap.currents[this.id];
return point && this.name;
},
function()
{
TrackmeMap.pan.toDevice(this.id, true);
});
find(search, TrackmeMap.zones, zones, function(){return this.ex.name}, function()
{
TrackmeMap.pan.toZone(this.ex.id);
});
find(search, TrackmeMap.labels, markers, function(){return this.ex.text}, function()
{
TrackmeMap.pan.toLabel(this.ex.id);
});
nav.show();
nav.children("a").each(function(index, element)
{
element = $(element);
if(element.text().containsi(search))
element.show();
else
element.hide();
});
nav.children("a:visible").size() == 0 ? nav.hide() : nav.show();
selected = 1;
pointer(true, event);
}
/* bind */
input.keyup(action).focus(function(event)
{
$(this).select();
action.call(this, event);
});
box.find(".address a").click(function(event)
{
TrackmeMap.search(input.val());
box.hide();
});
box.find(".hint").click(function(event)
{
input.val("").focus();
});
$(window).keydown(function(event)
{
if(event.altKey && event.which === 83)
{
$("[ui-open=searchbox]").click();
event.preventDefault();
event.stopPropagation();
}
});
},
filterDevice:function(input)
{
this.filter(input, "userdevsearch", {"searchname":"span", "searchimei":"div"/*, "searchtype":"select", "searchmodel":"text", "searchversion":"text"*/});
},
filter:function(input, rowName, keys)
{
var searchText = $(input).val().toLowerCase();
$("tr."+rowName).each(function(index, element)
{
element = $(element);
var valuelist = [];
for(var key in keys)
{
var type = keys[key];
switch(type)
{
case "text":
valuelist.push(element.children("td."+key).text());
break;
case "input":
valuelist.push(element.find("td."+key + " input").val());
break;
case "select":
valuelist.push(element.find("td."+key+" option:selected").text());
break;
default:
valuelist.push(element.find("td."+key+" "+type).text());
break;
}
}
for(var valkey in valuelist)
if(valuelist[valkey].toLowerCase().contains(searchText))
{
element.show();
return;
}
element.hide();
});
}
};var Slider =
{
// -------------------------------------------
// User settings
sliders:{},
create:function(id, min, max, step, value)
{
Slider.sliders[id] = value;
$("#slider-val-" + id).html(value);
var slider = $("#" + id).slider({
min : min,
max : max,
value : value,
step : step,
stop : Slider.stop,
slide : Slider.slide,
});
Slider.slide(null,
{
handle:slider.find("a.ui-slider-handle"),
value:value
});
},
val:function(name)
{
return Slider.sliders[name];
},
stop:function(event, ui)
{
var id = $(ui.handle).parent().attr("id");
Q({name : id, value : ui.value}); //set value in server
switch(id)
{
case "updspd":
Update.start();
break;
}
},
slide:function(event, ui)
{
var id = $(ui.handle).parent().attr("id");
Slider.sliders[id] = ui.value;
$("#slider-val-" + id).html(ui.value);
switch(id)
{
case "optrack":
case "trackw":
for(var key in TrackmeMap.tracks)
{
var list = TrackmeMap.tracks[key];
for(var line in list)
list[line].setOptions(
{
strokeWeight : Slider.val("trackw"),
strokeOpacity : Slider.val("optrack")
});
}
for(var key in TrackmeMap.currents)
{
if(TrackmeMap.currents[key].ex.back)
TrackmeMap.currents[key].ex.back.setOptions(
{
strokeWeight : Slider.val("trackw"),
strokeOpacity : Slider.val("optrack")
});
}
break;
case "opzone":
case "zonew":
case "opzonefill":
for(var key in TrackmeMap.zones)
{
TrackmeMap.zones[key].setOptions(
{
strokeWeight : Slider.val("zonew"),
strokeOpacity : Slider.val("opzone"),
fillOpacity: Slider.val("opzonefill")
});
}
break;
case "notifylevel":
$(".autoconfirm img").each(function(index, element)
{
element = $(element);
if(index < ui.value-1)
element.css({opacity:0.3, "-webkit-filter":"grayscale(1)"});
else
element.css({opacity:1, "-webkit-filter":"grayscale(0)"});
});
break;
}
}
// User settings end
// -------------------------------------------
};var Settings =
{
val:function(name)
{
var object = $("input[name='" + name + "'], select[name='" + name + "']");
if(object.size() === 0) return;
switch(object.attr("type"))
{
case "checkbox": return object.is(":checked");
case "select": return object.get(":selected").val();
case "text": return object.val();
}
},
useEffects:function(){return Settings.val("useeffects");},
autoDownload:function(){return Settings.val("autodownload");},
checkNew:function(){return Settings.val("checknew");},
notify:function(){return Settings.val("notify");},
gotonew:function(){return Settings.val("gotonew");},
showTraffic:function(){return Settings.val("showtraffic");},
showWeather:function(){return Settings.val("showweather");},
hideVoid:function(){return Settings.val("hidevoid");},
coloredTrack:function(){return Settings.val("coloredtrack");},
showDirection:function(){return Settings.val("showdirection");},
scaleToTrack:function(){return Settings.val("scaletotrack");},
showDeviceNames:function(){return Settings.val("showdevicenames");},
newWindow:function(){return Settings.val("reportnewwindow");},
checkboxclick:function(object)
{
Q({name:object.name, value:object.checked}, function(name)
{
switch(name)
{
case "useeffects":
location.reload(true);
break;
}
});
switch(object.name)
{
case "showtraffic":
traffic.setMap(traffic.getMap()?null:map);
break;
case "showweather":
weather.setMap(weather.getMap()?null:map);
break;
case "showdevicenames":
for(var dev in TrackmeMap.currents)
TrackmeMap.currents[dev].updateAttach();
break;
}
},
password:function()
{
var fields = [
{name:"change-password", type:"password", label:str("newpass")},
{name:"change-password-confirm", type:"password", label:str("conpass")},
{name:"current-password", type:"password", label:str("currpass")}
];
$.dialogs.form(fields, {title:fonticon("key"), id:"password", callback:function()
{
if($("#form-change-password, #form-change-password-confirm").checker("get"))
{
Q({pass:$.dialogs.value("change-password"), oldpass:$.dialogs.value("current-password")}, function(html)
{
$.dialogs.alert(html);
});
return;
}
return "stop";
}});
$("#form-change-password").checker("password");
$("#form-change-password-confirm").checker("equal", {element:"#form-change-password"});
},
phone:function(self)
{
var input = self;
$.dialogs.input($(input).text(), function()
{
if($("#form-value").checker("get"))
{
var phone = $.dialogs.value();
Unit.set(5, "Phone", phone, "u", function() {
$(input).text(phone);
});
return;
}
return "stop";
}, {title:"+380xxxxxxxxx"});
$("#form-value").checker(
{
regexp: /^\+380[0-9]{9}$/
});
},
apikey:function()
{
$.dialogs.confirm(str("getnewkeyask"), function(){
Q({apikey:1}, function(key){
$("#apikey-val").val(key);
});
}, {title:str("getnewkey")});
}
};
var Unit =
{
select:function(uid, type, event)
{
var group = null;
if(type == 'z') group = TrackmeMap.zones;
else if (type == 'd') group = TrackmeMap.currents;
else if (type == 'l') group = TrackmeMap.labels;
var obj = group[uid];
if(obj)
{
obj.setMap(obj.getMap() == null?map:null);
if(obj.updateAttach) obj.updateAttach();
}
Unit.set(uid, "Selected", 1, type);
if(event) event.stopPropagation();
return false;
},
//----- do work
set:function(id, param, value, type, callback)
{
var obj = $(id);
var attr = obj.attr("object");
if(attr)
{
attr = attr.split(";");
id = attr[0];
param = attr[2];
value = obj.val();
type = attr[1];
}
Q({set:id, k:param, v:value, t:type}, callback, "json");
},
colorList:function(me)
{
var dialog = $.t("div", {addClass:"center"});
var unitid = $(me).attr("ctid");
for(var k in Unit.colors)
{
dialog.append(
$.t("div", {addClass:"color"}).
attr("color", Unit.colors[k]).
css({background:Unit.colors[k]}).
click(function()
{
var type = $(me).attr("type");
Unit.set($(me).attr("ctid"), "Color", $(this).attr("color"), type, function(response)
{
$(me).css({background : response.color});
switch(type)
{
case "d":
TrackmeMap.devices[response.id].color = response.color;
break;
case "z":
TrackmeMap.zones[response.id].color = response.color;
break;
}
});
})
);
}
$.dialogs.alert(dialog, {title:"", unique:"cfg-color"});
},
colors:[
"#000000",
"#FF0000",
"#00FF00",
"#0000FF",
"#FFFF00",
"#00FFFF",
"#FF00FF",
"#FFFFFF"
]
};var Chart = {
instance : null,
defaults : {
},
load : function()
{
$("#chart").html("").addClass("loader");
Highcharts.setOptions(
{
global:{useUTC: false}
});
var error = function()
{
$("#chart").html($.t("div", {html:str("nodata"), addClass:"msg"}));
}
QFile("grid",
{
table : "chart",
dev : $("#to_chart option:selected").val(),
type : $("#charttype option:selected").val()
},
function(data)
{
if(data.empty)
{
error();
return;
}
try
{
Chart.instance = new Highcharts.StockChart($.extend(
{
chart:
{
renderTo : "chart",
zoomType: "x"
},
credits:
{
enabled: false
},
scrollbar:
{
liveRedraw: false
},
xAxis:
{
ordinal: false
},
title:
{
text : $("#to_chart option:selected").text() + ": " + $("#charttype option:selected").text(),
align : "right"
},
plotOptions:
{
series:
{
events:
{
click: function(event)
{
TrackmeMap.pan.toPoint(event.point.config[2], true);
}
}
}
},
tooltip:
{
yDecimals:2
}
}, data));
}
catch(e)
{
error();
}
$("#chart").removeClass("loader");
}, "json");
}
};
var Table = {
instances : [],
selects : [],
init : function(name)
{
if (name === undefined || name == "") return;
QFile("grid", {table : name}, function(json)
{
Table.fill(name, json);
});
},
fill : function(name, json)
{
try
{
if (json == "") return;
if (typeof (json) == 'string') json = $.parseJSON(json);
var data = new google.visualization.DataTable({
cols : json.fields
});
data.addRows(json.values);
Table.selects[name] = json.select;
Table.draw(name, data);
}
catch (e)
{
error(e);
}
},
draw : function(name, data)
{
var sort = false;
var scroll = $("#" + name).parent().scrollTop();
if (Table.instances[name])
{
sort = Table.instances[name].getSortInfo();
Table.instances[name].clearChart();
}
switch(name)
{
case "dev":
var pattern = $.html($.t("span", {onclick:"TrackmeMap.pan.toDevice(this, true)", html:"{0}"}));
var formatter = new google.visualization.PatternFormat(pattern);
formatter.format(data, [3]);
break;
}
Table.instances[name] = new google.visualization.Table($("#" + name).get(0));
var css = {
headerRow : "google-th",
oddTableRow : "google-tr",
tableRow : "google-tr",
hoverTableRow : "google-tr-hover",
headerCell : "google-td",
tableCell : "google-td",
selectedTableRow : "google-tr-sel"
};
Table.instances[name].draw(data, {
showRowNumber : false,
alternatingRowStyle : true,
allowHtml : true,
width : "100%",
sortColumn : sort ? sort.column : undefined,
sortAscending : sort ? sort.ascending : undefined,
cssClassNames : css
});
google.visualization.events.addListener(Table.instances[name], 'select', function()
{
if (!Table.instances[name].getSelection()[0]) return;
var row = Table.instances[name].getSelection()[0].row;
row = Table.selects[name][row];
switch (name)
{
/*case "dev":
TrackmeMap.pan.toDevice(row, true);
break;*/
case "dot":
TrackmeMap.pan.toLabel(row, true);
break;
case "zon":
TrackmeMap.pan.toZone(row);
break;
case "dir":
Direction.paint(row);
break;
case "eventlist":
TrackmeMap.pan.toPoint(row, true);
break;
case "jour":
Period.restore(row[0], row[1], row[2]);
break;
}
//if (name.indexOf("list") == 0) TrackmeMap.pan.toPoint(row, true);
Table.instances[name].setSelection(null);
});
$("#" + name).parent().scrollTop(scroll);
Loaded("global");
},
upd : function(name)
{
Table.init(name);
},
load : function()
{
$(".grid").each(function(index, Element)
{
Table.init(Element.id);
});
}
};
/*QFile("grid",
{
table : "chart",
dev : $("#to_chart option:selected").val(),
type : $("#charttype option:selected").val()
}, function(json)
{
console.log(json);
json = $.parseJSON(json, false);
if(json.length == 0)
{
$("#chart").removeClass("loader").html($.t("div", {html:str("nodata"), addClass:"msg"}));
return;
}
// SERIAL CHART
var chart = new AmCharts.AmSerialChart();
chart.pathToImages = "/img/amcharts/";
chart.dataProvider = json.data;
chart.autoMargins = true;
chart.categoryField = "Time";
// AXES
// category, bottom
var categoryAxis = chart.categoryAxis;
categoryAxis.parseDates = true;
categoryAxis.minPeriod = "ss"; //seconds
// value, left
//var valueAxis = new AmCharts.ValueAxis();
//chart.addValueAxis(valueAxis);
for(var key in json.graph)
{
// GRAPH
graph = new AmCharts.AmGraph();
graph.lineColor = "#637bb6";
graph.bullet = "round";
graph.bulletSize = 4;
graph.lineThickness = 1;
graph.valueField = json.graph[key];
graph.title = json.graph[key];
chart.addGraph(graph);
}
// CURSOR
var chartCursor = new AmCharts.ChartCursor();
chartCursor.categoryBalloonDateFormat = "JJ:NN, DD.MM.YYYY";
chartCursor.cursorColor = "#637bb6";
chart.addChartCursor(chartCursor);
// SCROLLBAR
var chartScrollbar = new AmCharts.ChartScrollbar();
//chartScrollbar.graph = graph;
chart.addChartScrollbar(chartScrollbar);
// LEGEND
var legend = new AmCharts.AmLegend();
//legend.color = "#000000";
chart.addLegend(legend);
// WRITE
chart.write("chart");
$("#chart").removeClass("loader");
Chart.instance = chart;
});*/var Tabs =
{
args:{},
init : function(args)
{
this.args = $.extend({dialog:"#tabs", tabs:"#tabs"}, args);
var opts = {
/*minHeight : 250,
minWidth : 440,*/
modal : true,
dialogClass : "base",
resizable : false,
draggable : false,
autoOpen : false,
};
$(this.args.dialog).dialog(opts);
$(this.args.tabs).tabs({
beforeActivate:function(event, ui)
{
switch(ui.newPanel.attr("id"))
{
case "tabs-devices":
Tabs.update.devices();
break;
case "tabs-zones":
Tabs.update.zones();
break;
}
}
});
},
redraw:function()
{
var mini = $("body").hasClass("mini") ? 0 : 50;
var dialog = $(this.args.dialog).dialog("option",
{
height : $(window).height() - mini,
width : $(window).width() - mini,
});
var panels = dialog.find(".ui-tabs-panel");
var padding = panels.outerHeight() - panels.height();
panels.height(dialog.outerHeight() - padding - dialog.find(".ui-tabs-nav").height());
},
open:function(index)
{
$(this.args.dialog).dialog("open");
this.redraw();
$(this.args.tabs).tabs({active:index});
},
devices:function()
{
Tabs.update.devices();
this.open(0);
},
zones:function()
{
Tabs.update.zones();
this.open(1);
},
photos:function()
{
this.open(2);
},
reports:function()
{
this.open(3);
},
history:function()
{
this.open(4);
},
loadhistory:function()
{
QFile("grid", $("#historyform").serialize(), function(json)
{
Table.fill("historylist", json);
}, "json");
},
update:
{
devices:function()
{
$("#tabs-devices").addClass("loader");
$("#sortdevice").fadeOut();
Q({"updateblock":"sttdev"}, function(html)
{
$("#tabs-devices").html(html).removeClass("loader");
Interface.update();
});
},
zones:function()
{
$("#tabs-zones").addClass("loader");
$("#sortzone").fadeOut();
Q({"updateblock":"sttzon"}, function(html)
{
$("#tabs-zones").html(html).removeClass("loader");
Interface.update();
});
},
}
};var Template =
{
list:{
},
generate:function()
{
this.list =
{
notify: $.html(
$.t("div", {addClass:"base box shadow msg %tag%", point:"%id%"}).
append($.t("div", {addClass:"title"}).
append($.t("a", {"goto":"device:%devid%", html:"%name%"})).
append(": %event%").
append($.t("span", {addClass:"ui-icon ui-icon-closethick fr", onclick:"Notify.remove(this)", html:"x"})
).
append($.t("hr")).
append($.t("div", {addClass:"data"}).
append("%value%").
append($.t("hr")).
append($.t("span", {addClass:"fr", html:"%icon%"})).
append("GPS "+str("time")+": %time%").
append($.t("br")).
append($.t("span", {addClass:"small gray", html:str("received")+": %stime%"}))
)
)
),
point: $.html(
$.t("table").
append(
$.t("tr").
append($.t("td", {colspan:2, html:$.t("b", {html:"%name%"}), addClass:"center"}))
).
append(
$.t("tr").
append($.t("td", {html:str("speed"), addClass:"text-right"})).
append($.t("td", {html:"%speed% "+str("kmh")}))
).
append(
$.t("tr").
append($.t("td", {html:str("mileage"), addClass:"text-right"})).
append($.t("td", {html:"%dist% km"}))
).
append(
$.t("tr").
append($.t("td", {html:str("fuel"), addClass:"text-right"})).
append($.t("td", {html:"%fuel% л"}))
).
append(
$.t("tr").
append($.t("td", {colspan:2, html:"
%time%"}))
)
),
ask: $.html($.t("div", {addClass:"center big", html:"%q%"}))
};
},
load:function(name, values)
{
var string = this.list[name];
if(!string) return "";
return this.replace(string, values);
},
replace:function(string, values)
{
for(var name in values)
string = string.replace("%"+name+"%", values[name]);
return string;
}
};var Thread =
{
lastid:0,
threads:[],
isRunning:function(id)
{
return Thread.threads[id] !== undefined && Thread.threads[id].ended == false;
},
stop:function(id)
{
if(Thread.threads[id] !== undefined)
Thread.threads[id].canceled = true;
},
stopAll:function()
{
for(var id in Thread.threads)
this.stop(id);
},
run:function(array, argss, func, after, cancel, iteration)
{
var id = Thread.lastid++;
var keys = [];
for(var key in array) keys.push(key);
Thread.threads[id] = {
timer:0,
arr:array,
args:argss,
keyset:keys,
iterations:iteration===undefined?1:iteration,
iteration:0,
runnable:func,
onEnd:after,
onCancel:cancel,
buffer:{},
canceled:false,
ended:false
};
setTimeout(function(id)
{
var thread = Thread.threads[id];
if(thread === undefined) return;
if(!thread.canceled)
{
for(var k=0;k= thread.keyset.length)
{
if(thread.onEnd)
thread.onEnd.call(thread);
thread.ended = true;
}
else
{
if(thread.canceled)
{
if(thread.onCancel)
thread.onCancel.call(thread);
thread.ended = true;
}
else
setTimeout(arguments.callee, 0, id);
}
}, 0, id);
return id;
}
};var Update =
{
isOnline:true,
interval:null,
bar:null,
barCounter:0,
barMax:0,
start:function(time)
{
if(this.interval) clearInterval(this.interval);
if(this.bar) clearInterval(this.bar);
if(time === undefined) time = Slider.val("updspd");
this.interval = setInterval(this.run, time*1000);
this.run(true);
this.barCounter = 1;
this.barMax = time;
this.bar = setInterval(function()
{
$("#updbar").progressbar({value:++Update.barCounter, max:Update.barMax});
}, 1000);
},
run:function(force)
{
Update.barCounter = 0;
if(force || Settings.checkNew() && Update.isOnline)
{
TrackmeMap.update.current();
Table.upd("dev");
Notify.synchronize();
}
else
Update.ping();
},
ping:function()
{
Q({ping:1});
},
on:function()
{
Update.isOnline = true;
$("#updbar").removeClass("off");
},
off:function(msg)
{
if(Update.isOnline)
{
Update.isOnline = false;
$("#updbar").addClass("off");
error(msg?msg:str("noConn"));
}
}
};