<commit_before>"use strict";

(function ($) {
    if (!GBrowserIsCompatible()) {
        return;
    }
    var geocoder = new GClientGeocoder();
    $(document).unload(GUnload);

    var fuzzyInterpretValue = function (obj) {
        obj = obj || {};
        if (typeof(obj) === 'string') {
            return { 'type': 'locate', 'address': obj };
        }
        if ( typeof(obj) === 'object' ) {
            if (obj.lat && obj.lng) {
                obj.longitude = ($.isFunction(obj.lng) ? obj.lng() : obj.lng);
                obj.latitude = ($.isFunction(obj.lat) ? obj.lat() : obj.lat);
            }
            if (!obj.type) {
                if (obj.longitude && obj.latitude) {
                    obj.type = 'static';
                } else if ( obj.address) {
                    obj.type = 'locate';
                } else {
                    obj.type = 'auto';
                }
            }
        }

        return obj;
    };

    var fuzzyInterpretList = function (list) {
        list = list || [ { 'type': 'auto' } ];

        if (! $.isArray(list) ) {
            list = [ list ];
        }

        $.each(list, function (index, value) {
            list[index] = fuzzyInterpretValue(value)
        });
        return list;
    };

    // centers is a list of objects:
    // * { 'type': 'auto',
    //     'zoom': '11' }
    //
    // * { 'type': 'static',
    //     'zoom': '11',
    //     'longitude': '16.372778',
    //     'latitude': '48.209206' }
    //
    // * { 'type': 'locate',
    //     'zoom': '12',
    //     'address': 'Vienna, Austria' }

    // triggers events:
    // * mapmoveend: center, northEast, southWest
    // * mapinitialized: map, uiOptions (if defaultUi is enabled)
    $.fn.createMap = function (centers, settings) {

        var defaultSettings = { 'defaultZoom': 11,
                                'scroll': true,
                                'onlyNormalMapType': true,
                                'defaultUi': true }; // if set, scroll and onlyNormalMapType are unused
        var settings = $.extend(defaultSettings, settings);

        centers = fuzzyInterpretList(centers);

        this.each(function () {
            var selectedElement = $(this);

            var addEvents = function (map, domElement) {
                // see http://code.google.com/intl/de-AT/apis/maps/documentation/reference.html#GMap2.Events
                GEvent.addListener(map, "addoverlay", function (overlay) {
                    var overlays = selectedElement.data('_overlays') || {};
                    var name = $(overlay).data('_name');
                    var named_overlays = overlays[name] || [];
                    named_overlays.push(overlay);
                    overlays[name] = named_overlays;
                    selectedElement.data('_overlays', overlays);
                });
                GEvent.addListener(map, "removeoverlay", function (overlay) {
                    var overlays = selectedElement.data('_overlays');
                    var name = $(overlay).data('_name');
                    var named_overlays = overlays[name];
                    named_overlays.splice(named_overlays.indexOf(overlay), 1);
                    overlays[name] = named_overlays;
                    selectedElement.data('_overlays', overlays);
                });

                GEvent.addListener(map, "moveend", function () {
                    var center = map.getCenter();
                    var bounds = map.getBounds();
                    var southWest = bounds.getSouthWest();
                    var northEast = bounds.getNorthEast();

                    $(domElement).trigger('mapmoveend', [ map, center, northEast, southWest]);
                });

                var delegatedEvents = "addmaptype removemaptype click dblclick";
                delegatedEvents += " singlerightclick movestart move zoomend";
                delegatedEvents += " maptypechanged infowindowopen infowindowbeforeclose";
                delegatedEvents += " infowindowclose addoverlay removeoverlay";
                delegatedEvents += " clearoverlays mouseover mouseout";
                delegatedEvents += " dragstart drag dragend load";

                delegatedEvents = delegatedEvents.split(' ');

                var manualEvent = [ 'moveend' ];

                $.each(delegatedEvents, function (index, eventname) {
                    if ($.inArray(manualEvent, eventname) === -1) {
                        GEvent.addListener(map, eventname, function () {
                            $(selectedElement).trigger('map' + eventname,
                                $.merge([ map ], arguments));
                        });
                    }
                });
            };

            // *****
            // initializing controller elements
            if (selectedElement.length !== 1) {
                throw 'Containing more than one element.';
            }
            var map = new GMap2(this);

            if (settings.defaultUi) {
                var customUI = map.getDefaultUI();
                if (!settings.scroll) {
                    customUI.zoom.scrollwheel = false;
                }

                if (settings.onlyNormalMapType) {
                    customUI.maptypes.hybrid = false;
                    customUI.maptypes.satellite = false;
                    customUI.maptypes.physical = false;
                }
            }

            selectedElement.data('_map', map);
            $(this).trigger('mapinitialized', [ map, customUI ]);

            if (settings.defaultUi) {
                map.setUI(customUI);
            }

            addEvents(map, this);

            var getCenterMapCallback = function (zoomlevel) {
                zoomlevel = zoomlevel || settings.defaultZoom;
                var centerMap = function (center) {
                    map.setCenter(center, parseInt(zoomlevel, 10));

                    var bounds = map.getBounds();
                    var southWest = bounds.getSouthWest();
                    var northEast = bounds.getNorthEast();

                    $(selectedElement).trigger('moveend', [ map, center, northEast, southWest]);
                };

                return centerMap;
            };

            // centering map
            $.each(centers, function (index, value) {
                var callback = getCenterMapCallback(value.zoom);
                if (value.type === 'static' &&
                   value.latitude !== '' && value.latitude !== '0' &&
                   value.longitude !== '' && value.longitude !== '0') {
                    $(map).queue('center', function () {
                        var center = new GLatLng(value.latitude, value.longitude);
                        callback(center);

                        $(map).clearQueue('center');
                        $(this).dequeue('center');
                    });
                } else if (value.type === 'auto') {
                    $(map).queue('center', function () {
                        var queue_item = $(this);
                        var setLocation = function (position) {
                            var lat = position.latitude || position.coords.latitude;
                            var lng = position.longitude || position.coords.longitude;
                            var center = new GLatLng(lat, lng);
                            callback(center);

                            $(map).clearQueue('center');
                            queue_item.dequeue('center');
                        };
                        /*
                        if (settings.useHtmlGeolocator &&
                            navigator && navigator.geolocation) {
                            navigator.geolocation.getCurrentPosition(setLocation);
                        } else
                        */
                        if (google.loader && google.loader.ClientLocation) {
                            var clientLocation = google.loader.ClientLocation;
                            setLocation(clientLocation);
                        } else {
                            queue_item.dequeue('center');
                        }
                    });
                } else if (value.type === 'locate') {

                    $(map).queue('center', function () {
                        var queue_item = $(this);
                        var foundAddress = function (point) {
                            if (point !== null) {
                                callback(point);

                                $(map).clearQueue('center');
                                queue_item.dequeue('center');
                            }
                        };

                        if (geocoder && value.address !== '') {
                            geocoder.getLatLng(value.address, foundAddress);
                        }
                    });
                }
            });
            $(map).dequeue('center');
        });
        return this;
    };

    // address is:
    // * a string
    // * an object (attributes: longitude, latitude)
    // * a list of objects

    // triggers events:
    // * markeradded: marker, point
    // * markermoved: marker, point
    $.fn.addMarker = function (addresses, settings) {

        var defaultSettings = { 'clear': true,
                                'center': true,
                                'defaultZoom': 13,
                                'closeInfoOnLeave': true,
                                'draggable': true,
                                'infoOnHover': false,
                                'name': 'undefined',
                                'options': {} };
        var settings = $.extend(defaultSettings, settings);

        addresses = fuzzyInterpretList(addresses);

        var markerOptions = $.extend({ 'draggable': settings.draggable },
                                        settings.options );

        this.each(function () {
            var selectedElement = $(this);

            var map = $(this).data('_map');
            if (!map) {
                return;
            }

            if (settings.clear) {
                map.clearOverlays();
            }

            $.each(addresses, function (index, address) {
                var addAddressToMap = function (point) {
                    var markerOverlay = new GMarker(point, markerOptions);
                    if (settings.draggable) {
                        GEvent.addListener(markerOverlay, "dragend", function (point) {
                            selectedElement.trigger('markermoved', [ map, markerOverlay, point ]);
                        });
                    }

                    $(markerOverlay).data('_name', settings.name)
                    map.addOverlay(markerOverlay);

                    if (address.info) {
                        GEvent.addListener(markerOverlay,
                            (settings.infoOnHover ? 'mouseover' : 'click'),
                            function () {
                                map.openInfoWindowHtml(point, address.info);
                            });
                        if (settings.infoOnHover && settings.closeInfoOnLeave) {
                            GEvent.addListener(markerOverlay, 'mouseout',
                                function () {
                                    map.closeInfoWindow();
                                });
                        }
                    }

                    if (settings.center) {
                        $(map).clearQueue('center');
                        $(map).queue('center', function () {
                            selectedElement.one('mapmoveend', function () {
                                var targetZoom = address.zoom || settings.defaultZoom;
                                map.setZoom(targetZoom);
                            });
                            map.panTo(point);
                        });
                        $(map).dequeue('center');
                    }
                    selectedElement.trigger('markeradded', [ map, markerOverlay, point ]);
                };

                if (address.type === 'auto') {
                    var point = map.getCenter();
                    addAddressToMap(point);
                } else if (address.type === 'static') {
                    var point = new GLatLng(address.latitude, address.longitude);
                    addAddressToMap(point);
                } else if (address.type === 'locate' && geocoder) {
                    geocoder.setViewport( map.getBounds() );
                    geocoder.getLatLng(address.address, function (point) {
                        if (point === null) {
                            // unable to geocode that address
                            point = map.getCenter()
                        }
                        addAddressToMap(point);
                   });
                }
            });
        });

        return this;
    };

    $.fn.removeMarker = function (name) {
        this.each(function () {
            var selectedElement = $(this);
            var map = selectedElement.data('_map');
            var overlays = selectedElement.data('_overlays') || {};

            var removeNamedOverlays = function (name) {
                var named_overlays = overlays[name] || [];
                named_overlays = named_overlays.slice(); // clone array
                $.each(named_overlays, function (index, overlay) {
                    map.removeOverlay(overlay);
                });
                overlays[name] = [];
            };

            if (name) {
                removeNamedOverlays(name);
            } else {
                $.each(overlays, function (name, overlay) {
                    removeNamedOverlays(name);
                });
            }
        });
        return this;
    };

    $.fn.trimVal = function () {
        return $.trim($(this).val());
    };

    $.serializeAddress = function (userSettings) {
        var defaultSettings = {'street': '',
                                'zip': '',
                                'city': '',
                                'country': ''
                };

        var s = $.extend(defaultSettings, userSettings);

        var address = (s.street === "" ? "" : s.street + ", ") +
                (s.zip === "" ? "" : s.zip + ' ') +
                (s.city === "" ? "" : s.city) +
                (s.country === "" ? "" : ", " + s.country);
        return address;
    };

}) (jQuery);

