<commit_before>/* globals hqImport */
// This file depends on reports/js/filters/main.js
var HQAsyncReport = function (o) {
    'use strict';
    var self = this;
    self.reportContent = o.reportContent ||  $('#report-content');
    self.filterForm = o.filterForm || $('#paramSelectorForm');
    self.loadingIssueModal = o.loadingIssueModal || $('#loadingReportIssueModal');
    self.issueAttempts = 0;
    self.hqLoading = null;
    self.standardReport = o.standardReport;
    self.filterRequest = null;
    self.reportRequest = null;
    self.customAsyncUrl = o.customAsyncUrl || null;
    self.additionalParams = o.additionalParams || '';
    self.additionalWindowParams = o.additionalWindowParams || '';
    self.loaderClass = '.report-loading';

    self.humanReadableErrors = {
        400: gettext("Please check your Internet connection!"),
        404: gettext("Report Not Found."),
        408: gettext("Request timed out when rendering this report. This might be an issue with our servers" +
            " or with your Internet connection. We encourage you to report an issue to CommCare HQ Support so we" +
            " can look into any possible issues."),
        500: gettext("Problem Rendering Report. Our error monitoring tools have noticed this and we are working quickly to" +
            " resolve this issue as soon as possible. We encourage you to contact CommCare HQ Support" +
            " if this issue persists for more than a few minutes. We appreciate any additional information" +
            " you can give us about this problem so we can fix it immediately."),
        502: gettext("Bad Gateway. Please contact CommCare HQ Support."),
        503: gettext("CommCare HQ is experiencing server difficulties. We're working quickly to resolve it." +
            " Thank you for your patience. We are extremely sorry."),
        504: gettext("Gateway Timeout. Please contact CommCare HQ Support."),
    };

    var loadFilters = function (data) {
        self.filterRequest = null;
        try {
            $('#hq-report-filters').html(data.filters);
            hqImport("reports/js/filters/main").init();
        } catch (e) {
            console.log(e);
        }
        $('#reportFiltersAccordion').removeClass('hide');
        self.standardReport.resetFilterState();
    };

    self.init = function () {
        self.reportContent.attr('style', 'position: relative;');

        self.updateReport(true, window.location.search.substr(1), self.standardReport.filterSet);

        // only update the report if there are actually filters set
        if (!self.standardReport.needsFilters) {
            self.standardReport.filterSubmitButton.addClass('disabled');
        }
        self.filterForm.submit(function () {
            var params = hqImport('reports/js/reports.util').urlSerialize(this);
            history.pushState(null,window.location.title,
                window.location.pathname + '?' + params
                + (self.additionalWindowParams ? '&' + self.additionalWindowParams : ''));
            self.updateFilters(params);
            self.updateReport(false, params, true);
            return false;
        });
    };

    self.updateFilters = function (form_params) {
        self.standardReport.saveDatespanToCookie();
        self.filterRequest = $.ajax({
            url: window.location.pathname.replace(self.standardReport.urlRoot,
                self.standardReport.urlRoot + 'filters/') + "?" + form_params + "&" + self.additionalParams,
            dataType: 'json',
            success: loadFilters,
        });
    };

    self.updateReport = function (initial_load, params, setFilters) {
        var process_filters = "";
        if (initial_load) {
            process_filters = "hq_filters=true&";
            if (self.standardReport.loadDatespanFromCookie()) {
                process_filters = process_filters +
                    "&startdate=" + self.standardReport.datespan.startdate +
                    "&enddate=" + self.standardReport.datespan.enddate;
            }
        }
        if (setFilters != undefined) {
            process_filters = process_filters + "&filterSet=" + setFilters;
        }
        if (setFilters) {
            $(self.standardReport.exportReportButton).removeClass('hide');
            $(self.standardReport.emailReportButton).removeClass('hide');
            $(self.standardReport.printReportButton).removeClass('hide');
        }

        self.reportRequest = $.ajax({
            url: (self.customAsyncUrl || window.location.pathname.replace(self.standardReport.urlRoot,
                self.standardReport.urlRoot + 'async/')) + "?" + process_filters + "&" + params + "&" + self.additionalParams,
            dataType: 'json',
            success: function (data) {
                self.reportRequest = null;
                if (data.filters) {
                    loadFilters(data);
                }
                self.issueAttempts = 0;
                self.loadingIssueModal.modal('hide');
                self.hqLoading = $(self.loaderClass);
                self.reportContent.html(data.report);
                hqImport('reports/js/charts/main').init();
                // clear lingering popovers
                _.each($('body > .popover'), function (popover) {
                    $(popover).remove();
                });
                self.reportContent.append(self.hqLoading);
                self.hqLoading.removeClass('hide');

                // Assorted UI cleanup/initialization
                $('.hq-report-time-notice').removeClass('hide');
                if ($.timeago) {
                    $(".timeago").timeago();
                }

                $('.loading-backdrop').fadeOut();
                self.hqLoading.fadeOut();

                if (!initial_load || !self.standardReport.needsFilters) {
                    self.standardReport.filterSubmitButton
                        .button('reset');
                    setTimeout(function () {
                        // Bootstrap clears all btn styles except btn on reset
                        // This gets around it by waiting 10ms.
                        self.standardReport.filterSubmitButton
                            .removeClass('btn-primary')
                            .addClass('disabled')
                            .prop('disabled', true);

                    }, 10);
                } else {
                    self.standardReport.filterSubmitButton
                        .button('reset')
                        .addClass('btn-primary')
                        .removeClass('disabled')
                        .prop('disabled', false);
                }
            },
            error: function (data) {
                var humanReadable;
                self.reportRequest = null;
                if (data.status != 0) {
                    // If it is a BadRequest allow for report to specify text
                    if (data.status === 400) {
                        humanReadable = data.responseText || self.humanReadableErrors[data.status];
                    } else {
                        humanReadable = self.humanReadableErrors[data.status];
                    }
                    self.loadingIssueModal.find('.report-error-status').html('' + data.status + ' ' +
                        ((humanReadable) ? humanReadable : ""));
                    if (self.issueAttempts > 0)
                        self.loadingIssueModal.find('.btn-primary').button('fail');
                    self.issueAttempts += 1;
                    self.loadingIssueModal.modal('show');
                } else {
                    self.hqLoading = $(self.loaderClass);
                    self.hqLoading.find('h4').text("Loading Stopped");
                    self.hqLoading.find('.js-loading-spinner').attr('style', 'visibility: hidden;');
                }
            },
            beforeSend: function () {
                self.standardReport.filterSubmitButton.button('loading');
                $('.loading-backdrop').fadeIn();
                if (self.hqLoading) {
                    self.hqLoading.attr('style', 'position: absolute; top: 30px; left: 40%;');
                    self.hqLoading.fadeIn();
                }

            },
        });
    };

    self.loadingIssueModal.on('reloadHQReport', function () {
        self.loadingIssueModal.find('.btn-primary').button('loading');
        self.updateReport(true, window.location.search.substr(1));
    });

    self.loadingIssueModal.on('hide hide.bs.modal', function () {
        if (self.issueAttempts > 0) {
            self.hqLoading = $(self.loaderClass);
            self.hqLoading.find('.js-loading-spinner').addClass('hide');
            self.hqLoading.find('h4').text(gettext('We were unsuccessful loading the report:'))
                .attr('style', 'margin-bottom: 10px;');
        }
    });

};
<commit_msg>Removed unused options from reports.async.js<commit_after>/* globals hqImport */
// This file depends on reports/js/filters/main.js
var HQAsyncReport = function (o) {
    'use strict';
    var self = this;
    self.reportContent = $('#report-content');
    self.filterForm = o.filterForm || $('#paramSelectorForm');
    self.loadingIssueModal = $('#loadingReportIssueModal');
    self.issueAttempts = 0;
    self.hqLoading = null;
    self.standardReport = o.standardReport;
    self.filterRequest = null;
    self.reportRequest = null;
    self.loaderClass = '.report-loading';

    self.humanReadableErrors = {
        400: gettext("Please check your Internet connection!"),
        404: gettext("Report Not Found."),
        408: gettext("Request timed out when rendering this report. This might be an issue with our servers" +
            " or with your Internet connection. We encourage you to report an issue to CommCare HQ Support so we" +
            " can look into any possible issues."),
        500: gettext("Problem Rendering Report. Our error monitoring tools have noticed this and we are working quickly to" +
            " resolve this issue as soon as possible. We encourage you to contact CommCare HQ Support" +
            " if this issue persists for more than a few minutes. We appreciate any additional information" +
            " you can give us about this problem so we can fix it immediately."),
        502: gettext("Bad Gateway. Please contact CommCare HQ Support."),
        503: gettext("CommCare HQ is experiencing server difficulties. We're working quickly to resolve it." +
            " Thank you for your patience. We are extremely sorry."),
        504: gettext("Gateway Timeout. Please contact CommCare HQ Support."),
    };

    var loadFilters = function (data) {
        self.filterRequest = null;
        try {
            $('#hq-report-filters').html(data.filters);
            hqImport("reports/js/filters/main").init();
        } catch (e) {
            console.log(e);
        }
        $('#reportFiltersAccordion').removeClass('hide');
        self.standardReport.resetFilterState();
    };

    self.init = function () {
        self.reportContent.attr('style', 'position: relative;');

        self.updateReport(true, window.location.search.substr(1), self.standardReport.filterSet);

        // only update the report if there are actually filters set
        if (!self.standardReport.needsFilters) {
            self.standardReport.filterSubmitButton.addClass('disabled');
        }
        self.filterForm.submit(function () {
            var params = hqImport('reports/js/reports.util').urlSerialize(this);
            history.pushState(null,window.location.title, window.location.pathname + '?' + params);
            self.updateFilters(params);
            self.updateReport(false, params, true);
            return false;
        });
    };

    self.updateFilters = function (form_params) {
        self.standardReport.saveDatespanToCookie();
        self.filterRequest = $.ajax({
            url: window.location.pathname.replace(self.standardReport.urlRoot,
                self.standardReport.urlRoot + 'filters/') + "?" + form_params,
            dataType: 'json',
            success: loadFilters,
        });
    };

    self.updateReport = function (initial_load, params, setFilters) {
        var process_filters = "";
        if (initial_load) {
            process_filters = "hq_filters=true&";
            if (self.standardReport.loadDatespanFromCookie()) {
                process_filters = process_filters +
                    "&startdate=" + self.standardReport.datespan.startdate +
                    "&enddate=" + self.standardReport.datespan.enddate;
            }
        }
        if (setFilters != undefined) {
            process_filters = process_filters + "&filterSet=" + setFilters;
        }
        if (setFilters) {
            $(self.standardReport.exportReportButton).removeClass('hide');
            $(self.standardReport.emailReportButton).removeClass('hide');
            $(self.standardReport.printReportButton).removeClass('hide');
        }

        self.reportRequest = $.ajax({
            url: (window.location.pathname.replace(self.standardReport.urlRoot,
                self.standardReport.urlRoot + 'async/')) + "?" + process_filters + "&" + params,
            dataType: 'json',
            success: function (data) {
                self.reportRequest = null;
                if (data.filters) {
                    loadFilters(data);
                }
                self.issueAttempts = 0;
                self.loadingIssueModal.modal('hide');
                self.hqLoading = $(self.loaderClass);
                self.reportContent.html(data.report);
                hqImport('reports/js/charts/main').init();
                // clear lingering popovers
                _.each($('body > .popover'), function (popover) {
                    $(popover).remove();
                });
                self.reportContent.append(self.hqLoading);
                self.hqLoading.removeClass('hide');

                // Assorted UI cleanup/initialization
                $('.hq-report-time-notice').removeClass('hide');
                if ($.timeago) {
                    $(".timeago").timeago();
                }

                $('.loading-backdrop').fadeOut();
                self.hqLoading.fadeOut();

                if (!initial_load || !self.standardReport.needsFilters) {
                    self.standardReport.filterSubmitButton
                        .button('reset');
                    setTimeout(function () {
                        // Bootstrap clears all btn styles except btn on reset
                        // This gets around it by waiting 10ms.
                        self.standardReport.filterSubmitButton
                            .removeClass('btn-primary')
                            .addClass('disabled')
                            .prop('disabled', true);

                    }, 10);
                } else {
                    self.standardReport.filterSubmitButton
                        .button('reset')
                        .addClass('btn-primary')
                        .removeClass('disabled')
                        .prop('disabled', false);
                }
            },
            error: function (data) {
                var humanReadable;
                self.reportRequest = null;
                if (data.status != 0) {
                    // If it is a BadRequest allow for report to specify text
                    if (data.status === 400) {
                        humanReadable = data.responseText || self.humanReadableErrors[data.status];
                    } else {
                        humanReadable = self.humanReadableErrors[data.status];
                    }
                    self.loadingIssueModal.find('.report-error-status').html('' + data.status + ' ' +
                        ((humanReadable) ? humanReadable : ""));
                    if (self.issueAttempts > 0)
                        self.loadingIssueModal.find('.btn-primary').button('fail');
                    self.issueAttempts += 1;
                    self.loadingIssueModal.modal('show');
                } else {
                    self.hqLoading = $(self.loaderClass);
                    self.hqLoading.find('h4').text("Loading Stopped");
                    self.hqLoading.find('.js-loading-spinner').attr('style', 'visibility: hidden;');
                }
            },
            beforeSend: function () {
                self.standardReport.filterSubmitButton.button('loading');
                $('.loading-backdrop').fadeIn();
                if (self.hqLoading) {
                    self.hqLoading.attr('style', 'position: absolute; top: 30px; left: 40%;');
                    self.hqLoading.fadeIn();
                }

            },
        });
    };

    self.loadingIssueModal.on('reloadHQReport', function () {
        self.loadingIssueModal.find('.btn-primary').button('loading');
        self.updateReport(true, window.location.search.substr(1));
    });

    self.loadingIssueModal.on('hide hide.bs.modal', function () {
        if (self.issueAttempts > 0) {
            self.hqLoading = $(self.loaderClass);
            self.hqLoading.find('.js-loading-spinner').addClass('hide');
            self.hqLoading.find('h4').text(gettext('We were unsuccessful loading the report:'))
                .attr('style', 'margin-bottom: 10px;');
        }
    });

};
<|endoftext|>


