<commit_before>'use strict';

import React from 'react';
import PropTypes from 'prop-types';
import _ from 'underscore';
import { console, object, ajax } from '@hms-dbmi-bgm/shared-portal-components/es/components/util';
import { BasicUserContentBody, ExpandableStaticHeader } from './../components/BasicUserContentBody';
import { HiGlassLoadingIndicator } from './../../item-pages/components/HiGlass/HiGlassPlainContainer';

export class HiGlassEmbeddedInstance extends React.PureComponent {

    static defaultProps = {
        "headerElement": "h3",
        "headerClassName": "section-title"
    };

    static propTypes = {
        "uuid": PropTypes.string.isRequired,
        "headerElement": PropTypes.string,
        "headerClassName": PropTypes.string,
    };

    constructor(props) {
        super(props);
        this.state = {
            'loading': false,
            'higlassItem': null
        };
    }

    componentDidMount() {
        const { higlassItem } = this.state;
        const { uuid } = this.props;
        if (!higlassItem && uuid && typeof uuid === 'string' && uuid.length > 0) {
            this.setState({ 'loading': true }, () => {
                // Use the @id to get the item, then remove the loading message
                ajax.load('/higlass-view-configs/' + uuid, (r) => {
                    this.setState({ 'higlassItem': r, 'loading': false });
                });
            });
        }
    }

    render() {
        const { headerElement = 'h3', headerClassName = "section-title" } = this.props;
        const { higlassItem, loading } = this.state;
        // If HiGlass item is loaded, then display viewer
        if (higlassItem) {
            const { title, options: { collapsible: isCollapsible = false, default_open = true } = {} } = higlassItem;
            const headerProps = { className: headerClassName };
            return (
                <React.Fragment>
                    {title && !isCollapsible ? React.createElement(headerElement, headerProps, title) : null}
                    {
                        isCollapsible ?
                            <ExpandableStaticHeader context={higlassItem} defaultOpen={default_open} title={title} href={null} titleElement={headerElement} titleTip={higlassItem.description} />
                            : <BasicUserContentBody context={higlassItem} href={null} />
                    }
                </React.Fragment>
            );
        }
        // If we're loading, show a loading screen
        if (loading) {
            return
<HiGlassLoadingIndicator title="Loading" />
;
        }
        return null;
    }
}<commit_msg>minor style updates<commit_after>'use strict';

import React from 'react';
import PropTypes from 'prop-types';
import _ from 'underscore';
import { console, object, ajax } from '@hms-dbmi-bgm/shared-portal-components/es/components/util';
import { BasicUserContentBody, ExpandableStaticHeader } from './../components/BasicUserContentBody';
import { HiGlassLoadingIndicator } from './../../item-pages/components/HiGlass/HiGlassPlainContainer';

export class HiGlassEmbeddedInstance extends React.PureComponent {

    static defaultProps = {
        "headerElement": "h3",
        "headerClassName": "tab-section-title mb-0"
    };

    static propTypes = {
        "uuid": PropTypes.string.isRequired,
        "headerElement": PropTypes.string,
        "headerClassName": PropTypes.string,
    };

    constructor(props) {
        super(props);
        this.state = {
            'loading': false,
            'higlassItem': null
        };
    }

    componentDidMount() {
        const { higlassItem } = this.state;
        const { uuid } = this.props;
        if (!higlassItem && uuid && typeof uuid === 'string' && uuid.length > 0) {
            this.setState({ 'loading': true }, () => {
                // Use the @id to get the item, then remove the loading message
                ajax.load('/higlass-view-configs/' + uuid, (r) => {
                    this.setState({ 'higlassItem': r, 'loading': false });
                });
            });
        }
    }

    render() {
        const { headerElement = 'h3', headerClassName = "tab-section-title mb-0" } = this.props;
        const { higlassItem, loading } = this.state;
        // If HiGlass item is loaded, then display viewer
        if (higlassItem) {
            const { title: propTitle, options: { collapsible: isCollapsible = false, default_open = true } = {} } = higlassItem;
            const headerProps = { className: headerClassName };
            const title = (propTitle && !isCollapsible) ? React.createElement(headerElement, headerProps, propTitle) : null;

            return (
                <React.Fragment>
                    {title}
                    {title ? (

) : null}
                    {
                        isCollapsible ?
                            <ExpandableStaticHeader context={higlassItem} defaultOpen={default_open} title={propTitle} href={null} titleElement={headerElement} titleTip={higlassItem.description} titleClassName="mb-0" />
                            : <BasicUserContentBody context={higlassItem} href={null} />
                    }
                </React.Fragment>
            );
        }
        // If we're loading, show a loading screen
        if (loading) {
            return
<HiGlassLoadingIndicator title="Loading" />
;
        }
        return null;
    }
}<|endoftext|>