<commit_msg>+ added clean error message if GMaps could not be found<commit_after>"use strict";

(function ($) {
    if (!window.GBrowserIsCompatible || !GBrowserIsCompatible()) {
        throw "Error when initializing GMaps API in jquery.simplemap.js";
    }
    var geocoder = new GClientGeocoder();
    $(document).unload(GUnload);

    var fuzzyInterpretValue = function (obj) {
        obj = obj || {};
        if (typeof(obj) === 'string') {
            return { 'type': 'locate', 'address': obj };
        }
        if ( typeof(obj) === 'object' ) {
            if (obj.lat && obj.lng) {
                obj.longitude = ($.isFunction(obj.lng) ? obj.lng() : obj.lng);
                obj.latitude = ($.isFunction(obj.lat) ? obj.lat() : obj.lat);
            }
            if (!obj.type) {
                if (obj.longitude && obj.latitude) {
                    obj.type = 'static';
                } else if ( obj.address) {
                    obj.type = 'locate';
                } else {
                    obj.type = 'auto';
                }
            }
        }

        return obj;
    };

    var fuzzyInterpretList = function (list) {
        list = list || [ { 'type': 'auto' } ];

        if (! $.isArray(list) ) {
            list = [ list ];
        }

        $.each(list, function (index, value) {
            list[index] = fuzzyInterpretValue(value)
        });
        return list;
    };

    // centers is a list of objects:
    // * { 'type': 'auto',
    //     'zoom': '11' }
    //
    // * { 'type': 'static',
    //     'zoom': '11',
    //     'longitude': '16.372778',
    //     'latitude': '48.209206' }
    //
    // * { 'type': 'locate',
    //     'zoom': '12',
    //     'address': 'Vienna, Austria' }

    // triggers events:
    // * mapmoveend: center, northEast, southWest
    // * mapinitialized: map, uiOptions (if defaultUi is enabled)
    $.fn.createMap = function (centers, settings) {

        var defaultSettings = { 'defaultZoom': 11,
                                'scroll': true,
                                'onlyNormalMapType': true,
                                'defaultUi': true }; // if set, scroll and onlyNormalMapType are unused
        var settings = $.extend(defaultSettings, settings);

        centers = fuzzyInterpretList(centers);

        this.each(function () {
            var selectedElement = $(this);

            var addEvents = function (map, domElement) {
                // see http://code.google.com/intl/de-AT/apis/maps/documentation/reference.html#GMap2.Events
                GEvent.addListener(map, "addoverlay", function (overlay) {
                    var overlays = selectedElement.data('_overlays') || {};
                    var name = $(overlay).data('_name');
                    var named_overlays = overlays[name] || [];
                    named_overlays.push(overlay);
                    overlays[name] = named_overlays;
                    selectedElement.data('_overlays', overlays);
                });
                GEvent.addListener(map, "removeoverlay", function (overlay) {
                    var overlays = selectedElement.data('_overlays');
                    var name = $(overlay).data('_name');
                    var named_overlays = overlays[name];
                    named_overlays.splice(named_overlays.indexOf(overlay), 1);
                    overlays[name] = named_overlays;
                    selectedElement.data('_overlays', overlays);
                });

                GEvent.addListener(map, "moveend", function () {
                    var center = map.getCenter();
                    var bounds = map.getBounds();
                    var southWest = bounds.getSouthWest();
                    var northEast = bounds.getNorthEast();

                    $(domElement).trigger('mapmoveend', [ map, center, northEast, southWest]);
                });

                var delegatedEvents = "addmaptype removemaptype click dblclick";
                delegatedEvents += " singlerightclick movestart move zoomend";
                delegatedEvents += " maptypechanged infowindowopen infowindowbeforeclose";
                delegatedEvents += " infowindowclose addoverlay removeoverlay";
                delegatedEvents += " clearoverlays mouseover mouseout";
                delegatedEvents += " dragstart drag dragend load";

                delegatedEvents = delegatedEvents.split(' ');

                var manualEvent = [ 'moveend' ];

                $.each(delegatedEvents, function (index, eventname) {
                    if ($.inArray(manualEvent, eventname) === -1) {
                        GEvent.addListener(map, eventname, function () {
                            $(selectedElement).trigger('map' + eventname,
                                $.merge([ map ], arguments));
                        });
                    }
                });
            };

            // *****
            // initializing controller elements
            if (selectedElement.length !== 1) {
                throw 'Containing more than one element.';
            }
            var map = new GMap2(this);

            if (settings.defaultUi) {
                var customUI = map.getDefaultUI();
                if (!settings.scroll) {
                    customUI.zoom.scrollwheel = false;
                }

                if (settings.onlyNormalMapType) {
                    customUI.maptypes.hybrid = false;
                    customUI.maptypes.satellite = false;
                    customUI.maptypes.physical = false;
                }
            }

            selectedElement.data('_map', map);
            $(this).trigger('mapinitialized', [ map, customUI ]);

            if (settings.defaultUi) {
                map.setUI(customUI);
            }

            addEvents(map, this);

            var getCenterMapCallback = function (zoomlevel) {
                zoomlevel = zoomlevel || settings.defaultZoom;
                var centerMap = function (center) {
                    map.setCenter(center, parseInt(zoomlevel, 10));

                    var bounds = map.getBounds();
                    var southWest = bounds.getSouthWest();
                    var northEast = bounds.getNorthEast();

                    $(selectedElement).trigger('moveend', [ map, center, northEast, southWest]);
                };

                return centerMap;
            };

            // centering map
            $.each(centers, function (index, value) {
                var callback = getCenterMapCallback(value.zoom);
                if (value.type === 'static' &&
                   value.latitude !== '' && value.latitude !== '0' &&
                   value.longitude !== '' && value.longitude !== '0') {
                    $(map).queue('center', function () {
                        var center = new GLatLng(value.latitude, value.longitude);
                        callback(center);

                        $(map).clearQueue('center');
                        $(this).dequeue('center');
                    });
                } else if (value.type === 'auto') {
                    $(map).queue('center', function () {
                        var queue_item = $(this);
                        var setLocation = function (position) {
                            var lat = position.latitude || position.coords.latitude;
                            var lng = position.longitude || position.coords.longitude;
                            var center = new GLatLng(lat, lng);
                            callback(center);

                            $(map).clearQueue('center');
                            queue_item.dequeue('center');
                        };
                        /*
                        if (settings.useHtmlGeolocator &&
                            navigator && navigator.geolocation) {
                            navigator.geolocation.getCurrentPosition(setLocation);
                        } else
                        */
                        if (google.loader && google.loader.ClientLocation) {
                            var clientLocation = google.loader.ClientLocation;
                            setLocation(clientLocation);
                        } else {
                            queue_item.dequeue('center');
                        }
                    });
                } else if (value.type === 'locate') {

                    $(map).queue('center', function () {
                        var queue_item = $(this);
                        var foundAddress = function (point) {
                            if (point !== null) {
                                callback(point);

                                $(map).clearQueue('center');
                                queue_item.dequeue('center');
                            }
                        };

                        if (geocoder && value.address !== '') {
                            geocoder.getLatLng(value.address, foundAddress);
                        }
                    });
                }
            });
            $(map).dequeue('center');
        });
        return this;
    };

    // address is:
    // * a string
    // * an object (attributes: longitude, latitude)
    // * a list of objects

    // triggers events:
    // * markeradded: marker, point
    // * markermoved: marker, point
    $.fn.addMarker = function (addresses, settings) {

        var defaultSettings = { 'clear': true,
                                'center': true,
                                'defaultZoom': 13,
                                'closeInfoOnLeave': true,
                                'draggable': true,
                                'infoOnHover': false,
                                'name': 'undefined',
                                'options': {} };
        var settings = $.extend(defaultSettings, settings);

        addresses = fuzzyInterpretList(addresses);

        var markerOptions = $.extend({ 'draggable': settings.draggable },
                                        settings.options );

        this.each(function () {
            var selectedElement = $(this);

            var map = $(this).data('_map');
            if (!map) {
                return;
            }

            if (settings.clear) {
                map.clearOverlays();
            }

            $.each(addresses, function (index, address) {
                var addAddressToMap = function (point) {
                    var markerOverlay = new GMarker(point, markerOptions);
                    if (settings.draggable) {
                        GEvent.addListener(markerOverlay, "dragend", function (point) {
                            selectedElement.trigger('markermoved', [ map, markerOverlay, point ]);
                        });
                    }

                    $(markerOverlay).data('_name', settings.name)
                    map.addOverlay(markerOverlay);

                    if (address.info) {
                        GEvent.addListener(markerOverlay,
                            (settings.infoOnHover ? 'mouseover' : 'click'),
                            function () {
                                map.openInfoWindowHtml(point, address.info);
                            });
                        if (settings.infoOnHover && settings.closeInfoOnLeave) {
                            GEvent.addListener(markerOverlay, 'mouseout',
                                function () {
                                    map.closeInfoWindow();
                                });
                        }
                    }

                    if (settings.center) {
                        $(map).clearQueue('center');
                        $(map).queue('center', function () {
                            selectedElement.one('mapmoveend', function () {
                                var targetZoom = address.zoom || settings.defaultZoom;
                                map.setZoom(targetZoom);
                            });
                            map.panTo(point);
                        });
                        $(map).dequeue('center');
                    }
                    selectedElement.trigger('markeradded', [ map, markerOverlay, point ]);
                };

                if (address.type === 'auto') {
                    var point = map.getCenter();
                    addAddressToMap(point);
                } else if (address.type === 'static') {
                    var point = new GLatLng(address.latitude, address.longitude);
                    addAddressToMap(point);
                } else if (address.type === 'locate' && geocoder) {
                    geocoder.setViewport( map.getBounds() );
                    geocoder.getLatLng(address.address, function (point) {
                        if (point === null) {
                            // unable to geocode that address
                            point = map.getCenter()
                        }
                        addAddressToMap(point);
                   });
                }
            });
        });

        return this;
    };

    $.fn.removeMarker = function (name) {
        this.each(function () {
            var selectedElement = $(this);
            var map = selectedElement.data('_map');
            var overlays = selectedElement.data('_overlays') || {};

            var removeNamedOverlays = function (name) {
                var named_overlays = overlays[name] || [];
                named_overlays = named_overlays.slice(); // clone array
                $.each(named_overlays, function (index, overlay) {
                    map.removeOverlay(overlay);
                });
                overlays[name] = [];
            };

            if (name) {
                removeNamedOverlays(name);
            } else {
                $.each(overlays, function (name, overlay) {
                    removeNamedOverlays(name);
                });
            }
        });
        return this;
    };

    $.fn.trimVal = function () {
        return $.trim($(this).val());
    };

    $.serializeAddress = function (userSettings) {
        var defaultSettings = {'street': '',
                                'zip': '',
                                'city': '',
                                'country': ''
                };

        var s = $.extend(defaultSettings, userSettings);

        var address = (s.street === "" ? "" : s.street + ", ") +
                (s.zip === "" ? "" : s.zip + ' ') +
                (s.city === "" ? "" : s.city) +
                (s.country === "" ? "" : ", " + s.country);
        return address;
    };

}) (jQuery);

