<commit_before>/**
 * Create a cards object to hold relevant card relating to specific action
 */
function Cards(){
    this.resource_cards = {
        brick : 10,
        grain : 10,
        sheep : 10,
        lumber: 10,
        ore   : 10
    };

    this.dev_cards = {
        year_of_plenty : 0,
        monopoly : 0,
        knight : 0,
        road_building  : 0,
    };

    this.victory_point_cards = {
        library : 0,
        market : 0,
        chapel : 0,
        university_of_catan  : 0,
        great_hall   : 0
    };

}

//Return number of cards in Cards Object
Cards.prototype.count_cards = function(){
    return this.resource_cards.brick + this.resource_cards.grain + this.resource_cards.sheep + this.resource_cards.lumber + this.resource_cards.ore;
};

Cards.prototype.count_victory_cards = function(){
    return this.victory_point_cards.library + this.victory_point_cards.market + this.victory_point_cards.chapel + this.victory_point_cards.university_of_catan + this.victory_point_cards.great_hall;
}

//Add card to cards
Cards.prototype.add_card = function(card){
    switch (card){
        case "brick":
            this.resource_cards.brick++;
            break;
        case "grain":
            this.resource_cards.grain++;
            break;
        case "sheep":
            this.resource_cards.sheep++;
            break;
        case "lumber":
            this.resource_cards.lumber++;
            break;
        case "ore":
            this.resource_cards.ore++;
            break;

        case "knight":
            this.dev_cards.knight++;
            break;
        case "year_of_plenty":
            this.dev_cards.year_of_plenty++;
            break;
        case "monopoly":
            this.dev_cards.monopoly++;
            break;
        case "road_building":
            this.dev_cards.road_building++;
            break;

        case "library":
            this.victory_point_cards.library++;
            break;
        case "chapel":
            this.victory_point_cards.chapel++;
            break;
        case "market":
            this.victory_point_cards.market++;
            break;
        case "great_hall":
            this.victory_point_cards.great_hall++;
            break;
        case "university_of_catan":
            this.victory_point_cards.university_of_catan++;
            break;
    }
}

Cards.prototype.remove_card = function(card){
    return this.remove_multiple_cards(card, 1);
}
Cards.prototype.remove_multiple_cards = function(card, qty){
    if (qty > 0) {
        if(card == "sheep" && this.resource_cards.sheep >= qty){
            this.resource_cards.sheep -= qty;
            return true;
        }else if(card == "grain" && this.resource_cards.grain >= qty){
            this.resource_cards.grain -= qty;
            return true;
        }else if(card == "brick" && this.resource_cards.brick >= qty){
            this.resource_cards.brick -= qty;
            return true;
        }else if(card == "lumber" && this.resource_cards.lumber >= qty){
            this.resource_cards.lumber -= qty;
            return true;
        }else if(card == "ore" && this.resource_cards.ore >= qty){
            this.resource_cards.ore -= qty;
            return true;
        }else{
            return false;
        }
    }
    return false;
}

Cards.prototype.remove_cards = function(purchase){
    //returns true if cards loaded successfully
    if ( purchase == 'road' ) {
        return this.remove_card('brick') && this.remove_card('lumber');
    }else if ( purchase == 'house' ) {
        return this.remove_card('brick') &&
            this.remove_card('lumber') &&
            this.remove_card('grain') &&
            this.remove_card('sheep');
    }else if ( purchase === 'city' ) {
        return this.remove_card('ore') &&
            this.remove_card('ore') &&
            this.remove_card('ore') &&
            this.remove_card('grain') &&
            this.remove_card('grain');
    }else if ( purchase === 'dev_card' ) {
        return this.remove_card('ore') &&
            this.remove_card('grain') &&
            this.remove_card('sheep');
    }else{
        logger.log('error', 'remove_cards function failed');
        return false;
    }
}

Cards.prototype.has_cards = function(card_list) {
    var missing_card = false;
    var removed_list = [];

    //  Mimic the removal of each card and see if we run out
    for (var i = 0; i < card_list.length; i++) {
        var next_card = card_list[i];
        if (this.remove_card(next_card)) {
            removed_list.push(next_card);
        } else {
            missing_card = true;
            break;
        }
    }

    //  In all cases, we restore the cards
    for (var i = 0; i < removed_list.length; i++) {
        var next_card = removed_list[i];
        this.add_card(next_card);
    }
    return !missing_card;
};

Cards.prototype.get_required_cards = function(object_type){
    var card_list = [];

    if ( object_type == 'road' ) {
        card_list.push('lumber');
        card_list.push('brick');
    }
    if ( object_type == 'house' ) {
        card_list.push('lumber');
        card_list.push('brick');
        card_list.push('grain');
        card_list.push('ore');
    }
    if ( object_type == 'city' ) {
        card_list.push('grain');
        card_list.push('grain');
        card_list.push('ore');
        card_list.push('ore');
        card_list.push('ore');
    }
    return card_list;
};

/**
 * @param {String} card_type : check whether players have enough cards
 */
Cards.prototype.available_cards = function ( card_type ) {
    if(card_type === 'dev_card'){
        return((this.resource_cards.ore > 0) && (this.resource_cards.sheep > 0) && (this.resource_cards.grain > 0));
    }
    if(card_type === 'house'){
        return((this.resource_cards.brick > 0) && (this.resource_cards.sheep > 0) && (this.resource_cards.grain > 0) && (this.resource_cards.lumber > 0));
    }
    if(card_type === 'road'){
        return((this.resource_cards.brick > 0) && (this.resource_cards.lumber > 0));
    }
    if(card_type === 'city'){
        return((this.resource_cards.ore > 2) && (this.resource_cards.grain > 1) && (this.resource_cards.grain > 0));
    }

}

if (typeof module !== 'undefined' && module.exports) {
    module.exports = Cards;
}

<commit_msg>Fine tuning of building and bidding<commit_after>/**
 * Create a cards object to hold relevant card relating to specific action
 */
function Cards(){
    this.resource_cards = {
        brick : 0,
        grain : 0,
        sheep : 0,
        lumber: 0,
        ore   : 0
    };

    this.dev_cards = {
        year_of_plenty : 0,
        monopoly : 0,
        knight : 0,
        road_building  : 0,
    };

    this.victory_point_cards = {
        library : 0,
        market : 0,
        chapel : 0,
        university_of_catan  : 0,
        great_hall   : 0
    };

}

//Return number of cards in Cards Object
Cards.prototype.count_cards = function(){
    return this.resource_cards.brick + this.resource_cards.grain + this.resource_cards.sheep + this.resource_cards.lumber + this.resource_cards.ore;
};

Cards.prototype.count_victory_cards = function(){
    return this.victory_point_cards.library + this.victory_point_cards.market + this.victory_point_cards.chapel + this.victory_point_cards.university_of_catan + this.victory_point_cards.great_hall;
}

//Add card to cards
Cards.prototype.add_card = function(card){
    switch (card){
        case "brick":
            this.resource_cards.brick++;
            break;
        case "grain":
            this.resource_cards.grain++;
            break;
        case "sheep":
            this.resource_cards.sheep++;
            break;
        case "lumber":
            this.resource_cards.lumber++;
            break;
        case "ore":
            this.resource_cards.ore++;
            break;

        case "knight":
            this.dev_cards.knight++;
            break;
        case "year_of_plenty":
            this.dev_cards.year_of_plenty++;
            break;
        case "monopoly":
            this.dev_cards.monopoly++;
            break;
        case "road_building":
            this.dev_cards.road_building++;
            break;

        case "library":
            this.victory_point_cards.library++;
            break;
        case "chapel":
            this.victory_point_cards.chapel++;
            break;
        case "market":
            this.victory_point_cards.market++;
            break;
        case "great_hall":
            this.victory_point_cards.great_hall++;
            break;
        case "university_of_catan":
            this.victory_point_cards.university_of_catan++;
            break;
    }
}

Cards.prototype.remove_card = function(card){
    return this.remove_multiple_cards(card, 1);
}
Cards.prototype.remove_multiple_cards = function(card, qty){
    if (qty > 0) {
        if(card == "sheep" && this.resource_cards.sheep >= qty){
            this.resource_cards.sheep -= qty;
            return true;
        }else if(card == "grain" && this.resource_cards.grain >= qty){
            this.resource_cards.grain -= qty;
            return true;
        }else if(card == "brick" && this.resource_cards.brick >= qty){
            this.resource_cards.brick -= qty;
            return true;
        }else if(card == "lumber" && this.resource_cards.lumber >= qty){
            this.resource_cards.lumber -= qty;
            return true;
        }else if(card == "ore" && this.resource_cards.ore >= qty){
            this.resource_cards.ore -= qty;
            return true;
        }else{
            return false;
        }
    }
    return false;
}

Cards.prototype.remove_cards = function(purchase){
    //returns true if cards loaded successfully
    if ( purchase == 'road' ) {
        return this.remove_card('brick') && this.remove_card('lumber');
    }else if ( purchase == 'house' ) {
        return this.remove_card('brick') &&
            this.remove_card('lumber') &&
            this.remove_card('grain') &&
            this.remove_card('sheep');
    }else if ( purchase === 'city' ) {
        return this.remove_card('ore') &&
            this.remove_card('ore') &&
            this.remove_card('ore') &&
            this.remove_card('grain') &&
            this.remove_card('grain');
    }else if ( purchase === 'dev_card' ) {
        return this.remove_card('ore') &&
            this.remove_card('grain') &&
            this.remove_card('sheep');
    }else{
        logger.log('error', 'remove_cards function failed');
        return false;
    }
}

Cards.prototype.has_cards = function(card_list) {
    var missing_card = false;
    var removed_list = [];

    //  Mimic the removal of each card and see if we run out
    for (var i = 0; i < card_list.length; i++) {
        var next_card = card_list[i];
        if (this.remove_card(next_card)) {
            removed_list.push(next_card);
        } else {
            missing_card = true;
            break;
        }
    }

    //  In all cases, we restore the cards
    for (var i = 0; i < removed_list.length; i++) {
        var next_card = removed_list[i];
        this.add_card(next_card);
    }
    return !missing_card;
};

Cards.prototype.get_required_cards = function(object_type){
    var card_list = [];

    if ( object_type == 'road' ) {
        card_list.push('lumber');
        card_list.push('brick');
    }
    if ( object_type == 'house' ) {
        card_list.push('lumber');
        card_list.push('brick');
        card_list.push('grain');
        card_list.push('ore');
    }
    if ( object_type == 'city' ) {
        card_list.push('grain');
        card_list.push('grain');
        card_list.push('ore');
        card_list.push('ore');
        card_list.push('ore');
    }
    return card_list;
};

/**
 * @param {String} card_type : check whether players have enough cards
 */
