<commit_before>var controllers = angular.module('MosaicoControllers', []);

controllers.controller('HomeCtrl', function($scope, $document, $rootScope, $http) {
    console.log('HomeCtrl');
    // $rootScope.inProducts = false;
    watchLoaded($scope, $rootScope);
    $scope.guest=true;
    $http.get('site/guest').success(function (data) {
        if(data=='false'){
            $scope.guest=false;
        }
    }).error(function (data) {
        console.log(data);
    });
    // $document.scrollTopAnimated(0, 1300).then(function() {
    //     addScrollSpy();
    // });
});

/*controllers.controller('SubastasCtrl', function($scope, $document, $rootScope) {
    console.log('SubastasController');
    $rootScope.inProducts = false;
    watchLoaded($scope, $rootScope);
    var section = angular.element(document.getElementById('cont2'));
    $document.scrollToElementAnimated(section, 50, 1500).then(function() {
        addScrollSpy();
    });
    $scope.openLogin = function() {
        popoverLogin.$promise.then(popoverLogin.show);
    }
});

controllers.controller('ContactoCtrl', function($scope, $document, $rootScope, $http) {
    console.log('ContactoController');
    $rootScope.inProducts = false;
    watchLoaded($scope, $rootScope);
    var section = angular.element(document.getElementById('cont3'));
    $document.scrollToElementAnimated(section, 50, 1500).then(function() {
        addScrollSpy();
    });
});*/

controllers.controller('ProductosCtrl', function($scope, $document, $routeParams, $rootScope, $http, $timeout, $modal, $sce) {
    console.log('ProductosController');
    var wwidth = $(window).width();
    var wheight = $(window).height();
    /*if (wwidth < 461) {
        $scope.numPerPage = 2;
    } else if (wwidth < 801) {
        $scope.numPerPage = 4;
    } else if (wwidth < 1101) {
        $scope.numPerPage = 6;
    } else {
        $scope.numPerPage = 8;
        if (wheight > 750) {
            $scope.numPerPage = 12;
        }
    }*/
    $scope.producto = [];
    $scope.currentPage = 0;
    $scope.filteredProducts = [];
    $scope.allProducts = [];
    // $rootScope.inProducts = true;
    $scope.loaded = $rootScope.loaded;
    watchLoaded($scope, $rootScope);
    categoriaActual = $routeParams.cat_id;
    $rootScope.categoria = categoriaActual;
    subcategoriaActual = $routeParams.subcat_id;
    loadedProducts();
    conts['cont4'] = 'productos/' + categoriaActual + '/' + subcategoriaActual;
    var section = angular.element(document.getElementById('cont4'));
    /*$document.scrollToElementAnimated(section, 50, 1500).then(function() {
        addScrollSpy();
    });*/
    $scope.range = function(n) {
        return new Array(n);
    };
    /*$scope.range2 = function(start, end) {
        var ret = [];
        if (!end) {
            end = start;
            start = 0;
        }
        for (var i = start; i < end; i++) {
            ret.push(i);
        }
        return ret;
    };*/
    $scope.addToCart = function(id) {
        console.log(id);
        if(galeriaModal){
        	galeriaModal.hide();
        }
        popover.$scope.cargando = true;
        popover.$promise.then(popover.show);
        $http.get('site/add-to-cart?productId=' + id + '&quantity=' + $scope.producto[id]).
        success(function(data) {
            if (data != '') {
                carrito = data;
                popover.$scope.content = htmlCarrito(carrito);
                $rootScope.cantidadCarrito = Object.keys(data).length - 1;
                popover.$scope.cargando = false;
            }
        }).
        error(function() {
            console.log('error add to cart');
            popover.$scope.cargando = false;
        });
    };
    /*$scope.prevPage = function() {
        if ($scope.currentPage > 0) {
            $scope.currentPage--;
        }
    };
    $scope.nextPage = function() {
        if ($scope.currentPage < $scope.filteredProducts.length - 1) {
            $scope.currentPage++;
        }
    };
    $scope.setPage = function() {
        $scope.currentPage = this.n;
    };*/
    var galeriaModal = $modal({
        scope: $scope,
        template: 'partials/galeria.html',
        show: false
    });
    $scope.showModal = function(id) {
    	galeriaModal.$scope.id=id;
    	galeriaModal.$scope.name=categories[categoriaActual][subcategoriaActual][id].name;
    	galeriaModal.$scope.image1=categories[categoriaActual][subcategoriaActual][id].image1;
    	galeriaModal.$scope.image2=categories[categoriaActual][subcategoriaActual][id].image2;
    	galeriaModal.$scope.image3=categories[categoriaActual][subcategoriaActual][id].image3;
    	galeriaModal.$scope.description=$sce.trustAsHtml(categories[categoriaActual][subcategoriaActual][id].description);
    	galeriaModal.$scope.stock=categories[categoriaActual][subcategoriaActual][id].stock;
    	galeriaModal.$scope.price=categories[categoriaActual][subcategoriaActual][id].price;
        galeriaModal.$promise.then(galeriaModal.show);
    };

    function loadedProducts() {
        if (typeof(categories) !== 'undefined') {
            $scope.allProducts = [];
            for (i in categories[categoriaActual][subcategoriaActual]) {
                if (categories[categoriaActual][subcategoriaActual][i].name) {
                    $scope.allProducts.push(categories[categoriaActual][subcategoriaActual][i]);
                }
            }
            /*for (var i = 0; i < $scope.allProducts.length; i++) {
                if (i % $scope.numPerPage === 0) {
                    $scope.filteredProducts[Math.floor(i / $scope.numPerPage)] = [$scope.allProducts[i]];
                } else {
                    $scope.filteredProducts[Math.floor(i / $scope.numPerPage)].push($scope.allProducts[i]);
                }
            }*/
        } else {
            $timeout(loadedProducts, 500);
        }
    }
});

controllers.controller('MainCtrl', function($scope, $document, $location, $rootScope, $http, $window, baseUrl, $popover) {
    console.log('MainCtrl');
    $scope.enviado = false;
    $scope.noenviado = false;
    $scope.cantidadCarrito = 0;
    $rootScope.loaded = false;
    // $rootScope.inProducts = false;
    popover = $popover($('#icoCarrito'), {
        title: 'Carrito',
        template: "partials/carrito.html",
        placement: "left",
        animation: "am-flip-x",
        content: "Cargando",
    });
    var divLogin = $('#loginRegistrarse');
    if (divLogin[0]) {
        var popoverLogin = $popover(divLogin, {
            title: 'Iniciar Sesión',
            template: "partials/login.html",
            placement: "left",
            animation: "am-fade-and-slide-left",
        });
        $scope.openLogin = function() {
            popoverLogin.$promise.then(popoverLogin.show);
        };
    }
    popover.$scope.cargando = true;
    $http.get('site/load-cart').
    success(function(data) {
        console.log('cart loaded');
        var html
        if (data) {
            html = htmlCarrito(data);
            $rootScope.cantidadCarrito = Object.keys(data).length - 1;
        } else {
            html = "0 productos";
        }
        popover.$scope.content = html;
        popover.$scope.cargando = false;
    }).
    error(function() {
        console.log('error cargando carrito');
    });
    loadProducts($http, $rootScope);
    watchLoaded($scope, $rootScope);
    /*$rootScope.$watch('inProducts', function() {
        $scope.inProducts = $rootScope.inProducts;
    });*/
    $scope.$watch('loaded', function() {
        watchLoadedCategory($scope, $rootScope);
    });
    $rootScope.$watch('categoria', function() {
        watchLoadedCategory($scope, $rootScope);
    });
    $scope.toSection = function(sectionId, categoriaId, subcategoriaId) {
        console.log('toSection');
        var hash = conts[sectionId];
        if (categoriaId && subcategoriaId) {
            hash = 'productos/' + categoriaId + '/' + subcategoriaId;
        }
        // $('.circle').removeAttr('du-scrollspy');
        var section = angular.element(document.getElementById(sectionId));
        if (section[0]) {
            /*$document.scrollToElementAnimated(section, 50, 1500).then(function() {
                addScrollSpy();
                if (hash) {*/
                    $location.hash(hash);
                    // $location.url(hash);
                /*}
            });*/
        } else {
            var url = baseUrl;
            $window.location.href = url + '#/' + hash;
            // $location.url(hash);
        }

    };
    $scope.changeSubcategory = function(subcategoriaId) {
        $location.url('productos/' + $rootScope.categoria + '/' + subcategoriaId);
    };
    popover.$scope.removeFromCart = function(id) {
        console.log('removeFromCart');
        popover.$scope.cargando = true;
        $http.get('site/remove-from-cart?productId=' + id).
        success(function(data) {
            if (data != '') {
                carrito = data;
                popover.$scope.content = htmlCarrito(carrito);
                $rootScope.cantidadCarrito = Object.keys(data).length - 1;
                popover.$scope.cargando = false;
            }
        }).
        error(function() {
            console.log('error');
            popover.$scope.cargando = false;
        });
    };
    $scope.enviar = function($event) {
        console.log('enviar');
        $event.preventDefault();
        $scope.enviado = false;
        $scope.noenviado = false;
        var form = $('#form-form').serializeArray();
        $.post('site/contact', form)
            .success(function(data) {
                if (data == '1') {
                    $scope.$apply(function() {
                        $scope.enviado = true;
                    });
                } else {
                    console.log(data);
                    $scope.$apply(function() {
                        $scope.noenviado = true;
                        $scope.errorNoEnviado = data;
                    });
                }
            })
            .error(function(data) {
                console.log('error enviar contacto');
            });
    };
});

controllers.controller('LoginCtrl', function($scope, $window, baseUrl) {
    console.log('LoginCtrl');
    $scope.errorLabel = '';
    $scope.ingresando = false;
    $scope.entrar = function() {
        //console.log('entrar');
        $scope.ingresando = true;
        $scope.errorLabel = '';
        $.post('site/entrar', {
                'LoginForm[username]': $scope.email,
                'LoginForm[password]': $scope.password
            })
            .success(function(response) {
                if (response == '1') {
                    console.log('logeado');
                    location.reload();
                } else {
                    console.log(response);
                    $scope.$apply(function() {
                        $scope.ingresando = false;
                        $scope.errorLabel = 'Datos no coinciden';
                    });
                }
            }).error(function(response) {
                $scope.errorLabel = 'Error';
                $scope.ingresando = false;
            });
    };
    $scope.registrarse = function() {
        var url = baseUrl + 'site/registro';
        $window.location.href = url;
    }
    $scope.keypressed = function(keyEvent) {
        if (keyEvent.which === 13) {
            $scope.entrar();
        }
        $scope.errorLabel = '';
    }
});
<commit_msg>fix menu subcategorias<commit_after>var controllers = angular.module('MosaicoControllers', []);

controllers.controller('HomeCtrl', function($scope, $document, $rootScope, $http) {
    console.log('HomeCtrl');
    $rootScope.inProducts = false;
    watchLoaded($scope, $rootScope);
    $scope.guest=true;
    $http.get('site/guest').success(function (data) {
        if(data=='false'){
            $scope.guest=false;
        }
    }).error(function (data) {
        console.log(data);
    });
    // $document.scrollTopAnimated(0, 1300).then(function() {
    //     addScrollSpy();
    // });
});

/*controllers.controller('SubastasCtrl', function($scope, $document, $rootScope) {
    console.log('SubastasController');
    $rootScope.inProducts = false;
    watchLoaded($scope, $rootScope);
    var section = angular.element(document.getElementById('cont2'));
    $document.scrollToElementAnimated(section, 50, 1500).then(function() {
        addScrollSpy();
    });
    $scope.openLogin = function() {
        popoverLogin.$promise.then(popoverLogin.show);
    }
});

controllers.controller('ContactoCtrl', function($scope, $document, $rootScope, $http) {
    console.log('ContactoController');
    $rootScope.inProducts = false;
    watchLoaded($scope, $rootScope);
    var section = angular.element(document.getElementById('cont3'));
    $document.scrollToElementAnimated(section, 50, 1500).then(function() {
        addScrollSpy();
    });
});*/