<|endoftext|>


<commit_before>/*!
 * enquire.js v2.1.2 - Awesome Media Queries in JavaScript
 * Copyright (c) 2014 Nick Williams - http://wicky.nillia.ms/enquire.js
 * License: MIT (http://www.opensource.org/licenses/mit-license.php)
 */

!function(a,b,c){var d=window.matchMedia;"undefined"!=typeof module&&module.exports?module.exports=c(d):"function"==typeof define&&define.amd?define(function(){return b[a]=c(d)}):b[a]=c(d)}("enquire",this,function(a){"use strict";function b(a,b){var c,d=0,e=a.length;for(d;e>d&&(c=b(a[d],d),c!==!1);d++);}function c(a){return"[object Array]"===Object.prototype.toString.apply(a)}function d(a){return"function"==typeof a}function e(a){this.options=a,!a.deferSetup&&this.setup()}function f(b,c){this.query=b,this.isUnconditional=c,this.handlers=[],this.mql=a(b);var d=this;this.listener=function(a){d.mql=a,d.assess()},this.mql.addListener(this.listener)}function g(){if(!a)throw new Error("matchMedia not present, legacy browsers require a polyfill");this.queries={},this.browserIsIncapable=!a("only all").matches}return e.prototype={setup:function(){this.options.setup&&this.options.setup(),this.initialised=!0},on:function(){!this.initialised&&this.setup(),this.options.match&&this.options.match()},off:function(){this.options.unmatch&&this.options.unmatch()},destroy:function(){this.options.destroy?this.options.destroy():this.off()},equals:function(a){return this.options===a||this.options.match===a}},f.prototype={addHandler:function(a){var b=new e(a);this.handlers.push(b),this.matches()&&b.on()},removeHandler:function(a){var c=this.handlers;b(c,function(b,d){return b.equals(a)?(b.destroy(),!c.splice(d,1)):void 0})},matches:function(){return this.mql.matches||this.isUnconditional},clear:function(){b(this.handlers,function(a){a.destroy()}),this.mql.removeListener(this.listener),this.handlers.length=0},assess:function(){var a=this.matches()?"on":"off";b(this.handlers,function(b){b[a]()})}},g.prototype={register:function(a,e,g){var h=this.queries,i=g&&this.browserIsIncapable;return h[a]||(h[a]=new f(a,i)),d(e)&&(e={match:e}),c(e)||(e=[e]),b(e,function(b){d(b)&&(b={match:b}),h[a].addHandler(b)}),this},unregister:function(a,b){var c=this.queries[a];return c&&(b?c.removeHandler(b):(c.clear(),delete this.queries[a])),this}},new g});<commit_msg>Remove unused library.<commit_after><|endoftext|>


<commit_before>var moz = {};
moz.defaults = {};
moz.defaults.all = {
    scales: {},
    scalefns: {},
    title: null,
    width: 350,
    height: 220,
    data: [],
    left: 50,
    right: 10,
    first: false, // not sure what this is anymore
    markers: null, // sets the marker lines
    x_accessor: 'date',
    y_accessor: 'value',
    y_max_accessor: 'value',
    list: false,
    goal: null,
    area: 'rgb(0,0,255)',
    top: 40,
    bottom: 30,
    xax_tick: 5,
    min_x: null,
    min_y: null,
    xax_count: 8,
    yax_tick: 5,
    yax_count: 4,
    axis_opacity: 0.3,
    decimal: false,
    xax_date_format: function(d) {
        var df = d3.time.format('%b %d');
        return df(d);
    },
    buffer: 8,
    type: 'count',
    target: '#viz'
}

var GRAPHS = {};
var app = {};

app.current_version = 28;
app.sample_multiplier = 100;
app.max_data_length = 0;