<commit_before>;( function( $ ){
	$.fn.jsBem = function( options ) {
        var defaults = {
	    bemESeparator: "__",
            bemMSeparator: "--",
            bemBlock: "",
            modifierClass: ""
		},

		jsBem = {
	    opt: {},
            $blocks: {},
            $bems: {},
            $bemClassElements: {},
            $finalBems: {},
	    init: function () {
	        jsBem.opt = $.extend(defaults, options);
	        jsBem.setBlockObject();
	    },

            setBlockObject: function() {
                this.$blocks = $( '*[data-bem-block="' + this.opt.bemBlock + '"]' );
                this.$bems   = $( '*[data-bem="' + this.opt.bemBlock + '"]' );

                if ( !this.$bems.length ) {
                    console.log( "No BEM elements found. Please re-check your code." );
                    return false;
                }

                this.setBemElements();
            },

            setBemElements: function() {
                var that = this;

                for( var i = 0; i < this.$bems.length; i++ ) {
                    var $el     = $(this.$bems[i]);
                    var elClass = $el.attr( "class" );

                    if ( this.isBemElement( elClass ) || this.isBemModifier( elClass ) ) {
                        this.bemClassController({
                            $el: $el,
                            classes: elClass.split( " " )
                        });
                    }
                }
            },

            bemClassController: function( $obj ) {
                if( this.isBemElement($obj.classes[0]) ) {
                    $obj.classes = $obj.classes[0].split(this.opt.bemESeparator).join(' ');
                    this.setFinalBemClass($obj, this.opt.bemESeparator);
                } else if( this.isBemModifier($obj.classes[0]) ) {
                    $obj.classes = $obj.classes[0].split(this.opt.bemMSeparator).join(' ');
                    this.setFinalBemClass($obj, this.opt.bemMSeparator);
                }
            },

            isBemElement: function( s ){
                return s.split( this.opt.bemESeparator ).length > 1;
            },

            isBemModifier: function( s ){
                return s.split( this.opt.bemMSeparator ).length > 1;
            },

            setFinalBemClass: function ($obj, bemClass) {
                var splitClasses    = $obj.classes.split(' ');
                var joinClasses     = splitClasses.join(this.opt.bemMSeparator + this.opt.modifierClass + bemClass);
                var classesLenght   = splitClasses.length;
                var finalClass      = '';

                for( var i = 0; i < classesLenght; i++ ) {
                    if( i == classesLenght - 1 && i < 2 ) {
                        finalClass+= splitClasses[i];
                    }else if( i < 1 ){
                        finalClass+= splitClasses[i] + this.opt.bemMSeparator + this.opt.modifierClass + bemClass;
                    }else if( i > 1 ) {
                        finalClass+= splitClasses[i];
                        console.log("Please try to keep your BEM elements with less nesting. You have 2 BEM Elements for this block: ", $obj.$el);
                    }else{
                        finalClass+= splitClasses[i] + bemClass;
                    }
                }

                $obj.$el.addClass(finalClass);
            }
		};

        $(function(){
            jsBem.init();
        });

		return this;
	}
}(jQuery));
<commit_msg>Correction<commit_after>;( function( $ ){
	$.fn.jsBem = function( options ) {
        var defaults = {
	    bemESeparator: "__",
            bemMSeparator: "--",
            bemBlock: "",
            modifierClass: ""
		},

		jsBem = {
	    opt: {},
            $blocks: {},
            $bems: {},
            $bemClassElements: {},
            $finalBems: {},
	    init: function () {
	        jsBem.opt = $.extend(defaults, options);
	        jsBem.setBlockObject();
	    },

            setBlockObject: function() {
                this.$blocks = $( '*[data-bem-block="' + this.opt.bemBlock + '"]' );
                this.$bems   = $( '*[data-bem="' + this.opt.bemBlock + '"]' );

                if ( !this.$bems.length ) {
                    console.log( "No BEM elements found. Please re-check your code." );
                    return false;
                }

                this.setBemBlocks();
                this.setBemElements();
            },

            setBemBlocks: function() {
                var that = this;

                for( var i = 0; i < this.$blocks.length; i++ ) {
                    $(this.$blocks[i]).addClass(this.opt.bemBlock + this.opt.bemMSeparator + this.opt.modifierClass);
                }
            },

            setBemElements: function() {
                var that = this;

                for( var i = 0; i < this.$bems.length; i++ ) {
                    var $el     = $(this.$bems[i]);
                    var elClass = $el.attr( "class" );

                    if ( this.isBemElement( elClass ) || this.isBemModifier( elClass ) ) {
                        this.bemClassController({
                            $el: $el,
                            classes: elClass.split( " " )
                        });
                    }
                }
            },

            bemClassController: function( $obj ) {
                if( this.isBemElement($obj.classes[0]) ) {
                    $obj.classes = $obj.classes[0].split(this.opt.bemESeparator).join(' ');
                    this.setFinalBemClass($obj, this.opt.bemESeparator);
                } else if( this.isBemModifier($obj.classes[0]) ) {
                    $obj.classes = $obj.classes[0].split(this.opt.bemMSeparator).join(' ');
                    this.setFinalBemClass($obj, this.opt.bemMSeparator);
                }
            },

            isBemElement: function( s ){
                return s.split( this.opt.bemESeparator ).length > 1;
            },

            isBemModifier: function( s ){
                return s.split( this.opt.bemMSeparator ).length > 1;
            },

            setFinalBemClass: function ($obj, bemClass) {
                var splitClasses    = $obj.classes.split(' ');
                var joinClasses     = splitClasses.join(this.opt.bemMSeparator + this.opt.modifierClass + bemClass);
                var classesLenght   = splitClasses.length;
                var finalClass      = '';

                for( var i = 0; i < classesLenght; i++ ) {
                    if( i == classesLenght - 1 && i < 2 ) {
                        finalClass+= splitClasses[i];
                    }else if( i < 1 ){
                        finalClass+= splitClasses[i] + this.opt.bemMSeparator + this.opt.modifierClass + bemClass;
                    }else if( i > 1 ) {
                        finalClass+= splitClasses[i];
                        console.log("Please try to keep your BEM elements with less nesting. You have 2 BEM Elements for this block: ", $obj.$el);
                    }else{
                        finalClass+= splitClasses[i] + bemClass;
                    }
                }

                $obj.$el.addClass(finalClass);
            }
		};

        $(function(){
            jsBem.init();
        });

		return this;
	}
}(jQuery));
<|endoftext|>


<commit_before>var util = require('util');
var co = require('co');
var _ = require('underscore');
var _s = require('underscore.string');
var resolve = require('url').resolve;

var model = require('./model');
var log = require('./biz').log;

var getRootURL = require('../modules/other/pathUtils').getRootURL;
var readFile = require('../modules/other/pathUtils').readFile;
var getAbsolutePath = require('../modules/other/pathUtils').getAbsolutePath;
var extractImgSrc = require('./biz').extractImgSrc;
var extractRequestHref = require('./biz').extractRequestHref;
var download2Buffer = require('./biz').download2Buffer;
var sleep = require('./biz').sleep;
var getURL = require('./biz').getURL;
var onSuccess = require('./biz').onSuccess;
var onError = require('./biz').onError;