<commit_before>(function() {

    angular
        .module('app')
        .controller('DashboardController', [
            '$mdDialog',
            '$scope',
            'tokenService',
            'Upload',
            '$location',
            '$sce',
            '$filter',
            '$state',
            '$rootScope',
            DashboardController
        ]);

    function DashboardController($mdDialog, $scope, tokenService, Upload, $location, $sce, $filter, $state, $rootScope) {
        $scope.events = {};

        $scope.updatesLoading = true;
        $scope.eventLoading = true;
        $scope.eventTopLoading = true;
        $scope.creativityLoading = false;
        $scope.contentTopLoading = true;
        $scope.offset = 0;
        $scope.nonFinalContents = [];
        $scope.finalContents = [];
        $scope.types = [
            { 'title': 'Articles', 'id': 1 },
            { 'title': 'Poetry', 'id': 2 },
            { 'title': 'Drama', 'id': 3 },
            { 'title': 'Paint and Colour', 'id': 4 },
            { 'title': 'Drawing ', 'id': 5 },
            { 'title': 'Sewing and Fabric', 'id': 6 },
            { 'title': 'Craft', 'id': 7 },
            // { 'title': 'Dancing', 'id': 8 },
            { 'title': 'Dancing', 'id': 8 },
            { 'title': 'Singing', 'id': 9 },
            { 'title': 'Instrumental', 'id': 10 },
            { 'title': 'Digital Music', 'id': 11 },
            { 'title': 'Decor', 'id': 12 },
            { 'title': 'Film and Video', 'id': 13 },
            { 'title': 'Animation', 'id': 14 },
            { 'title': 'Graphics', 'id': 15 },
            { 'title': 'UI and UX', 'id': 16 },
            { 'title': 'Websites', 'id': 17 },
            { 'title': 'Programming', 'id': 18 },
            { 'title': 'Apps', 'id': 19 },
            { 'title': 'Electronics', 'id': 20 },
            { 'title': 'DIY', 'id': 21 }
        ];

        $scope.tags = ['AngularJs', 'Web Developement', 'Elon Musk', 'Poetry', 'Artificial Intelligence', 'Product Design', 'Feminism', 'Technology', 'Self Driving Cars'];
        var cardObject = {};
        $scope.finalContents = [];
        $scope.mediaTypes = [4, 5, 6, 7, 12, 15, 16];

        // tokenService.get("eventsDashboard")
        // changing temporarily till api is fixed
        tokenService.get("minievents?limit=3")
            .then(function(events) {
                $scope.events = events.data;
                $scope.eventLoading = false;
                // $scope.myPagingFunction();
                // tokenService.get("contentsRandom")
                tokenService.get("contentsRandom")
                    .then(function(contentsDashboard) {
                        $scope.contents = contentsDashboard.data;
                        $scope.contentsTop = contentsDashboard.data;
                        $scope.contentLoading = false;
                        $scope.contentTopLoading = false;
                        $scope.contents.forEach(function(content) {
                            cardObject = {}
                            $scope.loading == false;
                            cardObject.Actions = content.Actions;
                            cardObject.Tags = content.Tags;
                            cardObject.created = content.created;
                            cardObject.created.at = Date.parse(cardObject.created.at.replace('-', '/', 'g')); //replace mysql date to js date format
                            cardObject.id = content.id;
                            cardObject.title = $sce.trustAsHtml(content.title);
                            cardObject.links = content.links;
                            cardObject.total = content.links;
                            content.Items.data.forEach(function(item) {
                                if (item.type == 'text') {
                                    cardObject.description = item.description;
                                    // cardObject.description = $filter('limitTo')(item.description, 110, 0);
                                    cardObject.description = $sce.trustAsHtml(cardObject.description);
                                } else if (item.type == 'cover' && !cardObject.type) {
                                    cardObject.type = item.type;
                                    cardObject.url = item.image;
                                } else if ((item.type == 'youtube' || item.type == 'soundcloud' || item.type == 'vimeo') && !cardObject.type) {
                                    cardObject.type = item.type;
                                    cardObject.url = $sce.trustAsResourceUrl(item.embed.url);
                                } else if (((item.type == 'cover') || (item.type == 'image')) && !cardObject.type) {
                                    cardObject.type = item.type;
                                    cardObject.url = item.image;
                                }
                            });
                            if (cardObject.type != 'cover' || cardObject.type != 'soundcloud' || cardObject.type != 'youtube') {
                                cardObject.description = $filter('limitTo')(cardObject.description, 90, 0)
                            } else {
                                cardObject.description = $filter('limitTo')(cardObject.description, 150, 0)

                            }
                            $scope.contentsTop.push(cardObject);
                            content = {};
                            $scope.loading = false;
                        });
                    });
                $scope.myPagingFunction();
            });
        $scope.showLikes = function(id, title) {
            $mdDialog.show({
                controller: 'ShowLikesController',
                templateUrl: 'app/views/partials/showLikes.html',
                parent: angular.element(document.body),
                scope: $scope,
                locals: {
                    title: title,
                    id: id
                },
                preserveScope: true,
                escapeToClose: true,
                fullscreen: true,
                clickOutsideToClose: true,
                controllerAs: 'dc'
            })
        }
        $scope.myPagingFunction = function() {
            if ($scope.creativityLoading == false && $scope.offset < 5) {
                $scope.creativityLoading = true;
                $scope.meraTitle = "abcd";
                tokenService.get("contents?limit=2&offset=" + $scope.offset)
                    .then(function(tableData) {
                        $scope.creativityLoading = false;
                        if (tableData.data.length < 2) {
                            $scope.moreItems = false;
                        }
                        $scope.nonFinalContents = [];
                        $scope.contents = tableData.data;

                        $scope.contents.forEach(function(content) {
                            cardObject = {};
                            cardObject.Actions = content.Actions;
                            cardObject.Tags = content.Tags;
                            cardObject.created = content.created;
                            cardObject.created.at = Date.parse(cardObject.created.at.replace('-', '/', 'g')); //replace mysql date to js date format
                            cardObject.id = content.id;
                            cardObject.title = $sce.trustAsHtml(content.title);
                            cardObject.content = content.content;
                            $scope.types.some(function(obj) {
                                if (obj.id == cardObject.content.type) {
                                    cardObject.content.category = obj.title;
                                } else {
                                    return;
                                }
                            });
                            cardObject.links = content.links;
                            cardObject.total = content.links;
                            content.Items.data.forEach(function(item) {
                                if (item.type == 'text') {
                                    cardObject.description = item.description;
                                    cardObject.description = $sce.trustAsHtml(cardObject.description);
                                } else if ((item.type == 'cover' && !cardObject.type)) {
                                    cardObject.type = item.type;
                                    cardObject.url = item.image;
                                } else if (item.type == 'soundcloud') {
                                    cardObject.type = item.type;
                                    item.embed.url = "//w.soundcloud.com/player/?url=" + item.embed.url;
                                    cardObject.url = $sce.trustAsResourceUrl(item.embed.url);
                                } else if ((item.type == 'youtube' || item.type == 'vimeo') && !cardObject.type) {
                                    cardObject.type = item.type;
                                    cardObject.url = $sce.trustAsResourceUrl(item.embed.url);
                                } else if (((item.type == 'cover') || (item.type == 'image')) && !cardObject.type) {
                                    cardObject.type = item.type;
                                    cardObject.url = item.image;
                                }
                            });
                             if (cardObject.type != 'cover' || cardObject.type != 'soundcloud' || cardObject.type != 'youtube') {
                                cardObject.description = $filter('limitTo')(cardObject.description, 90, 0)
                            } else {
                                cardObject.description = $filter('limitTo')(cardObject.description, 150, 0)

                            }
                            $scope.nonFinalContents.push(cardObject);
                            content = {};
                            $scope.creativityLoading = false;

                        });
                        $scope.creativityLoading = false;
                        $scope.finalContents = $scope.finalContents.concat($scope.nonFinalContents);
                        $scope.offset += 2;
                        $scope.myPagingFunction();
                    });
            }
        };

        // $scope.myPagingFunction();

        $scope.heart = function(content, $index) {
            if ($rootScope.authenticated) {
                $scope.finalContents[$index].Actions.Appreciate.status = !$scope.finalContents[$index].Actions.Appreciate.status;
                if ($scope.finalContents[$index].Actions.Appreciate.status) {
                    $scope.finalContents[$index].Actions.Appreciate.total += 1;
                    tokenService.post('appreciateContent/' + content.id).then(function(result) {

                    });
                } else {
                    $scope.finalContents[$index].Actions.Appreciate.total -= 1;

                    tokenService.delete('appreciateContent/' + content.id, '').then(function(result) {

                    });
                }
            } else {
                $rootScope.openLoginDialog(function() {
                    $scope.heart(content, $index);
                });
            }
        }
        $scope.bookmark = function(content, index) {
            $scope.finalContents[index].Actions.Bookmarked.status = !$scope.finalContents[index].Actions.Bookmarked.status;
            if ($scope.finalContents[index].Actions.Bookmarked.status) {
                $scope.finalContents[index].Actions.Bookmarked.total += 1;
                tokenService.post('bookmarkContent/' + content.id).then(function(result) {

                });
            } else {
                $scope.finalContents[index].Actions.Bookmarked.total -= 1;
                tokenService.delete('bookmarkContent/' + content.id, '').then(function(result) {

                });
            }
        }
        $scope.openProfile = function($event, username) {
            $event.stopPropagation();
            $state.go('home.profile', { username: username });
        };
        $scope.heartEvent = function(event, $index) {
            if ($rootScope.authenticated) {
                $scope.events[$index].Actions.Bookmarked.status = !$scope.events[$index].Actions.Bookmarked.status;
                if ($scope.events[$index].Actions.Bookmarked.status) {
                    $scope.events[$index].Actions.Bookmarked.total += 1;
                    tokenService.post('bookmarkEvent/' + event.id).then(function(result) {

                    });
                } else {
                    $scope.events[$index].Actions.Bookmarked.total -= 1;

                    tokenService.delete('bookmarkEvent/' + event.id, '').then(function(result) {

                    });
                }
            } else {
                $rootScope.openLoginDialog(function() {
                    $scope.heartEvent(event, $index);
                });
            }
        }
        $scope.rsvpEvent = function(event, $index, state) {
            if ($rootScope.authenticated) {
                // $scope.events[$index].participation_state = state;
                switch (state) {
                    case 2:
                        // intrested button pressed
                        if ($scope.events[$index].participation_state == 2) {
                            //person was intrested before and is'nt now
                            $scope.events[$index].participation_state = 0;
                            tokenService.delete('rsvpEvent/' + event.id, '').then(function(result) {

                            });
                        } else if ($scope.events[$index].participation_state == 1) {
                            //person was going but isnt intrested now
                            $scope.events[$index].participation_state = 0;
                            tokenService.delete('rsvpEvent/' + event.id, '').then(function(result) {

                            });
                        } else {
                            // person wasnt intrested before but is now
                            $scope.events[$index].participation_state = 2;
                            tokenService.post('rsvpEvent/' + event.id + '/' + 2).then(function(result) {

                            });
                        }
                        break;
                    case 1:
                        if ($scope.events[$index].participation_state == 2) {
                            // person intrested before and now he's going too
                            $scope.events[$index].participation_state = 1;
                            tokenService.post('rsvpEvent/' + event.id + '/' + 1).then(function(result) {

                            });
                        } else if ($scope.events[$index].participation_state == 1) {
                            // person is not going anymore
                            $scope.events[$index].participation_state = 0;
                            tokenService.delete('rsvpEvent/' + event.id, '').then(function(result) {

                            });
                        } else {
                            // person was not going before but is going now
                            tokenService.post('rsvpEvent/' + event.id + '/' + 1).then(function(result) {

                            });
                        }

                        break;
                }
            } else {
                $rootScope.openLoginDialog(function() {
                    $scope.rsvpEvent(event, $index);
                });
            }
        }
    }

})();
<commit_msg>now pulling 3 categories at a time on dashboard<commit_after>(function() {

    angular
        .module('app')
        .controller('DashboardController', [
            '$mdDialog',
            '$scope',
            'tokenService',
            'Upload',
            '$location',
            '$sce',
            '$filter',
            '$state',
            '$rootScope',
            DashboardController
        ]);

    function DashboardController($mdDialog, $scope, tokenService, Upload, $location, $sce, $filter, $state, $rootScope) {
        $scope.events = {};

        $scope.updatesLoading = true;
        $scope.eventLoading = true;
        $scope.eventTopLoading = true;
        $scope.creativityLoading = false;
        $scope.contentTopLoading = true;
        $scope.offset = 0;
        $scope.nonFinalContents = [];
        $scope.finalContents = [];
        $scope.types = [
            { 'title': 'Articles', 'id': 1 },
            { 'title': 'Poetry', 'id': 2 },
            { 'title': 'Drama', 'id': 3 },
            { 'title': 'Paint and Colour', 'id': 4 },
            { 'title': 'Drawing ', 'id': 5 },
            { 'title': 'Sewing and Fabric', 'id': 6 },
            { 'title': 'Craft', 'id': 7 },
            // { 'title': 'Dancing', 'id': 8 },
            { 'title': 'Dancing', 'id': 8 },
            { 'title': 'Singing', 'id': 9 },
            { 'title': 'Instrumental', 'id': 10 },
            { 'title': 'Digital Music', 'id': 11 },
            { 'title': 'Decor', 'id': 12 },
            { 'title': 'Film and Video', 'id': 13 },
            { 'title': 'Animation', 'id': 14 },
            { 'title': 'Graphics', 'id': 15 },
            { 'title': 'UI and UX', 'id': 16 },
            { 'title': 'Websites', 'id': 17 },
            { 'title': 'Programming', 'id': 18 },
            { 'title': 'Apps', 'id': 19 },
            { 'title': 'Electronics', 'id': 20 },
            { 'title': 'DIY', 'id': 21 }
        ];

        $scope.tags = ['AngularJs', 'Web Developement', 'Elon Musk', 'Poetry', 'Artificial Intelligence', 'Product Design', 'Feminism', 'Technology', 'Self Driving Cars'];
        var cardObject = {};
        $scope.finalContents = [];
        $scope.mediaTypes = [4, 5, 6, 7, 12, 15, 16];

        // tokenService.get("eventsDashboard")
        // changing temporarily till api is fixed
        tokenService.get("minievents?limit=3")
            .then(function(events) {
                $scope.events = events.data;
                $scope.eventLoading = false;
                // $scope.myPagingFunction();
                // tokenService.get("contentsRandom")
                tokenService.get("contentsRandom")
                    .then(function(contentsDashboard) {
                        $scope.contents = contentsDashboard.data;
                        $scope.contentsTop = contentsDashboard.data;
                        $scope.contentLoading = false;
                        $scope.contentTopLoading = false;
                        $scope.contents.forEach(function(content) {
                            cardObject = {}
                            $scope.loading == false;
                            cardObject.Actions = content.Actions;
                            cardObject.Tags = content.Tags;
                            cardObject.created = content.created;
                            cardObject.created.at = Date.parse(cardObject.created.at.replace('-', '/', 'g')); //replace mysql date to js date format
                            cardObject.id = content.id;
                            cardObject.title = $sce.trustAsHtml(content.title);
                            cardObject.links = content.links;
                            cardObject.total = content.links;
                            content.Items.data.forEach(function(item) {
                                if (item.type == 'text') {
                                    cardObject.description = item.description;
                                    // cardObject.description = $filter('limitTo')(item.description, 110, 0);
                                    cardObject.description = $sce.trustAsHtml(cardObject.description);
                                } else if (item.type == 'cover' && !cardObject.type) {
                                    cardObject.type = item.type;
                                    cardObject.url = item.image;
                                } else if ((item.type == 'youtube' || item.type == 'soundcloud' || item.type == 'vimeo') && !cardObject.type) {
                                    cardObject.type = item.type;
                                    cardObject.url = $sce.trustAsResourceUrl(item.embed.url);
                                } else if (((item.type == 'cover') || (item.type == 'image')) && !cardObject.type) {
                                    cardObject.type = item.type;
                                    cardObject.url = item.image;
                                }
                            });
                            if (cardObject.type != 'cover' || cardObject.type != 'soundcloud' || cardObject.type != 'youtube') {
                                cardObject.description = $filter('limitTo')(cardObject.description, 90, 0)
                            } else {
                                cardObject.description = $filter('limitTo')(cardObject.description, 150, 0)

                            }
                            $scope.contentsTop.push(cardObject);
                            content = {};
                            $scope.loading = false;
                        });
                    });
                $scope.myPagingFunction();
            });
        $scope.showLikes = function(id, title) {
            $mdDialog.show({
                controller: 'ShowLikesController',
                templateUrl: 'app/views/partials/showLikes.html',
                parent: angular.element(document.body),
                scope: $scope,
                locals: {
                    title: title,
                    id: id
                },
                preserveScope: true,
                escapeToClose: true,
                fullscreen: true,
                clickOutsideToClose: true,
                controllerAs: 'dc'
            })
        }
        $scope.myPagingFunction = function() {
            if ($scope.creativityLoading == false && $scope.offset < 5) {
                $scope.creativityLoading = true;
                $scope.meraTitle = "abcd";
                tokenService.get("contents?limit=3&offset=" + $scope.offset)
                    .then(function(tableData) {
                        $scope.creativityLoading = false;
                        if (tableData.data.length < 3) {
                            $scope.moreItems = false;
                        }
                        $scope.nonFinalContents = [];
                        $scope.contents = tableData.data;

                        $scope.contents.forEach(function(content) {
                            cardObject = {};
                            cardObject.Actions = content.Actions;
                            cardObject.Tags = content.Tags;
                            cardObject.created = content.created;
                            cardObject.created.at = Date.parse(cardObject.created.at.replace('-', '/', 'g')); //replace mysql date to js date format
                            cardObject.id = content.id;
                            cardObject.title = $sce.trustAsHtml(content.title);
                            cardObject.content = content.content;
                            $scope.types.some(function(obj) {
                                if (obj.id == cardObject.content.type) {
                                    cardObject.content.category = obj.title;
                                } else {
                                    return;
                                }
                            });
                            cardObject.links = content.links;
                            cardObject.total = content.links;
                            content.Items.data.forEach(function(item) {
                                if (item.type == 'text') {
                                    cardObject.description = item.description;
                                    cardObject.description = $sce.trustAsHtml(cardObject.description);
                                } else if ((item.type == 'cover' && !cardObject.type)) {
                                    cardObject.type = item.type;
                                    cardObject.url = item.image;
                                } else if (item.type == 'soundcloud') {
                                    cardObject.type = item.type;
                                    item.embed.url = "//w.soundcloud.com/player/?url=" + item.embed.url;
                                    cardObject.url = $sce.trustAsResourceUrl(item.embed.url);
                                } else if ((item.type == 'youtube' || item.type == 'vimeo') && !cardObject.type) {
                                    cardObject.type = item.type;
                                    cardObject.url = $sce.trustAsResourceUrl(item.embed.url);
                                } else if (((item.type == 'cover') || (item.type == 'image')) && !cardObject.type) {
                                    cardObject.type = item.type;
                                    cardObject.url = item.image;
                                }
                            });
                             if (cardObject.type != 'cover' || cardObject.type != 'soundcloud' || cardObject.type != 'youtube') {
                                cardObject.description = $filter('limitTo')(cardObject.description, 90, 0)
                            } else {
                                cardObject.description = $filter('limitTo')(cardObject.description, 150, 0)

                            }
                            $scope.nonFinalContents.push(cardObject);
                            content = {};
                            $scope.creativityLoading = false;

                        });
                        $scope.creativityLoading = false;
                        $scope.finalContents = $scope.finalContents.concat($scope.nonFinalContents);
                        $scope.offset += 3;
                        $scope.myPagingFunction();
                    });
            }
        };

        // $scope.myPagingFunction();

        $scope.heart = function(content, $index) {
            if ($rootScope.authenticated) {
                $scope.finalContents[$index].Actions.Appreciate.status = !$scope.finalContents[$index].Actions.Appreciate.status;
                if ($scope.finalContents[$index].Actions.Appreciate.status) {
                    $scope.finalContents[$index].Actions.Appreciate.total += 1;
                    tokenService.post('appreciateContent/' + content.id).then(function(result) {

                    });
                } else {
                    $scope.finalContents[$index].Actions.Appreciate.total -= 1;

                    tokenService.delete('appreciateContent/' + content.id, '').then(function(result) {

                    });
                }
            } else {
                $rootScope.openLoginDialog(function() {
                    $scope.heart(content, $index);
                });
            }
        }
        $scope.bookmark = function(content, index) {
            $scope.finalContents[index].Actions.Bookmarked.status = !$scope.finalContents[index].Actions.Bookmarked.status;
            if ($scope.finalContents[index].Actions.Bookmarked.status) {
                $scope.finalContents[index].Actions.Bookmarked.total += 1;
                tokenService.post('bookmarkContent/' + content.id).then(function(result) {

                });
            } else {
                $scope.finalContents[index].Actions.Bookmarked.total -= 1;
                tokenService.delete('bookmarkContent/' + content.id, '').then(function(result) {

                });
            }
        }
        $scope.openProfile = function($event, username) {
            $event.stopPropagation();
            $state.go('home.profile', { username: username });
        };
        $scope.heartEvent = function(event, $index) {
            if ($rootScope.authenticated) {
                $scope.events[$index].Actions.Bookmarked.status = !$scope.events[$index].Actions.Bookmarked.status;
                if ($scope.events[$index].Actions.Bookmarked.status) {
                    $scope.events[$index].Actions.Bookmarked.total += 1;
                    tokenService.post('bookmarkEvent/' + event.id).then(function(result) {

                    });
                } else {
                    $scope.events[$index].Actions.Bookmarked.total -= 1;

                    tokenService.delete('bookmarkEvent/' + event.id, '').then(function(result) {

                    });
                }
            } else {
                $rootScope.openLoginDialog(function() {
                    $scope.heartEvent(event, $index);
                });
            }
        }
        $scope.rsvpEvent = function(event, $index, state) {
            if ($rootScope.authenticated) {
                // $scope.events[$index].participation_state = state;
                switch (state) {
                    case 2:
                        // intrested button pressed
                        if ($scope.events[$index].participation_state == 2) {
                            //person was intrested before and is'nt now
                            $scope.events[$index].participation_state = 0;
                            tokenService.delete('rsvpEvent/' + event.id, '').then(function(result) {

                            });
                        } else if ($scope.events[$index].participation_state == 1) {
                            //person was going but isnt intrested now
                            $scope.events[$index].participation_state = 0;
                            tokenService.delete('rsvpEvent/' + event.id, '').then(function(result) {

                            });
                        } else {
                            // person wasnt intrested before but is now
                            $scope.events[$index].participation_state = 2;
                            tokenService.post('rsvpEvent/' + event.id + '/' + 2).then(function(result) {

                            });
                        }
                        break;
                    case 1:
                        if ($scope.events[$index].participation_state == 2) {
                            // person intrested before and now he's going too
                            $scope.events[$index].participation_state = 1;
                            tokenService.post('rsvpEvent/' + event.id + '/' + 1).then(function(result) {

                            });
                        } else if ($scope.events[$index].participation_state == 1) {
                            // person is not going anymore
                            $scope.events[$index].participation_state = 0;
                            tokenService.delete('rsvpEvent/' + event.id, '').then(function(result) {

                            });
                        } else {
                            // person was not going before but is going now
                            tokenService.post('rsvpEvent/' + event.id + '/' + 1).then(function(result) {

                            });
                        }

                        break;
                }
            } else {
                $rootScope.openLoginDialog(function() {
                    $scope.rsvpEvent(event, $index);
                });
            }
        }
    }

})();
<|endoftext|>