function moz_chart() {
    var args = arguments[0];
    if (!args) {
        args = {};
    }

    args = _.defaults(args, moz.defaults.all);

    var g = '';
    if (args.list) {
        args.x_accessor = 0;
        args.y_accessor = 1;
    }

    var svg = d3.select(args.target)
        .append('svg')
            .attr('width', args.width)
            .attr('height', args.height);

    // determine the x bounds, given the data, or go with specified range
    add_date_x(args);
    add_value_y(args);

    args.scalefns.xf = function(di) {
        return args.scales.X(di[args.x_accessor]);
    }

    args.scalefns.yf = function(di) {
        return args.scales.Y(di[args.y_accessor]);
    }

    if (args.title) {
        svg.append('text')
            .text(args.title)
            .attr('text-transform', 'upper')
            .attr('x', args.left)
            .attr('y', args.top / 2);
    }

    if (args.goal) {
        var num = d3.format("0,000");

        g = svg.append('g')
            .attr('class', 'goal');

        g.append('line')
            .attr('x1', args.left)
            .attr('x2', args.width - args.right)
            .attr('y1', args.scales.Y(args.goal))
            .attr('y2', args.scales.Y(args.goal))
            .attr('stroke-dasharray', '5,1')

        g.append('text')
            .attr('x', args.width - args.right)
            .attr('y', args.scales.Y(args.goal))
            .attr('dy', '1.1em')
            .attr('text-anchor', 'end')
            .text("Dec. 2014 Goal");

        g.append('text')
            .attr('x', args.width - args.right)
            .attr('y', args.scales.Y(args.goal))
            .attr('dy', '-.35em')
            .attr('text-anchor', 'end')
            .text(num(d3.round(args.goal)));
    }

    var line = d3.svg.line()
        .x(args.scalefns.xf)
        .y(args.scalefns.yf)
        .interpolate('cardinal');

    var area = d3.svg.area()
        .x(args.scalefns.xf)
        .y0(args.scales.Y(0))
        .y1(args.scalefns.yf)
        .interpolate('cardinal');

    // main area
    if (args.area) {
        svg.append('path')
            .attr('class', 'main-area')
            .attr('d', area(args.data))
            .attr('fill', args.area);
    }

    // main line
    svg.append('path')
        .attr('class', 'main-line')
        .attr('d', line(args.data))
        .attr('stroke', function() {
            return (args.area) ? args.area : 'black';
        });

    // annotations
    if (args.markers) {
        g = svg.append('g')
            .attr('class', 'dates');

        g.selectAll('.dates')
            .data(args.markers)
            .enter().append('line')
                .attr('x1', function(d) {
                    return args.scales.X(d['date'])
                })
                .attr('x2', function(d) {
                    return args.scales.X(d['date'])
                })
                .attr('y1', args.top)
                .attr('y2', function() {
                    return args.height - args.bottom - args.buffer;
                })
                .attr('stroke-dasharray', '3,1');

        g.selectAll('.dates')
            .data(args.markers)
            .enter().append('text')
                .attr('x', function(d) {
                    return args.scales.X(d['date'])
                })
                .attr('y', args.top - 8)
                .attr('text-anchor', 'middle')
                .text(function(d) {
                    return d['label'];
                });
    }

    var years = d3.time.years(
        d3.min(args.data, function(d) { return d[args.x_accessor]; }),
        d3.max(args.data, function(d) { return d[args.x_accessor]; })
    );

    g = svg.append('g')
        .attr('class', 'year-marker');

    g.selectAll('.year_marker')
        .data(years).enter()
            .append('line')
                .attr('x1', args.scales.X)
                .attr('x2', args.scales.X)
                .attr('y1', args.top)
                .attr('y2', args.height - args.bottom);

    var yformat = d3.time.format('%Y');
    g.selectAll('.year_marker')
        .data(years).enter()
            .append('text')
                .attr('x', args.scales.X)
                .attr('y', args.height - args.bottom + 28)
                .attr('text-anchor', 'middle')
                .text(function(d) {
                    return yformat(d)
                });

    g = svg.append('g')
        .attr('class', 'point');

    g.selectAll('.point')
        .data(args.data).enter()
            .append('circle')
                .classed('last_point', function(d, i) {
                    return i == args.data.length - 1;
                })
                .attr('cx', args.scalefns.xf)
                .attr('cy', args.scalefns.yf)
                .attr('r', 2.5)
                .attr('opacity', function(d, i) {
                    return (i == args.data.length - 1) ? 0.85 : 0;
                })
                .attr('fill', function() {
                    if(!args.area)
                        return 'black';

                    return args.area;
                });

    var yax_format;
    if (args.type == 'count') {
        yax_format = function(f) {
            var pf = d3.formatPrefix(f);
            return pf.scale(f) + pf.symbol;
        };
    }
    else {
        yax_format = function(d_) {
            var n = d3.format('%p');
            return n(d_);
        }
    }

    // x axis
    g = svg.append('g')
        .attr('class', 'x-axis');

    g.append('line')
        .attr('x1', args.scales.X(_.last(args.scales.X.ticks(args.xax_count))))
        .attr('x2', args.scales.X(_.first(args.scales.X.ticks(args.xax_count))))
        .attr('y1', args.height - args.bottom)
        .attr('y2', args.height - args.bottom)
        .attr('opacity', args.axis_opacity);

    g.selectAll('.xax-ticks')
        .data(args.scales.X.ticks(args.xax_count)).enter()
            .append('line')
                .attr('x1', args.scales.X)
                .attr('x2', args.scales.X)
                .attr('y1', args.height - args.bottom)
                .attr('y2', args.height - args.bottom + args.xax_tick)
                .attr('opacity', args.axis_opacity);

    g.selectAll('.xax-labels')
        .data(args.scales.X.ticks(args.xax_count)).enter()
            .append('text')
                .attr('x', args.scales.X)
                .attr('y', args.height - args.bottom + args.xax_tick * 7 / 3)
                .attr('dy', '.50em')
                .attr('text-anchor', 'middle')
                .text(function(d) {
                    return args.xax_date_format(d);
                })

    // y axis
    g = svg.append('g')
        .attr('class', 'y-axis');

    g.append('line')
        .attr('x1', args.left)
        .attr('x2', args.left)
        .attr('y1', args.scales.Y(_.first(args.scales.Y.ticks(args.yax_count))))
        .attr('y2', args.scales.Y(_.last(args.scales.Y.ticks(args.yax_count))))
        .attr('opacity', args.axis_opacity);

    g.selectAll('.yax-ticks')
        .data(args.scales.Y.ticks(args.yax_count)).enter()
            .append('line')
                .attr('x1', args.left)
                .attr('x2', args.left - args.yax_tick)
                .attr('y1', args.scales.Y)
                .attr('y2', args.scales.Y)
                .attr('opacity', args.axis_opacity);

    g.selectAll('.yax-labels')
        .data(args.scales.Y.ticks(args.yax_count)).enter()
            .append('text')
                .attr('x', args.left - args.yax_tick * 3 / 2)
                .attr('dx', -3).attr('y', args.scales.Y)
                .attr('dy', '.35em')
                .attr('text-anchor', 'end')
                .text(function(d, i) {
                    var o = yax_format(d);
                    return o;
                })

    //main rollover
    g = svg.append('g')
        .attr('class', 'transparent-rollover-rect');

    g.selectAll('.periods')
        .data(args.data).enter()
            .append('rect')
                .attr('x', function(d, i) {
                    var current_date = d;
                    var next_date, previous_date;
                    var x_coord;

                    if (i == 0) {
                        next_date = args.data[1];
                        x_coord = args.scalefns.xf(current_date)
                            - (args.scalefns.xf(next_date)
                            - args.scalefns.xf(current_date)) / 2;
                    }
                    else {
                        previous_date = args.data[i - 1];
                        x_coord = args.scalefns.xf(current_date)
                            - (args.scalefns.xf(current_date)
                            - args.scalefns.xf(previous_date)) / 2;
                    }

                    return x_coord;
                })
                .attr('y', args.top)
                .attr('width', function(d, i) {
                    if (i != args.data.length - 1) {
                        return args.scalefns.xf(args.data[i + 1]) - args.scalefns.xf(d);
                    }
                    else {
                        return args.scalefns.xf(args.data[1])
                            - args.scalefns.xf(args.data[0]);
                    }
                })
                .attr('height', args.height - args.bottom)
                .on('mouseover', goal_over(svg, args))
                .on('mouseout', goal_out(svg, args));
}

function goal_over(svg, args) {
    return function(d, i) {
        d3.selectAll('circle')
            .attr('opacity', 0).filter(function(g, j) {
                return d == g;
            })
            .attr('opacity', 0.85);

        svg.selectAll('text')
            .filter(function(g, j) {
                return d == g;
            })
            .attr('opacity', 0.3);

        var fmt = d3.time.format('%b %e, %Y');

        if (args.type == 'count') {
            var num = function(d_) {
                var n = d3.format("0,000");
                d_ = args.decimal ? d3.round(d_, 2) : d3.round(d_);
                return n(d_);
            }
        }
        else {
            var num = function(d_) {
                var n = d3.format('%');
                return n(d_);
            }
        }

        var dd = new Date(+d[args.x_accessor]);
        dd.setDate(dd.getDate() + 1);

        svg.append('text')
            .classed('goals_rollover_text', true)
            .attr('xml:space', 'preserve')
            .attr('x', args.width - args.right + 4)
            .attr('y', args.top / 2)
            .attr('text-anchor', 'end')
            .text(fmt(dd) + '  ' + num(d[args.y_accessor]));
    }
}
// nohup make ARGS="scripts/downloads_daily.py outData/2014-04-01.csv
// /data/weblogs/v2_raw/download-stats.mozilla.org/2014-04-01" hadoop &

function goal_out(svg, args) {
    return function(d, i) {
        svg.selectAll('circle')
            .attr('opacity', 0);

        svg.select('.goals_rollover_text')
            .remove();

        d3.selectAll('circle.last_point')
            .attr('opacity', 0.85);
    }
}

var percentage_comp = function(val, yes, neutral, no) {
    val = Math.round(val * 100) / 100;
    return val > 0 ? yes : (val == 0 ? neutral : no);
}

function strip_punctuation(s) {
    var punctuationless = s.replace(/[^a-zA-Z0-9 ]+/g, '');
    var finalString = 'chart_' + punctuationless.replace(/ +?/g, "");
    return finalString;
}

function perc(p) {
    return d3.round(p * 100, 1) + '%';
}

function percentage_change(first, last) {
    return (last - first) / last;
}

function version_to_int(v) {
    return parseInt(parseFloat(v));
}

function which_version(date) {
    var version = _.filter(app.versions, function(d) {
        return date >= d['date'] && date <= d['end'];
        //date > d
    })[0];
    return version;
}

function add_date_x(args) {
    var min_x = args.min_x ? args.min_x : args.data[0][args.x_accessor];
    var max_x = args.max_x ? args.max_x : _.last(args.data)[args.x_accessor];

    args.scales.X = d3.time.scale()
        .domain([min_x, max_x])
        .range([args.left + args.buffer, args.width - args.right]);

    return args;
}

function add_value_y(args) {
    args.scales.Y = d3.scale.linear()
        .domain([0, Math.max(d3.max(args.data, function(d) {
            return d[args.y_accessor]
        }) * 10 / 9, args.goal * 10 / 9)])
        .range([args.height - args.bottom - args.buffer, args.top]);

    return args;
}

function add_line_scalefns(args) {}<commit_msg>Fix issue #8<commit_after>'use strict';

var moz = {};
moz.defaults = {};
moz.defaults.all = {
    scales: {},
    scalefns: {},
    title: null,
    width: 350,
    height: 220,
    data: [],
    left: 50,
    right: 10,
    first: false, // not sure what this is anymore
    markers: null, // sets the marker lines
    x_accessor: 'date',
    y_accessor: 'value',
    y_max_accessor: 'value',
    list: false,
    goal: null,
    area: 'rgb(0,0,255)',
    top: 40,
    bottom: 30,
    xax_tick: 5,
    min_x: null,
    min_y: null,
    xax_count: 8,
    yax_tick: 5,
    yax_count: 4,
    axis_opacity: 0.3,
    decimal: false,
    xax_date_format: function(d) {
        var df = d3.time.format('%b %d');
        return df(d);
    },
    buffer: 8,
    type: 'count',
    target: '#viz'
}

var GRAPHS = {};
var app = {};

app.current_version = 28;
app.sample_multiplier = 100;
app.max_data_length = 0;