controllers.controller('ProductosCtrl', function($scope, $document, $routeParams, $rootScope, $http, $timeout, $modal, $sce) {
    console.log('ProductosController');
    var wwidth = $(window).width();
    var wheight = $(window).height();
    /*if (wwidth < 461) {
        $scope.numPerPage = 2;
    } else if (wwidth < 801) {
        $scope.numPerPage = 4;
    } else if (wwidth < 1101) {
        $scope.numPerPage = 6;
    } else {
        $scope.numPerPage = 8;
        if (wheight > 750) {
            $scope.numPerPage = 12;
        }
    }*/
    $scope.producto = [];
    $scope.currentPage = 0;
    $scope.filteredProducts = [];
    $scope.allProducts = [];
    $rootScope.inProducts = true;
    $scope.loaded = $rootScope.loaded;
    watchLoaded($scope, $rootScope);
    categoriaActual = $routeParams.cat_id;
    $rootScope.categoria = categoriaActual;
    subcategoriaActual = $routeParams.subcat_id;
    loadedProducts();
    conts['cont4'] = 'productos/' + categoriaActual + '/' + subcategoriaActual;
    var section = angular.element(document.getElementById('cont4'));
    /*$document.scrollToElementAnimated(section, 50, 1500).then(function() {
        addScrollSpy();
    });*/
    $scope.range = function(n) {
        return new Array(n);
    };
    /*$scope.range2 = function(start, end) {
        var ret = [];
        if (!end) {
            end = start;
            start = 0;
        }
        for (var i = start; i < end; i++) {
            ret.push(i);
        }
        return ret;
    };*/
    $scope.addToCart = function(id) {
        console.log(id);
        if(galeriaModal){
        	galeriaModal.hide();
        }
        popover.$scope.cargando = true;
        popover.$promise.then(popover.show);
        $http.get('site/add-to-cart?productId=' + id + '&quantity=' + $scope.producto[id]).
        success(function(data) {
            if (data != '') {
                carrito = data;
                popover.$scope.content = htmlCarrito(carrito);
                $rootScope.cantidadCarrito = Object.keys(data).length - 1;
                popover.$scope.cargando = false;
            }
        }).
        error(function() {
            console.log('error add to cart');
            popover.$scope.cargando = false;
        });
    };
    /*$scope.prevPage = function() {
        if ($scope.currentPage > 0) {
            $scope.currentPage--;
        }
    };
    $scope.nextPage = function() {
        if ($scope.currentPage < $scope.filteredProducts.length - 1) {
            $scope.currentPage++;
        }
    };
    $scope.setPage = function() {
        $scope.currentPage = this.n;
    };*/
    var galeriaModal = $modal({
        scope: $scope,
        template: 'partials/galeria.html',
        show: false
    });
    $scope.showModal = function(id) {
    	galeriaModal.$scope.id=id;
    	galeriaModal.$scope.name=categories[categoriaActual][subcategoriaActual][id].name;
    	galeriaModal.$scope.image1=categories[categoriaActual][subcategoriaActual][id].image1;
    	galeriaModal.$scope.image2=categories[categoriaActual][subcategoriaActual][id].image2;
    	galeriaModal.$scope.image3=categories[categoriaActual][subcategoriaActual][id].image3;
    	galeriaModal.$scope.description=$sce.trustAsHtml(categories[categoriaActual][subcategoriaActual][id].description);
    	galeriaModal.$scope.stock=categories[categoriaActual][subcategoriaActual][id].stock;
    	galeriaModal.$scope.price=categories[categoriaActual][subcategoriaActual][id].price;
        galeriaModal.$promise.then(galeriaModal.show);
    };

    function loadedProducts() {
        if (typeof(categories) !== 'undefined') {
            $scope.allProducts = [];
            for (i in categories[categoriaActual][subcategoriaActual]) {
                if (categories[categoriaActual][subcategoriaActual][i].name) {
                    $scope.allProducts.push(categories[categoriaActual][subcategoriaActual][i]);
                }
            }
            /*for (var i = 0; i < $scope.allProducts.length; i++) {
                if (i % $scope.numPerPage === 0) {
                    $scope.filteredProducts[Math.floor(i / $scope.numPerPage)] = [$scope.allProducts[i]];
                } else {
                    $scope.filteredProducts[Math.floor(i / $scope.numPerPage)].push($scope.allProducts[i]);
                }
            }*/
        } else {
            $timeout(loadedProducts, 500);
        }
    }
});

controllers.controller('MainCtrl', function($scope, $document, $location, $rootScope, $http, $window, baseUrl, $popover) {
    console.log('MainCtrl');
    $scope.enviado = false;
    $scope.noenviado = false;
    $scope.cantidadCarrito = 0;
    $rootScope.loaded = false;
    $rootScope.inProducts = false;
    popover = $popover($('#icoCarrito'), {
        title: 'Carrito',
        template: "partials/carrito.html",
        placement: "left",
        animation: "am-flip-x",
        content: "Cargando",
    });
    var divLogin = $('#loginRegistrarse');
    if (divLogin[0]) {
        var popoverLogin = $popover(divLogin, {
            title: 'Iniciar Sesión',
            template: "partials/login.html",
            placement: "left",
            animation: "am-fade-and-slide-left",
        });
        $scope.openLogin = function() {
            popoverLogin.$promise.then(popoverLogin.show);
        };
    }
    popover.$scope.cargando = true;
    $http.get('site/load-cart').
    success(function(data) {
        console.log('cart loaded');
        var html
        if (data) {
            html = htmlCarrito(data);
            $rootScope.cantidadCarrito = Object.keys(data).length - 1;
        } else {
            html = "0 productos";
        }
        popover.$scope.content = html;
        popover.$scope.cargando = false;
    }).
    error(function() {
        console.log('error cargando carrito');
    });
    loadProducts($http, $rootScope);
    watchLoaded($scope, $rootScope);
    $rootScope.$watch('inProducts', function() {
        $scope.inProducts = $rootScope.inProducts;
    });
    $scope.$watch('loaded', function() {
        watchLoadedCategory($scope, $rootScope);
    });
    $rootScope.$watch('categoria', function() {
        watchLoadedCategory($scope, $rootScope);
    });
    $scope.toSection = function(sectionId, categoriaId, subcategoriaId) {
        console.log('toSection');
        var hash = conts[sectionId];
        if (categoriaId && subcategoriaId) {
            hash = 'productos/' + categoriaId + '/' + subcategoriaId;
        }
        // $('.circle').removeAttr('du-scrollspy');
        var section = angular.element(document.getElementById(sectionId));
        if (section[0]) {
            /*$document.scrollToElementAnimated(section, 50, 1500).then(function() {
                addScrollSpy();
                if (hash) {*/
                    $location.hash(hash);
                    // $location.url(hash);
                /*}
            });*/
        } else {
            var url = baseUrl;
            $window.location.href = url + '#/' + hash;
            // $location.url(hash);
        }

    };
    $scope.changeSubcategory = function(subcategoriaId) {
        $location.url('productos/' + $rootScope.categoria + '/' + subcategoriaId);
    };
    popover.$scope.removeFromCart = function(id) {
        console.log('removeFromCart');
        popover.$scope.cargando = true;
        $http.get('site/remove-from-cart?productId=' + id).
        success(function(data) {
            if (data != '') {
                carrito = data;
                popover.$scope.content = htmlCarrito(carrito);
                $rootScope.cantidadCarrito = Object.keys(data).length - 1;
                popover.$scope.cargando = false;
            }
        }).
        error(function() {
            console.log('error');
            popover.$scope.cargando = false;
        });
    };
    $scope.enviar = function($event) {
        console.log('enviar');
        $event.preventDefault();
        $scope.enviado = false;
        $scope.noenviado = false;
        var form = $('#form-form').serializeArray();
        $.post('site/contact', form)
            .success(function(data) {
                if (data == '1') {
                    $scope.$apply(function() {
                        $scope.enviado = true;
                    });
                } else {
                    console.log(data);
                    $scope.$apply(function() {
                        $scope.noenviado = true;
                        $scope.errorNoEnviado = data;
                    });
                }
            })
            .error(function(data) {
                console.log('error enviar contacto');
            });
    };
});

controllers.controller('LoginCtrl', function($scope, $window, baseUrl) {
    console.log('LoginCtrl');
    $scope.errorLabel = '';
    $scope.ingresando = false;
    $scope.entrar = function() {
        //console.log('entrar');
        $scope.ingresando = true;
        $scope.errorLabel = '';
        $.post('site/entrar', {
                'LoginForm[username]': $scope.email,
                'LoginForm[password]': $scope.password
            })
            .success(function(response) {
                if (response == '1') {
                    console.log('logeado');
                    location.reload();
                } else {
                    console.log(response);
                    $scope.$apply(function() {
                        $scope.ingresando = false;
                        $scope.errorLabel = 'Datos no coinciden';
                    });
                }
            }).error(function(response) {
                $scope.errorLabel = 'Error';
                $scope.ingresando = false;
            });
    };
    $scope.registrarse = function() {
        var url = baseUrl + 'site/registro';
        $window.location.href = url;
    }
    $scope.keypressed = function(keyEvent) {
        if (keyEvent.which === 13) {
            $scope.entrar();
        }
        $scope.errorLabel = '';
    }
});
<|endoftext|>


<commit_before>'use strict';

const Promise = require('bluebird');
const AWS = require('aws-sdk');
const expiresAfterADay = 60 * 60 * 12;
const fs = require('fs');
const _ = require('underscore');
const deasync = require('deasync');
const logger = require('./logging').getLogger(__filename);

if ('production' === process.env.NODE_ENV || 'development' === process.env.NODE_ENV) {
    AWS.config.credentials = new AWS.EC2MetadataCredentials({
        httpOptions: {timeout: 10000}
    });
}
AWS.config.region = process.env.AWS_REGION;
const s3 = new AWS.S3();

let copyFile = function (source, destination, bucket) {
    let params = {Bucket: bucket, CopySource: `${bucket}/${source}`, Key: destination};
    return new Promise(function (resolve, reject) {
        s3.copyObject(params, function (err, data) {
            if (err) {
                reject(err);
            } else {
                resolve(data);
            }
        });
    });
};

const getSignedUrl = async function (path) {
    let params = {Bucket: process.env.BUCKET_PRIVATE, Key: path, Expires: expiresAfterADay}, signedUrl = null;
    try {
        signedUrl = await new Promise(function (resolve, reject) {
            s3.getSignedUrl('getObject', params, function (err, data) {
                if (err) {
                    reject(err);
                } else {
                    resolve(data);
                }
            });
        });
    }
    catch (error) {
        logger.error(`Getting Url ${path} from s3 failed`, null, error);
    }
    return signedUrl;
};

const uploadFile = function (fileName, key, bucket) {
    return new Promise(function (resolve, reject) {
        let params = {
            Bucket: bucket, Key: key, Body: fs.createReadStream(fileName)
        };
        s3.upload(params)
            .send(function (err, data) {
                if (err) {
                    reject(err);
                } else {
                    resolve(data);
                }
            });
    });
};

const uploadBuffer = function (buffer, key, bucket) {
    return s3.putObject({
        Bucket: bucket, Key: key, Body: buffer
    }).promise();
};

const getPublicUrl = function (path) {
    return `${process.env.PUBLIC_IMAGE_BASE_URL}/${path}`;
};