<commit_before>/*  Copyright (C) 2016  173210 <root.3.173210@live.com>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>. */

"use strict";

class Downloader {
	constructor() {
		this.http = require("http");
		this.querystring = require("querystring");
	}

	download(start, end,
		magnitudeMinimum, magnitudeMaximum,
		depthMinimum, depthMaximum,
		callback)
	{
		const body = this.querystring.stringify({
			"DB": "dat", "ACTION": "DOEQINFO", "ID": "GUEST",

			"YR1": start.getFullYear(), "MO1": start.getMonth() + 1,
			"DY1": start.getDate(), "HR1": start.getHours(),
			"MI1": start.getMinutes(),

			"YR2": end.getFullYear(), "MO2": end.getMonth() + 1,
			"DY2": end.getDate(), "HR2": end.getHours(),
			"MI2": end.getMinutes(),

			"MAG1": magnitudeMinimum, "MAG2": magnitudeMaximum,
			"DEP1": depthMinimum, "DEP2": depthMaximum
		});

		const request = this.http.request({
			hostname: "kyupub.sevo.kyushu-u.ac.jp", port: 80,
			path: "/win-cgi/harvest.pl", method: "POST",
			headers: { "Content-Type": "application/x-www-form-urlencoded",
				"Content-Length": body.length
			}
		}, callback);

		request.on("error", function(event) {
			alert(event.message);
		});

		request.write(body);
		request.end();
	}
}

