<commit_before>Twitter = (function(global) {
  var K = function(){}, isAndroid = Ti.Platform.osname === "android";
  var global_config = {};

  /**
   * Twitter constructor function
   *
   *     var client = Twitter({
   *       consumerKey: "INSERT YOUR KEY HERE",
   *       consumerSecret: "INSERT YOUR SECRET HERE"
   *     });
   *
   * Can be used with or without `new` keyword.
   *
   * @constructor
   * @requires jsOAuth: http://github.com/bytespider/jsOAuth
   * @param options {Object} Configuration object
   * @param options.consumerKey {String} Application consumer key
   * @param options.consumerSecret {String} Application consumer secret
   * @param options.accessTokenKey {String} (optional) The user's access token key
   * @param options.accessTokenSecret {String} (optional) The user's access token secret
   * @param [options.windowTitle="Twitter Authorization"] {String} (optional) The title to display in the authentication window
   */
  var Twitter = function(options) {
    var self;

    if (this instanceof Twitter) {
      self = this;
    } else {
      self = new K();
    }

    var accessTokenKey = Ti.App.Properties.getString('twitterAccessTokenKey'),
        accessTokenSecret = Ti.App.Properties.getString('twitterAccessTokenSecret');

    if (!options) { options = {}; }
    self.windowTitle = options.windowTitle || "Twitter Authorization";
    self.consumerKey = options.consumerKey;
    self.consumerSecret = options.consumerSecret;
    self.authorizeUrl = "https://api.twitter.com/oauth/authorize";
    self.accessTokenKey = options.accessTokenKey || accessTokenKey;
    self.accessTokenSecret = options.accessTokenSecret || accessTokenSecret;
    self.authorized = false;
    self.listeners = {};

    log2("SELF", self)

    if (self.accessTokenKey && self.accessTokenSecret) {
      self.authorized = true;
    }

    options.requestTokenUrl = options.requestTokenUrl || "https://api.twitter.com/oauth/request_token";
    self.oauthClient = jsOAuth.OAuth(options);

    return self;
  };

  Twitter.setup = function(cfg) {
    global_config = cfg;
  }

  K.prototype = Twitter.prototype;

  function createAuthWindow() {
    var self = this,
        oauth = this.oauthClient,
        webViewWindow = Ti.UI.createWindow({title: this.windowTitle}),
        webView = Ti.UI.createWebView(),
        loadingOverlay = Ti.UI.createView({
          backgroundColor: 'black',
          opacity: 0.7,
          zIndex: 1
        }),
        actInd = Titanium.UI.createActivityIndicator({
          height: 50,
          width: 10,
          message: 'Loading...',
          color: 'white'
        }),
        closeButton = Ti.UI.createButton({
          title: "Close"
        }),
        backButton = Ti.UI.createButton({
          title: "Back"
        });

    this.webView = webView;

    webViewWindow.leftNavButton = closeButton;

    actInd.show();
    loadingOverlay.add(actInd);
    webViewWindow.add(loadingOverlay);
    webViewWindow.open({modal: true});

    webViewWindow.add(webView);

    closeButton.addEventListener('click', function(e) {
      webViewWindow.close();
      self.fireEvent('cancel', {
        success: false,
        error: "The user cancelled.",
        result: null
      });
    });

    backButton.addEventListener('click', function(e) {
      webView.goBack();
    });

    webView.addEventListener('beforeload', function(e) {
      log("BEFORE LOAD!")
      if (!isAndroid) { webViewWindow.add(loadingOverlay); }
      actInd.show();
    });

    webView.addEventListener('load', function(event) {
      log("LOADED!")
      if(isAndroid) {
        actInd.hide();
        webViewWindow.remove(loadingOverlay);
      }

      log2("event.url", event.url);
      log2("self.authorizeUrl", self.authorizeUrl);
      // If we're not on the Twitter authorize page
      if (event.url.indexOf(self.authorizeUrl) === -1) {
        log("REMOVE")
        webViewWindow.remove(loadingOverlay);
        actInd.hide(); // Required for Android

        // Switch out close button for back button
        if (webViewWindow.leftNavButton !== backButton) {
          webViewWindow.leftNavButton = backButton;
        }
      } else {
        log("ELSE :(")
        // Switch out back button for close button
        if (webViewWindow.leftNavButton !== closeButton) {
          webViewWindow.leftNavButton = closeButton;
        }

        // Grab the PIN code out of the DOM
        var pin = event.source.evalJS("document.getElementById('oauth_pin').getElementsByTagName('code')[0].innerText");

        if (!pin) {
          // We're here when:
          // - "No thanks" button clicked
          // - Bad username/password

          webViewWindow.remove(loadingOverlay);
          actInd.hide();
        } else {
          if (!isAndroid) { // on iOS we can close the modal window right away
            webViewWindow.close();
          }

          oauth.accessTokenUrl = "https://api.twitter.com/oauth/access_token?oauth_verifier=" + pin;

          oauth.fetchAccessToken(function(data) {
            var returnedParams = oauth.parseTokenRequest(data.text);
            self.fireEvent('login', {
              success: true,
              error: false,
              accessTokenKey: returnedParams.oauth_token,
              accessTokenSecret: returnedParams.oauth_token_secret
            });

            Ti.App.Properties.setString('twitterAccessTokenKey', returnedParams.oauth_token);
            Ti.App.Properties.setString('twitterAccessTokenSecret', returnedParams.oauth_token_secret);
            self.authorized = true;

            if (isAndroid) { // we have to wait until now to close the modal window on Android: http://developer.appcelerator.com/question/91261/android-probelm-with-httpclient
              webViewWindow.close();
            }
          }, function(data) {
            self.fireEvent('login', {
              success: false,
              error: "Failure to fetch access token, please try again.",
              result: data
            });
          });
        }
      }
    });

  }

  /*
   * Requests the user to authorize via Twitter through a modal WebView.
   */
  Twitter.prototype.authorize = function() {
    var self = this;

    if (this.authorized) {
      // TODO: verify access tokens are still valid?

      // We're putting this fireEvent call inside setTimeout to allow
      // a user to add an event listener below the call to authorize.
      // Not totally sure if the timeout should be greater than 1. It
      // seems to do the trick on iOS/Android.
      setTimeout(function() {
        self.fireEvent('login', {
          success: true,
          error: false,
          accessTokenKey: self.accessTokenKey,
          accessTokenSecret: self.accessTokenSecret
        });
      }, 1);
    } else {
      createAuthWindow.call(this);

      this.oauthClient.fetchRequestToken(
        function(requestParams) {
          var authorizeUrl = self.authorizeUrl + requestParams;
          self.webView.url = authorizeUrl;
        },
        function(data) {
          self.fireEvent('login', {
            success: false,
            error: "Failure to fetch access token, please try again.",
            result: data
          });
        }
      );
    }
  };

  /*
   * Get client timeline added by L/R
   *
   * Returns instantiated twitter client for making calls with.
   */
  var _getClient = function() {
    var accessTokenKey = Ti.App.Properties.getString('twitterAccessTokenKey'),
           accessTokenSecret = Ti.App.Properties.getString('twitterAccessTokenSecret');

    return Twitter({consumerKey: global_config.consumerKey,
             consumerSecret: global_config.consumerSecret,
             accessTokenKey:accessTokenKey,
             accessTokenSecret:accessTokenSecret
            });
  }

  /*
   * Hacky timeline added by L/R since we didn't want it to be an auth request
   *
   * @param {Object} screen_name, timeout, limit - all optional except screen_name
   * @param {Function} callback
   */
  Twitter.timeline = function(params, callback) {
    var limit = (params.limit || 15)
    , timeout = (params.timeout || 11000)
    , name = params.screen_name
    , url = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name="+name+"&count="+limit;

    var request = function(url, fun) {
    	var xhr = Ti.Network.createHTTPClient({});
      xhr.timeout = timeout;
    	xhr.onload = fun;
      xhr.open("GET", url);
    	xhr.send();
    }

  	request(url, function(json){
  	  var tweets = eval('(' + this.responseText + ')'); // JSON.parse failed??
  	  callback(tweets);
  	});
  }

  /*
   * Favorite added by L/R.  Favorites a tweet.  Pass in tweet.id_str for it to work correctly.  Authorizes first
   *
   * @param {String} Tweet id_str property to reply to
   * @param {String} Tweet so should be under 140 or whatever it is
   * @param {Function} get e.success passed to it to check if you succeeded or not.
   */
  Twitter.reply = function(id, status, cb) {
    _getClient().authRequest(function(){ this.request("1.1/statuses/update.json", {status: status, in_reply_to_status_id: id}, "POST", cb); }, cb);
  }

  /*
   * Favorite added by L/R.  Favorites a tweet.  Authorizes first
   *
   * @param {String} Tweet id_str property of tweet to favorite
   * @param {Function} get e.success passed to it to check if you succeeded or not.
   */
  Twitter.favorite = function(id, cb) {
    _getClient().authRequest(function(){ this.request("1/favorites/create/"+id+".json", {id: id}, "POST", cb); }, cb);
  }

  /*
   * Retweet added by L/R.  Retweets. Authorizes first
   *
   * @param {String} Tweet id_str property to retweet
   * @param {Function} get e.success passed to it to check if you succeeded or not.
   */
  Twitter.retweet = function(id, cb) {
    _getClient().authRequest(function(){ this.request("1/statuses/retweet/"+id+".json", {id: id}, "POST", cb); }, cb);
  }

  /*
   * Tweet added by L/R.  Does a status update with just the text.  Authorizes first
   *
   * @param {String} Tweet so should be under 140 or whatever it is
   * @param {Function} get e.success passed to it to check if you succeeded or not.
   */
  Twitter.tweet = function(status, cb) {
    _getClient().authRequest(function(){ this.request("1.1/statuses/update.json", {status: status}, "POST", cb); }, cb);
  }

  /*
   * authRequest added by L/R.  Does a status update with just the text.  Authorizes first
   *
   * @param {Function} Function to auth beforehand
   * @param {Function} call the original callback if it fails
   */
  Twitter.prototype.authRequest = function(requestFun, callback) {
    this.addEventListener('login', function(e) {
       if (e.success) {
         Ti.App.Properties.setString('twitterAccessTokenKey', e.accessTokenKey);
         Ti.App.Properties.setString('twitterAccessTokenSecret', e.accessTokenSecret);
        requestFun.call(this);
       } else {
         alert(e.error);
       }
     });
    this.authorize();
  }

  /*
   * Make an authenticated Twitter API request.
   *
   * @param {String} path the Twitter API path without leading forward slash. For example: `1/statuses/home_timeline.json`
   * @param {Object} params  the parameters to send along with the API call
   * @param {String} [httpVerb="GET"] the HTTP verb to use
   * @param {Function} callback
   */
  Twitter.prototype.request = function(path, params, httpVerb, callback) {
    var self = this, oauth = this.oauthClient, url = "https://api.twitter.com/" + path;

    oauth.request({
      method: httpVerb,
      url: url,
      data: params,
      success: function(data) {
        callback.call(self, {
          success: true,
          error: false,
          result: data
        });
      },
      failure: function(data) {
        callback.call(self, {
          url: url,
          params: params,
          success: false,
          error: "Request failed",
          result: data
        });
      }
    });
  };

  /*
   * Add an event listener
   */
  Twitter.prototype.addEventListener = function(eventName, callback) {
    this.listeners = this.listeners || {};
    this.listeners[eventName] = this.listeners[eventName] || [];
    this.listeners[eventName].push(callback);
  };

  /*
   * Fire an event
   */
  Twitter.prototype.fireEvent = function(eventName, data) {
    var eventListeners = this.listeners[eventName] || [];
    for (var i = 0; i < eventListeners.length; i++) {
      eventListeners[i].call(this, data);
    }
  };

  return Twitter;
})(this);
<commit_msg>fix twitter android<commit_after>Twitter = (function(global) {
  var K = function(){}, isAndroid = Ti.Platform.osname === "android";
  var global_config = {};

  /**
   * Twitter constructor function
   *
   *     var client = Twitter({
   *       consumerKey: "INSERT YOUR KEY HERE",
   *       consumerSecret: "INSERT YOUR SECRET HERE"
   *     });
   *
   * Can be used with or without `new` keyword.
   *
   * @constructor
   * @requires jsOAuth: http://github.com/bytespider/jsOAuth
   * @param options {Object} Configuration object
   * @param options.consumerKey {String} Application consumer key
   * @param options.consumerSecret {String} Application consumer secret
   * @param options.accessTokenKey {String} (optional) The user's access token key
   * @param options.accessTokenSecret {String} (optional) The user's access token secret
   * @param [options.windowTitle="Twitter Authorization"] {String} (optional) The title to display in the authentication window
   */
  var Twitter = function(options) {
    var self;

    if (this instanceof Twitter) {
      self = this;
    } else {
      self = new K();
    }

    var accessTokenKey = Ti.App.Properties.getString('twitterAccessTokenKey'),
        accessTokenSecret = Ti.App.Properties.getString('twitterAccessTokenSecret');

    if (!options) { options = {}; }
    self.windowTitle = options.windowTitle || "Twitter Authorization";
    self.consumerKey = options.consumerKey;
    self.consumerSecret = options.consumerSecret;
    self.authorizeUrl = "https://api.twitter.com/oauth/authorize";
    self.accessTokenKey = options.accessTokenKey || accessTokenKey;
    self.accessTokenSecret = options.accessTokenSecret || accessTokenSecret;
    self.authorized = false;
    self.listeners = {};

    log2("SELF", self)

    if (self.accessTokenKey && self.accessTokenSecret) {
      self.authorized = true;
    }

    options.requestTokenUrl = options.requestTokenUrl || "https://api.twitter.com/oauth/request_token";
    self.oauthClient = jsOAuth.OAuth(options);

    return self;
  };

  Twitter.setup = function(cfg) {
    global_config = cfg;
  }

  K.prototype = Twitter.prototype;

  function createAuthWindow() {
    var self = this,
        oauth = this.oauthClient,
        webViewWindow = Ti.UI.createWindow({title: this.windowTitle}),
        webView = Ti.UI.createWebView(),
        loadingOverlay = Ti.UI.createView({
          backgroundColor: 'black',
          opacity: 0.7,
          zIndex: 1
        }),
        actInd = Titanium.UI.createActivityIndicator({
          height: 50,
          width: 10,
          message: 'Loading...',
          color: 'white'
        }),
        closeButton = Ti.UI.createButton({
          title: "Close"
        }),
        backButton = Ti.UI.createButton({
          title: "Back"
        });

    this.webView = webView;

    webViewWindow.leftNavButton = closeButton;

    actInd.show();
    loadingOverlay.add(actInd);
    webViewWindow.add(loadingOverlay);
    webViewWindow.open({modal: true});

    webViewWindow.add(webView);

    closeButton.addEventListener('click', function(e) {
      webViewWindow.close();
      self.fireEvent('cancel', {
        success: false,
        error: "The user cancelled.",
        result: null
      });
    });

    backButton.addEventListener('click', function(e) {
      webView.goBack();
    });

    webView.addEventListener('beforeload', function(e) {
      log("BEFORE LOAD!")
      if (!isAndroid) {
        webViewWindow.add(loadingOverlay);
        actInd.show();
      }
    });

    webView.addEventListener('load', function(event) {
      log("LOADED!")
      if(isAndroid) {
        actInd.hide();
        webViewWindow.remove(loadingOverlay);
      }

      log2("event.url", event.url);
      log2("self.authorizeUrl", self.authorizeUrl);
      // If we're not on the Twitter authorize page
      if (event.url.indexOf(self.authorizeUrl) === -1) {
        log("REMOVE")
        webViewWindow.remove(loadingOverlay);
        actInd.hide(); // Required for Android

        // Switch out close button for back button
        if (webViewWindow.leftNavButton !== backButton) {
          webViewWindow.leftNavButton = backButton;
        }
      } else {
        log("ELSE :(")
        // Switch out back button for close button
        if (webViewWindow.leftNavButton !== closeButton) {
          webViewWindow.leftNavButton = closeButton;
        }

        // Grab the PIN code out of the DOM
        var pin = event.source.evalJS("document.getElementById('oauth_pin').getElementsByTagName('code')[0].innerText");

        if (!pin) {
          // We're here when:
          // - "No thanks" button clicked
          // - Bad username/password

          webViewWindow.remove(loadingOverlay);
          actInd.hide();
        } else {
          if (!isAndroid) { // on iOS we can close the modal window right away
            webViewWindow.close();
          }

          oauth.accessTokenUrl = "https://api.twitter.com/oauth/access_token?oauth_verifier=" + pin;

          oauth.fetchAccessToken(function(data) {
            var returnedParams = oauth.parseTokenRequest(data.text);
            self.fireEvent('login', {
              success: true,
              error: false,
              accessTokenKey: returnedParams.oauth_token,
              accessTokenSecret: returnedParams.oauth_token_secret
            });

            Ti.App.Properties.setString('twitterAccessTokenKey', returnedParams.oauth_token);
            Ti.App.Properties.setString('twitterAccessTokenSecret', returnedParams.oauth_token_secret);
            self.authorized = true;

            if (isAndroid) { // we have to wait until now to close the modal window on Android: http://developer.appcelerator.com/question/91261/android-probelm-with-httpclient
              webViewWindow.close();
            }
          }, function(data) {
            self.fireEvent('login', {
              success: false,
              error: "Failure to fetch access token, please try again.",
              result: data
            });
          });
        }
      }
    });

  }

  /*
   * Requests the user to authorize via Twitter through a modal WebView.
   */
  Twitter.prototype.authorize = function() {
    var self = this;

    if (this.authorized) {
      // TODO: verify access tokens are still valid?

      // We're putting this fireEvent call inside setTimeout to allow
      // a user to add an event listener below the call to authorize.
      // Not totally sure if the timeout should be greater than 1. It
      // seems to do the trick on iOS/Android.
      setTimeout(function() {
        self.fireEvent('login', {
          success: true,
          error: false,
          accessTokenKey: self.accessTokenKey,
          accessTokenSecret: self.accessTokenSecret
        });
      }, 1);
    } else {
      createAuthWindow.call(this);

      this.oauthClient.fetchRequestToken(
        function(requestParams) {
          var authorizeUrl = self.authorizeUrl + requestParams;
          self.webView.url = authorizeUrl;
        },
        function(data) {
          self.fireEvent('login', {
            success: false,
            error: "Failure to fetch access token, please try again.",
            result: data
          });
        }
      );
    }
  };

  /*
   * Get client timeline added by L/R
   *
   * Returns instantiated twitter client for making calls with.
   */
  var _getClient = function() {
    var accessTokenKey = Ti.App.Properties.getString('twitterAccessTokenKey'),
           accessTokenSecret = Ti.App.Properties.getString('twitterAccessTokenSecret');

    return Twitter({consumerKey: global_config.consumerKey,
             consumerSecret: global_config.consumerSecret,
             accessTokenKey:accessTokenKey,
             accessTokenSecret:accessTokenSecret
            });
  }

  /*
   * Hacky timeline added by L/R since we didn't want it to be an auth request
   *
   * @param {Object} screen_name, timeout, limit - all optional except screen_name
   * @param {Function} callback
   */
  Twitter.timeline = function(params, callback) {
    var limit = (params.limit || 15)
    , timeout = (params.timeout || 11000)
    , name = params.screen_name
    , url = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name="+name+"&count="+limit;

    var request = function(url, fun) {
    	var xhr = Ti.Network.createHTTPClient({});
      xhr.timeout = timeout;
    	xhr.onload = fun;
      xhr.open("GET", url);
    	xhr.send();
    }

  	request(url, function(json){
  	  var tweets = eval('(' + this.responseText + ')'); // JSON.parse failed??
  	  callback(tweets);
  	});
  }

  /*
   * Favorite added by L/R.  Favorites a tweet.  Pass in tweet.id_str for it to work correctly.  Authorizes first
   *
   * @param {String} Tweet id_str property to reply to
   * @param {String} Tweet so should be under 140 or whatever it is
   * @param {Function} get e.success passed to it to check if you succeeded or not.
   */
  Twitter.reply = function(id, status, cb) {
    _getClient().authRequest(function(){ this.request("1.1/statuses/update.json", {status: status, in_reply_to_status_id: id}, "POST", cb); }, cb);
  }

  /*
   * Favorite added by L/R.  Favorites a tweet.  Authorizes first
   *
   * @param {String} Tweet id_str property of tweet to favorite
   * @param {Function} get e.success passed to it to check if you succeeded or not.
   */
  Twitter.favorite = function(id, cb) {
    _getClient().authRequest(function(){ this.request("1/favorites/create/"+id+".json", {id: id}, "POST", cb); }, cb);
  }

  /*
   * Retweet added by L/R.  Retweets. Authorizes first
   *
   * @param {String} Tweet id_str property to retweet
   * @param {Function} get e.success passed to it to check if you succeeded or not.
   */
  Twitter.retweet = function(id, cb) {
    _getClient().authRequest(function(){ this.request("1/statuses/retweet/"+id+".json", {id: id}, "POST", cb); }, cb);
  }

  /*
   * Tweet added by L/R.  Does a status update with just the text.  Authorizes first
   *
   * @param {String} Tweet so should be under 140 or whatever it is
   * @param {Function} get e.success passed to it to check if you succeeded or not.
   */
  Twitter.tweet = function(status, cb) {
    _getClient().authRequest(function(){ this.request("1.1/statuses/update.json", {status: status}, "POST", cb); }, cb);
  }

  /*
   * authRequest added by L/R.  Does a status update with just the text.  Authorizes first
   *
   * @param {Function} Function to auth beforehand
   * @param {Function} call the original callback if it fails
   */
  Twitter.prototype.authRequest = function(requestFun, callback) {
    this.addEventListener('login', function(e) {
       if (e.success) {
         Ti.App.Properties.setString('twitterAccessTokenKey', e.accessTokenKey);
         Ti.App.Properties.setString('twitterAccessTokenSecret', e.accessTokenSecret);
        requestFun.call(this);
       } else {
         alert(e.error);
       }
     });
    this.authorize();
  }

  /*
   * Make an authenticated Twitter API request.
   *
   * @param {String} path the Twitter API path without leading forward slash. For example: `1/statuses/home_timeline.json`
   * @param {Object} params  the parameters to send along with the API call
   * @param {String} [httpVerb="GET"] the HTTP verb to use
   * @param {Function} callback
   */
  Twitter.prototype.request = function(path, params, httpVerb, callback) {
    var self = this, oauth = this.oauthClient, url = "https://api.twitter.com/" + path;

    oauth.request({
      method: httpVerb,
      url: url,
      data: params,
      success: function(data) {
        callback.call(self, {
          success: true,
          error: false,
          result: data
        });
      },
      failure: function(data) {
        callback.call(self, {
          url: url,
          params: params,
          success: false,
          error: "Request failed",
          result: data
        });
      }
    });
  };

  /*
   * Add an event listener
   */
  Twitter.prototype.addEventListener = function(eventName, callback) {
    this.listeners = this.listeners || {};
    this.listeners[eventName] = this.listeners[eventName] || [];
    this.listeners[eventName].push(callback);
  };

  /*
   * Fire an event
   */
  Twitter.prototype.fireEvent = function(eventName, data) {
    var eventListeners = this.listeners[eventName] || [];
    for (var i = 0; i < eventListeners.length; i++) {
      eventListeners[i].call(this, data);
    }
  };

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


<commit_before>function InitView() {

	// create object instance
	var self = Ti.UI.createWindow({
		title:'Login',
	    width: '100%',
	    height: '100%',
		backgroundColor:'#ffffff',
	});

	var containerView = Ti.UI.createView({
		backgroundColor: 'transparent',
		width: '90%',
		height: '90%',
		top: '5%',
		left: '5%',
		layout: 'vertical'
	});
	self.add(containerView);

	var logoImage = Titanium.UI.createImageView({
	  image:'/zwarm-logo.png',
	  top: '7%'
	});
	containerView.add(logoImage);

	var nicknameLabel = Titanium.UI.createLabel({
		color:'#000000',
		text:'Please enter a nickname',
		font:{fontSize:30, fontFamily:'Helvetica Neue'},
		textAlign:'center',
		width:Ti.UI.FILL,
		height:Ti.UI.SIZE,
		top: '7%'
	});
	containerView.add(nicknameLabel);

	var nicknameInput = Ti.UI.createTextField({
		width:Ti.UI.FILL,
		height:Ti.UI.SIZE,
		top: '7%',
		hintText: 'anonymous'
	});
	containerView.add(nicknameInput);

	var initButton = Ti.UI.createButton({
		title: 'Go!',
		width: Ti.UI.FILL,
		top: '7%',
	});
	initButton.addEventListener('click', function(event) {
		var user = {
			id: Ti.Platform.createUUID(),
			nickname: getNickname(),
			platform: getPlatform(),
			notificationToken: getNotificationToken(),
		}

	    // call server
		var SwarmClient = require('/network/SwarmClient');
		var swarmClient = new SwarmClient();
		swarmClient.addUser(user, function(userJSON) {
			// set properties
			Ti.App.Properties.setString('user.id', userJSON.id);
			Ti.App.Properties.setString('user.name', userJSON.name);
			self.close();
		});

	});
	containerView.add(initButton);

	var getNickname = function() {
		var nickname = nicknameInput.value.trim();
		if (nickname.length == 0) {
			nickname = nicknameInput.hintText;
		}
		return nickname;
	}
	var getPlatform = function() {
		var platform = 'unknown';

		var osname = Ti.Platform.osname;
		if ((osname === 'iphone') || (osname === 'ipad')) {
			platform = 'ios';
		} else if (osname === 'android') {
			platform = 'android';
		}

		return platform;
	}
	var getNotificationToken = function() {
		var notificationToken = 'unknown';
		if (Ti.App.Properties.hasProperty('user.notificationToken')) {
			notificationToken = Ti.App.Properties.getString('user.notificationToken');
		}
		return notificationToken;
	}

	return self;
};

module.exports = InitView;<commit_msg>Send empty notification token and not "unknown"<commit_after>function InitView() {

	// create object instance
	var self = Ti.UI.createWindow({
		title:'Login',
	    width: '100%',
	    height: '100%',
		backgroundColor:'#ffffff',
	});

	var containerView = Ti.UI.createView({
		backgroundColor: 'transparent',
		width: '90%',
		height: '90%',
		top: '5%',
		left: '5%',
		layout: 'vertical'
	});
	self.add(containerView);

	var logoImage = Titanium.UI.createImageView({
	  image:'/zwarm-logo.png',
	  top: '7%'
	});
	containerView.add(logoImage);

	var nicknameLabel = Titanium.UI.createLabel({
		color:'#000000',
		text:'Please enter a nickname',
		font:{fontSize:30, fontFamily:'Helvetica Neue'},
		textAlign:'center',
		width:Ti.UI.FILL,
		height:Ti.UI.SIZE,
		top: '7%'
	});
	containerView.add(nicknameLabel);

	var nicknameInput = Ti.UI.createTextField({
		width:Ti.UI.FILL,
		height:Ti.UI.SIZE,
		top: '7%',
		hintText: 'anonymous'
	});
	containerView.add(nicknameInput);

	var initButton = Ti.UI.createButton({
		title: 'Go!',
		width: Ti.UI.FILL,
		top: '7%',
	});
	initButton.addEventListener('click', function(event) {
		var user = {
			id: Ti.Platform.createUUID(),
			nickname: getNickname(),
			platform: getPlatform(),
			notificationToken: getNotificationToken(),
		}

	    // call server
		var SwarmClient = require('/network/SwarmClient');
		var swarmClient = new SwarmClient();
		swarmClient.addUser(user, function(userJSON) {
			// set properties
			Ti.App.Properties.setString('user.id', userJSON.id);
			Ti.App.Properties.setString('user.name', userJSON.name);
			self.close();
		});

	});
	containerView.add(initButton);

	var getNickname = function() {
		var nickname = nicknameInput.value.trim();
		if (nickname.length == 0) {
			nickname = nicknameInput.hintText;
		}
		return nickname;
	}
	var getPlatform = function() {
		var platform = 'unknown';

		var osname = Ti.Platform.osname;
		if ((osname === 'iphone') || (osname === 'ipad')) {
			platform = 'ios';
		} else if (osname === 'android') {
			platform = 'android';
		}

		return platform;
	}
	var getNotificationToken = function() {
		var notificationToken = '';
		if (Ti.App.Properties.hasProperty('user.notificationToken')) {
			notificationToken = Ti.App.Properties.getString('user.notificationToken');
		}
		return notificationToken;
	}

	return self;
};

module.exports = InitView;<|endoftext|>


<commit_before>'use strict'
const fs = require('fs');
const readline = require('readline');
const google = require('googleapis');
const OAuth2 = google.auth.OAuth2;
const async = require('async');

const SCOPES = ['https://mail.google.com/'];
const TOKEN_DIR = (process.env.HOME ||
    process.env.HOMEPATH ||
    process.env.USERPROFILE) + '/.credentials/';

/** Working as currently intended **/
function readSecret(callback) {
    fs.readFile(__dirname + '/gmail_client_secret.json', function(err, content) {
        if (err) {
            throw err;
        } else {
            console.log('\tREAD SECRET > ' + JSON.stringify(JSON.parse(content)));
            callback(null, JSON.parse(content));
        }
    });
}

function readToken(callback) {
    fs.readFile(TOKEN_DIR + 'test.json', function(err, token) {
        if (err) {
            if (err.code != 'ENOENT') {
                throw err;
            }
            console.log('\tREAD TOKEN > User has not authenticated a google account yet.');
            callback(err);
        } else {
            console.log('\tREAD TOKEN > ' + JSON.stringify(JSON.parse(token)));
            callback(null, JSON.parse(token));
        }
    });
}

function storeToken(token) {
    try {
        fs.mkdirSync(TOKEN_DIR);
    } catch (err) {
        if (err.code != 'EEXIST') {
            throw err;
        }
    }
    fs.writeFile(TOKEN_DIR + 'test.json', JSON.stringify(token));
    console.log('\tstoreToken > ' + TOKEN_DIR + 'test.json\t' + JSON.stringify(token));
}

function getOAuth2Client() {
    let promise = new Promise(function(resolve, reject) {
        async.series([
            (callback) => {
                readSecret(callback);
            },
            (callback) => {
                readToken(callback);
            }
        ], (err, results) => {
            let secret = results[0];
            let token = results[1];

            let oauth2Client = new OAuth2(
                secret.installed.client_id,
                secret.installed.client_secret,
                secret.installed.redirect_uris[0]
            );

            if (!err) {
                oauth2Client.credentials = token;
            }

            console.log('\tCREATED AUTH CLIENT > ' + JSON.stringify(oauth2Client));
            resolve(oauth2Client);
        });
    });
    return promise;
}

module.exports = {

    requestAuthUrl: function(callback) {
        getOAuth2Client().then(function(oauth2Client) {
            let url = oauth2Client.generateAuthUrl({
                access_type: 'offline',
                scope: SCOPES
            });

            console.log('\tURL GENERATED > ' + url);
            callback(url);
        }).catch(function(err) {
            throw err;
        });
    },

    writeToken: function(token) {
        storeToken(token);
    },

    getAuthorizedOAuth2Client: function(callback) {
        return getOAuth2Client();
    }

};
<commit_msg>accidentally removed code to retrieve token<commit_after>'use strict'
const fs = require('fs');
const readline = require('readline');
const google = require('googleapis');
const OAuth2 = google.auth.OAuth2;
const async = require('async');

const SCOPES = ['https://mail.google.com/'];
const TOKEN_DIR = (process.env.HOME ||
    process.env.HOMEPATH ||
    process.env.USERPROFILE) + '/.credentials/';

/** Working as currently intended **/
function readSecret(callback) {
    fs.readFile(__dirname + '/gmail_client_secret.json', function(err, content) {
        if (err) {
            throw err;
        } else {
            console.log('\tREAD SECRET > ' + JSON.stringify(JSON.parse(content)));
            callback(null, JSON.parse(content));
        }
    });
}

function readToken(callback) {
    fs.readFile(TOKEN_DIR + 'test.json', function(err, token) {
        if (err) {
            if (err.code != 'ENOENT') {
                throw err;
            }
            console.log('\tREAD TOKEN > User has not authenticated a google account yet.');
            callback(err);
        } else {
            console.log('\tREAD TOKEN > ' + JSON.stringify(JSON.parse(token)));
            callback(null, JSON.parse(token));
        }
    });
}

function storeToken(token) {
    console.log('storeToken(token) > CALLED');
    try {
        fs.mkdirSync(TOKEN_DIR);
    } catch (err) {
        if (err.code != 'EEXIST') {
            throw err;
        }
    }
    fs.writeFile(TOKEN_DIR + 'test.json', JSON.stringify(token));
    console.log('\tstoreToken > ' + TOKEN_DIR + 'test.json\t' + JSON.stringify(token));
}

function getOAuth2Client() {
    let promise = new Promise(function(resolve, reject) {
        async.series([
            (callback) => {
                readSecret(callback);
            },
            (callback) => {
                readToken(callback);
            }
        ], (err, results) => {
            let secret = results[0];
            let token = results[1];

            let oauth2Client = new OAuth2(
                secret.installed.client_id,
                secret.installed.client_secret,
                secret.installed.redirect_uris[0]
            );

            if (!err) {
                oauth2Client.credentials = token;
            }

            console.log('\tCREATED AUTH CLIENT > ' + JSON.stringify(oauth2Client));
            resolve(oauth2Client);
        });
    });
    return promise;
}

module.exports = {

    requestAuthUrl: function(callback) {
        getOAuth2Client().then(function(oauth2Client) {
            let url = oauth2Client.generateAuthUrl({
                access_type: 'offline',
                scope: SCOPES
            });

            console.log('\tURL GENERATED > ' + url);
            callback(url);
        }).catch(function(err) {
            throw err;
        });
    },

    requestToken: function(code) {
        let promise = new Promise(function(resolve, reject) {
            getOAuth2Client().then(function(oauth2Client) {
                oauth2Client.getToken(code, function(err, token) {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(token);
                    }
                });
            });
        });
        return promise;
    },

    writeToken: function(token) {
        storeToken(token);
    },

    getAuthorizedOAuth2Client: function(callback) {
        return getOAuth2Client();
    }

};
<|endoftext|>


<commit_before>(function () {

function game_over() {
	setTimeout(function () {
		location.reload(true);
	}, 2000);
	$DOC.children().remove();
}

function shut_down_everything() {
	var $threads = $('section');
	if (!$threads.length)
		return setTimeout(game_over, 1000);
	pick_random($threads, 0.2).remove();
	pick_random($('hr, aside, h1, fieldset'), 0.2).remove();
	setTimeout(shut_down_everything, 500);
}

function shut_down_something() {
	var $posts = $('article');
	if (!$posts.length)
		return setTimeout(shut_down_everything, 500);
	var $posts = pick_random($posts, 0.1);
	$posts.each(function () {
		var num = extract_num($(this));
		if (CurThread) {
			try {
				clear_post_links(lookup_post(num));
			}
			catch (e) {}
		}
	});
	$posts.remove();
	if (Math.random() < 0.2)
		pick_random($('figure, blockquote, b'), 0.002).remove();
	setTimeout(shut_down_something, 500);
}

var tearingDown = false;
dispatcher[TEARDOWN] = function () {
	if (tearingDown)
		return;
	tearingDown = true;
	window.onbeforeunload = null;
	shut_down_something();
};

function pick_random($items, proportion) {
	var len = $items.length;
	var origLen = len;
	var toDelete = Math.max(1, Math.min(len, Math.ceil(len * proportion)));
	var $picked = $();
	for (; len > 0 && toDelete > 0; toDelete--) {
		var i = Math.floor(Math.random() * len);
		$picked = $picked.add($items[i]);
		$items.splice(i, 1);
		len = $items.length;
	}
	return $picked;
}

})();
<commit_msg>Fix curfew teardown<commit_after>(function () {

function game_over() {
	setTimeout(function () {
		location.reload(true);
	}, 2000);
	$DOC.children().remove();
}

function shut_down_everything() {
	var $threads = $('section');
	if (!$threads.length)
		return setTimeout(game_over, 1000);
	pick_random($threads, 0.2).remove();
	pick_random($('hr, aside, h1, fieldset'), 0.2).remove();
	setTimeout(shut_down_everything, 500);
}

function shut_down_something() {
	var $posts = $('article');
	if (!$posts.length)
		return setTimeout(shut_down_everything, 500);
	var $posts = pick_random($posts, 0.1);
	$posts.each(function () {
		var $post = $(this);
		var $section = $post.closest('section');
		try {
			var thread = Threads.get(extract_num($section));
			var replies = thread.get('replies');
			var num = extract_num($post);
			clear_post_links(replies.get(num), replies);
		}
		catch (e) {}
	});
	$posts.remove();
	if (Math.random() < 0.2)
		pick_random($('figure, blockquote, b'), 0.002).remove();
	setTimeout(shut_down_something, 500);
}

var tearingDown = false;
dispatcher[TEARDOWN] = function () {
	if (tearingDown)
		return;
	tearingDown = true;
	window.onbeforeunload = null;
	shut_down_something();
};

function pick_random($items, proportion) {
	var len = $items.length;
	var origLen = len;
	var toDelete = Math.max(1, Math.min(len, Math.ceil(len * proportion)));
	var $picked = $();
	for (; len > 0 && toDelete > 0; toDelete--) {
		var i = Math.floor(Math.random() * len);
		$picked = $picked.add($items[i]);
		$items.splice(i, 1);
		len = $items.length;
	}
	return $picked;
}

})();
<|endoftext|>


<commit_before>function pigLatin(string) {
  var result;

  console.log(!/^[a-zA-Z]+$/.test(string));
  if (!/^[a-zA-Z]+$/.test(string)) {
    result = null;
  }
  else if (/^[aeiou]/.test(string)) {
    result = string + 'way';
  }
  else {

  }

  return result;
}
<commit_msg>Initial Commit<commit_after>function pigLatin(string) {
  var result;

  console.log(!/^[a-zA-Z]+$/.test(string));
  if (!/^[a-zA-Z]+$/.test(string)) {
    result = null;
  }
  else if (/^[aeiou]/.test(string)) {
    result = string + 'way';
  }
  else {

  }

  return result;
}<|endoftext|>


<commit_before>module.exports = (client, message, args) => {

    { let numArray = args.map(n=> parseFloat(n));  let total = numArray.reduce( (p,c) => p/c>>0); message.channel.sendMessage(total); }

  };<commit_msg><commit_after>module.exports = (client, message, args) => {

    { let numArray = args.map(n=> parseFloat(n));  let total = numArray.reduce( (p,c) => ~~(p/c)); message.channel.sendMessage(total); }

  };<|endoftext|>


<commit_before>module.exports = Cmds.addCommand({
	cmds: [";run ", ";exec ", ";eval "],

	requires: {
		guild: false,
		loud: false
	},

	desc: "Execute JavaScript code",

	args: "[code]",

	example: "return 5*2;",

	///////////////////////////////////////////////////////////////////////////////////////////

	func: (cmd, args, msgObj, speaker, channel, guild) => {
		args = "(function() {\n" + args + "\n})()";
		var outStr = ["**Output:**"];
		var result = eval(args);
		console.log("Eval result: " + result);
		outStr.push("```");
		outStr.push(result);
		outStr.push("```");
		if (result != null) Util.print(channel, outStr.join("\n"));
	}
});<commit_msg>Changed eval type check<commit_after>module.exports = Cmds.addCommand({
	cmds: [";run ", ";exec ", ";eval "],

	requires: {
		guild: false,
		loud: false
	},

	desc: "Execute JavaScript code",

	args: "[code]",

	example: "return 5*2;",

	///////////////////////////////////////////////////////////////////////////////////////////

	func: (cmd, args, msgObj, speaker, channel, guild) => {
		args = "(function() {\n" + args + "\n})()";
		var outStr = ["**Output:**"];
		var result = eval(args);
		console.log("Eval result: " + result);
		outStr.push("```");
		outStr.push(result);
		outStr.push("```");
		if (result !== undefined) Util.print(channel, outStr.join("\n"));
	}
});<|endoftext|>


<commit_before>/*
 * CutJS
 * Copyright (c) 2013-2014 Ali Shakiba, Piqnt LLC and other contributors
 * Available under the MIT license
 * @license
 */

DEBUG = (typeof DEBUG === 'undefined' || DEBUG) && console;

/**
 * Cordova/PhoneGap FastCanvas plugin loader.
 */

window.addEventListener("load", function() {
  DEBUG && console.log("On load.");
  Cut.Loader.start();
}, false);

Cut.Loader = {
  start : function() {
    if (this.started) {
      return;
    }
    this.started = true;
    // device ready not called; must be in a browser
    var readyTimeout = setTimeout(function() {
      DEBUG && console.log("On deviceready timeout.");
      Cut.Loader.play();
    }, 2000);

    document.addEventListener("deviceready", function() {
      DEBUG && console.log("On deviceready.");
      clearTimeout(readyTimeout);
      Cut.Loader.play();
    }, false);

    document.addEventListener("pause", function() {
      Cut.Loader.pause();
    }, false);

    document.addEventListener("resume", function() {
      Cut.Loader.resume();
    }, false);
  },
  play : function() {
    this.played = true;
    for (var i = this.loaders.length - 1; i >= 0; i--) {
      this.roots.push(this.loaders[i]());
      this.loaders.splice(i, 1);
    }
  },
  pause : function() {
    for (var i = this.loaders.length - 1; i >= 0; i--) {
      this.roots[i].pause();
    }
  },
  resume : function() {
    for (var i = this.loaders.length - 1; i >= 0; i--) {
      this.roots[i].resume();
    }
  },
  loaders : [],
  roots : [],
  load : function(app, canvas) {
    function loader() {
      var context = null;
      var width = 0, height = 0, ratio = 1;

      DEBUG && console.log("Creating root...");
      var root = Cut.root(function(root) {
        context.setTransform(1, 0, 0, 1, 0, 0);
        context.clearRect(0, 0, width, height);
        root.render(context);
        FastCanvas.render();
      }, requestAnimationFrame);

      canvas = FastCanvas.create(typeof FASTCANVAS_FALLBACK !== "undefined"
          && FASTCANVAS_FALLBACK);
      console.log("FastCanvas: " + FastCanvas.isFast);

      DEBUG && console.log("Loading images...");
      Cut.loadImages(function(src, handleComplete, handleError) {
        var image = FastCanvas.createImage();
        DEBUG
            && console.log("Loading image: " + src
                + (image.id ? (", ID: " + image.id) : ""));
        image.onload = handleComplete;
        image.onerror = handleError;
        image.src = src;
        return image;
      }, init);

      function init() {
        DEBUG && console.log("Images loaded.");

        context = canvas.getContext("2d");

        var devicePixelRatio = window.devicePixelRatio || 1;
        var backingStoreRatio = context.webkitBackingStorePixelRatio
            || context.mozBackingStorePixelRatio
            || context.msBackingStorePixelRatio
            || context.oBackingStorePixelRatio
            || context.backingStorePixelRatio || 1;
        ratio = devicePixelRatio / backingStoreRatio;

        DEBUG && console.log("Loading...");
        app(root, document);

        resize();
        window.addEventListener("resize", resize, false);

        DEBUG && console.log("Start playing...");
        root.start();
      }

      function resize() {

        width = window.innerWidth;
        height = window.innerHeight;

        if (!FastCanvas.isFast) {
          canvas.style.width = width + "px";
          canvas.style.height = height + "px";
        }

        DEBUG && console.log("Size: " + width + " x " + height + " / " + ratio);

        width *= ratio;
        height *= ratio;

        if (!FastCanvas.isFast) {
          canvas.width = width;
          canvas.height = height;
        }

        root.ratio = ratio;

        DEBUG
            && console.log("Resize: " + width + " x " + height + " / " + ratio);

        root.visit({
          start : function(cut) {
            var stop = true;
            var listeners = cut.listeners("resize");
            if (listeners) {
              for (var l = 0; l < listeners.length; l++)
                stop &= !listeners[l].call(cut, width, height);
            }
            return stop;
          }
        });
      }

      return root;
    }

    if (this.played) {
      this.roots.push(loader());
    } else {
      this.loaders.push(loader);
    }

  }
};

!function() {
  var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  for (var v = 0; v < vendors.length && !window.requestAnimationFrame; v++) {
    var vendor = vendors[v];
    window.requestAnimationFrame = window[vendor + 'RequestAnimationFrame'];
    window.cancelAnimationFrame = window[vendor + 'CancelAnimationFrame']
        || window[vendor + 'CancelRequestAnimationFrame'];
  }
  if (!window.requestAnimationFrame) {
    var next = 0;
    window.requestAnimationFrame = function(callback) {
      var now = new Date().getTime();
      next = Math.max(next + 16, now);
      return window.setTimeout(function() {
        callback(next);
      }, next - now);
    };
  }
  if (!window.cancelAnimationFrame) {
    window.cancelAnimationFrame = function(id) {
      clearTimeout(id);
    };
  }

  var nop = function() {
  };
  document.addEventListener("touchstart", nop);
  document.addEventListener("mousedown", nop);
  document.addEventListener("touchend", nop);
  document.addEventListener("mouseup", nop);
  document.addEventListener("click", nop);
}();<commit_msg>fix fc<commit_after>/*
 * CutJS
 * Copyright (c) 2013-2014 Ali Shakiba, Piqnt LLC and other contributors
 * Available under the MIT license
 * @license
 */

DEBUG = (typeof DEBUG === 'undefined' || DEBUG) && console;

/**
 * Cordova/PhoneGap FastCanvas plugin loader.
 */

window.addEventListener("load", function() {
  DEBUG && console.log("On load.");
  Cut.Loader.start();
}, false);

Cut.Loader = {
  start : function() {
    if (this.started) {
      return;
    }
    this.started = true;
    // device ready not called; must be in a browser
    var readyTimeout = setTimeout(function() {
      DEBUG && console.log("On deviceready timeout.");
      Cut.Loader.play();
    }, 2000);

    document.addEventListener("deviceready", function() {
      DEBUG && console.log("On deviceready.");
      clearTimeout(readyTimeout);
      Cut.Loader.play();
    }, false);

    document.addEventListener("pause", function() {
      Cut.Loader.pause();
    }, false);

    document.addEventListener("resume", function() {
      Cut.Loader.resume();
    }, false);
  },
  play : function() {
    this.played = true;
    for (var i = this.loaders.length - 1; i >= 0; i--) {
      this.roots.push(this.loaders[i]());
      this.loaders.splice(i, 1);
    }
  },
  pause : function() {
    for (var i = this.loaders.length - 1; i >= 0; i--) {
      this.roots[i].pause();
    }
  },
  resume : function() {
    for (var i = this.loaders.length - 1; i >= 0; i--) {
      this.roots[i].resume();
    }
  },
  loaders : [],
  roots : [],
  load : function(app, canvas) {
    function loader() {
      var context = null;
      var width = 0, height = 0, ratio = 1;

      DEBUG && console.log("Creating root...");
      var root = Cut.root(function(root) {
        context.setTransform(1, 0, 0, 1, 0, 0);
        context.clearRect(0, 0, width, height);
        root.render(context);
        FastCanvas.render();
      }, function(callback) {
        window.requestAnimationFrame(callback);
      });

      canvas = FastCanvas.create(typeof FASTCANVAS_FALLBACK !== "undefined"
          && FASTCANVAS_FALLBACK);
      console.log("FastCanvas: " + FastCanvas.isFast);

      DEBUG && console.log("Loading images...");
      Cut.loadImages(function(src, handleComplete, handleError) {
        var image = FastCanvas.createImage();
        DEBUG
            && console.log("Loading image: " + src
                + (image.id ? (", ID: " + image.id) : ""));
        image.onload = handleComplete;
        image.onerror = handleError;
        image.src = src;
        return image;
      }, init);

      function init() {
        DEBUG && console.log("Images loaded.");

        context = canvas.getContext("2d");

        var devicePixelRatio = window.devicePixelRatio || 1;
        var backingStoreRatio = context.webkitBackingStorePixelRatio
            || context.mozBackingStorePixelRatio
            || context.msBackingStorePixelRatio
            || context.oBackingStorePixelRatio
            || context.backingStorePixelRatio || 1;
        ratio = devicePixelRatio / backingStoreRatio;

        DEBUG && console.log("Loading...");
        app(root, document);

        resize();
        window.addEventListener("resize", resize, false);

        DEBUG && console.log("Start playing...");
        root.start();
      }

      function resize() {

        width = window.innerWidth;
        height = window.innerHeight;

        if (!FastCanvas.isFast) {
          canvas.style.width = width + "px";
          canvas.style.height = height + "px";
        }

        DEBUG && console.log("Size: " + width + " x " + height + " / " + ratio);

        width *= ratio;
        height *= ratio;

        if (!FastCanvas.isFast) {
          canvas.width = width;
          canvas.height = height;
        }

        root.ratio = ratio;

        DEBUG
            && console.log("Resize: " + width + " x " + height + " / " + ratio);

        root.visit({
          start : function(cut) {
            var stop = true;
            var listeners = cut.listeners("resize");
            if (listeners) {
              for (var l = 0; l < listeners.length; l++)
                stop &= !listeners[l].call(cut, width, height);
            }
            return stop;
          }
        });
      }

      return root;
    }

    if (this.played) {
      this.roots.push(loader());
    } else {
      this.loaders.push(loader);
    }

  }
};

!function() {
  var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  for (var v = 0; v < vendors.length && !window.requestAnimationFrame; v++) {
    var vendor = vendors[v];
    window.requestAnimationFrame = window[vendor + 'RequestAnimationFrame'];
    window.cancelAnimationFrame = window[vendor + 'CancelAnimationFrame']
        || window[vendor + 'CancelRequestAnimationFrame'];
  }
  if (!window.requestAnimationFrame) {
    var next = 0;
    window.requestAnimationFrame = function(callback) {
      var now = new Date().getTime();
      next = Math.max(next + 16, now);
      return window.setTimeout(function() {
        callback(next);
      }, next - now);
    };
  }
  if (!window.cancelAnimationFrame) {
    window.cancelAnimationFrame = function(id) {
      clearTimeout(id);
    };
  }

  var nop = function() {
  };
  document.addEventListener("touchstart", nop);
  document.addEventListener("mousedown", nop);
  document.addEventListener("touchend", nop);
  document.addEventListener("mouseup", nop);
  document.addEventListener("click", nop);
}();<|endoftext|>


<commit_before>// RockUp
// Commands-Deply -- Push code and configuration to target servers

var Config = require('../lib/Config');
var RockUtil = require('./util');

module.exports = DeployCommand;

function DeployCommand (program) {
  program
    .command("deploy <environment>")
    .alias("push")
    .description("Deploy application to environment")
    .option("--host <name>", "The specific host to target")
    .option("--bundle <path>", "Deploy a bundle.tar.gz already in-hand")
    .action( function(env, cliOptions) {
        var config = Config._loadLocalConfigFile(env);
        cliOptions = cliOptions || {};
        var options = {};
        if ( cliOptions.host )
          options.hosts = [cliOptions.host];            // Target a single host
        if ( cliOptions.bundle )
          options.bundle = cliOptions.bundle;           // Use an already-tarred app bundle
        var deployment = new Deploy(config, options);
        deployment.push( RockUtil._endCommandCallback("Deployment") );
    });

  return program;
}
<commit_msg>require lib/Deploy in DeployCommand CLI<commit_after>// RockUp
// Commands-Deploy -- Push code and configuration to target servers

var RockUtil = require('./util');
var Config = require('../lib/Config');
var Deploy = require('../lib/Deploy');

module.exports = DeployCommand;

function DeployCommand (program) {
  program
    .command("deploy <environment>")
    .alias("push")
    .description("Deploy application to environment")
    .option("--host <name>", "The specific host to target")
    .option("--bundle <path>", "Deploy a bundle.tar.gz already in-hand")
    .action( function(env, cliOptions) {
        var config = Config._loadLocalConfigFile(env);
        cliOptions = cliOptions || {};
        var options = {};
        if ( cliOptions.host )
          options.hosts = [cliOptions.host];            // Target a single host
        if ( cliOptions.bundle )
          options.bundle = cliOptions.bundle;           // Use an already-tarred app bundle
        var deployment = new Deploy(config, options);
        deployment.push( RockUtil._endCommandCallback("Deployment") );
    });

  return program;
}
<|endoftext|>


<commit_before>const roles = require('../../config/roles'),
    moment = require('moment'),
    Discord = require('discord.js');

moment.locale('de');

exports.run = (bot, message, args) => {
    function respondError() {
        return bot.respond(message, `Datenbankabfrage fehlgeschlagen, die Protokolle könnten mehr Infos enthalten. (${bot.admin})`, true);
    }

    let embed = new Discord.RichEmbed({
        author: {
            name: bot.server.name,
            icon_url: bot.server.iconURL,
            url: 'http://bronies.de/'
        },
        title: `Statistiken:`,
        color: 0x243870
    });

    const table = 'stats';
    const now = moment();

    bot.r.table(table).get(bot.momentToReDate(now)).run().then(result => {
        if (result == null) {
            embed.setDescription('Heute wurden noch keine Nachrichten gesendet oder Befehle verwendet.');
        } else {
            const messagesString = result.messages == 1 ? 'Nachricht' : 'Nachrichten';
            const commandsString = result.commands == 1 ? 'Befehl' : 'Befehle';

            embed.setDescription(`Heute wurden bereits **${result.messages} ${messagesString}** gesendet und **${result.commands} ${commandsString}** verwendet.`);
        }

        bot.r.table(table).get(bot.momentToReDate(now.subtract(1, 'days'))).run().then(result => {
            if (result == null) {
                embed.addField('Gestern', 'Keine Nachrichten gesendet oder Befehle verwendet.');
            } else {
                const messagesString = result.messages == 1 ? 'Nachricht' : 'Nachrichten';
                const commandsString = result.commands == 1 ? 'Befehl' : 'Befehle';

                embed.addField('Gestern:', `${result.messages} ${messagesString} gesendet, ${result.commands} ${commandsString} verwendet.`);
            }

            bot.r.table(table).avg('messages').run().then(result => {
                const messages = Math.round(result * 100) / 100;

                bot.r.table(table).avg('commands').run().then(result => {
                    const commands = Math.round(result * 100) / 100;

                    if (result != null) {
                        const messagesString = messages == 1 ? 'Nachricht' : 'Nachrichten';
                        const commandsString = commands == 1 ? 'Befehl' : 'Befehle';

                        embed.addField('Durchschnitt:', `${messages} ${messagesString} pro Tag, ${commands} ${commandsString} pro Tag.`);
                    }

                    message.channel.sendEmbed(embed);
                }).error(error => {
                    bot.log('Could not get date in db: ' + error);
                    return respondError();
                });
            }).error(error => {
                bot.log('Could not get date in db: ' + error);
                return respondError();
            });
        }).error(error => {
            bot.log('Could not get date in db: ' + error);
            return respondError();
        });
    }).error(error => {
        bot.log('Could not get date in db: ' + error);
        return respondError();
    });

};

exports.config = {
    aliases: ['st'],
    server: true,
    role: roles.community,
    cooldown: 60,
    skip: roles.moderator
};

exports.help = {
    name: 'stats',
    description: 'Zeigt Statistiken zum Server an.',
    usage: ['!stats']
};<commit_msg>fixed typo<commit_after>const roles = require('../../config/roles'),
    moment = require('moment'),
    Discord = require('discord.js');

moment.locale('de');

exports.run = (bot, message, args) => {
    function respondError() {
        return bot.respond(message, `Datenbankabfrage fehlgeschlagen, die Protokolle könnten mehr Infos enthalten. (${bot.admin})`, true);
    }

    let embed = new Discord.RichEmbed({
        author: {
            name: bot.server.name,
            icon_url: bot.server.iconURL,
            url: 'http://bronies.de/'
        },
        title: `Statistiken:`,
        color: 0x243870
    });

    const table = 'stats';
    const now = moment();

    bot.r.table(table).get(bot.momentToReDate(now)).run().then(result => {
        if (result == null) {
            embed.setDescription('Heute wurden noch keine Nachrichten gesendet oder Befehle verwendet.');
        } else {
            const messagesString = result.messages == 1 ? 'Nachricht' : 'Nachrichten';
            const commandsString = result.commands == 1 ? 'Befehl' : 'Befehle';

            embed.setDescription(`Heute wurden bereits **${result.messages} ${messagesString}** gesendet und **${result.commands} ${commandsString}** verwendet.`);
        }

        bot.r.table(table).get(bot.momentToReDate(now.subtract(1, 'days'))).run().then(result => {
            if (result == null) {
                embed.addField('Gestern:', 'Keine Nachrichten gesendet oder Befehle verwendet.');
            } else {
                const messagesString = result.messages == 1 ? 'Nachricht' : 'Nachrichten';
                const commandsString = result.commands == 1 ? 'Befehl' : 'Befehle';

                embed.addField('Gestern:', `${result.messages} ${messagesString} gesendet, ${result.commands} ${commandsString} verwendet.`);
            }

            bot.r.table(table).avg('messages').run().then(result => {
                const messages = Math.round(result * 100) / 100;

                bot.r.table(table).avg('commands').run().then(result => {
                    const commands = Math.round(result * 100) / 100;

                    if (result != null) {
                        const messagesString = messages == 1 ? 'Nachricht' : 'Nachrichten';
                        const commandsString = commands == 1 ? 'Befehl' : 'Befehle';

                        embed.addField('Durchschnitt:', `${messages} ${messagesString} pro Tag, ${commands} ${commandsString} pro Tag.`);
                    }

                    message.channel.sendEmbed(embed);
                }).error(error => {
                    bot.log('Could not get date in db: ' + error);
                    return respondError();
                });
            }).error(error => {
                bot.log('Could not get date in db: ' + error);
                return respondError();
            });
        }).error(error => {
            bot.log('Could not get date in db: ' + error);
            return respondError();
        });
    }).error(error => {
        bot.log('Could not get date in db: ' + error);
        return respondError();
    });

};

exports.config = {
    aliases: ['st'],
    server: true,
    role: roles.community,
    cooldown: 60,
    skip: roles.moderator
};

exports.help = {
    name: 'stats',
    description: 'Zeigt Statistiken zum Server an.',
    usage: ['!stats']
};<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * Owner: david@famo.us
 * @license MPL 2.0
 * @copyright Famous Industries, Inc. 2014
 */

define(function(require, exports, module) {
    var Transform = require('../core/Transform');
    var Transitionable = require('../transitions/Transitionable');
    var EventHandler = require('../core/EventHandler');
    var Utilities = require('../math/Utilities');

    var GenericSync = require('../inputs/GenericSync');
    var MouseSync = require('../inputs/MouseSync');
    var TouchSync = require('../inputs/TouchSync');
    GenericSync.register({'mouse': MouseSync, 'touch': TouchSync});

    /**
     * Makes added render nodes responsive to drag beahvior.
     *   Emits events 'start', 'update', 'end'.
     * @class Draggable
     * @constructor
     * @param {Object} [options] options configuration object.
     * @param {Number} [options.snapX] grid width for snapping during drag
     * @param {Number} [options.snapY] grid height for snapping during drag
     * @param {Array.Number} [options.xRange] maxmimum [negative, positive] x displacement from start of drag
     * @param {Array.Number} [options.yRange] maxmimum [negative, positive] y displacement from start of drag
     * @param {Number} [options.scale] one pixel of input motion translates to this many pixels of output drag motion
     * @param {Number} [options.projection] User should set to Draggable._direction.x or
     *    Draggable._direction.y to constrain to one axis.
     *
     */
    function Draggable(options) {
        this.options = Object.create(Draggable.DEFAULT_OPTIONS);
        if (options) this.setOptions(options);

        this._positionState = new Transitionable([0,0]);
        this._differential  = [0,0];
        this._active = true;

        this.sync = new GenericSync(['mouse', 'touch'], {scale : this.options.scale});
        this.eventOutput = new EventHandler();
        EventHandler.setInputHandler(this,  this.sync);
        EventHandler.setOutputHandler(this, this.eventOutput);

        _bindEvents.call(this);
    }

    //binary representation of directions for bitwise operations
    var _direction = {
        x : 0x01,         //001
        y : 0x02          //010
    };

    Draggable.DIRECTION_X = _direction.x;
    Draggable.DIRECTION_Y = _direction.y;

    var _clamp = Utilities.clamp;

    Draggable.DEFAULT_OPTIONS = {
        projection  : _direction.x | _direction.y,
        scale       : 1,
        xRange      : null,
        yRange      : null,
        snapX       : 0,
        snapY       : 0,
        transition  : {duration : 0}
    };

    function _mapDifferential(differential) {
        var opts        = this.options;
        var projection  = opts.projection;
        var snapX       = opts.snapX;
        var snapY       = opts.snapY;

        //axes
        var tx = (projection & _direction.x) ? differential[0] : 0;
        var ty = (projection & _direction.y) ? differential[1] : 0;

        //snapping
        if (snapX > 0) tx -= tx % snapX;
        if (snapY > 0) ty -= ty % snapY;

        return [tx, ty];
    }

    function _handleStart() {
        if (!this._active) return;
        if (this._positionState.isActive()) this._positionState.halt();
        this.eventOutput.emit('start', {position : this.getPosition()});
    }

    function _handleMove(event) {
        if (!this._active) return;

        var options = this.options;
        this._differential = event.position;
        var newDifferential = _mapDifferential.call(this, this._differential);

        //buffer the differential if snapping is set
        this._differential[0] -= newDifferential[0];
        this._differential[1] -= newDifferential[1];

        var pos = this.getPosition();

        //modify position, retain reference
        pos[0] += newDifferential[0];
        pos[1] += newDifferential[1];

        //handle bounding box
        if (options.xRange){
            var xRange = [options.xRange[0] + 0.5 * options.snapX, options.xRange[1] - 0.5 * options.snapX];
            pos[0] = _clamp(pos[0], xRange);
        }

        if (options.yRange){
            var yRange = [options.yRange[0] + 0.5 * options.snapY, options.yRange[1] - 0.5 * options.snapY];
            pos[1] = _clamp(pos[1], yRange);
        }

        this.eventOutput.emit('update', {position : pos});
    }

    function _handleEnd() {
        if (!this._active) return;
        this.eventOutput.emit('end', {position : this.getPosition()});
    }

    function _bindEvents() {
        this.sync.on('start', _handleStart.bind(this));
        this.sync.on('update', _handleMove.bind(this));
        this.sync.on('end', _handleEnd.bind(this));
    }

    /**
     * Set internal options, overriding any default options
     *
     * @method setOptions
     *
     * @param {Object} [options] overrides of default options.  See constructor.
     */
    Draggable.prototype.setOptions = function setOptions(options) {
        var currentOptions = this.options;
        if (options.projection !== undefined) {
            var proj = options.projection;
            this.options.projection = 0;
            ['x', 'y'].forEach(function(val) {
                if (proj.indexOf(val) !== -1) currentOptions.projection |= _direction[val];
            });
        }
        if (options.scale  !== undefined) {
            currentOptions.scale  = options.scale;
            if(this.sync !== undefined)
                this.sync.setOptions({
                    scale: options.scale
                });
        }
        if (options.xRange !== undefined) currentOptions.xRange = options.xRange;
        if (options.yRange !== undefined) currentOptions.yRange = options.yRange;
        if (options.snapX  !== undefined) currentOptions.snapX  = options.snapX;
        if (options.snapY  !== undefined) currentOptions.snapY  = options.snapY;
    };

    /**
     * Get current delta in position from where this draggable started.
     *
     * @method getPosition
     *
     * @return {array<number>} [x, y] position delta from start.
     */
    Draggable.prototype.getPosition = function getPosition() {
        return this._positionState.get();
    };

    /**
     * Transition the element to the desired relative position via provided transition.
     *  For example, calling this with [0,0] will not change the position.
     *  Callback will be executed on completion.
     *
     * @method setRelativePosition
     *
     * @param {array<number>} position end state to which we interpolate
     * @param {transition} transition transition object specifying how object moves to new position
     * @param {function} callback zero-argument function to call on observed completion
     */
    Draggable.prototype.setRelativePosition = function setRelativePosition(position, transition, callback) {
        var currPos = this.getPosition();
        var relativePosition = [currPos[0] + position[0], currPos[1] + position[1]];
        this.setPosition(relativePosition, transition, callback);
    };

    /**
     * Transition the element to the desired absolute position via provided transition.
     *  Callback will be executed on completion.
     *
     * @method setPosition
     *
     * @param {array<number>} position end state to which we interpolate
     * @param {transition} transition transition object specifying how object moves to new position
     * @param {function} callback zero-argument function to call on observed completion
     */
    Draggable.prototype.setPosition = function setPosition(position, transition, callback) {
        if (this._positionState.isActive()) this._positionState.halt();
        this._positionState.set(position, transition, callback);
    };

    /**
     * Set this draggable to respond to user input.
     *
     * @method activate
     *
     */
    Draggable.prototype.activate = function activate() {
        this._active = true;
    };

    /**
     * Set this draggable to ignore user input.
     *
     * @method deactivate
     *
     */
    Draggable.prototype.deactivate = function deactivate() {
        this._active = false;
    };

    /**
     * Switch the input response stage between active and inactive.
     *
     * @method toggle
     *
     */
    Draggable.prototype.toggle = function toggle() {
        this._active = !this._active;
    };

    /**
     * Return render spec for this Modifier, applying to the provided
     *    target component.  This is similar to render() for Surfaces.
     *
     * @private
     * @method modify
     *
     * @param {Object} target (already rendered) render spec to
     *    which to apply the transform.
     * @return {Object} render spec for this Modifier, including the
     *    provided target
     */
    Draggable.prototype.modify = function modify(target) {
        var pos = this.getPosition();
        return {
            transform: Transform.translate(pos[0], pos[1]),
            target: target
        };
    };

    module.exports = Draggable;
});
<commit_msg>Update Draggable.js<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * Owner: david@famo.us
 * @license MPL 2.0
 * @copyright Famous Industries, Inc. 2014
 */

define(function(require, exports, module) {
    var Transform = require('../core/Transform');
    var Transitionable = require('../transitions/Transitionable');
    var EventHandler = require('../core/EventHandler');
    var Utilities = require('../math/Utilities');

    var GenericSync = require('../inputs/GenericSync');
    var MouseSync = require('../inputs/MouseSync');
    var TouchSync = require('../inputs/TouchSync');
    GenericSync.register({'mouse': MouseSync, 'touch': TouchSync});

    /**
     * Makes added render nodes responsive to drag beahvior.
     *   Emits events 'start', 'update', 'end'.
     * @class Draggable
     * @constructor
     * @param {Object} [options] options configuration object.
     * @param {Number} [options.snapX] grid width for snapping during drag
     * @param {Number} [options.snapY] grid height for snapping during drag
     * @param {Array.Number} [options.xRange] maxmimum [negative, positive] x displacement from start of drag
     * @param {Array.Number} [options.yRange] maxmimum [negative, positive] y displacement from start of drag
     * @param {Number} [options.scale] one pixel of input motion translates to this many pixels of output drag motion
     * @param {Number} [options.projection] User should set to Draggable._direction.x or
     *    Draggable._direction.y to constrain to one axis.
     *
     */
    function Draggable(options) {
        this.options = Object.create(Draggable.DEFAULT_OPTIONS);
        if (options) this.setOptions(options);

        this._positionState = new Transitionable([0,0]);
        this._differential  = [0,0];
        this._active = true;

        this.sync = new GenericSync(['mouse', 'touch'], {scale : this.options.scale});
        this.eventOutput = new EventHandler();
        EventHandler.setInputHandler(this,  this.sync);
        EventHandler.setOutputHandler(this, this.eventOutput);

        _bindEvents.call(this);
    }

    //binary representation of directions for bitwise operations
    var _direction = {
        x : 0x01,         //001
        y : 0x02          //010
    };

    Draggable.DIRECTION_X = _direction.x;
    Draggable.DIRECTION_Y = _direction.y;

    var _clamp = Utilities.clamp;

    Draggable.DEFAULT_OPTIONS = {
        projection  : _direction.x | _direction.y,
        scale       : 1,
        xRange      : null,
        yRange      : null,
        snapX       : 0,
        snapY       : 0,
        transition  : {duration : 0}
    };

    function _mapDifferential(differential) {
        var opts        = this.options;
        var projection  = opts.projection;
        var snapX       = opts.snapX;
        var snapY       = opts.snapY;

        //axes
        var tx = (projection & _direction.x) ? differential[0] : 0;
        var ty = (projection & _direction.y) ? differential[1] : 0;

        //snapping
        if (snapX > 0) tx -= tx % snapX;
        if (snapY > 0) ty -= ty % snapY;

        return [tx, ty];
    }

    function _handleStart() {
        if (!this._active) return;
        if (this._positionState.isActive()) this._positionState.halt();
        this.eventOutput.emit('start', {position : this.getPosition()});
    }

    function _handleMove(event) {
        if (!this._active) return;

        var options = this.options;
        this._differential = event.position;
        var newDifferential = _mapDifferential.call(this, this._differential);

        //buffer the differential if snapping is set
        this._differential[0] -= newDifferential[0];
        this._differential[1] -= newDifferential[1];

        var pos = this.getPosition();

        //modify position, retain reference
        pos[0] += newDifferential[0];
        pos[1] += newDifferential[1];

        //handle bounding box
        if (options.xRange){
            var xRange = [options.xRange[0] + 0.5 * options.snapX, options.xRange[1] - 0.5 * options.snapX];
            pos[0] = _clamp(pos[0], xRange);
        }

        if (options.yRange){
            var yRange = [options.yRange[0] + 0.5 * options.snapY, options.yRange[1] - 0.5 * options.snapY];
            pos[1] = _clamp(pos[1], yRange);
        }

        this.eventOutput.emit('update', {position : pos});
    }

    function _handleEnd() {
        if (!this._active) return;
        this.eventOutput.emit('end', {position : this.getPosition()});
    }

    function _bindEvents() {
        this.sync.on('start', _handleStart.bind(this));
        this.sync.on('update', _handleMove.bind(this));
        this.sync.on('end', _handleEnd.bind(this));
    }

    /**
     * Set internal options, overriding any default options
     *
     * @method setOptions
     *
     * @param {Object} [options] overrides of default options.  See constructor.
     */
    Draggable.prototype.setOptions = function setOptions(options) {
        var currentOptions = this.options;
        if (options.projection !== undefined) {
            var proj = options.projection;
            this.options.projection = 0;
            ['x', 'y'].forEach(function(val) {
                if (proj.indexOf(val) !== -1) currentOptions.projection |= _direction[val];
            });
        }
        if (options.scale  !== undefined) {
            currentOptions.scale  = options.scale;
            if (this.sync !== undefined){
                this.sync.setOptions({
                    scale: options.scale
                });
            }
        }
        if (options.xRange !== undefined) currentOptions.xRange = options.xRange;
        if (options.yRange !== undefined) currentOptions.yRange = options.yRange;
        if (options.snapX  !== undefined) currentOptions.snapX  = options.snapX;
        if (options.snapY  !== undefined) currentOptions.snapY  = options.snapY;
    };

    /**
     * Get current delta in position from where this draggable started.
     *
     * @method getPosition
     *
     * @return {array<number>} [x, y] position delta from start.
     */
    Draggable.prototype.getPosition = function getPosition() {
        return this._positionState.get();
    };

    /**
     * Transition the element to the desired relative position via provided transition.
     *  For example, calling this with [0,0] will not change the position.
     *  Callback will be executed on completion.
     *
     * @method setRelativePosition
     *
     * @param {array<number>} position end state to which we interpolate
     * @param {transition} transition transition object specifying how object moves to new position
     * @param {function} callback zero-argument function to call on observed completion
     */
    Draggable.prototype.setRelativePosition = function setRelativePosition(position, transition, callback) {
        var currPos = this.getPosition();
        var relativePosition = [currPos[0] + position[0], currPos[1] + position[1]];
        this.setPosition(relativePosition, transition, callback);
    };

    /**
     * Transition the element to the desired absolute position via provided transition.
     *  Callback will be executed on completion.
     *
     * @method setPosition
     *
     * @param {array<number>} position end state to which we interpolate
     * @param {transition} transition transition object specifying how object moves to new position
     * @param {function} callback zero-argument function to call on observed completion
     */
    Draggable.prototype.setPosition = function setPosition(position, transition, callback) {
        if (this._positionState.isActive()) this._positionState.halt();
        this._positionState.set(position, transition, callback);
    };

    /**
     * Set this draggable to respond to user input.
     *
     * @method activate
     *
     */
    Draggable.prototype.activate = function activate() {
        this._active = true;
    };

    /**
     * Set this draggable to ignore user input.
     *
     * @method deactivate
     *
     */
    Draggable.prototype.deactivate = function deactivate() {
        this._active = false;
    };

    /**
     * Switch the input response stage between active and inactive.
     *
     * @method toggle
     *
     */
    Draggable.prototype.toggle = function toggle() {
        this._active = !this._active;
    };

    /**
     * Return render spec for this Modifier, applying to the provided
     *    target component.  This is similar to render() for Surfaces.
     *
     * @private
     * @method modify
     *
     * @param {Object} target (already rendered) render spec to
     *    which to apply the transform.
     * @return {Object} render spec for this Modifier, including the
     *    provided target
     */
    Draggable.prototype.modify = function modify(target) {
        var pos = this.getPosition();
        return {
            transform: Transform.translate(pos[0], pos[1]),
            target: target
        };
    };

    module.exports = Draggable;
});
<|endoftext|>


<commit_before>/*
 ---

 script: create.js

 description: core content control creation and plugin loading routines

 copyright: (c) 2011 Contributors in (/AUTHORS.txt).

 license: MIT-style license in (/MIT-LICENSE.txt).

 requires:
 - MochaUI/MUI

 provides: [MUI.create, MUI.load, MUI.addPluginGroup, MUI.loadPluginGroups]

 ...
 */

MUI.append({

	addPluginGroup: function(group, name){
		MUI.options.pluginGroups[name] = group;
		MUI.options.path[name] = group.path;
	},

	loadPluginGroups:function(onload){
		var js = [];
		Object.each(MUI.options.pluginGroups, function(group, name){
			if (MUI.files['{' + name + '}mui-' + name + '.js'] != 'loaded'){
				MUI[name] = [];
				js = js.append(['{' + name + '}mui-' + name + '.js']);
			}
		});
		if (js.length > 0) new MUI.Require({'js':js, 'onload':onload });
		else return false;  // returns false to signal that everything is loaded
		return true;   // returns true to signal that it loading something
	},

	load:function(options){
		// convert none hash parameters to hash
		if (typeOf(options) == 'string') options = {control:options, loadOnly:true,onload:(arguments.length > 0) ? arguments[1] : null};
		if (typeOf(options) == 'array'){
			var controls = [];
			for (var j = 0; j < options.length; j++)
				controls.push({control:options[j]});
			options = {controls:controls, onload:(arguments.length > 1) ? arguments[1] : null, loadOnly:true};
		}
		MUI.create(options);
	},

	getControlAssets : function(control, js, css, traversed, name){
		if (typeOf(control) == 'string') control = {control:control};
		if (!traversed) traversed = [control.control];
		if (!name) name = control.control;
		name = name.replace(/(^MUI\.)/i, '');
		var cname = name.toLowerCase();

		// try and locate the requested item
		var config;
		var pgName;
		Object.each(MUI.options.pluginGroups, function(group, name){
			if (MUI[name][cname] != null){
				pgName = name;
				config = MUI[name][cname];
			}
		});
		if (config == null) return {js:js,css:css,config:null};

		// see if we can gather all of the dependency controls
		var dependsOn = config.dependsOn ? config.dependsOn : [];	// add configured dependencies if they exist
		if (config.childNode && control[config.childNode]){			// add child controls of the control has a childnode configured
			var children = control[config.childNode];
			if (typeof(children) != 'array') children = [children];				// some controls allow child nodes to be an array or a single node
			Object.each(control[config.childNode], function(child){
				var controlname = (child.control ? child.control : config.childType);
				if (typeof(controlname) == 'string'){
					traversed.include(controlname);
					MUI.getControlAssets(child, js, css, traversed, controlname);
				}
			})
		}
		// gather dependencies if we have some
		if (dependsOn.length > 0){
			Object.each(dependsOn, function(controlname){
				if (traversed.indexOf(controlname) >= 0 || control.control == controlname) return;  // make sure we do get into a runaway recursion
				MUI.getControlAssets(controlname, js, css, traversed);
			})
		}

		var path = {};
		var sname = MUI.options.pluginGroups[pgName].singularName;
		if (!config.location) config.location = cname;
		path[sname] = '{' + pgName + '}' + config.location + '/';

		if (config.paths) Object.each(config.paths, function(tpath, name){
			MUI.options.path[name] = MUI.replaceFields(tpath, path);
		});

		if (!config.js) js.push(path[sname] + cname + '.js');
		else js.combine(config.js);
		js = MUI.replaceFields(js, path);

		if (config.css) css.combine(config.css);
		css.combine(MUI.options.css);
		css = MUI.replaceFields(css, path);

		return {js:js,css:css,config:config};
	},

	create:function(options){
		// convert none hash parameters to hash
		if (typeOf(options) == 'string') options = {control:options,onload:(arguments.length > 1) ? arguments[1] : null};
		if (!MUI.initialized) MUI.initialize(); // initialize mocha if needed

		if (this.loadPluginGroups(function(){ // make sure all all plugin/control group configurations are loaded
			MUI.create(options);
		})) return;

		// convert array of plugin names to controls request
		var controls = options.controls;
		if (!controls) controls = [];
		if (typeOf(options) == 'array'){
			for (var j = 0; j < options.length; j++)
				controls.push({control:options[j]});
			options = {controls:controls,onload:options.onload};
		}

		if (controls.length == 0) controls = [options]; // make sure we have an array for list of controls to load

		// gather all of the assests for the requested controls/plugins
		var r = {js:[],css:[],traversed:(MUI.traversed ? MUI.traversed : [])};
		var config;
		for (var i = 0; i < controls.length; i++){
			if (!controls[i].control) return;
			if (controls[i].fromHTML && controls[i].drawOnInit === undefined) controls[i].drawOnInit = false;
			config = MUI.getControlAssets(controls[i], r.js, r.css, r.traversed).config;
		}

		// if only one control was requested and it is loaded then return it
		if (controls.length == 1 && r.js.length > 0 && MUI.files[r.js[0]] == 'loaded'){
			if ((config && config.loadOnly) || options.loadOnly) return null;
			var name = controls[0].control.replace(/(^MUI\.)/i, '');
			var klass = MUI[name];
			var obj = new klass(options);
			if (options.onNew) options.onNew(obj);
			if (options.fromHTML && obj.fromHTML) obj.fromHTML(options.content);
			new MUI.Require(r);
			return obj;
		}

		// build a callback function for the assests requested
		r.onload = function(){
			MUI.traversed = (MUI.traversed ? MUI.traversed : []).combine(r.traversed);
			if (this.onload) this.onload(this);

			controls.each(function(control){
				if (control.loadOnly || this.loadOnly) return;
				if (control.onload) control.onload(control);
				var name = control.control.replace(/(^MUI\.)/i, '');
				var klass = MUI[name];
				var obj = new klass(control);
				if (control.onNew) control.onNew(obj);
				if (control.fromHTML && obj.fromHTML) obj.fromHTML(options.content);
			}.bind(this));

		}.bind(options);
		new MUI.Require(r);
	}

});
<commit_msg>make cure loadonly is set when hash is passed in<commit_after>/*
 ---

 script: create.js

 description: core content control creation and plugin loading routines

 copyright: (c) 2011 Contributors in (/AUTHORS.txt).

 license: MIT-style license in (/MIT-LICENSE.txt).

 requires:
 - MochaUI/MUI

 provides: [MUI.create, MUI.load, MUI.addPluginGroup, MUI.loadPluginGroups]

 ...
 */

MUI.append({

	addPluginGroup: function(group, name){
		MUI.options.pluginGroups[name] = group;
		MUI.options.path[name] = group.path;
	},

	loadPluginGroups:function(onload){
		var js = [];
		Object.each(MUI.options.pluginGroups, function(group, name){
			if (MUI.files['{' + name + '}mui-' + name + '.js'] != 'loaded'){
				MUI[name] = [];
				js = js.append(['{' + name + '}mui-' + name + '.js']);
			}
		});
		if (js.length > 0) new MUI.Require({'js':js, 'onload':onload });
		else return false;  // returns false to signal that everything is loaded
		return true;   // returns true to signal that it loading something
	},

	load:function(options){
		// convert none hash parameters to hash
		if (typeOf(options) == 'string') options = {control:options, loadOnly:true,onload:(arguments.length > 0) ? arguments[1] : null};
		if (typeOf(options) == 'array'){
			var controls = [];
			for (var j = 0; j < options.length; j++)
				controls.push({control:options[j]});
			options = {controls:controls, onload:(arguments.length > 1) ? arguments[1] : null, loadOnly:true};
		}
		if (typeOf(options) == 'object'){
			options.loadOnly = true;
		}
		MUI.create(options);
	},

	getControlAssets : function(control, js, css, traversed, name){
		if (typeOf(control) == 'string') control = {control:control};
		if (!traversed) traversed = [control.control];
		if (!name) name = control.control;
		name = name.replace(/(^MUI\.)/i, '');
		var cname = name.toLowerCase();

		// try and locate the requested item
		var config;
		var pgName;
		Object.each(MUI.options.pluginGroups, function(group, name){
			if (MUI[name][cname] != null){
				pgName = name;
				config = MUI[name][cname];
			}
		});
		if (config == null) return {js:js,css:css,config:null};

		// see if we can gather all of the dependency controls
		var dependsOn = config.dependsOn ? config.dependsOn : [];	// add configured dependencies if they exist
		if (config.childNode && control[config.childNode]){			// add child controls of the control has a childnode configured
			var children = control[config.childNode];
			if (typeof(children) != 'array') children = [children];				// some controls allow child nodes to be an array or a single node
			Object.each(control[config.childNode], function(child){
				var controlname = (child.control ? child.control : config.childType);
				if (typeof(controlname) == 'string'){
					traversed.include(controlname);
					MUI.getControlAssets(child, js, css, traversed, controlname);
				}
			})
		}
		// gather dependencies if we have some
		if (dependsOn.length > 0){
			Object.each(dependsOn, function(controlname){
				if (traversed.indexOf(controlname) >= 0 || control.control == controlname) return;  // make sure we do get into a runaway recursion
				MUI.getControlAssets(controlname, js, css, traversed);
			})
		}

		var path = {};
		var sname = MUI.options.pluginGroups[pgName].singularName;
		if (!config.location) config.location = cname;
		path[sname] = '{' + pgName + '}' + config.location + '/';

		if (config.paths) Object.each(config.paths, function(tpath, name){
			MUI.options.path[name] = MUI.replaceFields(tpath, path);
		});

		if (!config.js) js.push(path[sname] + cname + '.js');
		else js.combine(config.js);
		js = MUI.replaceFields(js, path);

		if (config.css) css.combine(config.css);
		css.combine(MUI.options.css);
		css = MUI.replaceFields(css, path);

		return {js:js,css:css,config:config};
	},

	create:function(options){
		// convert none hash parameters to hash
		if (typeOf(options) == 'string') options = {control:options,onload:(arguments.length > 1) ? arguments[1] : null};
		if (!MUI.initialized) MUI.initialize(); // initialize mocha if needed

		if (this.loadPluginGroups(function(){ // make sure all all plugin/control group configurations are loaded
			MUI.create(options);
		})) return;

		// convert array of plugin names to controls request
		var controls = options.controls;
		if (!controls) controls = [];
		if (typeOf(options) == 'array'){
			for (var j = 0; j < options.length; j++)
				controls.push({control:options[j]});
			options = {controls:controls,onload:options.onload};
		}

		if (controls.length == 0) controls = [options]; // make sure we have an array for list of controls to load

		// gather all of the assests for the requested controls/plugins
		var r = {js:[],css:[],traversed:(MUI.traversed ? MUI.traversed : [])};
		var config;
		for (var i = 0; i < controls.length; i++){
			if (!controls[i].control) return;
			if (controls[i].fromHTML && controls[i].drawOnInit === undefined) controls[i].drawOnInit = false;
			config = MUI.getControlAssets(controls[i], r.js, r.css, r.traversed).config;
		}

		// if only one control was requested and it is loaded then return it
		if (controls.length == 1 && r.js.length > 0 && MUI.files[r.js[0]] == 'loaded'){
			if ((config && config.loadOnly) || options.loadOnly) return null;
			var name = controls[0].control.replace(/(^MUI\.)/i, '');
			var klass = MUI[name];
			var obj = new klass(options);
			if (options.onNew) options.onNew(obj);
			if (options.fromHTML && obj.fromHTML) obj.fromHTML(options.content);
			new MUI.Require(r);
			return obj;
		}

		// build a callback function for the assests requested
		r.onload = function(){
			MUI.traversed = (MUI.traversed ? MUI.traversed : []).combine(r.traversed);
			if (this.onload) this.onload(this);

			controls.each(function(control){
				if (control.loadOnly || this.loadOnly) return;
				if (control.onload) control.onload(control);
				var name = control.control.replace(/(^MUI\.)/i, '');
				var klass = MUI[name];
				var obj = new klass(control);
				if (control.onNew) control.onNew(obj);
				if (control.fromHTML && obj.fromHTML) obj.fromHTML(options.content);
			}.bind(this));

		}.bind(options);
		new MUI.Require(r);
	}

});
<|endoftext|>