var BloomFilter = require('../modules/repeater/repeater'),
    repeater = new BloomFilter();

/*
 * @site 站点
 * @sleepSeconds 休眠秒数
 * */
module.exports.fetchCities = fetchCities;
function* fetchCities(site) {
    var hotCities = JSON.parse(yield readFile(getAbsolutePath('spiders/hotCities.json')));
    var cities = hotCities[site].cities;
    var sleepSeconds = hotCities[site].sleepSeconds;
    var HotZone = require(getAbsolutePath('spiders/' + site + '/hotZone'));
    var Houses = require(getAbsolutePath('spiders/' + site + '/houses'));
    var Detail = require(getAbsolutePath('spiders/' + site + '/detail'));

    for (var i = 0, len = cities.length; i < len; i++) {
        var city = cities[i];
        try {
            var zones = yield new HotZone(city).getHotZones();
            sleep(sleepSeconds);
            for (var j = 0, len2 = zones.length; j < len2; j++) {
                var zone = zones[j];
                var listPage = yield new Houses(zone.href).getHouses();

                yield co(fetchHouses(listPage, Detail, sleepSeconds, city));

                for (var l = 0, len4 = listPage.pages.length; l < len4; l++) {
                    listPage = yield new Houses(listPage.pages[l]).getHouses();
                    yield co(fetchHouses(listPage, Detail, sleepSeconds, city));
                }

                sleep(sleepSeconds);
            }
        } catch (e) {
            log(util.format('%s: ---------ERROR', city));
            log(e.stack);
        }
    }
}

function* fetchHouses(listPage, Detail, sleepSeconds, city){
    for (var m = 0, len5 = listPage.houses.length; m < len5; m++) {
        var href = listPage.houses[m].href;
        if (!_s.startsWith(href, 'http')) {
            log('resolve: ', city, href);
            href = resolve(getRootURL(city), href);
        }
        yield co(fetchOneHouse(Detail, href, sleepSeconds));
    }
}

function* fetchOneHouse(Detail, href, sleepSeconds) {
    if (!repeater.exists(href)) {//防重
        repeater.add(href);

        if(href.trim()) {

            var detail = new Detail(href);
            var house = yield detail.getDetail();

            yield co(detail.moreDetail(house));

            if(house.longitude && house.latitude) {
                console.log(house);

                yield model.bulkCreate(house);
                onSuccess('creation successful.');
            }

            sleep(sleepSeconds);
        } else {
            log('NULL href');
        }
    }
}

//co(fetchCities(10));
<commit_msg>add applicable sleepSeconds.<commit_after>var util = require('util');
var co = require('co');
var _ = require('underscore');
var _s = require('underscore.string');
var resolve = require('url').resolve;

var model = require('./model');
var log = require('./biz').log;

var getRootURL = require('../modules/other/pathUtils').getRootURL;
var readFile = require('../modules/other/pathUtils').readFile;
var getAbsolutePath = require('../modules/other/pathUtils').getAbsolutePath;
var extractImgSrc = require('./biz').extractImgSrc;
var extractRequestHref = require('./biz').extractRequestHref;
var download2Buffer = require('./biz').download2Buffer;
var sleep = require('./biz').sleep;
var getURL = require('./biz').getURL;
var onSuccess = require('./biz').onSuccess;
var onError = require('./biz').onError;

var BloomFilter = require('../modules/repeater/repeater'),
    repeater = new BloomFilter();

/*
 * @site 站点
 * @sleepSeconds 休眠秒数
 * */
module.exports.fetchCities = fetchCities;
function* fetchCities(site) {
    var hotCities = JSON.parse(yield readFile(getAbsolutePath('spiders/hotCities.json')));
    var cities = hotCities[site].cities;
    var sleepSeconds = hotCities[site].sleepSeconds;
    var HotZone = require(getAbsolutePath('spiders/' + site + '/hotZone'));
    var Houses = require(getAbsolutePath('spiders/' + site + '/houses'));
    var Detail = require(getAbsolutePath('spiders/' + site + '/detail'));

    for (var i = 0, len = cities.length; i < len; i++) {
        var city = cities[i];
        try {
            var zones = yield new HotZone(city).getHotZones();
            sleep(sleepSeconds);
            for (var j = 0, len2 = zones.length; j < len2; j++) {
                var zone = zones[j];
                var listPage = yield new Houses(zone.href).getHouses();

                yield co(fetchHouses(listPage, Detail, sleepSeconds, city));

                for (var l = 0, len4 = listPage.pages.length; l < len4; l++) {
                    listPage = yield new Houses(listPage.pages[l]).getHouses();
                    yield co(fetchHouses(listPage, Detail, sleepSeconds, city));

                    sleep(sleepSeconds);
                }

                sleep(sleepSeconds);
            }
        } catch (e) {
            log(util.format('%s: ---------ERROR', city));
            log(e.stack);
        }
    }
}

function* fetchHouses(listPage, Detail, sleepSeconds, city){
    for (var m = 0, len5 = listPage.houses.length; m < len5; m++) {
        var href = listPage.houses[m].href;
        if (!_s.startsWith(href, 'http')) {
            log('resolve: ', city, href);
            href = resolve(getRootURL(city), href);
        }
        yield co(fetchOneHouse(Detail, href, sleepSeconds));
    }
}

function* fetchOneHouse(Detail, href, sleepSeconds) {
    if (!repeater.exists(href)) {//防重
        repeater.add(href);

        if(href.trim()) {

            var detail = new Detail(href);
            var house = yield detail.getDetail();

            yield co(detail.moreDetail(house));

            if(house.longitude && house.latitude) {
                console.log(house);

                yield model.bulkCreate(house);
                onSuccess('creation successful.');
            }

            sleep(sleepSeconds);
        } else {
            log('NULL href');
        }
    }
}

//co(fetchCities(10));
<|endoftext|>


<commit_before>import React, {Component} from 'react'
import PropTypes from 'prop-types'
import API from 'api'
import autobind from 'autobind-decorator'
import {Button} from 'react-bootstrap'

import HorizontalBarChart from 'components/HorizontalBarChart'
import Fieldset from 'components/Fieldset'
import ReportCollection from 'components/ReportCollection'
import moment from 'moment'

const d3 = require('d3')
const chartId = 'future_engagements_by_location'

/*
 * Component displaying a chart with number of future engagements per date and
 * location. Locations are grouped per date.
 */
export default class FutureEngagementsByLocation extends Component {
  static propTypes = {
    startDate: PropTypes.object.isRequired,
    endDate: PropTypes.object.isRequired,
  }

  constructor(props) {
    super(props)

    this.state = {
      graphData: {data: []},
      focusedDate: '',
      focusedLocation: '',
      updateChart: true,  // whether the chart needs to be updated
    }
  }

  get queryParams() {
    return {
      engagementDateStart: this.props.startDate.startOf('day').valueOf(),
      engagementDateEnd: this.props.endDate.valueOf(),
    }
  }

  get engagementDateRangeArray() {
    let dateArray = []
    let currentDate = this.props.startDate.clone()
    let endDate = this.props.endDate
    while (currentDate <= endDate) {
      dateArray.push(currentDate.clone().startOf('day'))
      currentDate = currentDate.add(1, 'days')
    }
    return dateArray
  }

  render() {
    let chart = ''
    if (this.state.graphData.data.length) {
      chart = <HorizontalBarChart
        chartId={chartId}
        data={this.state.graphData}
        onBarClick={this.goToSelection}
        updateChart={this.state.updateChart}
      />
    }
    let focusDetails = this.getFocusDetails()
    return (

        {chart}
        <Fieldset
            title={`Future Engagements ${focusDetails.titleSuffix}`}
            id='cancelled-reports-details'
            action={!focusDetails.resetFnc
              ? '' : <Button onClick={() => this[focusDetails.resetFnc]()}>{focusDetails.resetButtonLabel}</Button>
            }
          >
          <ReportCollection paginatedReports={this.state.reports} goToPage={this.goToReportsPage} />
        </Fieldset>

    )
  }

  getFocusDetails() {
    let titleSuffix = ''
    let resetFnc = ''
    let resetButtonLabel = ''
    const focusDate = moment(this.state.focusedDate).format('D MMMM YYYY')
    if (this.state.focusedLocation && this.state.focusedDate) {
      titleSuffix = `for ${this.state.focusedLocation.label} on ${focusDate}`
      resetFnc = 'goToSelection'
      resetButtonLabel = 'All locations'
    }
    return {
      titleSuffix: titleSuffix,
      resetFnc: resetFnc,
      resetButtonLabel: resetButtonLabel
    }
  }

  fetchData() {
    // Query used by the chart
    const chartQuery = this.runChartQuery(this.chartQueryParams())
    Promise.all([chartQuery]).then(values => {
      let reportsList = values[0].reportList.list
      console.log(reportsList)
      // add days without data as we want to display them in the chart
      let allCategories = this.engagementDateRangeArray.map(function(d) {
        return {
          key: d.valueOf(),
          values: [{}]
        }
      })
      let categoriesWithData = d3.nest()
        .key(function(d) { return moment(d.engagementDate).startOf('day').valueOf() })
        .key(function(d) { return (d.location) ? d.location.id : -1 })
        .rollup(function(leaves) { return leaves.length })
        .entries(reportsList)
      let groupedData = allCategories.map((d)=> {
        let categData = categoriesWithData.find((x) => { return x.key == d.key })
        return Object.assign({}, d, categData)
      })
      let graphData = {}
      graphData.data = groupedData
      graphData.categoryLabels = allCategories.reduce(
        function(prev, curr) {
          prev[curr.key] = moment(curr.key).format('D MMM YYYY')
          return prev
        },
        {}
      )
      graphData.leavesLabels = reportsList.reduce(
        function(prev, curr) {
          if (curr.location) {
            prev[curr.location.id] = curr.location.name
          }
          else {
            prev[-1] = 'No location allocated'
          }
          return prev
        },
        {}
      )
      this.setState({
        updateChart: true,  // update chart after fetching the data
        graphData: graphData
      })
    })
    this.fetchFocusData()

  }