class Globe {
	constructor() {
		Cesium.BingMapsApi.defaultKey = BING_KEY;
		this.viewer = new Cesium.Viewer("cesiumContainer");
		this.viewer.camera.flyTo({ destination:
			Cesium.Cartesian3.fromDegrees(131, 33, 1048576) });
		this.source = new Cesium.CustomDataSource("epicenters");
		this.viewer.dataSources.add(this.source);
		this._typeToShow = "depth";
	}

	removeAllEarthquake() {
		this.source.entities.removeAll();
	}

	addEarthquake(longitude, latitude, depth, magnitude) {
		function getColor(value, max) {
			return new Cesium.ColorMaterialProperty(
				Cesium.Color.fromHsl((1 - value / max) * 0.6, 1.0, 0.5));
		}

		function getPosition(height) {
			return Cesium.Cartesian3.fromDegrees(
				longitude, latitude, height);
		}

		const surfacePosition = getPosition(0);

		const width = new Cesium.ConstantProperty(2);
		const followSurface = new Cesium.ConstantProperty(false);
		const entities = this.source.entities;
		const description = (entities.values.length - 1) / 2
			+ ": M" + magnitude;
		const typeToShow = this._typeToShow;

		function addPolyline(type, color, surface, top) {
			const polyline = new Cesium.PolylineGraphics();
			polyline.material = color;
			polyline.width = width;
			polyline.followSurface = followSurface;
			polyline.positions = new Cesium.ConstantProperty([surface, top]);

			const entity = new Cesium.Entity({
				id: description + " (" + type + ")",
				show: type == typeToShow,
				polyline: polyline,
				type: type
			});

			entities.add(entity);
		}

		if (depth > 0) {
			const depthColor = getColor(Math.log(depth), 2);
			const depthPosition = getPosition(depth * 1000);

			addPolyline("depth", depthColor,
				surfacePosition, depthPosition);
		}

		const magnitudeColor = getColor(magnitude, 8);
		const magnitudePosition = getPosition(magnitude * 65536);
		addPolyline("magnitude", magnitudeColor,
			surfacePosition, magnitudePosition);
	}

	get typeToShow() {
		return this._typeToShow;
	}

	set typeToShow(type) {
		this._typeToShow = type;

		const entities = this.source.entities;
		entities.suspendEvents();
		for (let index = 0; index < entities.values.length; index++) {
			const entity = entities.values[index];
			entity.show = entity.type == type;
		}
		entities.resumeEvents();
	}
}

function ParserEventHandler(callback) {
	const object = this;

	object.stage = 0;
	object.record = null;
	object.td = false;
	object.handlers = {
		onopentag: function(name) {
			if (object.stage < 3) {
				if (name == "table")
					object.stage++;
			} else if (object.stage == 3) {
				if (name == "tr") {
					object.stage++;
				}
			} else if (object.stage == 5) {
				switch (name) {
				case "tr":
					object.record = [];
					break;

				case "td":
					if (object.record == null)
						throw new Cesium.RuntimeError("Unexpected table data");

					object.td = true;
					break;
				}
			}
		},
		ontext: function(text) {
			if (object.record && object.td)
				object.record.push(text);
		},
		onclosetag: function(name) {
			if (object.stage == 3) {
				if (name == "table")
					throw new Cesium.RuntimeError("Unexpected end of table");
			} else if (object.stage == 4) {
				switch (name) {
				case "table":
					throw new Cesium.RuntimeError("Unexpected end of table");

				case "tr":
					object.stage++;
					break;
				}
			} else if (object.stage == 5) {
				switch (name) {
				case "table":
					object.stage++;
				break;

				case "tr":
					if (object.record == null)
						throw new Cesium.RuntimeError("Unexpected end of table record");

					callback(object.record);
					object.record = null;
					break;

				case "td":
					if (!object.td)
						throw new Cesium.RuntimeError("Unexpected end of table data");

					object.td = false;
					break;
				}
			}
		}
	};
}

const globe = new Globe();

const htmlparser2 = require("htmlparser2");
const downloader = new Downloader();