function moz_chart() {
    var args = arguments[0];
    if (!args) {
        args = {};
    }

    args = _.defaults(args, moz.defaults.all);

    var g = '';
    if (args.list) {
        args.x_accessor = 0;
        args.y_accessor = 1;
    }

    var svg = d3.select(args.target)
        .append('svg')
            .attr('width', args.width)
            .attr('height', args.height);

    // determine the x bounds, given the data, or go with specified range
    add_date_x(args);
    add_value_y(args);

    args.scalefns.xf = function(di) {
        return args.scales.X(di[args.x_accessor]);
    }

    args.scalefns.yf = function(di) {
        return args.scales.Y(di[args.y_accessor]);
    }

    if (args.title) {
        svg.append('text')
            .text(args.title)
            .attr('text-transform', 'upper')
            .attr('x', args.left)
            .attr('y', args.top / 2);
    }

    if (args.goal) {
        var num = d3.format("0,000");

        g = svg.append('g')
            .attr('class', 'goal');

        g.append('line')
            .attr('x1', args.left)
            .attr('x2', args.width - args.right)
            .attr('y1', args.scales.Y(args.goal))
            .attr('y2', args.scales.Y(args.goal))
            .attr('stroke-dasharray', '5,1')

        g.append('text')
            .attr('x', args.width - args.right)
            .attr('y', args.scales.Y(args.goal))
            .attr('dy', '1.1em')
            .attr('text-anchor', 'end')
            .text("Dec. 2014 Goal");

        g.append('text')
            .attr('x', args.width - args.right)
            .attr('y', args.scales.Y(args.goal))
            .attr('dy', '-.35em')
            .attr('text-anchor', 'end')
            .text(num(d3.round(args.goal)));
    }

    // main area
    if (args.area) {
        var area = d3.svg.area()
            .x(args.scalefns.xf)
            .y0(args.scales.Y(0))
            .y1(args.scalefns.yf)
            .interpolate('cardinal');

        svg.append('path')
            .attr('class', 'main-area')
            .attr('d', area(args.data))
            .attr('fill', args.area);
    }

    // main line
    var line = d3.svg.line()
        .x(args.scalefns.xf)
        .y(args.scalefns.yf)
        .interpolate('cardinal');

    svg.append('path')
        .attr('class', 'main-line')
        .attr('d', line(args.data))
        .attr('stroke', function() {
            return (args.area) ? args.area : 'black';
        });

    // annotations
    if (args.markers) {
        g = svg.append('g')
            .attr('class', 'dates');

        g.selectAll('.dates')
            .data(args.markers)
            .enter().append('line')
                .attr('x1', function(d) {
                    return args.scales.X(d['date'])
                })
                .attr('x2', function(d) {
                    return args.scales.X(d['date'])
                })
                .attr('y1', args.top)
                .attr('y2', function() {
                    return args.height - args.bottom - args.buffer;
                })
                .attr('stroke-dasharray', '3,1');

        g.selectAll('.dates')
            .data(args.markers)
            .enter().append('text')
                .attr('x', function(d) {
                    return args.scales.X(d['date'])
                })
                .attr('y', args.top - 8)
                .attr('text-anchor', 'middle')
                .text(function(d) {
                    return d['label'];
                });
    }

    var years = d3.time.years(
        d3.min(args.data, function(d) { return d[args.x_accessor]; }),
        d3.max(args.data, function(d) { return d[args.x_accessor]; })
    );

    g = svg.append('g')
        .attr('class', 'year-marker');

    g.selectAll('.year_marker')
        .data(years).enter()
            .append('line')
                .attr('x1', args.scales.X)
                .attr('x2', args.scales.X)
                .attr('y1', args.top)
                .attr('y2', args.height - args.bottom);

    var yformat = d3.time.format('%Y');
    g.selectAll('.year_marker')
        .data(years).enter()
            .append('text')
                .attr('x', args.scales.X)
                .attr('y', args.height - args.bottom + 28)
                .attr('text-anchor', 'middle')
                .text(function(d) {
                    return yformat(d)
                });

    g = svg.append('g')
        .attr('class', 'point');

    g.selectAll('.point')
        .data(args.data).enter()
            .append('circle')
                .classed('last_point', function(d, i) {
                    return i == args.data.length - 1;
                })
                .attr('cx', args.scalefns.xf)
                .attr('cy', args.scalefns.yf)
                .attr('r', 2.5)
                .attr('opacity', function(d, i) {
                    return (i == args.data.length - 1) ? 0.85 : 0;
                })
                .attr('fill', function() {
                    if(!args.area)
                        return 'black';

                    return args.area;
                });

    var yax_format; // currently, {count, percentage}
    if (args.type == 'count') {
        yax_format = function(f) {
            var pf = d3.formatPrefix(f);
            return pf.scale(f) + pf.symbol;
        };
    }
    else {
        yax_format = function(d_) {
            var n = d3.format('%p');
            return n(d_);
        }
    }

    // x axis
    g = svg.append('g')
        .attr('class', 'x-axis');

    g.append('line')
        .attr('x1', args.scales.X(_.last(args.scales.X.ticks(args.xax_count))))
        .attr('x2', args.scales.X(_.first(args.scales.X.ticks(args.xax_count))))
        .attr('y1', args.height - args.bottom)
        .attr('y2', args.height - args.bottom)
        .attr('opacity', args.axis_opacity);

    g.selectAll('.xax-ticks')
        .data(args.scales.X.ticks(args.xax_count)).enter()
            .append('line')
                .attr('x1', args.scales.X)
                .attr('x2', args.scales.X)
                .attr('y1', args.height - args.bottom)
                .attr('y2', args.height - args.bottom + args.xax_tick)
                .attr('opacity', args.axis_opacity);

    g.selectAll('.xax-labels')
        .data(args.scales.X.ticks(args.xax_count)).enter()
            .append('text')
                .attr('x', args.scales.X)
                .attr('y', args.height - args.bottom + args.xax_tick * 7 / 3)
                .attr('dy', '.50em')
                .attr('text-anchor', 'middle')
                .text(function(d) {
                    return args.xax_date_format(d);
                })

    // y axis
    g = svg.append('g')
        .attr('class', 'y-axis');

    g.append('line')
        .attr('x1', args.left)
        .attr('x2', args.left)
        .attr('y1', args.scales.Y(_.first(args.scales.Y.ticks(args.yax_count))))
        .attr('y2', args.scales.Y(_.last(args.scales.Y.ticks(args.yax_count))))
        .attr('opacity', args.axis_opacity);

    g.selectAll('.yax-ticks')
        .data(args.scales.Y.ticks(args.yax_count)).enter()
            .append('line')
                .attr('x1', args.left)
                .attr('x2', args.left - args.yax_tick)
                .attr('y1', args.scales.Y)
                .attr('y2', args.scales.Y)
                .attr('opacity', args.axis_opacity);

    g.selectAll('.yax-labels')
        .data(args.scales.Y.ticks(args.yax_count)).enter()
            .append('text')
                .attr('x', args.left - args.yax_tick * 3 / 2)
                .attr('dx', -3).attr('y', args.scales.Y)
                .attr('dy', '.35em')
                .attr('text-anchor', 'end')
                .text(function(d, i) {
                    var o = yax_format(d);
                    return o;
                })

    //main rollover
    g = svg.append('g')
        .attr('class', 'transparent-rollover-rect');

    g.selectAll('.periods')
        .data(args.data).enter()
            .append('rect')
                .attr('x', function(d, i) {
                    var current_date = d;
                    var next_date, previous_date;
                    var x_coord;

                    if (i == 0) {
                        next_date = args.data[1];
                        x_coord = args.scalefns.xf(current_date)
                            - (args.scalefns.xf(next_date)
                            - args.scalefns.xf(current_date)) / 2;
                    }
                    else {
                        previous_date = args.data[i - 1];
                        x_coord = args.scalefns.xf(current_date)
                            - (args.scalefns.xf(current_date)
                            - args.scalefns.xf(previous_date)) / 2;
                    }

                    return x_coord;
                })
                .attr('y', args.top)
                .attr('width', function(d, i) {
                    if (i != args.data.length - 1) {
                        return args.scalefns.xf(args.data[i + 1]) - args.scalefns.xf(d);
                    }
                    else {
                        return args.scalefns.xf(args.data[1])
                            - args.scalefns.xf(args.data[0]);
                    }
                })
                .attr('height', args.height - args.bottom)
                .on('mouseover', goal_over(svg, args))
                .on('mouseout', goal_out(svg, args));
}

function goal_over(svg, args) {
    return function(d, i) {
        d3.selectAll('circle')
            .attr('opacity', 0)
            .filter(function(g, j) {
                return d == g;
            })
            .attr('opacity', 0.85);

        svg.selectAll('text')
            .filter(function(g, j) {
                return d == g;
            })
            .attr('opacity', 0.3);

        var fmt = d3.time.format('%b %e, %Y');

        if (args.type == 'count') {
            var num = function(d_) {
                var n = d3.format("0,000");
                d_ = args.decimal ? d3.round(d_, 2) : d3.round(d_);
                return n(d_);
            }
        }
        else {
            var num = function(d_) {
                var n = d3.format('%');
                return n(d_);
            }
        }

        var dd = new Date(+d[args.x_accessor]);
        dd.setDate(dd.getDate() + 1);

        svg.append('text')
            .classed('goals_rollover_text', true)
            .attr('xml:space', 'preserve')
            .attr('x', args.width - args.right + 4)
            .attr('y', args.top / 2)
            .attr('text-anchor', 'end')
            .text(function() {
                return fmt(dd) + '  ' + num(d[args.y_accessor])
            });
    }
}

// nohup make ARGS="scripts/downloads_daily.py outData/2014-04-01.csv
// /data/weblogs/v2_raw/download-stats.mozilla.org/2014-04-01" hadoop &

function goal_out(svg, args) {
    return function(d, i) {
        svg.selectAll('circle')
            .attr('opacity', 0);

        svg.select('.goals_rollover_text')
            .remove();

        d3.selectAll('circle.last_point')
            .attr('opacity', 0.85);
    }
}

var percentage_comp = function(val, yes, neutral, no) {
    val = Math.round(val * 100) / 100;
    return val > 0 ? yes : (val == 0 ? neutral : no);
}

function strip_punctuation(s) {
    var punctuationless = s.replace(/[^a-zA-Z0-9 ]+/g, '');
    var finalString = 'chart_' + punctuationless.replace(/ +?/g, "");
    return finalString;
}

function perc(p) {
    return d3.round(p * 100, 1) + '%';
}

function percentage_change(first, last) {
    return (last - first) / last;
}

function version_to_int(v) {
    return parseInt(parseFloat(v));
}

function which_version(date) {
    var version = _.filter(app.versions, function(d) {
        return date >= d['date'] && date <= d['end'];
        //date > d
    })[0];
    return version;
}

function add_date_x(args) {
    var min_x = args.min_x ? args.min_x : args.data[0][args.x_accessor];
    var max_x = args.max_x ? args.max_x : _.last(args.data)[args.x_accessor];

    args.scales.X = d3.time.scale()
        .domain([min_x, max_x])
        .range([args.left + args.buffer, args.width - args.right]);

    return args;
}