Cards.prototype.available_cards = function ( card_type ) {
    if(card_type === 'dev_card'){
        return((this.resource_cards.ore > 0) && (this.resource_cards.sheep > 0) && (this.resource_cards.grain > 0));
    }
    if(card_type === 'house'){
        return((this.resource_cards.brick > 0) && (this.resource_cards.sheep > 0) && (this.resource_cards.grain > 0) && (this.resource_cards.lumber > 0));
    }
    if(card_type === 'road'){
        return((this.resource_cards.brick > 0) && (this.resource_cards.lumber > 0));
    }
    if(card_type === 'city'){
        return((this.resource_cards.ore > 2) && (this.resource_cards.grain > 1) && (this.resource_cards.grain > 0));
    }

}

if (typeof module !== 'undefined' && module.exports) {
    module.exports = Cards;
}

<|endoftext|>


<commit_before>
(function(factory){if(typeof define==='function'&&define.amd){define(factory);}else if(typeof module!=='undefined'&&module.exports){module.exports=factory();}else{window.pym=factory.call(this);}})(function(){var MESSAGE_DELIMITER='xPYMx';var lib={};var _getParameterByName=function(name){var regex=new RegExp("[\\?&]"+name.replace(/[\[]/,'\\[').replace(/[\]]/,'\\]')+'=([^&#]*)');var results=regex.exec(location.search);if(results===null){return'';}
return decodeURIComponent(results[1].replace(/\+/g," "));};var _isSafeMessage=function(e,settings){if(settings.xdomain!=='*'){if(!e.origin.match(new RegExp(settings.xdomain+'$'))){return;}}
return true;};var _makeMessage=function(id,messageType,message){var bits=['pym',id,messageType,message];return bits.join(MESSAGE_DELIMITER);};var _makeMessageRegex=function(id){var bits=['pym',id,'(\\S+)','(.+)'];return new RegExp('^'+bits.join(MESSAGE_DELIMITER)+'$');};var _autoInit=function(){var elements=document.querySelectorAll('[data-pym-src]:not([data-pym-auto-initialized])');var length=elements.length;for(var idx=0;idx<length;++idx){var element=elements[idx];element.setAttribute('data-pym-auto-initialized','');if(element.id===''){element.id='pym-'+idx;}
var src=element.getAttribute('data-pym-src');var xdomain=element.getAttribute('data-pym-xdomain');var config={};if(xdomain){config.xdomain=xdomain;}
new lib.Parent(element.id,src,config);}};lib.Parent=function(id,url,config){this.id=id;this.url=url;this.el=document.getElementById(id);this.iframe=null;this.settings={xdomain:'*'};this.messageRegex=_makeMessageRegex(this.id);this.messageHandlers={};config=(config||{});this._constructIframe=function(){var width=this.el.offsetWidth.toString();this.iframe=document.createElement('iframe');var hash='';var hashIndex=this.url.indexOf('#');if(hashIndex>-1){hash=this.url.substring(hashIndex,this.url.length);this.url=this.url.substring(0,hashIndex);}
if(this.url.indexOf('?')<0){this.url+='?';}else{this.url+='&';}
this.iframe.src=this.url+'initialWidth='+width+'&childId='+this.id+'&parentUrl='+encodeURIComponent(window.location.href)+
hash;this.iframe.setAttribute('width','100%');this.iframe.setAttribute('scrolling','no');this.iframe.setAttribute('marginheight','0');this.iframe.setAttribute('frameborder','0');this.el.appendChild(this.iframe);window.addEventListener('resize',this._onResize);};this._onResize=function(){this.sendWidth();}.bind(this);this._fire=function(messageType,message){if(messageType in this.messageHandlers){for(var i=0;i<this.messageHandlers[messageType].length;i++){this.messageHandlers[messageType][i].call(this,message);}}};this.remove=function(){window.removeEventListener('message',this._processMessage);window.removeEventListener('resize',this._onResize);this.el.removeChild(this.iframe);};this._processMessage=function(e){if(!_isSafeMessage(e,this.settings)){return;}
if(typeof e.data!=='string'){return;}
var match=e.data.match(this.messageRegex);if(!match||match.length!==3){return false;}
var messageType=match[1];var message=match[2];this._fire(messageType,message);}.bind(this);this._onHeightMessage=function(message){var height=parseInt(message);this.iframe.setAttribute('height',height+'px');};this._onNavigateToMessage=function(message){document.location.href=message;};this.onMessage=function(messageType,callback){if(!(messageType in this.messageHandlers)){this.messageHandlers[messageType]=[];}
this.messageHandlers[messageType].push(callback);};this.sendMessage=function(messageType,message){this.el.getElementsByTagName('iframe')[0].contentWindow.postMessage(_makeMessage(this.id,messageType,message),'*');};this.sendWidth=function(){var width=this.el.offsetWidth.toString();this.sendMessage('width',width);};for(var key in config){this.settings[key]=config[key];}
this.onMessage('height',this._onHeightMessage);this.onMessage('navigateTo',this._onNavigateToMessage);window.addEventListener('message',this._processMessage,false);this._constructIframe();return this;};lib.Child=function(config){this.parentWidth=null;this.id=null;this.parentUrl=null;this.settings={renderCallback:null,xdomain:'*',polling:0};this.messageRegex=null;this.messageHandlers={};config=(config||{});this.onMessage=function(messageType,callback){if(!(messageType in this.messageHandlers)){this.messageHandlers[messageType]=[];}
this.messageHandlers[messageType].push(callback);};this._fire=function(messageType,message){if(messageType in this.messageHandlers){for(var i=0;i<this.messageHandlers[messageType].length;i++){this.messageHandlers[messageType][i].call(this,message);}}};this._processMessage=function(e){if(!_isSafeMessage(e,this.settings)){return;}
if(typeof e.data!=='string'){return;}
var match=e.data.match(this.messageRegex);if(!match||match.length!==3){return;}
var messageType=match[1];var message=match[2];this._fire(messageType,message);}.bind(this);this._onWidthMessage=function(message){var width=parseInt(message);if(width!==this.parentWidth){this.parentWidth=width;if(this.settings.renderCallback){this.settings.renderCallback(width);}
this.sendHeight();}};this.sendMessage=function(messageType,message){window.parent.postMessage(_makeMessage(this.id,messageType,message),'*');};this.sendHeight=function(){var height=document.getElementsByTagName('body')[0].offsetHeight.toString();this.sendMessage('height',height);}.bind(this);this.scrollParentTo=function(hash){this.sendMessage('navigateTo','#'+hash);};this.navigateParentTo=function(url){this.sendMessage('navigateTo',url);};this.id=_getParameterByName('childId')||config.id;this.messageRegex=new RegExp('^pym'+MESSAGE_DELIMITER+this.id+MESSAGE_DELIMITER+'(\\S+)'+MESSAGE_DELIMITER+'(.+)$');var width=parseInt(_getParameterByName('initialWidth'));this.parentUrl=_getParameterByName('parentUrl');this.onMessage('width',this._onWidthMessage);for(var key in config){this.settings[key]=config[key];}
window.addEventListener('message',this._processMessage,false);if(this.settings.renderCallback){this.settings.renderCallback(width);}
this.sendHeight();if(this.settings.polling){window.setInterval(this.sendHeight,this.settings.polling);}
return this;};_autoInit();return lib;});<commit_msg>Remove unused Pym asset from page embed<commit_after><|endoftext|>


<commit_before><commit_msg>Add -1/--onlyName mode to mirror `ls -1`<commit_after><|endoftext|>


<commit_before>'use strict';
var a = 'Hello world';
console.log(a);

var location_info = {
    lat: 0,
    lon: 0
};

var ngModule = angular.module;
var app = ngModule('hrApp', [
    'home',
    'about',
    'donate',
    'events',
    'globalNav',
    'ui.router',
    'geolocation',
    'createEvent',
    'register'
]);

ngModule('globalNav', [])
    .directive('globalNav', function () {
        return {
            restrict: 'E',
            replace: true,
            templateUrl: '../views/global-nav.html',
            controller: 'globalNavController',
            controllerAs: 'globalNavCtrl',
            bindToController: {
                searchText: '@'
            },
            scope: {}

        }
    })
    .controller('globalNavController', [
        '$scope', 'eventsService', function ($scope, eventsService) {
            var self = this;

        }
    ]);

// THIS IS A SERVICE. RETURN THINGS HERE
app.service('eventsService', [
    '$http', 'geolocation', function ($http, geoLocation) {
        'use strict';
        var service = this;

        service.$get = function (options) {
            options.params.lat = location_info.lat;
            options.params.lon = location_info.lon;
            return $http.get('/api/events/location', options)
                .then(function (response) {
                    return response;
                });
        };

        service.searchCall = function (text) {
            var requestOptions = {
                params: {}
            };
            if (text && text.length > 0) {
                requestOptions.params.search = text;
            }
            if (location_info.lat === 0) {
                return geoLocation.getLocation()
                    .then(function (data) {
                        location_info.lat = data.coords.latitude;
                        location_info.lon = data.coords.longitude;
                    })
                    .then(function () {
                        return service.$get(requestOptions);
                    });
            } else {
                return service.$get(requestOptions);
            }
        };

        service.get = function get (id) {
            // console.log(id);
            return $http.get('/api/events/id/' + id)
                .then(function (response) {
                    // console.log('singleEvent:', response);
                    return response;
                }, function (error) {
                    // console.log(error);
                });
        };

        service.signUp = function signUp(id, payload) {
            return $http.post('/api/events/signup/' + id, payload);
        }
    }
]);

app.service('createEventService', [
    '$http', function ($http) {
        'use strict';
        var service = this;

        service.createEvent = function (event) {
            event.volunteers_needed = {
                min: event.volunteers_min,
                max: event.volunteers_max
            }
            $http.post('/api/events/', event).then(function (resp) {
                //console.log(resp);
            });
            // console.log('Inside createEvent in Service', event);
        };
    }
]);

// THIS IS A SERVICE. RETURN THINGS HERE
app.service('donationService', [
    '$http', 'geolocation', function ($http, geoLocation) {
        'use strict';
        var service = this;

        service.$get = function (options) {
            options.params.lat = location_info.lat;
            options.params.lon = location_info.lon;
            return $http.get('/api/donations/location', options)
                .then(function (response) {
                    return response;
                }, function (error) {
                    console.log(error);
                });
        };

        service.searchCall = function (text) {
            var requestOptions = {
                params: {}
            };
            if (text && text.length > 0) {
                requestOptions.params.search = text;
            }
            if (location_info.lat === 0) {
                return geoLocation.getLocation()
                    .then(function (data) {
                        location_info.lat = data.coords.latitude;
                        location_info.lon = data.coords.longitude;
                    })
                    .then(function () {
                        return service.$get(requestOptions);
                    });
            } else {
                console.log('skipped lat/lon');
                return service.$get(requestOptions);
            }
        };

        service.get = function get (id) {
            return $http.get('/api/donations/' + id)
                .then(function (response) {
                    console.log('singleDonation:', response);
                    return response;
                }, function (error) {
                    console.log(error);
                });
        };
    }
]);