const deleteFolder = function (folderName, bucket) {
    return new Promise(function (resolve, reject) {
        let params = {Bucket: bucket, Prefix: folderName};
        s3.listObjects(params, function (err, data) {
            if (err) {
                return reject(err);
            }
            if (data.Contents.length > 0) {
                params = {Bucket: bucket};
                params.Delete = {};
                params.Delete.Objects = [];
                _.each(data.Contents, function (content) {
                    params.Delete.Objects.push({Key: content.Key});
                });
                s3.deleteObjects(params, function (errDelete) {
                    if (errDelete) {
                        return reject(errDelete);
                    }
                    return resolve();
                });
            } else {
                return resolve();
            }
        });
    });
};

const createFolderRegisterUser = async function (userId) {
    const privateBucket = process.env.BUCKET_PRIVATE;
    await Promise.all([copyFile('profileImage/default/profile.jpg', `profileImage/${userId}/profile.jpg`, privateBucket),
        copyFile('profileImage/default/profilePreview.jpg', `profileImage/${userId}/profilePreview.jpg`,
            privateBucket),
        copyFile('profileImage/default/thumbnail.jpg', `profileImage/${userId}/thumbnail.jpg`, privateBucket)]);
};

const getObject = function (path, bucket) {
    let params = {Bucket: bucket, Key: path}, done = false, result = null;
    s3.getObject(params, function (err, data) {
        if (err) {
            logger.error(`Getting Object ${path} from s3 failed`, null, err);
        }
        result = data;
        done = true;
    });
    deasync.loopWhile(function () {
        return !done;
    });
    return result;
};

module.exports = {
    getSignedUrl,
    getPublicUrl,
    getUrl: function (arg) {
    },
    uploadFile,
    uploadBuffer,
    deleteFolder,
    copyFile,
    createFolderRegisterUser,
    getObject
};
<commit_msg>Removed dasync and using only promises.<commit_after>'use strict';

const Promise = require('bluebird');
const AWS = require('aws-sdk');
const expiresAfterADay = 60 * 60 * 12;
const fs = require('fs');
const _ = require('underscore');
const logger = require('./logging').getLogger(__filename);

if ('production' === process.env.NODE_ENV || 'development' === process.env.NODE_ENV) {
    AWS.config.credentials = new AWS.EC2MetadataCredentials({
        httpOptions: {timeout: 10000}
    });
}
AWS.config.region = process.env.AWS_REGION;
const s3 = new AWS.S3();

let copyFile = function (source, destination, bucket) {
    let params = {Bucket: bucket, CopySource: `${bucket}/${source}`, Key: destination};
    return new Promise(function (resolve, reject) {
        s3.copyObject(params, function (err, data) {
            if (err) {
                reject(err);
            } else {
                resolve(data);
            }
        });
    });
};

const getSignedUrl = async function (path) {
    let params = {Bucket: process.env.BUCKET_PRIVATE, Key: path, Expires: expiresAfterADay}, signedUrl = null;
    try {
        signedUrl = await new Promise(function (resolve, reject) {
            s3.getSignedUrl('getObject', params, function (err, data) {
                if (err) {
                    reject(err);
                } else {
                    resolve(data);
                }
            });
        });
    }
    catch (error) {
        logger.error(`Getting Url ${path} from s3 failed`, null, error);
    }
    return signedUrl;
};

const uploadFile = function (fileName, key, bucket) {
    return new Promise(function (resolve, reject) {
        let params = {
            Bucket: bucket, Key: key, Body: fs.createReadStream(fileName)
        };
        s3.upload(params)
            .send(function (err, data) {
                if (err) {
                    reject(err);
                } else {
                    resolve(data);
                }
            });
    });
};

const uploadBuffer = function (buffer, key, bucket) {
    return s3.putObject({
        Bucket: bucket, Key: key, Body: buffer
    }).promise();
};

const getPublicUrl = function (path) {
    return `${process.env.PUBLIC_IMAGE_BASE_URL}/${path}`;
};

const deleteFolder = function (folderName, bucket) {
    return new Promise(function (resolve, reject) {
        let params = {Bucket: bucket, Prefix: folderName};
        s3.listObjects(params, function (err, data) {
            if (err) {
                return reject(err);
            }
            if (data.Contents.length > 0) {
                params = {Bucket: bucket};
                params.Delete = {};
                params.Delete.Objects = [];
                _.each(data.Contents, function (content) {
                    params.Delete.Objects.push({Key: content.Key});
                });
                s3.deleteObjects(params, function (errDelete) {
                    if (errDelete) {
                        return reject(errDelete);
                    }
                    return resolve();
                });
            } else {
                return resolve();
            }
        });
    });
};

const createFolderRegisterUser = async function (userId) {
    const privateBucket = process.env.BUCKET_PRIVATE;
    await Promise.all([copyFile('profileImage/default/profile.jpg', `profileImage/${userId}/profile.jpg`, privateBucket),
        copyFile('profileImage/default/profilePreview.jpg', `profileImage/${userId}/profilePreview.jpg`,
            privateBucket),
        copyFile('profileImage/default/thumbnail.jpg', `profileImage/${userId}/thumbnail.jpg`, privateBucket)]);
};

const getObject = function (path, bucket) {
    let params = {Bucket: bucket, Key: path};
    return s3.getObject(params).promise();
};

module.exports = {
    getSignedUrl,
    getPublicUrl,
    getUrl: function (arg) {
    },
    uploadFile,
    uploadBuffer,
    deleteFolder,
    copyFile,
    createFolderRegisterUser,
    getObject
};
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import OrganisationListRow from './OrganisationListRow'

export default class OrganisationList extends Component {

    render() {
    	let orgs = this.props.organisations;
    	let numberOfOrgs = orgs.length;
    	let rows = orgs.map(
    		(org, index) => <OrganisationListRow name={org.name} id={org.ud} key={index} />
    	);

		return(

						Name
						Id

					{rows}

        );
    }
}
<commit_msg>Corrected typo. id mispelled as ud.<commit_after>import React, { Component } from 'react'
import OrganisationListRow from './OrganisationListRow'

export default class OrganisationList extends Component {

    render() {
    	let orgs = this.props.organisations;
    	let numberOfOrgs = orgs.length;
    	let rows = orgs.map(
    		(org, index) => <OrganisationListRow name={org.name} id={org.id} key={index} />
    	);

		return(

						Name
						Id

					{rows}

        );
    }
}
<|endoftext|>


<commit_before>(function (Prism) {

	Prism.languages.typescript = Prism.languages.extend('javascript', {
		'class-name': {
			pattern: /(\b(?:class|extends|implements|instanceof|interface|new|type)\s+)(?!keyof\b)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?:\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>)?/,
			lookbehind: true,
			greedy: true,
			inside: null // see below
		},
		'builtin': /\b(?:string|Function|any|number|boolean|Array|symbol|console|Promise|unknown|never)\b/,
	});

	// The keywords TypeScript adds to JavaScript
	Prism.languages.typescript.keyword.push(
		/\b(?:abstract|as|declare|implements|is|keyof|readonly|require)\b/,
		// keywords that have to be followed by an identifier
		/\b(?:asserts|infer|interface|module|namespace|type)(?!\s*[^\s_${}*a-zA-Z\xA0-\uFFFF])/
	)

	// doesn't work with TS because TS is too complex
	delete Prism.languages.typescript['parameter'];

	// a version of typescript specifically for highlighting types
	var typeInside = Prism.languages.extend('typescript', {});
	delete typeInside['class-name'];

	Prism.languages.typescript['class-name'].inside = typeInside;

	Prism.languages.insertBefore('typescript', 'function', {
		'decorator': {
			pattern: /@[$\w\xA0-\uFFFF]+/,
			inside: {
				'at': {
					pattern: /^@/,
					alias: 'operator'
				},
				'function': /^[\s\S]+/
			}
		},
		'generic-function': {
			// e.g. foo<T extends "bar" | "baz">( ...
			pattern: /#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>(?=\s*\()/,
			greedy: true,
			inside: {
				'function': /^#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*/,
				'generic': {
					pattern: /<[\s\S]+/, // everything after the first <
					alias: 'class-name',
					inside: typeInside
				}
			}
		}
	});

	Prism.languages.ts = Prism.languages.typescript;

}(Prism));
<commit_msg>TypeScript: Added missing semicolon to fix lint<commit_after>(function (Prism) {

	Prism.languages.typescript = Prism.languages.extend('javascript', {
		'class-name': {
			pattern: /(\b(?:class|extends|implements|instanceof|interface|new|type)\s+)(?!keyof\b)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?:\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>)?/,
			lookbehind: true,
			greedy: true,
			inside: null // see below
		},
		'builtin': /\b(?:string|Function|any|number|boolean|Array|symbol|console|Promise|unknown|never)\b/,
	});

	// The keywords TypeScript adds to JavaScript
	Prism.languages.typescript.keyword.push(
		/\b(?:abstract|as|declare|implements|is|keyof|readonly|require)\b/,
		// keywords that have to be followed by an identifier
		/\b(?:asserts|infer|interface|module|namespace|type)(?!\s*[^\s_${}*a-zA-Z\xA0-\uFFFF])/
	);

	// doesn't work with TS because TS is too complex
	delete Prism.languages.typescript['parameter'];

	// a version of typescript specifically for highlighting types
	var typeInside = Prism.languages.extend('typescript', {});
	delete typeInside['class-name'];

	Prism.languages.typescript['class-name'].inside = typeInside;

	Prism.languages.insertBefore('typescript', 'function', {
		'decorator': {
			pattern: /@[$\w\xA0-\uFFFF]+/,
			inside: {
				'at': {
					pattern: /^@/,
					alias: 'operator'
				},
				'function': /^[\s\S]+/
			}
		},
		'generic-function': {
			// e.g. foo<T extends "bar" | "baz">( ...
			pattern: /#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>(?=\s*\()/,
			greedy: true,
			inside: {
				'function': /^#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*/,
				'generic': {
					pattern: /<[\s\S]+/, // everything after the first <
					alias: 'class-name',
					inside: typeInside
				}
			}
		}
	});

	Prism.languages.ts = Prism.languages.typescript;

}(Prism));
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import RadioButton from './index';
import isComponentOfType from '../utils/is-component-of-type';

class RadioGroup extends Component {
  static propTypes = {
    children: PropTypes.node,
    className: PropTypes.string,
    disabled: PropTypes.bool,
    onChange: PropTypes.func,
    value: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.bool,
    ]),
  };

  static defaultProps = {
    className: '',
    disabled: false,
  };

  constructor () {
    super(...arguments);

    this.handleChange = this.handleChange.bind(this);
  }

  handleChange (value, event) {
    if (this.props.onChange) {
      this.props.onChange(value, event);
    }
  };

  render () {
    return (

        {
          React.Children.map(this.props.children, child => (
            !isComponentOfType(RadioButton, child)
              ? child
              : React.cloneElement(child, {
                checked: child.props.value === this.props.value,
                disabled: this.props.disabled || child.props.disabled,
                onChange: event => this.handleChange(child.props.value, event),
              })
            )
          )
        }

    );
  }
}

export default RadioGroup;
export { RadioGroup };
<commit_msg>Converted RadioGroup to PureComponent<commit_after>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import RadioButton from './index';
import isComponentOfType from '../utils/is-component-of-type';

class RadioGroup extends PureComponent {
  static propTypes = {
    children: PropTypes.node,
    className: PropTypes.string,
    disabled: PropTypes.bool,
    onChange: PropTypes.func,
    value: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.bool,
    ]),
  };

  static defaultProps = {
    className: '',
    disabled: false,
  };

  constructor () {
    super(...arguments);

    this.handleChange = this.handleChange.bind(this);
  }

  handleChange (value, event) {
    if (this.props.onChange) {
      this.props.onChange(value, event);
    }
  };

  render () {
    return (

        {
          React.Children.map(this.props.children, child => (
            !isComponentOfType(RadioButton, child)
              ? child
              : React.cloneElement(child, {
                checked: child.props.value === this.props.value,
                disabled: this.props.disabled || child.props.disabled,
                onChange: event => this.handleChange(child.props.value, event),
              })
            )
          )
        }

    );
  }
}