function initializeData(start, end) {
	const parserEventHandler = new ParserEventHandler(function(record) {
		const latitude = parseFloat(record[6]);
		const longitude = parseFloat(record[7]);
		const depth = parseFloat(record[8]);
		const magnitude = parseFloat(record[9]);
		globe.addEarthquake(longitude, latitude, depth, magnitude);
	});

	const parser = new htmlparser2.Parser(parserEventHandler.handlers);

	const magnitudeMinimum = document.getElementById("magnitude-minimum").value;
	const magnitudeMaximum = document.getElementById("magnitude-maximum").value;
	const depthMinimum = document.getElementById("depth-minimum").value;
	const depthMaximum = document.getElementById("depth-maximum").value;

	downloader.download(start, end,
		magnitudeMinimum, magnitudeMaximum,
		depthMinimum, depthMaximum,
		function(response) {
			response.on("data", function(chunk) {
				parser.write(String.fromCharCode.apply(null, chunk));
			});

			response.on("end", function() {
				parser.end();
			});
		}
	);
}

const end = new Date(Date.now());
end.setMilliseconds(0);
end.setSeconds(0);
const start = new Date(end.getTime());
start.setDate(start.getDate() - 7);
initializeData(start, end);

document.getElementById("start-date").valueAsDate = start;
document.getElementById("start-time").valueAsDate = start;
document.getElementById("end-date").valueAsDate = end;
document.getElementById("end-time").valueAsDate = end;

document.getElementById("magnitude").onclick = function() {
	globe.typeToShow = "magnitude";
}

document.getElementById("depth").onclick = function() {
	globe.typeToShow = "depth";
}

document.getElementById("get").onclick = function() {
	function getDatetime(date, time) {
		function getMilliseconds(id) {
			return document.getElementById(id).valueAsDate.getTime();
		}

		return new Date(getMilliseconds(date) + getMilliseconds(time));
	}

	globe.removeAllEarthquake();
	initializeData(getDatetime("start-date", "start-time"),
		getDatetime("end-date", "end-time"));
}

const shell = require('electron').shell;
document.getElementById("source").onclick = function() {
	shell.openExternal("http://kyupub.sevo.kyushu-u.ac.jp/harvest/");
}
<commit_msg>viewer: Fix index<commit_after>/*  Copyright (C) 2016  173210 <root.3.173210@live.com>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>. */

"use strict";

class Downloader {
	constructor() {
		this.http = require("http");
		this.querystring = require("querystring");
	}

	download(start, end,
		magnitudeMinimum, magnitudeMaximum,
		depthMinimum, depthMaximum,
		callback)
	{
		const body = this.querystring.stringify({
			"DB": "dat", "ACTION": "DOEQINFO", "ID": "GUEST",

			"YR1": start.getFullYear(), "MO1": start.getMonth() + 1,
			"DY1": start.getDate(), "HR1": start.getHours(),
			"MI1": start.getMinutes(),

			"YR2": end.getFullYear(), "MO2": end.getMonth() + 1,
			"DY2": end.getDate(), "HR2": end.getHours(),
			"MI2": end.getMinutes(),

			"MAG1": magnitudeMinimum, "MAG2": magnitudeMaximum,
			"DEP1": depthMinimum, "DEP2": depthMaximum
		});

		const request = this.http.request({
			hostname: "kyupub.sevo.kyushu-u.ac.jp", port: 80,
			path: "/win-cgi/harvest.pl", method: "POST",
			headers: { "Content-Type": "application/x-www-form-urlencoded",
				"Content-Length": body.length
			}
		}, callback);

		request.on("error", function(event) {
			alert(event.message);
		});

		request.write(body);
		request.end();
	}
}

class Globe {
	constructor() {
		Cesium.BingMapsApi.defaultKey = BING_KEY;
		this.viewer = new Cesium.Viewer("cesiumContainer");
		this.viewer.camera.flyTo({ destination:
			Cesium.Cartesian3.fromDegrees(131, 33, 1048576) });
		this.source = new Cesium.CustomDataSource("epicenters");
		this.viewer.dataSources.add(this.source);
		this._typeToShow = "depth";
	}

	removeAllEarthquake() {
		this.source.entities.removeAll();
	}

	addEarthquake(longitude, latitude, depth, magnitude) {
		function getColor(value, max) {
			return new Cesium.ColorMaterialProperty(
				Cesium.Color.fromHsl((1 - value / max) * 0.6, 1.0, 0.5));
		}

		function getPosition(height) {
			return Cesium.Cartesian3.fromDegrees(
				longitude, latitude, height);
		}

		const surfacePosition = getPosition(0);

		const width = new Cesium.ConstantProperty(2);
		const followSurface = new Cesium.ConstantProperty(false);
		const entities = this.source.entities;
		const description = entities.values.length / 2
			+ ": M" + magnitude;
		const typeToShow = this._typeToShow;

		function addPolyline(type, color, surface, top) {
			const polyline = new Cesium.PolylineGraphics();
			polyline.material = color;
			polyline.width = width;
			polyline.followSurface = followSurface;
			polyline.positions = new Cesium.ConstantProperty([surface, top]);

			const entity = new Cesium.Entity({
				id: description + " (" + type + ")",
				show: type == typeToShow,
				polyline: polyline,
				type: type
			});

			entities.add(entity);
		}

		if (depth > 0) {
			const depthColor = getColor(Math.log(depth), 2);
			const depthPosition = getPosition(depth * 1000);

			addPolyline("depth", depthColor,
				surfacePosition, depthPosition);

			const magnitudeColor = getColor(magnitude, 8);
			const magnitudePosition = getPosition(magnitude * 65536);
			addPolyline("magnitude", magnitudeColor,
				surfacePosition, magnitudePosition);
		}
	}

	get typeToShow() {
		return this._typeToShow;
	}

	set typeToShow(type) {
		this._typeToShow = type;

		const entities = this.source.entities;
		entities.suspendEvents();
		for (let index = 0; index < entities.values.length; index++) {
			const entity = entities.values[index];
			entity.show = entity.type == type;
		}
		entities.resumeEvents();
	}
}

function ParserEventHandler(callback) {
	const object = this;

	object.stage = 0;
	object.record = null;
	object.td = false;
	object.handlers = {
		onopentag: function(name) {
			if (object.stage < 3) {
				if (name == "table")
					object.stage++;
			} else if (object.stage == 3) {
				if (name == "tr") {
					object.stage++;
				}
			} else if (object.stage == 5) {
				switch (name) {
				case "tr":
					object.record = [];
					break;

				case "td":
					if (object.record == null)
						throw new Cesium.RuntimeError("Unexpected table data");

					object.td = true;
					break;
				}
			}
		},
		ontext: function(text) {
			if (object.record && object.td)
				object.record.push(text);
		},
		onclosetag: function(name) {
			if (object.stage == 3) {
				if (name == "table")
					throw new Cesium.RuntimeError("Unexpected end of table");
			} else if (object.stage == 4) {
				switch (name) {
				case "table":
					throw new Cesium.RuntimeError("Unexpected end of table");

				case "tr":
					object.stage++;
					break;
				}
			} else if (object.stage == 5) {
				switch (name) {
				case "table":
					object.stage++;
				break;

				case "tr":
					if (object.record == null)
						throw new Cesium.RuntimeError("Unexpected end of table record");

					callback(object.record);
					object.record = null;
					break;

				case "td":
					if (!object.td)
						throw new Cesium.RuntimeError("Unexpected end of table data");

					object.td = false;
					break;
				}
			}
		}
	};
}

const globe = new Globe();

const htmlparser2 = require("htmlparser2");
const downloader = new Downloader();

function initializeData(start, end) {
	const parserEventHandler = new ParserEventHandler(function(record) {
		const latitude = parseFloat(record[6]);
		const longitude = parseFloat(record[7]);
		const depth = parseFloat(record[8]);
		const magnitude = parseFloat(record[9]);
		globe.addEarthquake(longitude, latitude, depth, magnitude);
	});

	const parser = new htmlparser2.Parser(parserEventHandler.handlers);

	const magnitudeMinimum = document.getElementById("magnitude-minimum").value;
	const magnitudeMaximum = document.getElementById("magnitude-maximum").value;
	const depthMinimum = document.getElementById("depth-minimum").value;
	const depthMaximum = document.getElementById("depth-maximum").value;

	downloader.download(start, end,
		magnitudeMinimum, magnitudeMaximum,
		depthMinimum, depthMaximum,
		function(response) {
			response.on("data", function(chunk) {
				parser.write(String.fromCharCode.apply(null, chunk));
			});

			response.on("end", function() {
				parser.end();
			});
		}
	);
}

const end = new Date(Date.now());
end.setMilliseconds(0);
end.setSeconds(0);
const start = new Date(end.getTime());
start.setDate(start.getDate() - 7);
initializeData(start, end);

document.getElementById("start-date").valueAsDate = start;
document.getElementById("start-time").valueAsDate = start;
document.getElementById("end-date").valueAsDate = end;
document.getElementById("end-time").valueAsDate = end;

document.getElementById("magnitude").onclick = function() {
	globe.typeToShow = "magnitude";
}

