<commit_before>define([
	"dojo/_base/declare", "dojo/_base/lang",
	"./TabViewerBase",
	"../AntibioticOverview", "../AMRPanelGridContainer", "../FeatureGridContainer", "../SpecialtyGeneGridContainer",
	"../../util/QueryToEnglish"
], function(declare, lang,
			TabViewerBase,
			AntibioticOverview, AMRPanelGridContainer, FeatureGridContainer, SpecialtyGeneGridContainer,
			QueryToEnglish){

	return declare([TabViewerBase], {

		perspectiveLabel: "Antibiotic View",
		perspectiveIconClass: "icon-selection-Antibiotic",

		onSetState: function(attr, oldVal, state){

			if(!state){
				return;
			}

			if(!state.search){
				this.queryNode.innerHTML = "Error";
				this.totalCountNode.innerHTML = "";
			}

			// bypass setting attribute and invoke tabs with state
			this.buildHeaderContent(state.search);

			if(state.hashParams && state.hashParams.view_tab){
				if(this[state.hashParams.view_tab]){
					var vt = this[state.hashParams.view_tab];

					vt.set("visible", true);
					this.viewer.selectChild(vt);
				}else{
					// console.log("No view-tab supplied in State Object");
				}
			}

			this.setActivePanelState();
		},

		setActivePanelState: function(){
			var activeQueryState;

			var active = (this.state && this.state.hashParams && this.state.hashParams.view_tab) ? this.state.hashParams.view_tab : "overview";
			var activeTab = this[active];
			var antibioticName = this.state.search.split(",")[1].split(")")[0];

			switch(active){
				case "overview":
					activeTab.set("state", lang.mixin({}, this.state));
					break;
				case "amr":
					activeTab.set("state", lang.mixin({}, this.state, {
						search: "eq(antibiotic," + antibioticName + ")"
					}));
					break;
				case "amrGenes":
					activeTab.set("state", lang.mixin({}, this.state, {
						search: "keyword(" + antibioticName + ")&eq(property,%22Antibiotic%20Resistance%22)"
					}));
					break;
				case "amrRegions":
					activeTab.set("state", lang.mixin({}, this.state, {
						search: "keyword(" + antibioticName + ")&eq(feature_type,classifier_predicted_region)"
					}));
					break;
				default:
					if(activeQueryState){
						activeTab.set("state", activeQueryState);
					}else{
						console.error("Missing Active Query State for: ", active);
					}
					break;
			}
		},

		buildHeaderContent: function(search){

			this.queryNode.innerHTML = QueryToEnglish(search);
			this.totalCountNode.innerHTML = "";
		},

		postCreate: function(){
			if(!this.state){
				this.state = {}
			}

			this.inherited(arguments); // creates this.viewer

			this.overview = new AntibioticOverview({
				title: "Overview",
				id: this.viewer.id + "_" + "overview"
			});

			this.amr = new AMRPanelGridContainer({
				title: "AMR Phenotypes",
				id: this.viewer.id + "_" + "amr"
			});

			this.amrGenes = new SpecialtyGeneGridContainer({
				title: "AMR Genes",
				id: this.viewer.id + "_" + "amrGenes"
			});

			this.amrRegions = new FeatureGridContainer({
				title: "AMR Regions",
				id: this.viewer.id + "_" + "amrRegions",
				defaultFilter: ""
			});

			this.viewer.addChild(this.overview);
			this.viewer.addChild(this.amr);
			this.viewer.addChild(this.amrGenes);
			this.viewer.addChild(this.amrRegions);
		}
	})
});
<commit_msg>custom facets for Antibiotic page<commit_after>define([
	"dojo/_base/declare", "dojo/_base/lang",
	"./TabViewerBase",
	"../AntibioticOverview", "../AMRPanelGridContainer", "../FeatureGridContainer", "../SpecialtyGeneGridContainer",
	"../../util/QueryToEnglish"
], function(declare, lang,
			TabViewerBase,
			AntibioticOverview, AMRPanelGridContainer, FeatureGridContainer, SpecialtyGeneGridContainer,
			QueryToEnglish){

	return declare([TabViewerBase], {

		perspectiveLabel: "Antibiotic View",
		perspectiveIconClass: "icon-selection-Antibiotic",

		onSetState: function(attr, oldVal, state){

			if(!state){
				return;
			}

			if(!state.search){
				this.queryNode.innerHTML = "Error";
				this.totalCountNode.innerHTML = "";
			}

			// bypass setting attribute and invoke tabs with state
			this.buildHeaderContent(state.search);

			if(state.hashParams && state.hashParams.view_tab){
				if(this[state.hashParams.view_tab]){
					var vt = this[state.hashParams.view_tab];

					vt.set("visible", true);
					this.viewer.selectChild(vt);
				}else{
					// console.log("No view-tab supplied in State Object");
				}
			}

			this.setActivePanelState();
		},

		setActivePanelState: function(){
			var activeQueryState;

			var active = (this.state && this.state.hashParams && this.state.hashParams.view_tab) ? this.state.hashParams.view_tab : "overview";
			var activeTab = this[active];
			var antibioticName = this.state.search.split(",")[1].split(")")[0];

			switch(active){
				case "overview":
					activeTab.set("state", lang.mixin({}, this.state));
					break;
				case "amr":
					activeTab.set("state", lang.mixin({}, this.state, {
						search: "eq(antibiotic," + antibioticName + ")"
					}));
					break;
				case "amrGenes":
					activeTab.set("state", lang.mixin({}, this.state, {
						search: "keyword(" + antibioticName + ")&eq(property,%22Antibiotic%20Resistance%22)"
					}));
					break;
				case "amrRegions":
					activeTab.set("state", lang.mixin({}, this.state, {
						search: "keyword(" + antibioticName + ")&eq(feature_type,classifier_predicted_region)"
					}));
					break;
				default:
					if(activeQueryState){
						activeTab.set("state", activeQueryState);
					}else{
						console.error("Missing Active Query State for: ", active);
					}
					break;
			}
		},

		buildHeaderContent: function(search){

			this.queryNode.innerHTML = QueryToEnglish(search);
			this.totalCountNode.innerHTML = "";
		},

		postCreate: function(){
			if(!this.state){
				this.state = {}
			}

			this.inherited(arguments); // creates this.viewer

			this.overview = new AntibioticOverview({
				title: "Overview",
				id: this.viewer.id + "_" + "overview"
			});

			this.amr = new AMRPanelGridContainer({
				title: "AMR Phenotypes",
				id: this.viewer.id + "_" + "amr"
			});

			this.amrGenes = new SpecialtyGeneGridContainer({
				title: "AMR Genes",
				facetFields: ["property", "source", "evidence", "classification"],
				id: this.viewer.id + "_" + "amrGenes"
			});

			this.amrRegions = new FeatureGridContainer({
				title: "AMR Regions",
				id: this.viewer.id + "_" + "amrRegions",
				defaultFilter: ""
			});

			this.viewer.addChild(this.overview);
			this.viewer.addChild(this.amr);
			this.viewer.addChild(this.amrGenes);
			this.viewer.addChild(this.amrRegions);
		}
	})
});
<|endoftext|>


<commit_before><commit_msg>created basic module<commit_after>M.wrap('github/jillix/editor/v0.0.1/editor.js', function (require, module, exports) {

var Bind = require('github/jillix/bind/v0.0.1/bind');

function init () {
    var self = this;
    config = self.mono.config.data;

    // init bind
    Bind(self).load(config.bind, function (err, bind) {

        if (err) {
            // TODO do something on error
            return;
        }

        // save bind instance
        self.bind = bind;

        // set an empty state is the same like: state.set(location.pathname);
        bind.view.render();
        self.emit('ready');
    });
}

module.exports = init;

return module;

});
<|endoftext|>