export default RadioGroup;
export { RadioGroup };
<|endoftext|>


<commit_before>import Section from '../section'

const Plugin = ({ title, description, color, href }) => (

    {title}

{description}

)

const Buttons = () => (

      Browse Plugins

      Download App

)
export default () => (

The power of open-source

            The ease of use and speed you’ve been looking for – the
            functionality and extensibility you didn’t know you needed.{' '}

            <Plugin
              title="giphy"
              color="#ffd500"
              description="Share GIFs on Giphy"
              href="https://github.com/wulkano/kap-giphy"
            />
            <Plugin
              title="now"
              color="#FFF"
              description="Share on ZEIT now   "
              href="https://github.com/lucaperret/kap-now"
            />
            <Plugin
              title="draggable"
              color="#00ffbe"
              description="Share with drag and drop"
              href="https://github.com/albinekb/kap-draggable"
            />

          <Buttons />

        <Buttons />

)
<commit_msg>🎉 RESPONSIVEFFFFS<commit_after>import Section from '../section'

const Plugin = ({ title, description, color, href }) => (

    {title}

{description}

)

const Buttons = () => (

      Browse Plugins

      Download App

)
export default () => (

The power of open-source

            The ease of use and speed you’ve been looking for – the
            functionality and extensibility you didn’t know you needed.{' '}

            <Plugin
              title="giphy"
              color="#ffd500"
              description="Share GIFs on Giphy"
              href="https://github.com/wulkano/kap-giphy"
            />
            <Plugin
              title="now"
              color="#FFF"
              description="Share on ZEIT now   "
              href="https://github.com/lucaperret/kap-now"
            />
            <Plugin
              title="draggable"
              color="#00ffbe"
              description="Share with drag and drop"
              href="https://github.com/albinekb/kap-draggable"
            />

          <Buttons />

        <Buttons />

)
<|endoftext|>


<commit_before>"use strict";

var bdyNamesUrl = "../get-bdy-names";
var metadataUrl = "../get-metadata";
var dataUrl = "../get-data";

var map;
var info;
var themer;
var geojsonLayer;

var numClasses = 7 // number of classes (i.e colours) in map theme
var minZoom = 4;
var maxZoom = 15;
var zoomLevel = 10;

var census;
var statsArray;
var currentStat;
var currentStatName;
var currentStatType;

var colours = ['#f6d2a9','#f5b78e','#f19c7c','#ea8171','#dd686c','#ca5268','#b13f64']

// get querystring values

//Code from http://forum.jquery.com/topic/getting-value-from-a-querystring

// get querystring as an array split on "&"
var querystring = location.search.replace('?', '').split('&');

// declare object
var queryObj = {};

// loop through each name-value pair and populate object
for (var i = 0; i < querystring.length; i++) {
    // get name and value
    var name = querystring[i].split('=')[0];
    var value = querystring[i].split('=')[1];
    // populate object
    queryObj[name] = value;
}

// get/set values from querystring
if (queryObj["census"] === undefined) {
    census = "2016";
} else {
    census = queryObj["stats"];
    // TODO: check census value is valid
}
if (queryObj["stats"] === undefined) {
    statsArray = ["b3"]; // total_persons
} else {
    statsArray = queryObj["stats"].lower().split(",");
}

function init() {

    // get stats metadata, including map theme classes
    getMetadata()

    // get list of boundaries and the zoom levels they display at
    var url = "${bdyNamesUrl}?min=${minZoom}&max=${maxZoom};

    console.log(url)

    //Initialize the map on the "map" div
    map = new L.Map('map', { preferCanvas: true });

    // acknowledge the data provider
    map.attributionControl.addAttribution('Census data © ABS');

    // load CARTO basemap tiles
    var tiles = L.tileLayer('http://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png', {
        attribution : '© OpenStreetMap © CartoDB',
        subdomains : 'abcd',
        minZoom : minZoom,
        maxZoom : maxZoom
    }).addTo(map);

    // set the view to a given center and zoom
    map.setView(new L.LatLng(-33.85, 151.15), zoomLevel);

    // get bookmarks
    var storage = {
        getAllItems : function (callback) {
            $.getJSON('bookmarks.json',
                function (json) {
                    callback(json);
            });
        }
    };

    // add bookmark control to map
    var bmControl = new L.Control.Bookmarks({
        position : 'topleft',
        localStorage : false,
        storage : storage
    }).addTo(map);

    // add control that shows info on mouseover
    info = L.control();
    info.onAdd = function (map) {
        this._div = L.DomUtil.create('div', 'info');
        this.update();
        return this._div;
    };
    info.update = function (props) {
//        var typePrefix;
//        var typeSuffix;
//      this._div.innerHTML = (props ? ''typePrefix + props[currentStat].toLocaleString(['en-AU']) + typeSuffix' ' + currentStatName : 'pick a boundary');
        this._div.innerHTML = "Test pattern";
    };
    info.addTo(map);

    // add radio buttons to choose stat to theme the map
    themer = L.control({
        position : 'bottomright'
    });
    themer.onAdd = function (map) {
        var div = L.DomUtil.create('div', 'info themer');
        div.innerHTML = "
Layers
go here
"
        return div;
    };
    themer.addTo(map);

    // event to trigger the map theme to change
    $("input:radio[name=radio]").click(function () {
        valueType = $(this).val();
        // reload the data - NEEDS TO BE REPLACED WITH A MORE EFFICIENT WAY
        getData();
    });

    // get a new set of data when map panned or zoomed
    // TODO: Handle map movement due to popup
    map.on('moveend', function (e) {
        // map.closePopup();
        getData();
    });

    // map.on('zoomend', function (e) {
    //     map.closePopup();
    //     //getData();
    // });

    // get the first lot of data
    getMetadata();
}

function getMetadata(){

    console.time("got metadata");

    // get zoom level
    zoomLevel = map.getZoom();

    // build URL with querystring
    var ua = [];
    ua.push(dataUrl);
//    ua.push("?z=");
//    ua.push((zoomLevel).toString());
    ua.push("?n=");
    ua.push((numClasses).toString());
//    ua.push("&census=");
//    ua.push(census);
    ua.push("&stats=");
    ua.push(statsArray.join());

    var reqStr = ua.join('');

    console.log(reqStr);

    //Fire off AJAX request
    $.getJSON(reqStr, gotMetadata);
}

function gotMetadata(json) {

    console.timeEnd("got metadata");

    var metadata = JSON.parse(json);

//        div.innerHTML = '
Profitability
Metric
' +
//            '
<input id="radio1" type="radio" name="radio" value="count">Policies
' +
//            '
<input id="radio2" type="radio" name="radio" value="ratestrength" checked="checked">Rate strength
' +
//            '
<input id="radio3" type="radio" name="radio" value="dollardiff">$ Difference
'

//    // now get the data
//    getData()
}

function getData() {

    console.time("got boundaries");

    // get zoom level
    zoomLevel = map.getZoom();
    //    console.log("Zoom level = " + zoomLevel.toString());

    //restrict to the zoom levels that have data
    if (zoomLevel < minZoom) {
        zoomLevel = minZoom;
    }
    if (zoomLevel > maxZoom) {
        zoomLevel = maxZoom;
    }

    // get map extents
    var bb = map.getBounds();
    var sw = bb.getSouthWest();
    var ne = bb.getNorthEast();

    // build URL with querystring
    var ua = [];
    ua.push(dataUrl);
    ua.push("?ml=");
    ua.push(sw.lng.toString());
    ua.push("&mb=");
    ua.push(sw.lat.toString());
    ua.push("&mr=");
    ua.push(ne.lng.toString());
    ua.push("&mt=");
    ua.push(ne.lat.toString());
    ua.push("&z=");
    ua.push((zoomLevel).toString());
    //    ua.push("&t=");
    //    ua.push(valueType);

    var reqStr = ua.join('');

    //Fire off AJAX request
    $.getJSON(reqStr, gotData);
}

function gotData(json) {
    console.timeEnd("got boundaries");
    console.time("parsed GeoJSON");

    if (json !== null) {
        if(geojsonLayer !== undefined) {
            geojsonLayer.clearLayers();
        }

        geojsonLayer = L.geoJson(json, {
            style : style,
            onEachFeature : onEachFeature
        }).addTo(map);
    } else {
        alert("No data returned!")
    }

    console.timeEnd("parsed GeoJSON");
}

function style(feature) {

    var renderVal;
    var colours;

    switch (valueType) {
    case "count":
        colours = countColours;
        renderVal = parseInt(feature.properties.count);
        break;
    case "dollardiff":
        colours = rateStrengthColours;
        renderVal = parseInt(feature.properties.dollardiff);
        break;
    case "ratestrength":
        colours = rateStrengthColours;
        renderVal = parseFloat(feature.properties.ratestrength);
        break;
    default:
        colours = rateStrengthColours;
        renderVal = parseFloat(feature.properties.ratestrength);
    }

    return {
        weight : 0,
        opacity : 0.0,
        color : '#666',
        fillOpacity : getOpacity(parseInt(feature.properties.count)),
        fillColor : getColor(renderVal, colours)
    };

    // fillOpacity : getOpacity(renderVal),

}

// get color depending on ratio of count versus max value
function getColor(d, colours) {

    var zoomDiff = 13 - zoomLevel;

    switch (valueType) {
        case "count":
            if (zoomDiff > 0) {
                d = d / Math.pow(4, zoomDiff);
            }

            return d > 500 ? colours[6] :
                d > 200 ? colours[5] :
                    d > 100 ? colours[4] :
                        d > 50 ? colours[3] :
                            d > 25 ? colours[2] :
                                d > 0 ? colours[1] :
                                    colours[0];
            break;

        case "dollardiff":
            // if (zoomDiff > 0) {
            //     d = d / Math.pow(4, zoomDiff);
            // }

            // var colour;
            //
            // if (d >= -25000 && d < -16000) {
            //     colour = colours[6]
            // } else if (d >= -16000 && d < -8000) {
            //     colour = colours[5]
            // } else if (d >= -8000 && d < 0) {
            //     colour = colours[4]
            // } else if (d = 0) {
            //     colour = colours[3]
            // } else if (d > 0 && d < 15000) {
            //     colour = colours[2]
            // } else if (d >= 12500 && d < 30000) {
            //     colour = colours[1]
            // } else {
            //     colour = colours[0]
            // }
            //
            // return colour;

            // 41226, "min": -24078
            //

            var values = dollarDiffMinMax[zoomLevel.toString()];

            return d > values[0] ? colours[6] :
                d > values[1] ? colours[5] :
                    d > values[2] ? colours[4] :
                        d > values[3] ? colours[3] :
                            d > values[4] ? colours[2] :
                                d > values[5] ? colours[1] :
                                    colours[0];
            break;

    case "ratestrength":
        return d > 1.7 ? colours[0] :
            d > 1.5 ? colours[1] :
            d > 1.3 ? colours[2] :
            d > 1.1 ? colours[3] :
            d > 0.9 ? colours[4] :
            d > 0.7 ? colours[5] :
                      colours[6];
        break;
    default:
        return d > 1.7 ? colours[0] :
            d > 1.5 ? colours[1] :
                d > 1.3 ? colours[2] :
                    d > 1.1 ? colours[3] :
                        d > 0.9 ? colours[4] :
                            d > 0.7 ? colours[5] :
                                colours[6];
    }
}