document.getElementById("depth").onclick = function() {
	globe.typeToShow = "depth";
}

document.getElementById("get").onclick = function() {
	function getDatetime(date, time) {
		function getMilliseconds(id) {
			return document.getElementById(id).valueAsDate.getTime();
		}

		return new Date(getMilliseconds(date) + getMilliseconds(time));
	}

	globe.removeAllEarthquake();
	initializeData(getDatetime("start-date", "start-time"),
		getDatetime("end-date", "end-time"));
}

const shell = require('electron').shell;
document.getElementById("source").onclick = function() {
	shell.openExternal("http://kyupub.sevo.kyushu-u.ac.jp/harvest/");
}
<|endoftext|>


<commit_before>/*
 * Copyright 2012 Amadeus s.a.s.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var Aria = require("../../Aria");
var ariaUtilsScriptLoader = require("../../utils/ScriptLoader");
var ariaMapProvidersIMapProvider = require("./IMapProvider");
var ariaUtilsJson = require("../../utils/Json");

/**
 * Load the bing 8 dependencies and creates map instances
 */
module.exports = Aria.classDefinition({
    $classpath : "aria.map.providers.Microsoft8MapProvider",
    $singleton : true,
    $implements : [ariaMapProvidersIMapProvider],
    $constructor : function () {

        /**
         * Credentials for bing8 maps
         * @type String
         */
        this.credentials = "";

        /**
         * @type aria.core.CfgBeans:Callback
         */
        this._loadCallback = null;

    },
    $destructor : function () {
        this._loadCallback = null;
    },
    $prototype : {

        /**
         * Load the Microsoft Bing 8 scripts
         * @param {aria.core.CgfBeans:Callback} cb
         */
        load : function (cb) {
            if (this.isLoaded()) {
                this.$callback(cb);
            } else {
                var that = this;
                this._loadCallback = cb;
                Aria.$window.__bing8MapLoadCallback = function () {
                    that._afterLoad.apply(that);
                    that = null;
                };
                var url = "://www.bing.com/api/maps/mapcontrol?mkt=en-US&callback=__bing8MapLoadCallback";
                var https = "https:" == Aria.$window.document.location.protocol;
                url = "http" + (https ? "s" : "") + url + (https ? "&s=1" : "");
                ariaUtilsScriptLoader.load([url]);
            }
        },

        /**
         * Load the 'Microsoft.Maps.Overlays.Style' module and calls the original callback
         * @private
         */
        _afterLoad : function () {
            this.$assert(35, this.isLoaded());
            Aria.$window.__bing8MapLoadCallback = null;
            var that = this;
            Aria.$window.Microsoft.Maps.loadModule('Microsoft.Maps.Overlays.Style', {
                callback : function () {
                    that.$callback(that._loadCallback);
                    that = null;
                }
            });

        },

        /**
         * Check if the Microsoft Bing 8 API is available
         * @return {Boolean}
         */
        isLoaded : function () {
            var microsoft = Aria.$window.Microsoft;
            return !!(microsoft &&
                microsoft.Maps &&
                microsoft.Maps.Map &&
                typeof(microsoft.Maps.Map) === "function" &&
                microsoft.Maps.loadModule);
        },

        /**
         * @param {aria.map.CfgBeans:MapCfg} cfg
         * @return {Object} Map instance. null if the dependencies are not loaded
         */
        getMap : function (cfg) {
            var initArgs = {
                credentials : this.credentials
            };

            ariaUtilsJson.inject(cfg.initArgs, initArgs);
            return (this.isLoaded()) ? new Aria.$window.Microsoft.Maps.Map(cfg.domElement, initArgs) : null;
        },

        /**
         * @param {Object} map previously created through the getMap method
         */
        disposeMap : function (map) {

            var node = map.getRootElement();
            map.dispose();

            if (node && node.parentNode) {
                node.parentNode.removeChild(node);
            }
        }
    }
});
<commit_msg>fix #1826 add a default key for Bing maps<commit_after>/*
 * Copyright 2012 Amadeus s.a.s.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var Aria = require("../../Aria");
var ariaUtilsScriptLoader = require("../../utils/ScriptLoader");
var ariaMapProvidersIMapProvider = require("./IMapProvider");
var ariaUtilsJson = require("../../utils/Json");

/**
 * Load the bing 8 dependencies and creates map instances
 */
module.exports = Aria.classDefinition({
    $classpath : "aria.map.providers.Microsoft8MapProvider",
    $singleton : true,
    $implements : [ariaMapProvidersIMapProvider],
    $constructor : function () {

        /**
         * Credentials for bing8 maps
         * @type String
         */
        this.credentials = "[YOUR_BING_MAPS_KEY]";

        /**
         * @type aria.core.CfgBeans:Callback
         */
        this._loadCallback = null;

    },
    $destructor : function () {
        this._loadCallback = null;
    },
    $prototype : {

        /**
         * Load the Microsoft Bing 8 scripts
         * @param {aria.core.CgfBeans:Callback} cb
         */
        load : function (cb) {
            if (this.isLoaded()) {
                this.$callback(cb);
            } else {
                var that = this;
                this._loadCallback = cb;
                Aria.$window.__bing8MapLoadCallback = function () {
                    that._afterLoad.apply(that);
                    that = null;
                };
                var url = "://www.bing.com/api/maps/mapcontrol?mkt=en-US&callback=__bing8MapLoadCallback";
                var https = "https:" == Aria.$window.document.location.protocol;
                url = "http" + (https ? "s" : "") + url + (https ? "&s=1" : "");
                ariaUtilsScriptLoader.load([url]);
            }
        },

        /**
         * Load the 'Microsoft.Maps.Overlays.Style' module and calls the original callback
         * @private
         */
        _afterLoad : function () {
            this.$assert(35, this.isLoaded());
            Aria.$window.__bing8MapLoadCallback = null;
            var that = this;
            Aria.$window.Microsoft.Maps.loadModule('Microsoft.Maps.Overlays.Style', {
                callback : function () {
                    that.$callback(that._loadCallback);
                    that = null;
                }
            });

        },

        /**
         * Check if the Microsoft Bing 8 API is available
         * @return {Boolean}
         */
        isLoaded : function () {
            var microsoft = Aria.$window.Microsoft;
            return !!(microsoft &&
                microsoft.Maps &&
                microsoft.Maps.Map &&
                typeof(microsoft.Maps.Map) === "function" &&
                microsoft.Maps.loadModule);
        },

        /**
         * @param {aria.map.CfgBeans:MapCfg} cfg
         * @return {Object} Map instance. null if the dependencies are not loaded
         */
        getMap : function (cfg) {
            var initArgs = {
                credentials : this.credentials
            };

            ariaUtilsJson.inject(cfg.initArgs, initArgs);
            return (this.isLoaded()) ? new Aria.$window.Microsoft.Maps.Map(cfg.domElement, initArgs) : null;
        },

        /**
         * @param {Object} map previously created through the getMap method
         */
        disposeMap : function (map) {

            var node = map.getRootElement();
            map.dispose();

            if (node && node.parentNode) {
                node.parentNode.removeChild(node);
            }
        }
    }
});
<|endoftext|>


<commit_before>/*
 * Copyright 2012 Amadeus s.a.s.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Validation Class for all Input widgets.
 */