// END THE SERVICE

ngModule('home', [])
    .directive('homePage', function () {
        return {
            restrict: 'E',
            bindToController: true,
            controller: 'homePageController',
            controllerAs: 'homePageCtrl',
            template: '

{{homePageCtrl.name}}

',
            replace: true,
            scope: {}
        }
    })
    .controller('homePageController', [
        '$http',
        '$scope',
        '$q',
        function ($http, $scope, $q) {
            var self = this,
                response,
                d = $q;
            self.name = 'Home Page View';
        }
    ]);

ngModule('register', [])
    .controller('registerPageController', function () {
       var self = this;
    });

ngModule('about', [])
    .directive('aboutPage', function () {
        return {
            restrict: 'E',
            bindToController: true,
            controller: 'aboutPageController',
            controllerAs: 'aboutPageCtrl',
            template: '

{{aboutPageCtrl.title}}

',
            replace: true,
            scope: {}

        }
    })
    .controller('aboutPageController', [
        '$scope',
        function ($scope) {
            var self = this;
            self.title = 'yay wtf';
            console.log('about page scope');
        }
    ]);

ngModule('events', [])
    .directive('eventsPage', function () {
        return {
            restrict: 'E',
            bindToController: true,
            controller: 'eventsPageController',
            controllerAs: 'eventsPageCtrl',
            template: '

{{eventsPageCtrl.title}}

',
            replace: true,
            scope: {}

        }
    })
    .controller('eventsPageController', [
        '$scope', 'eventsService',
        function ($scope, eventsService) {
            'use strict';
            var self = this;

            $scope.$watch(function () {
                return self.events;
            }, function (data) {
                console.log('data received', data.status);
                if (data && data.status && data.status === 200) {
                    $scope.events = data;
                    setTimeout($scope.$digest, 0);
                    console.log('set timeout for digest', new Date().getTime());
                }
            });

            $scope.runSearch = function (text) {
                console.log('yay text');
                eventsService.searchCall(text).then(function (data) {
                    console.log('received from api', new Date().getTime());
                    self.events = data.data;
                });
            };

            eventsService.searchCall().then(function (data) {
                self.events = data.data;
                console.log('received from api', new Date().getTime());
            });
            self.events = {result: [{description: 'test'}], status: 0};
            $scope.events = self.events;
            console.log('in controller', new Date().getTime());
        }
    ])
    .controller('eventDetailPageController', [
        '$scope', 'eventsService', '$stateParams',
        function ($scope, eventsService, $stateParams) {
            'use strict';
            var self = this;

            $scope.$watch(function () {
                return self.event;
            }, function (data) {
                console.log(data);
                if (data) {
                    $scope.event = data.resp;
                    setTimeout($scope.$digest, 0);
                    console.log('set timeout for digest', new Date().getTime());
                }
            });
            eventsService.get($stateParams.id).then(function (data) {
                self.event = data.data;
                console.log('received from api', new Date().getTime());
            });
            self.event = undefined;
            $scope.event = self.event;

            $scope.input = {
                name: '',
                email: '',
                phone: ''
            };

            $scope.signUp = function signUp(id, userData) {
                console.log('signUp', id);
                eventsService.signUp(id, userData).then(function () {
                    alert('Thanks for signing up');
                });
            }
            console.log('loaded controller', new Date().getTime());
        }
    ]);

ngModule('donate', [])
    .directive('donatePage', function () {
        return {
            restrict: 'E',
            bindToController: true,
            controller: 'donatePageController',
            controllerAs: 'donatePageCtrl',
            replace: true,
            scope: {}

        }
    })
    .controller('donateCategoryPageController', [
        '$scope',
        '$stateParams',
        'donationService',
        function ($scope, $stateParams, donationService) {
            console.log($stateParams);

            var self = this;
                self.category = $stateParams.category;
            $scope.$watch(function () {
                return self.donations;
            }, function (data) {
                if (data && data.status && data.status === 200) {
                    $scope.donations = data;
                    setTimeout($scope.$digest, 0);
                }
            });
            donationService.searchCall().then(function (data) {
                self.donations = data.data;
            });
            $scope.donations = self.donations;

        }
    ])
    .controller('donatePageController', [
        '$scope', 'donationService',
        function ($scope, donationService) {
            'use strict';
            var self = this;
            $scope.$watch(function () {
                return self.donations;
            }, function (data) {
                console.log('data received', data.status);
                if (data && data.status && data.status === 200) {
                    $scope.donations = data;
                    setTimeout($scope.$digest, 0);
                }
            });
            donationService.searchCall().then(function (data) {
                self.donations = data.data;
            });
            self.donations = {result: [{name: 'test'}], status: 0};
            $scope.donations = self.donations;
        }
    ]);

ngModule('myAccount', [])
    .controller('myAccountPageController', [
        '$scope',
        function ($scope) {
            var self = this;
            self.title = 'My Account';
            console.log('my account page scope');
        }
    ]);

ngModule('createEvent', [])
    .directive('create-page', function () {
        return {
            restrict: 'E',
            bindToController: true,
            controller: 'createController',
            controllerAs: 'createController',
            replace: true,
            scope: {}
        }
    })
    .controller('createController', [
        '$scope',
        'createEventService',
        function ($scope, createService) {
            $scope.event = {
                name: '',
                website: '',
                description: '',
                address: '',
                city: '',
                state: '',
                zip:'',
                contact_name: '',
                contact_phone: '',
                contact_email: '',
                volunteers_min: '',
                volunteers_max: '',
                img: '',
                start_date: '',
                end_date: ''
            };
            $scope.createEvent = function (event) {
                console.log('createEvent in controller');
                console.log('passedIn event:', event);
                var event = {
                    name: event.name,
                    website: event.website,
                    description: event.description,
                    address: event.address,
                    city: event.city,
                    state: event.state,
                    zip: event.zip,
                    contact_name: event.contact_name,
                    contact_phone: event.contact_phone,
                    contact_email: event.contact_email,
                    volunteers_min: event.volunteers_min,
                    volunteers_max: event.volunteers_max,
                    img: event.img,
                    start_date: event.start_date,
                    end_date: event.end_date
                };
                createService.createEvent(event);
            }
        }
    ]);

// bootstrapping the application this way avoids clutting up the
// home page with 'ngapp=hrapp'
app.config(function ($stateProvider, $urlRouterProvider) {
    // For any unmatched url, redirect to /state1
    $urlRouterProvider.otherwise("/");
    $stateProvider
        .state('root', {
            url: '/',
            templateUrl: '/views/home.html',
            controller: 'homePageController'
        })
        .state('about', {
            url: '/about',
            templateUrl: '/views/about.html',
            controller: 'aboutPageController'
        })
        .state('donate', {
            url: '/donate',
            templateUrl: '/views/donate.html',
            controller: 'donatePageController'
        })
        .state('donateCategory', {
            url: '/donate/:category',
            templateUrl: '/views/donate-category.html',
            controller: 'donateCategoryPageController'
        })
        .state('events', {
            url: '/events',
            templateUrl: '/views/events.html',
            controller: 'eventsPageController'
        })
        .state('eventsDetail', {
            url: '/events/:id',
            templateUrl: '/views/event-detail.html',
            controller: 'eventDetailPageController'
        })
        .state('my-account', {
            url: '/my-account',
            templateUrl: '/views/my-account.html',
            controller: 'myAccountPageController'
        })
        .state('register',  {
            url: '/register',
            templateUrl: '/views/register.html',
            controller: 'registerPageController'
        })
        .state('createEvent', {
            url: '/create/event',
            templateUrl: '/views/create-event.html',
            controller: 'createController'
        });
});

// bootstrapping the application this way avoids clutting up the
// home page with 'ngapp=hrapp'
angular.element(document).ready(function () {
    angular.bootstrap(document, ['hrApp']);
});
<commit_msg>Update app.js<commit_after>'use strict';
var a = 'Hello world';
console.log(a);

var location_info = {
    lat: 0,
    lon: 0
};

var ngModule = angular.module;
var app = ngModule('hrApp', [
    'home',
    'about',
    'donate',
    'events',
    'globalNav',
    'ui.router',
    'geolocation',
    'createEvent',
    'register'
]);

ngModule('globalNav', [])
    .directive('globalNav', function () {
        return {
            restrict: 'E',
            replace: true,
            templateUrl: '../views/global-nav.html',
            controller: 'globalNavController',
            controllerAs: 'globalNavCtrl',
            bindToController: {
                searchText: '@'
            },
            scope: {}

        }
    })
    .controller('globalNavController', [
        '$scope', 'eventsService', '$location', function ($scope, eventsService, $location) {
            var self = this;
            self.location = $location.$$path;
            if(self.location.includes('/donate')) {
                $scope.donateLink = true;
            }

            if(self.location.includes('/events')) {
                $scope.eventsLink = true;
            }
        }
    ]);

// THIS IS A SERVICE. RETURN THINGS HERE
app.service('eventsService', [
    '$http', 'geolocation', function ($http, geoLocation) {
        'use strict';
        var service = this;

        service.$get = function (options) {
            options.params.lat = location_info.lat;
            options.params.lon = location_info.lon;
            return $http.get('/api/events/location', options)
                .then(function (response) {
                    return response;
                });
        };

        service.searchCall = function (text) {
            var requestOptions = {
                params: {}
            };
            if (text && text.length > 0) {
                requestOptions.params.search = text;
            }
            if (location_info.lat === 0) {
                return geoLocation.getLocation()
                    .then(function (data) {
                        location_info.lat = data.coords.latitude;
                        location_info.lon = data.coords.longitude;
                    })
                    .then(function () {
                        return service.$get(requestOptions);
                    });
            } else {
                return service.$get(requestOptions);
            }
        };

        service.get = function get (id) {
            // console.log(id);
            return $http.get('/api/events/id/' + id)
                .then(function (response) {
                    // console.log('singleEvent:', response);
                    return response;
                }, function (error) {
                    // console.log(error);
                });
        };

        service.signUp = function signUp(id, payload) {
            return $http.post('/api/events/signup/' + id, payload);
        }
    }
]);

app.service('createEventService', [
    '$http', function ($http) {
        'use strict';
        var service = this;

        service.createEvent = function (event) {
            event.volunteers_needed = {
                min: event.volunteers_min,
                max: event.volunteers_max
            }
            $http.post('/api/events/', event).then(function (resp) {
                //console.log(resp);
            });
            // console.log('Inside createEvent in Service', event);
        };
    }
]);

