<commit_before>'use strict';

angular.module('copayApp.services').factory('currencySymbolService', function($log) {
  var root = {};
  root.currencySymbols = {
    'AED': 'د.إ',
    'AFN': '؋',
    'ALL': 'L',
    'AMD': '֏',
    'ANG': 'ƒ',
    'AOA': 'Kz',
    'ARS': '$',
    'AUD': '$',
    'AWG': 'ƒ',
    'AZN': '₼',
    'BAM': 'KM',
    'BBD': '$',
    'BDT': '৳',
    'BGN': 'лв',
    'BHD': '.د.ب',
    'BIF': 'FBu',
    'BMD': '$',
    'BND': '$',
    'BOB': '$b',
    'BRL': 'R$',
    'BSD': '$',
    'BTC': '฿',
    'BTN': 'Nu.',
    'BWP': 'P',
    'BYR': 'Br',
    'BYN': 'Br',
    'BZD': 'BZ$',
    'CAD': '$',
    'CDF': 'FC',
    'CHF': 'CHF',
    'CLP': '$',
    'CNY': '¥',
    'COP': '$',
    'CRC': '₡',
    'CUC': '$',
    'CUP': '₱',
    'CVE': '$',
    'CZK': 'Kč',
    'DJF': 'Fdj',
    'DKK': 'kr',
    'DOP': 'RD$',
    'DZD': 'دج',
    'EEK': 'kr',
    'EGP': '£',
    'ERN': 'Nfk',
    'ETB': 'Br',
    'ETH': 'Ξ',
    'EUR': '€',
    'FJD': '$',
    'FKP': '£',
    'GBP': '£',
    'GEL': '₾',
    'GGP': '£',
    'GHC': '₵',
    'GHS': 'GH₵',
    'GIP': '£',
    'GMD': 'D',
    'GNF': 'FG',
    'GTQ': 'Q',
    'GYD': '$',
    'HKD': '$',
    'HNL': 'L',
    'HRK': 'kn',
    'HTG': 'G',
    'HUF': 'Ft',
    'IDR': 'Rp',
    'ILS': '₪',
    'IMP': '£',
    'INR': '₹',
    'IQD': 'ع.د',
    'IRR': '﷼',
    'ISK': 'kr',
    'JEP': '£',
    'JMD': 'J$',
    'JOD': 'JD',
    'JPY': '¥',
    'KES': 'KSh',
    'KGS': 'лв',
    'KHR': '៛',
    'KMF': 'CF',
    'KPW': '₩',
    'KRW': '₩',
    'KWD': 'KD',
    'KYD': '$',
    'KZT': 'лв',
    'LAK': '₭',
    'LBP': '£',
    'LKR': '₨',
    'LRD': '$',
    'LSL': 'M',
    'LTC': 'Ł',
    'LTL': 'Lt',
    'LVL': 'Ls',
    'LYD': 'LD',
    'MAD': 'MAD',
    'MDL': 'lei',
    'MGA': 'Ar',
    'MKD': 'ден',
    'MMK': 'K',
    'MNT': '₮',
    'MOP': 'MOP$',
    'MRO': 'UM',
    'MRU': 'UM',
    'MUR': '₨',
    'MVR': 'Rf',
    'MWK': 'MK',
    'MXN': '$',
    'MYR': 'RM',
    'MZN': 'MT',
    'NAD': '$',
    'NGN': '₦',
    'NIO': 'C$',
    'NOK': 'kr',
    'NPR': '₨',
    'NZD': '$',
    'OMR': '﷼',
    'PAB': 'B/.',
    'PEN': 'S/.',
    'PGK': 'K',
    'PHP': '₱',
    'PKR': '₨',
    'PLN': 'zł',
    'PYG': 'Gs',
    'QAR': '﷼',
    'RMB': '￥',
    'RON': 'lei',
    'RSD': 'Дин.',
    'RUB': '₽',
    'RWF': 'R₣',
    'SAR': '﷼',
    'SBD': '$',
    'SCR': '₨',
    'SDG': 'ج.س.',
    'SEK': 'kr',
    'SGD': '$',
    'SHP': '£',
    'SLL': 'Le',
    'SOS': 'S',
    'SRD': '$',
    'SSP': '£',
    'STD': 'Db',
    'STN': 'Db',
    'SVC': '$',
    'SYP': '£',
    'SZL': 'E',
    'THB': '฿',
    'TJS': 'SM',
    'TMT': 'T',
    'TND': 'د.ت',
    'TOP': 'T$',
    'TRL': '₤',
    'TRY': '₺',
    'TTD': 'TT$',
    'TVD': '$',
    'TWD': 'NT$',
    'TZS': 'TSh',
    'UAH': '₴',
    'UGX': 'USh',
    'USD': '$',
    'UYU': '$U',
    'UZS': 'лв',
    'VEF': 'Bs',
    'VND': '₫',
    'VUV': 'VT',
    'WST': 'WS$',
    'XAF': 'FCFA',
    'XBT': 'Ƀ',
    'XCD': '$',
    'XOF': 'CFA',
    'XPF': '₣',
    'YER': '﷼',
    'ZAR': 'R',
    'ZWD': 'Z$'
  };

  root.getCurrencySymbol = function(code) {
    if (!code)
      return false;
    code = code.toUpperCase();

    if (root.currencySymbols[code]) {
      return root.currencySymbols[code];
    }
    $log.debug("Currency symbol for "+code+" not found");
    return false;
  };

  return root;

});<commit_msg>currency symbol<commit_after>'use strict';

angular.module('copayApp.services').factory('currencySymbolService', function($log) {
  var root = {};
  root.currencySymbols = {
    'AED': 'د.إ',
    'AFN': '؋',
    'ALL': 'L',
    'AMD': '֏',
    'ANG': 'ƒ',
    'AOA': 'Kz',
    'ARS': '$',
    'AUD': '$',
    'AWG': 'ƒ',
    'AZN': '₼',
    'BAM': 'KM',
    'BBD': '$',
    'BDT': '৳',
    'BGN': 'лв',
    'BHD': '.د.ب',
    'BIF': 'FBu',
    'BMD': '$',
    'BND': '$',
    'BOB': '$b',
    'BRL': 'R$',
    'BSD': '$',
    'BTC': '฿',
    'BTN': 'Nu.',
    'BWP': 'P',
    'BYR': 'Br',
    'BYN': 'Br',
    'BZD': 'BZ$',
    'CAD': '$',
    'CDF': 'FC',
    'CHF': 'CHF',
    'CLP': '$',
    'CNY': '¥',
    'COP': '$',
    'CRC': '₡',
    'CUC': '$',
    'CUP': '₱',
    'CVE': '$',
    'CZK': 'Kč',
    'DJF': 'Fdj',
    'DKK': 'kr',
    'DOP': 'RD$',
    'DZD': 'دج',
    'EEK': 'kr',
    'EGP': '£',
    'ERN': 'Nfk',
    'ETB': 'Br',
    'ETH': 'Ξ',
    'EUR': '€',
    'FJD': '$',
    'FKP': '£',
    'GBP': '£',
    'GEL': '₾',
    'GGP': '£',
    'GHC': '₵',
    'GHS': 'GH₵',
    'GIP': '£',
    'GMD': 'D',
    'GNF': 'FG',
    'GTQ': 'Q',
    'GYD': '$',
    'HKD': '$',
    'HNL': 'L',
    'HRK': 'kn',
    'HTG': 'G',
    'HUF': 'Ft',
    'IDR': 'Rp',
    'ILS': '₪',
    'IMP': '£',
    'INR': '₹',
    'IQD': 'ع.د',
    'IRR': '﷼',
    'ISK': 'kr',
    'JEP': '£',
    'JMD': 'J$',
    'JOD': 'JD',
    'JPY': '¥',
    'KES': 'KSh',
    'KGS': 'лв',
    'KHR': '៛',
    'KMF': 'CF',
    'KPW': '₩',
    'KRW': '₩',
    'KWD': 'KD',
    'KYD': '$',
    'KZT': 'лв',
    'LAK': '₭',
    'LBP': '£',
    'LKR': '₨',
    'LRD': '$',
    'LSL': 'M',
    'LTC': 'Ł',
    'LTL': 'Lt',
    'LVL': 'Ls',
    'LYD': 'LD',
    'MAD': 'MAD',
    'MDL': 'lei',
    'MGA': 'Ar',
    'MKD': 'ден',
    'MMK': 'K',
    'MNT': '₮',
    'MOP': 'MOP$',
    'MRO': 'UM',
    'MRU': 'UM',
    'MUR': '₨',
    'MVR': 'Rf',
    'MWK': 'MK',
    'MXN': '$',
    'MYR': 'RM',
    'MZN': 'MT',
    'NAD': '$',
    'NGN': '₦',
    'NIO': 'C$',
    'NOK': 'kr',
    'NPR': '₨',
    'NZD': '$',
    'OMR': '﷼',
    'PAB': 'B/.',
    'PEN': 'S/.',
    'PGK': 'K',
    'PHP': '₱',
    'PKR': '₨',
    'PLN': 'zł',
    'PYG': 'Gs',
    'QAR': '﷼',
    'RMB': '￥',
    'RON': 'lei',
    'RSD': 'Дин.',
    'RUB': '₽',
    'RWF': 'R₣',
    'SAR': '﷼',
    'SBD': '$',
    'SCR': '₨',
    'SDG': 'ج.س.',
    'SEK': 'kr',
    'SGD': '$',
    'SHP': '£',
    'SLL': 'Le',
    'SOS': 'S',
    'SRD': '$',
    'SSP': '£',
    'STD': 'Db',
    'STN': 'Db',
    'SVC': '$',
    'SYP': '£',
    'SZL': 'E',
    'THB': '฿',
    'TJS': 'SM',
    'TMT': 'T',
    'TND': 'د.ت',
    'TOP': 'T$',
    'TRL': '₤',
    'TRY': '₺',
    'TTD': 'TT$',
    'TVD': '$',
    'TWD': 'NT$',
    'TZS': 'TSh',
    'UAH': '₴',
    'UGX': 'USh',
    'USD': '$',
    'UYU': '$U',
    'UZS': 'лв',
    'VEF': 'Bs',
    'VND': '₫',
    'VUV': 'VT',
    'WST': 'WS$',
    'XAF': 'FCFA',
    'XBT': 'Ƀ',
    'XCD': '$',
    'XOF': 'CFA',
    'XPF': '₣',
    'YER': '﷼',
    'ZAR': 'R',
    'ZWD': 'Z$'
  };

  root.getCurrencySymbol = function(code) {
    if (!code) return false;

    code = code.toUpperCase();

    if (root.currencySymbols[code]) {
      return root.currencySymbols[code];
    }
    $log.debug("Currency symbol for "+code+" not found");
    return false;
  };

  return root;

});<|endoftext|>


<commit_before>this.mmooc=this.mmooc||{};