function add_value_y(args) {
    args.scales.Y = d3.scale.linear()
        .domain([0, Math.max(d3.max(args.data, function(d) {
            return d[args.y_accessor]
        }) * 10 / 9, args.goal * 10 / 9)])
        .range([args.height - args.bottom - args.buffer, args.top]);

    return args;
}

function add_line_scalefns(args) {}<|endoftext|>


<commit_before>/**
 * Created with IntelliJ IDEA.
 * User: a208574
 * Date: 13/08/12
 * Time: 01:17
 * To change this template use File | Settings | File Templates.
 */
<commit_msg>efefctive remove<commit_after><|endoftext|>


<commit_before>var controlsModule = (function(window, $) {

    /*Global variables within the module scope*/
    var _controlBarContainer;
    var _controlBarLowerContainer;
    var _table;
    var _options = {
        "startDate": null,
        "endDate": null
    };

    /**
     * @param {object} domContainer
     */
    function _init(domContainer, domContainer2) {
        if (!!domContainer) {
            _controlBarContainer = domContainer;
            _setDataUpdated();
            _setDraggingMouse();
            _setInputAddress();
            _setSlider();
            _setDateRange();
        } else {
            console.log("Upper controls container doesn't exist"); //Error
        }

        if (!!domContainer2) {
            _controlBarLowerContainer = domContainer2;

            _table = _controlBarLowerContainer.find('#example').DataTable({
                "ajax": {
                    "url": "empty.json",
                    "dataSrc": ""
                },
                "dom": '<"table-buttons"<"table-buttons"Bf>l>t<"table-buttons"ip>',
                "oLanguage": {
                   "sSearch": "Filter results:"
                 },
                "buttons": [{ extend: 'colvis', text: 'Select Columns'}],
                "fixedHeader": {
                    header: true,
                    footer: true
                },
                "columns": [{
                  "data": "incidntnum",
                  "title": "Incident#",
                  "name": "incidntnum",
                }, {
                  "data": "date",
                  "title": "Date",
                  "name": "date",
                  "render": function(data, type, row, meta) {
                    return moment(data).format('l')
                  },
                  "visible": false
                }, {
                  "data": "time",
                  "title": "Time",
                  "name": "time",
                  "visible": false
                }, {
                  "data": "address",
                  "title": "Address",
                  "name": "address",
                  "visible": false
                }, {
                  "data": "pddistrict",
                  "title": "District",
                  "name": "pddistrict",
                  "visible": false
                }, {
                  "className": "mobile",
                  "data": "category",
                  "title": "Category",
                  "name": "category",
                }, {
                  "data": "descript",
                  "title": "Description",
                  "name": "descript",
                }, {
                  "className": "mobile tablet",
                  "data": "resolution",
                  "title": "Resolution",
                  "name": "resolution",
                }],
                "pageLength": 50,
                "footerCallback": function(tfoot, data, start, end, display) {
                  var dupHeaderRow = $(this.api().table().header()).children('tr:first').clone()
                  // $(tfoot).html(dupHeaderRow.html());
                }
            });
        } else {
            console.log("Lower controls container doesn't exist");
        }
    }

    function _setInputAddress() {
        $('.typeahead').typeahead({
            source: function (query, process) {
              addresses = [];
              resourcesModule.getAutoSuggestionsFromService(query, function(data){
                  $.each(data, function (i, address) {
                      addresses.push(address.text);
                  });
                  process(addresses);
              });
            },
            updater: function(item) {
                clickedIndex = $('.typeahead').find('.active').index();
                var acFeatures = resourcesModule.getLatestAutocompleteFeatures();

                //Use the map module to change the user pin's location
                mapModule.plotUserLocation(acFeatures[clickedIndex]);
                mapModule.centerMapOnLocation(acFeatures[clickedIndex]);

                //Hide the suggestions list
                $(this).parent().hide();
                controlsModule.searchCrime(mapModule.getUserLocation());
                return item;
            },
            matcher: function (item) {
                return true; //set candidate list of addresses at "typehead"
            },
            highlighter: function(item) {
                var queries = $.grep(this.query.split(" "), function(x){return x;}); //remove empty string
                var ii=0, back_ii=0;
                var res = "";

                queries.forEach(function(a_query) {
                    ii = item.toLowerCase().indexOf(a_query.toLowerCase(), back_ii); //ii: index of item
                    if (ii < 0) { return; }
                    var a_str = item.substr(ii, a_query.length);
                    var highlight_str = '' + item.substr(ii, a_str.length) + '';
                    res += item.substr(back_ii, ii - back_ii) + highlight_str;
                    back_ii = ii + a_str.length;
                });
                res += item.substr(back_ii, item.length - ii);
                return res;
            },
            minLength: 4, items: 10
        });
    }

    function _setSlider() {
        _controlBarContainer.find('#range-slider').noUiSlider({
            start: [urlSearch.getRadius("ft")],
            step: 1,
            connect: 'lower',
            range: {
                'min': [0],
                'max': [5280]
            }
        });
        _controlBarContainer.find('#range-slider').on({
            "slide": function() {
                mapModule.setUserSearchRadius($(this).val() * .3048);
            },
            "change": function() {
                controlsModule.searchCrime(mapModule.getUserLocation());
            },
            "set": function() {
                mapModule.setUserSearchRadius($(this).val() * .3048);
                controlsModule.searchCrime(mapModule.getUserLocation());
            }
        });
        _controlBarContainer.find("#range-slider").Link('lower').to($('#range-slider-input'), null, wNumb({
            decimals: 0
        }));
    }

    function _setDateRange() {
        _options["startDate"] = moment().subtract(29, 'days').format('YYYY-MM-DD');
        _options["endDate"] = moment().format('YYYY-MM-DD');

        _controlBarContainer.find('#daterange').val(urlSearch.getStartDate().format('MM/DD/YYYY') + ' - ' + urlSearch.getEndDate().format('MM/DD/YYYY'));

        _controlBarContainer.find('#daterange').daterangepicker({
                ranges: {
                    'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                    'This Month': [moment().startOf('month'), moment().endOf('month')],
                    'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
                    'This Quarter': [moment().startOf('quarter'), moment().endOf('quarter')],
                    'Last Quarter': [moment().subtract(3, 'months').startOf('quarter'), moment().subtract(3, 'months').endOf('quarter')],
                    'This Year': [moment().startOf('year'), moment()],
                    'Last Year': [moment().subtract(1, 'year').startOf('year'), moment().subtract(1, 'year').endOf('year')]
                },
                startDate: urlSearch.getStartDate() || moment().subtract(29, 'days'), // OR isn't needed here, but would then totally depend on urlSearch module
                endDate: urlSearch.getEndDate() || moment(), // OR isn't needed here, but would then totally depend on urlSearch module
                format: 'MM/DD/YYYY'
            },
            function(start, end) {
                _options["startDate"] = start.format('YYYY-MM-DD');
                _options["endDate"] = end.format('YYYY-MM-DD');
                _controlBarContainer.find('#daterange').val(start.format('MM/DD/YYYY') + ' - ' + end.format('MM/DD/YYYY'));

                controlsModule.searchCrime(mapModule.getUserLocation());
            });
    }

    function _setDraggingMouse() {
        var isDraggingOnPin = false;
        var isCursorOnPin = false;
        var mapComponent = mapModule.getComponents()["map"]; //map
        var pinFeatureLayer = mapModule.getComponents()["layers"]["user"]; //FeatureLayer(pin)
        pinFeatureLayer.on("mouseover", function(e) { isCursorOnPin = true; });
        pinFeatureLayer.on("mouseout", function(e) { isCursorOnPin = false; });

        var diffLatlng = L.latLng(0.0, 0.0);
        mapComponent.on("mousedown", function(e) {
            if (isCursorOnPin) {
                isDraggingOnPin = true;
                userLatlng = pinFeatureLayer.getGeoJSON().geometry.coordinates;
                diffLatlng.lat = userLatlng[1] - e.latlng.lat;
                diffLatlng.lng = userLatlng[0] - e.latlng.lng;
                mapComponent.dragging.disable();
            }
        });
        mapComponent.on("mouseup", function(e) {
            if (!isDraggingOnPin) return;
            mapComponent.dragging.enable();
            var newGeoJson = pinFeatureLayer.getGeoJSON();
            mapModule.plotUserLocation(newGeoJson);
            mapModule.centerMapOnLocation(newGeoJson);

            var coordinates = pinFeatureLayer.getGeoJSON().geometry.coordinates;
            resourcesModule.reverseGeocoding(coordinates, function(response) {
                var address = response.features[0].place_name;
                var newUserLocation = response.features[0];
                newGeoJson.properties.name = address.split(', ')[0];
                newGeoJson.properties.locality = response.features[1].text;
                newGeoJson.properties.region = response.features[3].text;
                newGeoJson.properties.postalcode = response.features[2].text;
                address = newGeoJson.properties.name + ', ' + newGeoJson.properties.locality + ', ' + newGeoJson.properties.region;
                clickedIndex = $('.typeahead').val(address);
                controlsModule.searchCrime(newGeoJson);
            });
            isDraggingOnPin = false;
        });

        mapComponent.on("mousemove", function(e) {
            if (!isDraggingOnPin) return;
            current_geojson = pinFeatureLayer.getGeoJSON();
            current_geojson.geometry.coordinates[0] = e.latlng.lng + diffLatlng.lng;
            current_geojson.geometry.coordinates[1] = e.latlng.lat + diffLatlng.lat;
            pinFeatureLayer.setGeoJSON(current_geojson);
        });
    }

    /**
     * @param {string} query
     */
    function _refreshDownloadButtonURLs(query) {
        _controlBarLowerContainer.find("#download-csv").attr("href", resourcesModule.getCsvLink(query));
        _controlBarLowerContainer.find("#open-geojsonio").attr("href", resourcesModule.getGeojsonio(query));
        _controlBarLowerContainer.find("#open-cartodb").attr("href", resourcesModule.getCartoDbUrl(query));
        _controlBarLowerContainer.find("#email-share").attr("href", resourcesModule.setEmailLink());
    }

    /**
     * @param {string} query
     */
    function _loadDataToTable(query) {
        var datasetURL = resourcesModule.getDatasetJsonURL(query);
        _table.ajax.url(datasetURL).load(function(data){
          // console.log("data", data);
        });
    }

    function _searchCrime(userLocation) {

        //Start the API call
        //var userLocation = mapModule.getUserLocation();
        var radius = mapModule.getUserSearchRadius();

        urlSearch.pushIntoUrl(userLocation, _options, radius); // push search results into url
        _loadRadialIncidentData();
    }

    function _setDataUpdated() {
        var query = "?$select=date,time&$limit=1&$order=date DESC,time DESC";
        var datasetRequest = resourcesModule.getDatasetJsonURL(query);
        $.getJSON(datasetRequest, function(data) {
            $('#data-updated').html('Data available through ' + moment(data[0].date).format('MMMM DD, YYYY') + ' at ' + moment(data[0].time, 'HH:mm').format('hh:mm a') + '')
        });
    }

    function _getStartDate() {
        return _options["startDate"];
    }

    function _getEndDate() {
        return _options["endDate"];
    }

    function _loadRadialIncidentData() {
        var query = _buildRadialIncidentDataQuery();

        mapModule.showLoader();
        resourcesModule.getIncidentsFromAPI(query, function(data) {
            mapModule.drawApiResponse(data);
            _refreshDownloadButtonURLs(query);
            _loadDataToTable(query);
        });
    }

    function _buildRadialIncidentDataQuery() {
        var startDate = _options.startDate;
        var endDate = _options.endDate;
        var coordinates = mapModule.getUserLocation().geometry.coordinates;
        var longitude = coordinates[0];
        var latitude = coordinates[1];
        var radius = mapModule.getUserSearchRadius();

        return "?$where="
          + "date >= '" + startDate + "'"
          + " AND date <= '" + endDate + "'"
          + " AND within_circle(location," +  latitude + "," + longitude + "," + radius + ")"
          + "&$order=date DESC"
          + "&$limit=100000";
    }

    /**
     * @param {string} query
     */
    function _refreshDownloadButtonURLs(query) {
        _controlBarLowerContainer.find("#download-csv").attr("href", resourcesModule.getCsvLink(query));
        _controlBarLowerContainer.find("#open-geojsonio").attr("href", resourcesModule.getGeojsonio(query));
        _controlBarLowerContainer.find("#open-cartodb").attr("href", resourcesModule.getCartoDbUrl(query));
        _controlBarLowerContainer.find("#email-share").attr("href", resourcesModule.setEmailLink());
    }

    /**
     * @param {string} query
     */
    function _loadDataToTable(query) {
        var datasetURL = resourcesModule.getDatasetJsonURL(query);
        _table.ajax.url(datasetURL).load(function(data){
          // console.log("data", data);
        });
    }

    return {
        init: _init,
        searchCrime: _searchCrime,
        getEndDate: _getEndDate,
        getStartDate: _getStartDate,
        refreshDownloadButtonURLs: _refreshDownloadButtonURLs,
        loadDataToTable: _loadDataToTable
    };

})(window, jQuery);
<commit_msg>Change an order for increasing search efficiency.<commit_after>var controlsModule = (function(window, $) {

    /*Global variables within the module scope*/
    var _controlBarContainer;
    var _controlBarLowerContainer;
    var _table;
    var _options = {
        "startDate": null,
        "endDate": null
    };

    /**
     * @param {object} domContainer
     */
    function _init(domContainer, domContainer2) {
        if (!!domContainer) {
            _controlBarContainer = domContainer;
            _setDataUpdated();
            _setDraggingMouse();
            _setInputAddress();
            _setSlider();
            _setDateRange();
        } else {
            console.log("Upper controls container doesn't exist"); //Error
        }

        if (!!domContainer2) {
            _controlBarLowerContainer = domContainer2;

            _table = _controlBarLowerContainer.find('#example').DataTable({
                "ajax": {
                    "url": "empty.json",
                    "dataSrc": ""
                },
                "dom": '<"table-buttons"<"table-buttons"Bf>l>t<"table-buttons"ip>',
                "oLanguage": {
                   "sSearch": "Filter results:"
                 },
                "buttons": [{ extend: 'colvis', text: 'Select Columns'}],
                "fixedHeader": {
                    header: true,
                    footer: true
                },
                "columns": [{
                  "data": "incidntnum",
                  "title": "Incident#",
                  "name": "incidntnum",
                }, {
                  "data": "date",
                  "title": "Date",
                  "name": "date",
                  "render": function(data, type, row, meta) {
                    return moment(data).format('l')
                  },
                  "visible": false
                }, {
                  "data": "time",
                  "title": "Time",
                  "name": "time",
                  "visible": false
                }, {
                  "data": "address",
                  "title": "Address",
                  "name": "address",
                  "visible": false
                }, {
                  "data": "pddistrict",
                  "title": "District",
                  "name": "pddistrict",
                  "visible": false
                }, {
                  "className": "mobile",
                  "data": "category",
                  "title": "Category",
                  "name": "category",
                }, {
                  "data": "descript",
                  "title": "Description",
                  "name": "descript",
                }, {
                  "className": "mobile tablet",
                  "data": "resolution",
                  "title": "Resolution",
                  "name": "resolution",
                }],
                "pageLength": 50,
                "footerCallback": function(tfoot, data, start, end, display) {
                  var dupHeaderRow = $(this.api().table().header()).children('tr:first').clone()
                  // $(tfoot).html(dupHeaderRow.html());
                }
            });
        } else {
            console.log("Lower controls container doesn't exist");
        }
    }

    function _setInputAddress() {
        $('.typeahead').typeahead({
            source: function (query, process) {
              addresses = [];
              resourcesModule.getAutoSuggestionsFromService(query, function(data){
                  $.each(data, function (i, address) {
                      addresses.push(address.text);
                  });
                  process(addresses);
              });
            },
            updater: function(item) {
                clickedIndex = $('.typeahead').find('.active').index();
                var acFeatures = resourcesModule.getLatestAutocompleteFeatures();

                //Use the map module to change the user pin's location
                mapModule.plotUserLocation(acFeatures[clickedIndex]);
                mapModule.centerMapOnLocation(acFeatures[clickedIndex]);

                //Hide the suggestions list
                $(this).parent().hide();
                controlsModule.searchCrime(mapModule.getUserLocation());
                return item;
            },
            matcher: function (item) {
                return true; //set candidate list of addresses at "typehead"
            },
            highlighter: function(item) {
                var queries = $.grep(this.query.split(" "), function(x){return x;}); //remove empty string
                var ii=0, back_ii=0;
                var res = "";

                queries.forEach(function(a_query) {
                    ii = item.toLowerCase().indexOf(a_query.toLowerCase(), back_ii); //ii: index of item
                    if (ii < 0) { return; }
                    var a_str = item.substr(ii, a_query.length);
                    var highlight_str = '' + item.substr(ii, a_str.length) + '';
                    res += item.substr(back_ii, ii - back_ii) + highlight_str;
                    back_ii = ii + a_str.length;
                });
                res += item.substr(back_ii, item.length - ii);
                return res;
            },
            minLength: 4, items: 10
        });
    }

    function _setSlider() {
        _controlBarContainer.find('#range-slider').noUiSlider({
            start: [urlSearch.getRadius("ft")],
            step: 1,
            connect: 'lower',
            range: {
                'min': [0],
                'max': [5280]
            }
        });
        _controlBarContainer.find('#range-slider').on({
            "slide": function() {
                mapModule.setUserSearchRadius($(this).val() * .3048);
            },
            "change": function() {
                controlsModule.searchCrime(mapModule.getUserLocation());
            },
            "set": function() {
                mapModule.setUserSearchRadius($(this).val() * .3048);
                controlsModule.searchCrime(mapModule.getUserLocation());
            }
        });
        _controlBarContainer.find("#range-slider").Link('lower').to($('#range-slider-input'), null, wNumb({
            decimals: 0
        }));
    }

    function _setDateRange() {
        _options["startDate"] = moment().subtract(29, 'days').format('YYYY-MM-DD');
        _options["endDate"] = moment().format('YYYY-MM-DD');

        _controlBarContainer.find('#daterange').val(urlSearch.getStartDate().format('MM/DD/YYYY') + ' - ' + urlSearch.getEndDate().format('MM/DD/YYYY'));

        _controlBarContainer.find('#daterange').daterangepicker({
                ranges: {
                    'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                    'This Month': [moment().startOf('month'), moment().endOf('month')],
                    'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
                    'This Quarter': [moment().startOf('quarter'), moment().endOf('quarter')],
                    'Last Quarter': [moment().subtract(3, 'months').startOf('quarter'), moment().subtract(3, 'months').endOf('quarter')],
                    'This Year': [moment().startOf('year'), moment()],
                    'Last Year': [moment().subtract(1, 'year').startOf('year'), moment().subtract(1, 'year').endOf('year')]
                },
                startDate: urlSearch.getStartDate() || moment().subtract(29, 'days'), // OR isn't needed here, but would then totally depend on urlSearch module
                endDate: urlSearch.getEndDate() || moment(), // OR isn't needed here, but would then totally depend on urlSearch module
                format: 'MM/DD/YYYY'
            },
            function(start, end) {
                _options["startDate"] = start.format('YYYY-MM-DD');
                _options["endDate"] = end.format('YYYY-MM-DD');
                _controlBarContainer.find('#daterange').val(start.format('MM/DD/YYYY') + ' - ' + end.format('MM/DD/YYYY'));

                controlsModule.searchCrime(mapModule.getUserLocation());
            });
    }

    function _setDraggingMouse() {
        var isDraggingOnPin = false;
        var isCursorOnPin = false;
        var mapComponent = mapModule.getComponents()["map"]; //map
        var pinFeatureLayer = mapModule.getComponents()["layers"]["user"]; //FeatureLayer(pin)
        pinFeatureLayer.on("mouseover", function(e) { isCursorOnPin = true; });
        pinFeatureLayer.on("mouseout", function(e) { isCursorOnPin = false; });

        var diffLatlng = L.latLng(0.0, 0.0);
        mapComponent.on("mousedown", function(e) {
            if (isCursorOnPin) {
                isDraggingOnPin = true;
                userLatlng = pinFeatureLayer.getGeoJSON().geometry.coordinates;
                diffLatlng.lat = userLatlng[1] - e.latlng.lat;
                diffLatlng.lng = userLatlng[0] - e.latlng.lng;
                mapComponent.dragging.disable();
            }
        });
        mapComponent.on("mouseup", function(e) {
            if (!isDraggingOnPin) return;
            mapComponent.dragging.enable();
            var newGeoJson = pinFeatureLayer.getGeoJSON();
            mapModule.plotUserLocation(newGeoJson);
            mapModule.centerMapOnLocation(newGeoJson);

            isDraggingOnPin = false;

            controlsModule.searchCrime(newGeoJson);

            var coordinates = pinFeatureLayer.getGeoJSON().geometry.coordinates;
            resourcesModule.reverseGeocoding(coordinates, function(response) {
                var address = response.features[0].place_name;
                var newUserLocation = response.features[0];
                newGeoJson.properties.name = address.split(', ')[0];
                newGeoJson.properties.locality = response.features[1].text;
                newGeoJson.properties.region = response.features[3].text;
                newGeoJson.properties.postalcode = response.features[2].text;
                address = newGeoJson.properties.name + ', ' + newGeoJson.properties.locality + ', ' + newGeoJson.properties.region;
                clickedIndex = $('.typeahead').val(address);
            });

        });

        mapComponent.on("mousemove", function(e) {
            if (!isDraggingOnPin) return;
            current_geojson = pinFeatureLayer.getGeoJSON();
            current_geojson.geometry.coordinates[0] = e.latlng.lng + diffLatlng.lng;
            current_geojson.geometry.coordinates[1] = e.latlng.lat + diffLatlng.lat;
            pinFeatureLayer.setGeoJSON(current_geojson);
        });
    }

    /**
     * @param {string} query
     */
    function _refreshDownloadButtonURLs(query) {
        _controlBarLowerContainer.find("#download-csv").attr("href", resourcesModule.getCsvLink(query));
        _controlBarLowerContainer.find("#open-geojsonio").attr("href", resourcesModule.getGeojsonio(query));
        _controlBarLowerContainer.find("#open-cartodb").attr("href", resourcesModule.getCartoDbUrl(query));
        _controlBarLowerContainer.find("#email-share").attr("href", resourcesModule.setEmailLink());
    }

    /**
     * @param {string} query
     */
    function _loadDataToTable(query) {
        var datasetURL = resourcesModule.getDatasetJsonURL(query);
        _table.ajax.url(datasetURL).load(function(data){
          // console.log("data", data);
        });
    }

    function _searchCrime(userLocation) {

        //Start the API call
        //var userLocation = mapModule.getUserLocation();
        var radius = mapModule.getUserSearchRadius();

        urlSearch.pushIntoUrl(userLocation, _options, radius); // push search results into url
        _loadRadialIncidentData();
    }

    function _setDataUpdated() {
        var query = "?$select=date,time&$limit=1&$order=date DESC,time DESC";
        var datasetRequest = resourcesModule.getDatasetJsonURL(query);
        $.getJSON(datasetRequest, function(data) {
            $('#data-updated').html('Data available through ' + moment(data[0].date).format('MMMM DD, YYYY') + ' at ' + moment(data[0].time, 'HH:mm').format('hh:mm a') + '')
        });
    }

    function _getStartDate() {
        return _options["startDate"];
    }

    function _getEndDate() {
        return _options["endDate"];
    }

    function _loadRadialIncidentData() {
        var query = _buildRadialIncidentDataQuery();

        mapModule.showLoader();
        resourcesModule.getIncidentsFromAPI(query, function(data) {
            mapModule.drawApiResponse(data);
            _refreshDownloadButtonURLs(query);
            _loadDataToTable(query);
        });
    }

    function _buildRadialIncidentDataQuery() {
        var startDate = _options.startDate;
        var endDate = _options.endDate;
        var coordinates = mapModule.getUserLocation().geometry.coordinates;
        var longitude = coordinates[0];
        var latitude = coordinates[1];
        var radius = mapModule.getUserSearchRadius();

        return "?$where="
          + "date >= '" + startDate + "'"
          + " AND date <= '" + endDate + "'"
          + " AND within_circle(location," +  latitude + "," + longitude + "," + radius + ")"
          + "&$order=date DESC"
          + "&$limit=100000";
    }

    /**
     * @param {string} query
     */
    function _refreshDownloadButtonURLs(query) {
        _controlBarLowerContainer.find("#download-csv").attr("href", resourcesModule.getCsvLink(query));
        _controlBarLowerContainer.find("#open-geojsonio").attr("href", resourcesModule.getGeojsonio(query));
        _controlBarLowerContainer.find("#open-cartodb").attr("href", resourcesModule.getCartoDbUrl(query));
        _controlBarLowerContainer.find("#email-share").attr("href", resourcesModule.setEmailLink());
    }

    /**
     * @param {string} query
     */
    function _loadDataToTable(query) {
        var datasetURL = resourcesModule.getDatasetJsonURL(query);
        _table.ajax.url(datasetURL).load(function(data){
          // console.log("data", data);
        });
    }

    return {
        init: _init,
        searchCrime: _searchCrime,
        getEndDate: _getEndDate,
        getStartDate: _getStartDate,
        refreshDownloadButtonURLs: _refreshDownloadButtonURLs,
        loadDataToTable: _loadDataToTable
    };

})(window, jQuery);
<|endoftext|>