// THIS IS A SERVICE. RETURN THINGS HERE
app.service('donationService', [
    '$http', 'geolocation', function ($http, geoLocation) {
        'use strict';
        var service = this;

        service.$get = function (options) {
            options.params.lat = location_info.lat;
            options.params.lon = location_info.lon;
            return $http.get('/api/donations/location', options)
                .then(function (response) {
                    return response;
                }, function (error) {
                    console.log(error);
                });
        };

        service.searchCall = function (text) {
            var requestOptions = {
                params: {}
            };
            if (text && text.length > 0) {
                requestOptions.params.search = text;
            }
            if (location_info.lat === 0) {
                return geoLocation.getLocation()
                    .then(function (data) {
                        location_info.lat = data.coords.latitude;
                        location_info.lon = data.coords.longitude;
                    })
                    .then(function () {
                        return service.$get(requestOptions);
                    });
            } else {
                console.log('skipped lat/lon');
                return service.$get(requestOptions);
            }
        };

        service.get = function get (id) {
            return $http.get('/api/donations/' + id)
                .then(function (response) {
                    console.log('singleDonation:', response);
                    return response;
                }, function (error) {
                    console.log(error);
                });
        };
    }
]);

// END THE SERVICE

ngModule('home', [])
    .directive('homePage', function () {
        return {
            restrict: 'E',
            bindToController: true,
            controller: 'homePageController',
            controllerAs: 'homePageCtrl',
            template: '

{{homePageCtrl.name}}

',
            replace: true,
            scope: {}
        }
    })
    .controller('homePageController', [
        '$http',
        '$scope',
        '$q',
        function ($http, $scope, $q) {
            var self = this,
                response,
                d = $q;
            self.name = 'Home Page View';
        }
    ]);

ngModule('register', [])
    .controller('registerPageController', function () {
       var self = this;
    });

ngModule('about', [])
    .directive('aboutPage', function () {
        return {
            restrict: 'E',
            bindToController: true,
            controller: 'aboutPageController',
            controllerAs: 'aboutPageCtrl',
            template: '

{{aboutPageCtrl.title}}

',
            replace: true,
            scope: {}

        }
    })
    .controller('aboutPageController', [
        '$scope',
        function ($scope) {
            var self = this;
            self.title = 'yay wtf';
            console.log('about page scope');
        }
    ]);

ngModule('events', [])
    .directive('eventsPage', function () {
        return {
            restrict: 'E',
            bindToController: true,
            controller: 'eventsPageController',
            controllerAs: 'eventsPageCtrl',
            template: '

{{eventsPageCtrl.title}}

',
            replace: true,
            scope: {}

        }
    })
    .controller('eventsPageController', [
        '$scope', 'eventsService',
        function ($scope, eventsService) {
            'use strict';
            var self = this;

            $scope.$watch(function () {
                return self.events;
            }, function (data) {
                console.log('data received', data.status);
                if (data && data.status && data.status === 200) {
                    $scope.events = data;
                    setTimeout($scope.$digest, 0);
                    console.log('set timeout for digest', new Date().getTime());
                }
            });

            $scope.runSearch = function (text) {
                console.log('yay text');
                eventsService.searchCall(text).then(function (data) {
                    console.log('received from api', new Date().getTime());
                    self.events = data.data;
                });
            };

            eventsService.searchCall().then(function (data) {
                self.events = data.data;
                console.log('received from api', new Date().getTime());
            });
            self.events = {result: [{description: 'test'}], status: 0};
            $scope.events = self.events;
            console.log('in controller', new Date().getTime());
        }
    ])
    .controller('eventDetailPageController', [
        '$scope', 'eventsService', '$stateParams',
        function ($scope, eventsService, $stateParams) {
            'use strict';
            var self = this;

            $scope.$watch(function () {
                return self.event;
            }, function (data) {
                console.log(data);
                if (data) {
                    $scope.event = data.resp;
                    setTimeout($scope.$digest, 0);
                    console.log('set timeout for digest', new Date().getTime());
                }
            });
            eventsService.get($stateParams.id).then(function (data) {
                self.event = data.data;
                console.log('received from api', new Date().getTime());
            });
            self.event = undefined;
            $scope.event = self.event;

            $scope.input = {
                name: '',
                email: '',
                phone: ''
            };

            $scope.signUp = function signUp(id, userData) {
                console.log('signUp', id);
                eventsService.signUp(id, userData).then(function () {
                    alert('Thanks for signing up');
                });
            }
            console.log('loaded controller', new Date().getTime());
        }
    ]);

ngModule('donate', [])
    .directive('donatePage', function () {
        return {
            restrict: 'E',
            bindToController: true,
            controller: 'donatePageController',
            controllerAs: 'donatePageCtrl',
            replace: true,
            scope: {}

        }
    })
    .controller('donateCategoryPageController', [
        '$scope',
        '$stateParams',
        'donationService',
        function ($scope, $stateParams, donationService) {
            console.log($stateParams);

            var self = this;
                self.category = $stateParams.category;
            $scope.$watch(function () {
                return self.donations;
            }, function (data) {
                if (data && data.status && data.status === 200) {
                    $scope.donations = data;
                    setTimeout($scope.$digest, 0);
                }
            });
            donationService.searchCall().then(function (data) {
                self.donations = data.data;
            });
            $scope.donations = self.donations;

        }
    ])
    .controller('donatePageController', [
        '$scope', 'donationService',
        function ($scope, donationService) {
            'use strict';
            var self = this;
            $scope.$watch(function () {
                return self.donations;
            }, function (data) {
                console.log('data received', data.status);
                if (data && data.status && data.status === 200) {
                    $scope.donations = data;
                    setTimeout($scope.$digest, 0);
                }
            });
            donationService.searchCall().then(function (data) {
                self.donations = data.data;
            });
            self.donations = {result: [{name: 'test'}], status: 0};
            $scope.donations = self.donations;
        }
    ]);

ngModule('myAccount', [])
    .controller('myAccountPageController', [
        '$scope',
        function ($scope) {
            var self = this;
            self.title = 'My Account';
            console.log('my account page scope');
        }
    ]);

ngModule('createEvent', [])
    .directive('create-page', function () {
        return {
            restrict: 'E',
            bindToController: true,
            controller: 'createController',
            controllerAs: 'createController',
            replace: true,
            scope: {}
        }
    })
    .controller('createController', [
        '$scope',
        'createEventService',
        function ($scope, createService) {
            $scope.event = {
                name: '',
                website: '',
                description: '',
                address: '',
                city: '',
                state: '',
                zip:'',
                contact_name: '',
                contact_phone: '',
                contact_email: '',
                volunteers_min: '',
                volunteers_max: '',
                img: '',
                start_date: '',
                end_date: ''
            };
            $scope.createEvent = function (event) {
                console.log('createEvent in controller');
                console.log('passedIn event:', event);
                var event = {
                    name: event.name,
                    website: event.website,
                    description: event.description,
                    address: event.address,
                    city: event.city,
                    state: event.state,
                    zip: event.zip,
                    contact_name: event.contact_name,
                    contact_phone: event.contact_phone,
                    contact_email: event.contact_email,
                    volunteers_min: event.volunteers_min,
                    volunteers_max: event.volunteers_max,
                    img: event.img,
                    start_date: event.start_date,
                    end_date: event.end_date
                };
                createService.createEvent(event);
            }
        }
    ]);

// bootstrapping the application this way avoids clutting up the
// home page with 'ngapp=hrapp'
app.config(function ($stateProvider, $urlRouterProvider) {
    // For any unmatched url, redirect to /state1
    $urlRouterProvider.otherwise("/");
    $stateProvider
        .state('root', {
            url: '/',
            templateUrl: '/views/home.html',
            controller: 'homePageController'
        })
        .state('about', {
            url: '/about',
            templateUrl: '/views/about.html',
            controller: 'aboutPageController'
        })
        .state('donate', {
            url: '/donate',
            templateUrl: '/views/donate.html',
            controller: 'donatePageController'
        })
        .state('donateCategory', {
            url: '/donate/:category',
            templateUrl: '/views/donate-category.html',
            controller: 'donateCategoryPageController'
        })
        .state('events', {
            url: '/events',
            templateUrl: '/views/events.html',
            controller: 'eventsPageController'
        })
        .state('eventsDetail', {
            url: '/events/:id',
            templateUrl: '/views/event-detail.html',
            controller: 'eventDetailPageController'
        })
        .state('my-account', {
            url: '/my-account',
            templateUrl: '/views/my-account.html',
            controller: 'myAccountPageController'
        })
        .state('register',  {
            url: '/register',
            templateUrl: '/views/register.html',
            controller: 'registerPageController'
        })
        .state('createEvent', {
            url: '/create/event',
            templateUrl: '/views/create-event.html',
            controller: 'createController'
        });
});

// bootstrapping the application this way avoids clutting up the
// home page with 'ngapp=hrapp'
angular.element(document).ready(function () {
    angular.bootstrap(document, ['hrApp']);
});
<|endoftext|>