// get color depending on ratio of count versus max value
function getOpacity(d) {

    switch (valueType) {
    case "count":
        return d > 500 ? 0.7 :
        d > 250 ? 0.6 :
        d > 100 ? 0.5 :
        d > 50 ? 0.4 :
        d > 25 ? 0.3 :
        d > 0 ? 0.2 :
                0.1;
        break;
    // case "difference":
    //     zoomDiff = 11 - zoomLevel;
    //     if (zoomDiff > 0) {
     //        d = d / Math.pow(4, zoomDiff)
    //     }
    //
    //     return d > 500 ? 0.7 :
    //     d > 200 ? 0.6 :
    //     d > 100 ? 0.5 :
    //     d > 50 ? 0.4 :
    //     d > 25 ? 0.3 :
    //     d > 0 ? 0.2 :
    //             0.1;
    //     break;
    default:
        return d > 500 ? 0.7 :
        d > 200 ? 0.6 :
        d > 100 ? 0.5 :
        d > 50 ? 0.4 :
        d > 25 ? 0.3 :
        d > 0 ? 0.2 :
                0.1;
    }
}

function onEachFeature(feature, layer) {
    layer.on({
        mouseover : highlightFeature,
        mouseout : resetHighlight
    });
}

function highlightFeature(e) {
    var layer = e.target;

    // console.log(layer);

    layer.setStyle({
        weight : 2,
        opacity : 0.9,
        fillOpacity : 0.7
    });

    if (!L.Browser.ie && !L.Browser.opera) {
        layer.bringToFront();
    }

    info.update(layer.feature.properties);
}

function resetHighlight(e) {
    geojsonLayer.resetStyle(e.target);
    info.update();
}

// function zoomToFeature(e) {
//     map.fitBounds(e.target.getBounds());
// }<commit_msg>working on loadmap JS<commit_after>"use strict";

var bdyNamesUrl = "../get-bdy-names";
var metadataUrl = "../get-metadata";
var dataUrl = "../get-data";

var boundaryZooms;
var statsMetadata;

var map;
var info;
var themer;
var geojsonLayer;

var numClasses = 7 // number of classes (i.e colours) in map theme
var minZoom = 4;
var maxZoom = 15;
var currentZoomLevel = 10;

var census;
var statsArray;
var currentStat;
//var currentStatName;
//var currentStatType;
var currentStats;
var currentBoundary;

var colours = ['#f6d2a9','#f5b78e','#f19c7c','#ea8171','#dd686c','#ca5268','#b13f64']

// get querystring values
// code from http://forum.jquery.com/topic/getting-value-from-a-querystring
// get querystring as an array split on "&"
var querystring = location.search.replace('?', '').split('&');

// declare object
var queryObj = {};

// loop through each name-value pair and populate object
for (var i = 0; i < querystring.length; i++) {
    // get name and value
    var name = querystring[i].split('=')[0];
    var value = querystring[i].split('=')[1];
    // populate object
    queryObj[name] = value;
}

// get/set values from querystring
if (queryObj["census"] === undefined) {
    census = "2016";
} else {
    census = queryObj["stats"];
    // TODO: check census value is valid
}
if (queryObj["stats"] === undefined) {
    statsArray = ["b3"]; // total_persons
} else {
    statsArray = queryObj["stats"].lower().split(",");
}