<commit_before>//Dropzone.autoDiscover = false //Fix dropzone already attached error

$("div#uploader").dropzone({ url: "/submit/file",
paramName: "image",
method: "post",
maxFiles: 1,
success: function(object, response) {
	setTimeout(function () {
		console.log('id: ' + response)
		$('div#uploader').addClass('finished')
		$('.dz-preview').hide()
		$.getJSON('/ajax/imageInfo/?id='+ response, function (data) {
			console.log(data)
			if($('.cover-input_hidden').length) {
				console.log('already is')
				$('.cover-input_hidden').remove()
				$('div#uploader').css('background-image', 'url("/uploads/' + data[0].filename + '.jpg")')
				$('#upload-group').append('<input type="hidden" value="' + data[0]._id + '" name="cover_image_id" />')
				$('#upload-group').append('<input type="hidden" value="' + data[0].filename + '" name="cover_image_filename" />')
			} else {
				console.log('isnt')
				$('div#uploader').css('background-image', 'url("/uploads/' + data[0].filename + '.jpg")')
				$('#upload-group').append('<input type="hidden" value="' + data[0]._id + '" name="cover_image_id" />')
				$('#upload-group').append('<input type="hidden" value="' + data[0].filename + '" name="cover_image_filename" />')
			}
		})
	}, 500)
	}
})