this.mmooc.menu = function() {

    function _renderCourseMenu(course, selectedMenuItem, title) {
        var menuItems = [];

        var courseId = course.id;

        menuItems[menuItems.length] = {"title": "Kursforside", url: "/courses/" + courseId};
        menuItems[menuItems.length] = {"title": "Kunngjøringer", url: "/courses/" + courseId + "/announcements"};
        menuItems[menuItems.length] = {"title": "Grupper", url: "/courses/" + courseId + "/groups"};
        menuItems[menuItems.length] = {"title": "Diskusjoner", url: "/courses/" + courseId + "/discussion_topics"};
        menuItems[menuItems.length] = mmooc.menu.extractBadgesLinkFromPage();

        var subtitle = course.name;
        if (title == null) {
            title = course.name;
            subtitle = "";
        }

        var html = mmooc.util.renderTemplateWithData("coursemenu", {course: course, menuItems: menuItems, selectedMenuItem: selectedMenuItem, title: title, subtitle: subtitle });
        document.getElementById('header').insertAdjacentHTML('afterend', html);
    }

    function createStyleSheet () {
        var style = document.createElement("style");

        // WebKit hack :(
        style.appendChild(document.createTextNode(""));

        document.head.appendChild(style);

        return style.sheet;
    }

    var stylesheet = createStyleSheet();

    return {
        listModuleItems: function() {
            mmooc.api.getCurrentModule(function(module) {
                var courseId = mmooc.api.getCurrentCourseId();
                var html = mmooc.util.renderTemplateWithData("moduleitems", {module: module, courseId: courseId});
                document.getElementById('left-side').insertAdjacentHTML('afterbegin', html);
            });
        },
        showLeftMenu: function() {
            stylesheet.insertRule("body.with-left-side #main { margin-left: 305px !important }", stylesheet.cssRules.length);
            stylesheet.insertRule(".with-left-side #left-side { display: block !important }", stylesheet.cssRules.length);
        },

        showTeacherAdminMenu: function() {
            var roles = mmooc.api.getRoles();
            if (roles != null && (roles.indexOf('teacher') != -1 || roles.indexOf('admin') != -1)) {
                this.showLeftMenu();

                $("#section-tabs-header").show();
                $("nav[aria-label='context']").show();
                $("#edit_discussions_settings").show();
                $("#availability_options").show();
                $("#group_category_options").show();
                $("#editor_tabs").show();

                // Done via CSS since content is loaded using AJAX
                stylesheet.insertRule("body.pages .header-bar-outer-container { display: block }", stylesheet.cssRules.length);
                stylesheet.insertRule("#discussion-managebar { display: block }", stylesheet.cssRules.length);
            }

            if (roles != null && roles.indexOf('admin') != -1) {
                // Admin needs original canvas Course dropdown to access site admin settings
                $("#courses_menu_item").show();

                // Admin needs more profile settings
                $(".add_access_token_link").show();
                $("body.profile_settings").find("#content > table, #content > h2, #content > p").show();
            } else {
                document.getElementById('menu').insertAdjacentHTML('afterbegin', '
Kurs
');
            }
        },

        hideRightMenu: function() {
            $("#right-side").hide();
            $("body").removeClass('with-right-side');
        },

        showUserMenu: function() {
            var menu = document.getElementById('menu');
            if (menu !=  null) {
                var html = mmooc.util.renderTemplateWithData("usermenu", {user: mmooc.api.getUser()});
                menu.insertAdjacentHTML('afterend', html);

                var msgBadge = $("#mmooc-unread-messages-count");
                if (mmooc.api.getUnreadMessageSize() === 0) {
                  msgBadge.hide();
                }
                else {
                  msgBadge.html(mmooc.api.getUnreadMessageSize());
                  msgBadge.show();
                }

                mmooc.api.getActivityStreamForUser(function(activities) {
                    var unreadNotifications = 0;
                    for (var i = 0; i < activities.length; i++) {
                        if (mmooc.menu.checkReadStateFor(activities[i])) {
                            unreadNotifications++;
                        }
                    }

                    var badge = $("#mmooc-notification-count");
                    if (unreadNotifications == 0) {
                        badge.hide();
                    } else {
                        badge.html(unreadNotifications);
                        badge.show();
                    }

                    document.getElementById('mmooc-activity-stream').innerHTML = mmooc.util.renderTemplateWithData("activitystream", {activities: activities});

                    var notifications = $("#mmooc-notifications").find("li");
                    if (notifications.size() == 0) {
                        $("#mmooc-notifications").hide();
                    } else {
                        $("#mmooc-notifications").show();
                    }

                    var showAllItems = $("#mmooc-notifications-showall");
                    if (notifications.size() > 10) {
                        notifications.slice(10).addClass("hidden");

                        showAllItems.click(function() {
                            notifications.removeClass("hidden");
                            showAllItems.hide();
                        });
                    } else {
                        showAllItems.hide();
                    }

                });
            }
        },

        showCourseMenu: function(courseId, selectedMenuItem, title) {
            $("body").addClass("with-course-menu");
            mmooc.api.getCourse(courseId, function(course) {
                _renderCourseMenu(course, selectedMenuItem, title);
            });
        },

        showBackButton: function(url, title) {
            var buttonHTML = mmooc.util.renderTemplateWithData("backbutton", {url: url, title: title});
            document.getElementById('content-wrapper').insertAdjacentHTML('afterbegin', buttonHTML);
        },

        showGroupHeader: function() {
            var groupId = mmooc.api.getCurrentGroupId();
            var groupHeaderHTML = mmooc.util.renderTemplateWithData("backbutton", {groupId: groupId});
            document.getElementById('content-wrapper').insertAdjacentHTML('afterbegin', groupHeaderHTML);
        },

        showDiscussionGroupMenu: function() {
            var groupId = mmooc.api.getCurrentGroupId();
            if (groupId != null) {
                mmooc.api.getGroup(groupId, function(group) {
                    // For discussion pages we only want the title to be "<discussion>" instead of "Discussion: <discussion>"
                    var title = mmooc.util.getPageTitleAfterColon();
                    mmooc.menu.showCourseMenu(group.course_id, "Grupper", title);

                    var headerHTML = mmooc.util.renderTemplateWithData("groupdiscussionheader", { group: group});
                    document.getElementById('content-wrapper').insertAdjacentHTML('afterbegin', headerHTML);
                });
            }
        },

        checkReadStateFor: function (activity) {
            return activity.read_state === false;
        },

        extractBadgesLinkFromPage: function () {
            var href = $('li.section:contains("BadgeSafe")').find('a').attr('href');
            return {"title": mmooc.i18n.Badgesafe, url: href};
        },

        injectGroupsPage: function() {
          $('#courses_menu_item').after('
Grupper
');
        }
    };
}();
<commit_msg>Removed redundant menu item<commit_after>this.mmooc=this.mmooc||{};

this.mmooc.menu = function() {

    function _renderCourseMenu(course, selectedMenuItem, title) {
        var menuItems = [];

        var courseId = course.id;

        menuItems[menuItems.length] = {"title": "Kursforside", url: "/courses/" + courseId};
        menuItems[menuItems.length] = {"title": "Kunngjøringer", url: "/courses/" + courseId + "/announcements"};
        menuItems[menuItems.length] = {"title": "Diskusjoner", url: "/courses/" + courseId + "/discussion_topics"};
        menuItems[menuItems.length] = mmooc.menu.extractBadgesLinkFromPage();

        var subtitle = course.name;
        if (title == null) {
            title = course.name;
            subtitle = "";
        }

        var html = mmooc.util.renderTemplateWithData("coursemenu", {course: course, menuItems: menuItems, selectedMenuItem: selectedMenuItem, title: title, subtitle: subtitle });
        document.getElementById('header').insertAdjacentHTML('afterend', html);
    }

    function createStyleSheet () {
        var style = document.createElement("style");

        // WebKit hack :(
        style.appendChild(document.createTextNode(""));

        document.head.appendChild(style);

        return style.sheet;
    }

    var stylesheet = createStyleSheet();

    return {
        listModuleItems: function() {
            mmooc.api.getCurrentModule(function(module) {
                var courseId = mmooc.api.getCurrentCourseId();
                var html = mmooc.util.renderTemplateWithData("moduleitems", {module: module, courseId: courseId});
                document.getElementById('left-side').insertAdjacentHTML('afterbegin', html);
            });
        },
        showLeftMenu: function() {
            stylesheet.insertRule("body.with-left-side #main { margin-left: 305px !important }", stylesheet.cssRules.length);
            stylesheet.insertRule(".with-left-side #left-side { display: block !important }", stylesheet.cssRules.length);
        },

        showTeacherAdminMenu: function() {
            var roles = mmooc.api.getRoles();
            if (roles != null && (roles.indexOf('teacher') != -1 || roles.indexOf('admin') != -1)) {
                this.showLeftMenu();

                $("#section-tabs-header").show();
                $("nav[aria-label='context']").show();
                $("#edit_discussions_settings").show();
                $("#availability_options").show();
                $("#group_category_options").show();
                $("#editor_tabs").show();

                // Done via CSS since content is loaded using AJAX
                stylesheet.insertRule("body.pages .header-bar-outer-container { display: block }", stylesheet.cssRules.length);
                stylesheet.insertRule("#discussion-managebar { display: block }", stylesheet.cssRules.length);
            }

            if (roles != null && roles.indexOf('admin') != -1) {
                // Admin needs original canvas Course dropdown to access site admin settings
                $("#courses_menu_item").show();

                // Admin needs more profile settings
                $(".add_access_token_link").show();
                $("body.profile_settings").find("#content > table, #content > h2, #content > p").show();
            } else {
                document.getElementById('menu').insertAdjacentHTML('afterbegin', '
Kurs
');
            }
        },

        hideRightMenu: function() {
            $("#right-side").hide();
            $("body").removeClass('with-right-side');
        },

        showUserMenu: function() {
            var menu = document.getElementById('menu');
            if (menu !=  null) {
                var html = mmooc.util.renderTemplateWithData("usermenu", {user: mmooc.api.getUser()});
                menu.insertAdjacentHTML('afterend', html);

                var msgBadge = $("#mmooc-unread-messages-count");
                if (mmooc.api.getUnreadMessageSize() === 0) {
                  msgBadge.hide();
                }
                else {
                  msgBadge.html(mmooc.api.getUnreadMessageSize());
                  msgBadge.show();
                }

                mmooc.api.getActivityStreamForUser(function(activities) {
                    var unreadNotifications = 0;
                    for (var i = 0; i < activities.length; i++) {
                        if (mmooc.menu.checkReadStateFor(activities[i])) {
                            unreadNotifications++;
                        }
                    }

                    var badge = $("#mmooc-notification-count");
                    if (unreadNotifications == 0) {
                        badge.hide();
                    } else {
                        badge.html(unreadNotifications);
                        badge.show();
                    }

                    document.getElementById('mmooc-activity-stream').innerHTML = mmooc.util.renderTemplateWithData("activitystream", {activities: activities});

                    var notifications = $("#mmooc-notifications").find("li");
                    if (notifications.size() == 0) {
                        $("#mmooc-notifications").hide();
                    } else {
                        $("#mmooc-notifications").show();
                    }

                    var showAllItems = $("#mmooc-notifications-showall");
                    if (notifications.size() > 10) {
                        notifications.slice(10).addClass("hidden");

                        showAllItems.click(function() {
                            notifications.removeClass("hidden");
                            showAllItems.hide();
                        });
                    } else {
                        showAllItems.hide();
                    }

                });
            }
        },

        showCourseMenu: function(courseId, selectedMenuItem, title) {
            $("body").addClass("with-course-menu");
            mmooc.api.getCourse(courseId, function(course) {
                _renderCourseMenu(course, selectedMenuItem, title);
            });
        },

        showBackButton: function(url, title) {
            var buttonHTML = mmooc.util.renderTemplateWithData("backbutton", {url: url, title: title});
            document.getElementById('content-wrapper').insertAdjacentHTML('afterbegin', buttonHTML);
        },

        showGroupHeader: function() {
            var groupId = mmooc.api.getCurrentGroupId();
            var groupHeaderHTML = mmooc.util.renderTemplateWithData("backbutton", {groupId: groupId});
            document.getElementById('content-wrapper').insertAdjacentHTML('afterbegin', groupHeaderHTML);
        },

        showDiscussionGroupMenu: function() {
            var groupId = mmooc.api.getCurrentGroupId();
            if (groupId != null) {
                mmooc.api.getGroup(groupId, function(group) {
                    // For discussion pages we only want the title to be "<discussion>" instead of "Discussion: <discussion>"
                    var title = mmooc.util.getPageTitleAfterColon();
                    mmooc.menu.showCourseMenu(group.course_id, "Grupper", title);

                    var headerHTML = mmooc.util.renderTemplateWithData("groupdiscussionheader", { group: group});
                    document.getElementById('content-wrapper').insertAdjacentHTML('afterbegin', headerHTML);
                });
            }
        },

        checkReadStateFor: function (activity) {
            return activity.read_state === false;
        },

        extractBadgesLinkFromPage: function () {
            var href = $('li.section:contains("BadgeSafe")').find('a').attr('href');
            return {"title": mmooc.i18n.Badgesafe, url: href};
        },

        injectGroupsPage: function() {
          $('#courses_menu_item').after('
Grupper
');
        }
    };
}();
<|endoftext|>


<commit_before>const normal_text = {
  font: 'Macondo',
  fontSize: '28px',
  fontWeight: 100,
  fill: '#9d8b4f'
}

const red_text = {
  font: 'Macondo',
  fontSize: '28px',
  fontWeight: 100,
  fill: '#975d36'
}

const GAME = require('../../json/game.json')

export default class Intro {
  create () {
    this.bg = this.game.add.tileSprite(0, 0, 1200, 780, 'background');

    this.enterKey = this.game.input.keyboard.addKey(Phaser.Keyboard.ENTER);

    this.introText = this.add.text(
      GAME.width / 2,
      GAME.height / 2,
      `You are a Sumerian farmer, whose days are spent on the toil of the fields,
and whose nights are taken by contemplation
        of the heavens and the work of the Gods.

Scourges of beasts and greedy plunder the land, taking the fruits of others' labor.
Defend your harvest, with arrows from your bow and sacrifices to the Gods.

      `,
      normal_text
    )

    this.introText.anchor.x = 0.5
    this.introText.anchor.y = 0.5

    this.counter = 0

    const pressEnter = this.add.text(
      this.game.width,
      this.game.height,
      "Press ENTER or press on screen to continue",
      red_text
    )

    pressEnter.anchor.setTo(1)

    this.enterFlag = false;

  }

  update () {
    if ((this.enterKey.isDown && this.enterFlag === false) ||
        this.game.input.activePointer.leftButton.isDown && this.clickFlag === false) {
      this.enterFlag = true
      this.clickFlag = true
      this.counter++
      if (this.counter === 1) {
        this.introText.setText(`
Click and hold to draw arrows, aim with the cursor.
Use favors from the Gods by pressing E or touching the calendar.

You have at your service, according to Their timely will,
        the powers of thunder, fertility, fire and heavenly punishment.`)
      }

      if (this.counter === 2) {
        this.state.start('mainGame', true, false, {
          level: 1
        })
      }
    }

      if (this.enterKey.isUp) {
        this.enterFlag = false
      }

      if (this.game.input.activePointer.leftButton.isUp) {
        this.clickFlag = false
      }

  }
}
<commit_msg>Now works with touch<commit_after>const normal_text = {
  font: 'Macondo',
  fontSize: '28px',
  fontWeight: 100,
  fill: '#9d8b4f'
}

const red_text = {
  font: 'Macondo',
  fontSize: '28px',
  fontWeight: 100,
  fill: '#975d36'
}

const GAME = require('../../json/game.json')

export default class Intro {
  create () {
    this.bg = this.game.add.tileSprite(0, 0, 1200, 780, 'background');

    this.enterKey = this.game.input.keyboard.addKey(Phaser.Keyboard.ENTER);

    this.introText = this.add.text(
      GAME.width / 2,
      GAME.height / 2,
      `You are a Sumerian farmer, whose days are spent on the toil of the fields,
and whose nights are taken by contemplation
        of the heavens and the work of the Gods.

Scourges of beasts and greedy plunder the land, taking the fruits of others' labor.
Defend your harvest, with arrows from your bow and sacrifices to the Gods.

      `,
      normal_text
    )

    this.introText.anchor.x = 0.5
    this.introText.anchor.y = 0.5

    this.counter = 0

    const pressEnter = this.add.text(
      this.game.width,
      this.game.height,
      "Press ENTER or press on screen to continue",
      red_text
    )

    pressEnter.anchor.setTo(1)

    this.enterFlag = false;

  }

  update () {
    if ((this.enterKey.isDown && this.enterFlag === false) ||
        this.game.input.activePointer.justPressed() && this.clickFlag === false) {
      this.enterFlag = true
      this.clickFlag = true
      this.counter++
      if (this.counter === 1) {
        this.introText.setText(`
Click and hold to draw arrows, aim with the cursor.
Use favors from the Gods by pressing E or touching the calendar.

You have at your service, according to Their timely will,
        the powers of thunder, fertility, fire and heavenly punishment.`)
      }

      if (this.counter === 2) {
        this.state.start('mainGame', true, false, {
          level: 1
        })
      }
    }

      if (this.enterKey.isUp) {
        this.enterFlag = false
      }

      if (!this.game.input.activePointer.justPressed()) {
        this.clickFlag = false
      }

  }
}
<|endoftext|>


<commit_before>define( "UrlHash" , [ "Base" ] , function( Base ){
    /*!
     *  urlHash提取/保存 管理
     */
    var UrlHash = Base.extend( function(){
        this.url    = window.location.href;
    } , {
        gotoUrl     : function( url , params ){
            window.location.href    = this.getPageUrl( url , params );
            return this;
        } ,
        getPageUrl  : function( url , params ){
            var _urlHash    = [];
            for( var a in params ){
                _urlHash.push( a + "=" + encodeURIComponent( params[ a ] ) );
            }
            return url + "?" + _urlHash.join( "&" );
        } ,
        getHash     : function(){
            var _self   = this ,
                _url ,
                _keyVal ,
                _json   = {};
            return this.urlHash || ( function(){
                if( _self.url.indexOf( "?" ) > -1 ){
                    _url    = _self.url.replace( /.*\?/ , "" ).split( "&" );
                    for( var i = _url.length; i--; ){
                        _keyVal     = _url[ i ].split( "=" );
                        _json[ _keyVal[ 0 ] ]   = decodeURIComponent( _keyVal[ 1 ] );
                    }
                }
                _self.urlHash   = _json;
                return _json;
            } )();
        }
    } );
    return UrlHash;
} );<commit_msg>fix urlhash geturl \?<commit_after>define( "UrlHash" , [ "Base" ] , function( Base ){
    /*!
     *  urlHash提取/保存 管理
     */
    var UrlHash = Base.extend( function(){
        this.url    = window.location.href;
    } , {
        gotoUrl     : function( url , params ){
            window.location.href    = this.getPageUrl( url , params );
            return this;
        } ,
        getPageUrl  : function( url , params ){
            var _urlHash    = [];
            for( var a in params ){
                _urlHash.push( a + "=" + encodeURIComponent( params[ a ] ) );
            }
            return _urlHash.length ? ( url + "?" + _urlHash.join( "&" ) ) : url;
        } ,
        getHash     : function(){
            var _self   = this ,
                _url ,
                _keyVal ,
                _json   = {};
            return this.urlHash || ( function(){
                if( _self.url.indexOf( "?" ) > -1 ){
                    _url    = _self.url.replace( /.*\?/ , "" ).split( "&" );
                    for( var i = _url.length; i--; ){
                        _keyVal     = _url[ i ].split( "=" );
                        _json[ _keyVal[ 0 ] ]   = decodeURIComponent( _keyVal[ 1 ] );
                    }
                }
                _self.urlHash   = _json;
                return _json;
            } )();
        }
    } );
    return UrlHash;
} );<|endoftext|>


<commit_before>import Consumer from 'conductor';

Conductor.require('/vendor/jquery.js');
Conductor.require('/vendor/handlebars.js');
Conductor.require('/vendor/ember-latest.js');
Conductor.require('/vendor/loader.js');
Conductor.requireCSS('/css/glazier_card.css');
Conductor.requireCSS('/cards/github-stars/card.css');

import TestConsumer from 'app/consumers/test';
import IdentityConsumer from 'app/consumers/identity';

var card = Conductor.card({
  consumers: {
    'test': TestConsumer,
    'identity': IdentityConsumer,
    'repository': Conductor.Oasis.Consumer,
    'authenticatedGithubApi': Conductor.Oasis.Consumer,
    'unauthenticatedGithubApi': Conductor.Oasis.Consumer
  },

  App: null,

  render: function (intent, dimensions) {
    if (!dimensions) {
      dimensions = {
        width: 500,
        height: 300
      };
    }

    document.body.innerHTML = "

";

    Ember.run(this.App, 'advanceReadiness');

    return this.App;
  },

  activate: function() {
    this.App = requireModule('app/application');
  },

  metadata: {
    document: function(promise) {
      promise.resolve({
        title: "Github Issues"
      });
    }
  },

  resize: function(dimensions) {
    var width = Math.min(dimensions.width, 500);
    var height = Math.min(dimensions.height, 500);

    $('body>div').css({
      width: width
    });
  }
});

export default card;
<commit_msg>remove unused dimensions code in stars card<commit_after>import Consumer from 'conductor';

Conductor.require('/vendor/jquery.js');
Conductor.require('/vendor/handlebars.js');
Conductor.require('/vendor/ember-latest.js');
Conductor.require('/vendor/loader.js');
Conductor.requireCSS('/css/glazier_card.css');
Conductor.requireCSS('/cards/github-stars/card.css');

import TestConsumer from 'app/consumers/test';
import IdentityConsumer from 'app/consumers/identity';

var card = Conductor.card({
  consumers: {
    'test': TestConsumer,
    'identity': IdentityConsumer,
    'repository': Conductor.Oasis.Consumer,
    'authenticatedGithubApi': Conductor.Oasis.Consumer,
    'unauthenticatedGithubApi': Conductor.Oasis.Consumer
  },

  App: null,

  render: function (intent, dimensions) {
    document.body.innerHTML = "

";
    Ember.run(this.App, 'advanceReadiness');
  },

  activate: function() {
    this.App = requireModule('app/application');
  },

  metadata: {
    document: function(promise) {
      promise.resolve({
        title: "Github Issues"
      });
    }
  }
});

export default card;
<|endoftext|>


<commit_before>import L from 'leaflet';
import Actions from '../actions/actions';
import mapStore from '../stores/mapStore';
import { ModeConstants } from '../constants/constants';

export default class Marker {
  constructor(latLng, icon) {
    this.icon = icon;
    let options = {
      icon,
      draggable: true
    }
    let marker = new L.Marker(latLng, options);
    return this.withHooks(marker);
  }

  static idOnMap(marker) {
    return L.stamp(marker);
  }

  withHooks(marker) {
    let iconMargin = 0;
    let icon = this.icon;
    let mode = null;
    let map = mapStore.getState().map;

    marker.on('click', (e) => {
      e.target.getPopup()._isOpen = false;
      $(e.target.getPopup()._container).css('display', 'block');
    })

    marker.on('add', () => {
      $('.leaflet-popup').css('display', 'none')
    });

    marker.on('dragstart', (e) => {
      let icon = e.target._icon;

      mode = mapStore.getState().mode;
      Actions.changeMode(ModeConstants);

      if (!iconMargin) {
        iconMargin = parseInt(L.DomUtil.getStyle(icon, 'marginTop'));
      }

      icon.style.marginTop = `${iconMargin - 15}px`;
    });

    marker.on('dragend', (e) => {
      let map = mapStore.getState().map;
      e.target._icon.style.marginTop = `${iconMargin}px`;

      map.once('click', () => {
        Actions.changeMode(mode);
      })
    });

    return marker;
  }
}
<commit_msg>Fix marker drag change.<commit_after>import L from 'leaflet';
import Actions from '../actions/actions';
import mapStore from '../stores/mapStore';
import { ModeConstants } from '../constants/constants';

export default class Marker {
  constructor(latLng, icon) {
    this.icon = icon;
    let options = {
      icon,
      draggable: true
    }
    let marker = new L.Marker(latLng, options);
    return this.withHooks(marker);
  }

  static idOnMap(marker) {
    return L.stamp(marker);
  }

  withHooks(marker) {
    let iconMargin = 0;
    let icon = this.icon;
    let mode;
    let map = mapStore.getState().map;

    marker.on('click', (e) => {
      e.target.getPopup()._isOpen = false;
      $(e.target.getPopup()._container).css('display', 'block');
    })

    marker.on('add', () => {
      $('.leaflet-popup').css('display', 'none')
    });

    marker.on('dragstart', (e) => {
      let icon = e.target._icon;

      mode = mapStore.getState().mode;
      Actions.changeMode(ModeConstants.VIEW_MODE);

      if (!iconMargin) {
        iconMargin = parseInt(L.DomUtil.getStyle(icon, 'marginTop'));
      }

      icon.style.marginTop = `${iconMargin - 15}px`;
    });

    marker.on('dragend', (e) => {
      let map = mapStore.getState().map;
      e.target._icon.style.marginTop = `${iconMargin}px`;

      map.once('click', () => {
        Actions.changeMode(mode);
      })
    });

    return marker;
  }
}
<|endoftext|>


<commit_before>/*
 *  DeviceEvents.js
 *  2014/07/15
 *  @auther minimo
 *  This Program is MIT license.
 */

//実行ＯＳ種別
DEVICE_IOS = false;
DEVICE_ANDROID = false;

//定数
//PhoneGap使用可能フラグ
ENABLE_PHONEGAP = false;
DEBUG_PHONEGAP = false;

//GAMECENTER(GooglePlay)使用可能フラグ
ENABLE_GAMECENTER = false;
DEBUG_GAMECENTER = false;

//AdMob使用可能フラグ
ENABLE_ADMOB = false;
DEBUG_ADMOB = false;
TEST_ADMOB = false;

//Social Message
ENABLE_SOCIAL = false;

//PhoneGap Device Events
var onDeviceReady = function () {

    //使用ＯＳの判別
    DEVICE_IOS = ( /(android)/i.test(navigator.userAgent) )? false: true;
    if (!DEVICE_IOS) DEVICE_ANDROID = true;

    if (DEBUG_PHONEGAP) {
        AdvanceAlert('devicereadyイベントが発火しました');
        AdvanceAlert('Device:'+device.name+" "+device.platform);
    }

    ENABLE_PHONEGAP = true;

    //AdMob plugin
    if (AdMob) {
        var defaultOptions = {
            bannerId: admobid.banner,
            interstitialId: admobid.interstitial,
            position: AdMob.AD_POSITION.BOTTOM_CENTER,
            bgColor: 'black',
            isTesting: TEST_ADMOB,
            autoShow: true
        };
        AdMob.setOptions(defaultOptions);
        ENABLE_ADMOB = true;
    }

    //Game Center Plugin
    if (DEVICE_IOS) {
        gamecenter.auth(onGamecenterSuccess, onGamecenterFailure);
    }
    if (DEVICE_ANDROID) {
        googleplaygame.auth(onGamecenterSuccess, onGamecenterFailure);
    }

    //Social Message
    ENABLE_SOCIAL = true;
}

var onPause = function() {
    if (DEBUG_PHONEGAP) AdvanceAlert('pauseイベントが発火しました');

    //ゲーム中の場合ポーズシーンに移行
    var scene = appMain.currentScene;
    if (scene instanceof shotgun.MainScene && !scene.gameend) {
        appMain.pushScene(shotgun.PauseScene(scene));
    }
}

var onResume = function() {
    if (DEBUG_PHONEGAP) AdvanceAlert('resumeイベントが発火しました');

    //GAME CENTERに再度接続を行う
    if (DEVICE_IOS) {
        if (!ENABLE_GAMECENTER) {
            gamecenter.auth(onGamecenterSuccess, onGamecenterFailure);
        }
        return;
    }
    if (DEVICE_ANDROID) {
        if (!ENABLE_GAMECENTER) {
            googleplaygame.auth(onGamecenterSuccess, onGamecenterFailure);
        }
    }
}

var onOnline = function() {
    if (DEBUG_PHONEGAP) AdvanceAlert('onlineイベントが発火しました');
}

var onOffline = function() {
    if (DEBUG_PHONEGAP) AdvanceAlert('offlineイベントが発火しました');
}

//Phonegap Event listener
document.addEventListener("deviceready", onDeviceReady, false);
document.addEventListener('pause', onPause, false);
document.addEventListener('resume', onResume, false);
document.addEventListener('online', onOnline, false);
document.addEventListener('offline', onOffline, false);

/*
 *
 * iOS GameCenter
 * Android Google Play
 *
 */

// GAMECENTER CallBack
var onGamecenterSuccess = function() {
    if (DEBUG_GAMECENTER) AdvanceAlert('GameCenter connect success');
    ENABLE_GAMECENTER = true;
}

var onGamecenterFailure = function(result) {
    if (DEBUG_GAMECENTER) AdvanceAlert('GameCenterに接続できませんでした\n'+result);
    ENABLE_GAMECENTER = false;
}

//リーダーズボード参照
var showLeadersBoard = function(id) {
    id = id || "";

    if (DEVICE_IOS) {
        if (!ENABLE_PHONEGAP) {
            appMain.pushScene(shotgun.AlertDialog({
                height: SC_H*0.2,
                text1: "GameCenterに接続できませんでした",
                fontSize: 32,
                button: "OK"
            }));
            return false;
        }
        //GAMECENTERに接続してない場合は再接続
        if (!ENABLE_GAMECENTER) {
            gamecenter.auth(onGamecenterSuccess, onGamecenterFailure);

            //再接続失敗
            if (!ENABLE_GAMECENTER) {
                appMain.pushScene(shotgun.AlertDialog({
                    height: SC_H*0.2,
                    text1: "GameCenterに接続できませんでした",
                    fontSize: 32,
                    button: "OK"
                }));
                return false;
            }
        }

        gamecenter.showLeaderboard(function(){}, function(){}, {
            leaderboardId: id,
        });
        return true;
    }
    if (DEVICE_ANDROID) {
        if (id == "") {
            googleplaygame.showAllLeaderboards();
        } else {
            googleplaygame.showLeaderboard({
                leaderboardId: id,
            });
        }
        return true;
    }
}

//GameCenterにスコアを登録
var submitScore = function(mode, returnJoker, score) {
    if (!ENABLE_GAMECENTER) return false;
    if (DEVICE_IOS) {
        var id = "Normal_";
        if (mode == GAMEMODE_HARD) id = "Hard_";
        if (returnJoker) id += "RJ";
        gamecenter.submitScore(
            function() {
                if (DEBUG_GAMECENTER) AdvanceAlert('スコア登録に成功しました');
            },
            function() {
                if (DEBUG_GAMECENTER) AdvanceAlert('スコア登録に失敗しました');
            }, {
                score: score,
                leaderboardId: id,
            });
    }
    if (DEVICE_ANDROID) {
        var id = "";
        if (mode == GAMEMODE_NORMAL && !returnJoker) id = "CgkI-I-vk7YTEAIQAA";
        if (mode == GAMEMODE_NORMAL && returnJoker)  id = "CgkI-I-vk7YTEAIQAQ";
        if (mode == GAMEMODE_HARD   && !returnJoker) id = "CgkI-I-vk7YTEAIQAg";
        if (mode == GAMEMODE_HARD   && returnJoker)  id = "CgkI-I-vk7YTEAIQAw";
        googleplaygame.submitScore({
                score: score,
                leaderboardId: id,
            },
            function() {
                if (DEBUG_GAMECENTER) AdvanceAlert('スコア登録に成功しました');
            },
            function() {
                if (DEBUG_GAMECENTER) AdvanceAlert('スコア登録に失敗しました');
            });
    }
}

//GameCenterに実績登録
var reportAchievements = function(id, percent) {
    if (!ENABLE_GAMECENTER) return false;
    if (DEVICE_IOS) {
        gamecenter.reportAchievement(
            function(){
                if (DEBUG_GAMECENTER) AdvanceAlert('実績登録に成功しました');
            },
            function(){
                if (DEBUG_GAMECENTER) AdvanceAlert('実績登録に失敗しました');
            }, {
                achievementId: id,
                percent: "100",
            });
    }
    if (DEVICE_ANDROID) {
        googleplaygame.unlockAchievement({
                achievementId: id,
            },
            function(){
                if (DEBUG_GAMECENTER) AdvanceAlert('実績登録に成功しました');
            },
            function(){
                if (DEBUG_GAMECENTER) AdvanceAlert('実績登録に失敗しました');
            });
    }
    return true;
}

//GameCenterの実績をリセット
var resetAchievements = function() {
    if (!ENABLE_GAMECENTER) return false;
    if (DEVICE_IOS) {
        gamecenter.resetAchievements(
            function(){
                if (DEBUG_GAMECENTER) AdvanceAlert('実績リセットに成功しました');
            },
            function(){
            if (DEBUG_GAMECENTER) AdvanceAlert('実績リセットに失敗しました');
            });
    }
    if (DEVICE_ANDROID) {
    }
}

/*
 *
 * AdMob
 *
 */

var ad_units = {
    ios : {
        banner:       'ca-app-pub-4753786498901311/3019381180', // or DFP format "/6253334/dfp_example_ad"
        interstitial: 'ca-app-pub-4753786498901311/7270571985'
//        banner: '/6253334/dfp_example_ad', // or DFP format "/6253334/dfp_example_ad"
//        interstitial: 'ca-app-pub-3940256099942544/4411468910'
    },
    android : {
        banner:       'ca-app-pub-4753786498901311/3019381180', // or DFP format "/6253334/dfp_example_ad"
        interstitial: 'ca-app-pub-4753786498901311/7270571985'
    }
};
// select the right Ad Id according to platform
var admobid = ( /(android)/i.test(navigator.userAgent) ) ? ad_units.android : ad_units.ios;

// AdMob CallBack
var onBannerLeaveApp = function(result) {
    if (DEBUG_ADMOB) AdvanceAlert('OnBannerLeaveApp\n'+result);
}

var onBannerDismiss = function(result) {
    if (DEBUG_ADMOB) AdvanceAlert('OnBannerDismiss\n'+result);
}

var onInterstitialPresent = function(result) {
    if (DEBUG_ADMOB) AdvanceAlert('onInterstitialPresent\n'+result);
}

var onInterstitialLeaveApp = function(result) {
    if (DEBUG_ADMOB) AdvanceAlert('onInterstitialLeaveApp\n'+result);
}

var onInterstitialDissmiss = function(result) {
    if (DEBUG_ADMOB) AdvanceAlert('onInterstitialDissmiss\n'+result);
}

//AdMob Event listener
document.addEventListener('onBannerLeaveApp', onBannerLeaveApp, false);
document.addEventListener('onBannerDismiss', onBannerDismiss, false);
document.addEventListener('onInterstitialPresent', onInterstitialPresent, false);
document.addEventListener('onInterstitialLeaveApp', onInterstitialLeaveApp, false);
document.addEventListener('onInterstitialDissmiss', onInterstitialDissmiss, false);

/*
 *
 * Social Message
 *
 */

//SNSにメッセージを送（ゲームオーバー時）
var sendSocialMessage = function(mode, returnJoker, score) {
    if (!ENABLE_SOCIAL) return false;

    //メッセージテキストの作成
    var lb = "Normal";
    if (mode == GAMEMODE_HARD) lb = "Hard";
    if (returnJoker) lb += "_RJ";

    var url = "https://itunes.apple.com/jp/app/shottoganpoka/id951249463";
    var text = "ShotgunPoker Score:"+score+"pts("+lb+")【"+url+"】 #ShotgunPoker #SGP_"+lb;
    var message = {
        text: text,
//        activityTypes: ["PostToTwitter"],
    };
    window.socialmessage.send(message);
}

//SNSにメッセージを送る（総合情報）
var sendSocialMessageGlobal = function() {
    if (!ENABLE_SOCIAL) return false;

    var score = 0;
    var mode = GAMEMODE_NORMAL;
    var returnJoker = false;

    //ベストスコアはどれか
    var sc1 = appMain.highScore[GAMEMODE_NORMAL];
    var sc2 = appMain.highScore[GAMEMODE_NORMAL+10];
    var sc3 = appMain.highScore[GAMEMODE_HARD];
    var sc4 = appMain.highScore[GAMEMODE_HARD+10];
    var sc = [sc1, sc2, sc3, sc4];
    score = sc[0];
    for (var i = 1; i < sc.length; i++) {
        if (score < sc[i]) score = sc[i];
    }
    if (score == sc[0]) {mode = GAMEMODE_NORMAL; returnJoker = true;}
    if (score == sc[1]) {mode = GAMEMODE_NORMAL; returnJoker = false;}
    if (score == sc[2]) {mode = GAMEMODE_HARD;   returnJoker = true;}
    if (score == sc[3]) {mode = GAMEMODE_HARD;   returnJoker = false;}

    //メッセージテキストの作成
    var lb = "Normal";
    if (mode == GAMEMODE_HARD) lb = "Hard";
    if (returnJoker) lb += "-RJ";

    var url = "https://itunes.apple.com/jp/app/shottoganpoka/id951249463";
    var text = "ShotgunPoker MyBestScore:"+score+"pts("+lb+")【"+url+"】 #ShotgunPoker #SGP_Best";
    var message = {
        text: text,
//        activityTypes: ["PostToTwitter"],
    };
    window.socialmessage.send(message);
}
<commit_msg>ベストスコアツイート時バグ修正<commit_after>/*
 *  DeviceEvents.js
 *  2014/07/15
 *  @auther minimo
 *  This Program is MIT license.
 */

//実行ＯＳ種別
DEVICE_IOS = false;
DEVICE_ANDROID = false;

//定数
//PhoneGap使用可能フラグ
ENABLE_PHONEGAP = false;
DEBUG_PHONEGAP = false;

//GAMECENTER(GooglePlay)使用可能フラグ
ENABLE_GAMECENTER = false;
DEBUG_GAMECENTER = false;

//AdMob使用可能フラグ
ENABLE_ADMOB = false;
DEBUG_ADMOB = false;
TEST_ADMOB = false;

//Social Message
ENABLE_SOCIAL = false;

//PhoneGap Device Events
var onDeviceReady = function () {

    //使用ＯＳの判別
    DEVICE_IOS = ( /(android)/i.test(navigator.userAgent) )? false: true;
    if (!DEVICE_IOS) DEVICE_ANDROID = true;

    if (DEBUG_PHONEGAP) {
        AdvanceAlert('devicereadyイベントが発火しました');
        AdvanceAlert('Device:'+device.name+" "+device.platform);
    }

    ENABLE_PHONEGAP = true;

    //AdMob plugin
    if (AdMob) {
        var defaultOptions = {
            bannerId: admobid.banner,
            interstitialId: admobid.interstitial,
            position: AdMob.AD_POSITION.BOTTOM_CENTER,
            bgColor: 'black',
            isTesting: TEST_ADMOB,
            autoShow: true
        };
        AdMob.setOptions(defaultOptions);
        ENABLE_ADMOB = true;
    }

    //Game Center Plugin
    if (DEVICE_IOS) {
        gamecenter.auth(onGamecenterSuccess, onGamecenterFailure);
    }
    if (DEVICE_ANDROID) {
        googleplaygame.auth(onGamecenterSuccess, onGamecenterFailure);
    }

    //Social Message
    ENABLE_SOCIAL = true;
}

var onPause = function() {
    if (DEBUG_PHONEGAP) AdvanceAlert('pauseイベントが発火しました');

    //ゲーム中の場合ポーズシーンに移行
    var scene = appMain.currentScene;
    if (scene instanceof shotgun.MainScene && !scene.gameend) {
        appMain.pushScene(shotgun.PauseScene(scene));
    }
}

var onResume = function() {
    if (DEBUG_PHONEGAP) AdvanceAlert('resumeイベントが発火しました');

    //GAME CENTERに再度接続を行う
    if (DEVICE_IOS) {
        if (!ENABLE_GAMECENTER) {
            gamecenter.auth(onGamecenterSuccess, onGamecenterFailure);
        }
        return;
    }
    if (DEVICE_ANDROID) {
        if (!ENABLE_GAMECENTER) {
            googleplaygame.auth(onGamecenterSuccess, onGamecenterFailure);
        }
    }
}

var onOnline = function() {
    if (DEBUG_PHONEGAP) AdvanceAlert('onlineイベントが発火しました');
}

var onOffline = function() {
    if (DEBUG_PHONEGAP) AdvanceAlert('offlineイベントが発火しました');
}

//Phonegap Event listener
document.addEventListener("deviceready", onDeviceReady, false);
document.addEventListener('pause', onPause, false);
document.addEventListener('resume', onResume, false);
document.addEventListener('online', onOnline, false);
document.addEventListener('offline', onOffline, false);

/*
 *
 * iOS GameCenter
 * Android Google Play
 *
 */

// GAMECENTER CallBack
var onGamecenterSuccess = function() {
    if (DEBUG_GAMECENTER) AdvanceAlert('GameCenter connect success');
    ENABLE_GAMECENTER = true;
}

var onGamecenterFailure = function(result) {
    if (DEBUG_GAMECENTER) AdvanceAlert('GameCenterに接続できませんでした\n'+result);
    ENABLE_GAMECENTER = false;
}

//リーダーズボード参照
var showLeadersBoard = function(id) {
    id = id || "";

    if (DEVICE_IOS) {
        if (!ENABLE_PHONEGAP) {
            appMain.pushScene(shotgun.AlertDialog({
                height: SC_H*0.2,
                text1: "GameCenterに接続できませんでした",
                fontSize: 32,
                button: "OK"
            }));
            return false;
        }
        //GAMECENTERに接続してない場合は再接続
        if (!ENABLE_GAMECENTER) {
            gamecenter.auth(onGamecenterSuccess, onGamecenterFailure);

            //再接続失敗
            if (!ENABLE_GAMECENTER) {
                appMain.pushScene(shotgun.AlertDialog({
                    height: SC_H*0.2,
                    text1: "GameCenterに接続できませんでした",
                    fontSize: 32,
                    button: "OK"
                }));
                return false;
            }
        }

        gamecenter.showLeaderboard(function(){}, function(){}, {
            leaderboardId: id,
        });
        return true;
    }
    if (DEVICE_ANDROID) {
        if (id == "") {
            googleplaygame.showAllLeaderboards();
        } else {
            googleplaygame.showLeaderboard({
                leaderboardId: id,
            });
        }
        return true;
    }
}

//GameCenterにスコアを登録
var submitScore = function(mode, returnJoker, score) {
    if (!ENABLE_GAMECENTER) return false;
    if (DEVICE_IOS) {
        var id = "Normal_";
        if (mode == GAMEMODE_HARD) id = "Hard_";
        if (returnJoker) id += "RJ";
        gamecenter.submitScore(
            function() {
                if (DEBUG_GAMECENTER) AdvanceAlert('スコア登録に成功しました');
            },
            function() {
                if (DEBUG_GAMECENTER) AdvanceAlert('スコア登録に失敗しました');
            }, {
                score: score,
                leaderboardId: id,
            });
    }
    if (DEVICE_ANDROID) {
        var id = "";
        if (mode == GAMEMODE_NORMAL && !returnJoker) id = "CgkI-I-vk7YTEAIQAA";
        if (mode == GAMEMODE_NORMAL && returnJoker)  id = "CgkI-I-vk7YTEAIQAQ";
        if (mode == GAMEMODE_HARD   && !returnJoker) id = "CgkI-I-vk7YTEAIQAg";
        if (mode == GAMEMODE_HARD   && returnJoker)  id = "CgkI-I-vk7YTEAIQAw";
        googleplaygame.submitScore({
                score: score,
                leaderboardId: id,
            },
            function() {
                if (DEBUG_GAMECENTER) AdvanceAlert('スコア登録に成功しました');
            },
            function() {
                if (DEBUG_GAMECENTER) AdvanceAlert('スコア登録に失敗しました');
            });
    }
}

//GameCenterに実績登録
var reportAchievements = function(id, percent) {
    if (!ENABLE_GAMECENTER) return false;
    if (DEVICE_IOS) {
        gamecenter.reportAchievement(
            function(){
                if (DEBUG_GAMECENTER) AdvanceAlert('実績登録に成功しました');
            },
            function(){
                if (DEBUG_GAMECENTER) AdvanceAlert('実績登録に失敗しました');
            }, {
                achievementId: id,
                percent: "100",
            });
    }
    if (DEVICE_ANDROID) {
        googleplaygame.unlockAchievement({
                achievementId: id,
            },
            function(){
                if (DEBUG_GAMECENTER) AdvanceAlert('実績登録に成功しました');
            },
            function(){
                if (DEBUG_GAMECENTER) AdvanceAlert('実績登録に失敗しました');
            });
    }
    return true;
}

//GameCenterの実績をリセット
var resetAchievements = function() {
    if (!ENABLE_GAMECENTER) return false;
    if (DEVICE_IOS) {
        gamecenter.resetAchievements(
            function(){
                if (DEBUG_GAMECENTER) AdvanceAlert('実績リセットに成功しました');
            },
            function(){
            if (DEBUG_GAMECENTER) AdvanceAlert('実績リセットに失敗しました');
            });
    }
    if (DEVICE_ANDROID) {
    }
}

/*
 *
 * AdMob
 *
 */

var ad_units = {
    ios : {
        banner:       'ca-app-pub-4753786498901311/3019381180', // or DFP format "/6253334/dfp_example_ad"
        interstitial: 'ca-app-pub-4753786498901311/7270571985'
//        banner: '/6253334/dfp_example_ad', // or DFP format "/6253334/dfp_example_ad"
//        interstitial: 'ca-app-pub-3940256099942544/4411468910'
    },
    android : {
        banner:       'ca-app-pub-4753786498901311/3019381180', // or DFP format "/6253334/dfp_example_ad"
        interstitial: 'ca-app-pub-4753786498901311/7270571985'
    }
};
// select the right Ad Id according to platform
var admobid = ( /(android)/i.test(navigator.userAgent) ) ? ad_units.android : ad_units.ios;

// AdMob CallBack
var onBannerLeaveApp = function(result) {
    if (DEBUG_ADMOB) AdvanceAlert('OnBannerLeaveApp\n'+result);
}

var onBannerDismiss = function(result) {
    if (DEBUG_ADMOB) AdvanceAlert('OnBannerDismiss\n'+result);
}

var onInterstitialPresent = function(result) {
    if (DEBUG_ADMOB) AdvanceAlert('onInterstitialPresent\n'+result);
}

var onInterstitialLeaveApp = function(result) {
    if (DEBUG_ADMOB) AdvanceAlert('onInterstitialLeaveApp\n'+result);
}

var onInterstitialDissmiss = function(result) {
    if (DEBUG_ADMOB) AdvanceAlert('onInterstitialDissmiss\n'+result);
}

//AdMob Event listener
document.addEventListener('onBannerLeaveApp', onBannerLeaveApp, false);
document.addEventListener('onBannerDismiss', onBannerDismiss, false);
document.addEventListener('onInterstitialPresent', onInterstitialPresent, false);
document.addEventListener('onInterstitialLeaveApp', onInterstitialLeaveApp, false);
document.addEventListener('onInterstitialDissmiss', onInterstitialDissmiss, false);

/*
 *
 * Social Message
 *
 */

//SNSにメッセージを送（ゲームオーバー時）
var sendSocialMessage = function(mode, returnJoker, score) {
    if (!ENABLE_SOCIAL) return false;

    //メッセージテキストの作成
    var lb = "Normal";
    if (mode == GAMEMODE_HARD) lb = "Hard";
    if (returnJoker) lb += "_RJ";

    var url = "https://itunes.apple.com/jp/app/shottoganpoka/id951249463";
    var text = "ShotgunPoker Score:"+score+"pts("+lb+")【"+url+"】 #ShotgunPoker #SGP_"+lb;
    var message = {
        text: text,
//        activityTypes: ["PostToTwitter"],
    };
    window.socialmessage.send(message);
}

//SNSにメッセージを送る（総合情報）
var sendSocialMessageGlobal = function() {
    if (!ENABLE_SOCIAL) return false;

    var score = 0;
    var mode = GAMEMODE_NORMAL;
    var returnJoker = false;

    //ベストスコアはどれか
    var sc1 = appMain.highScore[GAMEMODE_NORMAL];
    var sc2 = appMain.highScore[GAMEMODE_NORMAL+10];
    var sc3 = appMain.highScore[GAMEMODE_HARD];
    var sc4 = appMain.highScore[GAMEMODE_HARD+10];
    var sc = [sc1, sc2, sc3, sc4];
    score = sc[0];
    for (var i = 1; i < sc.length; i++) {
        if (score < sc[i]) score = sc[i];
    }
    if (score == sc[0]) {mode = GAMEMODE_NORMAL; returnJoker = false;}
    if (score == sc[1]) {mode = GAMEMODE_NORMAL; returnJoker = true;}
    if (score == sc[2]) {mode = GAMEMODE_HARD;   returnJoker = false;}
    if (score == sc[3]) {mode = GAMEMODE_HARD;   returnJoker = true;}

    //メッセージテキストの作成
    var lb = "Normal";
    if (mode == GAMEMODE_HARD) lb = "Hard";
    if (returnJoker) lb += "-RJ";

    var url = "https://itunes.apple.com/jp/app/shottoganpoka/id951249463";
    var text = "ShotgunPoker MyBestScore:"+score+"pts("+lb+")【"+url+"】 #ShotgunPoker #SGP_Best";
    var message = {
        text: text,
//        activityTypes: ["PostToTwitter"],
    };
    window.socialmessage.send(message);
}
<|endoftext|>


<commit_before>define(function(require) {

    'use strict';

    var zrUtil = require('zrender/core/util');

    var echartsAPIList = [
        'getDom', 'getZr', 'getWidth', 'getHeight', 'dispatchAction', 'isDisposed',
        'on', 'off', 'getDataURL', 'getConnectedDataURL', 'getModel', 'getOption'
    ];

    function ExtensionAPI(chartInstance) {
        zrUtil.each(echartsAPIList, function (name) {
            this[name] = zrUtil.bind(chartInstance[name], chartInstance);
        }, this);

        // Namespace used for extensions, including builtin components
        this._namespaces = {
            // Default echarts namespace
            echarts: {}
        };

        this._defaultNS = 'echarts';
    }

    var extensionProto = ExtensionAPI.prototype;

    /**
     * Create a namespace for extension or component
     * @param {string} ns
     */
    extensionProto.createNamespace = function (ns) {
        this._namespaces[ns] = {};
    };

    /**
     * Set default namespace
     * @param {string} ns
     */
    extensionProto.useNamespace = function (ns) {
        this._defaultNS = ns;
    };

    /**
     * Get value from namespace
     * @param {string} key
     * @param {string} [ns] Use default namespace defined by useNamespace
     */
    extensionProto.get = function (key, ns) {
        ns = ns || this._defaultNS;
        return this._namespaces[ns] && this._namespaces[ns][key];
    };

    /**
     * Put value to namespace
     * @param {string} key
     * @param {*} val
     * @param {string} [ns] Use default namespace defined by useNamespace
     */
    extensionProto.put = function (key, val, ns) {
        ns = ns || this._defaultNS;
        if (this._namespaces[ns]) {
            this._namespaces[ns][key] = val;
        }
    };

    /**
     * Dispose namespace
     * @param {string} key
     */
    extensionProto.disposeNamespace = function (ns) {
        delete this._namespaces[ns];
    };

    return ExtensionAPI;
});<commit_msg>Remove namespace add in previous commit<commit_after>define(function(require) {

    'use strict';

    var zrUtil = require('zrender/core/util');

    var echartsAPIList = [
        'getDom', 'getZr', 'getWidth', 'getHeight', 'dispatchAction', 'isDisposed',
        'on', 'off', 'getDataURL', 'getConnectedDataURL', 'getModel', 'getOption'
    ];

    function ExtensionAPI(chartInstance) {
        zrUtil.each(echartsAPIList, function (name) {
            this[name] = zrUtil.bind(chartInstance[name], chartInstance);
        }, this);
    }

    return ExtensionAPI;
});<|endoftext|>


<commit_before>var idWindow;

var urlWindow = 'https://www.icloud.com';

chrome.browserAction.onClicked.addListener(function() {

	if (idWindow) {
		chrome.windows.update(idWindow, {
			focused : true
		}, function(window) {
			if (chrome.runtime.lastError) {
				openWindow();
			}
		});
	}

	else {
		openWindow();
	}

});

function openWindow() {

	var xWindow = screen.width - screen.availWidth + 25;
	var yWindow = screen.height - screen.availHeight + 25;

	var widthWindow = screen.width - xWindow - 25;
	var heightWindow = screen.height - yWindow - 25;

	chrome.windows.create({
		'url' : urlWindow,
		'type' : 'popup',
		'focused' : true,
		'left' : xWindow,
		'top' : yWindow,
		'width' : widthWindow,
		'height' : heightWindow
	}, function(window) {
		idWindow = window.id;
	});
}
<commit_msg>refactoring (code)<commit_after>var idWindow;

var urlWindow = 'https://www.icloud.com';

chrome.browserAction.onClicked.addListener(function() {

	if (idWindow) {
		chrome.windows.update(idWindow, {
			focused : true
		}, function(window) {
			if (chrome.runtime.lastError) {
				openWindow();
			}
		});
	}

	else {
		openWindow();
	}

});

function openWindow() {

	var xWindow = screen.width - screen.availWidth + 25;
	var yWindow = screen.height - screen.availHeight + 25;

	var widthWindow = screen.width - xWindow - 25;
	var heightWindow = screen.height - yWindow - 25;

	chrome.windows.create({
		'url' : urlWindow,
		'type' : 'popup',
		'focused' : true,
		'left' : xWindow,
		'top' : yWindow,
		'width' : widthWindow,
		'height' : heightWindow
	}, function(window) {
		idWindow = window.id;
	});
}
<|endoftext|>


<commit_before>define(["dojo/_base/kernel", "dojo/_base/declare", "dojo/_base/lang", "dojo/_base/Deferred", "dojo/on", "dojo/aspect", "put-selector/put"],
function(kernel, declare, lang, Deferred, listen, aspect, put){
	// This module isolates the base logic required by store-aware list/grid
	// components, e.g. OnDemandList/Grid and the Pagination extension.

	// Noop function, needed for _trackError when callback due to a bug in 1.8
	// (see http://bugs.dojotoolkit.org/ticket/16667)
	function noop(value){ return value; }

	function emitError(err){
		// called by _trackError in context of list/grid, if an error is encountered
		if(typeof err !== "object"){
			// Ensure we actually have an error object, so we can attach a reference.
			err = new Error(err);
		}else if(err.dojoType === "cancel"){
			// Don't fire dgrid-error events for errors due to canceled requests
			// (unfortunately, the Deferred instrumentation will still log them)
			return;
		}
		// TODO: remove this @ 0.4 (prefer grid property directly on event object)
		err.grid = this;

		if(listen.emit(this.domNode, "dgrid-error", {
				grid: this,
				error: err,
				cancelable: true,
				bubbles: true })){
			console.error(err);
		}
	}

	return declare(null, {
		// store: Object
		//		The object store (implementing the dojo/store API) from which data is
		//		to be fetched.
		store: null,

		// query: Object
		//		Specifies query parameter(s) to pass to store.query calls.
		query: null,

		// queryOptions: Object
		//		Specifies additional query options to mix in when calling store.query;
		//		sort, start, and count are already handled.
		queryOptions: null,

		// getBeforePut: boolean
		//		If true, a get request will be performed to the store before each put
		//		as a baseline when saving; otherwise, existing row data will be used.
		getBeforePut: true,

		// noDataMessage: String
		//		Message to be displayed when no results exist for a query, whether at
		//		the time of the initial query or upon subsequent observed changes.
		//		Defined by _StoreMixin, but to be implemented by subclasses.
		noDataMessage: "",

		// loadingMessage: String
		//		Message displayed when data is loading.
		//		Defined by _StoreMixin, but to be implemented by subclasses.
		loadingMessage: "",

		constructor: function(){
			// Create empty objects on each instance, not the prototype
			this.query = {};
			this.queryOptions = {};
			this.dirty = {};
			this._updating = {}; // Tracks rows that are mid-update
			this._columnsWithSet = {};

			// Reset _columnsWithSet whenever column configuration is reset
			aspect.before(this, "configStructure", lang.hitch(this, function(){
				this._columnsWithSet = {};
			}));
		},

		postCreate: function(){
			this.inherited(arguments);
			if(this.store){
				this._updateNotifyHandle(this.store);
			}
		},

		destroy: function(){
			this.inherited(arguments);
			if(this._notifyHandle){
				this._notifyHandle.remove();
			}
		},

		_configColumn: function(column){
			// summary:
			//		Implements extension point provided by Grid to store references to
			//		any columns with `set` methods, for use during `save`.
			if (column.set){
				this._columnsWithSet[column.field] = column;
			}
			this.inherited(arguments);
		},

		_updateNotifyHandle: function(store){
			// summary:
			//		Unhooks any previously-existing store.notify handle, and
			//		hooks up a new one for the given store.

			if(this._notifyHandle){
				// Unhook notify handler from previous store
				this._notifyHandle.remove();
				delete this._notifyHandle;
			}
			if(store && typeof store.notify === "function"){
				this._notifyHandle = aspect.after(store, "notify",
					lang.hitch(this, "_onNotify"), true);
			}
		},

		_setStore: function(store, query, queryOptions){
			// summary:
			//		Assigns a new store (and optionally query/queryOptions) to the list,
			//		and tells it to refresh.

			this._updateNotifyHandle(store);

			this.store = store;
			this.dirty = {}; // discard dirty map, as it applied to a previous store
			this.set("query", query, queryOptions);
		},
		_setQuery: function(query, queryOptions){
			// summary:
			//		Assigns a new query (and optionally queryOptions) to the list,
			//		and tells it to refresh.

			var sort = queryOptions && queryOptions.sort;

			this.query = query !== undefined ? query : this.query;
			this.queryOptions = queryOptions || this.queryOptions;

			// If we have new sort criteria, pass them through sort
			// (which will update _sort and call refresh in itself).
			// Otherwise, just refresh.
			sort ? this.set("sort", sort) : this.refresh();
		},
		setStore: function(store, query, queryOptions){
			kernel.deprecated("setStore(...)", 'use set("store", ...) instead', "dgrid 0.4");
			this.set("store", store, query, queryOptions);
		},
		setQuery: function(query, queryOptions){
			kernel.deprecated("setQuery(...)", 'use set("query", ...) instead', "dgrid 0.4");
			this.set("query", query, queryOptions);
		},

		_getQueryOptions: function(){
			// summary:
			//		Get a fresh queryOptions object, also including the current sort
			var options = lang.delegate(this.queryOptions, {});
			if(typeof(this._sort) === "function" || this._sort.length){
				// Prevents SimpleQueryEngine from doing unnecessary "null" sorts (which can
				// change the ordering in browsers that don't use a stable sort algorithm, eg Chrome)
				options.sort = this._sort;
			}
			return options;
		},
		_getQuery: function(){
			// summary:
			//		Implemented consistent with _getQueryOptions so that if query is
			//		an object, this returns a protected (delegated) object instead of
			//		the original.
			var q = this.query;
			return typeof q == "object" && q != null ? lang.delegate(q, {}) : q;
		},

		_setSort: function(property, descending){
			// summary:
			//		Sort the content

			// prevent default storeless sort logic as long as we have a store
			if(this.store){ this._lastCollection = null; }
			this.inherited(arguments);
		},

		_onNotify: function(object, existingId){
			// summary:
			//		Method called when the store's notify method is called.

			// Call inherited in case anything was mixed in earlier
			this.inherited(arguments);

			// For adds/puts, check whether any observers are hooked up;
			// if not, force a refresh to properly hook one up now that there is data
			if(object && this._numObservers < 1){
				this.refresh({ keepScrollPosition: true });
			}
		},

		insertRow: function(object, parent, beforeNode, i, options){
			var store = this.store,
				dirty = this.dirty,
				id = store && store.getIdentity(object),
				dirtyObj;

			if(id in dirty && !(id in this._updating)){ dirtyObj = dirty[id]; }
			if(dirtyObj){
				// restore dirty object as delegate on top of original object,
				// to provide protection for subsequent changes as well
				object = lang.delegate(object, dirtyObj);
			}
			return this.inherited(arguments);
		},

		updateDirty: function(id, field, value){
			// summary:
			//		Updates dirty data of a field for the item with the specified ID.
			var dirty = this.dirty,
				dirtyObj = dirty[id];

			if(!dirtyObj){
				dirtyObj = dirty[id] = {};
			}
			dirtyObj[field] = value;
		},
		setDirty: function(id, field, value){
			kernel.deprecated("setDirty(...)", "use updateDirty() instead", "dgrid 0.4");
			this.updateDirty(id, field, value);
		},

		save: function() {
			// Keep track of the store and puts
			var self = this,
				store = this.store,
				dirty = this.dirty,
				dfd = new Deferred(), promise = dfd.promise,
				getFunc = function(id){
					// returns a function to pass as a step in the promise chain,
					// with the id variable closured
					var data;
					return (self.getBeforePut || !(data = self.row(id).data)) ?
						function(){ return store.get(id); } :
						function(){ return data; };
				};

			// function called within loop to generate a function for putting an item
			function putter(id, dirtyObj) {
				// Return a function handler
				return function(object) {
					var colsWithSet = self._columnsWithSet,
						updating = self._updating,
						key, data;

					if (typeof object.set === "function") {
						object.set(dirtyObj);
					} else {
						// Copy dirty props to the original, applying setters if applicable
						for(key in dirtyObj){
							object[key] = dirtyObj[key];
						}
					}

					// Apply any set methods in column definitions.
					// Note that while in the most common cases column.set is intended
					// to return transformed data for the key in question, it is also
					// possible to directly modify the object to be saved.
					for(key in colsWithSet){
						data = colsWithSet[key].set(object);
						if(data !== undefined){ object[key] = data; }
					}

					updating[id] = true;
					// Put it in the store, returning the result/promise
					return Deferred.when(store.put(object), function() {
						// Clear the item now that it's been confirmed updated
						delete dirty[id];
						delete updating[id];
					});
				};
			}

			// For every dirty item, grab the ID
			for(var id in dirty) {
				// Create put function to handle the saving of the the item
				var put = putter(id, dirty[id]);

				// Add this item onto the promise chain,
				// getting the item from the store first if desired.
				promise = promise.then(getFunc(id)).then(put);
			}

			// Kick off and return the promise representing all applicable get/put ops.
			// If the success callback is fired, all operations succeeded; otherwise,
			// save will stop at the first error it encounters.
			dfd.resolve();
			return promise;
		},

		revert: function(){
			// summary:
			//		Reverts any changes since the previous save.
			this.dirty = {};
			this.refresh();
		},

		_trackError: function(func){
			// summary:
			//		Utility function to handle emitting of error events.
			// func: Function|String
			//		A function which performs some store operation, or a String identifying
			//		a function to be invoked (sans arguments) hitched against the instance.
			//		If sync, it can return a value, but may throw an error on failure.
			//		If async, it should return a promise, which would fire the error
			//		callback on failure.
			// tags:
			//		protected

			var result;

			if(typeof func == "string"){ func = lang.hitch(this, func); }

			try{
				result = func();
			}catch(err){
				// report sync error
				emitError.call(this, err);
			}

			// wrap in when call to handle reporting of potential async error
			return Deferred.when(result, noop, lang.hitch(this, emitError));
		},

		newRow: function(){
			// Override to remove no data message when a new row appears.
			// Run inherited logic first to prevent confusion due to noDataNode
			// no longer being present as a sibling.
			var row = this.inherited(arguments);
			if(this.noDataNode){
				put(this.noDataNode, "!");
				delete this.noDataNode;
			}
			return row;
		},
		removeRow: function(rowElement, justCleanup){
			var row = {element: rowElement};
			// Check to see if we are now empty...
			if(!justCleanup && this.noDataMessage &&
					(this.up(row).element === rowElement) &&
					(this.down(row).element === rowElement)){
				// ...we are empty, so show the no data message.
				this.noDataNode = put(this.contentNode, "div.dgrid-no-data");
				this.noDataNode.innerHTML = this.noDataMessage;
			}
			return this.inherited(arguments);
		}
	});
});
<commit_msg>Add warning about not setting sort on observable stores<commit_after>define(["dojo/_base/kernel", "dojo/_base/declare", "dojo/_base/lang", "dojo/_base/Deferred", "dojo/on", "dojo/aspect", "put-selector/put"],
function(kernel, declare, lang, Deferred, listen, aspect, put){
	// This module isolates the base logic required by store-aware list/grid
	// components, e.g. OnDemandList/Grid and the Pagination extension.

	// Noop function, needed for _trackError when callback due to a bug in 1.8
	// (see http://bugs.dojotoolkit.org/ticket/16667)
	function noop(value){ return value; }

	function emitError(err){
		// called by _trackError in context of list/grid, if an error is encountered
		if(typeof err !== "object"){
			// Ensure we actually have an error object, so we can attach a reference.
			err = new Error(err);
		}else if(err.dojoType === "cancel"){
			// Don't fire dgrid-error events for errors due to canceled requests
			// (unfortunately, the Deferred instrumentation will still log them)
			return;
		}
		// TODO: remove this @ 0.4 (prefer grid property directly on event object)
		err.grid = this;

		if(listen.emit(this.domNode, "dgrid-error", {
				grid: this,
				error: err,
				cancelable: true,
				bubbles: true })){
			console.error(err);
		}
	}

	return declare(null, {
		// store: Object
		//		The object store (implementing the dojo/store API) from which data is
		//		to be fetched.
		store: null,

		// query: Object
		//		Specifies query parameter(s) to pass to store.query calls.
		query: null,

		// queryOptions: Object
		//		Specifies additional query options to mix in when calling store.query;
		//		sort, start, and count are already handled.
		queryOptions: null,

		// getBeforePut: boolean
		//		If true, a get request will be performed to the store before each put
		//		as a baseline when saving; otherwise, existing row data will be used.
		getBeforePut: true,

		// noDataMessage: String
		//		Message to be displayed when no results exist for a query, whether at
		//		the time of the initial query or upon subsequent observed changes.
		//		Defined by _StoreMixin, but to be implemented by subclasses.
		noDataMessage: "",

		// loadingMessage: String
		//		Message displayed when data is loading.
		//		Defined by _StoreMixin, but to be implemented by subclasses.
		loadingMessage: "",

		constructor: function(){
			// Create empty objects on each instance, not the prototype
			this.query = {};
			this.queryOptions = {};
			this.dirty = {};
			this._updating = {}; // Tracks rows that are mid-update
			this._columnsWithSet = {};

			// Reset _columnsWithSet whenever column configuration is reset
			aspect.before(this, "configStructure", lang.hitch(this, function(){
				this._columnsWithSet = {};
			}));
		},

		postCreate: function(){
			this.inherited(arguments);
			if(this.store){
				this._updateNotifyHandle(this.store);
			}
		},

		destroy: function(){
			this.inherited(arguments);
			if(this._notifyHandle){
				this._notifyHandle.remove();
			}
		},

		_configColumn: function(column){
			// summary:
			//		Implements extension point provided by Grid to store references to
			//		any columns with `set` methods, for use during `save`.
			if (column.set){
				this._columnsWithSet[column.field] = column;
			}
			this.inherited(arguments);
		},

		_updateNotifyHandle: function(store){
			// summary:
			//		Unhooks any previously-existing store.notify handle, and
			//		hooks up a new one for the given store.

			if(this._notifyHandle){
				// Unhook notify handler from previous store
				this._notifyHandle.remove();
				delete this._notifyHandle;
			}
			if(store && typeof store.notify === "function"){
				this._notifyHandle = aspect.after(store, "notify",
					lang.hitch(this, "_onNotify"), true);

				var sort = this.get("sort");
				if (!sort || !sort.length) {
					console.warn("Observable store detected, but no sort order specified. " +
						"You may experience quirks when adding/updating items.  " +
						"These can be resolved by setting a sort order on the list or grid.");
				}
			}
		},

		_setStore: function(store, query, queryOptions){
			// summary:
			//		Assigns a new store (and optionally query/queryOptions) to the list,
			//		and tells it to refresh.

			this._updateNotifyHandle(store);

			this.store = store;
			this.dirty = {}; // discard dirty map, as it applied to a previous store
			this.set("query", query, queryOptions);
		},
		_setQuery: function(query, queryOptions){
			// summary:
			//		Assigns a new query (and optionally queryOptions) to the list,
			//		and tells it to refresh.

			var sort = queryOptions && queryOptions.sort;

			this.query = query !== undefined ? query : this.query;
			this.queryOptions = queryOptions || this.queryOptions;

			// If we have new sort criteria, pass them through sort
			// (which will update _sort and call refresh in itself).
			// Otherwise, just refresh.
			sort ? this.set("sort", sort) : this.refresh();
		},
		setStore: function(store, query, queryOptions){
			kernel.deprecated("setStore(...)", 'use set("store", ...) instead', "dgrid 0.4");
			this.set("store", store, query, queryOptions);
		},
		setQuery: function(query, queryOptions){
			kernel.deprecated("setQuery(...)", 'use set("query", ...) instead', "dgrid 0.4");
			this.set("query", query, queryOptions);
		},

		_getQueryOptions: function(){
			// summary:
			//		Get a fresh queryOptions object, also including the current sort
			var options = lang.delegate(this.queryOptions, {});
			if(typeof(this._sort) === "function" || this._sort.length){
				// Prevents SimpleQueryEngine from doing unnecessary "null" sorts (which can
				// change the ordering in browsers that don't use a stable sort algorithm, eg Chrome)
				options.sort = this._sort;
			}
			return options;
		},
		_getQuery: function(){
			// summary:
			//		Implemented consistent with _getQueryOptions so that if query is
			//		an object, this returns a protected (delegated) object instead of
			//		the original.
			var q = this.query;
			return typeof q == "object" && q != null ? lang.delegate(q, {}) : q;
		},

		_setSort: function(property, descending){
			// summary:
			//		Sort the content

			// prevent default storeless sort logic as long as we have a store
			if(this.store){ this._lastCollection = null; }
			this.inherited(arguments);
		},

		_onNotify: function(object, existingId){
			// summary:
			//		Method called when the store's notify method is called.

			// Call inherited in case anything was mixed in earlier
			this.inherited(arguments);

			// For adds/puts, check whether any observers are hooked up;
			// if not, force a refresh to properly hook one up now that there is data
			if(object && this._numObservers < 1){
				this.refresh({ keepScrollPosition: true });
			}
		},

		insertRow: function(object, parent, beforeNode, i, options){
			var store = this.store,
				dirty = this.dirty,
				id = store && store.getIdentity(object),
				dirtyObj;

			if(id in dirty && !(id in this._updating)){ dirtyObj = dirty[id]; }
			if(dirtyObj){
				// restore dirty object as delegate on top of original object,
				// to provide protection for subsequent changes as well
				object = lang.delegate(object, dirtyObj);
			}
			return this.inherited(arguments);
		},

		updateDirty: function(id, field, value){
			// summary:
			//		Updates dirty data of a field for the item with the specified ID.
			var dirty = this.dirty,
				dirtyObj = dirty[id];

			if(!dirtyObj){
				dirtyObj = dirty[id] = {};
			}
			dirtyObj[field] = value;
		},
		setDirty: function(id, field, value){
			kernel.deprecated("setDirty(...)", "use updateDirty() instead", "dgrid 0.4");
			this.updateDirty(id, field, value);
		},

		save: function() {
			// Keep track of the store and puts
			var self = this,
				store = this.store,
				dirty = this.dirty,
				dfd = new Deferred(), promise = dfd.promise,
				getFunc = function(id){
					// returns a function to pass as a step in the promise chain,
					// with the id variable closured
					var data;
					return (self.getBeforePut || !(data = self.row(id).data)) ?
						function(){ return store.get(id); } :
						function(){ return data; };
				};

			// function called within loop to generate a function for putting an item
			function putter(id, dirtyObj) {
				// Return a function handler
				return function(object) {
					var colsWithSet = self._columnsWithSet,
						updating = self._updating,
						key, data;

					if (typeof object.set === "function") {
						object.set(dirtyObj);
					} else {
						// Copy dirty props to the original, applying setters if applicable
						for(key in dirtyObj){
							object[key] = dirtyObj[key];
						}
					}

					// Apply any set methods in column definitions.
					// Note that while in the most common cases column.set is intended
					// to return transformed data for the key in question, it is also
					// possible to directly modify the object to be saved.
					for(key in colsWithSet){
						data = colsWithSet[key].set(object);
						if(data !== undefined){ object[key] = data; }
					}

					updating[id] = true;
					// Put it in the store, returning the result/promise
					return Deferred.when(store.put(object), function() {
						// Clear the item now that it's been confirmed updated
						delete dirty[id];
						delete updating[id];
					});
				};
			}

			// For every dirty item, grab the ID
			for(var id in dirty) {
				// Create put function to handle the saving of the the item
				var put = putter(id, dirty[id]);

				// Add this item onto the promise chain,
				// getting the item from the store first if desired.
				promise = promise.then(getFunc(id)).then(put);
			}

			// Kick off and return the promise representing all applicable get/put ops.
			// If the success callback is fired, all operations succeeded; otherwise,
			// save will stop at the first error it encounters.
			dfd.resolve();
			return promise;
		},

		revert: function(){
			// summary:
			//		Reverts any changes since the previous save.
			this.dirty = {};
			this.refresh();
		},

		_trackError: function(func){
			// summary:
			//		Utility function to handle emitting of error events.
			// func: Function|String
			//		A function which performs some store operation, or a String identifying
			//		a function to be invoked (sans arguments) hitched against the instance.
			//		If sync, it can return a value, but may throw an error on failure.
			//		If async, it should return a promise, which would fire the error
			//		callback on failure.
			// tags:
			//		protected

			var result;

			if(typeof func == "string"){ func = lang.hitch(this, func); }

			try{
				result = func();
			}catch(err){
				// report sync error
				emitError.call(this, err);
			}

			// wrap in when call to handle reporting of potential async error
			return Deferred.when(result, noop, lang.hitch(this, emitError));
		},

		newRow: function(){
			// Override to remove no data message when a new row appears.
			// Run inherited logic first to prevent confusion due to noDataNode
			// no longer being present as a sibling.
			var row = this.inherited(arguments);
			if(this.noDataNode){
				put(this.noDataNode, "!");
				delete this.noDataNode;
			}
			return row;
		},
		removeRow: function(rowElement, justCleanup){
			var row = {element: rowElement};
			// Check to see if we are now empty...
			if(!justCleanup && this.noDataMessage &&
					(this.up(row).element === rowElement) &&
					(this.down(row).element === rowElement)){
				// ...we are empty, so show the no data message.
				this.noDataNode = put(this.contentNode, "div.dgrid-no-data");
				this.noDataNode.innerHTML = this.noDataMessage;
			}
			return this.inherited(arguments);
		}
	});
});
<|endoftext|>


<commit_before>var $ = require('jquery');
var Backbone = require('backbone');
var UserAssetsListView = require('../../../../../../../../../javascripts/cartodb3/components/form-components/editors/fill/input-color/assets-picker/user-assets-list-view');
var AssetsCollection = require('../../../../../../../../../javascripts/cartodb3/data/assets-collection');
var ConfigModel = require('../../../../../../../../../javascripts/cartodb3/data/config-model');
var UserModel = require('../../../../../../../../../javascripts/cartodb3/data/user-model');
var OrganizationAssetsCollection = require('../../../../../../../../../javascripts/cartodb3/data/organization-assets-collection');
var AssetModel = require('../../../../../../../../../javascripts/cartodb3/data/asset-model');

describe('components/form-components/editors/fill/input-color/assets-picker/user-assets-list-view', function () {
  beforeEach(function () {
    this.model = new Backbone.Model({
      image: '/image.png'
    });
    this.selectedAsset = new Backbone.Model();

    this.configModel = new ConfigModel({
      base_url: '/u/pepe'
    });

    this.userModel = new UserModel({}, {
      configModel: this.configModel
    });

    var asset1 = new AssetModel({
      item: 1, state: '', public_url: 'one.jpg'
    });

    var asset2 = new AssetModel({
      item: 2, state: '', public_url: 'two.png'
    });

    var asset3 = new AssetModel({
      item: 3, state: '', public_url: 'three.gif'
    });

    this._userAssetCollection = new AssetsCollection([asset1, asset2, asset3], {
      configModel: configModel,
      userModel: userModel
    });

    this.view = new UserAssetsListView({
      title: 'Title',
      model: this.model,
      userAssetCollection: this._userAssetCollection,
      selectedAsset: this.selectedAsset,
      userModel: this.userModel
    });

    this.view.render();
  });

  it('should render the assets', function () {
    expect(this.view.$el.find('.js-asset').length).toBe(this._userAssetCollection.size() + 1);
  });

  it('should render the add button', function () {
    expect(this.view.$el.find('.AssetsList-item--text .js-asset').text().trim()).toBe('+');
    expect(this.view.$el.find('.AssetsList-item--text .js-asset').length).toBe(1);
  });

  it('should trigger an upload event when clicking the add button', function () {
    var triggered = false;

    this.view.bind('init-upload', function () {
      triggered = true;
    }, this);

    this.view.$el.find('.AssetsList-item--text .js-asset').click();
    expect(triggered).toBeTruthy();
  });

  it('should select an asset', function () {
    this._userAssetCollection.at(0).set('state', '');
    this._userAssetCollection.at(1).set('state', '');
    this._userAssetCollection.at(2).set('state', '');

    expect(this._userAssetCollection.where({ state: 'selected' }).length).toBe(0);
    $(this.view.$('.js-asset')[1]).click();
    expect(this.view.$('.is-selected').length).toBe(1);
    expect(this._userAssetCollection.where({ state: 'selected' }).length).toBe(1);
    expect(this._userAssetCollection.at(0).get('state')).toBe('selected');
  });

  it('should select all the assets', function () {
    this._userAssetCollection.at(0).set('state', 'selected');

    this.view.$('.js-select-all').click();
    expect(this.view.$('.is-selected').length).toBe(3);
    expect(this._userAssetCollection.at(0).get('state')).toBe('selected');
    expect(this._userAssetCollection.at(1).get('state')).toBe('selected');
    expect(this._userAssetCollection.at(2).get('state')).toBe('selected');
  });

  it('should deselect all the assets', function () {
    this._userAssetCollection.at(0).set('state', 'selected');
    this._userAssetCollection.at(1).set('state', 'selected');
    this._userAssetCollection.at(2).set('state', 'selected');

    this.view.$('.js-deselect-all').click();
    expect(this._userAssetCollection.at(0).get('state')).toBe('');
    expect(this._userAssetCollection.at(1).get('state')).toBe('');
    expect(this._userAssetCollection.at(2).get('state')).toBe('');
    expect(this.view.$('.is-selected').length).toBe(0);
  });

  describe('when user is inside organization', function () {
    var view;

    beforeEach(function () {
      spyOn(this.userModel, 'isInsideOrg').and.returnValue(true);

      this._organizationAssetCollection = new OrganizationAssetsCollection([{
        item: 1, state: ''
      }, {
        item: 2, state: ''
      }, {
        item: 3, state: ''
      }], {
        configModel: this.configModel,
        orgId: this.userModel
      });

      view = new UserAssetsListView({
        title: 'Title',
        model: this.model,
        userAssetCollection: this._userAssetCollection,
        organizationAssetCollection: this._organizationAssetCollection,
        selectedAsset: this.selectedAsset,
        userModel: this.userModel
      });

      view.render();
    });

    it('should select an asset and deselect all the organization assets', function () {
      this._organizationAssetCollection.at(0).set('state', 'selected');

      expect(this._userAssetCollection.where({ state: 'selected' }).length).toBe(0);
      expect(this._userAssetCollection.at(0).get('state')).toBe('');
      expect(this._organizationAssetCollection.where({ state: 'selected' }).length).toBe(1);
      expect(this._organizationAssetCollection.at(0).get('state')).toBe('selected');

      $(view.$('.js-asset')[1]).click();

      expect(this.view.$('.is-selected').length).toBe(1);
      expect(this._userAssetCollection.where({ state: 'selected' }).length).toBe(1);
      expect(this._userAssetCollection.at(0).get('state')).toBe('selected');
      expect(this._organizationAssetCollection.where({ state: 'selected' }).length).toBe(0);
      expect(this._organizationAssetCollection.at(0).get('state')).toBe('');
    });
  });

  it('should remove selected assets', function () {
    this._userAssetCollection.at(0).set('state', 'selected');
    this._userAssetCollection.at(1).set('state', 'selected');
    this._userAssetCollection.at(2).set('state', '');

    this.view.$('.js-remove').click();
    expect(this._userAssetCollection.size()).toBe(1);
  });

  it('should unset the selected asset', function () {
    var self = this;

    AssetModel.prototype.destroy = function () {
      self.view._onDestroyFinished({ status: 200 });
    };

    this._assetsCollection.at(0).set('state', 'selected');
    this._assetsCollection.at(1).set('state', '');
    this._assetsCollection.at(2).set('state', '');

    expect(this.selectedAsset.get('url')).toBe('one.jpg');
    expect(this.selectedAsset.get('kind')).toBe('custom-marker');

    this.view.$('.js-remove').click();
    expect(this.selectedAsset.get('url')).toBe(undefined);
    expect(this.selectedAsset.get('kind')).toBe(undefined);
  });

  afterEach(function () {
    this.view.clean();
  });
});

<commit_msg>fix tests<commit_after>var $ = require('jquery');
var Backbone = require('backbone');
var UserAssetsListView = require('../../../../../../../../../javascripts/cartodb3/components/form-components/editors/fill/input-color/assets-picker/user-assets-list-view');
var AssetsCollection = require('../../../../../../../../../javascripts/cartodb3/data/assets-collection');
var ConfigModel = require('../../../../../../../../../javascripts/cartodb3/data/config-model');
var UserModel = require('../../../../../../../../../javascripts/cartodb3/data/user-model');
var OrganizationAssetsCollection = require('../../../../../../../../../javascripts/cartodb3/data/organization-assets-collection');
var AssetModel = require('../../../../../../../../../javascripts/cartodb3/data/asset-model');

describe('components/form-components/editors/fill/input-color/assets-picker/user-assets-list-view', function () {
  beforeEach(function () {
    this.model = new Backbone.Model({
      image: '/image.png'
    });
    this.selectedAsset = new Backbone.Model();

    this.configModel = new ConfigModel({
      base_url: '/u/pepe'
    });

    this.userModel = new UserModel({}, {
      configModel: this.configModel
    });

    var asset1 = new AssetModel({
      item: 1, state: '', public_url: 'one.jpg'
    });

    var asset2 = new AssetModel({
      item: 2, state: '', public_url: 'two.png'
    });

    var asset3 = new AssetModel({
      item: 3, state: '', public_url: 'three.gif'
    });

    this._userAssetCollection = new AssetsCollection([asset1, asset2, asset3], {
      configModel: this.configModel,
      userModel: this.userModel
    });

    this.view = new UserAssetsListView({
      title: 'Title',
      model: this.model,
      userAssetCollection: this._userAssetCollection,
      selectedAsset: this.selectedAsset,
      userModel: this.userModel
    });

    this.view.render();
  });

  it('should render the assets', function () {
    expect(this.view.$el.find('.js-asset').length).toBe(this._userAssetCollection.size() + 1);
  });

  it('should render the add button', function () {
    expect(this.view.$el.find('.AssetsList-item--text .js-asset').text().trim()).toBe('+');
    expect(this.view.$el.find('.AssetsList-item--text .js-asset').length).toBe(1);
  });

  it('should trigger an upload event when clicking the add button', function () {
    var triggered = false;

    this.view.bind('init-upload', function () {
      triggered = true;
    }, this);

    this.view.$el.find('.AssetsList-item--text .js-asset').click();
    expect(triggered).toBeTruthy();
  });

  it('should select an asset', function () {
    this._userAssetCollection.at(0).set('state', '');
    this._userAssetCollection.at(1).set('state', '');
    this._userAssetCollection.at(2).set('state', '');

    expect(this._userAssetCollection.where({ state: 'selected' }).length).toBe(0);
    $(this.view.$('.js-asset')[1]).click();
    expect(this.view.$('.is-selected').length).toBe(1);
    expect(this._userAssetCollection.where({ state: 'selected' }).length).toBe(1);
    expect(this._userAssetCollection.at(0).get('state')).toBe('selected');
  });

  it('should select all the assets', function () {
    this._userAssetCollection.at(0).set('state', 'selected');

    this.view.$('.js-select-all').click();
    expect(this.view.$('.is-selected').length).toBe(3);
    expect(this._userAssetCollection.at(0).get('state')).toBe('selected');
    expect(this._userAssetCollection.at(1).get('state')).toBe('selected');
    expect(this._userAssetCollection.at(2).get('state')).toBe('selected');
  });

  it('should deselect all the assets', function () {
    this._userAssetCollection.at(0).set('state', 'selected');
    this._userAssetCollection.at(1).set('state', 'selected');
    this._userAssetCollection.at(2).set('state', 'selected');

    this.view.$('.js-deselect-all').click();
    expect(this._userAssetCollection.at(0).get('state')).toBe('');
    expect(this._userAssetCollection.at(1).get('state')).toBe('');
    expect(this._userAssetCollection.at(2).get('state')).toBe('');
    expect(this.view.$('.is-selected').length).toBe(0);
  });

  describe('when user is inside organization', function () {
    var view;

    beforeEach(function () {
      spyOn(this.userModel, 'isInsideOrg').and.returnValue(true);

      this._organizationAssetCollection = new OrganizationAssetsCollection([{
        item: 1, state: ''
      }, {
        item: 2, state: ''
      }, {
        item: 3, state: ''
      }], {
        configModel: this.configModel,
        orgId: this.userModel
      });

      view = new UserAssetsListView({
        title: 'Title',
        model: this.model,
        userAssetCollection: this._userAssetCollection,
        organizationAssetCollection: this._organizationAssetCollection,
        selectedAsset: this.selectedAsset,
        userModel: this.userModel
      });

      view.render();
    });

    it('should select an asset and deselect all the organization assets', function () {
      this._organizationAssetCollection.at(0).set('state', 'selected');

      expect(this._userAssetCollection.where({ state: 'selected' }).length).toBe(0);
      expect(this._userAssetCollection.at(0).get('state')).toBe('');
      expect(this._organizationAssetCollection.where({ state: 'selected' }).length).toBe(1);
      expect(this._organizationAssetCollection.at(0).get('state')).toBe('selected');

      $(view.$('.js-asset')[1]).click();

      expect(this.view.$('.is-selected').length).toBe(1);
      expect(this._userAssetCollection.where({ state: 'selected' }).length).toBe(1);
      expect(this._userAssetCollection.at(0).get('state')).toBe('selected');
      expect(this._organizationAssetCollection.where({ state: 'selected' }).length).toBe(0);
      expect(this._organizationAssetCollection.at(0).get('state')).toBe('');
    });
  });

  it('should remove selected assets', function () {
    this._userAssetCollection.at(0).set('state', 'selected');
    this._userAssetCollection.at(1).set('state', 'selected');
    this._userAssetCollection.at(2).set('state', '');

    this.view.$('.js-remove').click();
    expect(this._userAssetCollection.size()).toBe(1);
  });

  it('should unset the selected asset', function () {
    var self = this;

    AssetModel.prototype.destroy = function () {
      self.view._onDestroyFinished({ status: 200 });
    };

    this._assetsCollection.at(0).set('state', 'selected');
    this._assetsCollection.at(1).set('state', '');
    this._assetsCollection.at(2).set('state', '');

    expect(this.selectedAsset.get('url')).toBe('one.jpg');
    expect(this.selectedAsset.get('kind')).toBe('custom-marker');

    this.view.$('.js-remove').click();
    expect(this.selectedAsset.get('url')).toBe(undefined);
    expect(this.selectedAsset.get('kind')).toBe(undefined);
  });

  afterEach(function () {
    this.view.clean();
  });
});

<|endoftext|>