function init() {
    //Initialize the map on the "map" div
    map = new L.Map('map', { preferCanvas: true });

    // acknowledge the data provider
    map.attributionControl.addAttribution('Census data © ABS');

    // load CARTO basemap tiles
    var tiles = L.tileLayer('http://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png', {
        attribution : '© OpenStreetMap © CartoDB',
        subdomains : 'abcd',
        minZoom : minZoom,
        maxZoom : maxZoom
    }).addTo(map);

    // set the view to a given center and zoom
    map.setView(new L.LatLng(-33.85, 151.15), currentZoomLevel);

    // get bookmarks
    var storage = {
        getAllItems : function (callback) {
            $.getJSON('bookmarks.json',
                function (json) {
                    callback(json);
            });
        }
    };

    // add bookmark control to map
    var bmControl = new L.Control.Bookmarks({
        position : 'topleft',
        localStorage : false,
        storage : storage
    }).addTo(map);

    // add control that shows info on mouseover
    info = L.control();
    info.onAdd = function (map) {
        this._div = L.DomUtil.create('div', 'info');
        this.update();
        return this._div;
    };
    info.update = function (props) {
//        var typePrefix;
//        var typeSuffix;
//      this._div.innerHTML = (props ? ''typePrefix + props[currentStat].toLocaleString(['en-AU']) + typeSuffix' ' + currentStatName : 'pick a boundary');
        this._div.innerHTML = "Test pattern";
    };
    info.addTo(map);

    // add radio buttons to choose stat to theme the map
    themer = L.control({
        position : 'bottomright'
    });
    themer.onAdd = function (map) {
        var div = L.DomUtil.create('div', 'info themer');
        div.innerHTML = "
Layers
go here
"
        return div;
    };
    themer.addTo(map);

    // event to trigger the map theme to change
    $("input:radio[name=radio]").click(function () {
        valueType = $(this).val();
        // reload the data - NEEDS TO BE REPLACED WITH A MORE EFFICIENT WAY
        getData();
    });

    // get a new set of data when map panned or zoomed
    // TODO: Handle map movement due to popup
    map.on('moveend', function (e) {
        // map.closePopup();

        // get zoom level
        currentZoomLevel = map.getZoom();

        getData();
    });

    // map.on('zoomend', function (e) {
    //     map.closePopup();
    //     //getData();
    // });

    // get list of boundaries and the zoom levels they display at
    // and get stats metadata, including map theme classes
    $.when(
        $.getJSON(bdyNamesUrl + "?min=" +  + minZoom.toString() + "&max=" + maxZoom.toString()),
        $.getJSON(metadataUrl + "?n=" +  + numClasses.toString() + "&stats=" + statsArray.join())
    ).done(function(bdysResponse, metadataResponse) {
        boundaryZooms = bdysResponse[0];
        currentBoundary = boundaryZooms[currentZoomLevel.toString()];
//        console.log(currentBoundary);

        statsMetadata = metadataResponse[0];
        var bdyStats = statsMetadata.boundaries

        // loop through each boundary to get the current one
        for (var i = 0; i < bdyStats.length; i++) {
            if (bdyStats[i].boundary === currentBoundary) {
                currentStats = bdyStats[i].stats;
                currentStat = currentStats[0]; // pick the first stat in the URL to map first
            }
        }
//        console.log(currentStats);

        // get the first lot of data
        getData();
    });

//function gotMetadata(json) {
//
//    console.timeEnd("got metadata");
//
//    console.log(json);
//
//
////        div.innerHTML = '
Profitability
Metric
' +
////            '
<input id="radio1" type="radio" name="radio" value="count">Policies
' +
////            '
<input id="radio2" type="radio" name="radio" value="ratestrength" checked="checked">Rate strength
' +
////            '
<input id="radio3" type="radio" name="radio" value="dollardiff">$ Difference
'
//
////    // now get the data
////    getData()
//}

function getData() {

    console.time("got boundaries");

    //restrict to the zoom levels that have data
    if (currentZoomLevel < minZoom) {
        currentZoomLevel = minZoom;
    }
    if (currentZoomLevel > maxZoom) {
        currentZoomLevel = maxZoom;
    }

    // get map extents
    var bb = map.getBounds();
    var sw = bb.getSouthWest();
    var ne = bb.getNorthEast();

    // build URL
    var ua = [];
    ua.push(dataUrl);
    ua.push("?ml=");
    ua.push(sw.lng.toString());
    ua.push("&mb=");
    ua.push(sw.lat.toString());
    ua.push("&mr=");
    ua.push(ne.lng.toString());
    ua.push("&mt=");
    ua.push(ne.lat.toString());
    ua.push("&s=");
    ua.push(currentStat.id);
    ua.push("&t=");
    ua.push(currentStat.table);
    ua.push("&z=");
    ua.push((currentZoomLevel).toString());

    var requestString = ua.join('');

    console.log(requestString);

    //Fire off AJAX request
    $.getJSON(requestString, gotData);
}

function gotData(json) {
    console.timeEnd("got boundaries");
    console.time("parsed GeoJSON");

    if (json !== null) {
        if(geojsonLayer !== undefined) {
            geojsonLayer.clearLayers();
        }

        geojsonLayer = L.geoJson(json, {
            style : style,
            onEachFeature : onEachFeature
        }).addTo(map);
    } else {
        alert("No data returned!")
    }

    console.timeEnd("parsed GeoJSON");
}

function style(feature) {

    var renderVal;
    var colours;

    switch (valueType) {
    case "count":
        colours = countColours;
        renderVal = parseInt(feature.properties.count);
        break;
    case "dollardiff":
        colours = rateStrengthColours;
        renderVal = parseInt(feature.properties.dollardiff);
        break;
    case "ratestrength":
        colours = rateStrengthColours;
        renderVal = parseFloat(feature.properties.ratestrength);
        break;
    default:
        colours = rateStrengthColours;
        renderVal = parseFloat(feature.properties.ratestrength);
    }

    return {
        weight : 0,
        opacity : 0.0,
        color : '#666',
        fillOpacity : getOpacity(parseInt(feature.properties.count)),
        fillColor : getColor(renderVal, colours)
    };

    // fillOpacity : getOpacity(renderVal),

}

// get color depending on ratio of count versus max value
function getColor(d, colours) {

    var zoomDiff = 13 - currentZoomLevel;

    switch (valueType) {
        case "count":
            if (zoomDiff > 0) {
                d = d / Math.pow(4, zoomDiff);
            }

            return d > 500 ? colours[6] :
                d > 200 ? colours[5] :
                    d > 100 ? colours[4] :
                        d > 50 ? colours[3] :
                            d > 25 ? colours[2] :
                                d > 0 ? colours[1] :
                                    colours[0];
            break;

        case "dollardiff":
            // if (zoomDiff > 0) {
            //     d = d / Math.pow(4, zoomDiff);
            // }

            // var colour;
            //
            // if (d >= -25000 && d < -16000) {
            //     colour = colours[6]
            // } else if (d >= -16000 && d < -8000) {
            //     colour = colours[5]
            // } else if (d >= -8000 && d < 0) {
            //     colour = colours[4]
            // } else if (d = 0) {
            //     colour = colours[3]
            // } else if (d > 0 && d < 15000) {
            //     colour = colours[2]
            // } else if (d >= 12500 && d < 30000) {
            //     colour = colours[1]
            // } else {
            //     colour = colours[0]
            // }
            //
            // return colour;

            // 41226, "min": -24078
            //

            var values = dollarDiffMinMax[currentZoomLevel.toString()];

            return d > values[0] ? colours[6] :
                d > values[1] ? colours[5] :
                    d > values[2] ? colours[4] :
                        d > values[3] ? colours[3] :
                            d > values[4] ? colours[2] :
                                d > values[5] ? colours[1] :
                                    colours[0];
            break;

    case "ratestrength":
        return d > 1.7 ? colours[0] :
            d > 1.5 ? colours[1] :
            d > 1.3 ? colours[2] :
            d > 1.1 ? colours[3] :
            d > 0.9 ? colours[4] :
            d > 0.7 ? colours[5] :
                      colours[6];
        break;
    default:
        return d > 1.7 ? colours[0] :
            d > 1.5 ? colours[1] :
                d > 1.3 ? colours[2] :
                    d > 1.1 ? colours[3] :
                        d > 0.9 ? colours[4] :
                            d > 0.7 ? colours[5] :
                                colours[6];
    }
}

// get color depending on ratio of count versus max value
function getOpacity(d) {

    switch (valueType) {
    case "count":
        return d > 500 ? 0.7 :
        d > 250 ? 0.6 :
        d > 100 ? 0.5 :
        d > 50 ? 0.4 :
        d > 25 ? 0.3 :
        d > 0 ? 0.2 :
                0.1;
        break;
    // case "difference":
    //     zoomDiff = 11 - currentZoomLevel;
    //     if (zoomDiff > 0) {
     //        d = d / Math.pow(4, zoomDiff)
    //     }
    //
    //     return d > 500 ? 0.7 :
    //     d > 200 ? 0.6 :
    //     d > 100 ? 0.5 :
    //     d > 50 ? 0.4 :
    //     d > 25 ? 0.3 :
    //     d > 0 ? 0.2 :
    //             0.1;
    //     break;
    default:
        return d > 500 ? 0.7 :
        d > 200 ? 0.6 :
        d > 100 ? 0.5 :
        d > 50 ? 0.4 :
        d > 25 ? 0.3 :
        d > 0 ? 0.2 :
                0.1;
    }
}

function onEachFeature(feature, layer) {
    layer.on({
        mouseover : highlightFeature,
        mouseout : resetHighlight
    });
}

function highlightFeature(e) {
    var layer = e.target;

    // console.log(layer);

    layer.setStyle({
        weight : 2,
        opacity : 0.9,
        fillOpacity : 0.7
    });

    if (!L.Browser.ie && !L.Browser.opera) {
        layer.bringToFront();
    }

    info.update(layer.feature.properties);
}

function resetHighlight(e) {
    geojsonLayer.resetStyle(e.target);
    info.update();
}

// function zoomToFeature(e) {
//     map.fitBounds(e.target.getBounds());
// }<|endoftext|>


<commit_before>$(window).load(function() {

  var threeColumnContentCalled = false;
  var windowWidthMark = 1180;

  var preElements = $('.content').find('pre');

  // fix css for three column layout
  threeColumnContent();

  $(window).resize(function() {
    // fix css for three column layout
    if (!threeColumnContentCalled) {
	    threeColumnContent();
    }
    hideScrollbarMoz();
  });

  function hideScrollbarMoz() {
  	var cW, sW;
  	$.each(preElements, function(i, pre) {
      cW = pre.clientWidth,
  	  sW = pre.scrollWidth;
  	  $(pre).find('.scrolls-x').removeClass('scrolls-x');
  	  if (cW != sW) {
  	  	$(pre).addClass('scrolls-x');
  	  } else {
  	  	//if ($(pre).hasClass('scrolls-x').removeClass('scroll-x'));
  	  }

  	});
  };

  hideScrollbarMoz();

  // color combos
  var GRAY = '#4a4a4a',
      LIGHT_GRAY = '#E9E8E3',
      DARK_GRAY = '#3A3A3A',
      DARK_BLUE =	'#363B48',
      FUXSIA = '#DF3F54',
      LIGHT_FUXSIA = '#F17C71',
      ZENBURN_BG = '#3F3F3F',
      LIGHT_WHITE = '#F3F6FB',
      LIGHTER_WHITE = '#F8F8F4',
      BLACK = '#000',
      WHITE = '#FFF';

  var combo1 = [LIGHT_GRAY, ZENBURN_BG, GRAY, DARK_GRAY, FUXSIA, LIGHT_WHITE],
      combo2 = [DARK_GRAY, BLACK, LIGHT_GRAY, LIGHT_WHITE, LIGHT_FUXSIA, BLACK],
      combo3 = [DARK_BLUE, BLACK, LIGHT_GRAY, LIGHT_WHITE, LIGHT_FUXSIA, BLACK],
      combo4 = [FUXSIA, ZENBURN_BG, LIGHT_GRAY, LIGHT_WHITE, LIGHT_FUXSIA, ZENBURN_BG],
      combo5 = [LIGHTER_WHITE, ZENBURN_BG, GRAY, DARK_GRAY, FUXSIA, WHITE];

  var theme = '#enjoy-mondays';

  // add here all elements affected by background-color: background_1
  var bg_1_elements = [];

  // http://stackoverflow.com/questions/9708192/use-a-concatenated-dynamic-string-as-javascript-object-key
  bg_1_elements.push(
    'body' + theme,
    theme + ' .content-root',
    theme + ' .menubar',
    theme + ' .content',
    theme + ' #main-header',
   	theme + ' h1',
   	theme + ' h2',
   	theme + ' h3',
   	theme + ' h4',
   	theme + ' h5',
   	theme + ' h6',
   	theme + ' p',
   	theme + ' ul',
   	theme + ' ol'
  );

  // add here all elements affected by background-color: background_2
  var bg_2_elements = [];

  bg_2_elements.push(
    theme + ' .hljs',
    theme + ' pre > code'
  );

  // add here all elements affected by background-color: background_3
  var bg_3_elements = [];

  bg_3_elements.push(
    theme + ' code'
  );

  // add here all elements affected by color: color_1
  var color_1_elements = [];

  color_1_elements.push(
    'body' + theme
  );

  // add here all elements affected by color: color_2
  var color_2_elements = [];

  color_2_elements.push(
    theme + ' a'
  );

  // add here all elements affected by color: color_3
  var color_3_elements = [];

  color_3_elements.push(
    theme + ' .menu a:visited',
    theme + ' .menu a:hover',
    theme + ' .menu a.active'
  );

  // add here all elements affected by border-color: color_3
  color_3_elements.border = [];

  color_3_elements.border.push(
    theme + ' .menu a:visited',
    theme + ' .menu a:hover',
    theme + ' .menu a.active',
    theme + ' a.active',
    theme + ' a:hover'
  );

  // fix for
 elements floated to right for third column layout
  // each
 element gets floated right
  // special case
 followed by one or more
 tags,
  // jump the each in this case also for all but the first

  // want each element before
 tags to have total height (height + margin and padding)
  // to be same as floated
 at right
  function threeColumnContent() {
    // if not needed, return
  	if ($(window).width() < windowWidthMark) {
      return;
  	} else {
  	  threeColumnContentCalled = true;
  	}

    $.each(preElements, function(i, preElement) {

      var $this_pre = $(preElement);

      // get previous sibling of this pre element
      var $previous = $this_pre.prev();

      // if previous elements is
, jump each as it's allready accounted for
      // if ($previous.prop('tagName') === 'PRE') return;
      if (isPre($previous.prop('nodeName'))) {
      	return;
      }

      // get measures
      // total height of preElement
      var this_pre_heights = getHeights($this_pre);

      // total height of previous to this preElement
      var previous_heights = getHeights($previous);

      // get next sibling for case
 is followed by one or more
 elements
      var $next = $this_pre.next();

      // calculate pre heights
      // top measures don't affect
      // if only one pre element, total height to consider if paddings are the same, inner height
      var this_pre_height = this_pre_heights.inner_height;
      var previous_height = previous_heights.inner_height;

      // case
 is followed by one or more

      // if more then one pre element, sum of inner heights and 'inner' paddings
      if (isPre($next.prop('nodeName'))) {

        this_pre_height = this_pre_height + this_pre_heights.padding_bottom;
      	var next_pre_heights = getHeights($next);

      	while (isPre($next.prop('nodeName'))) {
          this_pre_height = this_pre_height + next_pre_heights.inner_height + this_pre_heights.padding_top;
          $next = $next.next();
        }

        // if previous height < pre_height
        if (previous_height < this_pre_height) {
          // set -margin and padding to compensate float empty space
          $previous.css('margin-bottom', - (this_pre_height - previous_heights.inner_height));
          $previous.css('padding-bottom', (this_pre_height - previous_heights.inner_height + previous_heights.padding_bottom));
        }

      } else {

      	// if previous height < pre_height
        if (previous_height < this_pre_height) {
          // set -margin and padding to compensate float empty space
          $previous.css('margin-bottom', - (this_pre_height - previous_heights.inner_height));
          $previous.css('padding-bottom', (this_pre_height - previous_heights.inner_height + previous_heights.padding_bottom));
        }

      }
    });

	// return true if nodename is

	function isPre(nodeName) {
	  return (nodeName === 'PRE');
	}

	// return heights of element: inner height, padding-top, padding-bottom, margin-top, margin-bottom
	function getHeights(elem) {
	  var h = {};

	  h.inner_height = $(elem).height();
	  h.padding_bottom = parseInt($(elem).css('padding-bottom'));
	  h.padding_top = parseInt($(elem).css('padding-top'));

	  return h;
	}
}

  function colorSwapTest(colors) {

    $.each(bg_1_elements, function(i, elem) {
      $(elem).css('background-color', colors[0]);
    });

    $.each(bg_3_elements, function(i, elem) {
      $(elem).css('background-color', colors[5]);
    });

    $.each(bg_2_elements, function(i, elem) {
      $(elem).css('background-color', colors[1]);
    });

    $.each(color_1_elements, function(i, elem) {
      $(elem).css('color', colors[2]);
    });

    $.each(color_2_elements, function(i, elem) {
      $(elem).css('color', colors[3]);
    });

    $.each(color_3_elements, function(i, elem) {
      $(elem).css('color', colors[4]);
    });

    $.each(color_3_elements.border, function(i, elem) {
      $(elem).css('border-color', colors[4]);
    });

    fixCodeBackground();

    var previousWindowWidth = $(window).width();

    $(window).resize(function() {
      var newWindowWidth = $(window).width();

      if (previousWindowWidth < windowWidthMark && newWindowWidth > windowWidthMark || previousWindowWidth > windowWidthMark && newWindowWidth < windowWidthMark) {
        previousWindowWidth = newWindowWidth;
        fixCodeBackground();
      }
    })

  }

  // color swapper
  $('#color-swapper a').click(function(e) {
    e.preventDefault();
    var color = $(this).parent().attr('class');
    var colors;

    // each class is the name of the first color in combo
    // TODO (if is to be used, refactor into more general function)
    switch (color) {
      case 'LIGHT_GRAY':
        colors = combo1;
        break;
      case 'DARK_GRAY':
        colors = combo2;
        break;
      case 'DARK_BLUE':
        colors = combo3;
        break;
      case 'FUXSIA':
        colors = combo4;
        break;
      case 'LIGHTER_WHITE':
        colors = combo5;
        break;
    }

    colorSwapTest(colors);

  });

  function fixCodeBackground() {
  	setTimeout(function() {
      var color1 = $(preElements[0]).css('background-color');
      //$('pre > code').css('background-color');
  	  var color2 = $('p').css('background-color');

  	  if ($(window).width() < windowWidthMark) {
  	    $('.content, .content-root').css('background-color', color2);
  	  } else {
  	    $('.content, .content-root').css('background-color', color1);
  	  }
  	}, 150);
  }

});<commit_msg>Testing color combos. Combo1 ok.<commit_after>$(window).load(function() {

  var threeColumnContentCalled = false;
  var windowWidthMark = 1180;

  var preElements = $('.content').find('pre');

  // fix css for three column layout
  threeColumnContent();

  $(window).resize(function() {
    // fix css for three column layout
    if (!threeColumnContentCalled) {
	    threeColumnContent();
    }
    hideScrollbarMoz();
  });

  function hideScrollbarMoz() {
  	var cW, sW;
  	$.each(preElements, function(i, pre) {
      cW = pre.clientWidth,
  	  sW = pre.scrollWidth;
  	  $(pre).find('.scrolls-x').removeClass('scrolls-x');
  	  if (cW != sW) {
  	  	$(pre).addClass('scrolls-x');
  	  } else {
  	  	//if ($(pre).hasClass('scrolls-x').removeClass('scroll-x'));
  	  }

  	});
  };

  hideScrollbarMoz();

  // color combos
  var GRAY = '#4a4a4a',
      LIGHT_GRAY = '#E9E8E3',
      DARK_GRAY = '#3A3A3A',
      DARK_BLUE =	'#363B48',
      FUXSIA = '#DF3F54',
      LIGHT_FUXSIA = '#F17C71',
      ZENBURN_BG = '#3F3F3F',
      LIGHT_WHITE = '#F3F6FB',
      LIGHTER_WHITE = '#F8F8F4',
      BLACK = '#000',
      WHITE = '#FFF';

  var combo1 = [LIGHT_GRAY, ZENBURN_BG, GRAY, DARK_GRAY, FUXSIA, LIGHT_WHITE],
      combo2 = [DARK_GRAY, BLACK, LIGHT_GRAY, LIGHT_WHITE, LIGHT_FUXSIA, BLACK],
      combo3 = [DARK_BLUE, BLACK, LIGHT_GRAY, LIGHT_WHITE, LIGHT_FUXSIA, BLACK],
      combo4 = [FUXSIA, ZENBURN_BG, LIGHT_GRAY, LIGHT_WHITE, LIGHT_FUXSIA, ZENBURN_BG],
      combo5 = [LIGHTER_WHITE, ZENBURN_BG, GRAY, DARK_GRAY, FUXSIA, WHITE];

  var theme = '#enjoy-mondays';

  // add here all elements affected by background-color: background_1
  var bg_1_elements = [];

  // http://stackoverflow.com/questions/9708192/use-a-concatenated-dynamic-string-as-javascript-object-key
  bg_1_elements.push(
    'body' + theme,
    theme + ' .content-root',
    theme + ' .menubar',
    theme + ' .content',
    theme + ' #main-header',
   	theme + ' h1',
   	theme + ' h2',
   	theme + ' h3',
   	theme + ' h4',
   	theme + ' h5',
   	theme + ' h6',
   	theme + ' p',
   	theme + ' ul',
   	theme + ' ol'
  );

  // add here all elements affected by background-color: background_2
  var bg_2_elements = [];

  bg_2_elements.push(
    theme + ' .hljs',
    theme + ' pre > code'
  );

  // add here all elements affected by background-color: background_3
  var bg_3_elements = [];

  bg_3_elements.push(
    theme + ' code'
  );

  // add here all elements affected by color: color_1
  var color_1_elements = [];

  color_1_elements.push(
    'body' + theme
  );

  // add here all elements affected by color: color_2
  var color_2_elements = [];

  color_2_elements.push(
    theme + ' a'
  );

  // add here all elements affected by color: color_3
  var color_3_elements = [];

  color_3_elements.push(
    theme + ' .menu a:visited',
    theme + ' .menu a:hover',
    theme + ' .menu a.active'
  );

  // add here all elements affected by border-color: color_3
  color_3_elements.border = [];

  color_3_elements.border.push(
    theme + ' .menu a:visited',
    theme + ' .menu a:hover',
    theme + ' .menu a.active',
    theme + ' a.active',
    theme + ' a:hover'
  );

  // fix for
 elements floated to right for third column layout
  // each
 element gets floated right
  // special case
 followed by one or more
 tags,
  // jump the each in this case also for all but the first

  // want each element before
 tags to have total height (height + margin and padding)
  // to be same as floated
 at right
  function threeColumnContent() {
    // if not needed, return
  	if ($(window).width() < windowWidthMark) {
      return;
  	} else {
  	  threeColumnContentCalled = true;
  	}

    $.each(preElements, function(i, preElement) {

      var $this_pre = $(preElement);

      // get previous sibling of this pre element
      var $previous = $this_pre.prev();

      // if previous elements is
, jump each as it's allready accounted for
      // if ($previous.prop('tagName') === 'PRE') return;
      if (isPre($previous.prop('nodeName'))) {
      	return;
      }

      // get measures
      // total height of preElement
      var this_pre_heights = getHeights($this_pre);

      // total height of previous to this preElement
      var previous_heights = getHeights($previous);

      // get next sibling for case
 is followed by one or more
 elements
      var $next = $this_pre.next();

      // calculate pre heights
      // top measures don't affect
      // if only one pre element, total height to consider if paddings are the same, inner height
      var this_pre_height = this_pre_heights.inner_height;
      var previous_height = previous_heights.inner_height;

      // case
 is followed by one or more

      // if more then one pre element, sum of inner heights and 'inner' paddings
      if (isPre($next.prop('nodeName'))) {

        this_pre_height = this_pre_height + this_pre_heights.padding_bottom;
      	var next_pre_heights = getHeights($next);

      	while (isPre($next.prop('nodeName'))) {
          this_pre_height = this_pre_height + next_pre_heights.inner_height + this_pre_heights.padding_top;
          $next = $next.next();
        }

        // if previous height < pre_height
        if (previous_height < this_pre_height) {
          // set -margin and padding to compensate float empty space
          $previous.css('margin-bottom', - (this_pre_height - previous_heights.inner_height));
          $previous.css('padding-bottom', (this_pre_height - previous_heights.inner_height + previous_heights.padding_bottom));
        }

      } else {

      	// if previous height < pre_height
        if (previous_height < this_pre_height) {
          // set -margin and padding to compensate float empty space
          $previous.css('margin-bottom', - (this_pre_height - previous_heights.inner_height));
          $previous.css('padding-bottom', (this_pre_height - previous_heights.inner_height + previous_heights.padding_bottom));
        }

      }
    });

	// return true if nodename is

	function isPre(nodeName) {
	  return (nodeName === 'PRE');
	}

	// return heights of element: inner height, padding-top, padding-bottom, margin-top, margin-bottom
	function getHeights(elem) {
	  var h = {};

	  h.inner_height = $(elem).height();
	  h.padding_bottom = parseInt($(elem).css('padding-bottom'));
	  h.padding_top = parseInt($(elem).css('padding-top'));

	  return h;
	}
}

  function colorSwapTest(colors) {

    $.each(bg_1_elements, function(i, elem) {
      $(elem).css('background-color', colors[0]);
    });

    $.each(bg_3_elements, function(i, elem) {
      $(elem).css('background-color', colors[5]);
    });

    $.each(bg_2_elements, function(i, elem) {
      $(elem).css('background-color', colors[1]);
    });

    $.each(color_1_elements, function(i, elem) {
      $(elem).css('color', colors[2]);
    });

    $.each(color_2_elements, function(i, elem) {
      $(elem).css('color', colors[3]);
    });

    $.each(color_3_elements, function(i, elem) {
      $(elem).css('color', colors[4]);
    });

    $.each(color_3_elements.border, function(i, elem) {
      $(elem).css('border-color', colors[4]);
    });

    fixCodeBackground();

    var previousWindowWidth = $(window).width();

    $(window).resize(function() {
      var newWindowWidth = $(window).width();

      if (previousWindowWidth < windowWidthMark && newWindowWidth > windowWidthMark || previousWindowWidth > windowWidthMark && newWindowWidth < windowWidthMark) {
        previousWindowWidth = newWindowWidth;
        fixCodeBackground();
      }
    })

  }

  // color swapper
  $('#color-swapper a').click(function(e) {
    e.preventDefault();
    var color = $(this).parent().attr('class');
    var colors;

    // each class is the name of the first color in combo
    // TODO (if is to be used, refactor into more general function)
    switch (color) {
      case 'LIGHT_GRAY':
        colors = combo1;
        break;
      case 'DARK_GRAY':
        colors = combo2;
        break;
      case 'DARK_BLUE':
        colors = combo3;
        break;
      case 'FUXSIA':
        colors = combo4;
        break;
      case 'LIGHTER_WHITE':
        colors = combo5;
        break;
    }

    colorSwapTest(colors);

  });

  function fixCodeBackground() {
  	setTimeout(function() {
      var color1 = $(preElements[0]).css('background-color');
      //$('pre > code').css('background-color');
  	  var color2 = $('p').css('background-color');

  	  if ($(window).width() < windowWidthMark) {
  	    $('.content, .content-root').css('background-color', color2);
  	  } else {
  	    $('.content, .content-root').css('background-color', color1);
  	  }
  	}, 150);
  }

});<|endoftext|>


<commit_before>const path = require('path');

const mainJs = path.resolve(__dirname, 'src/client/main.js');
const outputPath = path.resolve(__dirname, 'public/dist');

module.exports = {
  devtool: 'cheap-module-eval-source-map',
  entry:   [
    mainJs
  ],
  output:  {
    path:       outputPath,
    filename:   'vote-app.js',
    publicPath: '/dist'
  },
  module:  {
    loaders: [
      {
        test:    /\.jsx?/,
        loader:  'babel',
        exclude: /node_modules/
      },
      {
        test:    /\.jsx?$/,
        exclude: /node_modules/,
        loader:  'eslint'
      }
    ]
  }
};

<commit_msg>switched back to non fancy source maps (because they work) for webpack<commit_after>const path = require('path');

const mainJs = path.resolve(__dirname, 'src/client/main.js');
const outputPath = path.resolve(__dirname, 'public/dist');

module.exports = {
  devtool: 'source-map',
  entry:   [
    mainJs
  ],
  output:  {
    path:       outputPath,
    filename:   'vote-app.js',
    publicPath: '/dist'
  },
  module:  {
    loaders: [
      {
        test:    /\.jsx?/,
        loader:  'babel',
        exclude: /node_modules/
      },
      {
        test:    /\.jsx?$/,
        exclude: /node_modules/,
        loader:  'eslint'
      }
    ]
  }
};

<|endoftext|>


<commit_before>"use strict";
var webpack = require('webpack');
var path = require('path');
var loaders = require('./webpack.loaders');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var DashboardPlugin = require('webpack-dashboard/plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var LodashModuleReplacementPlugin = require('lodash-webpack-plugin');
var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

const HOST = process.env.HOST || "127.0.0.1";
const PORT = process.env.PORT || "8888";

loaders.push({
	test: /\.jsx?$/,
	exclude: /(node_modules|bower_components|public\/)/,
	loader: ['react-hot-loader/webpack', 'babel-loader']
});

loaders.push({
  test: /\.scss$/,
  loaders: ['style-loader', 'css-loader?importLoaders=1', 'sass-loader'],
  exclude: ['node_modules']
});

loaders.push({
  test: require.resolve('two.js'),
  loader: 'imports-loader?this=>window',
});

module.exports = {
  entry: [
		'webpack-hot-middleware/client',
    'react-hot-loader/patch',
    './src/index.js', // your app's entry point
  ],
  devtool: process.env.WEBPACK_DEVTOOL || 'eval-source-map',
  output: {
    publicPath: '/',
    path: path.join(__dirname, 'public'),
    filename: '[hash].bundle.js'
  },
  resolve: {
    extensions: ['.js', '.jsx']
  },
  module: {
    loaders
  },
  plugins: [
    new BundleAnalyzerPlugin(),
		new LodashModuleReplacementPlugin,
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new ExtractTextPlugin({
      filename: 'style.css',
      allChunks: true
    }),
    new DashboardPlugin(),
    new HtmlWebpackPlugin({
      template: './src/template.html',
      files: {
        css: ['style.css'],
        js: ["bundle.js"],
      },
      filename: 'index.html',
    }),
    new CopyWebpackPlugin([
      { from: 'src/assets/audio', to: 'assets/audio' },
      { from: 'src/utils/autotrack.js' },
      { from: 'src/assets/images/logo.png' },
      { from: 'src/assets/images/ico/flash.ico' },
    ]),
  ]
};
<commit_msg>:rocket: add alias path to webpack<commit_after>"use strict";
var webpack = require('webpack');
var path = require('path');
var loaders = require('./webpack.loaders');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var DashboardPlugin = require('webpack-dashboard/plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var LodashModuleReplacementPlugin = require('lodash-webpack-plugin');
var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

const HOST = process.env.HOST || "127.0.0.1";
const PORT = process.env.PORT || "8888";

loaders.push({
	test: /\.jsx?$/,
	exclude: /(node_modules|bower_components|public\/)/,
	loader: ['react-hot-loader/webpack', 'babel-loader']
});

loaders.push({
  test: /\.scss$/,
  loaders: ['style-loader', 'css-loader?importLoaders=1', 'sass-loader'],
  exclude: ['node_modules']
});

loaders.push({
  test: require.resolve('two.js'),
  loader: 'imports-loader?this=>window',
});

module.exports = {
  entry: [
		'webpack-hot-middleware/client',
    'react-hot-loader/patch',
    './src/index.js', // your app's entry point
  ],
  devtool: process.env.WEBPACK_DEVTOOL || 'eval-source-map',
  output: {
    publicPath: '/',
    path: path.join(__dirname, 'public'),
    filename: '[hash].bundle.js'
  },
  resolve: {
    extensions: ['.js', '.jsx'],
		alias: {
		  yuen: path.resolve(__dirname, 'src/utilities/'),
		}
  },
  module: {
    loaders
  },
  plugins: [
    new BundleAnalyzerPlugin(),
		new LodashModuleReplacementPlugin,
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new ExtractTextPlugin({
      filename: 'style.css',
      allChunks: true
    }),
    new DashboardPlugin(),
    new HtmlWebpackPlugin({
      template: './src/template.html',
      files: {
        css: ['style.css'],
        js: ["bundle.js"],
      },
      filename: 'index.html',
    }),
    new CopyWebpackPlugin([
      { from: 'src/assets/audio', to: 'assets/audio' },
      { from: 'src/utils/autotrack.js' },
      { from: 'src/assets/images/logo.png' },
      { from: 'src/assets/images/ico/flash.ico' },
    ]),
  ]
};
<|endoftext|>


<commit_before>import path from 'path'
import webpack from 'webpack'
import HtmlWebpackPlugin from 'html-webpack-plugin'
import CleanWebpackPlugin from 'clean-webpack-plugin'
import StyleLintPlugin from 'stylelint-webpack-plugin'
import ExtractTextPlugin from 'extract-text-webpack-plugin'
import merge from 'webpack-merge'
import baseConfig from './base'

export default merge.strategy({
  module: 'replace',
  plugins: 'replace',
  'output.filename': 'replace'
})(baseConfig, {
  module: {
    rules: [
      // --------- img ----------
      {
        test: /\.(pdf|png|jpe?g|gif)$/i,
        exclude: /node_modules/,
        use: [
          // {
          //   loader: 'url-loader',
          //   options: {
          //     limit: 8192,
          //   }
          // },
          {
            loader: 'file-loader',
            options: {
              name: '[name].[hash].[ext]'
            }
          }
        ]
      },

      // ----------- JSX -----------
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        enforce: 'pre',
        use: [
          {
            loader: 'eslint-loader',
            options: {
              failOnError: true
            }
          }
        ],
      },
      {
        test: /\.jsx?$/,
        use: [
          { loader: 'babel-loader' }
        ],
        exclude: /node_modules/
      },

      // ----------- CSS -----------
      {
        test: /\.scss$/,
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: [
            { loader: 'css-loader' },
            { loader: 'resolve-url-loader' },
            {
              loader: 'sass-loader',
              options: {
                sourceMap: true,
                includePaths: [
                  path.resolve(__dirname, '../src')
                ]
              }
            }
          ]
        })
      }
    ]
  },
  plugins: [
    new CleanWebpackPlugin(['build']),
    new webpack.EnvironmentPlugin([
      'NODE_ENV'
    ]),
    new HtmlWebpackPlugin({
      title: 'Hello, I\'m Jeff Dolle',
      template: 'src/index.template.ejs',
      inject: 'body'
    }),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin({
      compress: { warnings: false }
    }),
    new StyleLintPlugin({
      configFile: '.stylelintrc.json'
    }),
    new ExtractTextPlugin('[name].scss')
  ],
  devtool: 'source-map',
  output: {
    filename: '[name].prod.bundle.js'
  }
})
<commit_msg>Fix production css modules<commit_after>import path from 'path'
import webpack from 'webpack'
import HtmlWebpackPlugin from 'html-webpack-plugin'
import CleanWebpackPlugin from 'clean-webpack-plugin'
import StyleLintPlugin from 'stylelint-webpack-plugin'
import ExtractTextPlugin from 'extract-text-webpack-plugin'
import merge from 'webpack-merge'
import baseConfig from './base'