  fetchFocusData() {
    const reportsQueryParams = {}
    Object.assign(reportsQueryParams, this.queryParams)
    Object.assign(reportsQueryParams, {pageNum: this.state.reportsPageNum})
    if (this.state.focusedDate) {
      Object.assign(reportsQueryParams, {
        // Use here the start and end of a date in order to make sure the
        // fetch is independent of the engagementDate time value
        engagementDateStart: moment(this.state.focusedDate).startOf('day').valueOf(),
        engagementDateEnd: moment(this.state.focusedDate).endOf('day').valueOf(),
        locationId: this.state.focusedLocation.key
      })
    }
    // Query used by the reports collection
    let reportsQuery = API.query(/* GraphQL */`
        reportList(f:search, query:$reportsQueryParams) {
          pageNum, pageSize, totalCount, list {
            ${ReportCollection.GQL_REPORT_FIELDS}
          }
        }
      `, {reportsQueryParams}, '($reportsQueryParams: ReportSearchQuery)')
    Promise.all([reportsQuery]).then(values => {
      this.setState({
        updateChart: false,  // only update the report list
        reports: values[0].reportList
      })
    })
  }

  chartQueryParams = () => {
    const chartQueryParams = {}
    const queryParams = this.queryParams
    Object.assign(chartQueryParams, queryParams)
    Object.assign(chartQueryParams, {
      pageSize: 0,  // retrieve all the filtered reports
    })
    return chartQueryParams
  }

  runChartQuery = (chartQueryParams) => {
    return API.query(/* GraphQL */`
    reportList(f:search, query:$chartQueryParams) {
      totalCount, list {
        ${ReportCollection.GQL_REPORT_FIELDS}
      }
    }
  `, {chartQueryParams}, '($chartQueryParams: ReportSearchQuery)')
  }

  @autobind
  goToReportsPage(newPage) {
    this.setState({updateChart: false, reportsPageNum: newPage}, () => this.fetchFocusData())
  }

  resetChartSelection(chartId) {
    d3.selectAll('#' + chartId + ' rect').attr('class', '')
  }

  @autobind
  goToSelection(item) {
    // Note: we set updateChart to false as we do not want to re-render the chart
    // when changing the focus bar
    this.setState(
      {
        updateChart: false,
        reportsPageNum: 0,
        focusedDate: (item ? parseInt(item.parentKey, 10) : ''),
        focusedLocation: (item ? {key: item.key, label: this.state.graphData.leavesLabels[item.key]} : '')
      },
      () => this.fetchFocusData()
    )
    // remove highlighting of the bars
    this.resetChartSelection(chartId)
    if (item) {
      // highlight the selected bar
      d3.select('#' + chartId + ' #bar_' + item.key + item.parentKey).attr('class', 'selected-bar')
    }
  }

  componentDidMount() {
    this.fetchData()
  }

  componentDidUpdate(prevProps, prevState) {
    const startDateChanged = prevProps.startDate.valueOf() !== this.props.startDate.valueOf()
    const endDateChanged = prevProps.endDate.valueOf() !== this.props.endDate.valueOf()
    if (startDateChanged || endDateChanged) {
      this.fetchData()
    }
  }
}
<commit_msg>NCI-Agency/anet#161 Add clone props start date before applying start of day<commit_after>import React, {Component} from 'react'
import PropTypes from 'prop-types'
import API from 'api'
import autobind from 'autobind-decorator'
import {Button} from 'react-bootstrap'

import HorizontalBarChart from 'components/HorizontalBarChart'
import Fieldset from 'components/Fieldset'
import ReportCollection from 'components/ReportCollection'
import moment from 'moment'

const d3 = require('d3')
const chartId = 'future_engagements_by_location'

/*
 * Component displaying a chart with number of future engagements per date and
 * location. Locations are grouped per date.
 */
export default class FutureEngagementsByLocation extends Component {
  static propTypes = {
    startDate: PropTypes.object.isRequired,
    endDate: PropTypes.object.isRequired,
  }

  constructor(props) {
    super(props)

    this.state = {
      graphData: {data: []},
      focusedDate: '',
      focusedLocation: '',
      updateChart: true,  // whether the chart needs to be updated
    }
  }

  get queryParams() {
    return {
      engagementDateStart: this.props.startDate.clone().startOf('day').valueOf(),
      engagementDateEnd: this.props.endDate.valueOf(),
    }
  }

  get engagementDateRangeArray() {
    let dateArray = []
    let currentDate = this.props.startDate.clone()
    let endDate = this.props.endDate
    while (currentDate <= endDate) {
      dateArray.push(currentDate.clone().startOf('day'))
      currentDate = currentDate.add(1, 'days')
    }
    return dateArray
  }

  render() {
    let chart = ''
    if (this.state.graphData.data.length) {
      chart = <HorizontalBarChart
        chartId={chartId}
        data={this.state.graphData}
        onBarClick={this.goToSelection}
        updateChart={this.state.updateChart}
      />
    }
    let focusDetails = this.getFocusDetails()
    return (

        {chart}
        <Fieldset
            title={`Future Engagements ${focusDetails.titleSuffix}`}
            id='cancelled-reports-details'
            action={!focusDetails.resetFnc
              ? '' : <Button onClick={() => this[focusDetails.resetFnc]()}>{focusDetails.resetButtonLabel}</Button>
            }
          >
          <ReportCollection paginatedReports={this.state.reports} goToPage={this.goToReportsPage} />
        </Fieldset>

    )
  }

  getFocusDetails() {
    let titleSuffix = ''
    let resetFnc = ''
    let resetButtonLabel = ''
    const focusDate = moment(this.state.focusedDate).format('D MMMM YYYY')
    if (this.state.focusedLocation && this.state.focusedDate) {
      titleSuffix = `for ${this.state.focusedLocation.label} on ${focusDate}`
      resetFnc = 'goToSelection'
      resetButtonLabel = 'All locations'
    }
    return {
      titleSuffix: titleSuffix,
      resetFnc: resetFnc,
      resetButtonLabel: resetButtonLabel
    }
  }

  fetchData() {
    // Query used by the chart
    const chartQuery = this.runChartQuery(this.chartQueryParams())
    Promise.all([chartQuery]).then(values => {
      let reportsList = values[0].reportList.list
      console.log(reportsList)
      // add days without data as we want to display them in the chart
      let allCategories = this.engagementDateRangeArray.map(function(d) {
        return {
          key: d.valueOf(),
          values: [{}]
        }
      })
      let categoriesWithData = d3.nest()
        .key(function(d) { return moment(d.engagementDate).startOf('day').valueOf() })
        .key(function(d) { return (d.location) ? d.location.id : -1 })
        .rollup(function(leaves) { return leaves.length })
        .entries(reportsList)
      let groupedData = allCategories.map((d)=> {
        let categData = categoriesWithData.find((x) => { return x.key == d.key })
        return Object.assign({}, d, categData)
      })
      let graphData = {}
      graphData.data = groupedData
      graphData.categoryLabels = allCategories.reduce(
        function(prev, curr) {
          prev[curr.key] = moment(curr.key).format('D MMM YYYY')
          return prev
        },
        {}
      )
      graphData.leavesLabels = reportsList.reduce(
        function(prev, curr) {
          if (curr.location) {
            prev[curr.location.id] = curr.location.name
          }
          else {
            prev[-1] = 'No location allocated'
          }
          return prev
        },
        {}
      )
      this.setState({
        updateChart: true,  // update chart after fetching the data
        graphData: graphData
      })
    })
    this.fetchFocusData()

  }

  fetchFocusData() {
    const reportsQueryParams = {}
    Object.assign(reportsQueryParams, this.queryParams)
    Object.assign(reportsQueryParams, {pageNum: this.state.reportsPageNum})
    if (this.state.focusedDate) {
      Object.assign(reportsQueryParams, {
        // Use here the start and end of a date in order to make sure the
        // fetch is independent of the engagementDate time value
        engagementDateStart: moment(this.state.focusedDate).startOf('day').valueOf(),
        engagementDateEnd: moment(this.state.focusedDate).endOf('day').valueOf(),
        locationId: this.state.focusedLocation.key
      })
    }
    // Query used by the reports collection
    let reportsQuery = API.query(/* GraphQL */`
        reportList(f:search, query:$reportsQueryParams) {
          pageNum, pageSize, totalCount, list {
            ${ReportCollection.GQL_REPORT_FIELDS}
          }
        }
      `, {reportsQueryParams}, '($reportsQueryParams: ReportSearchQuery)')
    Promise.all([reportsQuery]).then(values => {
      this.setState({
        updateChart: false,  // only update the report list
        reports: values[0].reportList
      })
    })
  }

  chartQueryParams = () => {
    const chartQueryParams = {}
    const queryParams = this.queryParams
    Object.assign(chartQueryParams, queryParams)
    Object.assign(chartQueryParams, {
      pageSize: 0,  // retrieve all the filtered reports
    })
    return chartQueryParams
  }

  runChartQuery = (chartQueryParams) => {
    return API.query(/* GraphQL */`
    reportList(f:search, query:$chartQueryParams) {
      totalCount, list {
        ${ReportCollection.GQL_REPORT_FIELDS}
      }
    }
  `, {chartQueryParams}, '($chartQueryParams: ReportSearchQuery)')
  }

  @autobind
  goToReportsPage(newPage) {
    this.setState({updateChart: false, reportsPageNum: newPage}, () => this.fetchFocusData())
  }

  resetChartSelection(chartId) {
    d3.selectAll('#' + chartId + ' rect').attr('class', '')
  }

  @autobind
  goToSelection(item) {
    // Note: we set updateChart to false as we do not want to re-render the chart
    // when changing the focus bar
    this.setState(
      {
        updateChart: false,
        reportsPageNum: 0,
        focusedDate: (item ? parseInt(item.parentKey, 10) : ''),
        focusedLocation: (item ? {key: item.key, label: this.state.graphData.leavesLabels[item.key]} : '')
      },
      () => this.fetchFocusData()
    )
    // remove highlighting of the bars
    this.resetChartSelection(chartId)
    if (item) {
      // highlight the selected bar
      d3.select('#' + chartId + ' #bar_' + item.key + item.parentKey).attr('class', 'selected-bar')
    }
  }

  componentDidMount() {
    this.fetchData()
  }

  componentDidUpdate(prevProps, prevState) {
    const startDateChanged = prevProps.startDate.valueOf() !== this.props.startDate.valueOf()
    const endDateChanged = prevProps.endDate.valueOf() !== this.props.endDate.valueOf()
    if (startDateChanged || endDateChanged) {
      this.fetchData()
    }
  }
}
<|endoftext|>


<commit_before>/* globals BUILDCONFIG */