$("div#avatar").dropzone({ url: "/submit/file/avatar",
paramName: "image",
method: "post",
maxFile: 1,
success: function(object, response) {
	setTimeout(function () {
		alert(response)
	})
}
})
<commit_msg>Load dropzone from bower components instead and just provide the configuration in our own file<commit_after>Dropzone.autoDiscover = false //Fix dropzone already attached error

var dropzoneOptions = {
  paramName: "image",
  method: "post",
  maxFile: 1,
  dictDefaultMessage: "

Huvudbild

Släpp bilden här för att ladda upp Rekommenderad storlek 1200 x 630 px
 Lägg till bild
",
  dictFallbackMessage: "Uppdatera din webbläsare för att kunna ladda upp bilder",
  dictFileTooBig: "Bilden är för stor ({{filesize}}MiB). Maxstorlek: {{maxFilesize}}MiB.",
  dictInvalidFileType: "Du kan inte ladda upp den här typen av filer",
  dictCancelUpload: "Avbryt uppladdning",
  dictCancelUploadConfirmation: "Är du säker på att du vill avbryta?",
  dictRemoveFile: "Ta bort bild",
  dictRemoveFileConfirmation: null,
  dictMaxFilesExceeded: "Du kan inte ladda upp fler bilder",
}

$("div#uploader").dropzone(
  $.extend({
    url: "/submit/file",
    success: function(object, response) {
      setTimeout(function () {
        console.log('id: ' + response)
        $('div#uploader').addClass('finished')
        $('.dz-preview').hide()
        $.getJSON('/ajax/imageInfo/?id='+ response, function (data) {
          console.log(data)
          if($('.cover-input_hidden').length) {
            console.log('already is')
            $('.cover-input_hidden').remove()
            $('div#uploader').css('background-image', 'url("/uploads/' + data[0].filename + '.jpg")')
            $('#upload-group').append('<input type="hidden" value="' + data[0]._id + '" name="cover_image_id" />')
            $('#upload-group').append('<input type="hidden" value="' + data[0].filename + '" name="cover_image_filename" />')
          } else {
            console.log('isnt')
            $('div#uploader').css('background-image', 'url("/uploads/' + data[0].filename + '.jpg")')
            $('#upload-group').append('<input type="hidden" value="' + data[0]._id + '" name="cover_image_id" />')
            $('#upload-group').append('<input type="hidden" value="' + data[0].filename + '" name="cover_image_filename" />')
          }
        })
      }, 500)
    }
  }, dropzoneOptions)
)

$("div#avatar").dropzone(
  $.extend({
    url: "/submit/file/avatar",
    success: function(object, response) {
      setTimeout(function () {
        alert(response)
      })
    }
  }, dropzoneOptions)
)
<|endoftext|>