export default merge.strategy({
  module: 'replace',
  plugins: 'replace',
  'output.filename': 'replace'
})(baseConfig, {
  module: {
    rules: [
      // --------- img ----------
      {
        test: /\.(pdf|png|jpe?g|gif)$/i,
        exclude: /node_modules/,
        use: [
          // {
          //   loader: 'url-loader',
          //   options: {
          //     limit: 8192,
          //   }
          // },
          {
            loader: 'file-loader',
            options: {
              name: '[name].[hash].[ext]'
            }
          }
        ]
      },

      // ----------- JSX -----------
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        enforce: 'pre',
        use: [
          {
            loader: 'eslint-loader',
            options: {
              failOnError: true
            }
          }
        ],
      },
      {
        test: /\.jsx?$/,
        use: [
          { loader: 'babel-loader' }
        ],
        exclude: /node_modules/
      },

      // ----------- CSS -----------
      {
        test: /\.scss$/,
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: [
            {
              loader: 'css-loader',
              options: {
                modules: true
              }
            },
            { loader: 'resolve-url-loader' },
            {
              loader: 'sass-loader',
              options: {
                sourceMap: true,
                includePaths: [
                  path.resolve(__dirname, '../src')
                ]
              }
            }
          ]
        })
      }
    ]
  },
  plugins: [
    new CleanWebpackPlugin(['build']),
    new webpack.EnvironmentPlugin([
      'NODE_ENV'
    ]),
    new HtmlWebpackPlugin({
      title: 'Hello, I\'m Jeff Dolle',
      template: 'src/index.template.ejs',
      inject: 'body'
    }),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin({
      compress: { warnings: false }
    }),
    new StyleLintPlugin({
      configFile: '.stylelintrc.json'
    }),
    new ExtractTextPlugin('[name].scss')
  ],
  devtool: 'source-map',
  output: {
    filename: '[name].prod.bundle.js'
  }
})
<|endoftext|>