<commit_before>function makeMap() {
  var commonStyles = { "color": "#111111", "weight": 1, "opacity": 0.65, "fillOpacity": 0.5 }
  var claimStyles = {
    claimed_by_you: $.extend({}, commonStyles, { "fillColor": "#9d5fa7", "fillOpacity": 0.8 }),
    claimed: $.extend({}, commonStyles, { "fillColor": "#d5545a", "fillOpacity": 0.8 }),
    quarantine: $.extend({}, commonStyles, { "fillColor": "#6dbd4b", "fillOpacity": 0.8 }),
    firstQuartile: $.extend({}, commonStyles, { "fillColor": "#eff3ff" }),
    secondQuartile: $.extend({}, commonStyles, { "fillColor": "#bdd7e7" }),
    thirdQuartile: $.extend({}, commonStyles, { "fillColor": "#6baed6" }),
    fourthQuartile: $.extend({}, commonStyles, { "fillColor": "#2171b5" }),
  }

  var map = L.map('map');

  var mesh_layer; //Rendered map
  var last_update_bounds;
  var last_update_centroid;

  var tileLayer = L.tileLayer('http://{s}.tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png', {
    attribution: '© OpenStreetMap contributors'
  }).addTo(map);

  $('#address_search_form').submit(function (event) {
    event.preventDefault();
    FitPcode($('#address_search').val());
  });

  var FitPcode = function (pcode) {
    $.getJSON('/pcode_get_bounds?pcode=' + pcode, function (json) {
      if (json) {
        map.fitBounds([[json.swlat, json.swlng], [json.nelat, json.nelng]])
      }
      else { alert("Postcode not found"); }
    });
  };

  var FindLocation = function () {
    var lat = Cookies.get("lat");
    var lng = Cookies.get("lng");
    var pcode = Cookies.get("postcode");
    if (lat && lng) {
      var zoom = Cookies.get("zoom");
      if (zoom) {
        map.setView([lat, lng], zoom)
      }
      else {
        map.setView([lat, lng], 15)
      }
    }
    else if (pcode) {
      FitPcode(pcode)
    }
    else {
      var australia_coord = [-29.8650, 131.2094];
      map.setView(australia_coord, 5);
    }
  };

  FindLocation();

  function priorityStyles(feature) {
    var propensity = feature.properties.avg_swing_propensity
    if (propensity < 0.2625) return claimStyles.firstQuartile
    if (propensity < 0.3250) return claimStyles.secondQuartile
    if (propensity < 0.3875) return claimStyles.thirdQuartile
    return claimStyles.fourthQuartile
  }

  function addGeoJsonProperties(json) {

    var layer = L.geoJson(json, {
      style: function (feature) {
        switch (feature.properties.claim_status) {
          case 'claimed_by_you': return claimStyles.claimed_by_you
          case 'claimed': return claimStyles.claimed
          case 'quarantine': return claimStyles.quarantine
          default: return priorityStyles(feature)
        }
      },
      onEachFeature: function (feature, featureLayer) {
        featureLayer._leaflet_id = feature.properties.slug;

        function downloadmesh(mesh_id) {
          var campaign = $('#campaign').val();
          var url = LAMBDA_BASE_URL + '/map?slug=' + mesh_id + '&campaign=' + campaign;
          var base64str = $.get(url, function (base64str) {
            if (base64str.message == "Internal server error") {
              return alert("This area cannot be downloaded due to a pdf rendering error, please try another area.");
            };
            //decode base64 string
            var binary = atob(base64str.base64.replace(/\s/g, ''));
            var len = binary.length;
            var buffer = new ArrayBuffer(len);
            var view = new Uint8Array(buffer);
            for (var i = 0; i < len; i++) {
              view[i] = binary.charCodeAt(i);
            }

            //create the blob object
            var blob = new Blob([view], { type: "application/pdf" });

            //create clickable URL for download
            var url = window.URL.createObjectURL(blob);
            var a = document.createElement('a');
            a.href = url;
            a.download = mesh_id + '.pdf';
            a.click();
            $('#load').addClass('hidden');
          })
        };

        this.btnClaim = function (featureLayer) {
          var leaflet_id = this._leaflet_id;
          $.post("/claim_meshblock/" + leaflet_id);
          $('.unclaim').removeClass('hidden');
          $('.download').removeClass('hidden');
          $('.claim').addClass('hidden');
          if ($("#map").data("is-admin") === true) {
            this.setStyle(claimStyles.quarantine)
          } else {
            this.setStyle(claimStyles.claimed_by_you)
          }
          $('#load').removeClass('hidden');
          downloadmesh(leaflet_id);
        }

        this.btnUnclaim = function (featureLayer) {
          $.post("/unclaim_meshblock/" + this._leaflet_id);
          this.setStyle(claimStyles.firstQuartile)
          $('.unclaim').addClass('hidden');
          $('.download').addClass('hidden');
          $('.claim').removeClass('hidden');
        }

        this.btnDownload = function (featureLayer) {
          var leaflet_id = this._leaflet_id;
          $('#load').removeClass('hidden');
          downloadmesh(leaflet_id);
        }

        function create_popup_btn(container, div_class, btn_text_inner, faq_text_inner) {
          var grpdiv = L.DomUtil.create('div', 'popupgrp hidden ' + div_class, container)
          var txtdiv = L.DomUtil.create('div', 'popuptxt txt' + div_class, grpdiv)
          txtdiv.innerHTML = faq_text_inner
          var btndiv = L.DomUtil.create('div', 'popupbutton btn' + div_class, grpdiv)
          var btn = L.DomUtil.create('button', '', btndiv)
          btn.setAttribute('type', 'button')
          btn.setAttribute('name', div_class)
          btn.innerHTML = btn_text_inner
          var btndom = L.DomEvent
          btndom.addListener(btn, 'click', L.DomEvent.stopPropagation)
          btndom.addListener(btn, 'click', L.DomEvent.preventDefault)
          return { grpdiv, btn, btndom }
        };

        var container = L.DomUtil.create('div')
        var claimout = create_popup_btn(container, 'claim', 'Claim + Download',
          'Click to claim area and download PDF of addresses to doorknock.
');
        claimout.btndom.addListener(claimout.btn, 'click', this.btnClaim, featureLayer);
        var unclaimout = create_popup_btn(container, 'unclaim', 'Unclaim',
          'Click to remove your claim on this area.
');
        unclaimout.btndom.addListener(unclaimout.btn, 'click', this.btnUnclaim, featureLayer);
        var downloadout = create_popup_btn(container, 'download', 'Download',
          'Click to download your claimed area.
')
        downloadout.btndom.addListener(downloadout.btn, 'click', this.btnDownload, featureLayer);
        var otherstxtcontainer = L.DomUtil.create('div', 'popuptxt hidden otherstext', container)
        otherstxtcontainer.innerHTML = 'This area is claimed by someone else and is unable to be claimed.'
        var quarantinetxtcontainer = L.DomUtil.create('div', 'popuptxt hidden quarantinetext', container)
        quarantinetxtcontainer.innerHTML = 'This area is coordinated by a central event. ' +
          'Click here to find it.';
        if (feature.properties.claim_status === 'claimed_by_you') {
          L.DomUtil.removeClass(unclaimout.grpdiv, 'hidden');
          L.DomUtil.removeClass(downloadout.grpdiv, 'hidden');
          var popup = L.popup({}, featureLayer).setContent(container);
        }
        else if (feature.properties.claim_status === 'claimed') {
          L.DomUtil.removeClass(otherstxtcontainer, 'hidden');
          var popup = L.popup({}, featureLayer).setContent(container);
        }
        else if (feature.properties.claim_status === 'quarantine') {
          if ($("#map").data("is-admin") === true) {
            L.DomUtil.removeClass(unclaimout.grpdiv, 'hidden');
            L.DomUtil.removeClass(downloadout.grpdiv, 'hidden');
          } else {
            L.DomUtil.removeClass(quarantinetxtcontainer, 'hidden');
          }
          var popup = L.popup({}, featureLayer).setContent(container);
        }
        else {
          L.DomUtil.removeClass(claimout.grpdiv, 'hidden');
          var popup = L.popup({}, featureLayer).setContent(container);
        }
        featureLayer.bindPopup(popup)

      }
    });

    return layer;
  };

  function getMeshblockCallback(json) {
    last_update_bounds = map.getBounds()
    last_update_centroid = map.getCenter()
    if (mesh_layer) { map.removeLayer(mesh_layer) }
    mesh_layer = addGeoJsonProperties(json)
    mesh_layer.addTo(map)
    $('#load').addClass('hidden')
  };

  var instruct = L.control();
  instruct.onAdd = function (map) {
    this._div = L.DomUtil.create('div', 'instruct');
    this._div.innerHTML = "Zoom in further to load doorknockable areas.";
    this.update();
    return this._div;
  }

  instruct.update = function () {
    $(".instruct").toggleClass('hidden', map.getZoom() > 14)
  }

  instruct.addTo(map);

  function updateMap() {
    var distance_moved, reload_dist
    var lat_lng_bnd = map.getBounds();
    var lat_lng_centroid = map.getCenter();
    Cookies.set("lat", lat_lng_centroid.lat);
    Cookies.set("lng", lat_lng_centroid.lng);
    if (last_update_centroid) {
      distance_moved = lat_lng_centroid.distanceTo(last_update_centroid)
    } else {
      distance_moved = 201
    }
    var zoom = map.getZoom();
    if (zoom > 14) {
      reload_dist = 1000 / (zoom - 14);
    } else {
      reload_dist = 0;
    }
    Cookies.set("zoom", zoom);

    //Reload map if zoom not too high
    //Distance moved is not short
    //and
    //there is no last_update or the current map bounds are not within the last update's
    if (zoom > 14 && (!last_update_bounds || distance_moved > reload_dist) &&
      (!last_update_bounds || !last_update_bounds.contains(lat_lng_bnd))) {
      $('#load').removeClass('hidden');

      var data = {
        sey: lat_lng_bnd.getSouthWest().lat,
        sex: lat_lng_bnd.getSouthWest().lng,
        nwy: lat_lng_bnd.getNorthEast().lat,
        nwx: lat_lng_bnd.getNorthEast().lng,
      }

      $.getJSON('/meshblocks_bounds', data, getMeshblockCallback)
        .fail(function () {
          $('#load').addClass('hidden')
        })
    }
    instruct.update()
  }

  map.on('moveend', function () {
    updateMap();
  });

  var legend = L.control({ position: 'bottomright' });

  legend.onAdd = function (map) {
    var div = L.DomUtil.create('div', 'legend');
    div.innerHTML = [
      '
Higher Priority
',
      '
Lower Priority
',
      '
Claimed
',
      '
My area
',
      '
Organised event
',
    ].join('');
    return div;
  }

  legend.addTo(map);
  map.whenReady(updateMap);
}

function windowHeight() {
  if (window.innerHeight != undefined) return window.innerHeight;
  var B = document.body, D = document.documentElement;
  return Math.max(B.clientHeight, D.clientHeight);
}
var headerHeight = $('.header').height();

var LAMBDA_BASE_URL = $("#map").data("lambda-base-url");
$('#map').height(windowHeight() - headerHeight);
$('#map').width("100%");
makeMap();

function openHelp() {
  $('#dialog').dialog({
    minWidth: 800,
    width: 800,
    height: Math.min(windowHeight() - headerHeight - 200, 800),
    beforeClose: function () { $('#dialog').addClass('hidden') }
  });
  $('#dialog').dialog({ position: { my: 'center top', at: 'center top+15%', of: window } });
  $('#dialog').removeClass('hidden');
  try { window.localStorage.setItem('helpSeen', 'true') } catch (_) { }
};
$('#faqlink').click(openHelp);

var helpSeen = 'false';
try { helpSeen = window.localStorage.getItem('helpSeen') } catch (_) { }
if (helpSeen !== 'true') $(window).load(openHelp);
<commit_msg>Incorporate linear doors remaining ratio into priority<commit_after>function makeMap() {
  var commonStyles = { "color": "#111111", "weight": 1, "opacity": 0.65, "fillOpacity": 0.5 }
  var claimStyles = {
    claimed_by_you: $.extend({}, commonStyles, { "fillColor": "#9d5fa7", "fillOpacity": 0.8 }),
    claimed: $.extend({}, commonStyles, { "fillColor": "#d5545a", "fillOpacity": 0.8 }),
    quarantine: $.extend({}, commonStyles, { "fillColor": "#6dbd4b", "fillOpacity": 0.8 }),
    firstQuartile: $.extend({}, commonStyles, { "fillColor": "#eff3ff" }),
    secondQuartile: $.extend({}, commonStyles, { "fillColor": "#bdd7e7" }),
    thirdQuartile: $.extend({}, commonStyles, { "fillColor": "#6baed6" }),
    fourthQuartile: $.extend({}, commonStyles, { "fillColor": "#2171b5" }),
  }

  var map = L.map('map');

  var mesh_layer; //Rendered map
  var last_update_bounds;
  var last_update_centroid;

  var tileLayer = L.tileLayer('http://{s}.tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png', {
    attribution: '© OpenStreetMap contributors'
  }).addTo(map);

  $('#address_search_form').submit(function (event) {
    event.preventDefault();
    FitPcode($('#address_search').val());
  });

  var FitPcode = function (pcode) {
    $.getJSON('/pcode_get_bounds?pcode=' + pcode, function (json) {
      if (json) {
        map.fitBounds([[json.swlat, json.swlng], [json.nelat, json.nelng]])
      }
      else { alert("Postcode not found"); }
    });
  };

  var FindLocation = function () {
    var lat = Cookies.get("lat");
    var lng = Cookies.get("lng");
    var pcode = Cookies.get("postcode");
    if (lat && lng) {
      var zoom = Cookies.get("zoom");
      if (zoom) {
        map.setView([lat, lng], zoom)
      }
      else {
        map.setView([lat, lng], 15)
      }
    }
    else if (pcode) {
      FitPcode(pcode)
    }
    else {
      var australia_coord = [-29.8650, 131.2094];
      map.setView(australia_coord, 5);
    }
  };

  FindLocation();

  function normalise(val, min, max) { return (val - min) / (max - min) }

  function priorityStyles(feature) {
    var propensity = normalise(feature.properties.avg_swing_propensity, 0.2, 0.45) // observed range
    var doors_knocked = feature.properties.outcomes_recorded || 0
    var total_doors = feature.properties.total_addresses_on_block || 1
    var priority = propensity * (1 - doors_knocked / total_doors)
    if (priority <= 0.25) return claimStyles.firstQuartile
    if (priority <= 0.50) return claimStyles.secondQuartile
    if (priority <= 0.75) return claimStyles.thirdQuartile
    return claimStyles.fourthQuartile
  }

  function addGeoJsonProperties(json) {

    var layer = L.geoJson(json, {
      style: function (feature) {
        switch (feature.properties.claim_status) {
          case 'claimed_by_you': return claimStyles.claimed_by_you
          case 'claimed': return claimStyles.claimed
          case 'quarantine': return claimStyles.quarantine
          default: return priorityStyles(feature)
        }
      },
      onEachFeature: function (feature, featureLayer) {
        featureLayer._leaflet_id = feature.properties.slug;

        function downloadmesh(mesh_id) {
          var campaign = $('#campaign').val();
          var url = LAMBDA_BASE_URL + '/map?slug=' + mesh_id + '&campaign=' + campaign;
          var base64str = $.get(url, function (base64str) {
            if (base64str.message == "Internal server error") {
              return alert("This area cannot be downloaded due to a pdf rendering error, please try another area.");
            };
            //decode base64 string
            var binary = atob(base64str.base64.replace(/\s/g, ''));
            var len = binary.length;
            var buffer = new ArrayBuffer(len);
            var view = new Uint8Array(buffer);
            for (var i = 0; i < len; i++) {
              view[i] = binary.charCodeAt(i);
            }

            //create the blob object
            var blob = new Blob([view], { type: "application/pdf" });

            //create clickable URL for download
            var url = window.URL.createObjectURL(blob);
            var a = document.createElement('a');
            a.href = url;
            a.download = mesh_id + '.pdf';
            a.click();
            $('#load').addClass('hidden');
          })
        };

        this.btnClaim = function (featureLayer) {
          var leaflet_id = this._leaflet_id;
          $.post("/claim_meshblock/" + leaflet_id);
          $('.unclaim').removeClass('hidden');
          $('.download').removeClass('hidden');
          $('.claim').addClass('hidden');
          if ($("#map").data("is-admin") === true) {
            this.setStyle(claimStyles.quarantine)
          } else {
            this.setStyle(claimStyles.claimed_by_you)
          }
          $('#load').removeClass('hidden');
          downloadmesh(leaflet_id);
        }

        this.btnUnclaim = function (featureLayer) {
          $.post("/unclaim_meshblock/" + this._leaflet_id);
          this.setStyle(claimStyles.firstQuartile)
          $('.unclaim').addClass('hidden');
          $('.download').addClass('hidden');
          $('.claim').removeClass('hidden');
        }

        this.btnDownload = function (featureLayer) {
          var leaflet_id = this._leaflet_id;
          $('#load').removeClass('hidden');
          downloadmesh(leaflet_id);
        }

        function create_popup_btn(container, div_class, btn_text_inner, faq_text_inner) {
          var grpdiv = L.DomUtil.create('div', 'popupgrp hidden ' + div_class, container)
          var txtdiv = L.DomUtil.create('div', 'popuptxt txt' + div_class, grpdiv)
          txtdiv.innerHTML = faq_text_inner
          var btndiv = L.DomUtil.create('div', 'popupbutton btn' + div_class, grpdiv)
          var btn = L.DomUtil.create('button', '', btndiv)
          btn.setAttribute('type', 'button')
          btn.setAttribute('name', div_class)
          btn.innerHTML = btn_text_inner
          var btndom = L.DomEvent
          btndom.addListener(btn, 'click', L.DomEvent.stopPropagation)
          btndom.addListener(btn, 'click', L.DomEvent.preventDefault)
          return { grpdiv, btn, btndom }
        };

        var container = L.DomUtil.create('div')
        var claimout = create_popup_btn(container, 'claim', 'Claim + Download',
          'Click to claim area and download PDF of addresses to doorknock.
');
        claimout.btndom.addListener(claimout.btn, 'click', this.btnClaim, featureLayer);
        var unclaimout = create_popup_btn(container, 'unclaim', 'Unclaim',
          'Click to remove your claim on this area.
');
        unclaimout.btndom.addListener(unclaimout.btn, 'click', this.btnUnclaim, featureLayer);
        var downloadout = create_popup_btn(container, 'download', 'Download',
          'Click to download your claimed area.
')
        downloadout.btndom.addListener(downloadout.btn, 'click', this.btnDownload, featureLayer);
        var otherstxtcontainer = L.DomUtil.create('div', 'popuptxt hidden otherstext', container)
        otherstxtcontainer.innerHTML = 'This area is claimed by someone else and is unable to be claimed.'
        var quarantinetxtcontainer = L.DomUtil.create('div', 'popuptxt hidden quarantinetext', container)
        quarantinetxtcontainer.innerHTML = 'This area is coordinated by a central event. ' +
          'Click here to find it.';
        if (feature.properties.claim_status === 'claimed_by_you') {
          L.DomUtil.removeClass(unclaimout.grpdiv, 'hidden');
          L.DomUtil.removeClass(downloadout.grpdiv, 'hidden');
          var popup = L.popup({}, featureLayer).setContent(container);
        }
        else if (feature.properties.claim_status === 'claimed') {
          L.DomUtil.removeClass(otherstxtcontainer, 'hidden');
          var popup = L.popup({}, featureLayer).setContent(container);
        }
        else if (feature.properties.claim_status === 'quarantine') {
          if ($("#map").data("is-admin") === true) {
            L.DomUtil.removeClass(unclaimout.grpdiv, 'hidden');
            L.DomUtil.removeClass(downloadout.grpdiv, 'hidden');
          } else {
            L.DomUtil.removeClass(quarantinetxtcontainer, 'hidden');
          }
          var popup = L.popup({}, featureLayer).setContent(container);
        }
        else {
          L.DomUtil.removeClass(claimout.grpdiv, 'hidden');
          var popup = L.popup({}, featureLayer).setContent(container);
        }
        featureLayer.bindPopup(popup)

      }
    });

    return layer;
  };

  function getMeshblockCallback(json) {
    last_update_bounds = map.getBounds()
    last_update_centroid = map.getCenter()
    if (mesh_layer) { map.removeLayer(mesh_layer) }
    mesh_layer = addGeoJsonProperties(json)
    mesh_layer.addTo(map)
    $('#load').addClass('hidden')
  };

  var instruct = L.control();
  instruct.onAdd = function (map) {
    this._div = L.DomUtil.create('div', 'instruct');
    this._div.innerHTML = "Zoom in further to load doorknockable areas.";
    this.update();
    return this._div;
  }

  instruct.update = function () {
    $(".instruct").toggleClass('hidden', map.getZoom() > 14)
  }

  instruct.addTo(map);

  function updateMap() {
    var distance_moved, reload_dist
    var lat_lng_bnd = map.getBounds();
    var lat_lng_centroid = map.getCenter();
    Cookies.set("lat", lat_lng_centroid.lat);
    Cookies.set("lng", lat_lng_centroid.lng);
    if (last_update_centroid) {
      distance_moved = lat_lng_centroid.distanceTo(last_update_centroid)
    } else {
      distance_moved = 201
    }
    var zoom = map.getZoom();
    if (zoom > 14) {
      reload_dist = 1000 / (zoom - 14);
    } else {
      reload_dist = 0;
    }
    Cookies.set("zoom", zoom);

    //Reload map if zoom not too high
    //Distance moved is not short
    //and
    //there is no last_update or the current map bounds are not within the last update's
    if (zoom > 14 && (!last_update_bounds || distance_moved > reload_dist) &&
      (!last_update_bounds || !last_update_bounds.contains(lat_lng_bnd))) {
      $('#load').removeClass('hidden');

      var data = {
        sey: lat_lng_bnd.getSouthWest().lat,
        sex: lat_lng_bnd.getSouthWest().lng,
        nwy: lat_lng_bnd.getNorthEast().lat,
        nwx: lat_lng_bnd.getNorthEast().lng,
      }

      $.getJSON('/meshblocks_bounds', data, getMeshblockCallback)
        .fail(function () {
          $('#load').addClass('hidden')
        })
    }
    instruct.update()
  }

  map.on('moveend', function () {
    updateMap();
  });

  var legend = L.control({ position: 'bottomright' });

  legend.onAdd = function (map) {
    var div = L.DomUtil.create('div', 'legend');
    div.innerHTML = [
      '
Higher Priority
',
      '
Lower Priority
',
      '
Claimed
',
      '
My area
',
      '
Organised event
',
    ].join('');
    return div;
  }

  legend.addTo(map);
  map.whenReady(updateMap);
}

function windowHeight() {
  if (window.innerHeight != undefined) return window.innerHeight;
  var B = document.body, D = document.documentElement;
  return Math.max(B.clientHeight, D.clientHeight);
}
var headerHeight = $('.header').height();

var LAMBDA_BASE_URL = $("#map").data("lambda-base-url");
$('#map').height(windowHeight() - headerHeight);
$('#map').width("100%");
makeMap();

function openHelp() {
  $('#dialog').dialog({
    minWidth: 800,
    width: 800,
    height: Math.min(windowHeight() - headerHeight - 200, 800),
    beforeClose: function () { $('#dialog').addClass('hidden') }
  });
  $('#dialog').dialog({ position: { my: 'center top', at: 'center top+15%', of: window } });
  $('#dialog').removeClass('hidden');
  try { window.localStorage.setItem('helpSeen', 'true') } catch (_) { }
};
$('#faqlink').click(openHelp);

var helpSeen = 'false';
try { helpSeen = window.localStorage.getItem('helpSeen') } catch (_) { }
if (helpSeen !== 'true') $(window).load(openHelp);
<|endoftext|>


<commit_before>'use strict';
/*global json2html*/
/*global Swipe*/
/*global UI*/
/*global App*/
/*global getID*/
/*global getClass*/

UI.FeedPage= function(elem){
	var element = elem;
	document.addEventListener('reloadFeed', function(e){displayContentItems(e);});

	var displayContentItems = function(e) {
		var tempHTML = '';
		//var feedData = e.detail;
		var feedData = App.postman.show();
		feedData.forEach(function (elem) {
			//console.log(elem.comments);
			elem.pages = [];
			var wordArray = [];
			var wordsTo300 = [];
			wordArray = elem.body.split(' ');
			do{
				var tempTo300 = '';
				do {
					tempTo300 += wordArray.shift() + ' ';
				} while (tempTo300.length <= 300 && wordArray.length > 0);
				wordsTo300.push(tempTo300);
			} while (wordArray.length > 0);

			for(var rep = 0;rep < wordsTo300.length;rep ++){
				elem.pages.push({body: wordsTo300[rep]});
			}
			tempHTML += json2html.transform(elem, mainTemplate);
		});
		element.innerHTML = tempHTML;
		buildSlider();
		commentHandlers();
		fakeBuildNavDrawer(feedData);
		var feedMode = new CustomEvent('feedMode', {});
		document.dispatchEvent(feedMode);
	};

	var buildSlider = function(){
		function sliderCallback(pos, elem){
			var _id = elem.parentElement.parentElement.id.replace('post-', '');
			var bullets = document.querySelector('[id^=pagination-' + _id +']').getElementsByTagName('li');
			var j = bullets.length;
			while (j--) {
				bullets[j].className = ' ';
			}
			bullets[pos].className = 'on';
		}

		var sliders = document.querySelectorAll('[id^=post-]');
		for(var i=0;i<sliders.length;i++) {
			window.mySwipe = Swipe(sliders[i], {
				startSlide: 0,
				//auto: 3000,
				continuous: false,
				disableScroll: false,
				stopPropagation: true,
				callback: sliderCallback,
				transitionEnd: function(index, element) {}
			});
		}
	};

	var commentHandlers = function(){
		function switchButtonClasses(id){
			if(!id){return;}
			//get all the comment buttons
			var tempComments = getID('comments-' + id);
			if(tempComments.className === 'comments line'){
				tempComments.className = 'comments line active';
			} else {
				tempComments.className = 'comments line';
			}
		}
		element.addEventListener('click', function(e){
			switchButtonClasses(e.target.dataset.id);
		});
	};

	var fakeBuildNavDrawer = function(template){
		var numAlerts, numTracked, rep;
		var alerts = [];
		var tracked = [];
		var templateLength = template.length;
		numAlerts = ((Math.random() * 3) << 0) + 2;
		numTracked = ((Math.random() * 3) << 0) + 2;
		for(rep = 0;rep < numAlerts;rep ++){
			alerts.push(template[(Math.random() * templateLength) <<0]);
		}
		for(rep = 0;rep < numTracked;rep ++){
			tracked.push(template[(Math.random() * templateLength) <<0]);
		}

		var refillNavDrawer = new CustomEvent('refillNavDrawer', {detail: {alerts: alerts, tracked: tracked}});
		document.dispatchEvent(refillNavDrawer);
	};

	var mainTemplate = {
		'tag':'article',
		'class':'missedConnection line post',
		'html':'
from: ${tempname}
',
		'children' : [
			{
				'tag':'h2',
				'html':'${title}',
				'data-id': '${_id}',
				'class':'title line'
			},
			{
				'tag':'section',
				'id':'post-${_id}',
				'children': [
					{
						'tag':'ul',
						'class':'post-wrap line',
						'children' : function(){
							return(json2html.transform(this.pages, pageMicroTemplate));
						}
					}
				],
			},
			{
				'tag':'nav',
				'id':'pagination-${_id}',
				'class':'line',
				'children' : [
					{
						'tag' : 'ul',
						'children' : function(){
							var out = [];
							for(var rep=0;rep<this.pages.length;rep++){
								out.push(rep === 0 ? {class: 'on'} : {});
							}
							return(json2html.transform(out, bulletMicroTemplate));
						}
					}
				]
			},
			{
				'tag' : 'div',
				id: 'comments-${_id}',
				'class' :'comments line',
				'html' :
					'<form class="comment-box" method="post" action="api/v1/comments/${_id}">'+
						'Submit a comment'+
						'<textarea class="comment-out" name="body"></textarea>'+
						'<button data-id=${_id} class="submit-comment" type="submit" value="send-comment" onclick="App.postman.comment(this.parentElement.children[1].value, this.dataset.id)">Submit A Comment</button>'+'</form>',
				'children' : [
					{
						'tag' : 'ul',
						'children' : [
							{
								'tag' : 'li',
								'children' : function(){
									return(json2html.transform(this.comments, commentMicroTemplate));
								}
							}
						]
					}
				]
			},
			{
				'tag':'footer',
				'class':'gesturebar line',
				'children': [
					{
						'tag':'div',
						'class':'vote',
						'children': [
							{
								'tag':'button',
								'class':'upvote',
								'title':'up vote',
								'html':''
							},
							{
								'tag':'button',
								'class': 'downvote',
								'title':'down vote',
								'html':''
							}
						]
					},
					{
						'tag':'button',
						'class':'viewComment',
						'data-id': '${_id}',
						'title':'comment',
						'html':''
					}
				]
			}
		]
	};

	var commentMicroTemplate = {
		'tag':'div',
		'data-id':'${_id}',
		'children': [
			{
				'tag':'h5',
				'html':'${tempname}'
			},
			{
				'tag':'p',
				'html':'${body}'
			}
		]
	};

	var pageMicroTemplate = {
		tag: 'li',
		html: '${body}'
	};

	var bulletMicroTemplate = {
		tag: 'li',
		class: '${class}'
	};
};
<commit_msg>fixed commenthandler again, fucking git<commit_after>'use strict';
/*global json2html*/
/*global Swipe*/
/*global UI*/
/*global App*/
/*global getID*/
/*global getClass*/

UI.FeedPage= function(elem){
	var element = elem;
	document.addEventListener('reloadFeed', function(e){displayContentItems(e);});

	var displayContentItems = function(e) {
		var tempHTML = '';
		//var feedData = e.detail;
		var feedData = App.postman.show();
		feedData.forEach(function (elem) {
			//console.log(elem.comments);
			elem.pages = [];
			var wordArray = [];
			var wordsTo300 = [];
			wordArray = elem.body.split(' ');
			do{
				var tempTo300 = '';
				do {
					tempTo300 += wordArray.shift() + ' ';
				} while (tempTo300.length <= 300 && wordArray.length > 0);
				wordsTo300.push(tempTo300);
			} while (wordArray.length > 0);

			for(var rep = 0;rep < wordsTo300.length;rep ++){
				elem.pages.push({body: wordsTo300[rep]});
			}
			tempHTML += json2html.transform(elem, mainTemplate);
		});
		element.innerHTML = tempHTML;
		buildSlider();
		commentHandlers();
		fakeBuildNavDrawer(feedData);
		var feedMode = new CustomEvent('feedMode', {});
		document.dispatchEvent(feedMode);
	};

	var buildSlider = function(){
		function sliderCallback(pos, elem){
			var _id = elem.parentElement.parentElement.id.replace('post-', '');
			var bullets = document.querySelector('[id^=pagination-' + _id +']').getElementsByTagName('li');
			var j = bullets.length;
			while (j--) {
				bullets[j].className = ' ';
			}
			bullets[pos].className = 'on';
		}

		var sliders = document.querySelectorAll('[id^=post-]');
		for(var i=0;i<sliders.length;i++) {
			window.mySwipe = Swipe(sliders[i], {
				startSlide: 0,
				//auto: 3000,
				continuous: false,
				disableScroll: false,
				stopPropagation: true,
				callback: sliderCallback,
				transitionEnd: function(index, element) {}
			});
		}
	};

	var commentHandlers = function(){
		element.addEventListener('click', function(e){
			var id = e.targetdataset.id;
			if(!id){return;}
			//get all the comment buttons
			var tempComments = getID('comments-' + id);
			if(tempComments.className === 'comments line'){
				tempComments.className = 'comments line active';
			} else {
				tempComments.className = 'comments line';
			}
		});
	};

	var fakeBuildNavDrawer = function(template){
		var numAlerts, numTracked, rep;
		var alerts = [];
		var tracked = [];
		var templateLength = template.length;
		numAlerts = ((Math.random() * 3) << 0) + 2;
		numTracked = ((Math.random() * 3) << 0) + 2;
		for(rep = 0;rep < numAlerts;rep ++){
			alerts.push(template[(Math.random() * templateLength) <<0]);
		}
		for(rep = 0;rep < numTracked;rep ++){
			tracked.push(template[(Math.random() * templateLength) <<0]);
		}

		var refillNavDrawer = new CustomEvent('refillNavDrawer', {detail: {alerts: alerts, tracked: tracked}});
		document.dispatchEvent(refillNavDrawer);
	};

	var mainTemplate = {
		'tag':'article',
		'class':'missedConnection line post',
		'html':'
from: ${tempname}
',
		'children' : [
			{
				'tag':'h2',
				'html':'${title}',
				'data-id': '${_id}',
				'class':'title line'
			},
			{
				'tag':'section',
				'id':'post-${_id}',
				'children': [
					{
						'tag':'ul',
						'class':'post-wrap line',
						'children' : function(){
							return(json2html.transform(this.pages, pageMicroTemplate));
						}
					}
				],
			},
			{
				'tag':'nav',
				'id':'pagination-${_id}',
				'class':'line',
				'children' : [
					{
						'tag' : 'ul',
						'children' : function(){
							var out = [];
							for(var rep=0;rep<this.pages.length;rep++){
								out.push(rep === 0 ? {class: 'on'} : {});
							}
							return(json2html.transform(out, bulletMicroTemplate));
						}
					}
				]
			},
			{
				'tag' : 'div',
				id: 'comments-${_id}',
				'class' :'comments line',
				'html' :
					'<form class="comment-box" method="post" action="api/v1/comments/${_id}">'+
						'Submit a comment'+
						'<textarea class="comment-out" name="body"></textarea>'+
						'<button data-id=${_id} class="submit-comment" type="submit" value="send-comment" onclick="App.postman.comment(this.parentElement.children[1].value, this.dataset.id)">Submit A Comment</button>'+'</form>',
				'children' : [
					{
						'tag' : 'ul',
						'children' : [
							{
								'tag' : 'li',
								'children' : function(){
									return(json2html.transform(this.comments, commentMicroTemplate));
								}
							}
						]
					}
				]
			},
			{
				'tag':'footer',
				'class':'gesturebar line',
				'children': [
					{
						'tag':'div',
						'class':'vote',
						'children': [
							{
								'tag':'button',
								'class':'upvote',
								'title':'up vote',
								'html':''
							},
							{
								'tag':'button',
								'class': 'downvote',
								'title':'down vote',
								'html':''
							}
						]
					},
					{
						'tag':'button',
						'class':'viewComment',
						'data-id': '${_id}',
						'title':'comment',
						'html':''
					}
				]
			}
		]
	};

	var commentMicroTemplate = {
		'tag':'div',
		'data-id':'${_id}',
		'children': [
			{
				'tag':'h5',
				'html':'${tempname}'
			},
			{
				'tag':'p',
				'html':'${body}'
			}
		]
	};

	var pageMicroTemplate = {
		tag: 'li',
		html: '${body}'
	};

	var bulletMicroTemplate = {
		tag: 'li',
		class: '${class}'
	};
};
<|endoftext|>


<commit_before>$(document).ready(function() {

  //AJAX call for initial search with search bar
  $('#search').on('submit', function(event) {
    event.preventDefault();
    searchSetup();
    var $target = $(event.target);
    $.ajax({
      url: $target.attr('action'),
      type: 'POST',
      data: $target.serialize(),
      dataType: "JSON"
    }).done(function(response) {
      searchFinish(response);
      twitterButton();
    })
  })

  //AJAX call for initial search with thumbnail images
  $('.thumbnailSearch').on('click', function(event) {
    event.preventDefault();
    searchSetup();
    var $target = $(event.target);
    $.ajax({
      url: '/search/' + $target.attr('categoryId'),
      type: 'GET',
      dataType: "JSON"
    }).done(function(response) {
      searchFinish(response);
      twitterButton();
    })
  })

  //AJAX call to update likeCount of content and create Like
  $("#like").on('click', function(event) {
    event.preventDefault();
    $.ajax({
      url: '/' + content[contentNum].type + '/' + content[contentNum].id,
      type: 'POST'
    }).done(function(response) {
      console.log(response)
      if (response === "exists") {
        var n = noty({
          text: 'Like Already Exists!',
          type: 'warning',
          layout: 'topCenter',
          theme: 'relax',
          timeout: 1000
        });
      } else {
        var n = noty({
          text: 'Like Successful!',
          type: 'success',
          layout: 'topCenter',
          theme: 'relax',
          timeout: 1000
        });
      }
    }).fail(function(response) {
      var n = noty({
        text: 'Like Failed!',
        type: 'error',
        layout: 'topCenter',
        theme: 'relax',
        timeout: 1000
      });
    });
  })

  // Javascript used to go to the next piece of content
  $("#next").on('click', function(event) {
    event.preventDefault();
    if (content[++contentNum].type === "video") {
      $("#content iframe").attr("src", youtubeId(content[contentNum].url))
    } else {
      $("#content iframe").attr("src", content[contentNum].url)
    }
    twitterButton();
  })

  // Javascript used to go to go back to the previous piece of content
  $("#back").on('click', function(event) {
    event.preventDefault();
    if (content[--contentNum].type === "video") {
      $("#content iframe").attr("src", youtubeId(content[contentNum].url))
    } else {
      $("#content iframe").attr("src", content[contentNum].url)
    }
    twitterButton();
  })

  // JavaScript used to toggle between show and edit partials on profile page
  $("#editButton").on('click', function(event) {
    var $target = $(event.target);
    $target.text($target.text() === "Edit List" ? "Show List" : "Edit List");
    $("#showListDiv").toggle();
    $("#editListDiv").toggle();
  });

  //AJAX call to delete videos and articles from posts
  $("#editList").on('submit', function(event) {
    event.preventDefault();
    var $target = $(event.target);
    $.ajax({
      url: $target.attr('action'),
      type: 'DELETE',
      data: $target.serialize()
    }).done(function(response) {
      var n = noty({
        text: 'List Update Successful!',
        type: 'success',
        layout: 'topCenter',
        theme: 'relax',
        timeout: 1000
      });
      $("input:checked").each(function() {
        $("a[href='" + $(this).prev().attr('href') + "']").remove();
        $(this).remove();
      });
    }).fail(function(response) {
      var n = noty({
        text: 'List Update Failed!',
        type: 'error',
        layout: 'topCenter',
        theme: 'relax',
        timeout: 1000
      });
    });
  })

});

function youtubeId(url) {
  var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
  var match = url.match(regExp);

  if (match && match[2].length == 11) {
    return "//www.youtube.com/embed/" + match[2];
  }
}

function httpConvert(url) {
  return url = url.replace(/^http:\/\//, 'https://')
}

function twitterButton() {
  $("#twitterDiv").empty();
  var $clone = $(".twitter-share-button-template").clone();
  $clone.show();
  $clone.attr("data-url", httpConvert(content[contentNum].url));
  $clone.attr("class", "twitter-share-button");
  $("#twitterDiv").append($clone);
  $.getScript("http://platform.twitter.com/widgets.js");
}

function searchSetup() {
  $("#search").hide();
  $("#initial").show();
  $(".homepage").hide();
  $("#searchWrapper img").show();
}

function searchFinish(response) {
  content = response
  $("#initial").remove();
  $("#searchWrapper img").hide();
  $("#search").show();
  $("#likeButtons").show();
  $("#content").show();
  $content = $("#content iframe")
  contentNum = 0;
  if (content[contentNum].type === "video") {
    $content.attr("src", youtubeId(content[contentNum].url))
    $content.attr("contentId", content[contentNum].id)
  } else {
    $content.attr("src", content[contentNum].url)
    $content.attr("contentId", content[contentNum].id)
  }
}<commit_msg>Added resetCounter function to reset counter after user scrolls through all the content for given category<commit_after>$(document).ready(function() {

  //AJAX call for initial search with search bar
  $('#search').on('submit', function(event) {
    event.preventDefault();
    searchSetup();
    var $target = $(event.target);
    $.ajax({
      url: $target.attr('action'),
      type: 'POST',
      data: $target.serialize(),
      dataType: "JSON"
    }).done(function(response) {
      searchFinish(response);
      twitterButton();
    })
  })

  //AJAX call for initial search with thumbnail images
  $('.thumbnailSearch').on('click', function(event) {
    event.preventDefault();
    searchSetup();
    var $target = $(event.target);
    $.ajax({
      url: '/search/' + $target.attr('categoryId'),
      type: 'GET',
      dataType: "JSON"
    }).done(function(response) {
      searchFinish(response);
      twitterButton();
    })
  })

  //AJAX call to update likeCount of content and create Like
  $("#like").on('click', function(event) {
    event.preventDefault();
    $.ajax({
      url: '/' + content[contentNum].type + '/' + content[contentNum].id,
      type: 'POST'
    }).done(function(response) {
      console.log(response)
      if (response === "exists") {
        var n = noty({
          text: 'Like Already Exists!',
          type: 'warning',
          layout: 'topCenter',
          theme: 'relax',
          timeout: 1000
        });
      } else {
        var n = noty({
          text: 'Like Successful!',
          type: 'success',
          layout: 'topCenter',
          theme: 'relax',
          timeout: 1000
        });
      }
    }).fail(function(response) {
      var n = noty({
        text: 'Like Failed!',
        type: 'error',
        layout: 'topCenter',
        theme: 'relax',
        timeout: 1000
      });
    });
  })

  // Javascript used to go to the next piece of content
  $("#next").on('click', function(event) {
    event.preventDefault();
    if (content[++contentNum].type === "video") {
      $("#content iframe").attr("src", youtubeId(content[contentNum].url))
    } else {
      $("#content iframe").attr("src", content[contentNum].url)
    }
    resetCounter(contentNum, content)
    twitterButton();
  })

  // Javascript used to go to go back to the previous piece of content
  $("#back").on('click', function(event) {
    event.preventDefault();
    if (content[--contentNum].type === "video") {
      $("#content iframe").attr("src", youtubeId(content[contentNum].url))
    } else {
      $("#content iframe").attr("src", content[contentNum].url)
    }
    twitterButton();
  })

  // JavaScript used to toggle between show and edit partials on profile page
  $("#editButton").on('click', function(event) {
    var $target = $(event.target);
    $target.text($target.text() === "Edit List" ? "Show List" : "Edit List");
    $("#showListDiv").toggle();
    $("#editListDiv").toggle();
  });

  //AJAX call to delete videos and articles from posts
  $("#editList").on('submit', function(event) {
    event.preventDefault();
    var $target = $(event.target);
    $.ajax({
      url: $target.attr('action'),
      type: 'DELETE',
      data: $target.serialize()
    }).done(function(response) {
      var n = noty({
        text: 'List Update Successful!',
        type: 'success',
        layout: 'topCenter',
        theme: 'relax',
        timeout: 1000
      });
      $("input:checked").each(function() {
        $("a[href='" + $(this).prev().attr('href') + "']").remove();
        $(this).remove();
      });
    }).fail(function(response) {
      var n = noty({
        text: 'List Update Failed!',
        type: 'error',
        layout: 'topCenter',
        theme: 'relax',
        timeout: 1000
      });
    });
  })

});

function youtubeId(url) {
  var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
  var match = url.match(regExp);

  if (match && match[2].length == 11) {
    return "//www.youtube.com/embed/" + match[2];
  }
}

function httpConvert(url) {
  return url = url.replace(/^http:\/\//, 'https://')
}

function twitterButton() {
  $("#twitterDiv").empty();
  var $clone = $(".twitter-share-button-template").clone();
  $clone.show();
  $clone.attr("data-url", httpConvert(content[contentNum].url));
  $clone.attr("class", "twitter-share-button");
  $("#twitterDiv").append($clone);
  $.getScript("http://platform.twitter.com/widgets.js");
}

function resetCounter(counter, array) {
  if (counter > array.length) {
    counter = -1
  }
}

function searchSetup() {
  $("#search").hide();
  $("#initial").show();
  $(".homepage").hide();
  $("#searchWrapper img").show();
}

function searchFinish(response) {
  content = response
  $("#initial").remove();
  $("#searchWrapper img").hide();
  $("#search").show();
  $("#likeButtons").show();
  $("#content").show();
  $content = $("#content iframe")
  contentNum = 0;
  if (content[contentNum].type === "video") {
    $content.attr("src", youtubeId(content[contentNum].url))
    $content.attr("contentId", content[contentNum].id)
  } else {
    $content.attr("src", content[contentNum].url)
    $content.attr("contentId", content[contentNum].id)
  }
}<|endoftext|>