<commit_before>var UserManager = {
    currentUser: null,
    viewingUser: null,
    tabs: null,
    $rightView: null,
    $playlists: null,
    $followings: null,
    $followers: null,
    $playlistsTab: null,
    $followingsTab: null,
    $followersTab: null,
    $followButton: null,
    $unFollowButton: null,
    $editButton: null,
    $img: null,
    $changePictureBox: null,

    init: function(userJSON) {
        if (userJSON) {
            UserManager.currentUser = new User(userJSON);
            EventSystem.addEventListener('user_profile_updated', function(params) {
                UserManager.currentUser.displayName = params.displayName;
                UserManager.currentUser.nickname = params.nickname;
                UserManager.currentUser.firstName = params.first_name;
                UserManager.currentUser.lastName = params.last_name;
                UserManager.currentUser.tagline = params.tagline;
                UserManager.loadCurrentUser();
                history.pushState(null, null, UserManager.currentUser.getUrl());
            });

            EventSystem.addEventListener('flattr_click_made', function(data) {
                UserManager.currentUser.nrOfFlattrs += 1;
            });
        }

        UserManager.$rightView = $('#right .profile');
        UserManager.$playlists = $('#right .profile .pane.profile-playlists');
        UserManager.$followings = $('#right .profile .pane.profile-followings');
        UserManager.$followers = $('#right .profile .pane.profile-followers');
        UserManager.$playlistsTab = $('#right .profile .tabs .profile-playlists');
        UserManager.$followingsTab = $('#right .profile .tabs .profile-followings');
        UserManager.$followersTab = $('#right .profile .tabs .profile-followers');
        UserManager.$followButton = $('#right .profile .follow.button');
        UserManager.$unFollowButton = $('#right .profile .unfollow.button');
        UserManager.$editButton = $('#right .profile .edit.button');
        UserManager.$img = $('#right .profile .picture-container .picture');
        UserManager.$changePictureBox = $('#right .profile .picture-container .change');

        UserManager.tabs = new Tabs(UserManager.$rightView.find('.tab-area'), {
            'profile-followers': UserManager.loadFollowers,
            'profile-followings': UserManager.loadFollowings
        });
    },

    isLoggedIn: function() {
        return UserManager.currentUser !== null;
    },

    show: function() {
        Menu.deSelect();
        UserManager.tabs.select('profile-playlists');
        history.pushState(null, null, UserManager.viewingUser.getUrl());

        $('#right > div').hide();
        UserManager.$rightView.show();
    },

    loadCurrentUser: function() {
        UserManager.resetUserProfileView();
        UserManager.populateUserProfile(UserManager.currentUser);
        UserManager.show();
    },

    loadProfile: function(nickOrId) {
        UserManager.resetUserProfileView();

        LoadingBar.show();

        $.ajax({
            type: 'GET',
            url: '/api/users/' + nickOrId,
            complete: function(jqXHR, textStatus) {
                LoadingBar.hide();
            },
            statusCode: {
                200: function(data) {
                    $('#right .profile').show();
                    UserManager.populateUserProfile(new User(data));
                },
                404: function(data, textStatus) {
                    alert('User "' + nickOrId + '" not found');
                }
            }
        });
    },

    resetUserProfileView: function() {
        UserManager.$followButton.hide();
        UserManager.$unFollowButton.hide();
        UserManager.$editButton.hide();
        UserManager.$changePictureBox.text('');
        UserManager.$changePictureBox.hide();
        UserManager.$playlists.html('');
        UserManager.$followings.html('');
        UserManager.$followers.html('');

        if (UserManager.$img) {
            UserManager.$img.remove();
        }

        $('#right .profile .information-container .flattr').hide();
        $('#right .profile .information-container .flattr .username').text('');
        $('#right .profile .information-container .flattr .count').text('');
        $('#right .profile .information-container .display-name').text('');
        $('#right .profile .information-container .nickname').text('');
        $('#right .profile .information-container .tagline').text('');

        UserManager.tabs.select('profile-playlists');

        $('#right .profile .tabs').hide();
    },

    populateUserProfile: function(user) {
        UserManager.viewingUser = user;

        var largeImageUrl = user.largeImageUrl;

        UserManager.$img = $('')
            .attr('src', largeImageUrl)
            .prependTo($('#right .profile .picture-container'));

        UserManager.$followButton.unbind('click').click(function() {
            $.post('/me/followings/' + user.id, function(data) {
                UserManager.$followButton.hide();
                UserManager.$unFollowButton.show();

                UserManager.currentUser.nrOfFollowings += 1;
                user.nrOfFollowers += 1;

                Utils.addFollowing(user);

                UserManager.loadFollowers();
            });
        });

        UserManager.$unFollowButton.unbind('click').click(function() {
            $.ajax({
                type: 'DELETE',
                url: '/me/followings/' + user.id,
                statusCode: {
                    200: function(data) {
                        UserManager.$followButton.show();
                        UserManager.$unFollowButton.hide();

                        UserManager.currentUser.nrOfFollowings -= 1;
                        user.nrOfFollowers -= 1;

                        Utils.removeFollowing(user.id);

                        UserManager.loadFollowers();
                    }
                }
            });
        });

        UserManager.$editButton.unbind('click').click(function() {
            new EditProfileDialog().show();
        });

        if (UserManager.isLoggedIn() && UserManager.currentUser.id === user.id) {
            user.playlists = playlistManager.playlists;
            UserManager.$editButton.show();
            UserManager.$changePictureBox.html(TranslationSystem.get('Configure your profile picture for $email at $gravatar', {$email: UserManager.currentUser.email, $gravatar: 'gravatar.com'}));
            UserManager.$changePictureBox.show();
        } else if (UserManager.isLoggedIn() && Utils.isFollowingUser(user.id)) {
            UserManager.$unFollowButton.show();
        } else if (UserManager.isLoggedIn()) {
            UserManager.$followButton.show();
        }

        if (user.flattrUserName) {
            $('#right .profile .information-container .flattr .username')
                .text(user.flattrUserName)
                .attr('href', 'http://flattr.com/profile/' + user.flattrUserName);
            $('#right .profile .information-container .flattr .count').html(TranslationSystem.get('$count donations made', {$count: '' + user.nrOfFlattrs + ''}));
            $('#right .profile .information-container .flattr').show();
        }

        $('#right .profile .information-container .display-name').text(user.displayName);
        $('#right .profile .information-container .nickname').text(user.nickname || '');
        $('#right .profile .information-container .tagline').text(user.tagline || '');

        UserManager.updatePlaylistsTabLabel(user.nrOfPlaylists);
        UserManager.updateFollowersTabLabel(user.nrOfFollowers);
        UserManager.updateFollowingsTabLabel(user.nrOfFollowings);

        if (UserManager.isLoggedIn() && UserManager.currentUser.id === user.id) {
            $.each(playlistManager.playlists, function(index, item) {
                var playlist = new Playlist(item.title, item.videos, item.remoteId, item.owner, item.isPrivate, item.followers);
                if (playlist.videos.length) {
                    UserManager.$playlists.append(PlaylistView.createSmallPlaylistView(playlist, true));
                }
            });
        } else {
            UserManager.loadPlaylists();
        }

        $('#right .profile .tabs').show();
    },

    updateFollowersTabLabel: function(nrOfFollowers) {
        UserManager.$followersTab.text(TranslationSystem.get('Followers') + ' (' + nrOfFollowers + ')');
    },

    updateFollowingsTabLabel: function(nrOfFollowings) {
        UserManager.$followingsTab.text(TranslationSystem.get('Following') + ' (' + nrOfFollowings + ')');
    },

    updatePlaylistsTabLabel: function(nrOfPlaylists) {
        UserManager.$playlistsTab.text(TranslationSystem.get('Playlists') + ' (' + nrOfPlaylists + ')');
    },

    loadPlaylists: function() {
        LoadingBar.show();
        $.getJSON('/api/users/' + UserManager.viewingUser.id + '/playlists', function(data) {
            $.each(data, function(index, item) {
                var playlist = new Playlist(item.title, item.videos, item.remoteId, item.owner, item.isPrivate, item.followers);
                if (playlist.videos.length) {
                    UserManager.$playlists.append(PlaylistView.createSmallPlaylistView(playlist));
                }
            });
            LoadingBar.hide();
        });
    },

    loadFollowers: function() {
        $.getJSON('/api/users/' + UserManager.viewingUser.id + '/followers', function(data) {
            UserManager.$followers.html('');
            UserManager.updateFollowersTabLabel(data.length);
            $.each(data, function(i, item) {
                UserManager.$followers.append(new User(item).getSmallView());
            });
        });
    },

    loadFollowings: function() {
        $.getJSON('/api/users/' + UserManager.viewingUser.id + '/followings', function(data) {
            UserManager.$followings.html('');
            UserManager.updateFollowingsTabLabel(data.length);
            $.each(data, function(i, item) {
                UserManager.$followings.append(new User(item).getSmallView());
            });
        });
    },

    findUser: function(nickOrId, callback) {
        $.getJSON('/api/users/' + nickOrId, function(data) {
             callback(data);
        });
    }
};
<commit_msg>Fixed bug with null user in UserManager<commit_after>var UserManager = {
    currentUser: null,
    viewingUser: null,
    tabs: null,
    $rightView: null,
    $playlists: null,
    $followings: null,
    $followers: null,
    $playlistsTab: null,
    $followingsTab: null,
    $followersTab: null,
    $followButton: null,
    $unFollowButton: null,
    $editButton: null,
    $img: null,
    $changePictureBox: null,

    init: function(userJSON) {
        if (userJSON) {
            UserManager.currentUser = new User(userJSON);
            EventSystem.addEventListener('user_profile_updated', function(params) {
                UserManager.currentUser.displayName = params.displayName;
                UserManager.currentUser.nickname = params.nickname;
                UserManager.currentUser.firstName = params.first_name;
                UserManager.currentUser.lastName = params.last_name;
                UserManager.currentUser.tagline = params.tagline;
                UserManager.loadCurrentUser();
                history.pushState(null, null, UserManager.currentUser.getUrl());
            });

            EventSystem.addEventListener('flattr_click_made', function(data) {
                UserManager.currentUser.nrOfFlattrs += 1;
            });
        }

        UserManager.$rightView = $('#right .profile');
        UserManager.$playlists = $('#right .profile .pane.profile-playlists');
        UserManager.$followings = $('#right .profile .pane.profile-followings');
        UserManager.$followers = $('#right .profile .pane.profile-followers');
        UserManager.$playlistsTab = $('#right .profile .tabs .profile-playlists');
        UserManager.$followingsTab = $('#right .profile .tabs .profile-followings');
        UserManager.$followersTab = $('#right .profile .tabs .profile-followers');
        UserManager.$followButton = $('#right .profile .follow.button');
        UserManager.$unFollowButton = $('#right .profile .unfollow.button');
        UserManager.$editButton = $('#right .profile .edit.button');
        UserManager.$img = $('#right .profile .picture-container .picture');
        UserManager.$changePictureBox = $('#right .profile .picture-container .change');

        UserManager.tabs = new Tabs(UserManager.$rightView.find('.tab-area'), {
            'profile-followers': UserManager.loadFollowers,
            'profile-followings': UserManager.loadFollowings
        });
    },

    isLoggedIn: function() {
        return UserManager.currentUser !== null;
    },

    show: function() {
        Menu.deSelect();
        UserManager.tabs.select('profile-playlists');
        if (UserManager.viewingUser) {
            history.pushState(null, null, UserManager.viewingUser.getUrl());
        } else {
            history.pushState(null, null, '/');
        }
        $('#right > div').hide();
        UserManager.$rightView.show();
    },

    loadCurrentUser: function() {
        UserManager.resetUserProfileView();
        UserManager.populateUserProfile(UserManager.currentUser);
        UserManager.show();
    },

    loadProfile: function(nickOrId) {
        UserManager.resetUserProfileView();

        LoadingBar.show();

        $.ajax({
            type: 'GET',
            url: '/api/users/' + nickOrId,
            complete: function(jqXHR, textStatus) {
                LoadingBar.hide();
            },
            statusCode: {
                200: function(data) {
                    $('#right .profile').show();
                    UserManager.populateUserProfile(new User(data));
                },
                404: function(data, textStatus) {
                    alert('User "' + nickOrId + '" not found');
                }
            }
        });
    },

    resetUserProfileView: function() {
        UserManager.$followButton.hide();
        UserManager.$unFollowButton.hide();
        UserManager.$editButton.hide();
        UserManager.$changePictureBox.text('');
        UserManager.$changePictureBox.hide();
        UserManager.$playlists.html('');
        UserManager.$followings.html('');
        UserManager.$followers.html('');

        if (UserManager.$img) {
            UserManager.$img.remove();
        }

        $('#right .profile .information-container .flattr').hide();
        $('#right .profile .information-container .flattr .username').text('');
        $('#right .profile .information-container .flattr .count').text('');
        $('#right .profile .information-container .display-name').text('');
        $('#right .profile .information-container .nickname').text('');
        $('#right .profile .information-container .tagline').text('');

        UserManager.tabs.select('profile-playlists');

        $('#right .profile .tabs').hide();
    },

    populateUserProfile: function(user) {
        UserManager.viewingUser = user;

        var largeImageUrl = user.largeImageUrl;

        UserManager.$img = $('')
            .attr('src', largeImageUrl)
            .prependTo($('#right .profile .picture-container'));

        UserManager.$followButton.unbind('click').click(function() {
            $.post('/me/followings/' + user.id, function(data) {
                UserManager.$followButton.hide();
                UserManager.$unFollowButton.show();

                UserManager.currentUser.nrOfFollowings += 1;
                user.nrOfFollowers += 1;

                Utils.addFollowing(user);

                UserManager.loadFollowers();
            });
        });

        UserManager.$unFollowButton.unbind('click').click(function() {
            $.ajax({
                type: 'DELETE',
                url: '/me/followings/' + user.id,
                statusCode: {
                    200: function(data) {
                        UserManager.$followButton.show();
                        UserManager.$unFollowButton.hide();

                        UserManager.currentUser.nrOfFollowings -= 1;
                        user.nrOfFollowers -= 1;

                        Utils.removeFollowing(user.id);

                        UserManager.loadFollowers();
                    }
                }
            });
        });

        UserManager.$editButton.unbind('click').click(function() {
            new EditProfileDialog().show();
        });

        if (UserManager.isLoggedIn() && UserManager.currentUser.id === user.id) {
            user.playlists = playlistManager.playlists;
            UserManager.$editButton.show();
            UserManager.$changePictureBox.html(TranslationSystem.get('Configure your profile picture for $email at $gravatar', {$email: UserManager.currentUser.email, $gravatar: 'gravatar.com'}));
            UserManager.$changePictureBox.show();
        } else if (UserManager.isLoggedIn() && Utils.isFollowingUser(user.id)) {
            UserManager.$unFollowButton.show();
        } else if (UserManager.isLoggedIn()) {
            UserManager.$followButton.show();
        }

        if (user.flattrUserName) {
            $('#right .profile .information-container .flattr .username')
                .text(user.flattrUserName)
                .attr('href', 'http://flattr.com/profile/' + user.flattrUserName);
            $('#right .profile .information-container .flattr .count').html(TranslationSystem.get('$count donations made', {$count: '' + user.nrOfFlattrs + ''}));
            $('#right .profile .information-container .flattr').show();
        }

        $('#right .profile .information-container .display-name').text(user.displayName);
        $('#right .profile .information-container .nickname').text(user.nickname || '');
        $('#right .profile .information-container .tagline').text(user.tagline || '');

        UserManager.updatePlaylistsTabLabel(user.nrOfPlaylists);
        UserManager.updateFollowersTabLabel(user.nrOfFollowers);
        UserManager.updateFollowingsTabLabel(user.nrOfFollowings);

        if (UserManager.isLoggedIn() && UserManager.currentUser.id === user.id) {
            $.each(playlistManager.playlists, function(index, item) {
                var playlist = new Playlist(item.title, item.videos, item.remoteId, item.owner, item.isPrivate, item.followers);
                if (playlist.videos.length) {
                    UserManager.$playlists.append(PlaylistView.createSmallPlaylistView(playlist, true));
                }
            });
        } else {
            UserManager.loadPlaylists();
        }

        $('#right .profile .tabs').show();
    },

    updateFollowersTabLabel: function(nrOfFollowers) {
        UserManager.$followersTab.text(TranslationSystem.get('Followers') + ' (' + nrOfFollowers + ')');
    },

    updateFollowingsTabLabel: function(nrOfFollowings) {
        UserManager.$followingsTab.text(TranslationSystem.get('Following') + ' (' + nrOfFollowings + ')');
    },

    updatePlaylistsTabLabel: function(nrOfPlaylists) {
        UserManager.$playlistsTab.text(TranslationSystem.get('Playlists') + ' (' + nrOfPlaylists + ')');
    },

    loadPlaylists: function() {
        LoadingBar.show();
        $.getJSON('/api/users/' + UserManager.viewingUser.id + '/playlists', function(data) {
            $.each(data, function(index, item) {
                var playlist = new Playlist(item.title, item.videos, item.remoteId, item.owner, item.isPrivate, item.followers);
                if (playlist.videos.length) {
                    UserManager.$playlists.append(PlaylistView.createSmallPlaylistView(playlist));
                }
            });
            LoadingBar.hide();
        });
    },

    loadFollowers: function() {
        $.getJSON('/api/users/' + UserManager.viewingUser.id + '/followers', function(data) {
            UserManager.$followers.html('');
            UserManager.updateFollowersTabLabel(data.length);
            $.each(data, function(i, item) {
                UserManager.$followers.append(new User(item).getSmallView());
            });
        });
    },

    loadFollowings: function() {
        $.getJSON('/api/users/' + UserManager.viewingUser.id + '/followings', function(data) {
            UserManager.$followings.html('');
            UserManager.updateFollowingsTabLabel(data.length);
            $.each(data, function(i, item) {
                UserManager.$followings.append(new User(item).getSmallView());
            });
        });
    },

    findUser: function(nickOrId, callback) {
        $.getJSON('/api/users/' + nickOrId, function(data) {
             callback(data);
        });
    }
};
<|endoftext|>