Aria.classDefinition({
    $classpath : "aria.widgets.form.InputValidationHandler",
    $dependencies : ["aria.DomEvent", "aria.utils.Dom", "aria.popups.Popup", "aria.widgets.container.Div",
            "aria.templates.Layout"],
    $constructor : function (widget) {
        this._context = widget._context;
        this._lineNumber = widget._lineNumber;
        this._field = widget.getDom();
        this._WidgetCfg = widget._cfg;
        this._validationPopup = null; // null when the validation is closed
        this._preferredPositions = {
            "top right" : {
                reference : "top right",
                popup : "bottom left",
                offset : {
                    left : -30
                }
            },
            "bottom right" : {
                reference : "bottom right",
                popup : "top left",
                offset : {
                    left : -30
                }
            },
            "top left" : {
                reference : "top left",
                popup : "bottom right",
                offset : {
                    right : -30
                }
            },
            "bottom left" : {
                reference : "bottom left",
                popup : "top right",
                offset : {
                    right : -30
                }
            }
        };

        /**
         * Div for the error tooltip skinning. The reference is keep to change its state depending on the positioning of
         * the popup.
         * @type aria.widgets.container.Div
         */
        this._div = null;

    },
    $destructor : function () {
        this._closeValidation();
        this._context = null;
        this._field = null;
        this._WidgetCfg = null;
        this._validationPopup = null;
    },
    $prototype : {

        /**
         * Error messages can be declared in the template or within the widget via the framework itself. Need to
         * determine which is which.
         * @param {Array} errorMessage
         * @private
         */
        _checkErrorMessage : function (errorMessage) {

            var msg = null;

            for (var i = 0; i < errorMessage.length; i++) {
                if (msg === null && errorMessage[i]) {
                    msg = errorMessage[i];
                }
            }

            return msg;
        },

        /**
         * Creates the container markup with the error message
         * @param {aria.templates.MarkupWriter} out Markup writer which should receive the content of the popup.
         * @private
         */
        _renderValidationContent : function (out) {
            var errorMessage;
            if (this._WidgetCfg.formatError) {// framework errors
                errorMessage = this._WidgetCfg.formatErrorMessages;
            } else if (this._WidgetCfg.error) {// template errors
                errorMessage = this._WidgetCfg.errorMessages;
            }

            var div = new aria.widgets.container.Div({
                sclass : "errortip",
                width : 289,
                margins : "0 0 0 0"
            }, this._context);
            out.registerBehavior(div);
            div.writeMarkupBegin(out);
            out.write(this._checkErrorMessage(errorMessage));
            div.writeMarkupEnd(out);
            this._div = div;
        },

        /**
         * Internal method called when the validation must be open
         * @private
         */
        _openValidation : function () {
            if (this._validationPopup) {
                return;
            }
            // create the section
            var section = this._context.createSection({
                fn : this._renderValidationContent,
                scope : this
            });
            // we no longer store the section in this._section as the section is properly disposed by the popup when it
            // is disposed
            var popup = new aria.popups.Popup();
            this._validationPopup = popup;
            this._validationPopup.$on({
                "onAfterClose" : this._afterValidationClose,
                "onPositioned" : this._onTooltipPositioned,
                scope : this
            });
            aria.templates.Layout.$on({
                "viewportResized" : this._onViewportResized,
                scope : this
            });
            this._validationPopup.open({
                section : section,
                domReference : this._field,
                preferredPositions : this._getPreferredPositions(),
                closeOnMouseClick : true,
                closeOnMouseScroll : false
            });
        },

        /**
         * Creates an array of preferred positions, will first get the preferred position specified in the widgets
         * errorTipPosition property.
         * @return {Array} Returns an array of preferred positions.
         */
        _getPreferredPositions : function () {
            var errorTipPosition = this._WidgetCfg.errorTipPosition;
            var preferredPositions = [this._preferredPositions[errorTipPosition]];
            for (var i in this._preferredPositions) {
                if (this._preferredPositions.hasOwnProperty(i) && errorTipPosition != i) {
                    preferredPositions.push(this._preferredPositions[i]);
                }
            }
            return preferredPositions;
        },

        /**
         * Raised after the popup is closed.
         * @param {Object} evt
         */
        _afterValidationClose : function (evt) {
            this._validationPopup.$dispose();
            // Note that we must not call this._div.$dispose() here
            // as this is already done through the section
            this._div = null;
            this._validationPopup = null;
            aria.templates.Layout.$unregisterListeners(this);
        },

        /**
         * Internal method called when the popup must be closed
         * @private
         */
        _closeValidation : function () {
            if (!this._validationPopup) {
                return;
            }
            this._validationPopup.close();
        },

        /**
         * Raised by the popup when its positioned. Needed to change the skin of the popup to place the arrow properly.
         * @param {Object} evt
         */
        _onTooltipPositioned : function (evt) {
            var position = evt.position;
            if (position) {
                // state is named after the position, except for topRight where it is named normal
                var state = position.reference.replace(" right", "Right").replace(" left", "Left");
                if (state === 'topRight') {
                    state = 'normal';
                }
                var div = this._div, frame = div._frame;
                div.initWidgetDom();
                // this is backward compatibility for skin without errortooltip position states
                if (frame.checkState(state)) {
                    frame.changeState(state);
                }
            }
        },

        /**
         * Raised when the viewport is resized. Needed to fix the position of the popup after the resize.
         * @param {Object} evt
         */
        _onViewportResized : function (evt) {
            // Added for PTR 05374683: popup is misplaced after window resize
            this._closeValidation();
            this._openValidation();
        },

        /**
         * Called when the input field wants to show a validation popup.
         * @param {aria.DomEvent} domEvt
         * @public
         */
        show : function () {
            this._openValidation();
        },

        /**
         * Called when the input field wants to close a validation popup.
         * @param {aria.DomEvent} domEvt
         * @public
         */
        hide : function () {
            this._closeValidation();
        }
    }
});
<commit_msg>fix #617 InputValidationHandler issue<commit_after>/*
 * Copyright 2012 Amadeus s.a.s.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Validation Class for all Input widgets.
 */
Aria.classDefinition({
    $classpath : "aria.widgets.form.InputValidationHandler",
    $dependencies : ["aria.DomEvent", "aria.utils.Dom", "aria.popups.Popup", "aria.widgets.container.Div",
            "aria.templates.Layout"],
    $constructor : function (widget) {
        this._context = widget._context;
        this._lineNumber = widget._lineNumber;
        this._field = widget.getDom();
        this._WidgetCfg = widget._cfg;
        this._validationPopup = null; // null when the validation is closed
        this._preferredPositions = {
            "top right" : {
                reference : "top right",
                popup : "bottom left",
                offset : {
                    left : -30
                }
            },
            "bottom right" : {
                reference : "bottom right",
                popup : "top left",
                offset : {
                    left : -30
                }
            },
            "top left" : {
                reference : "top left",
                popup : "bottom right",
                offset : {
                    right : -30
                }
            },
            "bottom left" : {
                reference : "bottom left",
                popup : "top right",
                offset : {
                    right : -30
                }
            }
        };

        /**
         * Div for the error tooltip skinning. The reference is keep to change its state depending on the positioning of
         * the popup.
         * @type aria.widgets.container.Div
         */
        this._div = null;

    },
    $destructor : function () {
        this._closeValidation();
        this._context = null;
        this._field = null;
        this._WidgetCfg = null;
        this._validationPopup = null;
    },
    $prototype : {

        /**
         * Error messages can be declared in the template or within the widget via the framework itself. Need to
         * determine which is which.
         * @param {Array} errorMessage
         * @private
         */
        _checkErrorMessage : function (errorMessage) {

            var msg = null;

            for (var i = 0; i < errorMessage.length; i++) {
                if (msg === null && errorMessage[i]) {
                    msg = errorMessage[i];
                }
            }

            return msg;
        },

        /**
         * Creates the container markup with the error message
         * @param {aria.templates.MarkupWriter} out Markup writer which should receive the content of the popup.
         * @private
         */
        _renderValidationContent : function (out) {
            var errorMessage;
            if (this._WidgetCfg.formatError) {// framework errors
                errorMessage = this._WidgetCfg.formatErrorMessages;
            } else if (this._WidgetCfg.error) {// template errors
                errorMessage = this._WidgetCfg.errorMessages;
            }

            var div = new aria.widgets.container.Div({
                sclass : "errortip",
                width : 289,
                margins : "0 0 0 0"
            }, this._context);
            out.registerBehavior(div);
            div.writeMarkupBegin(out);
            out.write(this._checkErrorMessage(errorMessage));
            div.writeMarkupEnd(out);
            this._div = div;
        },

        /**
         * Internal method called when the validation must be open
         * @private
         */
        _openValidation : function () {
            if (this._validationPopup) {
                return;
            }
            // create the section
            var section = this._context.createSection({
                fn : this._renderValidationContent,
                scope : this
            });
            // we no longer store the section in this._section as the section is properly disposed by the popup when it
            // is disposed
            var popup = new aria.popups.Popup();
            this._validationPopup = popup;
            this._validationPopup.$on({
                "onAfterClose" : this._afterValidationClose,
                "onPositioned" : this._onTooltipPositioned,
                scope : this
            });
            aria.templates.Layout.$on({
                "viewportResized" : this._onViewportResized,
                scope : this
            });
            this._validationPopup.open({
                section : section,
                domReference : this._field,
                preferredPositions : this._getPreferredPositions(),
                closeOnMouseClick : true,
                closeOnMouseScroll : false
            });
        },

        /**
         * Creates an array of preferred positions, will first get the preferred position specified in the widgets
         * errorTipPosition property.
         * @return {Array} Returns an array of preferred positions.
         */
        _getPreferredPositions : function () {
            var errorTipPosition = this._WidgetCfg.errorTipPosition;
            var preferredPositions = [this._preferredPositions[errorTipPosition]];
            for (var i in this._preferredPositions) {
                if (this._preferredPositions.hasOwnProperty(i) && errorTipPosition != i) {
                    preferredPositions.push(this._preferredPositions[i]);
                }
            }
            return preferredPositions;
        },

        /**
         * Raised after the popup is closed.
         * @param {Object} evt
         */
        _afterValidationClose : function (evt) {
            this._validationPopup.$dispose();
            // Note that we must not call this._div.$dispose() here
            // as this is already done through the section
            this._div = null;
            this._validationPopup = null;
            aria.templates.Layout.$unregisterListeners(this);
        },

        /**
         * Internal method called when the popup must be closed
         * @private
         */
        _closeValidation : function () {
            if (!this._validationPopup) {
                return;
            }
            this._validationPopup.close();
        },

        /**
         * Raised by the popup when its positioned. Needed to change the skin of the popup to place the arrow properly.
         * @param {Object} evt
         */
        _onTooltipPositioned : function (evt) {
            var position = evt.position;
            if (position) {
                // state is named after the position, except for topRight where it is named normal
                var state = position.reference.replace(" right", "Right").replace(" left", "Left");
                if (state === 'topRight') {
                    state = 'normal';
                }
                var div = this._div, frame = div._frame;

                // Make sure that the div is initialised (only once),
                // as _onTooltipPositioned can be called several times for the same popup
                div.getDom();
                // this is backward compatibility for skin without errortooltip position states
                if (frame.checkState(state)) {
                    frame.changeState(state);
                }
            }
        },

        /**
         * Raised when the viewport is resized. Needed to fix the position of the popup after the resize.
         * @param {Object} evt
         */
        _onViewportResized : function (evt) {
            // Added for PTR 05374683: popup is misplaced after window resize
            this._closeValidation();
            this._openValidation();
        },

        /**
         * Called when the input field wants to show a validation popup.
         * @param {aria.DomEvent} domEvt
         * @public
         */
        show : function () {
            this._openValidation();
        },

        /**
         * Called when the input field wants to close a validation popup.
         * @param {aria.DomEvent} domEvt
         * @public
         */
        hide : function () {
            this._closeValidation();
        }
    }
});
<|endoftext|>