/* global L */
const availableProcessingOptions = [
    {
        label: 'Color Corrected',
        description:
            `Export with the color-corrections and false color composites configured
            for this project`,
        value: 'current',
        default: true
    }, {
        label: 'Raw',
        value: 'raw',
        exportOptions: {
            raw: true
        }
    }, {
        label: 'NDVI',
        value: 'ndvi',
        description:
            'Assess whether the target being observed contains live green vegetation or not',
        toolId: '7311e8ca-9af7-4fab-b63e-559d2e765388'
    }, {
        label: 'NDWI',
        value: 'ndwi',
        description:
            'An index that is primarily used to distinguish water bodies.',
        toolId: '2d3a351f-54b4-42a9-9db4-d027b9aac03c'
    }, {
        label: 'NDMI',
        value: 'ndmi',
        description:
            'An index that assesses the variation of the moisture content of vegetation.',
        toolId: '44fad5c9-1e0d-4631-aaa0-a61182619cb1'
    }
];

export default (app) => {
    class ProjectService {
        constructor(
            $resource, $location, $http, $q, APP_CONFIG,
            tokenService, authService, statusService
        ) {
            'ngInject';

            this.tokenService = tokenService;
            this.authService = authService;
            this.statusService = statusService;
            this.$http = $http;
            this.$location = $location;
            this.$q = $q;
            this.availableProcessingOptions = availableProcessingOptions;

            this.tileServer = `${APP_CONFIG.tileServerLocation}`;

            this.Project = $resource(
                `${BUILDCONFIG.API_HOST}/api/projects/:id/`, {
                    id: '@properties.id'
                }, {
                    query: {
                        method: 'GET',
                        cache: false
                    },
                    get: {
                        method: 'GET',
                        cache: false
                    },
                    create: {
                        method: 'POST'
                    },
                    delete: {
                        method: 'DELETE'
                    },
                    updateProject: {
                        method: 'PUT',
                        url: `${BUILDCONFIG.API_HOST}/api/projects/:id`,
                        params: {
                            id: '@id'
                        }
                    },
                    addScenes: {
                        method: 'POST',
                        url: `${BUILDCONFIG.API_HOST}/api/projects/:projectId/scenes/`,
                        params: {
                            projectId: '@projectId'
                        },
                        isArray: true
                    },
                    projectScenes: {
                        method: 'GET',
                        cache: false,
                        url: `${BUILDCONFIG.API_HOST}/api/projects/:projectId/scenes`,
                        params: {
                            projectId: '@projectId',
                            pending: '@pending'
                        }
                    },
                    projectAois: {
                        method: 'GET',
                        cache: false,
                        url: `${BUILDCONFIG.API_HOST}/api/projects/:projectId/areas-of-interest`,
                        params: {
                            projectId: '@projectId'
                        }
                    },
                    removeScenes: {
                        method: 'DELETE',
                        url: `${BUILDCONFIG.API_HOST}/api/projects/:projectId/scenes/`,
                        params: {
                            projectId: '@projectId'
                        }
                    },
                    export: {
                        method: 'POST',
                        url: '/api/exports/'
                    },
                    listExports: {
                        method: 'GET',
                        url: `${BUILDCONFIG.API_HOST}/api/exports?project=:project`,
                        params: {
                            project: '@project'
                        }
                    },
                    createAOI: {
                        method: 'POST',
                        url: `${BUILDCONFIG.API_HOST}/api/projects/:projectId/areas-of-interest/`,
                        params: {
                            projectId: '@projectId'
                        }
                    },
                    approveScene: {
                        method: 'POST',
                        url: `${BUILDCONFIG.API_HOST}` +
                            '/api/projects/:projectId/scenes/:sceneId/accept',
                        params: {
                            projectId: '@projectId',
                            sceneId: '@sceneId'
                        }
                    }
                }
            );
        }

        query(params = {}) {
            return this.Project.query(params).$promise;
        }

        searchQuery() {
            return this.$q((resolve, reject) => {
                let pageSize = 1000;
                let firstPageParams = {
                    pageSize: pageSize,
                    page: 0,
                    sort: 'createdAt,desc'
                };

                let firstRequest = this.query(firstPageParams);

                firstRequest.then((page) => {
                    let self = this;
                    let num = page.count;
                    let requests = [firstRequest];
                    if (page.count > pageSize) {
                        let requestMaker = function *(totalResults) {
                            let pageNum = 1;
                            while (pageNum * pageSize <= totalResults) {
                                let pageParams = {
                                    pageSize: pageSize,
                                    page: pageNum,
                                    sort: 'createdAt,desc'
                                };
                                yield self.query(pageParams);
                                pageNum += 1;
                            }
                        };

                        requests = requests.concat(Array.from(requestMaker(num)));
                    }

                    this.$q.all(requests).then(
                        (allResponses) => {
                            resolve(
                                allResponses.reduce((res, resp) => res.concat(resp.results), [])
                            );
                        },
                        () => {
                            reject('Error loading projects.');
                        }
                    );
                }, () => {
                    reject('Error loading projects.');
                });
            });
        }

        fetchProject(id) {
            return this.Project.get({id}).$promise;
        }

        listExports(params = {}) {
            return this.Project.listExports(params).$promise;
        }

        export(project, settings = {}, options = {}) {
            const defaultOptions = {
                resolution: 9,
                stitch: false,
                crop: false
            };

            const finalOptions = Object.assign(defaultOptions, options);

            const defaultSettings = {
                projectId: project.id,
                exportStatus: 'NOTEXPORTED',
                exportType: 'S3',
                visibility: 'PRIVATE',
                exportOptions: finalOptions
            };

            const finalSettings = Object.assign(defaultSettings, settings);

            const userRequest = this.authService.getCurrentUser();

            return userRequest.then(
                (user) => {
                    return this.Project.export(
                        Object.assign(finalSettings, {
                            organizationId: user.organizationId
                        })
                    ).$promise;
                },
                (error) => {
                    return error;
                }
            );
        }

        createProject(name, params = {}) {
            return this.authService.getCurrentUser().then(
                (user) => {
                    return this.Project.create({
                        organizationId: user.organizationId,
                        name: name,
                        description: params.description || '',
                        visibility: params.visibility || 'PRIVATE',
                        tileVisibility: params.tileVisibility || 'PRIVATE',
                        tags: params.tags || [],
                        isAOIProject: params.isAOIProject || false
                    }).$promise;
                },
                (error) => {
                    return error;
                }
            );
        }

        addScenes(projectId, sceneIds) {
            return this.Project.addScenes(
                {projectId: projectId},
                sceneIds
            ).$promise;
        }

        getProjectScenes(params) {
            return this.Project.projectScenes(params).$promise;
        }

        getProjectCorners(projectId) {
            return this.getAllProjectScenes({projectId: projectId}).then((scenes) => {
                let corners = {
                    lowerLeftLon: null,
                    lowerLeftLat: null,
                    upperRightLon: null,
                    upperRightLat: null
                };
                scenes.forEach(scene => {
                    let metadata = scene.sceneMetadata;
                    if (metadata.lowerLeftCornerLatitude < corners.lowerLeftLat ||
                        corners.lowerLeftLat === null) {
                        corners.lowerLeftLat = metadata.lowerLeftCornerLatitude;
                    }
                    if (metadata.lowerLeftCornerLongitude < corners.lowerLeftLon ||
                        corners.lowerLeftLon === null) {
                        corners.lowerLeftLon = metadata.lowerLeftCornerLongitude;
                    }
                    if (metadata.upperRightCornerLatitude < corners.upperRightLat ||
                        corners.upperRightLat === null) {
                        corners.upperRightLat = metadata.upperRightCornerLatitude;
                    }
                    if (metadata.upperRightCornerLongitude < corners.upperRightLon ||
                        corners.upperRightLon === null) {
                        corners.upperRightLon = metadata.upperRightCornerLongitude;
                    }
                });
                return corners;
            });
        }

        /** Return all scenes in a single collection, making multiple requests if necessary
         *
         * @param {object} params to pass as query params
         * @return {Promise} promise that will resolve when all scenes are available
         */
        getAllProjectScenes(params) {
            return this.$q((resolve, reject) => {
                let pageSize = 30;
                let firstPageParams = Object.assign({}, params, {
                    pageSize: pageSize,
                    page: 0,
                    sort: 'createdAt,desc'
                });
                let firstRequest = this.getProjectScenes(firstPageParams);

                firstRequest.then((page) => {
                    let self = this;
                    let numScenes = page.count;
                    let requests = [firstRequest];
                    if (page.count > pageSize) {
                        let requestMaker = function *(totalResults) {
                            let pageNum = 1;
                            while (pageNum * pageSize <= totalResults) {
                                let pageParams = Object.assign({}, params, {
                                    pageSize: pageSize,
                                    page: pageNum,
                                    sort: 'createdAt,desc'
                                });
                                yield self.getProjectScenes(pageParams);
                                pageNum = pageNum + 1;
                            }
                        };

                        requests = requests.concat(Array.from(requestMaker(numScenes)));
                        // Unpack responses into a single scene list.
                        // The structure to unpack is:
                        // [{ results: [{},{},...] }, { results: [{},{},...]},...]
                    }

                    this.$q.all(requests).then(
                        (allResponses) => {
                            resolve(
                                allResponses.reduce((res, resp) => res.concat(resp.results), [])
                            );
                        },
                        () => {
                            reject('Error loading scenes.');
                        }
                    );
                }, () => {
                    reject('Error loading scenes.');
                });
            });
        }

        getProjectStatus(projectId) {
            return this.getAllProjectScenes({ projectId }).then(scenes => {
                if (scenes) {
                    const counts = scenes.reduce((acc, scene) => {
                        const ingestStatus = scene.statusFields.ingestStatus;
                        acc[ingestStatus] = acc[ingestStatus] + 1 || 1;
                        return acc;
                    }, {});
                    if (counts.FAILED) {
                        return 'FAILED';
                    } else if (counts.NOTINGESTING || counts.TOBEINGESTED || counts.INGESTING) {
                        return 'PARTIAL';
                    } else if (counts.INGESTED) {
                        return 'CURRENT';
                    }
                }
                return 'NOSCENES';
            });
        }

        getProjectSceneCount(params) {
            let countParams = Object.assign({}, params, {pageSize: 1, page: 0});
            return this.Project.projectScenes(countParams).$promise;
        }

        removeScenesFromProject(projectId, scenes) {
            return this.$http({
                method: 'DELETE',
                url: `${BUILDCONFIG.API_HOST}/api/projects/${projectId}/scenes/`,
                data: scenes,
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            });
        }

        deleteProject(projectId) {
            return this.Project.delete({id: projectId}).$promise;
        }

        updateProject(params) {
            return this.Project.updateProject(params).$promise;
        }

        createAOI(project, params) {
            return this.$q((resolve, reject) => {
                this.authService.getCurrentUser().then(user => {
                    const paramsWithOrg =
                          Object.assign(params, { organizationId: user.organizationId });
                    this.Project.createAOI(
                        {projectId: project},
                        paramsWithOrg
                    ).$promise.then(() => resolve(), (err) => reject(err));
                });
            });
        }

        approveScene(projectId, sceneId) {
            return this.Project.approveScene({ projectId, sceneId }).$promise;
        }

        getProjectLayerURL(project, params) {
            let projectId = typeof project === 'object' ? project.id : project;
            let queryParams = params || {};
            queryParams.tag = new Date().getTime();
            let formattedParams = L.Util.getParamString(queryParams);

            return `${this.tileServer}/${projectId}/{z}/{x}/{y}/${formattedParams}`;
        }

        getProjectShareLayerURL(project, token) {
            let projectId = typeof project === 'object' ? project.id : project;

            let params = {
                tag: new Date().getTime()
            };

            if (token) {
                params.token = token;
            }

            let formattedParams = L.Util.getParamString(params);

            return `${this.tileServer}/${projectId}/{z}/{x}/{y}/${formattedParams}`;
        }

        getZoomLevel(bbox) {
            let diffLng = Math.abs(bbox[0] - bbox[2]);
            let diffLat = Math.abs(bbox[1] - bbox[3]);

            // Scale down if latitude is less than 55 to adjust for
            // web mercator distortion
            let lngMultiplier = bbox[0] < 55 ? 0.8 : 1;
            let maxDiff = diffLng > diffLat ? diffLng : diffLat;
            let diff = maxDiff * lngMultiplier;
            if (diff >= 0.5) {
                return 8;
            } else if (diff >= 0.01 && diff < 0.5) {
                return 11;
            } else if (diff >= 0.005 && diff < 0.01) {
                return 16;
            }
            return 18;
        }

        getProjectThumbnailURL(project, token) {
            if (project.extent) {
                let coords = project.extent.coordinates[0];
                // Lower left and upper right coordinates in extent
                let bbox = [... coords[0], ... coords[2]];
                let params = {
                    bbox: bbox,
                    zoom: this.getZoomLevel(bbox),
                    token: token
                };
                let formattedParams = L.Util.getParamString(params);
                let url = `${this.tileServer}/${project.id}/export/${formattedParams}`;
                return url;
            }
            return null;
        }

        getBaseURL() {
            let host = this.$location.host();
            let protocol = this.$location.protocol();
            let port = this.$location.port();
            let formattedPort = port !== 80 && port !== 443 ? ':' + port : '';
            return `${protocol}://${host}${formattedPort}`;
        }

        getProjectShareURL(project) {
            return this.$q((resolve, reject) => {
                let shareUrl = `${this.getBaseURL()}/share/${project.id}`;
                if (project.tileVisibility === 'PRIVATE') {
                    this.tokenService.getOrCreateProjectMapToken(project).then((token) => {
                        resolve(`${shareUrl}/?mapToken=${token.id}`);
                    }, (error) => reject(error));
                } else {
                    resolve(shareUrl);
                }
            });
        }

        getProjectAois(projectId) {
            return this.Project.projectAois({projectId: projectId}).$promise;
        }
    }

    app.service('projectService', ProjectService);
};
<commit_msg>Use `API_HOST` for project export url<commit_after>/* globals BUILDCONFIG */

