<commit_before>/*
   Copyright 2011 Lazar Laszlo (lazarsoft@gmail.com, www.lazarsoft.info)

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

var qrcode = {};
qrcode.imagedata = null;
qrcode.width = 0;
qrcode.height = 0;
qrcode.qrCodeSymbol = null;
qrcode.debug = false;
qrcode.maxImgSize = 1024*1024;

qrcode.sizeOfDataLengthInfo =  [  [ 10, 9, 8, 8 ],  [ 12, 11, 16, 10 ],  [ 14, 13, 16, 12 ] ];

qrcode.callback = null;

qrcode.vidSuccess = function (stream)
{
    qrcode.localstream = stream;
    if(qrcode.webkit)
        qrcode.video.src = window.webkitURL.createObjectURL(stream);
    else
    if(qrcode.moz)
    {
        qrcode.video.mozSrcObject = stream;
        qrcode.video.play();
    }
    else
        qrcode.video.src = stream;

    qrcode.gUM=true;

    qrcode.canvas_qr2 = document.createElement('canvas');
    qrcode.canvas_qr2.id = "qr-canvas";
    qrcode.qrcontext2 = qrcode.canvas_qr2.getContext('2d');
    qrcode.canvas_qr2.width = qrcode.video.videoWidth;
    qrcode.canvas_qr2.height = qrcode.video.videoHeight;
    setTimeout(qrcode.captureToCanvas, 500);
}

qrcode.vidError = function(error)
{
    qrcode.gUM=false;
    return;
}

qrcode.captureToCanvas = function()
{
    if(qrcode.gUM)
    {
        try{
            if(qrcode.video.videoWidth == 0)
            {
                setTimeout(qrcode.captureToCanvas, 500);
                return;
            }
            else
            {
                qrcode.canvas_qr2.width = qrcode.video.videoWidth;
                qrcode.canvas_qr2.height = qrcode.video.videoHeight;
            }
            qrcode.qrcontext2.drawImage(qrcode.video,0,0);
            try{
                qrcode.decode();
            }
            catch(e){
                console.log(e);
                setTimeout(qrcode.captureToCanvas, 500);
            };
        }
        catch(e){
                console.log(e);
                setTimeout(qrcode.captureToCanvas, 500);
        };
    }
}

qrcode.setWebcam = function(videoId)
{
    var n=navigator;
    qrcode.video=document.getElementById(videoId);

    var options = true;
    if(navigator.mediaDevices && navigator.mediaDevices.enumerateDevices)
    {
        try{
            navigator.mediaDevices.enumerateDevices()
            .then(function(devices) {
              devices.forEach(function(device) {
                console.log("deb1");
                if (device.kind === 'videoinput') {
                  if(device.label.toLowerCase().search("back") >-1)
                    options=[{'sourceId': device.deviceId}] ;
                }
                console.log(device.kind + ": " + device.label +
                            " id = " + device.deviceId);
              });
            })

        }
        catch(e)
        {
            console.log(e);
        }
    }
    else{
        console.log("no navigator.mediaDevices.enumerateDevices" );
    }

    if(n.getUserMedia)
        n.getUserMedia({video: options, audio: false}, qrcode.vidSuccess, qrcode.vidError);
    else
    if(n.webkitGetUserMedia)
    {
        qrcode.webkit=true;
        n.webkitGetUserMedia({video:options, audio: false}, qrcode.vidSuccess, qrcode.vidError);
    }
    else
    if(n.mozGetUserMedia)
    {
        qrcode.moz=true;
        n.mozGetUserMedia({video: options, audio: false}, qrcode.vidSuccess, qrcode.vidError);
    }
}

qrcode.decode = function(src){

    if(arguments.length==0)
    {
        if(qrcode.canvas_qr2)
        {
            var canvas_qr = qrcode.canvas_qr2;
            var context = qrcode.qrcontext2;
        }
        else
        {
            var canvas_qr = document.getElementById("qr-canvas");
            var context = canvas_qr.getContext('2d');
        }
        qrcode.width = canvas_qr.width;
        qrcode.height = canvas_qr.height;
        qrcode.imagedata = context.getImageData(0, 0, qrcode.width, qrcode.height);
        qrcode.result = qrcode.process(context);
        if(qrcode.callback!=null)
            qrcode.callback(qrcode.result);
        return qrcode.result;
    }
    else
    {
        var image = new Image();
        image.crossOrigin = "Anonymous";
        image.onload=function(){
            //var canvas_qr = document.getElementById("qr-canvas");
            var canvas_out = document.getElementById("out-canvas");
            if(canvas_out!=null)
            {
                var outctx = canvas_out.getContext('2d');
                outctx.clearRect(0, 0, 320, 240);
                outctx.drawImage(image, 0, 0, 320, 240);
            }

            var canvas_qr = document.createElement('canvas');
            var context = canvas_qr.getContext('2d');
            var nheight = image.height;
            var nwidth = image.width;
            if(image.width*image.height>qrcode.maxImgSize)
            {
                var ir = image.width / image.height;
                nheight = Math.sqrt(qrcode.maxImgSize/ir);
                nwidth=ir*nheight;
            }

            canvas_qr.width = nwidth;
            canvas_qr.height = nheight;

            context.drawImage(image, 0, 0, canvas_qr.width, canvas_qr.height );
            qrcode.width = canvas_qr.width;
            qrcode.height = canvas_qr.height;
            try{
                qrcode.imagedata = context.getImageData(0, 0, canvas_qr.width, canvas_qr.height);
            }catch(e){
                qrcode.result = "Cross domain image reading not supported in your browser! Save it to your computer then drag and drop the file!";
                if(qrcode.callback!=null)
                    qrcode.callback(qrcode.result);
                return;
            }

            try
            {
                qrcode.result = qrcode.process(context);
            }
            catch(e)
            {
                console.log(e);
                qrcode.result = "error decoding QR Code";
            }
            if(qrcode.callback!=null)
                qrcode.callback(qrcode.result);
        }
        image.onerror = function ()
        {
            if(qrcode.callback!=null)
                qrcode.callback("Failed to load the image");
        }
        image.src = src;
    }
}

qrcode.isUrl = function(s)
{
    var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
    return regexp.test(s);
}

qrcode.decode_url = function (s)
{
  var escaped = "";
  try{
    escaped = escape( s );
  }
  catch(e)
  {
    console.log(e);
    escaped = s;
  }
  var ret = "";
  try{
    ret = decodeURIComponent( escaped );
  }
  catch(e)
  {
    console.log(e);
    ret = escaped;
  }
  return ret;
}

qrcode.decode_utf8 = function ( s )
{
    if(qrcode.isUrl(s))
        return qrcode.decode_url(s);
    else
        return s;
}

qrcode.process = function(ctx){

    var start = new Date().getTime();

    var image = qrcode.grayScaleToBitmap(qrcode.grayscale());
    //var image = qrcode.binarize(128);

    if(qrcode.debug)
    {
        for (var y = 0; y < qrcode.height; y++)
        {
            for (var x = 0; x < qrcode.width; x++)
            {
                var point = (x * 4) + (y * qrcode.width * 4);
                qrcode.imagedata.data[point] = image[x+y*qrcode.width]?0:0;
                qrcode.imagedata.data[point+1] = image[x+y*qrcode.width]?0:0;
                qrcode.imagedata.data[point+2] = image[x+y*qrcode.width]?255:0;
            }
        }
        ctx.putImageData(qrcode.imagedata, 0, 0);
    }

    //var finderPatternInfo = new FinderPatternFinder().findFinderPattern(image);

    var detector = new Detector(image);

    var qRCodeMatrix = detector.detect();

    if(qrcode.debug)
    {
        for (var y = 0; y < qRCodeMatrix.bits.Height; y++)
        {
            for (var x = 0; x < qRCodeMatrix.bits.Width; x++)
            {
                var point = (x * 4*2) + (y*2 * qrcode.width * 4);
                qrcode.imagedata.data[point] = qRCodeMatrix.bits.get_Renamed(x,y)?0:0;
                qrcode.imagedata.data[point+1] = qRCodeMatrix.bits.get_Renamed(x,y)?0:0;
                qrcode.imagedata.data[point+2] = qRCodeMatrix.bits.get_Renamed(x,y)?255:0;
            }
        }
        ctx.putImageData(qrcode.imagedata, 0, 0);
    }

    var reader = Decoder.decode(qRCodeMatrix.bits);
    var data = reader.DataByte;
    var str="";
    for(var i=0;i<data.length;i++)
    {
        for(var j=0;j<data[i].length;j++)
            str+=String.fromCharCode(data[i][j]);
    }

    var end = new Date().getTime();
    var time = end - start;
    console.log(time);

    return qrcode.decode_utf8(str);
    //alert("Time:" + time + " Code: "+str);
}

qrcode.getPixel = function(x,y){
    if (qrcode.width < x) {
        throw "point error";
    }
    if (qrcode.height < y) {
        throw "point error";
    }
    var point = (x * 4) + (y * qrcode.width * 4);
    var p = (qrcode.imagedata.data[point]*33 + qrcode.imagedata.data[point + 1]*34 + qrcode.imagedata.data[point + 2]*33)/100;
    return p;
}

qrcode.binarize = function(th){
    var ret = new Array(qrcode.width*qrcode.height);
    for (var y = 0; y < qrcode.height; y++)
    {
        for (var x = 0; x < qrcode.width; x++)
        {
            var gray = qrcode.getPixel(x, y);

            ret[x+y*qrcode.width] = gray<=th?true:false;
        }
    }
    return ret;
}

qrcode.getMiddleBrightnessPerArea=function(image)
{
    var numSqrtArea = 4;
    //obtain middle brightness((min + max) / 2) per area
    var areaWidth = Math.floor(qrcode.width / numSqrtArea);
    var areaHeight = Math.floor(qrcode.height / numSqrtArea);
    var minmax = new Array(numSqrtArea);
    for (var i = 0; i < numSqrtArea; i++)
    {
        minmax[i] = new Array(numSqrtArea);
        for (var i2 = 0; i2 < numSqrtArea; i2++)
        {
            minmax[i][i2] = new Array(0,0);
        }
    }
    for (var ay = 0; ay < numSqrtArea; ay++)
    {
        for (var ax = 0; ax < numSqrtArea; ax++)
        {
            minmax[ax][ay][0] = 0xFF;
            for (var dy = 0; dy < areaHeight; dy++)
            {
                for (var dx = 0; dx < areaWidth; dx++)
                {
                    var target = image[areaWidth * ax + dx+(areaHeight * ay + dy)*qrcode.width];
                    if (target < minmax[ax][ay][0])
                        minmax[ax][ay][0] = target;
                    if (target > minmax[ax][ay][1])
                        minmax[ax][ay][1] = target;
                }
            }
            //minmax[ax][ay][0] = (minmax[ax][ay][0] + minmax[ax][ay][1]) / 2;
        }
    }
    var middle = new Array(numSqrtArea);
    for (var i3 = 0; i3 < numSqrtArea; i3++)
    {
        middle[i3] = new Array(numSqrtArea);
    }
    for (var ay = 0; ay < numSqrtArea; ay++)
    {
        for (var ax = 0; ax < numSqrtArea; ax++)
        {
            middle[ax][ay] = Math.floor((minmax[ax][ay][0] + minmax[ax][ay][1]) / 2);
            //Console.out.print(middle[ax][ay] + ",");
        }
        //Console.out.println("");
    }
    //Console.out.println("");

    return middle;
}

qrcode.grayScaleToBitmap=function(grayScale)
{
    var middle = qrcode.getMiddleBrightnessPerArea(grayScale);
    var sqrtNumArea = middle.length;
    var areaWidth = Math.floor(qrcode.width / sqrtNumArea);
    var areaHeight = Math.floor(qrcode.height / sqrtNumArea);

    var buff = new ArrayBuffer(qrcode.width*qrcode.height);
    var bitmap = new Uint8Array(buff);

    //var bitmap = new Array(qrcode.height*qrcode.width);

    for (var ay = 0; ay < sqrtNumArea; ay++)
    {
        for (var ax = 0; ax < sqrtNumArea; ax++)
        {
            for (var dy = 0; dy < areaHeight; dy++)
            {
                for (var dx = 0; dx < areaWidth; dx++)
                {
                    bitmap[areaWidth * ax + dx+ (areaHeight * ay + dy)*qrcode.width] = (grayScale[areaWidth * ax + dx+ (areaHeight * ay + dy)*qrcode.width] < middle[ax][ay])?true:false;
                }
            }
        }
    }
    return bitmap;
}

qrcode.grayscale = function()
{
    var buff = new ArrayBuffer(qrcode.width*qrcode.height);
    var ret = new Uint8Array(buff);
    //var ret = new Array(qrcode.width*qrcode.height);

    for (var y = 0; y < qrcode.height; y++)
    {
        for (var x = 0; x < qrcode.width; x++)
        {
            var gray = qrcode.getPixel(x, y);

            ret[x+y*qrcode.width] = gray;
        }
    }
    return ret;
}

function URShift( number,  bits)
{
    if (number >= 0)
        return number >> bits;
    else
        return (number >> bits) + (2 << ~bits);
}

<commit_msg>Delete qrcode.js<commit_after><|endoftext|>


<commit_before>module.exports = {
    // Replace with a dummy date for testing.
    Date: Date,
    // Test a log entry for acceptance.
    json: function () {},
    // We start with a noop acceptor, so we have a `null` queue to assert that
    // nothing is going to happen unless you reconfigure the acceptor.
    // configure the sink to actually do something.
    queue: null,
    // Additional properties added to every message.
    properties: { pid: process.pid }
}

/*

sink.json = function (level, qualifier, label, body) {
    var header = {
        when: this.Date.now(),
        pid: process.pid,
        level: level,
        qualifier: qualifier,
        label: label,
        qualified: qualifier + '#' + label
    }
    if (triage(LEVEL[level], header, body, this.properties)) {
        for (var key in system) {
            header[key] = system[key]
        }
        for (var key in body) {
            header[key] = body[key]
        }
        this.queue.push(entry)
    }
}

sink.json = function (level, qualifier, label, body) {
    this.queue.push({
        level: level,
        qualifier: qualifier,
        label: label,
        body: body,
        system: this.properties
    })
}

sink.setTriage(function (level, header, body, system, append) {
    append.header = header
    append.body = body
    append.system = system
    return true
})

*/
<commit_msg>Remove `Sink.queue`.<commit_after>module.exports = {
    // Replace with a dummy date for testing.
    Date: Date,
    // Test a log entry for acceptance.
    json: function () {},
    // Additional properties added to every message.
    properties: { pid: process.pid }
}