<commit_before>import Ember from 'ember';
import jobMixin from 'ember-data-offline/mixins/job';

export default Ember.Object.extend(jobMixin, {
  task() {
    return this[this.get('method')].apply(this.get('adapter'), this.get('params'));
  },

  findAll(store, typeClass, sinceToken, adapterResp){
    let offlineAdapter = this.get('offlineAdapter');
    adapterResp.then(records => {
      if (!Ember.isEmpty(records)) {
        offlineAdapter.persistData(typeClass, records);
      }
    });
  },

  find(store, typeClass, id, snapshot, onlineResp){
    let adapter = this;
    let offlineAdapter = adapter.get('offlineAdapter');
    //check offline storage
    Ember.RSVP.resolve().then(() => {
      return offlineAdapter.find(store, typeClass, id, snapshot);
    }).then(offineRecord => {
      if (Ember.isEmpty(offineRecord)) {
        return onlineResp;
      }
    }).then(onlineRecord => {
      if (!Ember.isEmpty(onlineRecord)) {
        offlineAdapter.persistData(typeClass, onlineRecord);
      }
    }).catch(() => {
        onlineResp.then(onlineRecord => {
          if (!Ember.isEmpty(onlineRecord)) {
            offlineAdapter.persistData(typeClass, onlineRecord);
          }
        });
    });
  }

});
<commit_msg>pretify import<commit_after>import Ember from 'ember';
import jobMixin from 'ember-data-offline/mixins/job';

const { isEmpty, RSVP } = Ember;

export default Ember.Object.extend(jobMixin, {
  task() {
    return this[this.get('method')].apply(this.get('adapter'), this.get('params'));
  },

  findAll(store, typeClass, sinceToken, adapterResp){
    let offlineAdapter = this.get('offlineAdapter');
    adapterResp.then(records => {
      if (!isEmpty(records)) {
        offlineAdapter.persistData(typeClass, records);
      }
    });
  },

  find(store, typeClass, id, snapshot, onlineResp){
    let adapter = this;
    let offlineAdapter = adapter.get('offlineAdapter');

    RSVP.resolve().then(() => {
      return offlineAdapter.find(store, typeClass, id, snapshot);
    }).then(offineRecord => {
      if (isEmpty(offineRecord)) {
        return onlineResp;
      }
    }).then(onlineRecord => {
      if (!isEmpty(onlineRecord)) {
        offlineAdapter.persistData(typeClass, onlineRecord);
      }
    }).catch(() => {
        onlineResp.then(onlineRecord => {
          if (!isEmpty(onlineRecord)) {
            offlineAdapter.persistData(typeClass, onlineRecord);
          }
        });
    });
  }
});
<|endoftext|>