/* global L */
const availableProcessingOptions = [
    {
        label: 'Color Corrected',
        description:
            `Export with the color-corrections and false color composites configured
            for this project`,
        value: 'current',
        default: true
    }, {
        label: 'Raw',
        value: 'raw',
        exportOptions: {
            raw: true
        }
    }, {
        label: 'NDVI',
        value: 'ndvi',
        description:
            'Assess whether the target being observed contains live green vegetation or not',
        toolId: '7311e8ca-9af7-4fab-b63e-559d2e765388'
    }, {
        label: 'NDWI',
        value: 'ndwi',
        description:
            'An index that is primarily used to distinguish water bodies.',
        toolId: '2d3a351f-54b4-42a9-9db4-d027b9aac03c'
    }, {
        label: 'NDMI',
        value: 'ndmi',
        description:
            'An index that assesses the variation of the moisture content of vegetation.',
        toolId: '44fad5c9-1e0d-4631-aaa0-a61182619cb1'
    }
];

export default (app) => {
    class ProjectService {
        constructor(
            $resource, $location, $http, $q, APP_CONFIG,
            tokenService, authService, statusService
        ) {
            'ngInject';

            this.tokenService = tokenService;
            this.authService = authService;
            this.statusService = statusService;
            this.$http = $http;
            this.$location = $location;
            this.$q = $q;
            this.availableProcessingOptions = availableProcessingOptions;

            this.tileServer = `${APP_CONFIG.tileServerLocation}`;

            this.Project = $resource(
                `${BUILDCONFIG.API_HOST}/api/projects/:id/`, {
                    id: '@properties.id'
                }, {
                    query: {
                        method: 'GET',
                        cache: false
                    },
                    get: {
                        method: 'GET',
                        cache: false
                    },
                    create: {
                        method: 'POST'
                    },
                    delete: {
                        method: 'DELETE'
                    },
                    updateProject: {
                        method: 'PUT',
                        url: `${BUILDCONFIG.API_HOST}/api/projects/:id`,
                        params: {
                            id: '@id'
                        }
                    },
                    addScenes: {
                        method: 'POST',
                        url: `${BUILDCONFIG.API_HOST}/api/projects/:projectId/scenes/`,
                        params: {
                            projectId: '@projectId'
                        },
                        isArray: true
                    },
                    projectScenes: {
                        method: 'GET',
                        cache: false,
                        url: `${BUILDCONFIG.API_HOST}/api/projects/:projectId/scenes`,
                        params: {
                            projectId: '@projectId',
                            pending: '@pending'
                        }
                    },
                    projectAois: {
                        method: 'GET',
                        cache: false,
                        url: `${BUILDCONFIG.API_HOST}/api/projects/:projectId/areas-of-interest`,
                        params: {
                            projectId: '@projectId'
                        }
                    },
                    removeScenes: {
                        method: 'DELETE',
                        url: `${BUILDCONFIG.API_HOST}/api/projects/:projectId/scenes/`,
                        params: {
                            projectId: '@projectId'
                        }
                    },
                    export: {
                        method: 'POST',
                        url: `${BUILDCONFIG.API_HOST}/api/exports/`
                    },
                    listExports: {
                        method: 'GET',
                        url: `${BUILDCONFIG.API_HOST}/api/exports?project=:project`,
                        params: {
                            project: '@project'
                        }
                    },
                    createAOI: {
                        method: 'POST',
                        url: `${BUILDCONFIG.API_HOST}/api/projects/:projectId/areas-of-interest/`,
                        params: {
                            projectId: '@projectId'
                        }
                    },
                    approveScene: {
                        method: 'POST',
                        url: `${BUILDCONFIG.API_HOST}` +
                            '/api/projects/:projectId/scenes/:sceneId/accept',
                        params: {
                            projectId: '@projectId',
                            sceneId: '@sceneId'
                        }
                    }
                }
            );
        }

        query(params = {}) {
            return this.Project.query(params).$promise;
        }

        searchQuery() {
            return this.$q((resolve, reject) => {
                let pageSize = 1000;
                let firstPageParams = {
                    pageSize: pageSize,
                    page: 0,
                    sort: 'createdAt,desc'
                };

                let firstRequest = this.query(firstPageParams);

                firstRequest.then((page) => {
                    let self = this;
                    let num = page.count;
                    let requests = [firstRequest];
                    if (page.count > pageSize) {
                        let requestMaker = function *(totalResults) {
                            let pageNum = 1;
                            while (pageNum * pageSize <= totalResults) {
                                let pageParams = {
                                    pageSize: pageSize,
                                    page: pageNum,
                                    sort: 'createdAt,desc'
                                };
                                yield self.query(pageParams);
                                pageNum += 1;
                            }
                        };

                        requests = requests.concat(Array.from(requestMaker(num)));
                    }

                    this.$q.all(requests).then(
                        (allResponses) => {
                            resolve(
                                allResponses.reduce((res, resp) => res.concat(resp.results), [])
                            );
                        },
                        () => {
                            reject('Error loading projects.');
                        }
                    );
                }, () => {
                    reject('Error loading projects.');
                });
            });
        }

        fetchProject(id) {
            return this.Project.get({id}).$promise;
        }

        listExports(params = {}) {
            return this.Project.listExports(params).$promise;
        }

        export(project, settings = {}, options = {}) {
            const defaultOptions = {
                resolution: 9,
                stitch: false,
                crop: false
            };

            const finalOptions = Object.assign(defaultOptions, options);

            const defaultSettings = {
                projectId: project.id,
                exportStatus: 'NOTEXPORTED',
                exportType: 'S3',
                visibility: 'PRIVATE',
                exportOptions: finalOptions
            };

            const finalSettings = Object.assign(defaultSettings, settings);

            const userRequest = this.authService.getCurrentUser();

            return userRequest.then(
                (user) => {
                    return this.Project.export(
                        Object.assign(finalSettings, {
                            organizationId: user.organizationId
                        })
                    ).$promise;
                },
                (error) => {
                    return error;
                }
            );
        }

        createProject(name, params = {}) {
            return this.authService.getCurrentUser().then(
                (user) => {
                    return this.Project.create({
                        organizationId: user.organizationId,
                        name: name,
                        description: params.description || '',
                        visibility: params.visibility || 'PRIVATE',
                        tileVisibility: params.tileVisibility || 'PRIVATE',
                        tags: params.tags || [],
                        isAOIProject: params.isAOIProject || false
                    }).$promise;
                },
                (error) => {
                    return error;
                }
            );
        }

        addScenes(projectId, sceneIds) {
            return this.Project.addScenes(
                {projectId: projectId},
                sceneIds
            ).$promise;
        }

        getProjectScenes(params) {
            return this.Project.projectScenes(params).$promise;
        }

        getProjectCorners(projectId) {
            return this.getAllProjectScenes({projectId: projectId}).then((scenes) => {
                let corners = {
                    lowerLeftLon: null,
                    lowerLeftLat: null,
                    upperRightLon: null,
                    upperRightLat: null
                };
                scenes.forEach(scene => {
                    let metadata = scene.sceneMetadata;
                    if (metadata.lowerLeftCornerLatitude < corners.lowerLeftLat ||
                        corners.lowerLeftLat === null) {
                        corners.lowerLeftLat = metadata.lowerLeftCornerLatitude;
                    }
                    if (metadata.lowerLeftCornerLongitude < corners.lowerLeftLon ||
                        corners.lowerLeftLon === null) {
                        corners.lowerLeftLon = metadata.lowerLeftCornerLongitude;
                    }
                    if (metadata.upperRightCornerLatitude < corners.upperRightLat ||
                        corners.upperRightLat === null) {
                        corners.upperRightLat = metadata.upperRightCornerLatitude;
                    }
                    if (metadata.upperRightCornerLongitude < corners.upperRightLon ||
                        corners.upperRightLon === null) {
                        corners.upperRightLon = metadata.upperRightCornerLongitude;
                    }
                });
                return corners;
            });
        }

        /** Return all scenes in a single collection, making multiple requests if necessary
         *
         * @param {object} params to pass as query params
         * @return {Promise} promise that will resolve when all scenes are available
         */
        getAllProjectScenes(params) {
            return this.$q((resolve, reject) => {
                let pageSize = 30;
                let firstPageParams = Object.assign({}, params, {
                    pageSize: pageSize,
                    page: 0,
                    sort: 'createdAt,desc'
                });
                let firstRequest = this.getProjectScenes(firstPageParams);

                firstRequest.then((page) => {
                    let self = this;
                    let numScenes = page.count;
                    let requests = [firstRequest];
                    if (page.count > pageSize) {
                        let requestMaker = function *(totalResults) {
                            let pageNum = 1;
                            while (pageNum * pageSize <= totalResults) {
                                let pageParams = Object.assign({}, params, {
                                    pageSize: pageSize,
                                    page: pageNum,
                                    sort: 'createdAt,desc'
                                });
                                yield self.getProjectScenes(pageParams);
                                pageNum = pageNum + 1;
                            }
                        };

                        requests = requests.concat(Array.from(requestMaker(numScenes)));
                        // Unpack responses into a single scene list.
                        // The structure to unpack is:
                        // [{ results: [{},{},...] }, { results: [{},{},...]},...]
                    }

                    this.$q.all(requests).then(
                        (allResponses) => {
                            resolve(
                                allResponses.reduce((res, resp) => res.concat(resp.results), [])
                            );
                        },
                        () => {
                            reject('Error loading scenes.');
                        }
                    );
                }, () => {
                    reject('Error loading scenes.');
                });
            });
        }

        getProjectStatus(projectId) {
            return this.getAllProjectScenes({ projectId }).then(scenes => {
                if (scenes) {
                    const counts = scenes.reduce((acc, scene) => {
                        const ingestStatus = scene.statusFields.ingestStatus;
                        acc[ingestStatus] = acc[ingestStatus] + 1 || 1;
                        return acc;
                    }, {});
                    if (counts.FAILED) {
                        return 'FAILED';
                    } else if (counts.NOTINGESTING || counts.TOBEINGESTED || counts.INGESTING) {
                        return 'PARTIAL';
                    } else if (counts.INGESTED) {
                        return 'CURRENT';
                    }
                }
                return 'NOSCENES';
            });
        }

        getProjectSceneCount(params) {
            let countParams = Object.assign({}, params, {pageSize: 1, page: 0});
            return this.Project.projectScenes(countParams).$promise;
        }

        removeScenesFromProject(projectId, scenes) {
            return this.$http({
                method: 'DELETE',
                url: `${BUILDCONFIG.API_HOST}/api/projects/${projectId}/scenes/`,
                data: scenes,
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            });
        }

        deleteProject(projectId) {
            return this.Project.delete({id: projectId}).$promise;
        }

        updateProject(params) {
            return this.Project.updateProject(params).$promise;
        }

        createAOI(project, params) {
            return this.$q((resolve, reject) => {
                this.authService.getCurrentUser().then(user => {
                    const paramsWithOrg =
                          Object.assign(params, { organizationId: user.organizationId });
                    this.Project.createAOI(
                        {projectId: project},
                        paramsWithOrg
                    ).$promise.then(() => resolve(), (err) => reject(err));
                });
            });
        }

        approveScene(projectId, sceneId) {
            return this.Project.approveScene({ projectId, sceneId }).$promise;
        }

        getProjectLayerURL(project, params) {
            let projectId = typeof project === 'object' ? project.id : project;
            let queryParams = params || {};
            queryParams.tag = new Date().getTime();
            let formattedParams = L.Util.getParamString(queryParams);

            return `${this.tileServer}/${projectId}/{z}/{x}/{y}/${formattedParams}`;
        }

        getProjectShareLayerURL(project, token) {
            let projectId = typeof project === 'object' ? project.id : project;

            let params = {
                tag: new Date().getTime()
            };

            if (token) {
                params.token = token;
            }

            let formattedParams = L.Util.getParamString(params);

            return `${this.tileServer}/${projectId}/{z}/{x}/{y}/${formattedParams}`;
        }

        getZoomLevel(bbox) {
            let diffLng = Math.abs(bbox[0] - bbox[2]);
            let diffLat = Math.abs(bbox[1] - bbox[3]);

            // Scale down if latitude is less than 55 to adjust for
            // web mercator distortion
            let lngMultiplier = bbox[0] < 55 ? 0.8 : 1;
            let maxDiff = diffLng > diffLat ? diffLng : diffLat;
            let diff = maxDiff * lngMultiplier;
            if (diff >= 0.5) {
                return 8;
            } else if (diff >= 0.01 && diff < 0.5) {
                return 11;
            } else if (diff >= 0.005 && diff < 0.01) {
                return 16;
            }
            return 18;
        }

        getProjectThumbnailURL(project, token) {
            if (project.extent) {
                let coords = project.extent.coordinates[0];
                // Lower left and upper right coordinates in extent
                let bbox = [... coords[0], ... coords[2]];
                let params = {
                    bbox: bbox,
                    zoom: this.getZoomLevel(bbox),
                    token: token
                };
                let formattedParams = L.Util.getParamString(params);
                let url = `${this.tileServer}/${project.id}/export/${formattedParams}`;
                return url;
            }
            return null;
        }

        getBaseURL() {
            let host = this.$location.host();
            let protocol = this.$location.protocol();
            let port = this.$location.port();
            let formattedPort = port !== 80 && port !== 443 ? ':' + port : '';
            return `${protocol}://${host}${formattedPort}`;
        }

        getProjectShareURL(project) {
            return this.$q((resolve, reject) => {
                let shareUrl = `${this.getBaseURL()}/share/${project.id}`;
                if (project.tileVisibility === 'PRIVATE') {
                    this.tokenService.getOrCreateProjectMapToken(project).then((token) => {
                        resolve(`${shareUrl}/?mapToken=${token.id}`);
                    }, (error) => reject(error));
                } else {
                    resolve(shareUrl);
                }
            });
        }

        getProjectAois(projectId) {
            return this.Project.projectAois({projectId: projectId}).$promise;
        }
    }

    app.service('projectService', ProjectService);
};
<|endoftext|>