<commit_before>function sendEnquire(fromModal){
    var message = "Requisicao do Site \n\n" +
                "Nome Contato: " + $("#nomeContato").val() + "\n\n" +
                "Empresa: " + $("#empresaContato").val() + "\n\n" +
                "Telefone Contato: " + $("#telefoneContato").val() + "\n\n" +
                "Email Contato: " + $("#emailContato").val() + "\n\n" +
                "Origem do contato: " + $.urlParam("s") + "\n\n" +
                "Mensagem: " + $("#mensagem").val();

    var postData = {
      nome: $("#nomeContato").val(),
      empresa: $("#empresaContato").val(),
      telefone: $("#telefoneContato").val(),
      email: $("#emailContato").val(),
      message: message
    };

    var cleanForm = function(){
        $("form input").val('');
        $("form textarea").val('');
        $("#sendMessage").prop('disabled', false);
    };

    $("#sendMessage").prop('disabled', true);

    $.ajax({
        url: "http://purewaterefluentes.tempsite.ws/sendEmail.php",
        method: "POST",
        data: postData,
        dataType: "json",
        success: function(){
            console.log('success' + arguments);
            $("#confirmationModal").modal("show");
            $("#confirmationModal").on('hidden.bs.modal', cleanForm);
        },
        error: function(){
            console.log('fail' + arguments);
          $(".alert-danger").show();
        }
    });
}

function sendEnquireFormspree(fromModal){
    var message = "Requisicao do Site \n\n" +
                "Nome Contato: " + $("#nomeContato").val() + "\n\n" +
                "Empresa: " + $("#empresaContato").val() + "\n\n" +
                "Telefone Contato: " + $("#telefoneContato").val() + "\n\n" +
                "Email Contato: " + $("#emailContato").val() + "\n\n" +
                "Origem do contato: " + $.urlParam("s") + "\n\n" +
                "Mensagem: " + $("#mensagem").val();

    var mail = {
      _replyto: $("#emailContato").val(),
      _subject: "Requisicao do Site - " + $("#nomeContato").val(),
      message: message
    };

    var cleanForm = function(){
        $("form input").val('');
        $("form textarea").val('');
        $("#sendMessage").prop('disabled', false);
    };

    $("#sendMessage").prop('disabled', true);

    $.ajax({
        url: "https://formspree.io/vendas@purewaterefluentes.com.br",
        method: "POST",
        data: mail,
        dataType: "json",
        success: function(){
            $("#confirmationModal").modal("show");
            $("#confirmationModal").on('hidden.bs.modal', cleanForm);
        },
        error: function(){
          $(".alert-danger").show()
        }
    });
}

$.urlParam = function(name){
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    return results && decodeURIComponent(results[1]) || null;
}
<commit_msg>add log<commit_after>function sendEnquire(fromModal){
    var message = "Requisicao do Site \n\n" +
                "Nome Contato: " + $("#nomeContato").val() + "\n\n" +
                "Empresa: " + $("#empresaContato").val() + "\n\n" +
                "Telefone Contato: " + $("#telefoneContato").val() + "\n\n" +
                "Email Contato: " + $("#emailContato").val() + "\n\n" +
                "Origem do contato: " + $.urlParam("s") + "\n\n" +
                "Mensagem: " + $("#mensagem").val();

    var postData = {
      nome: $("#nomeContato").val(),
      empresa: $("#empresaContato").val(),
      telefone: $("#telefoneContato").val(),
      email: $("#emailContato").val(),
      message: message
    };

    var cleanForm = function(){
        $("form input").val('');
        $("form textarea").val('');
        $("#sendMessage").prop('disabled', false);
    };

    $("#sendMessage").prop('disabled', true);

    $.ajax({
        url: "http://purewaterefluentes.tempsite.ws/sendEmail.php",
        method: "POST",
        data: postData,
        dataType: "json",
        success: function(){
            console.log('success');
             console.log(arguments);
            $("#confirmationModal").modal("show");
            $("#confirmationModal").on('hidden.bs.modal', cleanForm);
        },
        error: function(){
            console.log('fail' + arguments);
            console.log(arguments);
          $(".alert-danger").show();
        }
    });
}

function sendEnquireFormspree(fromModal){
    var message = "Requisicao do Site \n\n" +
                "Nome Contato: " + $("#nomeContato").val() + "\n\n" +
                "Empresa: " + $("#empresaContato").val() + "\n\n" +
                "Telefone Contato: " + $("#telefoneContato").val() + "\n\n" +
                "Email Contato: " + $("#emailContato").val() + "\n\n" +
                "Origem do contato: " + $.urlParam("s") + "\n\n" +
                "Mensagem: " + $("#mensagem").val();

    var mail = {
      _replyto: $("#emailContato").val(),
      _subject: "Requisicao do Site - " + $("#nomeContato").val(),
      message: message
    };

    var cleanForm = function(){
        $("form input").val('');
        $("form textarea").val('');
        $("#sendMessage").prop('disabled', false);
    };

    $("#sendMessage").prop('disabled', true);

    $.ajax({
        url: "https://formspree.io/vendas@purewaterefluentes.com.br",
        method: "POST",
        data: mail,
        dataType: "json",
        success: function(){
            $("#confirmationModal").modal("show");
            $("#confirmationModal").on('hidden.bs.modal', cleanForm);
        },
        error: function(){
          $(".alert-danger").show()
        }
    });
}

$.urlParam = function(name){
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    return results && decodeURIComponent(results[1]) || null;
}
<|endoftext|>