<commit_before>/*jslint unparam: true */
/*global window, $ */
$(function() {
    'use strict';

    var jbody = $(document.body),
        progressBar = $('#progress'),
        fileOk = $('#file-ok').remove().show(),
        fileExists = $('#file-exists').remove().show(),
        listFile = $('#list-file').remove().show(),
        itemsOnPage = 10,
        filesData = {};

    var dragTimer = 0;
    // http://stackoverflow.com/questions/6848043/how-do-i-detect-a-file-is-being-dragged-rather-than-a-draggable-element-on-my-pa
    $(document).on('dragover', function(e) {
        var dt = e.originalEvent.dataTransfer;
        if (dt.types != null && (dt.types.indexOf ? dt.types.indexOf('Files') != -1 : dt.types.contains('application/x-moz-file'))) {

            jbody.addClass('dragover');

            if (dragTimer) {
                window.clearTimeout(dragTimer);
                dragTimer = 0;
            }
        }
    }).on('dragleave drop', function(e) {
        if (!dragTimer) {
            dragTimer = window.setTimeout(function() {
                jbody.removeClass('dragover');
                dragTimer = 0;
            }, 25);
        }
    });

    var endTimer = 0;

    // Change this to the location of your server-side upload handler:
    $('#fileupload').fileupload({
        url: '/upload',
        dataType: 'json',
        autoUpload: true,
        done: function(e, data) {
            if (data.result.status === 'exists') {
                fileExists.clone().children('strong').text(data.result.name).parent().appendTo('#files');
            } else {
                fileOk.clone().children('strong').text(data.result.name).parent().appendTo('#files');
            }

            if (!endTimer) {
                endTimer = window.setTimeout(function() {
                    refreshFiles();
                    endTimer = 0;
                }, 250);
            }
        },
        progressall: function(e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            $('#progress .progress-bar').css(
                'width',
                progress + '%'
            );
        },
        start: function() {
            progressBar.removeClass('nothing-to-show');
        },
        stop: function() {
            progressBar.addClass('nothing-to-show');
        }
    })
        .prop('disabled', !$.support.fileInput)
        .parent().addClass($.support.fileInput ? undefined : 'disabled');

    function bytesToSize(bytes) {
        var sizes = ['bytes', 'Kb', 'Mb', 'Gb', 'Tb'];
        if (bytes == 0) return '0 Bytes';
        var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
        return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
    };

    $('#pagination').pagination({
        itemsOnPage: itemsOnPage,
        cssStyle: 'pagination',
        prevText: '«',
        nextText: '»',
        onPageClick: function(pageNumber) {
            showFiles(pageNumber);
        }
    });

    function refreshFiles() {
        $.getJSON('/files', function(data) {
            filesData = {};
            filesData = data;

            $('#pagination').pagination('updateItems', data.length);

            showFiles(1);
        });
    }

    function showFiles(pageNumber) {
        var files = $('.file');
        if (files.length) {
            files.each(function(index, element) {
                element.remove();
            })
        }

        var jlist = $("#list");

        filesData.slice(((pageNumber - 1) * itemsOnPage), (pageNumber * itemsOnPage)).reverse()
            .forEach(function(file) {
                var path = '/' + file.hash + '.' + file.extension;

                if (document.getElementById(path)) {
                    return;
                }

                var j = listFile.clone();
                j.find('.name').text(file.name);

                var date = new Date(file.mtime);

                var details = date.toLocaleString() + "
" + bytesToSize(file.size);

                j.attr('id', path);
                j.children('a').attr('href', path);

                if (/^image\//.test(file.type)) {
                    j.find('.icon').empty().append($('').attr('src', '/thumbnail' + path))
                    details += "
x480 - x720 - x1080";
                }

                var button = $('
<button type="button" class="btn btn-xs btn-link">Remove</button>');
                button.click(function() {
                    if (confirm("Do you really want to remove \"" + file.name + "\"? It's a good file.")) {
                        $.getJSON('/remove' + path, function(data) {
                            j.remove();
                        });
                    }
                });

                j.find('.details small').html(details)
                    .append(button);

                jlist.prepend(j);
            });

    }

    refreshFiles();

    var fetchUrlInput = $('#fetchUrlInput');
    $('#fetchForm').submit(function(e) {
        e.preventDefault();

        var url = fetchUrlInput.val();

        if (!/^https?:\/\//.test(url)) {
            url = 'http://' + url;
        }

        $.get('/fetch/' + url, function(data) {
            fetchUrlInput.val('').focus();
            refreshFiles();
        });
    });

});
<commit_msg>Detect the page anchor and render the right page accordingly when navigating back from opening a file.<commit_after>/*jslint unparam: true */
/*global window, $ */
$(function() {
    'use strict';

    var jbody = $(document.body),
        progressBar = $('#progress'),
        fileOk = $('#file-ok').remove().show(),
        fileExists = $('#file-exists').remove().show(),
        listFile = $('#list-file').remove().show(),
        itemsOnPage = 10,
        filesData = {};

    var dragTimer = 0;
    // http://stackoverflow.com/questions/6848043/how-do-i-detect-a-file-is-being-dragged-rather-than-a-draggable-element-on-my-pa
    $(document).on('dragover', function(e) {
        var dt = e.originalEvent.dataTransfer;
        if (dt.types != null && (dt.types.indexOf ? dt.types.indexOf('Files') != -1 : dt.types.contains('application/x-moz-file'))) {

            jbody.addClass('dragover');

            if (dragTimer) {
                window.clearTimeout(dragTimer);
                dragTimer = 0;
            }
        }
    }).on('dragleave drop', function(e) {
        if (!dragTimer) {
            dragTimer = window.setTimeout(function() {
                jbody.removeClass('dragover');
                dragTimer = 0;
            }, 25);
        }
    });

    var endTimer = 0;

    // Change this to the location of your server-side upload handler:
    $('#fileupload').fileupload({
        url: '/upload',
        dataType: 'json',
        autoUpload: true,
        done: function(e, data) {
            if (data.result.status === 'exists') {
                fileExists.clone().children('strong').text(data.result.name).parent().appendTo('#files');
            } else {
                fileOk.clone().children('strong').text(data.result.name).parent().appendTo('#files');
            }

            if (!endTimer) {
                endTimer = window.setTimeout(function() {
                    refreshFiles();
                    endTimer = 0;
                }, 250);
            }
        },
        progressall: function(e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            $('#progress .progress-bar').css(
                'width',
                progress + '%'
            );
        },
        start: function() {
            progressBar.removeClass('nothing-to-show');
        },
        stop: function() {
            progressBar.addClass('nothing-to-show');
        }
    })
        .prop('disabled', !$.support.fileInput)
        .parent().addClass($.support.fileInput ? undefined : 'disabled');

    function bytesToSize(bytes) {
        var sizes = ['bytes', 'Kb', 'Mb', 'Gb', 'Tb'];
        if (bytes == 0) return '0 Bytes';
        var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
        return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
    };

    $('#pagination').pagination({
        itemsOnPage: itemsOnPage,
        cssStyle: 'pagination',
        prevText: '«',
        nextText: '»',
        onPageClick: function(pageNumber) {
            showFiles(pageNumber);
        }
    });

    function refreshFiles(pageNumber) {
        pageNumber = typeof pageNumber !== 'undefined' ? pageNumber : 1;

        $('#pagination').pagination('drawPage', pageNumber);

        $.getJSON('/files', function(data) {
            filesData = {};
            filesData = data;

            $('#pagination').pagination('updateItems', data.length);

            showFiles(pageNumber);
        });
    }

    function showFiles(pageNumber) {
        var files = $('.file');
        if (files.length) {
            files.each(function(index, element) {
                element.remove();
            })
        }

        var jlist = $("#list");

        filesData.slice(((pageNumber - 1) * itemsOnPage), (pageNumber * itemsOnPage)).reverse()
            .forEach(function(file) {
                var path = '/' + file.hash + '.' + file.extension;

                if (document.getElementById(path)) {
                    return;
                }

                var j = listFile.clone();
                j.find('.name').text(file.name);

                var date = new Date(file.mtime);

                var details = date.toLocaleString() + "
" + bytesToSize(file.size);

                j.attr('id', path);
                j.children('a').attr('href', path);

                if (/^image\//.test(file.type)) {
                    j.find('.icon').empty().append($('').attr('src', '/thumbnail' + path))
                    details += "
x480 - x720 - x1080";
                }

                var button = $('
<button type="button" class="btn btn-xs btn-link">Remove</button>');
                button.click(function() {
                    if (confirm("Do you really want to remove \"" + file.name + "\"? It's a good file.")) {
                        $.getJSON('/remove' + path, function(data) {
                            j.remove();
                        });
                    }
                });

                j.find('.details small').html(details)
                    .append(button);

                jlist.prepend(j);
            });

    }

    refreshFiles(window.location.hash.split('-')[1]);

    var fetchUrlInput = $('#fetchUrlInput');
    $('#fetchForm').submit(function(e) {
        e.preventDefault();

        var url = fetchUrlInput.val();

        if (!/^https?:\/\//.test(url)) {
            url = 'http://' + url;
        }

        $.get('/fetch/' + url, function(data) {
            fetchUrlInput.val('').focus();
            refreshFiles();
        });
    });

});
<|endoftext|>


<commit_before>/*
  Navigation
*/
console.log('--> navigation.js');

(function() {

  var $hamburger = $('#mobile-menu');
  var $mobileNav = $('nav.nav-plus');

  // Document Ready
  $(document).ready(function() {

    // Trigger a resize for the footer position function
    $(window).trigger('resize');

  });

  //  Touch Feedback (material design style)
  //  http://codepen.io/440design/pen/iEztk
  //
  $(function () {
      var ink, d, x, y;
      $("nav.nav-plus a").click(function (e) {
              if ($(this).find(".feedback-ink").length === 0) {
                  $(this).prepend("");
              }

              ink = $(this).find(".feedback-ink");
              ink.removeClass("animate");

              if (!ink.height() && !ink.width()) {
                  d = Math.max($(this).outerWidth(), $(this).outerHeight());
                  ink.css({ height: d, width: d });
              }

              x = e.pageX - $(this).offset().left - ink.width() / 2;
              y = e.pageY - $(this).offset().top - ink.height() / 2;

              ink.css({ top: y + 'px', left: x + 'px' }).addClass("animate");
      });
  });

  // Hamburger to X
  //
  function doTheHammy(option) {

      // Elements
      var $trigger = $hamburger;
      var $first = $trigger.find('.hammy-special .fir');
      var $second = $trigger.find('.hammy-special .sec');
      var $third = $trigger.find('.hammy-special .thi');

      if (option === "open") {
          TweenLite.to($first, .35, { rotation: "-360px", autoAlpha: 0, ease: Power1.easeInOut });
          TweenLite.to($second, .35, { y: 7, rotation: "-230px", ease: Power1.easeInOut });
          TweenLite.to($third, .35, { y: "-7px", rotation: 50, ease: Power1.easeInOut });
          $trigger.addClass('on');
      }
      if(option === "close") {
          TweenLite.to($first, .35, { rotation: 0, autoAlpha: 1, ease: Power1.easeInOut });
          TweenLite.to($second, .35, { y: 0, rotation: 0, ease: Power1.easeInOut });
          TweenLite.to($third, .35, { y: 0, rotation: 0, ease: Power1.easeInOut });
          $trigger.removeClass('on');
      }

  }

  // Open & Close Mobile Nav Functions
  //
  function closeNav() {

    doTheHammy('close');
    TweenLite.to($mobileNav, .3, { width: 0, ease: Power1.easeOut })
    $hamburger.removeClass('active');

  }

  function openNav() {

    doTheHammy('open');
    TweenLite.to($mobileNav, .3, { width: 305, ease: Power1.easeOut })
    $hamburger.addClass('active');

  }

  // Hamburger Click Event
  //
  $hamburger.on('click', function(e) {
    e.preventDefault();

    // Default Action
    if(! $hamburger.hasClass('active')) {
      openNav();
    } else {
      closeNav();
    }

    // Close on Document Click
    $(document).on('click touchstart', function(event) {
      if(!$(event.target).closest($hamburger).length && !$(event.target).closest($mobileNav).length && $hamburger.hasClass('active')) {
          closeNav();
          return false;
      }
    });

    // Close with Escape key
    $(document).keyup(function(e) {
      if (e.which === 27 && $hamburger.hasClass('active')) {
        closeNav();
      }
    });

  });

  // Footer Positioning
  $(window).resize(function() {

    var h = window.innerHeight,
        navH = $('nav.nav-plus .links').height(),
        footerH = $('.nav-footer').height();

        setTimeout(function() {
          if(navH + (footerH * 2) < h) {
            $('.nav-footer').css('position', 'absolute');
          } else {
            $('.nav-footer').css('position', 'relative');
          }
        },200);
  });

})();<commit_msg>git is hard<commit_after><|endoftext|>


<commit_before>var armyc2 = armyc2 || {};
/** namespace */
armyc2.c2sd = armyc2.c2sd || {};
armyc2.c2sd.renderer = armyc2.c2sd.renderer || {};
armyc2.c2sd.renderer.utilities = armyc2.c2sd.renderer.utilities || {};
/**
 *
 * @param {Number} R
 * @param {Number} G
 * @param {Number} B
 * @param {Number} A
 * @returns {armyc2.c2sd.renderer.utilities.Color}
 */
armyc2.c2sd.renderer.utilities.Color = function (R,G,B,A) {

    //private vars
    this.A = 255;
    this.R = 0;
    this.G = 0;
    this.B = 0;

    //constructor code
    this.R = R;
    this.G = G;
    this.B = B;
    if(A !== undefined)
        this.A = A;
};

    armyc2.c2sd.renderer.utilities.Color.prototype.convert = function(integer)
    {
        //Simpler
        //var str = integer.toString(16);
        //return str.length === 1 ? "0" + str : str;

        //Much Faster
        var hexAlphabet = "0123456789ABCDEF";
        return isNaN(integer) ? "00" : hexAlphabet.charAt((integer - integer % 16)/16) + hexAlphabet.charAt(integer % 16);
    };

    armyc2.c2sd.renderer.utilities.Color.prototype.getAlpha = function()
    {
        return this.A;
    };

    armyc2.c2sd.renderer.utilities.Color.prototype.getRed = function()
    {
        return this.R;
    };

    armyc2.c2sd.renderer.utilities.Color.prototype.getGreen = function()
    {
        return this.G;
    };

    armyc2.c2sd.renderer.utilities.Color.prototype.getBlue = function()
    {
        return this.B;
    };

    armyc2.c2sd.renderer.utilities.Color.prototype.toARGB = function()
    {
        return (this.A << 24) + ((this.R & 0xFF) << 16) + ((this.G & 0xFF) << 8) + (this.B & 0xFF);
    };
    /**
     * A hex string in the format of AARRGGBB
	 * @param {Boolean} withAlpha Optional, default is true. If set to false,
	 * will return a hex string without alpha values.
     */
    armyc2.c2sd.renderer.utilities.Color.prototype.toHexString = function(withAlpha)
    {
        if(withAlpha === false)
        {
            return "#" + this.convert(this.R) +
                            this.convert(this.G) +
                            this.convert(this.B);
        }
        else
        {
            return "#" + this.convert(this.A) +
                            this.convert(this.R) +
                            this.convert(this.G) +
                            this.convert(this.B);
        }
    };
    /**
     * A KML Formatted hex string is in the format of AABBGGRR
     */
    armyc2.c2sd.renderer.utilities.Color.prototype.toKMLHexString = function()
    {
        return "#" +
                this.convert(this.A) +
                this.convert(this.B) +
                this.convert(this.G) +
                this.convert(this.R);
    };

//static public vars/functions
//milstd.renderer.ClassName.MY_CONSTANT = "constant_value";
//milstd.renderer.ClassName.myStaticFunction = function(){};

/**
 * @param {Number} color int value of a color
 * @return {Number} 0 - 255, alpha value
 */
armyc2.c2sd.renderer.utilities.Color.getAlphaFromColor = function(color)
{
	var alpha = 255;
	if (color > 16777215) alpha = (color >>> 24);
	return alpha;
};

/**
 * @param {Number} color int value of a color
 * @return {Number} 0 - 255, Red value
 */
armyc2.c2sd.renderer.utilities.Color.getRedFromColor = function(color)
{
	var red = 255;
	red = (color >> 16) & 0xFF;
	return red;
};

/**
 * @param {Number} color int value of a color
 * @return {Number} 0 - 255, Green value
 */
armyc2.c2sd.renderer.utilities.Color.getGreenFromColor = function(color)
{
	var green = 255;
	green = (color >> 8) & 0xFF;
	return green;
};

/**
 * @param {Number} color int value of a color
 * @return {Number} 0 - 255, Blue value
 */
armyc2.c2sd.renderer.utilities.Color.getBlueFromColor = function(color)
{
	var blue = 255;
	if (color > 16777215)
		blue = color & 0x000000FF;
	else
		blue = color & 0x0000FF;
	return blue;
};

/**
*
* @param hexValue - String representing hex value
* (formatted "0xRRGGBB" i.e. "0xFFFFFF")
* OR
* formatted "0xAARRGGBB" i.e. "0x00FFFFFF" for a color with an alpha value
* I will also put up with "RRGGBB" and "AARRGGBB" without the starting "0x"
* @return
*/
armyc2.c2sd.renderer.utilities.Color.getColorFromHexString = function(hexValue)
{
    var hexOriginal = new String(hexValue);

    var hexAlphabet = "0123456789ABCDEF";

    if(hexValue.charAt(0)==='#')
        hexValue = hexValue.substring(1);
    if(hexValue.substring(0,2)===("0x") || hexValue.substring(0,2)===("0X"))
        hexValue = hexValue.substring(2);

    hexValue = hexValue.toUpperCase();

    var count = hexValue.length,
        value = null,
        k = 0,
        int1 = 0,
        int2 = 0;

    if(count === 8 || count === 6)
    {
        value = new Array();//int[(count / 2)];
        for(var i=0; i<count;i+=2)
        {
                int1 = hexAlphabet.indexOf(hexValue.charAt(i));
                int2 = hexAlphabet.indexOf(hexValue.charAt(i+1));
                value[k]=(int1 * 16) + int2;
                k++;
        }

        if(count === 8)
        {
                return new armyc2.c2sd.renderer.utilities.Color(value[1],value[2],value[3],value[0]);
        }
        else if(count === 6)
        {
                return new armyc2.c2sd.renderer.utilities.Color(value[0],value[1],value[2]);
        }
    }
    else
    {
            //ErrorLogger.LogMessage("SymbolUtilties", "getColorFromHexString", "Bad hex value: " + hexOriginal, Level.WARNING);
    }
    return null;
};

armyc2.c2sd.renderer.utilities.Color.rgbToHexString = function(r,g,b,a)
{
    var temp = armyc2.c2sd.renderer.utilities.Color(r,g,b,a);
    return temp.toHexString(true);
};

armyc2.c2sd.renderer.utilities.Color.white =  new armyc2.c2sd.renderer.utilities.Color (255, 255, 255);
armyc2.c2sd.renderer.utilities.Color.WHITE = armyc2.c2sd.renderer.utilities.Color.white;
armyc2.c2sd.renderer.utilities.Color.lightGray =  new armyc2.c2sd.renderer.utilities.Color (192, 192, 192);
armyc2.c2sd.renderer.utilities.Color.LIGHT_GRAY = armyc2.c2sd.renderer.utilities.Color.lightGray;
armyc2.c2sd.renderer.utilities.Color.gray =  new armyc2.c2sd.renderer.utilities.Color (128, 128, 128);
armyc2.c2sd.renderer.utilities.Color.GRAY = armyc2.c2sd.renderer.utilities.Color.gray;
armyc2.c2sd.renderer.utilities.Color.darkGray =  new armyc2.c2sd.renderer.utilities.Color (64, 64, 64);
armyc2.c2sd.renderer.utilities.Color.DARK_GRAY = armyc2.c2sd.renderer.utilities.Color.darkGray;
armyc2.c2sd.renderer.utilities.Color.black =  new armyc2.c2sd.renderer.utilities.Color (0, 0, 0);
armyc2.c2sd.renderer.utilities.Color.BLACK = armyc2.c2sd.renderer.utilities.Color.black;
armyc2.c2sd.renderer.utilities.Color.red =  new armyc2.c2sd.renderer.utilities.Color (255, 0, 0);
armyc2.c2sd.renderer.utilities.Color.RED = armyc2.c2sd.renderer.utilities.Color.red;
armyc2.c2sd.renderer.utilities.Color.pink =  new armyc2.c2sd.renderer.utilities.Color (255, 175, 175);
armyc2.c2sd.renderer.utilities.Color.PINK = armyc2.c2sd.renderer.utilities.Color.pink;
armyc2.c2sd.renderer.utilities.Color.orange =  new armyc2.c2sd.renderer.utilities.Color (255, 200, 0);
armyc2.c2sd.renderer.utilities.Color.ORANGE = armyc2.c2sd.renderer.utilities.Color.orange;
armyc2.c2sd.renderer.utilities.Color.yellow =  new armyc2.c2sd.renderer.utilities.Color (255, 255, 0);
armyc2.c2sd.renderer.utilities.Color.YELLOW = armyc2.c2sd.renderer.utilities.Color.yellow;
armyc2.c2sd.renderer.utilities.Color.green =  new armyc2.c2sd.renderer.utilities.Color (0, 255, 0);
armyc2.c2sd.renderer.utilities.Color.GREEN = armyc2.c2sd.renderer.utilities.Color.green;
armyc2.c2sd.renderer.utilities.Color.magenta =  new armyc2.c2sd.renderer.utilities.Color (255, 0, 255);
armyc2.c2sd.renderer.utilities.Color.MAGENTA = armyc2.c2sd.renderer.utilities.Color.magenta;
armyc2.c2sd.renderer.utilities.Color.cyan =  new armyc2.c2sd.renderer.utilities.Color (0, 255, 255);
armyc2.c2sd.renderer.utilities.Color.CYAN = armyc2.c2sd.renderer.utilities.Color.cyan;
armyc2.c2sd.renderer.utilities.Color.blue =  new armyc2.c2sd.renderer.utilities.Color (0, 0, 255);
armyc2.c2sd.renderer.utilities.Color.BLUE = armyc2.c2sd.renderer.utilities.Color.blue;

<commit_msg>fix for rgbToHexString<commit_after>var armyc2 = armyc2 || {};
/** namespace */
armyc2.c2sd = armyc2.c2sd || {};
armyc2.c2sd.renderer = armyc2.c2sd.renderer || {};
armyc2.c2sd.renderer.utilities = armyc2.c2sd.renderer.utilities || {};
/**
 *
 * @param {Number} R
 * @param {Number} G
 * @param {Number} B
 * @param {Number} A
 * @returns {armyc2.c2sd.renderer.utilities.Color}
 */
armyc2.c2sd.renderer.utilities.Color = function (R,G,B,A) {

    //private vars
    this.A = 255;
    this.R = 0;
    this.G = 0;
    this.B = 0;

    //constructor code
    this.R = R;
    this.G = G;
    this.B = B;
    if(A !== undefined)
        this.A = A;
};

    armyc2.c2sd.renderer.utilities.Color.prototype.convert = function(integer)
    {
        //Simpler
        //var str = integer.toString(16);
        //return str.length === 1 ? "0" + str : str;

        //Much Faster
        var hexAlphabet = "0123456789ABCDEF";
        return isNaN(integer) ? "00" : hexAlphabet.charAt((integer - integer % 16)/16) + hexAlphabet.charAt(integer % 16);
    };

    armyc2.c2sd.renderer.utilities.Color.prototype.getAlpha = function()
    {
        return this.A;
    };

    armyc2.c2sd.renderer.utilities.Color.prototype.getRed = function()
    {
        return this.R;
    };

    armyc2.c2sd.renderer.utilities.Color.prototype.getGreen = function()
    {
        return this.G;
    };

    armyc2.c2sd.renderer.utilities.Color.prototype.getBlue = function()
    {
        return this.B;
    };

    armyc2.c2sd.renderer.utilities.Color.prototype.toARGB = function()
    {
        return (this.A << 24) + ((this.R & 0xFF) << 16) + ((this.G & 0xFF) << 8) + (this.B & 0xFF);
    };
    /**
     * A hex string in the format of AARRGGBB
	 * @param {Boolean} withAlpha Optional, default is true. If set to false,
	 * will return a hex string without alpha values.
     */
    armyc2.c2sd.renderer.utilities.Color.prototype.toHexString = function(withAlpha)
    {
        if(withAlpha === false)
        {
            return "#" + this.convert(this.R) +
                            this.convert(this.G) +
                            this.convert(this.B);
        }
        else
        {
            return "#" + this.convert(this.A) +
                            this.convert(this.R) +
                            this.convert(this.G) +
                            this.convert(this.B);
        }
    };
    /**
     * A KML Formatted hex string is in the format of AABBGGRR
     */
    armyc2.c2sd.renderer.utilities.Color.prototype.toKMLHexString = function()
    {
        return "#" +
                this.convert(this.A) +
                this.convert(this.B) +
                this.convert(this.G) +
                this.convert(this.R);
    };

//static public vars/functions
//milstd.renderer.ClassName.MY_CONSTANT = "constant_value";
//milstd.renderer.ClassName.myStaticFunction = function(){};

/**
 * @param {Number} color int value of a color
 * @return {Number} 0 - 255, alpha value
 */
armyc2.c2sd.renderer.utilities.Color.getAlphaFromColor = function(color)
{
	var alpha = 255;
	if (color > 16777215) alpha = (color >>> 24);
	return alpha;
};

/**
 * @param {Number} color int value of a color
 * @return {Number} 0 - 255, Red value
 */
armyc2.c2sd.renderer.utilities.Color.getRedFromColor = function(color)
{
	var red = 255;
	red = (color >> 16) & 0xFF;
	return red;
};

/**
 * @param {Number} color int value of a color
 * @return {Number} 0 - 255, Green value
 */
armyc2.c2sd.renderer.utilities.Color.getGreenFromColor = function(color)
{
	var green = 255;
	green = (color >> 8) & 0xFF;
	return green;
};

/**
 * @param {Number} color int value of a color
 * @return {Number} 0 - 255, Blue value
 */
armyc2.c2sd.renderer.utilities.Color.getBlueFromColor = function(color)
{
	var blue = 255;
	if (color > 16777215)
		blue = color & 0x000000FF;
	else
		blue = color & 0x0000FF;
	return blue;
};

/**
*
* @param hexValue - String representing hex value
* (formatted "0xRRGGBB" i.e. "0xFFFFFF")
* OR
* formatted "0xAARRGGBB" i.e. "0x00FFFFFF" for a color with an alpha value
* I will also put up with "RRGGBB" and "AARRGGBB" without the starting "0x"
* @return
*/
armyc2.c2sd.renderer.utilities.Color.getColorFromHexString = function(hexValue)
{
    var hexOriginal = new String(hexValue);

    var hexAlphabet = "0123456789ABCDEF";

    if(hexValue.charAt(0)==='#')
        hexValue = hexValue.substring(1);
    if(hexValue.substring(0,2)===("0x") || hexValue.substring(0,2)===("0X"))
        hexValue = hexValue.substring(2);

    hexValue = hexValue.toUpperCase();

    var count = hexValue.length,
        value = null,
        k = 0,
        int1 = 0,
        int2 = 0;

    if(count === 8 || count === 6)
    {
        value = new Array();//int[(count / 2)];
        for(var i=0; i<count;i+=2)
        {
                int1 = hexAlphabet.indexOf(hexValue.charAt(i));
                int2 = hexAlphabet.indexOf(hexValue.charAt(i+1));
                value[k]=(int1 * 16) + int2;
                k++;
        }

        if(count === 8)
        {
                return new armyc2.c2sd.renderer.utilities.Color(value[1],value[2],value[3],value[0]);
        }
        else if(count === 6)
        {
                return new armyc2.c2sd.renderer.utilities.Color(value[0],value[1],value[2]);
        }
    }
    else
    {
            //ErrorLogger.LogMessage("SymbolUtilties", "getColorFromHexString", "Bad hex value: " + hexOriginal, Level.WARNING);
    }
    return null;
};

armyc2.c2sd.renderer.utilities.Color.rgbToHexString = function(r,g,b,a)
{
    var temp = new armyc2.c2sd.renderer.utilities.Color(r,g,b,a);
    return temp.toHexString(true);
};

armyc2.c2sd.renderer.utilities.Color.white =  new armyc2.c2sd.renderer.utilities.Color (255, 255, 255);
armyc2.c2sd.renderer.utilities.Color.WHITE = armyc2.c2sd.renderer.utilities.Color.white;
armyc2.c2sd.renderer.utilities.Color.lightGray =  new armyc2.c2sd.renderer.utilities.Color (192, 192, 192);
armyc2.c2sd.renderer.utilities.Color.LIGHT_GRAY = armyc2.c2sd.renderer.utilities.Color.lightGray;
armyc2.c2sd.renderer.utilities.Color.gray =  new armyc2.c2sd.renderer.utilities.Color (128, 128, 128);
armyc2.c2sd.renderer.utilities.Color.GRAY = armyc2.c2sd.renderer.utilities.Color.gray;
armyc2.c2sd.renderer.utilities.Color.darkGray =  new armyc2.c2sd.renderer.utilities.Color (64, 64, 64);
armyc2.c2sd.renderer.utilities.Color.DARK_GRAY = armyc2.c2sd.renderer.utilities.Color.darkGray;
armyc2.c2sd.renderer.utilities.Color.black =  new armyc2.c2sd.renderer.utilities.Color (0, 0, 0);
armyc2.c2sd.renderer.utilities.Color.BLACK = armyc2.c2sd.renderer.utilities.Color.black;
armyc2.c2sd.renderer.utilities.Color.red =  new armyc2.c2sd.renderer.utilities.Color (255, 0, 0);
armyc2.c2sd.renderer.utilities.Color.RED = armyc2.c2sd.renderer.utilities.Color.red;
armyc2.c2sd.renderer.utilities.Color.pink =  new armyc2.c2sd.renderer.utilities.Color (255, 175, 175);
armyc2.c2sd.renderer.utilities.Color.PINK = armyc2.c2sd.renderer.utilities.Color.pink;
armyc2.c2sd.renderer.utilities.Color.orange =  new armyc2.c2sd.renderer.utilities.Color (255, 200, 0);
armyc2.c2sd.renderer.utilities.Color.ORANGE = armyc2.c2sd.renderer.utilities.Color.orange;
armyc2.c2sd.renderer.utilities.Color.yellow =  new armyc2.c2sd.renderer.utilities.Color (255, 255, 0);
armyc2.c2sd.renderer.utilities.Color.YELLOW = armyc2.c2sd.renderer.utilities.Color.yellow;
armyc2.c2sd.renderer.utilities.Color.green =  new armyc2.c2sd.renderer.utilities.Color (0, 255, 0);
armyc2.c2sd.renderer.utilities.Color.GREEN = armyc2.c2sd.renderer.utilities.Color.green;
armyc2.c2sd.renderer.utilities.Color.magenta =  new armyc2.c2sd.renderer.utilities.Color (255, 0, 255);
armyc2.c2sd.renderer.utilities.Color.MAGENTA = armyc2.c2sd.renderer.utilities.Color.magenta;
armyc2.c2sd.renderer.utilities.Color.cyan =  new armyc2.c2sd.renderer.utilities.Color (0, 255, 255);
armyc2.c2sd.renderer.utilities.Color.CYAN = armyc2.c2sd.renderer.utilities.Color.cyan;
armyc2.c2sd.renderer.utilities.Color.blue =  new armyc2.c2sd.renderer.utilities.Color (0, 0, 255);
armyc2.c2sd.renderer.utilities.Color.BLUE = armyc2.c2sd.renderer.utilities.Color.blue;

<|endoftext|>


<commit_before>$(function () {
  var $preview = $('#preview')
    , $editor = $('#editor')

  var TEMPLATE_ROW = $('#template-row').html()
  Mustache.parse(TEMPLATE_ROW)

  function render () {
    var content = $editor.val()

    var maxLength = 0

    var rendered = content.split('\n').map(function (row, i) {
      var cols = row.split('\\')
      if (cols.length > maxLength) {
        maxLength = cols.length
      }
      return renderRow(row, i)
    }).join('')

    $preview.css('width', maxLength * 20).html(rendered)

    var width = maxLength * 20 + 80 + 200
    width = width < 200 ? 200 : width
    width = width > 600 ? 600 : width

    $('#preview-container').css('width', width)
    $('#editor-container').css('right', width)
  }

  function renderRow (row, i) {
    var structure = {
      i: i,
      cols: [],
      text: ''
    }

    structure.cols = row.split('\\').map(function (col, j) {
      var divider = col.indexOf('~~')
      if (divider >= 0) {
        structure.text = col.substring(divider).trim()
        col = col.substring(0, divider)
      }

      var column = {
        j: j,
        raw: col,
        layers: []
      }

      col.split('!~').forEach(function (layer) {
        layer = layer.trim()
        if (layer) {
          var name = 'BSicon_' + (layer.replace(/ /, '_')) + '.svg'
            , hash = CryptoJS.MD5(name).toString(CryptoJS.enc.Hex)
          column.layers.push({
            a: hash.substring(0, 1),
            b: hash.substring(0, 2),
            name: encodeURIComponent(name)
          })
        }
      })

      return column
    })

    return Mustache.render(TEMPLATE_ROW, structure)
  }

  function syncFocus () {
    var selection = $editor.prop('selectionStart')

    var content = $editor.val()

    var rows = content.substring(0, selection).split('\n')
      , cols = rows.pop().split('\\')
      , cell = cols.pop()
      , text = cell + content.substring(selection).split('\n').shift()

    var row = rows.length
      , col = cols.length

    $preview.find('.focus').removeClass('focus')

    var divider = text.indexOf('~~')
      , heading = cell.length

    if ((divider == 0 && heading >= 1) || (divider > 0 && heading > divider)) {
      $preview.find('> div > .text[data-row="' + row + '"]').addClass('focus')
    } else {
      $preview.find('> div > .cell[data-row="' + row + '"][data-col="' + col + '"]').addClass('focus')
    }
  }

  $preview.on('click', '> div > .cell[data-row][data-col]', function () {
    var $this = $(this)

    var row = $this.data('row')
      , col = $this.data('col')

    var rows = $editor.val().split('\n').slice(0, row + 1)
      , cols = rows.pop().split('\\').slice(0, col + 1)

    var above = rows.join('\n').length
    above = rows.length ? above + 1 : 0

    var selection = cols.pop()

    var divider = selection.indexOf('~~')
    if (divider >= 0) {
      selection = selection.substring(0, divider)
    }

    var col = cols.join('\\').length
    col = cols.length ? col + 1 : 0

    var selectionStart = above + col
      , selectionEnd = selectionStart + selection.length

    $editor
      .prop('selectionStart', selectionStart)
      .prop('selectionEnd', selectionEnd)
      .focus()

    $preview.find('.focus').removeClass('focus')
    $this.addClass('focus')
  })

  $preview.on('click', '> div > .text[data-row]', function () {
    var $this = $(this)

    var row = $this.data('row')

    var rows = $editor.val().split('\n').slice(0, row + 1)
      , line = rows.pop()

    var above = rows.join('\n').length
    above = rows.length ? above + 1 : 0

    var divider = line.indexOf('~~')

    var selectionStart = above
      , selectionEnd = selectionStart + line.length

    if (divider > 0) {
      selectionStart += divider
    } else {
      selectionStart += line.length
    }

    $editor
      .prop('selectionStart', selectionStart)
      .prop('selectionEnd', selectionEnd)
      .focus()

    $preview.find('.focus').removeClass('focus')
    $this.addClass('focus')
  })

  $editor.on('keyup', $.debounce(250, function () {
    localStorage.setItem('content', $editor.val())
    render()
    syncFocus()
  }))

  $editor.on('mouseup', function () {
    syncFocus()
  })

  $editor.val(localStorage.getItem('content'))
  render()
})
<commit_msg>一些啰嗦的代码<commit_after>$(function () {
  var $preview = $('#preview')
    , $editor = $('#editor')

  var TEMPLATE_ROW = $('#template-row').html()
  Mustache.parse(TEMPLATE_ROW)

  function render () {
    var content = $editor.val()

    var maxLength = 0

    var rendered = content.split('\n').map(function (row, i) {
      maxLength = Math.max(maxLength, row.split('\\').length)
      return renderRow(row, i)
    }).join('')

    $preview.css('width', maxLength * 20).html(rendered)

    var width = Math.min(Math.max(maxLength * 20 + 80 + 200, 200), 600)

    $('#preview-container').css('width', width)
    $('#editor-container').css('right', width)
  }

  function renderRow (row, i) {
    var structure = {
      i: i,
      cols: [],
      text: ''
    }

    structure.cols = row.split('\\').map(function (col, j) {
      var divider = col.indexOf('~~')
      if (divider >= 0) {
        structure.text = col.substring(divider).trim()
        col = col.substring(0, divider)
      }

      var column = {
        j: j,
        raw: col,
        layers: []
      }

      col.split('!~').forEach(function (layer) {
        layer = layer.trim()
        if (layer) {
          var name = 'BSicon_' + (layer.replace(/ /, '_')) + '.svg'
            , hash = CryptoJS.MD5(name).toString(CryptoJS.enc.Hex)
          column.layers.push({
            a: hash.substring(0, 1),
            b: hash.substring(0, 2),
            name: encodeURIComponent(name)
          })
        }
      })

      return column
    })

    return Mustache.render(TEMPLATE_ROW, structure)
  }

  function syncFocus () {
    var selection = $editor.prop('selectionStart')

    var content = $editor.val()

    var rows = content.substring(0, selection).split('\n')
      , cols = rows.pop().split('\\')
      , cell = cols.pop()
      , text = cell + content.substring(selection).split('\n').shift()

    var row = rows.length
      , col = cols.length

    $preview.find('.focus').removeClass('focus')

    var divider = text.indexOf('~~')
      , heading = cell.length

    if ((divider == 0 && heading >= 1) || (divider > 0 && heading > divider)) {
      $preview.find('> div > .text[data-row="' + row + '"]').addClass('focus')
    } else {
      $preview.find('> div > .cell[data-row="' + row + '"][data-col="' + col + '"]').addClass('focus')
    }
  }

  $preview.on('click', '> div > .cell[data-row][data-col]', function () {
    var $this = $(this)

    var row = $this.data('row')
      , col = $this.data('col')

    var rows = $editor.val().split('\n').slice(0, row + 1)
      , cols = rows.pop().split('\\').slice(0, col + 1)

    var above = rows.join('\n').length
    above = rows.length ? above + 1 : 0

    var selection = cols.pop()

    var divider = selection.indexOf('~~')
    if (divider >= 0) {
      selection = selection.substring(0, divider)
    }

    var col = cols.join('\\').length
    col = cols.length ? col + 1 : 0

    var selectionStart = above + col
      , selectionEnd = selectionStart + selection.length

    $editor
      .prop('selectionStart', selectionStart)
      .prop('selectionEnd', selectionEnd)
      .focus()

    $preview.find('.focus').removeClass('focus')
    $this.addClass('focus')
  })

  $preview.on('click', '> div > .text[data-row]', function () {
    var $this = $(this)

    var row = $this.data('row')

    var rows = $editor.val().split('\n').slice(0, row + 1)
      , line = rows.pop()

    var above = rows.join('\n').length
    above = rows.length ? above + 1 : 0

    var divider = line.indexOf('~~')

    var selectionStart = above
      , selectionEnd = selectionStart + line.length

    if (divider > 0) {
      selectionStart += divider
    } else {
      selectionStart += line.length
    }

    $editor
      .prop('selectionStart', selectionStart)
      .prop('selectionEnd', selectionEnd)
      .focus()

    $preview.find('.focus').removeClass('focus')
    $this.addClass('focus')
  })

  $editor.on('keyup', $.debounce(250, function () {
    localStorage.setItem('content', $editor.val())
    render()
    syncFocus()
  }))

  $editor.on('mouseup', function () {
    syncFocus()
  })

  $editor.val(localStorage.getItem('content'))
  render()
})
<|endoftext|>


<commit_before>elation.require([
    'utils.events',
    'utils.worker',
    'engine.engine',
    'engine.assets',
    'engine.external.pako',
    'engine.external.three.three', 'engine.external.three.FBXLoader', 'engine.external.three.ColladaLoader', 'engine.external.xmldom',
    'engine.external.three.OBJLoader', 'engine.external.three.MTLLoader', 'engine.external.three.VRMLLoader',
  ], function() {

  elation.define('engine.assetworker', {
    _construct: function() {
      var srcmap = {};
      THREE.Cache.enabled = true;
      THREE.ImageLoader.prototype.load = function(url, onLoad) {
        var uuid = srcmap[url];
        if (!uuid) {
          srcmap[url] = uuid = THREE.Math.generateUUID();
        }
        var img = { uuid: uuid, src: url, toDataURL: function() { return url; } };
        if ( onLoad ) {
          onLoad( img );
        }
      }
      this.loader = new elation.engine.assets.loaders.model();
      elation.engine.assets.init();
    },
    onmessage: function(ev) {
      var msg = ev.data;
      if (msg.type == 'job') {
        if (msg.data) {
          this.loader.load(msg.data);
        }
      } else if (msg.type == 'setcorsproxy') {
        elation.engine.assets.setCORSProxy(msg.data);
      }
    }
  }, elation.worker.base);

  elation.define('engine.assets.loaders.model', {
    _construct: function(args) {
      elation.class.call(this, args);
      this.parsers = {
        'collada': new elation.engine.assets.loaders.model_collada(),
        'obj': new elation.engine.assets.loaders.model_obj(),
        'fbx': new elation.engine.assets.loaders.model_fbx(),
        'wrl': new elation.engine.assets.loaders.model_wrl(),
      }
    },
    getFullURL: function(src) {
      var corsproxy = elation.engine.assets.corsproxy || '';
      var baseurl = src.substr( 0, src.lastIndexOf( "/" ) + 1 )
      var fullurl = src;
      if (src.match(/^(https?:)?\/\//) && !src.match(/^(https?:)?\/\/localhost/)) {
        fullurl = corsproxy + fullurl;
      }
      return fullurl;
    },
    load: function(job) {
      var fullurl = this.getFullURL(job.data.src);
      elation.net.get(fullurl, null, {
        responseType: 'arraybuffer',
        callback: elation.bind(this, this.onload, job),
        onprogress: elation.bind(this, this.onprogress, job),
        onerror: elation.bind(this, this.onerror, job),
        headers: {
          'X-Requested-With': 'Elation Engine asset loader'
        }
      });
    },
    contentIsGzipped: function(databuf) {
      var c1 = databuf[0], c2 = databuf[1];
      //console.log('gzip check?', [c1, c2], [0x1f, 0x8b]);
      if (c1 == 0x1f && c2 == 0x8b) {
        return true;
      }
      return false;
    },
    detectContentType: function(content) {
      var foo = '';
      for (var i = 0; i < 500; i++) {
        foo += content[i];
      }
      //content = foo;
      var tests = [
        [/<COLLADA/im, 'collada'],
        [/^\s*v\s+-?[\d\.]+\s+-?[\d\.]+\s+-?[\d\.]+\s*$/im, 'obj'],
        [/FBXHeader/i, 'fbx'],
        [/^\#VRML/, 'wrl']
      ];

      var type = false;
      tests.forEach(function(t) {
        if (content.match(t[0])) {
          type = t[1];
        }
      });
      return type;
    },
    parse: function(data, job) {
      var type = this.detectContentType(data);
      if (this.parsers[type]) {
        return this.parsers[type].parse(data, job);
      }
      return new Promise(function(resolve, reject) {
        resolve(false);
      });
    },
    onload: function(job, rawdata, xhr) {
      var databuf = new Uint8Array(rawdata),
          modeldata = false;

      if (this.contentIsGzipped(databuf)) {
        modeldata = window.pako.inflate(databuf, {to: 'string'});
      } else {
        var dataview = new DataView(rawdata);
        if (false && typeof TextDecoder !== 'undefined') {
          var decoder = new TextDecoder('utf-8');
          modeldata = decoder.decode(dataview);
        } else {
          var str = '';
          var bufview = new Uint8Array(rawdata);
          var l = bufview.length;
          for (var i = 0; i < l; i++) {
            str += String.fromCharCode(bufview[i]);
          }
          try {
            modeldata = decodeURIComponent(escape(str));
          } catch (e) {
            modeldata = str;
          }
        }
      }
      if (modeldata) {
        this.parse(modeldata, job).then(function(data) {
          var transferrables = [];
          // Convert BufferGeometry arrays back to Float32Arrays so they can be transferred efficiently
          for (var i = 0; i < data.geometries.length; i++) {
            var geo = data.geometries[i];
            for (var k in geo.data.attributes) {
              var arr = Float32Array.from(geo.data.attributes[k].array);
              transferrables.push(arr.buffer);
              geo.data.attributes[k].array = arr;
            }
          }
          postMessage({message: 'finished', id: job.id, data: data}, transferrables);
        }, function(d) {
          postMessage({message: 'error', id: job.id, data: d.toString()});
        });
      } else {
        postMessage({message: 'error', id: job.id, data: 'no modeldata found'});
      }
    },
    onprogress: function(job, ev) {
      //console.log('progress', job, ev);
    },
    onerror: function(job, ev) {
      console.log('error', job, ev);
      postMessage({message: 'error', id: job.id, data: 'unknown error'});
    },
  });
  elation.define('engine.assets.loaders.model_obj', {
    parse: function(data, job) {
      return new Promise(elation.bind(this, function(resolve, reject) {
        var mtl = job.data.mtl || false;

        var baseurl = job.data.src.substr( 0, job.data.src.lastIndexOf( "/" ) + 1 )
/*
        if (!mtl) {
          var re = /^mtllib (.*)$/im;
          var m = data.match(re);
          if (m) {
            mtl = m[1];
          }
        }
*/
        //var loader = (mtl ? new THREE.OBJMTLLoader() : new THREE.OBJLoader());
        var loader = new THREE.OBJLoader();
        var modeldata = loader.parse(data);

        if (mtl) {
          mtl = this.getFullURL(mtl, baseurl);
          if (elation.engine.assets.corsproxy) {
            mtl = elation.engine.assets.corsproxy + mtl;
          }
          var mtlLoader = new THREE.MTLLoader( );
          mtlLoader.setBaseUrl( mtl.substr( 0, mtl.lastIndexOf( "/" ) + 1 ) );
          mtlLoader.setCrossOrigin( 'anonymous' );
          mtlLoader.load( mtl,
            elation.bind(this, function ( materials ) {
              var materialsCreator = materials;
              materialsCreator.preload();

              modeldata.traverse( function ( object ) {

                if ( object instanceof THREE.Mesh ) {

                  if (object.material instanceof THREE.MeshFaceMaterial) {
                    var newmaterials = [];
                    object.material.materials.forEach(function(m) {
                      if ( m.name ) {

                        var material = materialsCreator.create( m.name );

                        if ( material ) {
                          newmaterials.push(material);
                        } else {
                          newmaterials.push(m);
                        }
                      } else {
                        newmaterials.push(m);
                      }
                    });
                    object.material.materials = newmaterials;
                  } else {
                    if ( object.material.name ) {

                      var material = materialsCreator.create( object.material.name );

                      if ( material ) object.material = material;

                    }
                  }

                }

              } );
              resolve(this.convertToJSON(modeldata));
            }),
            undefined,
            elation.bind(this, function() {
              resolve(this.convertToJSON(modeldata));
            })
          );
        } else {
          resolve(this.convertToJSON(modeldata));
        }
        return modeldata;
      }));
    },
    convertToJSON: function(scene) {
      // Convert Geometries to BufferGeometries
      scene.traverse(function(n) {
        if (n.geometry && n.geometry instanceof THREE.Geometry) {
          var bufgeo = new THREE.BufferGeometry().fromGeometry(n.geometry);
          n.geometry = bufgeo;
        }
      });
      return scene.toJSON();
    }
  }, elation.engine.assets.base);
  elation.define('engine.assets.loaders.model_collada', {
    parser: new DOMParser(),

    parse: function(xml, job) {
      return new Promise(elation.bind(this, function(resolve, reject) {
        var docRoot = this.parser.parseFromString(xml);
        var collada = docRoot.getElementsByTagName('COLLADA')[0];
        var data = false;

        // helper functions
        function getChildrenByTagName(node, tag) {
          var tags = [];
          for (var i = 0; i < node.childNodes.length; i++) {
            var childnode = node.childNodes[i];
            if (childnode.tagName == tag) {
              tags.push(childnode);
              childnode.querySelectorAll = querySelectorAll;
              childnode.querySelector = querySelector;
            }
          };
          return tags;
        }
        function querySelectorAll(selector) {
          var sels = selector.split(","),
              run = function(node,selector) {
                  var sel = selector.split(/[ >]+/), com = selector.match(/[ >]+/g) || [], s, c, ret = [node], nodes, l, i, subs, m, j, check, x, w, ok,
                      as;
                  com.unshift(" ");
                  while(s = sel.shift()) {
                      c = com.shift();
                      if( c) c = c.replace(/^ +| +$/g,"");
                      nodes = ret.slice(0);
                      ret = [];
                      l = nodes.length;
                      subs = s.match(/[#.[]?[a-z_-]+(?:='[^']+'|="[^"]+")?]?/gi);
                      m = subs.length;
                      for( i=0; i<l; i++) {
                          if( subs[0].charAt(0) == "#") ret = [document.getElementById(subs[0].substr(1))];
                          else {
                              check = c == ">" ? nodes[i].children : nodes[i].getElementsByTagName("*");
                              if( !check) continue;
                              w = check.length;
                              for( x=0; x<w; x++) {
                                  ok = true;
                                  for( j=0; j<m; j++) {
                                      switch(subs[j].charAt(0)) {
                                      case ".":
                                          if( !check[x].className.match(new RegExp("\\b"+subs[j].substr(1)+"\\b"))) ok = false;
                                          break;
                                      case "[":
                                          as = subs[j].substr(1,subs[j].length-2).split("=");
                                          if( !check[x].getAttribute(as[0])) ok = false;
                                          else if( as[1]) {
                                              as[1] = as[1].replace(/^['"]|['"]$/g,"");
                                              if( check[x].getAttribute(as[0]) != as[1]) ok = false;
                                          }
                                          break;
                                      default:
                                          if( check[x].tagName.toLowerCase() != subs[j].toLowerCase()) ok = false;
                                          break;
                                      }
                                      if( !ok) break;
                                  }
                                  if( ok) ret.push(check[x]);
                              }
                          }
                      }
                  }
                  return ret;
              }, l = sels.length, i, ret = [], tmp, m, j;
          for( i=0; i<l; i++) {
              tmp = run(this,sels[i]);
              m = tmp.length;
              for( j=0; j<m; j++) {
                  ret.push(tmp[j]);
              }
          }
          return ret;

        }
        function querySelector(selector) {
          return this.querySelectorAll(selector)[0];
        }

        function fakeQuerySelector(node) {
          node.querySelectorAll = querySelectorAll;
          node.querySelector = querySelector;

          if (node.childNodes && node.childNodes.length > 0) {
            for (var i = 0; i < node.childNodes.length; i++) {
              fakeQuerySelector(node.childNodes[i]);
            }
          }
        }
        fakeQuerySelector(docRoot);
        var loader = new THREE.ColladaLoader();
        loader.options.convertUpAxis = true;
        loader.options.upAxis = 'Y';
        loader.parse(docRoot, function(parsed) {
          parsed.scene.traverse(function(n) {
            if ((n.geometry instanceof THREE.BufferGeometry && !n.geometry.attributes.normals) ||
                (n.geometry instanceof THREE.Geometry && !n.geometry.faceVertexNormals)) {
              n.geometry.computeFaceNormals();
              n.geometry.computeVertexNormals();
            }
            // Convert to BufferGeometry for better loading efficiency
            if (n.geometry && n.geometry instanceof THREE.Geometry) {
              var bufgeo = new THREE.BufferGeometry().fromGeometry(n.geometry);
              n.geometry = bufgeo;
            }
          });
          data = parsed;
        }, job.data.src);

        data.scene.updateMatrix();
        resolve(data.scene.toJSON());
      }));
    },
  }, elation.engine.assets.base);
  elation.define('engine.assets.loaders.model_wrl', {
    parse: function(data, job) {
      return new Promise(function(resolve, reject) {
        var loader = new THREE.VRMLLoader();
        var modeldata = loader.parse(data);

        resolve(modeldata.toJSON());
      });
    }
  }, elation.engine.assets.base);
  elation.define('engine.assets.loaders.model_fbx', {
    parse: function(data, job) {
      return new Promise(function(resolve, reject) {
        var loader = new THREE.FBXLoader();
        var modeldata = loader.parse(data);
        resolve(modeldata.toJSON());
      });
    }
  }, elation.engine.assets.base);

});

<commit_msg>Fix for older browsers (Samsung GearVR)<commit_after>elation.require([
    'utils.events',
    'utils.worker',
    'engine.engine',
    'engine.assets',
    'engine.external.pako',
    'engine.external.three.three', 'engine.external.three.FBXLoader', 'engine.external.three.ColladaLoader', 'engine.external.xmldom',
    'engine.external.three.OBJLoader', 'engine.external.three.MTLLoader', 'engine.external.three.VRMLLoader',
  ], function() {

  elation.define('engine.assetworker', {
    _construct: function() {
      var srcmap = {};
      THREE.Cache.enabled = true;
      THREE.ImageLoader.prototype.load = function(url, onLoad) {
        var uuid = srcmap[url];
        if (!uuid) {
          srcmap[url] = uuid = THREE.Math.generateUUID();
        }
        var img = { uuid: uuid, src: url, toDataURL: function() { return url; } };
        if ( onLoad ) {
          onLoad( img );
        }
      }
      this.loader = new elation.engine.assets.loaders.model();
      elation.engine.assets.init();
    },
    onmessage: function(ev) {
      var msg = ev.data;
      if (msg.type == 'job') {
        if (msg.data) {
          this.loader.load(msg.data);
        }
      } else if (msg.type == 'setcorsproxy') {
        elation.engine.assets.setCORSProxy(msg.data);
      }
    }
  }, elation.worker.base);

  elation.define('engine.assets.loaders.model', {
    _construct: function(args) {
      elation.class.call(this, args);
      this.parsers = {
        'collada': new elation.engine.assets.loaders.model_collada(),
        'obj': new elation.engine.assets.loaders.model_obj(),
        'fbx': new elation.engine.assets.loaders.model_fbx(),
        'wrl': new elation.engine.assets.loaders.model_wrl(),
      }
    },
    getFullURL: function(src) {
      var corsproxy = elation.engine.assets.corsproxy || '';
      var baseurl = src.substr( 0, src.lastIndexOf( "/" ) + 1 )
      var fullurl = src;
      if (src.match(/^(https?:)?\/\//) && !src.match(/^(https?:)?\/\/localhost/)) {
        fullurl = corsproxy + fullurl;
      }
      return fullurl;
    },
    load: function(job) {
      var fullurl = this.getFullURL(job.data.src);
      elation.net.get(fullurl, null, {
        responseType: 'arraybuffer',
        callback: elation.bind(this, this.onload, job),
        onprogress: elation.bind(this, this.onprogress, job),
        onerror: elation.bind(this, this.onerror, job),
        headers: {
          'X-Requested-With': 'Elation Engine asset loader'
        }
      });
    },
    contentIsGzipped: function(databuf) {
      var c1 = databuf[0], c2 = databuf[1];
      //console.log('gzip check?', [c1, c2], [0x1f, 0x8b]);
      if (c1 == 0x1f && c2 == 0x8b) {
        return true;
      }
      return false;
    },
    detectContentType: function(content) {
      var foo = '';
      for (var i = 0; i < 500; i++) {
        foo += content[i];
      }
      //content = foo;
      var tests = [
        [/<COLLADA/im, 'collada'],
        [/^\s*v\s+-?[\d\.]+\s+-?[\d\.]+\s+-?[\d\.]+\s*$/im, 'obj'],
        [/FBXHeader/i, 'fbx'],
        [/^\#VRML/, 'wrl']
      ];

      var type = false;
      tests.forEach(function(t) {
        if (content.match(t[0])) {
          type = t[1];
        }
      });
      return type;
    },
    parse: function(data, job) {
      var type = this.detectContentType(data);
      if (this.parsers[type]) {
        return this.parsers[type].parse(data, job);
      }
      return new Promise(function(resolve, reject) {
        resolve(false);
      });
    },
    onload: function(job, rawdata, xhr) {
      var databuf = new Uint8Array(rawdata),
          modeldata = false;

      if (this.contentIsGzipped(databuf)) {
        modeldata = window.pako.inflate(databuf, {to: 'string'});
      } else {
        var dataview = new DataView(rawdata);
        if (false && typeof TextDecoder !== 'undefined') {
          var decoder = new TextDecoder('utf-8');
          modeldata = decoder.decode(dataview);
        } else {
          var str = '';
          var bufview = new Uint8Array(rawdata);
          var l = bufview.length;
          for (var i = 0; i < l; i++) {
            str += String.fromCharCode(bufview[i]);
          }
          try {
            modeldata = decodeURIComponent(escape(str));
          } catch (e) {
            modeldata = str;
          }
        }
      }
      if (modeldata) {
        this.parse(modeldata, job).then(function(data) {
          var transferrables = [];
          // Convert BufferGeometry arrays back to Float32Arrays so they can be transferred efficiently
          for (var i = 0; i < data.geometries.length; i++) {
            var geo = data.geometries[i];
            for (var k in geo.data.attributes) {
              //var arr = Float32Array.from(geo.data.attributes[k].array);
              var src = geo.data.attributes[k].array;
              var arr = new Float32Array(src.length);
              for (var j = 0; j < src.length; j++) {
                arr[j] = src[j];
              }
              transferrables.push(arr.buffer);
              geo.data.attributes[k].array = arr;
            }
          }
          postMessage({message: 'finished', id: job.id, data: data}, transferrables);
        }, function(d) {
          postMessage({message: 'error', id: job.id, data: d.toString()});
        });
      } else {
        postMessage({message: 'error', id: job.id, data: 'no modeldata found'});
      }
    },
    onprogress: function(job, ev) {
      //console.log('progress', job, ev);
    },
    onerror: function(job, ev) {
      console.log('error', job, ev);
      postMessage({message: 'error', id: job.id, data: 'unknown error'});
    },
  });
  elation.define('engine.assets.loaders.model_obj', {
    parse: function(data, job) {
      return new Promise(elation.bind(this, function(resolve, reject) {
        var mtl = job.data.mtl || false;

        var baseurl = job.data.src.substr( 0, job.data.src.lastIndexOf( "/" ) + 1 )
/*
        if (!mtl) {
          var re = /^mtllib (.*)$/im;
          var m = data.match(re);
          if (m) {
            mtl = m[1];
          }
        }
*/
        //var loader = (mtl ? new THREE.OBJMTLLoader() : new THREE.OBJLoader());
        var loader = new THREE.OBJLoader();
        var modeldata = loader.parse(data);

        if (mtl) {
          mtl = this.getFullURL(mtl, baseurl);
          if (elation.engine.assets.corsproxy) {
            mtl = elation.engine.assets.corsproxy + mtl;
          }
          var mtlLoader = new THREE.MTLLoader( );
          mtlLoader.setBaseUrl( mtl.substr( 0, mtl.lastIndexOf( "/" ) + 1 ) );
          mtlLoader.setCrossOrigin( 'anonymous' );
          mtlLoader.load( mtl,
            elation.bind(this, function ( materials ) {
              var materialsCreator = materials;
              materialsCreator.preload();

              modeldata.traverse( function ( object ) {

                if ( object instanceof THREE.Mesh ) {

                  if (object.material instanceof THREE.MeshFaceMaterial) {
                    var newmaterials = [];
                    object.material.materials.forEach(function(m) {
                      if ( m.name ) {

                        var material = materialsCreator.create( m.name );

                        if ( material ) {
                          newmaterials.push(material);
                        } else {
                          newmaterials.push(m);
                        }
                      } else {
                        newmaterials.push(m);
                      }
                    });
                    object.material.materials = newmaterials;
                  } else {
                    if ( object.material.name ) {

                      var material = materialsCreator.create( object.material.name );

                      if ( material ) object.material = material;

                    }
                  }

                }

              } );
              resolve(this.convertToJSON(modeldata));
            }),
            undefined,
            elation.bind(this, function() {
              resolve(this.convertToJSON(modeldata));
            })
          );
        } else {
          resolve(this.convertToJSON(modeldata));
        }
        return modeldata;
      }));
    },
    convertToJSON: function(scene) {
      // Convert Geometries to BufferGeometries
      scene.traverse(function(n) {
        if (n.geometry && n.geometry instanceof THREE.Geometry) {
          var bufgeo = new THREE.BufferGeometry().fromGeometry(n.geometry);
          n.geometry = bufgeo;
        }
      });
      return scene.toJSON();
    }
  }, elation.engine.assets.base);
  elation.define('engine.assets.loaders.model_collada', {
    parser: new DOMParser(),

    parse: function(xml, job) {
      return new Promise(elation.bind(this, function(resolve, reject) {
        var docRoot = this.parser.parseFromString(xml);
        var collada = docRoot.getElementsByTagName('COLLADA')[0];
        var data = false;

        // helper functions
        function getChildrenByTagName(node, tag) {
          var tags = [];
          for (var i = 0; i < node.childNodes.length; i++) {
            var childnode = node.childNodes[i];
            if (childnode.tagName == tag) {
              tags.push(childnode);
              childnode.querySelectorAll = querySelectorAll;
              childnode.querySelector = querySelector;
            }
          };
          return tags;
        }
        function querySelectorAll(selector) {
          var sels = selector.split(","),
              run = function(node,selector) {
                  var sel = selector.split(/[ >]+/), com = selector.match(/[ >]+/g) || [], s, c, ret = [node], nodes, l, i, subs, m, j, check, x, w, ok,
                      as;
                  com.unshift(" ");
                  while(s = sel.shift()) {
                      c = com.shift();
                      if( c) c = c.replace(/^ +| +$/g,"");
                      nodes = ret.slice(0);
                      ret = [];
                      l = nodes.length;
                      subs = s.match(/[#.[]?[a-z_-]+(?:='[^']+'|="[^"]+")?]?/gi);
                      m = subs.length;
                      for( i=0; i<l; i++) {
                          if( subs[0].charAt(0) == "#") ret = [document.getElementById(subs[0].substr(1))];
                          else {
                              check = c == ">" ? nodes[i].children : nodes[i].getElementsByTagName("*");
                              if( !check) continue;
                              w = check.length;
                              for( x=0; x<w; x++) {
                                  ok = true;
                                  for( j=0; j<m; j++) {
                                      switch(subs[j].charAt(0)) {
                                      case ".":
                                          if( !check[x].className.match(new RegExp("\\b"+subs[j].substr(1)+"\\b"))) ok = false;
                                          break;
                                      case "[":
                                          as = subs[j].substr(1,subs[j].length-2).split("=");
                                          if( !check[x].getAttribute(as[0])) ok = false;
                                          else if( as[1]) {
                                              as[1] = as[1].replace(/^['"]|['"]$/g,"");
                                              if( check[x].getAttribute(as[0]) != as[1]) ok = false;
                                          }
                                          break;
                                      default:
                                          if( check[x].tagName.toLowerCase() != subs[j].toLowerCase()) ok = false;
                                          break;
                                      }
                                      if( !ok) break;
                                  }
                                  if( ok) ret.push(check[x]);
                              }
                          }
                      }
                  }
                  return ret;
              }, l = sels.length, i, ret = [], tmp, m, j;
          for( i=0; i<l; i++) {
              tmp = run(this,sels[i]);
              m = tmp.length;
              for( j=0; j<m; j++) {
                  ret.push(tmp[j]);
              }
          }
          return ret;

        }
        function querySelector(selector) {
          return this.querySelectorAll(selector)[0];
        }

        function fakeQuerySelector(node) {
          node.querySelectorAll = querySelectorAll;
          node.querySelector = querySelector;

          if (node.childNodes && node.childNodes.length > 0) {
            for (var i = 0; i < node.childNodes.length; i++) {
              fakeQuerySelector(node.childNodes[i]);
            }
          }
        }
        fakeQuerySelector(docRoot);
        var loader = new THREE.ColladaLoader();
        loader.options.convertUpAxis = true;
        loader.options.upAxis = 'Y';
        loader.parse(docRoot, function(parsed) {
          parsed.scene.traverse(function(n) {
            if ((n.geometry instanceof THREE.BufferGeometry && !n.geometry.attributes.normals) ||
                (n.geometry instanceof THREE.Geometry && !n.geometry.faceVertexNormals)) {
              n.geometry.computeFaceNormals();
              n.geometry.computeVertexNormals();
            }
            // Convert to BufferGeometry for better loading efficiency
            if (n.geometry && n.geometry instanceof THREE.Geometry) {
              var bufgeo = new THREE.BufferGeometry().fromGeometry(n.geometry);
              n.geometry = bufgeo;
            }
          });
          data = parsed;
        }, job.data.src);

        data.scene.updateMatrix();
        resolve(data.scene.toJSON());
      }));
    },
  }, elation.engine.assets.base);
  elation.define('engine.assets.loaders.model_wrl', {
    parse: function(data, job) {
      return new Promise(function(resolve, reject) {
        var loader = new THREE.VRMLLoader();
        var modeldata = loader.parse(data);

        resolve(modeldata.toJSON());
      });
    }
  }, elation.engine.assets.base);
  elation.define('engine.assets.loaders.model_fbx', {
    parse: function(data, job) {
      return new Promise(function(resolve, reject) {
        var loader = new THREE.FBXLoader();
        var modeldata = loader.parse(data);
        resolve(modeldata.toJSON());
      });
    }
  }, elation.engine.assets.base);

});

<|endoftext|>