<commit_before>var map;
var infowindow;
var service;
var userPosition;
var idCounter = 0;
var idCounterTwo = 0;
var listArray = new Array();
var listTwoArray = new Array();
var searchBox;
var isGetLocationChecked = false;

/*
* Funktion som initiera Google Maps kartan och tar redan
*/

function initMap() {
	map = new google.maps.Map(document.getElementById('map'), {
	  center: {lat: 55.5916628, lng: 12.9875187},
	  zoom: 12,
      scrollwheel: false
	});

	service = new google.maps.places.PlacesService(map);
	infowindow = new google.maps.InfoWindow();
	autoCompleteFunction();
}

function autoCompleteFunction(){
// Create the search box and link it to the UI element.
  var input = document.getElementById('pac-input');
  searchBox = new google.maps.places.Autocomplete(input);

  // Bias the SearchBox results towards current map's viewport.
  map.addListener('bounds_changed', function() {
    searchBox.setBounds(map.getBounds());
  });

  //var markers = [];
}

/*
* Funktion som triggras när man klickar på Get Location knappen
* funktionen tar reda på användarens position
*/
$("#getLocationBtn").click(function() {

	var location_timeout = setTimeout("geolocFail()", 10000);
	document.getElementById('getLocationBtn').innerHTML= "Loading...  ";

	if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position){
			clearTimeout(location_timeout);
			userPosition = {lat:position.coords.latitude, lng: position.coords.longitude};
			console.log(userPosition);
			makeSearch(userPosition);
            document.getElementById('getLocationBtn').innerHTML= "Got it ✓";
			if (position){
				var button = document.querySelector("#searchBtn")
				button.className = "btn btn-dark btn-lg activated";
				isGetLocationChecked = true;
			}
			document.getElementById('resultFromAPI').innerHTML= " ";
			document.getElementById('resultTwoFromAPI').innerHTML= " ";
		},function(error) {
            document.getElementById('getLocationBtn').innerHTML= "Access denied   ✖";
            clearTimeout(location_timeout);
		});
	} else {
        document.getElementById('getLocationBtn').innerHTML= "Geolocation not supported";
        alert("Geolocation is not supported by this browser.");
    }
});

$("#searchBtn").click(function(){
	if($('#pac-input').val().length != 0){
        document.getElementById('resultFromAPI').innerHTML= " ";
        document.getElementById('resultTwoFromAPI').innerHTML= " ";
		var place = searchBox.getPlace();
		var latitude = place.geometry.location.lat();
		var longitude = place.geometry.location.lng();
		var location = {lat: latitude, lng: longitude};
		makeSearch(location);
		show();
		$('html, body').animate({
            scrollTop: $("#portfolio").offset().top
    	}, 2000);
	}else if(isGetLocationChecked == true){
		show();
		$('html, body').animate({
            scrollTop: $("#portfolio").offset().top
		}, 2000);
	}else{
		alert("Something went wrong, please write in your adress or get your location!");
	}
});

function showSearch(){
    var pacCard = document.querySelector("#pac-card");
    pacCard.className = "pac-card visShow";
}

/*
* Funktion som gör sökningen av närliggande resturanger från användarens position
*/
function makeSearch(userPosition){
	var userPos = userPosition;
	console.log(userPosition);
	var request = {
		location: userPos,
	  	radius: 1000,
	  	type: ['restaurant'],
		opennow: true
	}
	service.nearbySearch(request, callback);

}

/*
* Funktion som tar emot närliggande resturanger ifrån APIn
*/
function callback(results, status) {
	console.log(status);
	console.log(results);
    $("resultsFromAPI").text(" ");
	if (status === google.maps.places.PlacesServiceStatus.OK) {
		for (var i = 0; i < results.length; i++) {
			if (i <= 9) {
				$("#resultFromAPI").append('' + results[i].name + '');
				var restaurantSection = document.querySelector("#portfolio");
				restaurantSection.className = "show";
				listArray.push(results[i]);
				idCounter++;
            } else {
                $("#resultTwoFromAPI").append('' + results[i].name + '');
                listTwoArray.push(results[i]);
                idCounterTwo++;
            }
        }
		createUserMarker();
	}
}