/*

sink.json = function (level, qualifier, label, body) {
    var header = {
        when: this.Date.now(),
        pid: process.pid,
        level: level,
        qualifier: qualifier,
        label: label,
        qualified: qualifier + '#' + label
    }
    if (triage(LEVEL[level], header, body, this.properties)) {
        for (var key in system) {
            header[key] = system[key]
        }
        for (var key in body) {
            header[key] = body[key]
        }
        this.queue.push(entry)
    }
}

sink.json = function (level, qualifier, label, body) {
    this.queue.push({
        level: level,
        qualifier: qualifier,
        label: label,
        body: body,
        system: this.properties
    })
}

sink.setTriage(function (level, header, body, system, append) {
    append.header = header
    append.body = body
    append.system = system
    return true
})

*/
<|endoftext|>


<commit_before>// Generated by CoffeeScript 1.6.1

$(function() {
  return $.getJSON('/api/v1/data/', {
    'user': $('#user').html()
  }, function(data) {
    var datum, feed_tmpl, info, _i, _len, _results;
    console.log(moment().format());
    $('#submissions_feed').html('');
    if (data.length === 0) {
      return $('#submissions_feed').html('
No submissions yet =[
');
    } else {
      feed_tmpl = _.template($('#submission_feed_tmpl').html());
      _results = [];
      for (_i = 0, _len = data.length; _i < _len; _i++) {
        datum = data[_i];
        info = {
          label: 'submission received',
          time: moment(datum.timestamp).fromNow(),
          link: "/api/v1/data/" + datum.survey
        };
        _results.push($('#submissions_feed').append(feed_tmpl(info)));
      }
      return _results;
    }
  });
});
<commit_msg>Submission feed on dashboard correctly calculates relative time with UTC time.<commit_after>// Generated by CoffeeScript 1.6.1

$(function() {
  return $.getJSON('/api/v1/data/', {
    'user': $('#user').html()
  }, function(data) {
    var datum, feed_tmpl, info, _i, _len, _results;
    console.log(moment().format());
    $('#submissions_feed').html('');
    if (data.length === 0) {
      return $('#submissions_feed').html('
No submissions yet =[
');
    } else {
      feed_tmpl = _.template($('#submission_feed_tmpl').html());
      _results = [];
      for (_i = 0, _len = data.length; _i < _len; _i++) {
        datum = data[_i];
        info = {
          label: 'submission received',
          time: moment.utc(datum.timestamp).fromNow(),
          link: "/api/v1/data/" + datum.survey
        };
        _results.push($('#submissions_feed').append(feed_tmpl(info)));
      }
      return _results;
    }
  });
});
<|endoftext|>


<commit_before>
function filterMachines(f) {
	$('.machines-buttons .quick-button').removeClass('active');
	$('.machines-buttons .btn-'+f).addClass('active');
	if (f === 'all') f = '*';
	else f = '.'+f;
	$('#machines-loader').isotope( { filter: f } );
}

var cloudlyVMSmanager  = {
    template: '',
    actualMachines: '',
    colors : {
		'#36a9e1':'lightBlue',
		'#bdea74':'green',
		'#78cd51':'darkGreen',
		'#eae874':'yellow',
		'#fa603d':'lightOrange',
		'#ff5454':'red',
		'#CBD4E4':'silver',
		'#e84c8a':'pink',
		'#000000':'black'
		},
    initAction: function(){
        var $this = this;
        $('#machines-loader').isotope({
            itemSelector: '.vms-machine'
        });
        $.ajax({
            type: 'GET',
            url: '/ajax/cloud/box-template/',
            data: '',
            success: function(res){
                $this.template = res;
                setInterval(function(){
                    $this.loadMachinesData();
                },1000);
            }
        });
    },
    loadMachinesData: function(){
        var actualMachines = $(".vms-machine");

        var $this = this;
        $.ajax({
            type: 'GET',
            url: '/ajax/cloud/vms/',
            data: '',
            success: function(res){
                var jsonData = $.parseJSON(res);
                $this.checkRemoved(jsonData,actualMachines);
                $this.parseMachinesData(jsonData);

            }
        });
    },
    parseMachinesData: function(jsonData){
        var $this = this;
        if(jsonData){
            $.each(jsonData,function(vms,data){
                //exist VMS
                if($('#'+vms).length){
                    $this.updateVMS(vms,data);
                }
                else {
                    $this.addVMS(vms,data);
                }
            });
        }
    },
    updateVMS: function(vms,data){
        chartStatElement($('#'+vms).find('.chart').html(data.averge));
        $('#'+vms).find('.value').html(data.state);

        var panel = $("#"+vms).find('.panel');
        $.each(this.colors,function(code,color){
                if(panel.hasClass(color) && panel.attr('class').indexOf(data.vmcolor) === -1){

                        $(panel).switchClass(color,data.vmcolor);

                        //console.log('VM '+vms+' changed color: '+color+' to: '+data.vmcolor+' and actual has class: '+panel.attr('class'));
                        return;
                }
        });

    },
    addVMS: function(vms,data){
        var template = this.template;
        template = template.replace('{@vmlink@}',data.link);
        template = template.replace('{@vm@}',vms);
        template = template.replace('{@vm@}',vms);
        template = template.replace('{@vmtitle@}',data.vmtitle);
        template = template.replace('{@vmcolor@}',data.vmcolor);
        template = template.replace('{@averge@}',data.averge);
        template = template.replace("{@state@}", data.state);

        template = $(template);
//        console.log(template);
        var prepend = $('#machines-loader').prepend(template);
        chartStatElement($('#'+vms).find('.chart').html(data.averge));
        prepend.isotope( 'reloadItems' ).isotope({ sortBy: 'original-order' });

    },
    checkRemoved: function(machines,actualMachines){
        var machineIds = 'testVMS';
	var $container = $('#machines-loader');
        $.each(machines,function(vms,value){
            machineIds += vms+',';
        });

        $.each(actualMachines,function(index,item){
            var id = $(item).attr('id');
            if(machineIds.indexOf(id) < 0){
                $container.isotope( 'remove', item ).isotope('layout');
            }
        });

    },
    reloadPositions: function(){
            $('#machines-loader').isotope( 'reloadItems' ).isotope({ sortBy: 'original-order' });
    },
    addBlank: function(){
        this.addVMS('testVMS',{"averge":"0.0,0.0,0.0,0.0","state":"Running"});

    }
}

$(document).ready (function() {

	var btns = ['all','critical','offline', 'suspended', 'windows', 'linux', 'bsd', 'private'];
	for (var i = 0; i < btns.length; ++i) {
	    (function(){
		var type = btns[i];
		var btn = $('.machines-buttons .btn-'+type);
		btn.click(function() { filterMachines(type); });
	    })();
	}

        cloudlyVMSmanager.initAction();

});

<commit_msg>adjusted colors for the isotope boxes<commit_after>
function filterMachines(f) {
	$('.machines-buttons .quick-button').removeClass('active');
	$('.machines-buttons .btn-'+f).addClass('active');
	if (f === 'all') f = '*';
	else f = '.'+f;
	$('#machines-loader').isotope( { filter: f } );
}

var cloudlyVMSmanager  = {
    template: '',
    actualMachines: '',
    colors : {
		'#36a9e1':'lightBlue',
		'#78cd51':'green',
		'#333366':'darkGreen',
		'#eae874':'yellow',
		'#fa603d':'lightOrange',
		'#ff5454':'red',
		'#CBD4E4':'silver',
		'#e84c8a':'pink',
		'#000000':'black'
		},
    initAction: function(){
        var $this = this;
        $('#machines-loader').isotope({
            itemSelector: '.vms-machine'
        });
        $.ajax({
            type: 'GET',
            url: '/ajax/cloud/box-template/',
            data: '',
            success: function(res){
                $this.template = res;
                setInterval(function(){
                    $this.loadMachinesData();
                },1000);
            }
        });
    },
    loadMachinesData: function(){
        var actualMachines = $(".vms-machine");

        var $this = this;
        $.ajax({
            type: 'GET',
            url: '/ajax/cloud/vms/',
            data: '',
            success: function(res){
                var jsonData = $.parseJSON(res);
                $this.checkRemoved(jsonData,actualMachines);
                $this.parseMachinesData(jsonData);

            }
        });
    },
    parseMachinesData: function(jsonData){
        var $this = this;
        if(jsonData){
            $.each(jsonData,function(vms,data){
                //exist VMS
                if($('#'+vms).length){
                    $this.updateVMS(vms,data);
                }
                else {
                    $this.addVMS(vms,data);
                }
            });
        }
    },
    updateVMS: function(vms,data){
        chartStatElement($('#'+vms).find('.chart').html(data.averge));
        $('#'+vms).find('.value').html(data.state);

        var panel = $("#"+vms).find('.panel');
        $.each(this.colors,function(code,color){
                if(panel.hasClass(color) && panel.attr('class').indexOf(data.vmcolor) === -1){

                        $(panel).switchClass(color,data.vmcolor);

                        //console.log('VM '+vms+' changed color: '+color+' to: '+data.vmcolor+' and actual has class: '+panel.attr('class'));
                        return;
                }
        });

    },
    addVMS: function(vms,data){
        var template = this.template;
        template = template.replace('{@vmlink@}',data.link);
        template = template.replace('{@vm@}',vms);
        template = template.replace('{@vm@}',vms);
        template = template.replace('{@vmtitle@}',data.vmtitle);
        template = template.replace('{@vmcolor@}',data.vmcolor);
        template = template.replace('{@averge@}',data.averge);
        template = template.replace("{@state@}", data.state);

        template = $(template);
//        console.log(template);
        var prepend = $('#machines-loader').prepend(template);
        chartStatElement($('#'+vms).find('.chart').html(data.averge));
        prepend.isotope( 'reloadItems' ).isotope({ sortBy: 'original-order' });

    },
    checkRemoved: function(machines,actualMachines){
        var machineIds = 'testVMS';
	var $container = $('#machines-loader');
        $.each(machines,function(vms,value){
            machineIds += vms+',';
        });

        $.each(actualMachines,function(index,item){
            var id = $(item).attr('id');
            if(machineIds.indexOf(id) < 0){
                $container.isotope( 'remove', item ).isotope('layout');
            }
        });

    },
    reloadPositions: function(){
            $('#machines-loader').isotope( 'reloadItems' ).isotope({ sortBy: 'original-order' });
    },
    addBlank: function(){
        this.addVMS('testVMS',{"averge":"0.0,0.0,0.0,0.0","state":"Running"});

    }
}

$(document).ready (function() {

	var btns = ['all','critical','offline', 'suspended', 'windows', 'linux', 'bsd', 'private'];
	for (var i = 0; i < btns.length; ++i) {
	    (function(){
		var type = btns[i];
		var btn = $('.machines-buttons .btn-'+type);
		btn.click(function() { filterMachines(type); });
	    })();
	}

        cloudlyVMSmanager.initAction();

});

<|endoftext|>


<commit_before><commit_msg>Issue #6 - Blog post displaying 1 day behind<commit_after><|endoftext|>


<commit_before>var session = null;

// instead of windows.onload
$(document).ready( function() {
    // hide iphone/ipad URL bar
    setTimeout(function() { window.scrollTo(0, 1) }, 100);

    $(".logout").click( function ( event ) {
        if (!confirm("Leave Poietic Generator?")) {
            return false;
        }
        return true;
    });

    // initialize zoness
    sessionF = new Session(
        SESSION_TYPE_DRAW,
        function( session ) {
            //console.log("page_draw/ready: session callback ok");
            $(".username").text(session.user_name);

            var board = new Board( session );
            var editor = new Editor( session, board, 'session-editor' );
            var color_picker = new ColorPicker( editor );
            var chat = new Chat( session);
			var viewer = new Viewer( session, board, 'session-viewer', color_picker );

            //console.log("page_draw/ready: prepicker");
            $("#brush").click( function( event ){
                event.preventDefault();
                if ( true === color_picker.is_visible() ) {
                    color_picker.hide(this);
                } else {
                    color_picker.show(this);
                }
            });
        }
    );
});

<commit_msg>The scroll to hide URL bar is now in jQuery Mobile.<commit_after>var session = null;

// instead of windows.onload
$(document).ready( function() {
    // hide iphone/ipad URL bar
    //setTimeout(function() { window.scrollTo(0, 1) }, 100);

    $(".logout").click( function ( event ) {
        if (!confirm("Leave Poietic Generator?")) {
            return false;
        }
        return true;
    });

    // initialize zoness
    sessionF = new Session(
        SESSION_TYPE_DRAW,
        function( session ) {
            //console.log("page_draw/ready: session callback ok");
            $(".username").text(session.user_name);

            var board = new Board( session );
            var editor = new Editor( session, board, 'session-editor' );
            var color_picker = new ColorPicker( editor );
            var chat = new Chat( session);
			var viewer = new Viewer( session, board, 'session-viewer', color_picker );

            //console.log("page_draw/ready: prepicker");
            $("#brush").click( function( event ){
                event.preventDefault();
                if ( true === color_picker.is_visible() ) {
                    color_picker.hide(this);
                } else {
                    color_picker.show(this);
                }
            });
        }
    );
});

<|endoftext|>


<commit_before>'use strict';

(function () {
  function initTreatmentDrawer() {
    $('#eventType').val('BG Check');
    $('#glucoseValue').val('').attr('placeholder', 'Value in ' + browserSettings.units);
    $('#meter').prop('checked', true);
    $('#carbsGiven').val('');
    $('#insulinGiven').val('');
    $('#preBolus').val(0);
    $('#notes').val('');
    $('#enteredBy').val(browserStorage.get('enteredBy') || '');
    $('#nowtime').prop('checked', true);
    $('#eventTimeValue').val(moment().format('HH:mm'));
    $('#eventDateValue').val(moment().format('YYYY-MM-D'));
  }

  function checkForErrors(data) {
    var errors = [];
    if (isNaN(data.glucose)) {
      errors.push('Blood glucose must be a number');
    }

    if (isNaN(data.carbs)) {
      errors.push('Carbs must be a number');
    }

    if (isNaN(data.insulin)) {
      errors.push('Insulin must be a number');
    }
    return errors;
  }

  function prepareData() {
    var data = {
      enteredBy: $('#enteredBy').val()
    , eventType: $('#eventType').val()
    , glucose: $('#glucoseValue').val()
    , glucoseType: $('#treatment-form').find('input[name=glucoseType]:checked').val()
    , carbs: $('#carbsGiven').val()
    , insulin: $('#insulinGiven').val()
    , preBolus: parseInt($('#preBolus').val())
    , notes: $('#notes').val()
    , units: browserSettings.units
    };

    if ($('#othertime').is(':checked')) {
      data.eventTime = Nightscout.utils.mergeInputTime($('#eventTimeValue').val(), $('#eventDateValue').val());
    }

    return data;
  }

  function treatmentSubmit(event) {

    var data = prepareData();
    var errors = checkForErrors(data);

    if (errors.length > 0) {
      window.alert(errors.join('\n'));
    } else {
      confirmPost(data);
    }

    if (event) {
      event.preventDefault();
    }
  }

  function buildConfirmText(data) {
    var text = [
      'Please verify that the data entered is correct: '
      , 'Event type: ' + data.eventType
    ];

    if (data.glucose) {
      text.push('Blood glucose: ' + data.glucose);
      text.push('Method: ' + data.glucoseType);
    }

    if (data.carbs) { text.push('Carbs Given: ' + data.carbs); }
    if (data.insulin) { text.push('Insulin Given: ' + data.insulin); }
    if (data.preBolus) { text.push('Insulin Given: ' + data.insulin); }
    if (data.notes) { text.push('Notes: ' + data.notes); }
    if (data.enteredBy) { text.push('Entered By: ' + data.enteredBy); }

    text.push('Event Time: ' + (data.eventTime ? data.eventTime.format('LLL') : moment().format('LLL')));
    return text.join('\n');
  }

  function confirmPost(data) {
    if (window.confirm(buildConfirmText(data))) {
      var dataJson = JSON.stringify(data, null, ' ');
      var xhr = new XMLHttpRequest();
      xhr.open('POST', '/api/v1/treatments/', true);
      xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
      xhr.send(dataJson);

      browserStorage.set('enteredBy', data.enteredBy);

      closeDrawer('#treatmentDrawer');
    }
  }

  $('#treatmentDrawerToggle').click(function (event) {
    toggleDrawer('#treatmentDrawer', initTreatmentDrawer);
    event.preventDefault();
  });

  $('#treatmentDrawer').find('button').click(treatmentSubmit);

  $('#eventTime').find('input:radio').change(function (event) {
    if ($('#othertime').is(':checked')) {
      $('#eventTimeValue').focus();
    }
    event.preventDefault();
  });

  $('.eventinput').focus(function (event) {
    $('#othertime').prop('checked', true);
    var moment = Nightscout.utils.mergeInputTime($('#eventTimeValue').val(), $('#eventDateValue').val());
    $(this).attr('oldminutes', moment.minutes());
    $(this).attr('oldhours', moment.hours());
    event.preventDefault();
  })
  .change(function (event) {
    $('#othertime').prop('checked', true);
    var moment = Nightscout.utils.mergeInputTime($('#eventTimeValue').val(), $('#eventDateValue').val());
    if ($(this).attr('oldminutes') === ' 59' && moment.minutes() === 0) {
      moment.add(1, 'hours');
    }
    if ($(this).attr('oldminutes') === '0' && moment.minutes() === 59) {
      moment.add(-1, 'hours');
    }
    $('#eventTimeValue').val(moment.format('HH:mm'));
    $('#eventDateValue').val(moment.format('YYYY-MM-D'));
    $(this).attr('oldminutes', moment.minutes());
    $(this).attr('oldhours', moment.hours());
    event.preventDefault();
  });
})();<commit_msg>selecting now resets time to current<commit_after>'use strict';

(function () {
  function initTreatmentDrawer() {
    $('#eventType').val('BG Check');
    $('#glucoseValue').val('').attr('placeholder', 'Value in ' + browserSettings.units);
    $('#meter').prop('checked', true);
    $('#carbsGiven').val('');
    $('#insulinGiven').val('');
    $('#preBolus').val(0);
    $('#notes').val('');
    $('#enteredBy').val(browserStorage.get('enteredBy') || '');
    $('#nowtime').prop('checked', true);
    $('#eventTimeValue').val(moment().format('HH:mm'));
    $('#eventDateValue').val(moment().format('YYYY-MM-D'));
  }

  function checkForErrors(data) {
    var errors = [];
    if (isNaN(data.glucose)) {
      errors.push('Blood glucose must be a number');
    }

    if (isNaN(data.carbs)) {
      errors.push('Carbs must be a number');
    }

    if (isNaN(data.insulin)) {
      errors.push('Insulin must be a number');
    }
    return errors;
  }

  function prepareData() {
    var data = {
      enteredBy: $('#enteredBy').val()
    , eventType: $('#eventType').val()
    , glucose: $('#glucoseValue').val()
    , glucoseType: $('#treatment-form').find('input[name=glucoseType]:checked').val()
    , carbs: $('#carbsGiven').val()
    , insulin: $('#insulinGiven').val()
    , preBolus: parseInt($('#preBolus').val())
    , notes: $('#notes').val()
    , units: browserSettings.units
    };

    if ($('#othertime').is(':checked')) {
      data.eventTime = Nightscout.utils.mergeInputTime($('#eventTimeValue').val(), $('#eventDateValue').val());
    }

    return data;
  }

  function treatmentSubmit(event) {

    var data = prepareData();
    var errors = checkForErrors(data);

    if (errors.length > 0) {
      window.alert(errors.join('\n'));
    } else {
      confirmPost(data);
    }

    if (event) {
      event.preventDefault();
    }
  }

  function buildConfirmText(data) {
    var text = [
      'Please verify that the data entered is correct: '
      , 'Event type: ' + data.eventType
    ];

    if (data.glucose) {
      text.push('Blood glucose: ' + data.glucose);
      text.push('Method: ' + data.glucoseType);
    }

    if (data.carbs) { text.push('Carbs Given: ' + data.carbs); }
    if (data.insulin) { text.push('Insulin Given: ' + data.insulin); }
    if (data.preBolus) { text.push('Insulin Given: ' + data.insulin); }
    if (data.notes) { text.push('Notes: ' + data.notes); }
    if (data.enteredBy) { text.push('Entered By: ' + data.enteredBy); }

    text.push('Event Time: ' + (data.eventTime ? data.eventTime.format('LLL') : moment().format('LLL')));
    return text.join('\n');
  }

  function confirmPost(data) {
    if (window.confirm(buildConfirmText(data))) {
      var dataJson = JSON.stringify(data, null, ' ');
      var xhr = new XMLHttpRequest();
      xhr.open('POST', '/api/v1/treatments/', true);
      xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
      xhr.send(dataJson);

      browserStorage.set('enteredBy', data.enteredBy);

      closeDrawer('#treatmentDrawer');
    }
  }

  $('#treatmentDrawerToggle').click(function (event) {
    toggleDrawer('#treatmentDrawer', initTreatmentDrawer);
    event.preventDefault();
  });

  $('#treatmentDrawer').find('button').click(treatmentSubmit);

  $('#eventTime').find('input:radio').change(function (event) {
    if ($('#othertime').is(':checked')) {
      $('#eventTimeValue').focus();
    } else {
      $('#eventTimeValue').val(moment().format('HH:mm'));
      $('#eventDateValue').val(moment().format('YYYY-MM-D'));
    }
    event.preventDefault();
  });

  $('.eventinput').focus(function (event) {
    $('#othertime').prop('checked', true);
    var moment = Nightscout.utils.mergeInputTime($('#eventTimeValue').val(), $('#eventDateValue').val());
    $(this).attr('oldminutes', moment.minutes());
    $(this).attr('oldhours', moment.hours());
    event.preventDefault();
  })
  .change(function (event) {
    $('#othertime').prop('checked', true);
    var moment = Nightscout.utils.mergeInputTime($('#eventTimeValue').val(), $('#eventDateValue').val());
    if ($(this).attr('oldminutes') === ' 59' && moment.minutes() === 0) {
      moment.add(1, 'hours');
    }
    if ($(this).attr('oldminutes') === '0' && moment.minutes() === 59) {
      moment.add(-1, 'hours');
    }
    $('#eventTimeValue').val(moment.format('HH:mm'));
    $('#eventDateValue').val(moment.format('YYYY-MM-D'));
    $(this).attr('oldminutes', moment.minutes());
    $(this).attr('oldhours', moment.hours());
    event.preventDefault();
  });
})();<|endoftext|>


<commit_before>import Api from '@/services/Api'

export default {
  index () {
    return Api().get('songs')
  },
  post (song) {
    return Api().post('song', song)
  },
  show (songId) {
    return Api().get(`song/${songId}`)
  },
  put (song) {
    console.log('Song', song)
    return Api().put(`song/edit`, song)
  }
}
<commit_msg>add search argument to index method<commit_after>import Api from '@/services/Api'

export default {
  index (search) {
    return Api().get('songs', {
      params: {
        search: search
      }
    })
  },
  post (song) {
    return Api().post('song', song)
  },
  show (songId) {
    return Api().get(`song/${songId}`)
  },
  put (song) {
    console.log('Song', song)
    return Api().put(`song/edit`, song)
  }
}
<|endoftext|>


<commit_before>// auto-suggest docs:
// http://code.drewwilson.com/entry/autosuggest-jquery-plugin
// Changes to previous
// - prefill and ashtmlid in data-auto-suggest-config
define([
    "jquery",
    "../core/parser",
    "../registry",
    "jquery_autosuggest",
    "jquery_form"
], function($, Parser, registry) {
    var parser = new Parser("autosuggest");
    parser.add_argument("words", "");
    parser.add_argument("pre-fill");
    parser.add_argument("as-html-id");
    parser.add_argument("selected-value-prop", "name");
    parser.add_argument("search-obj-prop", "name");

    var _ = {
        name: "autosuggest",
        trigger: "input.pat-autosuggest",
        init: function($el, opts) {
            if ($el.length > 1)
                return $el.each(function() { _.init($(this), opts); });

            var cfg = _.parser.parse($el, opts);

            if ($el.attr("readonly"))
                cfg.startText = "";
            else
                cfg.startText = $el.attr("placeholder") || "Enter text";

            // jquery_autosuggest does not like the placeholder attr (yet)
            $el.attr("placeholder", "");

            if (cfg.preFill && (cfg.preFill.slice(0,1) === ","))
                cfg.preFill = cfg.preFill.slice(1);

            $el.on("keydown.pat-autosuggest", _.onKeyDown);

            var data = cfg.words.split(/\s*,\s*/).map(function(word) {
                return {value: word, name: word};
            });

            cfg.selectionAdded = function() {
                $el.next().trigger("change");
            };
            cfg.selectionRemoved = function(elem) {
                elem.remove();
                $el.next().trigger("change");
            };

            $el.on("change.pat-autosuggest", false);

            // XXX: See https://github.com/Patternslib/Patterns/issues/149
            if (cfg.asHtmlId !== undefined) {
                cfg.asHtmlID = cfg.asHtmlId;
            }
            $el.autoSuggest(data, cfg);

            return $el;
        },
        destroy: function($el) {
            $el.off(".pat-autosuggest");

            // XXX: destroy the jqueryPlugin, unfortunately it doesn't
            // support this as of now
        },

        parser: parser,

        onKeyDown: function(ev) {
            var $this = $(this);
            if (ev.which === 13) {
                var $results = $this.parents(".as-selections").next();
                ev.preventDefault();
                // skip ENTER->comma translation, if selection is active
                if (($results.is(":visible")) &&
                    ($results.find(".active").length > 0)) return;
                var newev = $.Event("keydown");
                newev.ctrlKey = false;
                newev.which = 188;
                newev.keyCode = 188;
                $this.trigger(newev);
            }
        }
    };
    registry.register(_);
    return _;
});

// jshint indent: 4, browser: true, jquery: true, quotmark: double
// vim: sw=4 expandtab
<commit_msg>Add a placeholder option that takes precedence over placeholder attr. #192<commit_after>// auto-suggest docs:
// http://code.drewwilson.com/entry/autosuggest-jquery-plugin
// Changes to previous
// - prefill and ashtmlid in data-auto-suggest-config
define([
    "jquery",
    "../core/parser",
    "../registry",
    "jquery_autosuggest",
    "jquery_form"
], function($, Parser, registry) {
    var parser = new Parser("autosuggest");
    parser.add_argument("words", "");
    parser.add_argument("pre-fill");
    parser.add_argument("as-html-id");
    parser.add_argument("selected-value-prop", "name");
    parser.add_argument("search-obj-prop", "name");
    parser.add_argument("placeholder", function($el) {
        var placeholder = $el.attr("placeholder") || "Enter text";
        // jquery_autosuggest does not like the placeholder attr (yet)
        $el.attr("placeholder", "");
        return placeholder;
    });

    var _ = {
        name: "autosuggest",
        trigger: "input.pat-autosuggest",
        init: function($el, opts) {
            if ($el.length > 1)
                return $el.each(function() { _.init($(this), opts); });

            var cfg = _.parser.parse($el, opts);

            if ($el.attr("readonly"))
                cfg.startText = "";
            else
                cfg.startText = cfg.placeholder;

            if (cfg.preFill && (cfg.preFill.slice(0,1) === ","))
                cfg.preFill = cfg.preFill.slice(1);

            $el.on("keydown.pat-autosuggest", _.onKeyDown);

            var data = cfg.words.split(/\s*,\s*/).map(function(word) {
                return {value: word, name: word};
            });

            cfg.selectionAdded = function() {
                $el.next().trigger("change");
            };
            cfg.selectionRemoved = function(elem) {
                elem.remove();
                $el.next().trigger("change");
            };

            $el.on("change.pat-autosuggest", false);

            // XXX: See https://github.com/Patternslib/Patterns/issues/149
            if (cfg.asHtmlId !== undefined) {
                cfg.asHtmlID = cfg.asHtmlId;
            }
            $el.autoSuggest(data, cfg);

            return $el;
        },
        destroy: function($el) {
            $el.off(".pat-autosuggest");

            // XXX: destroy the jqueryPlugin, unfortunately it doesn't
            // support this as of now
        },

        parser: parser,

        onKeyDown: function(ev) {
            var $this = $(this);
            if (ev.which === 13) {
                var $results = $this.parents(".as-selections").next();
                ev.preventDefault();
                // skip ENTER->comma translation, if selection is active
                if (($results.is(":visible")) &&
                    ($results.find(".active").length > 0)) return;
                var newev = $.Event("keydown");
                newev.ctrlKey = false;
                newev.which = 188;
                newev.keyCode = 188;
                $this.trigger(newev);
            }
        }
    };
    registry.register(_);
    return _;
});

// jshint indent: 4, browser: true, jquery: true, quotmark: double
// vim: sw=4 expandtab
<|endoftext|>


<commit_before>dojo.provide("dojox.data.RailsStore");
dojo.require("dojox.data.JsonRestStore");
// Contains code donated by Travis Tilley under CLA

dojo.declare("dojox.data.RailsStore", dojox.data.JsonRestStore, {
	constructor: function(){
		//	summary:
		//		RailsStore is a data store for interacting with RESTful Rails controllers
	},
	preamble: function(options){
		if(typeof options.target == 'string' && !options.service){
			var target = options.target.replace(/\/$/g, '');

			// Special getRequest handler for handling content type negotiation via
			// the Rails format extension, as well as properly setting the ID param
			// in the URL.
			var getRequest = function(id, args){
				args = args || {};
				var url = target;
				var query;
				var ident;

				if(dojo.isObject(id)){
					ident = '';
					query = '?' + dojo.objectToQuery(id);
				}else if(args.query && args.query.indexOf('?') != -1){
					ident = args.query.replace(/\?.*/, '');
					query = args.query.replace(/[^?]*\?/g, '?');
				}else{
					ident = id || '';
					query = '';
				}

				if(ident.indexOf('=') != -1){
					query = ident;
					ident = '';
				}

				if(ident){
					url = url + '/' + ident + '.json' + query;
				}else{
					url = url + '.json' + query;
				}

				return {
					url : url,
					handleAs : 'json',
					contentType : 'application/json',
					sync : dojox.rpc._sync,
					headers : {
						Accept : 'application/json,application/javascript'
					}
				};
			};

			options.service = dojox.rpc.Rest(this.target, true, null,
					getRequest);
		}
	},
	fetch: function(args){
		args = args || {};

		function addToQuery(obj) {
			if(args.query == null){
				args.query = '?';
			}else if (dojo.isObject(args.query)){
				args.query = '?' + dojo.objectToQuery(args.query) + '&';
			}else if (args.query.indexOf('?') == -1){
				args.query = args.query + '?';
			}

			args.query = args.query + dojo.objectToQuery(obj);
		}
		if(args.start || args.count){
			// in addition to the content range headers, also provide query parameters for use
			// with the will_paginate plugin if so desired.
			if((args.start || 0) % args.count){
				throw new Error("The start parameter must be a multiple of a the count parameter");
			}
			addToQuery({
				page: (args.start || 0) / args.count,
				per_page: args.count
			});
		}
		if(args.sort){
			// make the sort into query parameters
			var queryObj = {
				sortBy : [],
				sortDir : []
			};

			dojo.forEach(args.sort, function(item) {
				queryObj.sortBy.push(item.attribute);
				queryObj.sortDir.push(!!item.descending ? 'DESC' : 'ASC');
			});

			addToQuery(queryObj);
			delete args.sort;
		}

		return this.inherited(arguments);
	}
});
<commit_msg>Updates to the RailsStore for avoiding the modification of args.query (messes with certain widgets)<commit_after>dojo.provide("dojox.data.RailsStore");
dojo.require("dojox.data.JsonRestStore");
// Contains code donated by Travis Tilley under CLA

dojo.declare("dojox.data.RailsStore", dojox.data.JsonRestStore, {
	constructor: function(){
		//	summary:
		//		RailsStore is a data store for interacting with RESTful Rails controllers
	},
	preamble: function(options){
		if(typeof options.target == 'string' && !options.service){
			var target = options.target.replace(/\/$/g, '');

			// Special getRequest handler for handling content type negotiation via
			// the Rails format extension, as well as properly setting the ID param
			// in the URL.
			var getRequest = function(id, args){
				args = args || {};
				var url = target;
				var query;
				var ident;

				if(dojo.isObject(id)){
					ident = '';
					query = '?' + dojo.objectToQuery(id);
				}else if(args.queryStr && args.queryStr.indexOf('?') != -1){
					ident = args.queryStr.replace(/\?.*/, '');
					query = args.queryStr.replace(/[^?]*\?/g, '?');
				}else if(dojo.isString(args.query) && args.query.indexOf('?') != -1){
					ident = args.query.replace(/\?.*/, '');
					query = args.query.replace(/[^?]*\?/g, '?');
				}else{
					ident = id ? id.toString() : '';
					query = '';
				}

				if(ident.indexOf('=') != -1){
					query = ident;
					ident = '';
				}

				if(ident){
					url = url + '/' + ident + '.json' + query;
				}else{
					url = url + '.json' + query;
				}

				var isSync = dojox.rpc._sync;
				dojox.rpc._sync = false;

				return {
					url : url,
					handleAs : 'json',
					contentType : 'application/json',
					sync : isSync,
					headers : {
						Accept : 'application/json,application/javascript',
						Range : args && (args.start >= 0 || args.count >= 0)
								? "items="
										+ (args.start || '0')
										+ '-'
										+ ((args.count && (args.count
												+ (args.start || 0) - 1)) || '')
								: undefined
					}
				};
			};

			options.service = dojox.rpc.Rest(this.target, true, null,
					getRequest);
		}
	},
	fetch: function(args){
		args = args || {};
		function addToQueryStr(obj){
			function buildInitialQueryString(){
				if(args.queryStr == null){
					args.queryStr = '';
				}
				if(dojo.isObject(args.query)){
					args.queryStr = '?' + dojo.objectToQuery(args.query);
				}else if(dojo.isString(args.query)){
					args.queryStr = args.query;
				}
			}
			function separator(){
				if(args.queryStr.indexOf('?') == -1){
					return '?';
				}else{
					return '&';
				}
			}
			if (args.queryStr == null){
				buildInitialQueryString();
			}
			args.queryStr = args.queryStr + separator() + dojo.objectToQuery(obj);
		}
		if(args.start || args.count){
			// in addition to the content range headers, also provide query parameters for use
			// with the will_paginate plugin if so desired.
			if((args.start || 0) % args.count){
				throw new Error("The start parameter must be a multiple of the count parameter");
			}
			addToQueryStr({
				page: ((args.start || 0) / args.count) + 1,
				per_page: args.count
			});
		}
		if(args.sort){
			// make the sort into query parameters
			var queryObj = {
				sortBy : [],
				sortDir : []
			};

			dojo.forEach(args.sort, function(item){
				queryObj.sortBy.push(item.attribute);
				queryObj.sortDir.push(!!item.descending ? 'DESC' : 'ASC');
			});

			addToQueryStr(queryObj);
			delete args.sort;
		}

		return this.inherited(arguments);
	}
});
<|endoftext|>


<commit_before>// auto-suggest docs:
// http://code.drewwilson.com/entry/autosuggest-jquery-plugin
// Changes to previous
// - prefill and ashtmlid in data-auto-suggest-config
define([
    'jquery',
    '../core/logging',
    '../core/parser',
    '../registry',
    '../utils',
    'jquery_autosuggest',
    'jquery_form'
], function($, logging, Parser, registry, utils) {
    var log = logging.getLogger('autosuggest');

    var parser = new Parser("autosuggest");
    parser.add_argument('words');
    parser.add_argument('pre-fill');
    parser.add_argument('as-html-id');
    parser.add_argument('selected-value-prop', "name");
    parser.add_argument('search-obj-prop', "name");
    parser.add_argument('start-text', "Enter text");

    var _ = {
        name: 'autosuggest',
        trigger: "input.pat-autosuggest",
        init: function($el, opts) {
            if ($el.length > 1)
                return $el.each(function() { _.init($(this), opts); });

            var cfg = _.parser.parse($el, opts);
            if ($el.attr('readonly'))
                cfg.startText = "";

            if (cfg.preFill && (cfg.preFill.slice(0,1) === ','))
                cfg.preFill = cfg.preFill.slice(1);

            $el.on('keydown.pat-autosuggest', _.onKeyDown);

            var data = cfg.words.split(/\s*,\s*/).map(function(word) {
                return {value: word, name: word};
            });

            cfg.selectionAdded = function(elem) {
                $el.next().trigger("change");
            };
            cfg.selectionRemoved = function(elem) {
                elem.remove();
                $el.next().trigger("change");
            };

            // XXX: See https://github.com/Patternslib/Patterns/issues/149
            if (cfg['asHtmlId'] !== undefined) {
                cfg['asHtmlID'] = cfg['asHtmlId'];
            }
            $el.autoSuggest(data, cfg);

            return $el;
        },
        destroy: function($el) {
            $el.off('.pat-autosuggest');

            // XXX: destroy the jqueryPlugin, unfortunately it doesn't
            // support this as of now
        },

        parser: parser,

        onKeyDown: function(ev) {
            var $this = $(this);
            if (ev.which === 13) {
                var $results = $this.parents('.as-selections').next();
                ev.preventDefault();
                // skip ENTER->comma translation, if selection is active
                if (($results.is(':visible')) &&
                    ($results.find('.active').length > 0)) return;
                var newev = $.Event("keydown");
                newev.ctrlKey = false;
                newev.which = 188;
                newev.keyCode = 188;
                $this.trigger(newev);
            }
        }
    };
    registry.register(_);
    return _;
});

// jshint indent: 4, browser: true, jquery: true, quotmark: double
// vim: sw=4 expandtab
<commit_msg>autosuggest words default to empty string<commit_after>// auto-suggest docs:
// http://code.drewwilson.com/entry/autosuggest-jquery-plugin
// Changes to previous
// - prefill and ashtmlid in data-auto-suggest-config
define([
    'jquery',
    '../core/logging',
    '../core/parser',
    '../registry',
    '../utils',
    'jquery_autosuggest',
    'jquery_form'
], function($, logging, Parser, registry, utils) {
    var log = logging.getLogger('autosuggest');

    var parser = new Parser("autosuggest");
    parser.add_argument('words', "");
    parser.add_argument('pre-fill');
    parser.add_argument('as-html-id');
    parser.add_argument('selected-value-prop', "name");
    parser.add_argument('search-obj-prop', "name");
    parser.add_argument('start-text', "Enter text");

    var _ = {
        name: 'autosuggest',
        trigger: "input.pat-autosuggest",
        init: function($el, opts) {
            if ($el.length > 1)
                return $el.each(function() { _.init($(this), opts); });

            var cfg = _.parser.parse($el, opts);
            if ($el.attr('readonly'))
                cfg.startText = "";

            if (cfg.preFill && (cfg.preFill.slice(0,1) === ','))
                cfg.preFill = cfg.preFill.slice(1);

            $el.on('keydown.pat-autosuggest', _.onKeyDown);

            var data = cfg.words.split(/\s*,\s*/).map(function(word) {
                return {value: word, name: word};
            });

            cfg.selectionAdded = function(elem) {
                $el.next().trigger("change");
            };
            cfg.selectionRemoved = function(elem) {
                elem.remove();
                $el.next().trigger("change");
            };

            // XXX: See https://github.com/Patternslib/Patterns/issues/149
            if (cfg['asHtmlId'] !== undefined) {
                cfg['asHtmlID'] = cfg['asHtmlId'];
            }
            $el.autoSuggest(data, cfg);

            return $el;
        },
        destroy: function($el) {
            $el.off('.pat-autosuggest');

            // XXX: destroy the jqueryPlugin, unfortunately it doesn't
            // support this as of now
        },

        parser: parser,

        onKeyDown: function(ev) {
            var $this = $(this);
            if (ev.which === 13) {
                var $results = $this.parents('.as-selections').next();
                ev.preventDefault();
                // skip ENTER->comma translation, if selection is active
                if (($results.is(':visible')) &&
                    ($results.find('.active').length > 0)) return;
                var newev = $.Event("keydown");
                newev.ctrlKey = false;
                newev.which = 188;
                newev.keyCode = 188;
                $this.trigger(newev);
            }
        }
    };
    registry.register(_);
    return _;
});

// jshint indent: 4, browser: true, jquery: true, quotmark: double
// vim: sw=4 expandtab
<|endoftext|>


<commit_before>
var forecast = require('./lib/forecast');
var select_options = require('../../lib/options');

module.exports = {

    name: 'weather',

    label: 'Weer widget',

    image_url: 'assets/content/modules/weather.png',

    config: {
        position: '',
        title: '',
        panel: '',
        opacity: 1,
        show_text: true,
        fullwidth: false,
        location: {
            name: '',
            gid: '',
            lat: '',
            lng: ''
        },
        forecast: {
            template: 'weather-three',
            units: 'C'
        },
        text: {
            color: '',
            size: ''
        }
    },

    google_api_key: process.env.SJ_GOOGLE_JS_API_KEY,

    fields: {
        config: {
            'forecast.template': {
                type: 'select',
                label: 'Template',
                options: {
                    'Vandaag': 'weather-today', /*trans*/
                    '3 dagen': 'weather-three', /*trans*/
                    '5 dagen': 'weather-five' /*trans*/
                },
                attrs: {'class': 'uk-form-width-medium'}
            },
            'text.color': {
                type: 'select',
                label: 'Tekstkleur',
                options: select_options.text_color,
                attrs: {'class': 'uk-form-width-medium'}
            },
            'text.size': {
                type: 'select',
                label: 'Tekstgrootte',
                options: select_options.text_size,
                attrs: {'class': 'uk-form-width-medium'}
            }
        },
        advanced_1: {
            'forecast.units': {
                type: 'select',
                label: 'Maateenheid',
                options: {
                    'Celcius': 'C', /*trans*/
                    'Fahrenheit': 'F', /*trans*/
                },
                attrs: {'class': 'uk-form-width-medium'}
            },
            'show_text': {
                type: 'checkbox',
                label: 'Toon tekst in verwachting'
            }
        }
    },

    commands: {
        getWeather(config, params, cb) {
            if (!config.location.lat || !config.location.lng) {
                return cb(null, {
                    error: 'Geen lat-lng voor locatie bekend.',
                    weather: {}
                });
            }
            forecast.getWeather(config.forecast.units, config.location.lat, config.location.lng, (params.ignore_cache || false),
                (err, weather) => {
                    if (err) {
                        //todo retry/return cache
                        return cb(err);
                    }
                    cb(null, {error: false, weather, params});
                });
        }
    }
};<commit_msg>added params.id in getWeather<commit_after>
var forecast = require('./lib/forecast');
var select_options = require('../../lib/options');

module.exports = {

    name: 'weather',

    label: 'Weer widget',

    image_url: 'assets/content/modules/weather.png',

    config: {
        position: '',
        title: '',
        panel: '',
        opacity: 1,
        show_text: true,
        fullwidth: false,
        location: {
            name: '',
            gid: '',
            lat: '',
            lng: ''
        },
        forecast: {
            template: 'weather-three',
            units: 'C'
        },
        text: {
            color: '',
            size: ''
        }
    },

    google_api_key: process.env.SJ_GOOGLE_JS_API_KEY,

    fields: {
        config: {
            'forecast.template': {
                type: 'select',
                label: 'Template',
                options: {
                    'Vandaag': 'weather-today', /*trans*/
                    '3 dagen': 'weather-three', /*trans*/
                    '5 dagen': 'weather-five' /*trans*/
                },
                attrs: {'class': 'uk-form-width-medium'}
            },
            'text.color': {
                type: 'select',
                label: 'Tekstkleur',
                options: select_options.text_color,
                attrs: {'class': 'uk-form-width-medium'}
            },
            'text.size': {
                type: 'select',
                label: 'Tekstgrootte',
                options: select_options.text_size,
                attrs: {'class': 'uk-form-width-medium'}
            }
        },
        advanced_1: {
            'forecast.units': {
                type: 'select',
                label: 'Maateenheid',
                options: {
                    'Celcius': 'C', /*trans*/
                    'Fahrenheit': 'F', /*trans*/
                },
                attrs: {'class': 'uk-form-width-medium'}
            },
            'show_text': {
                type: 'checkbox',
                label: 'Toon tekst in verwachting'
            }
        }
    },

    commands: {
        getWeather(config, params, cb) {
            if (!config.location.lat || !config.location.lng) {
                return cb(null, {
                    error: 'Geen lat-lng voor locatie bekend.',
                    weather: {}
                });
            }
            forecast.getWeather(config.forecast.units, config.location.lat, config.location.lng, (params.ignore_cache || false), params.id,
                (err, weather) => {
                    if (err) {
                        //todo retry/return cache
                        return cb(err);
                    }
                    cb(null, {error: false, weather, params});
                });
        }
    }
};<|endoftext|>


<commit_before>/*
 * changes:
 * - open($el, opts) instead of open($el, duration)
 * - same for close
 */
define([
    "jquery",
    "./inject",
    "../core/logger",
    "../core/parser",
    "../core/store",
    "../registry"
], function($, inject, logger, Parser, store, registry) {
    var log = logger.getLogger("pat.collapsible"),
        parser = new Parser("collapsible");

    parser.add_argument("load-content");
    parser.add_argument("store", "none", ["none", "session", "local"]);
    parser.add_argument("duration", "fast");
    parser.add_argument("easing", "linear");
    parser.add_argument("closed", false);

    var _ = {
        name: "collapsible",
        trigger: ".pat-collapsible",

        init: function($el, opts) {
            return $el.each(function() {
                var $el = $(this),
                    options = _._validateOptions(this, parser.parse($el, opts)),
                // create collapsible structure
                    $trigger = $el.children(':first'),
                    $content = $el.children(':gt(0)'),
                    $panel, state, storage;
                if ($content.length > 0)
                    $panel = $content.wrapAll('
')
                        .parent();
                else
                    $panel = $('
').insertAfter($trigger);

                $el.data("patternCollapsible", options);
                state=(options.closed || $el.hasClass("closed")) ? "closed" : "open";
                if (options.store!=="none") {
                    storage=(options.store==="local" ? store.local : store.session)(_.name);
                    state=storage.get(this.id) || state;
                }

                if (state==="closed") {
                    $el.removeClass("open").addClass("closed");
                    $panel.hide();
                } else {
                    _.loadContent($el);
                    $el.addClass("open");
                    $panel.show();
                }

                $trigger
                    .off(".pat-collapsible")
                    .on("click.pat-collapsible", null, $el, _._onClick);

                return $el;
            });
        },

        _onClick: function(event) {
            // XXX: hack to ignore clicks on a tooltip in our trigger element
            if ($(event.target).attr("data-tooltip") === undefined) {
                _.toggle(event.data);
            }
        },

        destroy: function($el) {
            $el.removeData("patternCollapsible");
            $el.children(":first").off('.pat-collapsible');
        },

        open: function($el) {
            if (!$el.hasClass("open"))
                _.toggle($el);
            return $el;
        },

        close: function($el) {
            if (!$el.hasClass("closed"))
                _.toggle($el);
            return $el;
        },

        _validateOptions: function(trigger, options) {
            if (options.store!=="none") {
                if (!trigger.id) {
                    log.warn("state persistance requested, but element has no id");
                    options.store="none";
                } else if (!store.supported) {
                    log.warn("state persistance requested, but browser does not support webstorage");
                    options.store="none";
                }
            }
            return options;
        },

        loadContent: function($el) {
            var options = $el.data("patternCollapsible");
            if (!options.loadContent)
                return;
            var components = options.loadContent.split('#'),
                url = components[0],
                id = components[1] ? '#' + components[1] : null,
                opts = [{
                    url: url,
                    source: id,
                    $target: $('.panel-content', $el)
                }];
            inject.execute(opts, $el);
        },

        toggle: function($el) {
            var options = $el.data("patternCollapsible"),
                $panel = $el.find('.panel-content'),
                new_state = $el.hasClass("closed") ? "open" : "closed";

            if (options.store!=="none") {
                var storage=(options.store==="local" ? store.local : store.session)(_.name);
                storage.set($el.attr("id"), new_state);
            }

            if (new_state==="open") {
                $el.trigger('patterns-collapsible-open');
                _._transit($el, $panel, "closed", "open", options);
            } else {
                $el.trigger('patterns-collapsible-close');
                _._transit($el, $panel, "open", "closed", options);
            }

            // allow for chaining
            return $el;
        },

        _transit: function($el, $panel, from_cls, to_cls, options) {
            if (to_cls === "open")
                _.loadContent($el);
            $el.removeClass(from_cls);
            if (options.duration)
                $el.addClass("in-progress");
            $panel.slideToggle(options.duration, options.easing, function() {
                $el
                    .removeClass("in-progress")
                    .addClass(to_cls);
            });
        }
    };

    registry.register(_);
    return _;
});

// jshint indent: 4, browser: true, jquery: true, quotmark: double
// vim: sw=4 expandtab
<commit_msg>collapsible as jquery plugin<commit_after>/*
 * changes:
 * - open($el, opts) instead of open($el, duration)
 * - same for close
 */
define([
    "jquery",
    "./inject",
    "../core/logger",
    "../core/parser",
    "../core/store",
    "../registry"
], function($, inject, logger, Parser, store, registry) {
    var log = logger.getLogger("pat.collapsible"),
        parser = new Parser("collapsible");

    parser.add_argument("load-content");
    parser.add_argument("store", "none", ["none", "session", "local"]);
    parser.add_argument("duration", "fast");
    parser.add_argument("easing", "linear");
    parser.add_argument("closed", false);

    var _ = {
        name: "collapsible",
        trigger: ".pat-collapsible",
        jquery_plugin: true,
        init: function($el, opts) {
            return $el.each(function() {
                var $el = $(this),
                    options = _._validateOptions(this, parser.parse($el, opts)),
                // create collapsible structure
                    $trigger = $el.children(':first'),
                    $content = $el.children(':gt(0)'),
                    $panel, state, storage;
                if ($content.length > 0)
                    $panel = $content.wrapAll('
')
                        .parent();
                else
                    $panel = $('
').insertAfter($trigger);

                $el.data("patternCollapsible", options);
                state=(options.closed || $el.hasClass("closed")) ? "closed" : "open";
                if (options.store!=="none") {
                    storage=(options.store==="local" ? store.local : store.session)(_.name);
                    state=storage.get(this.id) || state;
                }

                if (state==="closed") {
                    $el.removeClass("open").addClass("closed");
                    $panel.hide();
                } else {
                    _.loadContent($el);
                    $el.addClass("open");
                    $panel.show();
                }

                $trigger
                    .off(".pat-collapsible")
                    .on("click.pat-collapsible", null, $el, _._onClick);

                return $el;
            });
        },

        _onClick: function(event) {
            // XXX: hack to ignore clicks on a tooltip in our trigger element
            if ($(event.target).attr("data-tooltip") === undefined) {
                _.toggle(event.data);
            }
        },

        destroy: function($el) {
            $el.removeData("patternCollapsible");
            $el.children(":first").off('.pat-collapsible');
        },

        open: function($el) {
            if (!$el.hasClass("open"))
                _.toggle($el);
            return $el;
        },

        close: function($el) {
            if (!$el.hasClass("closed"))
                _.toggle($el);
            return $el;
        },

        _validateOptions: function(trigger, options) {
            if (options.store!=="none") {
                if (!trigger.id) {
                    log.warn("state persistance requested, but element has no id");
                    options.store="none";
                } else if (!store.supported) {
                    log.warn("state persistance requested, but browser does not support webstorage");
                    options.store="none";
                }
            }
            return options;
        },

        loadContent: function($el) {
            var options = $el.data("patternCollapsible");
            if (!options.loadContent)
                return;
            var components = options.loadContent.split('#'),
                url = components[0],
                id = components[1] ? '#' + components[1] : null,
                opts = [{
                    url: url,
                    source: id,
                    $target: $('.panel-content', $el)
                }];
            inject.execute(opts, $el);
        },

        toggle: function($el) {
            var options = $el.data("patternCollapsible"),
                $panel = $el.find('.panel-content'),
                new_state = $el.hasClass("closed") ? "open" : "closed";

            if (options.store!=="none") {
                var storage=(options.store==="local" ? store.local : store.session)(_.name);
                storage.set($el.attr("id"), new_state);
            }

            if (new_state==="open") {
                $el.trigger('patterns-collapsible-open');
                _._transit($el, $panel, "closed", "open", options);
            } else {
                $el.trigger('patterns-collapsible-close');
                _._transit($el, $panel, "open", "closed", options);
            }

            // allow for chaining
            return $el;
        },

        _transit: function($el, $panel, from_cls, to_cls, options) {
            if (to_cls === "open")
                _.loadContent($el);
            $el.removeClass(from_cls);
            if (options.duration)
                $el.addClass("in-progress");
            $panel.slideToggle(options.duration, options.easing, function() {
                $el
                    .removeClass("in-progress")
                    .addClass(to_cls);
            });
        }
    };

    registry.register(_);
    return _;
});

// jshint indent: 4, browser: true, jquery: true, quotmark: double
// vim: sw=4 expandtab
<|endoftext|>


<commit_before>/* Experimental vector tile layer for Leaflet
 * Uses D3 to render GeoJSON; faster than Leaflet's native.
 * Originally by Ziggy Jonsson: http://bl.ocks.org/ZJONSSON/5602552
 * Reworked by Nelson Minar: http://bl.ocks.org/NelsonMinar/5624141
 *
 * While working (and fast!) this plugin requires work to work like
 * a typical Leaflet layer. Todo:
 *   Make this work even if <svg> isn't in the DOM yet;
 *     For now, add a fake GeoJSON layer to your map before one of these
 *     new L.geoJson({"type":"LineString","coordinates":[[0,0],[0,0]]}).addTo(map);
 *   Make this work for tile types that aren't FeatureCollection
 *   Match D3 idioms for .classed(), .style(), etc? Or match the Leaflet API?
 *   Work on allowing feature popups, etc.
 */
L.TileLayer.d3_geoJSON =  L.TileLayer.extend({
    onAdd : function(map) {
        L.TileLayer.prototype.onAdd.call(this,map);
        this._path = d3.geo.path().projection(function(d) {
            var point = map.latLngToLayerPoint(new L.LatLng(d[1],d[0]));
            return [point.x,point.y];
        });
        this.on("tileunload",function(d) {
            if (d.tile.xhr) d.tile.xhr.abort();
            if (d.tile.nodes) d.tile.nodes.remove();
            d.tile.nodes = null;
            d.tile.xhr = null;
        });
    },
    _loadTile : function(tile,tilePoint) {
        var self = this;
        this._adjustTilePoint(tilePoint);

        if (!tile.nodes && !tile.xhr) {
            tile.xhr = d3.json(this.getTileUrl(tilePoint),function(geoJson) {
                tile.xhr = null;
                tile.nodes = d3.select(map._container).select("svg").append("g");
                tile.nodes.selectAll("path")
                    .data(geoJson.features).enter()
                  .append("path")
                    .attr("d", self._path)
                    .attr("class", self.options.class)
                    .attr("style", self.options.style)
                    .attr("data-huc8", function(x){return x.properties.huc8;})
                    .attr("data-name", function(x){return x.properties.name;})
                    .on("mouseover", function(x) {
                        $('#headerbar').html(x.properties.name);
                        d3.select(d3.event.target).classed("highlightriver", true);
                        $('#bottomright').html(
                          'Avg Stage: '     + x.properties.svalue.toFixed(1) + ' ft
' +
                          'Avg Discharge: ' + x.properties.dvalue.toFixed(1) + ' cfs
' +
                          'Avg Rank: '      + x.properties.drank.toFixed(0) + '%
' +
                          'Maximum values for today'
                        );
                    })
                    .on("mouseout",  function(x) { d3.select(d3.event.target).classed("highlightriver", false); });
            });
        }
    }
});
<commit_msg>Values are now current for date shown<commit_after>/* Experimental vector tile layer for Leaflet
 * Uses D3 to render GeoJSON; faster than Leaflet's native.
 * Originally by Ziggy Jonsson: http://bl.ocks.org/ZJONSSON/5602552
 * Reworked by Nelson Minar: http://bl.ocks.org/NelsonMinar/5624141
 *
 * While working (and fast!) this plugin requires work to work like
 * a typical Leaflet layer. Todo:
 *   Make this work even if <svg> isn't in the DOM yet;
 *     For now, add a fake GeoJSON layer to your map before one of these
 *     new L.geoJson({"type":"LineString","coordinates":[[0,0],[0,0]]}).addTo(map);
 *   Make this work for tile types that aren't FeatureCollection
 *   Match D3 idioms for .classed(), .style(), etc? Or match the Leaflet API?
 *   Work on allowing feature popups, etc.
 */
L.TileLayer.d3_geoJSON =  L.TileLayer.extend({
    onAdd : function(map) {
        L.TileLayer.prototype.onAdd.call(this,map);
        this._path = d3.geo.path().projection(function(d) {
            var point = map.latLngToLayerPoint(new L.LatLng(d[1],d[0]));
            return [point.x,point.y];
        });
        this.on("tileunload",function(d) {
            if (d.tile.xhr) d.tile.xhr.abort();
            if (d.tile.nodes) d.tile.nodes.remove();
            d.tile.nodes = null;
            d.tile.xhr = null;
        });
    },
    _loadTile : function(tile,tilePoint) {
        var self = this;
        this._adjustTilePoint(tilePoint);

        if (!tile.nodes && !tile.xhr) {
            tile.xhr = d3.json(this.getTileUrl(tilePoint),function(geoJson) {
                tile.xhr = null;
                tile.nodes = d3.select(map._container).select("svg").append("g");
                tile.nodes.selectAll("path")
                    .data(geoJson.features).enter()
                  .append("path")
                    .attr("d", self._path)
                    .attr("class", self.options.class)
                    .attr("style", self.options.style)
                    .attr("data-huc8", function(x){return x.properties.huc8;})
                    .attr("data-name", function(x){return x.properties.name;})
                    .on("mouseover", function(x) {
                        $('#headerbar').html(x.properties.name);
                        d3.select(d3.event.target).classed("highlightriver", true);
                        $('#bottomright').html(
                          'Avg Stage: '     + x.properties.svalue.toFixed(1) + ' ft
' +
                          'Avg Discharge: ' + x.properties.dvalue.toFixed(1) + ' cfs
' +
                          'Avg Rank: '      + x.properties.drank.toFixed(0) + '%';
                        );
                    })
                    .on("mouseout",  function(x) { d3.select(d3.event.target).classed("highlightriver", false); });
            });
        }
    }
});
<|endoftext|>


<commit_before>define([
    'require',
    '../core/parser',
    '../logging'
], function(require) {
    var Parser = require('../core/parser'),
        parser = new Parser("injectcontent"),
        log = require('../logging').getLogger('collapsible');

    var init = function($el, opts) {
        // create collapsible structure
        var $ctrl = $el.children(':first'),
            $content = $el.children(':gt(0)'),
            $panel;
        if ($content.length > 0) {
            $panel = $content.wrapAll('
')
                .parent();
        } else {
            $panel = $('
').insertAfter($ctrl);
        }

        // set initial state
        if ((opts && opts.closed) || $el.hasClass("closed")) {
            $el.removeClass("closed");
            close($el, 0);
        } else {
            $el.addClass("open");
            $el.trigger('patterns-collapsible-open');
            // loadcontent($el);
        }

        // bind to click events
        $ctrl.bind("click", function() { toggle($el, "fast"); });

        // allow for chaining
        return $el;
    };

    // var loadcontent = function($el) {
    //     // check whether we have to fetch content
    //     var opts_str = $el.data('collapsible'),
    //         src, href, id, $panel;

    //     if (!opts_str) return;

    //     src = parser.parse(opts_str)["injectcontent"] || "";
    //     href = src.split('#')[0];
    //     id = src.split('#')[1];
    //     log.debug(href, id);
    //     if (!id) {
    //         log.error('injectcontent url needs id to fetch content for panel', src);
    //     } else {
    //         $panel = $el.find('.panel-content');
    //         $.ajax({
    //             context: $el,
    //             url: href,
    //             error: function(jqxhr, status, error) {
    //                 log.error('Error loading panel content', jqxhr, status, error);
    //                 $panel.html(
    //                     status + ': Failed to load panel content from: ' + href
    //                 );
    //             },
    //             success: function(data, status, jqxhr) {
    //                 // just copied from old inject code
    //                 data = data
    //                     .replace(/


<commit_before>$('document').ready(function() {
	requirejs([
		'lavender/masonry',
		'lavender/imagesLoaded',
	], function(Masonry, imagesLoaded) {
		var fixed = localStorage.getItem('fixed') || 0,
			masonry;

		function doMasonry() {
			if($('.home').length) {
				masonry = new Masonry('.row.home > div', {
					itemSelector: '.category-item',
					columnWidth: '.category-item',
					transitionDuration: 0,
					isInitLayout: false
				});

				$('.row.home > div p img').imagesLoaded(function() {
					masonry.layout();
				});

				var saved = JSON.parse(localStorage.getItem('masonry:layout'));
				if (saved) {
					for (var cid in saved) {
						if (saved.hasOwnProperty(cid)) {
							var category = saved[cid];

							$('.category-item[data-cid="' + cid + '"]').css({
								left: category.left,
								top: category.top,
								position: 'absolute'
							});
						}
					}
				}

				masonry.on('layoutComplete', function() {
					var saved = {};

					$('.category-item').each(function() {
						var $this = $(this);

						saved[$this.attr('data-cid')] = {
							left: $this.css('left'),
							top: $this.css('top'),
						};
					});

					localStorage.setItem('masonry:layout', JSON.stringify(saved));
				});
			}
		}

		function resize(fixed) {
			fixed = parseInt(fixed, 10);

			var container = fixed ? $('.container-fluid') : $('.container');
			container.toggleClass('container-fluid', fixed !== 1).toggleClass('container', fixed === 1);
			localStorage.setItem('fixed', fixed);
			doMasonry();
		}

		$(window).on('action:ajaxify.end', function(ev, data) {
			var url = data.url;

			if(!/^\/admin\//.test(url) && !/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
				if (url === "") {
					doMasonry();
					$('.category-header .badge i').tooltip();
				}

				resize(fixed);
			}
		});

		if (!$('.admin').length) {
			setupResizer();
		}

		$(window).on('action:posts.loaded', function() {
			doMasonry();
		});

		function setupResizer() {
			var div = $('

');

			div.css({
				position:'fixed',
				bottom: '20px',
				right: '20px'
			}).hide().appendTo(document.body);

			$(window).on('mousemove', function(ev) {
				if (ev.clientX > $(window).width() - 150 && ev.clientY > $(window).height() - 150) {
					div.fadeIn();
				} else {
					div.stop(true, true).fadeOut();
				}
			});

			div.find('.resizer').on('click', function() {
				fixed = parseInt(fixed, 10) === 1 ? 0 : 1;
				resize(fixed);
			});
		}
	});

	(function() {
		// loading animation
		var ajaxifyGo = ajaxify.go,
			loadData = ajaxify.loadData,
			refreshTitle = app.refreshTitle,
			loadingBar = $('.loading-bar');

		ajaxify.go = function(url, callback, quiet) {
			loadingBar.fadeIn(0).removeClass('reset')
			return ajaxifyGo(url, callback, quiet);
		};

		$(window).on('action:ajaxify.loadingTemplates', function() {
			loadingBar.css('width', '90%');
		});

		app.refreshTitle = function(url) {
			loadingBar.css('width', '100%');
			setTimeout(function() {
				loadingBar.fadeOut(250);

				setTimeout(function() {
					loadingBar.addClass('reset').css('width', '0%');
				}, 250);
			}, 750);

			return refreshTitle(url);
		};
	}());
});<commit_msg>prevent lav from derping ACP container<commit_after>$('document').ready(function() {
	requirejs([
		'lavender/masonry',
		'lavender/imagesLoaded',
	], function(Masonry, imagesLoaded) {
		var fixed = localStorage.getItem('fixed') || 0,
			masonry;

		function doMasonry() {
			if($('.home').length) {
				masonry = new Masonry('.row.home > div', {
					itemSelector: '.category-item',
					columnWidth: '.category-item',
					transitionDuration: 0,
					isInitLayout: false
				});

				$('.row.home > div p img').imagesLoaded(function() {
					masonry.layout();
				});

				var saved = JSON.parse(localStorage.getItem('masonry:layout'));
				if (saved) {
					for (var cid in saved) {
						if (saved.hasOwnProperty(cid)) {
							var category = saved[cid];

							$('.category-item[data-cid="' + cid + '"]').css({
								left: category.left,
								top: category.top,
								position: 'absolute'
							});
						}
					}
				}

				masonry.on('layoutComplete', function() {
					var saved = {};

					$('.category-item').each(function() {
						var $this = $(this);

						saved[$this.attr('data-cid')] = {
							left: $this.css('left'),
							top: $this.css('top'),
						};
					});

					localStorage.setItem('masonry:layout', JSON.stringify(saved));
				});
			}
		}

		function resize(fixed) {
			fixed = parseInt(fixed, 10);

			var container = fixed ? $('.container-fluid') : $('.container');
			container.toggleClass('container-fluid', fixed !== 1).toggleClass('container', fixed === 1);
			localStorage.setItem('fixed', fixed);
			doMasonry();
		}

		$(window).on('action:ajaxify.end', function(ev, data) {
			var url = data.url;

			if(!/^admin\//.test(url) && !/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
				if (url === "") {
					doMasonry();
					$('.category-header .badge i').tooltip();
				}

				resize(fixed);
			}
		});

		if (!$('.admin').length) {
			setupResizer();
		}

		$(window).on('action:posts.loaded', function() {
			doMasonry();
		});

		function setupResizer() {
			var div = $('

');

			div.css({
				position:'fixed',
				bottom: '20px',
				right: '20px'
			}).hide().appendTo(document.body);

			$(window).on('mousemove', function(ev) {
				if (ev.clientX > $(window).width() - 150 && ev.clientY > $(window).height() - 150) {
					div.fadeIn();
				} else {
					div.stop(true, true).fadeOut();
				}
			});

			div.find('.resizer').on('click', function() {
				fixed = parseInt(fixed, 10) === 1 ? 0 : 1;
				resize(fixed);
			});
		}
	});

	(function() {
		// loading animation
		var ajaxifyGo = ajaxify.go,
			loadData = ajaxify.loadData,
			refreshTitle = app.refreshTitle,
			loadingBar = $('.loading-bar');

		ajaxify.go = function(url, callback, quiet) {
			loadingBar.fadeIn(0).removeClass('reset')
			return ajaxifyGo(url, callback, quiet);
		};

		$(window).on('action:ajaxify.loadingTemplates', function() {
			loadingBar.css('width', '90%');
		});

		app.refreshTitle = function(url) {
			loadingBar.css('width', '100%');
			setTimeout(function() {
				loadingBar.fadeOut(250);

				setTimeout(function() {
					loadingBar.addClass('reset').css('width', '0%');
				}, 250);
			}, 750);

			return refreshTitle(url);
		};
	}());
});<|endoftext|>