<commit_before>// TODO - add support for row/column selection

var Lang = A.Lang,
	isBoolean = Lang.isBoolean,

	AgetClassName = A.getClassName,

	CELL = 'cell',
	DATATABLE = 'datatable',
	ID = 'id',
	MULTIPLE = 'multiple',
	SELECTED = 'selected',
	SELECT_CELL_ON_EDIT = 'selectCellOnEdit',

	CSS_DATATABLE_CELL_SELECTED = AgetClassName(DATATABLE, CELL, SELECTED);

var DataTableSelection = A.Base.create("dataTableSelection", A.Plugin.Base, [], {
	selectedCellHash: null,
	selectedColumnHash: null,
	selectedRowHash: null,

	initializer: function() {
		var instance = this;

		instance.selectedCellHash = {};
		instance.selectedColumnHash = {};
		instance.selectedRowHash = {};

		instance.afterHostMethod('_editCell', instance._editCell);
	},

	isCellSelected: function(cell) {
		var instance = this;

		return instance.selectedCellHash[cell.get(ID)];
	},

	isColumnSelected: function(column) {
		// TODO
	},

	isRowSelected: function(row) {
		// TODO
	},

	selectCell: function(cell) {
		var instance = this;

		if (!instance.get(MULTIPLE)) {
			instance.unselectAllCells();
		}

		instance.selectedCellHash[cell.get(ID)] = cell;

		cell.addClass(CSS_DATATABLE_CELL_SELECTED);
	},

	selectColumn: function(row) {
		// TODO
	},

	selectRow: function(row) {
		// TODO
	},

	toggleCell: function(cell, forceAdd) {
		var instance = this;

		if (forceAdd || !instance.isCellSelected(cell)) {
			instance.selectCell(cell);
		}
		else {
			instance.unselectCell(cell);
		}
	},

	toggleColumn: function(column, forceAdd) {
		// TODO
	},

	toggleRow: function(row, forceAdd) {
		// TODO
	},

	unselectCell: function(cell) {
		var instance = this;

		delete instance.selectedCellHash[cell.get(ID)];

		cell.removeClass(CSS_DATATABLE_CELL_SELECTED);
	},

	unselectColumn: function(column) {
		// TODO
	},

	unselectRow: function(row) {
		// TODO
	},

	unselectAllCells: function() {
		var instance = this;

		A.each(instance.selectedCellHash, A.bind(instance.unselectCell, instance));
	},

	unselectAllColumns: function() {
		// TODO
	},

	unselectAllRows: function() {
		// TODO
	},

	_editCell: function(event) {
		var instance = this;

		if (instance.get(SELECT_CELL_ON_EDIT)) {
			instance.selectCell(event.cell);
		}
	}
},
{
    NS: "selection",

    NAME: "dataTableSelection",

    ATTRS: {
		selectCellOnEdit: {
			value: true,
			validator: isBoolean
		},

		multiple: {
			value: false,
			validator: isBoolean
		}
    }
});

A.namespace("Plugin").DataTableSelection = DataTableSelection;<commit_msg>AUI-413 Add "selectEvent" attribute to aui-datatable-selection<commit_after>// TODO - add support for row/column selection

var Lang = A.Lang,
	isBoolean = Lang.isBoolean,
	isString = Lang.isString,

	AgetClassName = A.getClassName,

	_toInitialCap = A.cached(function(str) {
        return str.substring(0, 1).toUpperCase() + str.substring(1);
    }),

	CELL = 'cell',
	DATATABLE = 'datatable',
	ID = 'id',
	MOUSEDOWN = 'mousedown',
	MULTIPLE = 'multiple',
	SELECTED = 'selected',
	SELECT_CELL_ON_EDIT = 'selectCellOnEdit',
	SELECT_EVENT = 'selectEvent',

	CSS_DATATABLE_CELL_SELECTED = AgetClassName(DATATABLE, CELL, SELECTED);

var DataTableSelection = A.Base.create("dataTableSelection", A.Plugin.Base, [], {
	selectedCellHash: null,
	selectedColumnHash: null,
	selectedRowHash: null,

	initializer: function() {
		var instance = this;

		instance.selectedCellHash = {};
		instance.selectedColumnHash = {};
		instance.selectedRowHash = {};

		instance.afterHostMethod('_editCell', instance._editCell);

		instance.afterHostEvent(instance.get(SELECT_EVENT), instance._afterSelectEvent);
	},

	isCellSelected: function(cell) {
		var instance = this;

		return instance.selectedCellHash[cell.get(ID)];
	},

	isColumnSelected: function(column) {
		// TODO
	},

	isRowSelected: function(row) {
		// TODO
	},

	selectCell: function(cell) {
		var instance = this;

		if (!instance.get(MULTIPLE)) {
			instance.unselectAllCells();
		}

		instance.selectedCellHash[cell.get(ID)] = cell;

		cell.addClass(CSS_DATATABLE_CELL_SELECTED);
	},

	selectColumn: function(row) {
		// TODO
	},

	selectRow: function(row) {
		// TODO
	},

	toggleCell: function(cell, forceAdd) {
		var instance = this;

		if (forceAdd || !instance.isCellSelected(cell)) {
			instance.selectCell(cell);
		}
		else {
			instance.unselectCell(cell);
		}
	},

	toggleColumn: function(column, forceAdd) {
		// TODO
	},

	toggleRow: function(row, forceAdd) {
		// TODO
	},

	unselectCell: function(cell) {
		var instance = this;

		delete instance.selectedCellHash[cell.get(ID)];

		cell.removeClass(CSS_DATATABLE_CELL_SELECTED);
	},

	unselectColumn: function(column) {
		// TODO
	},

	unselectRow: function(row) {
		// TODO
	},

	unselectAllCells: function() {
		var instance = this;

		A.each(instance.selectedCellHash, A.bind(instance.unselectCell, instance));
	},

	unselectAllColumns: function() {
		// TODO
	},

	unselectAllRows: function() {
		// TODO
	},

	_afterSelectEvent: function(event) {
		var instance = this;

		instance.selectCell(event.cell);
	},

	_editCell: function(event) {
		var instance = this;

		if (instance.get(SELECT_CELL_ON_EDIT)) {
			instance.selectCell(event.cell);
		}
	},

	_setSelectEvent: function(val) {
		return CELL + _toInitialCap(val);
	}
},
{
    NS: "selection",

    NAME: "dataTableSelection",

    ATTRS: {
		selectCellOnEdit: {
			value: true,
			validator: isBoolean
		},

		selectEvent: {
			setter: '_setSelectEvent',
			value: MOUSEDOWN,
			validator: isString
		},

		multiple: {
			value: false,
			validator: isBoolean
		}
    }
});

A.namespace("Plugin").DataTableSelection = DataTableSelection;<|endoftext|>