/*
* Funktion som skapar markern för användarens position i kartan
*/
function createUserMarker(){
	var userMarker = new google.maps.Marker({
		position: userPosition,
		map: map,
		title: 'Din position',
		icon: 'http://maps.google.com/mapfiles/ms/icons/blue.png'
	});

	google.maps.event.addListener(userMarker, 'click', function() {
		infowindow.setContent("Your position");
		infowindow.open(map, this);
	});
}

/*
* Funktion som triggas när man klickar på ett resturangnamn i listan
* funktionen tar reda på vilken resturang man har klickat
*/
$('#resultFromAPI').on('click', '.selectedRestaurang', function(){
	console.log(this.id);
	console.log(listArray[this.id]);
	var currentId = listArray[this.id];
	createMarker(currentId);
	$('html, body').animate({
        scrollTop: $("#contact").offset().top
    }, 2000);
});
$('#resultTwoFromAPI').on('click', '.selectedRestaurang', function(){
	console.log(this.id);
	console.log(listTwoArray[this.id]);
	var currentId = listTwoArray[this.id];
	createMarker(currentId);
	$('html, body').animate({
        scrollTop: $("#contact").offset().top
    }, 2000);
});

/*
* Funktion som sätter ut en marker för en vald resturang
* Visar även detljer för varje resturang i liten ruta när
* man klickar på en ikon
*/

function createMarker(place) {
	var los = place.geometry.location;
	var infowindow = new google.maps.InfoWindow({ map: map });
    infowindow.close();
	var marker = new google.maps.Marker({
	  map: map,
	  position: place.geometry.location
	});

	marker.addListener('click', function(){
		var request = {
			reference: place.reference
		};
		service.getDetails(request, function(details, status) {
			console.log(details)
			infowindow.setContent([
			details.name,
			details.formatted_address,
			'' + details.website + '',
			details.opening_hours.weekday_text[0],
			details.opening_hours.weekday_text[1],
			details.opening_hours.weekday_text[2],
			details.opening_hours.weekday_text[3],
			details.opening_hours.weekday_text[4],
			details.opening_hours.weekday_text[5],
			details.opening_hours.weekday_text[6],
			'Betyg: ' + details.rating,
			details.formatted_phone_number].join("
"));
		  infowindow.open(map, marker);

		});
	})

	map.setZoom(15);
	map.panTo(marker.position);
}

// ----- DÖLJER ALLT UTOM FÖRSTASIDAN I FÖRSTA LÄGET & VISAR ALLT NÄR MAN TRYCKER PÅ SÖK -----

function show(){
    var menuSection = document.querySelector(".menu");
		var portfolio = document.querySelector("#portfolio");
    var mapSection = document.querySelector("#contact");
    var footerSection = document.querySelector("#footer");
		var map = document.querySelector("#map")

    menuSection.className = "visShow";
		portfolio.className = "show"
    mapSection.className = "show";
    footerSection.className = "show";
		map.className ="show"

		$(document).ready(function() {
    $(window).resize(function() {
        google.maps.event.trigger(map, 'resize');
    });
    google.maps.event.trigger(map, 'resize');
});

}
<commit_msg>Fixed uno bugg<commit_after>var map;
var infowindow;
var service;
var userPosition;
var idCounter = 0;
var idCounterTwo = 0;
var listArray = new Array();
var listTwoArray = new Array();
var searchBox;
var isGetLocationChecked = false;

/*
* Funktion som initiera Google Maps kartan och tar redan
*/

function initMap() {
	map = new google.maps.Map(document.getElementById('map'), {
	  center: {lat: 55.5916628, lng: 12.9875187},
	  zoom: 12,
      scrollwheel: false
	});

	service = new google.maps.places.PlacesService(map);
	infowindow = new google.maps.InfoWindow();
	autoCompleteFunction();
}

function autoCompleteFunction(){
// Create the search box and link it to the UI element.
  var input = document.getElementById('pac-input');
  searchBox = new google.maps.places.Autocomplete(input);

  // Bias the SearchBox results towards current map's viewport.
  map.addListener('bounds_changed', function() {
    searchBox.setBounds(map.getBounds());
  });

  //var markers = [];
}

/*
* Funktion som triggras när man klickar på Get Location knappen
* funktionen tar reda på användarens position
*/
$("#getLocationBtn").click(function() {

	var location_timeout = setTimeout("geolocFail()", 10000);
	document.getElementById('getLocationBtn').innerHTML= "Loading...  ";

	if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position){
			clearTimeout(location_timeout);
			userPosition = {lat:position.coords.latitude, lng: position.coords.longitude};
			console.log(userPosition);
			makeSearch(userPosition);
            document.getElementById('getLocationBtn').innerHTML= "Got it ✓";
			if (position){
				var button = document.querySelector("#searchBtn")
				button.className = "btn btn-dark btn-lg activated";
				isGetLocationChecked = true;
			}
			document.getElementById('resultFromAPI').innerHTML= " ";
			document.getElementById('resultTwoFromAPI').innerHTML= " ";
		},function(error) {
            document.getElementById('getLocationBtn').innerHTML= "Access denied   ✖";
            clearTimeout(location_timeout);
		});
	} else {
        document.getElementById('getLocationBtn').innerHTML= "Geolocation not supported";
        alert("Geolocation is not supported by this browser.");
    }
});

$("#searchBtn").click(function(){

	if($('#pac-input').val().length != 0){
        document.getElementById('resultFromAPI').innerHTML= " ";
        document.getElementById('resultTwoFromAPI').innerHTML= " ";
		var place = searchBox.getPlace();
		var latitude = place.geometry.location.lat();
		var longitude = place.geometry.location.lng();
		var location = {lat: latitude, lng: longitude};
		makeSearch(location);
		show();
		$('html, body').animate({
            scrollTop: $("#portfolio").offset().top
    	}, 2000);
			document.getElementById('pac-input').value= "";
	}else if(isGetLocationChecked == true){
		show();
		$('html, body').animate({
            scrollTop: $("#portfolio").offset().top
		}, 2000);
	}else{
		alert("Something went wrong, please write in your adress or get your location!");
	}
});

function showSearch(){
    var pacCard = document.querySelector("#pac-card");
    pacCard.className = "pac-card visShow";
}

/*
* Funktion som gör sökningen av närliggande resturanger från användarens position
*/
function makeSearch(userPosition){
	var userPos = userPosition;
	console.log(userPosition);
	var request = {
		location: userPos,
	  	radius: 1000,
	  	type: ['restaurant'],
		opennow: true
	}
	service.nearbySearch(request, callback);

}

/*
* Funktion som tar emot närliggande resturanger ifrån APIn
*/
function callback(results, status) {
	console.log(status);
	console.log(results);
    $("resultsFromAPI").text(" ");
	if (status === google.maps.places.PlacesServiceStatus.OK) {
		for (var i = 0; i < results.length; i++) {
			if (i <= 9) {
				$("#resultFromAPI").append('' + results[i].name + '');
				var restaurantSection = document.querySelector("#portfolio");
				restaurantSection.className = "show";
				listArray.push(results[i]);
				idCounter++;
            } else {
                $("#resultTwoFromAPI").append('' + results[i].name + '');
                listTwoArray.push(results[i]);
                idCounterTwo++;
            }
        }
		createUserMarker();
	}
}

/*
* Funktion som skapar markern för användarens position i kartan
*/
function createUserMarker(){
	var userMarker = new google.maps.Marker({
		position: userPosition,
		map: map,
		title: 'Din position',
		icon: 'http://maps.google.com/mapfiles/ms/icons/blue.png'
	});

	google.maps.event.addListener(userMarker, 'click', function() {
		infowindow.setContent("Your position");
		infowindow.open(map, this);
	});
}

/*
* Funktion som triggas när man klickar på ett resturangnamn i listan
* funktionen tar reda på vilken resturang man har klickat
*/
$('#resultFromAPI').on('click', '.selectedRestaurang', function(){
	console.log(this.id);
	console.log(listArray[this.id]);
	var currentId = listArray[this.id];
	createMarker(currentId);
	$('html, body').animate({
        scrollTop: $("#contact").offset().top
    }, 2000);
});
$('#resultTwoFromAPI').on('click', '.selectedRestaurang', function(){
	console.log(this.id);
	console.log(listTwoArray[this.id]);
	var currentId = listTwoArray[this.id];
	createMarker(currentId);
	$('html, body').animate({
        scrollTop: $("#contact").offset().top
    }, 2000);
});

/*
* Funktion som sätter ut en marker för en vald resturang
* Visar även detljer för varje resturang i liten ruta när
* man klickar på en ikon
*/

function createMarker(place) {
	var los = place.geometry.location;
	var infowindow = new google.maps.InfoWindow({ map: map });
    infowindow.close();
	var marker = new google.maps.Marker({
	  map: map,
	  position: place.geometry.location
	});

	marker.addListener('click', function(){
		var request = {
			reference: place.reference
		};
		service.getDetails(request, function(details, status) {
			console.log(details)
			infowindow.setContent([
			details.name,
			details.formatted_address,
			'' + details.website + '',
			details.opening_hours.weekday_text[0],
			details.opening_hours.weekday_text[1],
			details.opening_hours.weekday_text[2],
			details.opening_hours.weekday_text[3],
			details.opening_hours.weekday_text[4],
			details.opening_hours.weekday_text[5],
			details.opening_hours.weekday_text[6],
			'Betyg: ' + details.rating,
			details.formatted_phone_number].join("
"));
		  infowindow.open(map, marker);

		});
	})

	map.setZoom(15);
	map.panTo(marker.position);
}

// ----- DÖLJER ALLT UTOM FÖRSTASIDAN I FÖRSTA LÄGET & VISAR ALLT NÄR MAN TRYCKER PÅ SÖK -----

function show(){
    var menuSection = document.querySelector(".menu");
		var portfolio = document.querySelector("#portfolio");
    var mapSection = document.querySelector("#contact");
    var footerSection = document.querySelector("#footer");
		var map = document.querySelector("#map")

    menuSection.className = "visShow";
		portfolio.className = "show"
    mapSection.className = "show";
    footerSection.className = "show";
		map.className ="show"

		$(document).ready(function() {
    $(window).resize(function() {
        google.maps.event.trigger(map, 'resize');
    });
    google.maps.event.trigger(map, 'resize');
});

}
<|endoftext|>