<commit_before>'use strict';

/*
* The original C++ code and copyright notice is from the [Boost library]{@link http://www.boost.org/doc/libs/1_62_0/boost/math/special_functions/gamma.hpp}.
*
* The implementation has been modified for JavaScript.
*/

/*
* Copyright John Maddock 2006-7, 2013-14.
* Copyright Paul A. Bristow 2007, 2013-14.
* Copyright Nikhar Agrawal 2013-14
* Copyright Christopher Kormanyos 2013-14
* Use, modification and distribution are subject to the
* Boost Software License, Version 1.0. (See accompanying file
* LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt)
*/

// MODULES //

var evalrational = require( '@stdlib/math/base/tools/evalrational' ).factory;
var factorial = require( '@stdlib/math/base/special/factorial' );
var floor = require( '@stdlib/math/base/special/floor' );
var gamma = require( '@stdlib/math/base/special/gamma' );
var log1p = require( '@stdlib/math/base/special/log1p' );
var abs = require( '@stdlib/math/base/special/abs' );
var exp = require( '@stdlib/math/base/special/exp' );
var pow = require( '@stdlib/math/base/special/pow' );
var EPSILON = require( '@stdlib/math/constants/float64-eps' );
var E = require( '@stdlib/math/constants/float64-e' );

// VARIABLES //

var MAX_FACTORIAL = 170;
var G = 10.90051099999999983936049829935654997826;
var NUM = [
	38474670393.31776828316099004518914832218,
	36857665043.51950660081971227404959150474,
	15889202453.72942008945006665994637853242,
	4059208354.298834770194507810788393801607,
	680547661.1834733286087695557084801366446,
	78239755.00312005289816041245285376206263,
	6246580.776401795264013335510453568106366,
	341986.3488721347032223777872763188768288,
	12287.19451182455120096222044424100527629,
	261.6140441641668190791708576058805625502,
	2.506628274631000502415573855452633787834
];
var DENOM = [
	0,
	362880,
	1026576,
	1172700,
	723680,
	269325,
	63273,
	9450,
	870,
	45,
	1
];

// FUNCTIONS //

/**
* Calculate the Lanczos sum approximation.
*
* @private
* @param {number} z - input value
* @returns {number} Lanczos approximation
*/
var lanczosSum = evalrational( NUM, DENOM );

/**
* Calculates the ratio of two gamma functions.
*
* #### Notes
*
* - For z smaller than machine epsilon, we get spurious numeric overflow unless we're very careful, this can occur either inside lanczosSum(z) or in the final combination of terms, to avoid this, split the product up into 2 (or 3) parts:
*
*   ``` tex
*    G(z) / G(L) = 1 / (z * G(L)) ; z < \epsilon, L = z + \delta = \delta \\
*    z * G(L) = z * G(\lim) * (G(L)/G(\lim)) ; \lim = \text{largest factorial}
*  ```
*
* @private
* @param {number} z - function value
* @param {number} delta - difference
* @returns {number} ratio
*/
function tgammaDeltaRatioImpLanczos( z, delta ) {
	var result;
	var ratio;
	var zgh;
	if ( z < EPSILON ) {
		if ( MAX_FACTORIAL < delta ) {
			ratio = tgammaDeltaRatioImpLanczos( delta, MAX_FACTORIAL - delta );
			ratio *= z;
			ratio *= factorial( MAX_FACTORIAL - 1 );
			return 1.0 / ratio;
		}
		return 1.0 / ( z * gamma( z + delta ) );
	}
	zgh = z + G - 0.5;
	if ( abs(delta) < 10 ) {
		result = exp( ( 0.5 - z ) * log1p( delta / zgh ));
	} else {
		result = pow( zgh / (zgh + delta), z - 0.5 );
	}
	// Split the calculation up to avoid spurious overflow:
	result *= lanczosSum( z ) / lanczosSum( z + delta );
	result *= pow( E / ( zgh + delta ), delta );
	return result;
} // end FUNCTION tgamma_delta_ratio_imp_lanczos()

// MAIN //

/**
* Implementation of the gamma ratio.
*
* @private
* @param {number} z - function value
* @param {number} delta - difference
* @returns {number} ratio
*/
function tgammaDeltaRatioImp( z, delta ) {
	var result;

	if ( z <= 0.0 || z + delta <= 0.0 ) {
		// This isn't very sophisticated, or accurate, but it does work:
		return gamma( z ) / gamma( z + delta );
	}
	if ( floor(delta) === delta ) {
		if ( floor(z) === z ) {
			// Both z and delta are integers, see if we can just use table lookup of the factorials to get the result:
			if ( z <= MAX_FACTORIAL && ( z + delta <= MAX_FACTORIAL ) ) {
				return factorial( floor(z) - 1 ) /
					factorial( floor(z+delta) - 1 );
			}
		}
		if ( abs(delta) < 20 ) {
			// Delta is a small integer, we can use a finite product:
			if ( delta === 0 ) {
				return 1.0;
			}
			if ( delta < 0 ) {
				z -= 1.0;
			}
			result = z;
			// eslint-disable-next-line no-cond-assign
			while ( ( delta -= 1 ) !== 0 ) {
				z -= 1.0;
				result *= z;
			}
			return result;
		}
		result = 1.0 / z;
		// eslint-disable-next-line no-cond-assign
		while ( ( delta -= 1 ) !== 0 ) {
			z += 1;
			result /= z;
		}
		return result;
	}
	return tgammaDeltaRatioImpLanczos( z, delta );
} // end FUNCTION tgammaDeltaRatioImp()

// EXPORTS //

module.exports = tgammaDeltaRatioImp;
<commit_msg>Avoid conditional assignment<commit_after>'use strict';

/*
* The original C++ code and copyright notice is from the [Boost library]{@link http://www.boost.org/doc/libs/1_62_0/boost/math/special_functions/gamma.hpp}.
*
* The implementation has been modified for JavaScript.
*/

/*
* Copyright John Maddock 2006-7, 2013-14.
* Copyright Paul A. Bristow 2007, 2013-14.
* Copyright Nikhar Agrawal 2013-14
* Copyright Christopher Kormanyos 2013-14
* Use, modification and distribution are subject to the
* Boost Software License, Version 1.0. (See accompanying file
* LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt)
*/

// MODULES //

var evalrational = require( '@stdlib/math/base/tools/evalrational' ).factory;
var factorial = require( '@stdlib/math/base/special/factorial' );
var floor = require( '@stdlib/math/base/special/floor' );
var gamma = require( '@stdlib/math/base/special/gamma' );
var log1p = require( '@stdlib/math/base/special/log1p' );
var abs = require( '@stdlib/math/base/special/abs' );
var exp = require( '@stdlib/math/base/special/exp' );
var pow = require( '@stdlib/math/base/special/pow' );
var EPSILON = require( '@stdlib/math/constants/float64-eps' );
var E = require( '@stdlib/math/constants/float64-e' );

// VARIABLES //

var MAX_FACTORIAL = 170;
var G = 10.90051099999999983936049829935654997826;
var NUM = [
	38474670393.31776828316099004518914832218,
	36857665043.51950660081971227404959150474,
	15889202453.72942008945006665994637853242,
	4059208354.298834770194507810788393801607,
	680547661.1834733286087695557084801366446,
	78239755.00312005289816041245285376206263,
	6246580.776401795264013335510453568106366,
	341986.3488721347032223777872763188768288,
	12287.19451182455120096222044424100527629,
	261.6140441641668190791708576058805625502,
	2.506628274631000502415573855452633787834
];
var DENOM = [
	0,
	362880,
	1026576,
	1172700,
	723680,
	269325,
	63273,
	9450,
	870,
	45,
	1
];

// FUNCTIONS //

/**
* Calculate the Lanczos sum approximation.
*
* @private
* @param {number} z - input value
* @returns {number} Lanczos approximation
*/
var lanczosSum = evalrational( NUM, DENOM );

/**
* Calculates the ratio of two gamma functions.
*
* #### Notes
*
* - For z smaller than machine epsilon, we get spurious numeric overflow unless we're very careful, this can occur either inside lanczosSum(z) or in the final combination of terms, to avoid this, split the product up into 2 (or 3) parts:
*
*   ``` tex
*    G(z) / G(L) = 1 / (z * G(L)) ; z < \epsilon, L = z + \delta = \delta \\
*    z * G(L) = z * G(\lim) * (G(L)/G(\lim)) ; \lim = \text{largest factorial}
*  ```
*
* @private
* @param {number} z - function value
* @param {number} delta - difference
* @returns {number} ratio
*/
function tgammaDeltaRatioImpLanczos( z, delta ) {
	var result;
	var ratio;
	var zgh;
	if ( z < EPSILON ) {
		if ( MAX_FACTORIAL < delta ) {
			ratio = tgammaDeltaRatioImpLanczos( delta, MAX_FACTORIAL - delta );
			ratio *= z;
			ratio *= factorial( MAX_FACTORIAL - 1 );
			return 1.0 / ratio;
		}
		return 1.0 / ( z * gamma( z + delta ) );
	}
	zgh = z + G - 0.5;
	if ( abs(delta) < 10 ) {
		result = exp( ( 0.5 - z ) * log1p( delta / zgh ));
	} else {
		result = pow( zgh / (zgh + delta), z - 0.5 );
	}
	// Split the calculation up to avoid spurious overflow:
	result *= lanczosSum( z ) / lanczosSum( z + delta );
	result *= pow( E / ( zgh + delta ), delta );
	return result;
} // end FUNCTION tgamma_delta_ratio_imp_lanczos()

// MAIN //

/**
* Implementation of the gamma ratio.
*
* @private
* @param {number} z - function value
* @param {number} delta - difference
* @returns {number} ratio
*/
function tgammaDeltaRatioImp( z, delta ) {
	var result;

	if ( z <= 0.0 || z + delta <= 0.0 ) {
		// This isn't very sophisticated, or accurate, but it does work:
		return gamma( z ) / gamma( z + delta );
	}
	if ( floor(delta) === delta ) {
		if ( floor(z) === z ) {
			// Both z and delta are integers, see if we can just use table lookup of the factorials to get the result:
			if ( z <= MAX_FACTORIAL && ( z + delta <= MAX_FACTORIAL ) ) {
				return factorial( floor(z) - 1 ) /
					factorial( floor(z+delta) - 1 );
			}
		}
		if ( abs(delta) < 20 ) {
			// Delta is a small integer, we can use a finite product:
			if ( delta === 0 ) {
				return 1.0;
			}
			if ( delta < 0 ) {
				z -= 1.0;
			}
			result = z;
			delta -= 1;
			while ( delta !== 0 ) {
				z -= 1.0;
				result *= z;
				delta -= 1;
			}
			return result;
		}
		result = 1.0 / z;
		delta -= 1;
		while ( delta !== 0 ) {
			z += 1;
			result /= z;
			delta -= 1;
		}
		return result;
	}
	return tgammaDeltaRatioImpLanczos( z, delta );
} // end FUNCTION tgammaDeltaRatioImp()

// EXPORTS //

module.exports = tgammaDeltaRatioImp;
<|endoftext|>


<commit_before>var async = require("async"),
    redis = require("redis"),
    cheerio = require("cheerio"),
    request = require("request");

var customTrim = function(s, charlist) {
  var tmp = s.replace(new RegExp("^[" + charlist + "]+"), "");
  tmp = tmp.replace(new RegExp("[" + charlist + "]+$"), "")
  return tmp;
};

function scrape(verseKey, verseFind, version, cb){
  var redis_client = redis.createClient();
  var url = "http://mobile.legacy.biblegateway.com/passage/?search=" + encodeURIComponent(verseFind) + "&version=" + version;

  redis_client.get(url, function(err, reply) {
    if (!reply){
      request(
        {
          "url": url,
          "headers" : {
            "User-Agent": "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)"
          }
        },
        function(err, response, body) {
          if (err) {console.log(err);}

          var output = "";
          var $ = cheerio.load(body);

          $(".publisher-info-bottom").remove();
          $(".passage-display-version").remove();

          $(".passage-wrap > .passage-content").find(".passage-display, p").each(function(i, e){
            $(e).find(".footnote, .footnotes").remove();
            $(e).removeAttr("class");
            $(e).removeAttr("id");
            $(e).find("p, span, div, sup").removeAttr("class");
            $(e).find("p, span, div, sup").removeAttr("id");
            output += $("

").html($(e).clone()).html();
          });

          redis_client.set(url, output);
          redis_client.quit();

          var result = {};
          result[verseKey] = output;

          cb(null, result);
        }
      );
    } else {
      redis_client.quit();
      var result = {};
      result[verseKey] = reply;
      cb(null, result);
    }
  });
}

function parse_fr(read, callback){
  var bible_books = "Gn|Gen|Ex|Lev|Nom|Nb|Deut|Jos|Jg|Jug|Rt|1 ?Sam|2 ?Sam|1 ?R|2 ?R|1 ?Ch|2 ?Ch|1 ?Chron|2 ?Chron|Esd|Ne|Neh|Est|Jb|Ps|Pr|Prov|Ec|Isa|Esa|Jr|Jer|La|Ezdr|Ez|Da|Dan|Os|Jl|Am|Ab|Jon|Mic|Na|Hab|So|Ag|Zach|Ma|Mal|Mt|Mat|Matt|Mc|Lc|Jn|John|Acts|Act|Ac|Rom|1 ?Cor|2 ?Cor|Gal|Eph|Ph|Phil|Col|1 ?Th|2 ?Th|1 ?Tim|1 Thess|2 Thess|2 ?Tim|Tt|Phm|He|Hé|Héb|Heb|Jc|1 ?Pie|2 ?Pie|1 ?Jn|2 ?Jn|3 ?Jn|Jd|Ap|Apo|Apoc|Genèse|Exode|Lévitique|Nombres|Deutéronome|Josué|Juges|Ruth|1 ?Samuel|2 ?Samuel|1 ?Rois|2 ?Rois|1 ?Chroniques|2 ?Chroniques|Esdras|Néhémie|Esther|Job|Psaume|Psaumes|Proverbes|Proverbe|Ecclésiaste|Cantique des cantiques|Esaïe|Ésaïe|Jérémie|Lamentations|Ézéchiel|Daniel|Osée|Joël|Amos|Abdias|Jonas|Michée|Nahum|Habakuk|Sophonie|Aggée|Zacharie|Malachie|Matthieu|Marc|Luc|Jean|Actes|Romains|1 ?Corinthiens|2 ?Corinthiens|Galates|Éphésiens|Philippiens|Colossiens|1 ?Thessaloniciens|2 ?Thessaloniciens|1 ?Timothée|2 ?Timothée|Tite|Philémon|Hébreux|Jacques|1 ?Pierre|2 ?Pierre|1 ?Jean|2 ?Jean|3 ?Jean|Jude|Apocalypse";
  var bible_regexp = new RegExp("(("+bible_books+")\\.?\\ ([0-9\\.;,: \\-\\–](?!"+bible_books+"))+)", "g");
  var bible_book_regexp = new RegExp("("+bible_books+")\\.?", "g");

  var verses = read.match(bible_regexp),
    verses_parsed = [];

  var scrape_tasks_lsg = [];

  if (verses){
    for (var i = 0; i < verses.length; i++){
      var verse = customTrim(verses[i], " ;,()<>.:-");

      var french_verse_replacement = [
        {"s": "Esa.", "r": "Ésaïe"},
        {"s": "Esa ", "r": "Ésaïe "},
        {"s": "Apo.", "r": "Ap."},
        {"s": "Za.", "r": "Zac."},
        {"s": "Zach.", "r": "Zac."},
        {"s": "Jug.", "r": "Jg."}
      ];

      for (var sr = 0; sr < french_verse_replacement.length; sr++){
        if (verse.indexOf(french_verse_replacement[sr]["s"]) == 0){
          var new_verse = verse.replace(french_verse_replacement[sr]["s"], french_verse_replacement[sr]["r"]);
          read = read.replace(verse, new_verse);
          verse = new_verse;
        }
      }

      if (verse.length > 0 && verse.match(/\d/g)) {
        verses_parsed.push(verse);
      }
    }

    verses_parsed = verses_parsed.sort(function(a, b){
      return b.length - a.length;
    });

    for (var i = 0; i < verses_parsed.length; i++){

      var final_verse = verses_parsed[i].replace(/\.|\#|\$|\/|\[|\]/g, '');
      read = read.replace(new RegExp('(?!]*?>)('+verses_parsed[i]+')(?![^<]*?)', "g"), ''+verses_parsed[i]+'');
      (function(verseKey, verseFind){scrape_tasks_lsg.push(function(cb){
        scrape(verseKey, verseFind, "LSG", cb);
      })})(final_verse, verses_parsed[i]);
    }

    async.series([
      function(callback){
        async.series(scrape_tasks_lsg, function(err, results){
          var verses = {};
          for (var i = 0; i < results.length; i++){
            for (var attrname in results[i]) { verses[attrname] = results[i][attrname]; }
          }

          callback(null, {"name": "LSG", "verses": verses, "read": read});
        });
      }
    ], function(err, result){
      callback(result);
    });
  }
}

module.exports = parse_fr;<commit_msg>Update fr bible parser. Replace h1 with h3<commit_after>var async = require("async"),
    redis = require("redis"),
    cheerio = require("cheerio"),
    request = require("request");

var customTrim = function(s, charlist) {
  var tmp = s.replace(new RegExp("^[" + charlist + "]+"), "");
  tmp = tmp.replace(new RegExp("[" + charlist + "]+$"), "")
  return tmp;
};

function scrape(verseKey, verseFind, version, cb){
  var redis_client = redis.createClient();
  var url = "http://mobile.legacy.biblegateway.com/passage/?search=" + encodeURIComponent(verseFind) + "&version=" + version;

  redis_client.get(url, function(err, reply) {
    if (!reply){
      request(
        {
          "url": url,
          "headers" : {
            "User-Agent": "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)"
          }
        },
        function(err, response, body) {
          if (err) {console.log(err);}

          var output = "";
          var $ = cheerio.load(body);

          $(".publisher-info-bottom").remove();
          $(".passage-display-version").remove();

          $(".passage-wrap > .passage-content").find(".passage-display, p").each(function(i, e){
            $(e).find(".footnote, .footnotes").remove();
            $(e).removeAttr("class");
            $(e).removeAttr("id");
            $(e).find("p, span, div, sup").removeAttr("class");
            $(e).find("p, span, div, sup").removeAttr("id");
            output += $("

").html($(e).clone()).html();
            output = output.replace("h1>", "h3>");
          });

          redis_client.set(url, output);
          redis_client.quit();

          var result = {};
          result[verseKey] = output;

          cb(null, result);
        }
      );
    } else {
      redis_client.quit();
      var result = {};
      result[verseKey] = reply;
      cb(null, result);
    }
  });
}

function parse_fr(read, callback){
  var bible_books = "Gn|Gen|Ex|Lev|Nom|Nb|Deut|Jos|Jg|Jug|Rt|1 ?Sam|2 ?Sam|1 ?R|2 ?R|1 ?Ch|2 ?Ch|1 ?Chron|2 ?Chron|Esd|Ne|Neh|Est|Jb|Ps|Pr|Prov|Ec|Isa|Esa|Jr|Jer|La|Ezdr|Ez|Da|Dan|Os|Jl|Am|Ab|Jon|Mic|Na|Hab|So|Ag|Zach|Ma|Mal|Mt|Mat|Matt|Mc|Lc|Jn|John|Acts|Act|Ac|Rom|1 ?Cor|2 ?Cor|Gal|Eph|Ph|Phil|Col|1 ?Th|2 ?Th|1 ?Tim|1 Thess|2 Thess|2 ?Tim|Tt|Phm|He|Hé|Héb|Heb|Jc|1 ?Pie|2 ?Pie|1 ?Jn|2 ?Jn|3 ?Jn|Jd|Ap|Apo|Apoc|Genèse|Exode|Lévitique|Nombres|Deutéronome|Josué|Juges|Ruth|1 ?Samuel|2 ?Samuel|1 ?Rois|2 ?Rois|1 ?Chroniques|2 ?Chroniques|Esdras|Néhémie|Esther|Job|Psaume|Psaumes|Proverbes|Proverbe|Ecclésiaste|Cantique des cantiques|Esaïe|Ésaïe|Jérémie|Lamentations|Ézéchiel|Daniel|Osée|Joël|Amos|Abdias|Jonas|Michée|Nahum|Habakuk|Sophonie|Aggée|Zacharie|Malachie|Matthieu|Marc|Luc|Jean|Actes|Romains|1 ?Corinthiens|2 ?Corinthiens|Galates|Éphésiens|Philippiens|Colossiens|1 ?Thessaloniciens|2 ?Thessaloniciens|1 ?Timothée|2 ?Timothée|Tite|Philémon|Hébreux|Jacques|1 ?Pierre|2 ?Pierre|1 ?Jean|2 ?Jean|3 ?Jean|Jude|Apocalypse";
  var bible_regexp = new RegExp("(("+bible_books+")\\.?\\ ([0-9\\.;,: \\-\\–](?!"+bible_books+"))+)", "g");
  var bible_book_regexp = new RegExp("("+bible_books+")\\.?", "g");

  var verses = read.match(bible_regexp),
    verses_parsed = [];

  var scrape_tasks_lsg = [];

  if (verses){
    for (var i = 0; i < verses.length; i++){
      var verse = customTrim(verses[i], " ;,()<>.:-");

      var french_verse_replacement = [
        {"s": "Esa.", "r": "Ésaïe"},
        {"s": "Esa ", "r": "Ésaïe "},
        {"s": "Apo.", "r": "Ap."},
        {"s": "Za.", "r": "Zac."},
        {"s": "Zach.", "r": "Zac."},
        {"s": "Jug.", "r": "Jg."},
        {"s": "Nom. ", "r": "Nm. "}
      ];

      for (var sr = 0; sr < french_verse_replacement.length; sr++){
        if (verse.indexOf(french_verse_replacement[sr]["s"]) == 0){
          var new_verse = verse.replace(french_verse_replacement[sr]["s"], french_verse_replacement[sr]["r"]);
          read = read.replace(verse, new_verse);
          verse = new_verse;
        }
      }

      if (verse.length > 0 && verse.match(/\d/g)) {
        verses_parsed.push(verse);
      }
    }

    verses_parsed = verses_parsed.sort(function(a, b){
      return b.length - a.length;
    });

    for (var i = 0; i < verses_parsed.length; i++){

      var final_verse = verses_parsed[i].replace(/\.|\#|\$|\/|\[|\]/g, '');
      read = read.replace(new RegExp('(?!]*?>)('+verses_parsed[i]+')(?![^<]*?)', "g"), ''+verses_parsed[i]+'');
      (function(verseKey, verseFind){scrape_tasks_lsg.push(function(cb){
        scrape(verseKey, verseFind, "LSG", cb);
      })})(final_verse, verses_parsed[i]);
    }

    async.series([
      function(callback){
        async.series(scrape_tasks_lsg, function(err, results){
          var verses = {};
          for (var i = 0; i < results.length; i++){
            for (var attrname in results[i]) { verses[attrname] = results[i][attrname]; }
          }

          callback(null, {"name": "LSG", "verses": verses, "read": read});
        });
      }
    ], function(err, result){
      callback(result);
    });
  }
}

module.exports = parse_fr;<|endoftext|>


<commit_before>// https://fgnass.github.com/spin.js
(function(a,b){function L(a){E(arguments,function(c,d){a[c]===b&&(a[c]=d)});return a}function K(a){E(arguments,function(b,c){a[l][J(a,b)||b]=c});return a}function J(a,c){var e=a[l];if(e[c]!==b)return c;c=c.charAt(0).toUpperCase()+c.slice(1);for(var f=0;f<B[d];f++){var g=B[f]+c;if(e[g]!==b)return g}}function I(a,b){var c=[i,b,~~(a*100)].join("-");if(!C[c]){var e=H(),f="{"+i+":"+a+"}",g;for(g=0;g<B[d];g++)try{e.insertRule("@"+(B[g]&&"-"+B[g].toLowerCase()+"-"||"")+"keyframes "+c+"{0%{"+i+":1}"+b+"%"+f+"to"+f+"}",e.cssRules[d])}catch(h){}C[c]=1}return c}function H(){var b=a.styleSheets;b[d]||G(a.documentElement[r],F(l));return b[0]}function G(a,b,c){c&&!c[s]&&G(a,c),a.insertBefore(b,c||null);return a}function F(b){var c=a.createElement(b||"div");E(arguments,function(a,b){c[a]=b});return c}function E(a,b){var c=~~((a[d]-1)/2);for(var e=1;e<=c;e++)b(a[e*2-1],a[e*2])}var c="width",d="length",e="radius",f="lines",g="trail",h="color",i="opacity",j="speed",k="shadow",l="style",m="height",n="left",o="top",p="px",q="childNodes",r="firstChild",s="parentNode",t="position",u="relative",v="absolute",w="animation",x="transform",y="Origin",z="coord",A="#000",B="webkit0Moz0ms0O".split(0),C={},D,M=function(a){this.el=this[f](this.opts=L(a||{},f,12,g,100,d,7,c,5,e,10,h,A,i,.25,j,1))},N=M.prototype={spin:function(a){var b=this,c=b.el;a&&G(a,K(c,n,~~(a.offsetWidth/2)+p,o,~~(a.offsetHeight/2)+p),a[r]),b.on=1;if(!D){var d=b.opts,e=0,h=20/d[j],k=(1-d[i])/(h*d[g]/100),l=h/d[f];(function m(){e++;for(var a=d[f];a;a--){var g=Math.max(1-(e+a*l)%h*k,d[i]);b[i](c,d[f]-a,g,d)}b.on&&setTimeout(m,50)})()}return b},stop:function(){var a=this,b=a.el;a.on=0,b[s]&&b[s].removeChild(b);return a}};N[f]=function(a){function r(b,g){return K(F(),t,v,c,a[d]+a[c]+p,m,a[c]+p,"background",b,"boxShadow",g,x+y,n,x,"rotate("+~~(360/a[f]*q)+"deg) translate("+a[e]+p+",0)","borderRadius","100em")}var b=K(F(),t,u),l=I(a[i],a[g]),q=0;for(;q<a[f];q++){var s=K(F(),t,v,o,1+~(a[c]/2)+p,x,"translate3d(0,0,0)",w,l+" "+1/a[j]+"s linear infinite "+(-1+1/a[f]*q/a[j])+"s");a[k]&&G(s,K(r(A,"0 0 4px "+A),o,2+p)),G(b,G(s,r(a[h],"0 0 1px rgba(0,0,0,.1)")))}return b},N[i]=function(a,b,c){a[q][b][l][i]=c};var O="behavior",P="url(#default#VML)",Q="group0roundrect0fill0stroke".split(0);(function(){var a=K(F(Q[0]),O,P);if(!J(a,x)&&a.adj){var b=H(),g;for(g=0;g<Q[d];g++)b.addRule(Q[g],O+":"+P);N[f]=function(){function s(d,g,k){G(l,G(K(j(),"rotation",360/a[f]*d+"deg",n,~~g),G(K(F(Q[1],"arcsize",1),c,b,m,a[c],n,a[e],o,-a[c]/2,"filter",k),F(Q[2],h,a[h],i,a[i]),F(Q[3],i,0))))}function j(){return K(F(Q[0],z+"size",g+" "+g,z+y,-b+" "+ -b),c,g,m,g)}var a=this.opts,b=a[d]+a[c],g=2*b,l=j(),q=~(a[d]+a[e]+a[c])+p,r;if(a[k])for(r=1;r<=a[f];r++)s(r,-2,"progid:DXImage"+x+".Microsoft.Blur(pixel"+e+"=2,make"+k+"=1,"+k+i+"=.3)");for(r=1;r<=a[f];r++)s(r);return G(K(F(),"margin",q+" 0 0 "+q,t,u),l)},N[i]=function(a,b,c,d){d=d[k]&&d[f]||0,a[r][q][b+d][r][r][i]=c}}else D=J(a,w)})(),window.Spinner=M})(document)<commit_msg>Updated the minified version<commit_after>// https://fgnass.github.com/spin.js
(function(a,b){function L(a){E(arguments,function(c,d){a[c]===b&&(a[c]=d)});return a}function K(a){E(arguments,function(b,c){a[l][J(a,b)||b]=c});return a}function J(a,c){var e=a[l];if(e[c]!==b)return c;c=c.charAt(0).toUpperCase()+c.slice(1);for(var f=0;f<B[d];f++){var g=B[f]+c;if(e[g]!==b)return g}}function I(a,b){var c=[i,b,~~(a*100)].join("-");if(!C[c]){var e=H(),f="{"+i+":"+a+"}",g;for(g=0;g<B[d];g++)try{e.insertRule("@"+(B[g]&&"-"+B[g].toLowerCase()+"-"||"")+"keyframes "+c+"{0%{"+i+":1}"+b+"%"+f+"to"+f+"}",e.cssRules[d])}catch(h){}C[c]=1}return c}function H(){var b=a.styleSheets;b[d]||G(a.documentElement[r],F(l));return b[0]}function G(a,b,c){c&&!c[s]&&G(a,c),a.insertBefore(b,c||null);return a}function F(b){var c=a.createElement(b||"div");E(arguments,function(a,b){c[a]=b});return c}function E(a,b){var c=~~((a[d]-1)/2);for(var e=1;e<=c;e++)b(a[e*2-1],a[e*2])}var c="width",d="length",e="radius",f="lines",g="trail",h="color",i="opacity",j="speed",k="shadow",l="style",m="height",n="left",o="top",p="px",q="childNodes",r="firstChild",s="parentNode",t="position",u="relative",v="absolute",w="animation",x="transform",y="Origin",z="coord",A="#000",B="webkit0Moz0ms0O".split(0),C={},D,M=function(a){this.el=this[f](this.opts=L(a||{},f,12,g,100,d,7,c,5,e,10,h,A,i,.25,j,1))},N=M.prototype={spin:function(a){var b=this,c=b.el;a&&G(a,K(c,n,~~(a.offsetWidth/2)+p,o,~~(a.offsetHeight/2)+p),a[r]),b.on=1;if(!D){var d=b.opts,e=0,h=20/d[j],k=(1-d[i])/(h*d[g]/100),l=h/d[f];(function m(){e++;for(var a=d[f];a;a--){var g=Math.max(1-(e+a*l)%h*k,d[i]);b[i](c,d[f]-a,g,d)}b.on&&setTimeout(m,50)})()}return b},stop:function(){var a=this,b=a.el;a.on=0,b[s]&&b[s].removeChild(b);return a}};N[f]=function(a){function r(b,g){return K(F(),t,v,c,a[d]+a[c]+p,m,a[c]+p,"background",b,"boxShadow",g,x+y,n,x,"rotate("+~~(360/a[f]*q)+"deg) translate("+a[e]+p+",0)","borderRadius","100em")}var b=K(F(),t,u),l=I(a[i],a[g]),q=0;for(;q<a[f];q++){var s=K(F(),t,v,o,1+~(a[c]/2)+p,x,"translate3d(0,0,0)",w,l+" "+1/a[j]+"s linear infinite "+(1/a[f]/a[j]*q-1/a[j])+"s");a[k]&&G(s,K(r(A,"0 0 4px "+A),o,2+p)),G(b,G(s,r(a[h],"0 0 1px rgba(0,0,0,.1)")))}return b},N[i]=function(a,b,c){a[q][b][l][i]=c};var O="behavior",P="url(#default#VML)",Q="group0roundrect0fill0stroke".split(0);(function(){var a=K(F(Q[0]),O,P);if(!J(a,x)&&a.adj){var b=H(),g;for(g=0;g<Q[d];g++)b.addRule(Q[g],O+":"+P);N[f]=function(){function s(d,g,k){G(l,G(K(j(),"rotation",360/a[f]*d+"deg",n,~~g),G(K(F(Q[1],"arcsize",1),c,b,m,a[c],n,a[e],o,-a[c]/2,"filter",k),F(Q[2],h,a[h],i,a[i]),F(Q[3],i,0))))}function j(){return K(F(Q[0],z+"size",g+" "+g,z+y,-b+" "+ -b),c,g,m,g)}var a=this.opts,b=a[d]+a[c],g=2*b,l=j(),q=~(a[d]+a[e]+a[c])+p,r;if(a[k])for(r=1;r<=a[f];r++)s(r,-2,"progid:DXImage"+x+".Microsoft.Blur(pixel"+e+"=2,make"+k+"=1,"+k+i+"=.3)");for(r=1;r<=a[f];r++)s(r);return G(K(F(),"margin",q+" 0 0 "+q,t,u),l)},N[i]=function(a,b,c,d){d=d[k]&&d[f]||0,a[r][q][b+d][r][r][i]=c}}else D=J(a,w)})(),window.Spinner=M})(document)<|endoftext|>


<commit_before>$(function() {

	// chat aliases
	var you = 'You';
	var robot = 'Robin';

	// slow reply by 400 to 800 ms
	var delayStart = 400;
	var delayEnd = 800;

	// initialize
	var bot = new chatBot();
	var chat = $('.chat');
	var waiting = 0;
	$('.busy').text(robot + ' is typing...');

	// submit user input and get chat-bot's reply
	var submitChat = function() {

		var input = $('.input input').val();
		if(input == '') return;

		$('.input input').val('');
		updateChat(you, input);

		var reply = bot.respondTo(input);
		if(reply == null) return;

		speak(reply);
		ping();

		var latency = Math.floor((Math.random() * (delayEnd - delayStart)) + delayStart);
		$('.busy').css('display', 'block');
		waiting++;
		setTimeout( function() {
			if(typeof reply === 'string') {
				updateChat(robot, reply);
			} else {
				for(var r in reply) {
					updateChat(robot, reply[r]);
				}
			}
			if(--waiting == 0) $('.busy').css('display', 'none');
		}, latency);
	}

	var speak = function(texts){
		if(window.speechSynthesis){
	        for(var i=0; i < texts.length; i++){
	            var utterance = new SpeechSynthesisUtterance(texts[i]);
	            utterance.lang = 'en-US';
	            window.speechSynthesis.speak(utterance);
	        }
		}
    }

    var ping = function(){

    	var payload = {
            "value1": "demo",
            "value2": "demo2"
        };

        var data = new FormData();
        //data.append( "json", JSON.stringify({value1: "demo", value2: "demo2"});

        fetch("https://crossorigin.me/https://maker.ifttt.com/trigger/winter-games-game1/with/key/dvHJXlCso1laUplLipy7LT",
        {
        	method: "POST",
        	headers: new Headers({
				"Content-Type": "application/json"
			}),
            body: JSON.stringify({"value1": "demo", "value2": "demo2"})
        })
        .then(function(res){ console.log(res); })
        // $.post({
        //     url: 'https://crossorigin.me/https://maker.ifttt.com/trigger/winter-games-game1/with/key/dvHJXlCso1laUplLipy7LT',
        //     contentType : "application/json",
        //     dataType: "jsonp",
        //     //dataType: 'json',
        //     //jsonpCallback: "logResults",
        //     data: JSON.stringify({ value1: "demo" })
        // });
    }

	// add a new line to the chat
	var updateChat = function(party, text) {

		var style = 'you';
		if(party != you) {
			style = 'other';
		}

		var line = $('

');
		line.find('.party').addClass(style).text(party + ':');
		line.find('.text').text(text);

		chat.append(line);

		chat.stop().animate({ scrollTop: chat.prop("scrollHeight")});

	}

	// event binding
	$('.input').bind('keydown', function(e) {
		if(e.keyCode == 13) {
			submitChat();
		}
	});
	$('.input a').bind('click', submitChat);

	// initial chat state
	updateChat(robot, 'Hi buddy, Can I help you?');
	$('#chatbar').focus();

});<commit_msg>Minor change<commit_after>$(function() {

	// chat aliases
	var you = 'You';
	var robot = 'Robin';

	// slow reply by 400 to 800 ms
	var delayStart = 400;
	var delayEnd = 800;

	// initialize
	var bot = new chatBot();
	var chat = $('.chat');
	var waiting = 0;
	$('.busy').text(robot + ' is typing...');

	// submit user input and get chat-bot's reply
	var submitChat = function() {

		var input = $('.input input').val();
		if(input == '') return;

		$('.input input').val('');
		updateChat(you, input);

		var reply = bot.respondTo(input);
		if(reply == null) return;

		speak(reply);
		ping();

		var latency = Math.floor((Math.random() * (delayEnd - delayStart)) + delayStart);
		$('.busy').css('display', 'block');
		waiting++;
		setTimeout( function() {
			if(typeof reply === 'string') {
				updateChat(robot, reply);
			} else {
				for(var r in reply) {
					updateChat(robot, reply[r]);
				}
			}
			if(--waiting == 0) $('.busy').css('display', 'none');
		}, latency);
	}

	var speak = function(texts){
		if(window.speechSynthesis){
	        for(var i=0; i < texts.length; i++){
	            var utterance = new SpeechSynthesisUtterance(texts[i]);
	            utterance.lang = 'en-US';
	            window.speechSynthesis.speak(utterance);
	        }
		}
    }

    var ping = function(){

    	var payload = {
            "value1": "demo",
            "value2": "demo2"
        };

        var data = new FormData();
        //data.append( "json", JSON.stringify({value1: "demo", value2: "demo2"});

        fetch("https://maker.ifttt.com/trigger/winter-games-game1/with/key/dvHJXlCso1laUplLipy7LT",
        {
        	method: "POST",
        	mode: 'cors',
        	headers: new Headers({
				"Content-Type": "application/json"
			}),
            body: JSON.stringify({"value1": "demo", "value2": "demo2"})
        })
        .then(function(res){ console.log(res); })
        // $.post({
        //     url: 'https://crossorigin.me/https://maker.ifttt.com/trigger/winter-games-game1/with/key/dvHJXlCso1laUplLipy7LT',
        //     contentType : "application/json",
        //     dataType: "jsonp",
        //     //dataType: 'json',
        //     //jsonpCallback: "logResults",
        //     data: JSON.stringify({ value1: "demo" })
        // });
    }

	// add a new line to the chat
	var updateChat = function(party, text) {

		var style = 'you';
		if(party != you) {
			style = 'other';
		}

		var line = $('

');
		line.find('.party').addClass(style).text(party + ':');
		line.find('.text').text(text);

		chat.append(line);

		chat.stop().animate({ scrollTop: chat.prop("scrollHeight")});

	}

	// event binding
	$('.input').bind('keydown', function(e) {
		if(e.keyCode == 13) {
			submitChat();
		}
	});
	$('.input a').bind('click', submitChat);

	// initial chat state
	updateChat(robot, 'Hi buddy, Can I help you?');
	$('#chatbar').focus();

});<|endoftext|>


<commit_before>$(function() {

	// chat aliases
	var you = 'You';
	var robot = 'Robin';

	// slow reply by 400 to 800 ms
	var delayStart = 400;
	var delayEnd = 800;

	// initialize
	var bot = new chatBot();
	var chat = $('.chat');
	var waiting = 0;
	$('.busy').text(robot + ' is typing...');

	// submit user input and get chat-bot's reply
	var submitChat = function() {

		var input = $('.input input').val();
		if(input == '') return;

		$('.input input').val('');
		updateChat(you, input);

		var reply = bot.respondTo(input);
		if(reply == null) return;

		speak(reply);
		ping();

		var latency = Math.floor((Math.random() * (delayEnd - delayStart)) + delayStart);
		$('.busy').css('display', 'block');
		waiting++;
		setTimeout( function() {
			if(typeof reply === 'string') {
				updateChat(robot, reply);
			} else {
				for(var r in reply) {
					updateChat(robot, reply[r]);
				}
			}
			if(--waiting == 0) $('.busy').css('display', 'none');
		}, latency);
	}

	var speak = function(texts){
		if(window.speechSynthesis){
	        for(var i=0; i < texts.length; i++){
	            var utterance = new SpeechSynthesisUtterance(texts[i]);
	            utterance.lang = 'en-US';
	            window.speechSynthesis.speak(utterance);
	        }
		}
    }

    var ping = function(){

    	var payload = {
            "value1": "demo",
            "value2": "demo2"
        };

		var data = new FormData();
		data.append( "json", JSON.stringify( payload ) );

		var ifttt = "https://maker.ifttt.com/trigger/winter-games-game1/with/key/dvHJXlCso1laUplLipy7LT";
        //fetch("http://anyorigin.com/go?url=https://maker.ifttt.com/trigger/winter-games-game1/with/key/dvHJXlCso1laUplLipy7LT",
        //fetch("http://whateverorigin.org/get?url=" + encodeURIComponent(ifttt),
        fetch("https://crossorigin.me/https://maker.ifttt.com/trigger/winter-games-game1/with/key/dvHJXlCso1laUplLipy7LT",
        {
        	method: "POST",
        	mode: 'cors',
        	headers: new Headers({
				"Content-Type": "application/json"
			}),
            //body: JSON.stringify({"value1": "demo", "value2": "demo2"})
            body : data
        })
        .then(function(res){ console.log(res); })
        // $.post({
        //     url: 'https://crossorigin.me/https://maker.ifttt.com/trigger/winter-games-game1/with/key/dvHJXlCso1laUplLipy7LT',
        //     contentType : "application/json",
        //     dataType: "jsonp",
        //     //dataType: 'json',
        //     //jsonpCallback: "logResults",
        //     data: JSON.stringify({ value1: "demo" })
        // });
    }

	// add a new line to the chat
	var updateChat = function(party, text) {

		var style = 'you';
		if(party != you) {
			style = 'other';
		}

		var line = $('

');
		line.find('.party').addClass(style).text(party + ':');
		line.find('.text').text(text);

		chat.append(line);

		chat.stop().animate({ scrollTop: chat.prop("scrollHeight")});

	}

	// event binding
	$('.input').bind('keydown', function(e) {
		if(e.keyCode == 13) {
			submitChat();
		}
	});
	$('.input a').bind('click', submitChat);

	// initial chat state
	updateChat(robot, 'Hi buddy, Can I help you?');
	$('#chatbar').focus();

});<commit_msg>Clean Up<commit_after>$(function() {

	// chat aliases
	var you = 'You';
	var robot = 'Robin';

	// slow reply by 400 to 800 ms
	var delayStart = 400;
	var delayEnd = 800;

	// initialize
	var bot = new chatBot();
	var chat = $('.chat');
	var waiting = 0;
	$('.busy').text(robot + ' is typing...');

	// submit user input and get chat-bot's reply
	var submitChat = function() {

		var input = $('.input input').val();
		if(input == '') return;

		$('.input input').val('');
		updateChat(you, input);

		var reply = bot.respondTo(input);
		if(reply == null) return;

		speak(reply);
		ping();

		var latency = Math.floor((Math.random() * (delayEnd - delayStart)) + delayStart);
		$('.busy').css('display', 'block');
		waiting++;
		setTimeout( function() {
			if(typeof reply === 'string') {
				updateChat(robot, reply);
			} else {
				for(var r in reply) {
					updateChat(robot, reply[r]);
				}
			}
			if(--waiting == 0) $('.busy').css('display', 'none');
		}, latency);
	}

	var speak = function(texts){
		if(window.speechSynthesis){
	        for(var i=0; i < texts.length; i++){
	            var utterance = new SpeechSynthesisUtterance(texts[i]);
	            utterance.lang = 'en-US';
	            window.speechSynthesis.speak(utterance);
	        }
		}
    }

    var ping = function(){

    	var payload = {
            "value1": "demo",
            "value2": "demo2"
        };

		var data = new FormData();
		data.append( "json", JSON.stringify( payload ) );

		var corsProvider = "https://crossorigin.me/";
		var iftttRecipe = "https://maker.ifttt.com/trigger/winter-games-game1/with/key/dvHJXlCso1laUplLipy7LT";
        fetch(corsProvider + iftttRecipe,
        {
        	method: "POST",
        	mode: 'cors',
        	headers: new Headers({
				"Content-Type": "application/json"
			}),
            //body: JSON.stringify({"value1": "demo", "value2": "demo2"})
            body : data
        })
		.then(function(res){ console.log(res); })
        // $.post({
        //     url: 'https://crossorigin.me/https://maker.ifttt.com/trigger/winter-games-game1/with/key/dvHJXlCso1laUplLipy7LT',
        //     contentType : "application/json",
        //     dataType: "jsonp",
        //     //dataType: 'json',
        //     //jsonpCallback: "logResults",
        //     data: JSON.stringify({ value1: "demo" })
        // });
    }

	// add a new line to the chat
	var updateChat = function(party, text) {

		var style = 'you';
		if(party != you) {
			style = 'other';
		}

		var line = $('

');
		line.find('.party').addClass(style).text(party + ':');
		line.find('.text').text(text);

		chat.append(line);

		chat.stop().animate({ scrollTop: chat.prop("scrollHeight")});

	}

	// event binding
	$('.input').bind('keydown', function(e) {
		if(e.keyCode == 13) {
			submitChat();
		}
	});
	$('.input a').bind('click', submitChat);

	// initial chat state
	updateChat(robot, 'Hi buddy, Can I help you?');
	$('#chatbar').focus();

});<|endoftext|>


<commit_before>const MlbRequest = require('./Request');
const url = require('url');

const CONSTANTS = require('../CONFIG').PLAYER;
const ACTIONS = CONSTANTS.ACTIONS;
const PUBLIC_LOOKUP = CONSTANTS.ENDPOINTS.PUBLIC_LOOKUP;
const STATS_API = CONSTANTS.ENDPOINTS.STATS_API;
const WSFB = CONSTANTS.ENDPOINTS.WSFB;

/**
 * Represents an MLB Request.
 */
class PlayerRequest extends MlbRequest {
    /**
     * Create MLB request.
     * @private
     * @param {string} endpoint
     */
    constructor(endpoint) {
        super();
        this.endpoint = endpoint;
        this.url = null;
    }
    /**
     * Builds a URL object to be used by http.
     * Returns `this` for chaining.
     * @private
     * @param {object} options
     * @return {object}
     */
    buildUrl(options) {
        let uri = '';
        switch (this.endpoint) {
        case ACTIONS.SEARCH:
            uri = `${PUBLIC_LOOKUP.BASE}${PUBLIC_LOOKUP.SEARCH}.bam?sport_code='mlb'&name_part='${options.query}%25'&active_sw='${options.active ? 'Y' : 'N'}'`;
            break;
        case ACTIONS.DETAILS:
            uri = `${STATS_API.BASE}/people/?personIds=${options.id}`;
            break;
        case ACTIONS.STATS:
            const statEndpoint = PUBLIC_LOOKUP.STATS[options.stat_role][options.stat_type];
            uri = `${PUBLIC_LOOKUP.BASE}${statEndpoint}.bam?player_id=${options.id}&league_list_id='mlb_hist'&${statEndpoint}.season=${options.stat_season}&game_type='${options.stat_game_type}'`;
            break;
        case ACTIONS.INJURIES:
            uri = `${WSFB.BASE}${WSFB.INJURIES}.bam`;
            break;
        case ACTIONS.NEWS:
            uri = `${WSFB.BASE}${WSFB.NEWS}.bam?player_id='${options.id}'&wsfb_news_browse.recPP=15&wsfb_news_browse.recSP=1`;
            break;
        case ACTIONS.TRANSACTIONS:
            uri = `${PUBLIC_LOOKUP.BASE}${PUBLIC_LOOKUP.TRANSACTIONS}.bam?sport_code='mlb'&start_date=${options.start_date}&end_date=${options.end_date}`;
            break;
        default:
            this.emit('error', 'No endpoint provided.');
            break;
        }
        this.url = url.parse(uri);
        return this;
    }
}

module.exports = PlayerRequest;
<commit_msg>update stats uri to reflect changes to cornelius action options<commit_after>const MlbRequest = require('./Request');
const url = require('url');

const CONSTANTS = require('../CONFIG').PLAYER;
const ACTIONS = CONSTANTS.ACTIONS;
const PUBLIC_LOOKUP = CONSTANTS.ENDPOINTS.PUBLIC_LOOKUP;
const STATS_API = CONSTANTS.ENDPOINTS.STATS_API;
const WSFB = CONSTANTS.ENDPOINTS.WSFB;

/**
 * Represents an MLB Request.
 */
class PlayerRequest extends MlbRequest {
    /**
     * Create MLB request.
     * @private
     * @param {string} endpoint
     */
    constructor(endpoint) {
        super();
        this.endpoint = endpoint;
        this.url = null;
    }
    /**
     * Builds a URL object to be used by http.
     * Returns `this` for chaining.
     * @private
     * @param {object} options
     * @return {object}
     */
    buildUrl(options) {
        let uri = '';
        switch (this.endpoint) {
        case ACTIONS.SEARCH:
            uri = `${PUBLIC_LOOKUP.BASE}${PUBLIC_LOOKUP.SEARCH}.bam?sport_code='mlb'&name_part='${options.query}%25'&active_sw='${options.active ? 'Y' : 'N'}'`;
            break;
        case ACTIONS.DETAILS:
            uri = `${STATS_API.BASE}/people/?personIds=${options.id}`;
            break;
        case ACTIONS.STATS:
            const statEndpoint = PUBLIC_LOOKUP.STATS[options.role][options.type];
            uri = `${PUBLIC_LOOKUP.BASE}${statEndpoint}.bam?player_id=${options.id}&league_list_id='mlb_hist'&${statEndpoint}.season=${options.season}&game_type='${options.game_type}'`;
            break;
        case ACTIONS.INJURIES:
            uri = `${WSFB.BASE}${WSFB.INJURIES}.bam`;
            break;
        case ACTIONS.NEWS:
            uri = `${WSFB.BASE}${WSFB.NEWS}.bam?player_id='${options.id}'&wsfb_news_browse.recPP=15&wsfb_news_browse.recSP=1`;
            break;
        case ACTIONS.TRANSACTIONS:
            uri = `${PUBLIC_LOOKUP.BASE}${PUBLIC_LOOKUP.TRANSACTIONS}.bam?sport_code='mlb'&start_date=${options.start_date}&end_date=${options.end_date}`;
            break;
        default:
            this.emit('error', 'No endpoint provided.');
            break;
        }
        this.url = url.parse(uri);
        return this;
    }
}

module.exports = PlayerRequest;
<|endoftext|>


<commit_before>var app = {
    // Application Constructor
    initialize: function() {
      this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
      document.addEventListener('deviceready', this.onDeviceReady, false);
      document.addEventListener("offline", checkConnection, false);
      document.addEventListener("pause", onPause, false);
      document.addEventListener("resume", onResume, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
      app.receivedEvent('deviceready');
      screen.lockOrientation('portrait');
      localStorage.setItem("saldo_actual",0);
      localStorage.setItem("wisi","false");
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
      getDeviceProperty();
      detectGEO();
    }
  };

  function detectGEO(){
    var options = {
      enableHighAccuracy: true,
      timeout: 5000,
      maximumAge: 75000
    };
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(onSuccess, onError, options);
    } else {
      console.log('Geolocalización no soportada');
    }
  }

// onSuccess Geolocation    //
function onSuccess(position) {
  localStorage.removeItem("position");
  lat1= position.coords.latitude;
  lng1= position.coords.longitude;
  var pos= {lat:lat1,lng:lng1};
  localStorage.setItem("position",JSON.stringify(pos));
  console.log('Coordenadas detectadas');
}

function onError(error) {
  console.log('Error detectando coordenadas');
}

function getDeviceProperty()
{
     var deviceOS  = device.platform  ;  //fetch the device operating system
     var deviceOSVersion = device.version ;  //fetch the device OS version
     localStorage.setItem("OS",deviceOS);
   }

   function onPause() {
    localStorage.setItem("wisi","false");
    console.log("paused");
    if(!localStorage.scanear)searchWISI();
  }

  function searchWISI(){
    window.setTimeout(function(){
      WifiWizard.listNetworks(listHandler, fail);
    },120000);
  }

  function onResume() {
    localStorage.setItem("wisi","true");
    localStorage.setItem("scanner","false");
    console.log("resume");
  }

  function checkConnection() {
    var state=true;
    var networkState = navigator.connection.type;
    var states = {};
    states[Connection.UNKNOWN]  = 'Unknown connection';
    states[Connection.ETHERNET] = 'Ethernet connection';
    states[Connection.WIFI]     = 'WiFi connection';
    states[Connection.CELL_2G]  = 'Cell 2G connection';
    states[Connection.CELL_3G]  = 'Cell 3G connection';
    states[Connection.CELL_4G]  = 'Cell 4G connection';
    states[Connection.CELL]     = 'Cell generic connection';
    states[Connection.NONE]     = 'No network connection';

    if(states[networkState]=='No network connection'){
        //navigator.vibrate(1000);
        //alert('Internet no disponible!');
        state=false;
      }
      return state;
    }

    function fail(e){
      console.log("Detect active WIFI "+e);
    }

  function listHandler(a){
  //console.log("listar "+localStorage.wisi);
  if(localStorage.wisi=="false"){
    var exists=0;
    for(var i=0; i<a.length; i++){
      if((a[i].search("WISI TE CONECTA")>0||a[i].search("VALENCIA_V")>0)&&exists==0){
        if(localStorage.wisi=="false"){
            cordova.plugins.notification.local.schedule({ message:"Red WISI detectada",sound: "file://sounds/HTC Happy.mp3" });
            //myApp.alert("Red WISI detectada", "");
            localStorage.setItem("wisi","true");
            //navigator.vibrate(1000);
            exists++;
          }
        }
      }
      searchWISI();
    }
  }<commit_msg>Sound WISI<commit_after>var app = {
    // Application Constructor
    initialize: function() {
      this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
      document.addEventListener('deviceready', this.onDeviceReady, false);
      document.addEventListener("offline", checkConnection, false);
      document.addEventListener("pause", onPause, false);
      document.addEventListener("resume", onResume, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
      app.receivedEvent('deviceready');
      screen.lockOrientation('portrait');
      localStorage.setItem("saldo_actual",0);
      localStorage.setItem("wisi","false");
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
      getDeviceProperty();
      detectGEO();
    }
  };

  function detectGEO(){
    var options = {
      enableHighAccuracy: true,
      timeout: 5000,
      maximumAge: 75000
    };
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(onSuccess, onError, options);
    } else {
      console.log('Geolocalización no soportada');
    }
  }

// onSuccess Geolocation    //
function onSuccess(position) {
  localStorage.removeItem("position");
  lat1= position.coords.latitude;
  lng1= position.coords.longitude;
  var pos= {lat:lat1,lng:lng1};
  localStorage.setItem("position",JSON.stringify(pos));
  console.log('Coordenadas detectadas');
}

function onError(error) {
  console.log('Error detectando coordenadas');
}

function getDeviceProperty()
{
     var deviceOS  = device.platform  ;  //fetch the device operating system
     var deviceOSVersion = device.version ;  //fetch the device OS version
     localStorage.setItem("OS",deviceOS);
   }

   function onPause() {
    localStorage.setItem("wisi","false");
    console.log("paused");
    if(!localStorage.scanear)searchWISI();
  }

  function searchWISI(){
    window.setTimeout(function(){
      WifiWizard.listNetworks(listHandler, fail);
    },120000);
  }

  function onResume() {
    localStorage.setItem("wisi","true");
    localStorage.setItem("scanner","false");
    console.log("resume");
  }

  function checkConnection() {
    var state=true;
    var networkState = navigator.connection.type;
    var states = {};
    states[Connection.UNKNOWN]  = 'Unknown connection';
    states[Connection.ETHERNET] = 'Ethernet connection';
    states[Connection.WIFI]     = 'WiFi connection';
    states[Connection.CELL_2G]  = 'Cell 2G connection';
    states[Connection.CELL_3G]  = 'Cell 3G connection';
    states[Connection.CELL_4G]  = 'Cell 4G connection';
    states[Connection.CELL]     = 'Cell generic connection';
    states[Connection.NONE]     = 'No network connection';

    if(states[networkState]=='No network connection'){
        //navigator.vibrate(1000);
        //alert('Internet no disponible!');
        state=false;
      }
      return state;
    }

    function fail(e){
      console.log("Detect active WIFI "+e);
    }

  function listHandler(a){
  //console.log("listar "+localStorage.wisi);
  if(localStorage.wisi=="false"){
    var exists=0;
    for(var i=0; i<a.length; i++){
      if((a[i].search("WISI TE CONECTA")>0||a[i].search("VALENCIA_V")>0)&&exists==0){
        if(localStorage.wisi=="false"){
            cordova.plugins.notification.local.schedule({ message:"Red WISI detectada",sound: "file://sounds/HTC Happy.mp3" });
            //myApp.alert("Red WISI detectada", "");
            localStorage.setItem("wisi","true");
            navigator.vibrate(1000);
            exists++;
          }
        }
      }
      searchWISI();
    }
  }<|endoftext|>


<commit_before>var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
        document.addEventListener("offline", checkConnection, false);
        document.addEventListener("pause", onPause, false);
        document.addEventListener("resume", onResume, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
        screen.lockOrientation('portrait');
        localStorage.setItem("saldo_actual",0);
        localStorage.setItem("wisi",false);
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        getDeviceProperty();
        detectGEO();
    }
};
function detectGEO(){
  var options = {
    enableHighAccuracy: true,
    timeout: 5000,
    maximumAge: 75000
  };
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(onSuccess, onError, options);
  } else {
      console.log('Geolocalización no soportada');
  }
}

// onSuccess Geolocation    //
function onSuccess(position) {
  localStorage.removeItem("position");
  lat1= position.coords.latitude;
  lng1= position.coords.longitude;
  var pos= {lat:lat1,lng:lng1};
  localStorage.setItem("position",JSON.stringify(pos));
  console.log('Coordenadas detectadas');
}
function onError(error) {
  console.log('Error detectando coordenadas');
}

function getDeviceProperty()
{
     var deviceOS  = device.platform  ;  //fetch the device operating system
     var deviceOSVersion = device.version ;  //fetch the device OS version
     localStorage.setItem("OS",deviceOS);
}

function onPause() {
    console.log("paused");
    localStorage.setItem("wisi","false");
}
function searchWISI(){
    window.setTimeout(function(){
        WifiWizard.listNetworks(listHandler, fail);
    },30000);
}

function onResume() {
  console.log("resume");
  localStorage.setItem("wisi","true");
}

function checkConnection() {
    var state=true;
    var networkState = navigator.connection.type;
    var states = {};
    states[Connection.UNKNOWN]  = 'Unknown connection';
    states[Connection.ETHERNET] = 'Ethernet connection';
    states[Connection.WIFI]     = 'WiFi connection';
    states[Connection.CELL_2G]  = 'Cell 2G connection';
    states[Connection.CELL_3G]  = 'Cell 3G connection';
    states[Connection.CELL_4G]  = 'Cell 4G connection';
    states[Connection.CELL]     = 'Cell generic connection';
    states[Connection.NONE]     = 'No network connection';

    if(states[networkState]=='No network connection'){
        //navigator.vibrate(1000);
        //alert('Internet no disponible!');
        state=false;
    }
    return state;
}

function fail(e){
    console.log("Detect active WIFI "+e);
}

function listHandler(a){
  //console.log("listar "+localStorage.wisi);
  if(localStorage.wisi=="false"){
    var exists=0;
    for(var i=0; i<a.length; i++){
        if((a[i].search("WISI TE CONECTA")>0||a[i].search("VALENCIA_V")>0)&&exists==0){
            //cordova.plugins.notification.local.schedule({ message:"Red WISI detectada" });
            navigator.vibrate(1000);
            myApp.alert("Red WISI detectada", "");
            localStorage.setItem("wisi","true");
            exists++;
        }
    }
  }
  searchWISI();
}<commit_msg>config<commit_after>var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
        document.addEventListener("offline", checkConnection, false);
        document.addEventListener("pause", onPause, false);
        document.addEventListener("resume", onResume, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
        screen.lockOrientation('portrait');
        localStorage.setItem("saldo_actual",0);
        localStorage.setItem("wisi",false);
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        getDeviceProperty();
        detectGEO();
    }
};
function detectGEO(){
  var options = {
    enableHighAccuracy: true,
    timeout: 5000,
    maximumAge: 75000
  };
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(onSuccess, onError, options);
  } else {
      console.log('Geolocalización no soportada');
  }
}

// onSuccess Geolocation    //
function onSuccess(position) {
  localStorage.removeItem("position");
  lat1= position.coords.latitude;
  lng1= position.coords.longitude;
  var pos= {lat:lat1,lng:lng1};
  localStorage.setItem("position",JSON.stringify(pos));
  console.log('Coordenadas detectadas');
}
function onError(error) {
  console.log('Error detectando coordenadas');
}

function getDeviceProperty()
{
     var deviceOS  = device.platform  ;  //fetch the device operating system
     var deviceOSVersion = device.version ;  //fetch the device OS version
     localStorage.setItem("OS",deviceOS);
}

function onPause() {
    console.log("paused");
    localStorage.setItem("wisi","false");
    searchWISI();
}
function searchWISI(){
    window.setTimeout(function(){
        WifiWizard.listNetworks(listHandler, fail);
    },30000);
}

function onResume() {
  console.log("resume");
  localStorage.setItem("wisi","true");
}

function checkConnection() {
    var state=true;
    var networkState = navigator.connection.type;
    var states = {};
    states[Connection.UNKNOWN]  = 'Unknown connection';
    states[Connection.ETHERNET] = 'Ethernet connection';
    states[Connection.WIFI]     = 'WiFi connection';
    states[Connection.CELL_2G]  = 'Cell 2G connection';
    states[Connection.CELL_3G]  = 'Cell 3G connection';
    states[Connection.CELL_4G]  = 'Cell 4G connection';
    states[Connection.CELL]     = 'Cell generic connection';
    states[Connection.NONE]     = 'No network connection';

    if(states[networkState]=='No network connection'){
        //navigator.vibrate(1000);
        //alert('Internet no disponible!');
        state=false;
    }
    return state;
}

function fail(e){
    console.log("Detect active WIFI "+e);
}

function listHandler(a){
  //console.log("listar "+localStorage.wisi);
  if(localStorage.wisi=="false"){
    var exists=0;
    for(var i=0; i<a.length; i++){
        if((a[i].search("WISI TE CONECTA")>0||a[i].search("VALENCIA_V")>0)&&exists==0){
            //cordova.plugins.notification.local.schedule({ message:"Red WISI detectada" });
            navigator.vibrate(1000);
            myApp.alert("Red WISI detectada", "");
            localStorage.setItem("wisi","true");
            exists++;
        }
    }
  }
  searchWISI();
}<|endoftext|>


<commit_before>module.exports = function (grunt) {
  var path = require('path');
  var which = require('which');
  var fs = require('fs');
  var semver = require('semver');

  var Api = require('crosswalk-apk-generator');

  var generate_apk = function(data,done) {
    var outDir = data.outDir || '.';
    var appConfig = {};
    var envConfig = {};

    // copy user-supplied parameters into envConfig or appConfig
    var envProperties = Object.keys(Api.Env.CONFIG_DEFAULTS);
    Object.keys(data).forEach(function(property){
      if (envProperties.indexOf(property)!=-1) {
        envConfig[property] = data[property];
      } else {
        appConfig[property] = data[property];
      }
    });

    // automatically find androidSDKDir from 'android' command in PATH
    if (!envConfig.androidSDKDir) {
      var androidPath = which.sync('android');
      // up two directories
      envConfig.androidSDKDir = path.dirname(path.dirname(androidPath));
    }

    if (!envConfig.xwalkAndroidDir) {
      var fromEnvVar = process.env.XWALK_APP_TEMPLATE;
      if (fromEnvVar) {
        envConfig.xwalkAndroidDir = fromEnvVar;
      } else {
        grunt.log.error('No xwalk app template specified. Use xwalkAndroidDir in Gruntfile.js or XWALK_APP_TEMPLATE.');
        done(false);
      }
    }

    // determine arch from xwalkAndroidDir/native_libs/
    if (envConfig.xwalkAndroidDir) {
      var nativeLibs = path.join(envConfig.xwalkAndroidDir,'native_libs');
      var arches = fs.readdirSync(nativeLibs);

      if (envConfig.arch) {
        // check it matches
        var foundArch = arches[0].slice(0,3);
        var specified = envConfig.arch.slice(0,3);
        if (foundArch!=specified) {
          grunt.log.error('\'arch\' property set to ('+specified+') in Gruntfile.js, but no app template for that architecture found.');
          grunt.log.error('architectures found :', arches);
          grunt.log.error('have you set xwalkAndroidDir property or XWALK_APP_TEMPLATE correctly?');
          grunt.log.error('XWALK_APP_TEMPLATE: ', process.env.XWALK_APP_TEMPLATE);
          done(false);
        }
      } else {
        // use the one in native_libs, if only one
        if (arches.length==0) {
          grunt.log.error('no architectures found in '+nativeLibs);
          done(false);
        } else
        if (arches.length>1) {
          grunt.log.error('multiple architectures found in '+nativeLibs);
          grunt.log.error('please specify using the \'arch\' property in your Gruntfile.js');
          done(false);
        }

        // use discovered
        envConfig.arch = arches[0];
      }
    }

    if (!envConfig.androidAPIVersion) {
      // get the api latest version from androidSDK/build-tools
      var buildToolsDir = path.join(envConfig.androidSDKDir,"build-tools");
      var files = fs.readdirSync(buildToolsDir);
      var androidAPIVersions = files.sort(semver.compare);
      var length = androidAPIVersions.length;
      var latest = androidAPIVersions[length-1];
      envConfig.androidAPIVersion = latest;
    }

    var logger = grunt.log;
    logger.log = logger.write; // Api.CommandRunner calls logger.log()

    var commandRunner = Api.CommandRunner(data.verbose, logger);

    // create a promise for a configured Env object
    var envPromise = Api.Env(envConfig, {commandRunner: commandRunner});

    // create a promise for a configured App object
    var appPromise = Api.App(appConfig);

    // use the Q promises library to synchronise the promises, so we
    // can create the objects in "parallel"
    Api.Q.all([envPromise, appPromise])
    .then(
      function (objects) {
        // once the App and Env are constructed, use the Env instance
        // to do a build for the App instance
        var env = objects[0];
        var app = objects[1];

        // create a Locations object for this App instance
        var locations = Api.Locations(app.sanitisedName, app.pkg, env.arch, outDir);

        // run the build
        return env.build(app, locations);
      }
    )
    .done(
      // success
      function (finalApk) {
        grunt.log.writeln('\n*** DONE\n    output apk path is ' + finalApk);
        done();
      },

      // error handler
      function (err) {
        grunt.log.error('!!! ERROR');
        grunt.log.error(err.stack);
        done(false);
      }
    );
  };

  /**
  * Build an apk
  *
  * Deps:
  *
  * Configuration options:
  *
  *   appName - the name of the application; used as the base filename
  *   outDir - output directory to put the zipfile into
  *   version - application version
  *
  */
  grunt.registerMultiTask('crosswalk', 'Tasks for generating apk packages for crosswalk on Android', function (identifier) {
    var done = this.async();

    generate_apk(this.data, done);
  });

};

<commit_msg>Fix for Android SDK installed in a bundle.<commit_after>module.exports = function (grunt) {
  var path = require('path');
  var which = require('which');
  var fs = require('fs');
  var semver = require('semver');
  var _ = require('lodash');

  var Api = require('crosswalk-apk-generator');

  var generate_apk = function(data,done) {
    var outDir = data.outDir || '.';
    var appConfig = {};
    var envConfig = {};

    // copy user-supplied parameters into envConfig or appConfig
    var envProperties = Object.keys(Api.Env.CONFIG_DEFAULTS);
    Object.keys(data).forEach(function(property){
      if (envProperties.indexOf(property)!=-1) {
        envConfig[property] = data[property];
      } else {
        appConfig[property] = data[property];
      }
    });

    // automatically find androidSDKDir from 'android' command in PATH
    if (!envConfig.androidSDKDir) {
      var androidPath = which.sync('android');
      // up two directories
      envConfig.androidSDKDir = path.dirname(path.dirname(androidPath));
    }

    if (!envConfig.xwalkAndroidDir) {
      var fromEnvVar = process.env.XWALK_APP_TEMPLATE;
      if (fromEnvVar) {
        envConfig.xwalkAndroidDir = fromEnvVar;
      } else {
        grunt.log.error('No xwalk app template specified. Use xwalkAndroidDir in Gruntfile.js or XWALK_APP_TEMPLATE.');
        done(false);
      }
    }

    // determine arch from xwalkAndroidDir/native_libs/
    if (envConfig.xwalkAndroidDir) {
      var nativeLibs = path.join(envConfig.xwalkAndroidDir,'native_libs');
      var arches = fs.readdirSync(nativeLibs);

      if (envConfig.arch) {
        // check it matches
        var foundArch = arches[0].slice(0,3);
        var specified = envConfig.arch.slice(0,3);
        if (foundArch!=specified) {
          grunt.log.error('\'arch\' property set to ('+specified+') in Gruntfile.js, but no app template for that architecture found.');
          grunt.log.error('architectures found :', arches);
          grunt.log.error('have you set xwalkAndroidDir property or XWALK_APP_TEMPLATE correctly?');
          grunt.log.error('XWALK_APP_TEMPLATE: ', process.env.XWALK_APP_TEMPLATE);
          done(false);
        }
      } else {
        // use the one in native_libs, if only one
        if (arches.length==0) {
          grunt.log.error('no architectures found in '+nativeLibs);
          done(false);
        } else
        if (arches.length>1) {
          grunt.log.error('multiple architectures found in '+nativeLibs);
          grunt.log.error('please specify using the \'arch\' property in your Gruntfile.js');
          done(false);
        }

        // use discovered
        envConfig.arch = arches[0];
      }
    }

    if (!envConfig.androidAPIVersion) {
      // get the api latest version from androidSDK/build-tools
      var platformsDir = path.join(envConfig.androidSDKDir,"platforms");
      var files = fs.readdirSync(platformsDir);
      var androidAPIVersions = _.map(files,function(file) {
          var bits = file.split("-");
          return bits[bits.length-1];
      });
      var sorted = androidAPIVersions.sort(semver.compare);
      var latest = sorted[sorted.length-1];
      envConfig.androidAPIVersion = latest;
    }

    var logger = grunt.log;
    logger.log = logger.write; // Api.CommandRunner calls logger.log()

    var commandRunner = Api.CommandRunner(data.verbose, logger);

    // create a promise for a configured Env object
    var envPromise = Api.Env(envConfig, {commandRunner: commandRunner});

    // create a promise for a configured App object
    var appPromise = Api.App(appConfig);

    // use the Q promises library to synchronise the promises, so we
    // can create the objects in "parallel"
    Api.Q.all([envPromise, appPromise])
    .then(
      function (objects) {
        // once the App and Env are constructed, use the Env instance
        // to do a build for the App instance
        var env = objects[0];
        var app = objects[1];

        // create a Locations object for this App instance
        var locations = Api.Locations(app.sanitisedName, app.pkg, env.arch, outDir);

        // run the build
        return env.build(app, locations);
      }
    )
    .done(
      // success
      function (finalApk) {
        grunt.log.writeln('\n*** DONE\n    output apk path is ' + finalApk);
        done();
      },

      // error handler
      function (err) {
        grunt.log.error('!!! ERROR');
        grunt.log.error(err.stack);
        done(false);
      }
    );
  };

  /**
  * Build an apk
  *
  * Deps:
  *
  * Configuration options:
  *
  *   appName - the name of the application; used as the base filename
  *   outDir - output directory to put the zipfile into
  *   version - application version
  *
  */
  grunt.registerMultiTask('crosswalk', 'Tasks for generating apk packages for crosswalk on Android', function (identifier) {
    var done = this.async();

    generate_apk(this.data, done);
  });

};

<|endoftext|>


<commit_before>angular.module('app.controllers').controller('home', function ($scope, $timeout, socialActivity, homeCtrlParams,
        profile, activity, groups, $ionicScrollDelegate, favorite, $ionicPlatform, $rootScope) {
  $scope.filter = homeCtrlParams.filter;

  $scope.isLoadMore = false;
  var activityCollection = activity.getActivities();

  $scope.changeGroupFilter = function(group){
    var isDifferentGroupThanCurrentlyActive = $scope.filter.selectedGroup != group
    if(!$scope.isSpinnerShow && isDifferentGroupThanCurrentlyActive)
      $scope.showSpinner();

    if(isDifferentGroupThanCurrentlyActive){
      // we want to make sure the spinner is displayed prior the rendering starts
      $timeout(function(){
        $scope.filter.selectedGroup = group
      }, 0);
    }

  }

  $scope.closeModalImageViewer = function(){
    $rootScope.modalImageUrl = null
  }

  $scope.canCreateLeaderContent = function(){
    var selectedGroupID = null
    if($scope.filter.selectedGroup)
      selectedGroupID = $scope.filter.selectedGroup.id
    return groups.canCreateLeaderContent(selectedGroupID)
  }

  function refreshListOfActivities() {
    if(homeCtrlParams.filter.selectedGroup)
      $scope.activities = homeCtrlParams.filter.selectedGroup.activities
    else
      $scope.activities = activityCollection.getFilteredModels();

    //we want to wait until rendering is finished
    $timeout(function(){
      $scope.hideSpinner()
    }, 0);
  }

  function setFiltersData() {
    homeCtrlParams.filter.groups = groups.groupsJoinedByCurrentUser();
    _(homeCtrlParams.filter.groups).each(function (group) {
      group.activities = activityCollection.getFilteredModels(group);
      group.inPriorityZoneCount = activityCollection.inPriorityZoneCount(group.activities);
      group.read = !_.some(group.activities, function (item) {
        return !item.get('read');
      });
      if (homeCtrlParams.filter.selectedGroup && homeCtrlParams.filter.selectedGroup.id === group.id) {
        homeCtrlParams.filter.selectedGroup = group;
      }
    });
    homeCtrlParams.filter.inPriorityZoneCount = activityCollection.inPriorityZoneCount(activityCollection.getFilteredModels());
  }

  function prepare() {
    homeCtrlParams.loaded = true;
    activityCollection.sort();
    setFiltersData();

    $scope.loading = false;
    $ionicScrollDelegate.resize();
  }

  function loadActivities(loadType) {
    var prevSize = activityCollection.size();
    activity.load(loadType).then(function () {
      if (loadType === 'append' && prevSize === activityCollection.size()) {
        $scope.isLoadMore = false;
      } else {
        $scope.isLoadMore = true;
      }
      prepare();

      $scope.$emit('home.activities-reloaded');
      $scope.$broadcast('scroll.refreshComplete');
      $scope.$broadcast('scroll.infiniteScrollComplete');
      refreshListOfActivities();
    }).finally(socialActivity.load);
  }

  $scope.togglePostWindow = function () {
    $scope.showPostWindow = !$scope.showPostWindow;
    $scope.execApply();
  };

  $scope.createNewContent = function (type) {
    var selectedGroup = homeCtrlParams.filter.selectedGroup ? homeCtrlParams.filter.selectedGroup.id : ''
    var p = '/'+type+'/create/' + selectedGroup
    $scope.path(p);
    $scope.showPostWindow = false;
  };

  $scope.filterLineStep = function () {
    return 5;
  };

  $scope.steps = function () {
    var items = homeCtrlParams.filter.groups.length - 3;
    items = items > 0 ? items : 0;
    var step = $scope.filterLineStep();
    var stepsCount = Math.ceil(items / step);
    var steps = [3];
    for (var i = 1; i < stepsCount; i++) {
      steps.push(i * step + 3);
    }
    if (items && 0 === items % step) {
      steps.push(steps[steps.length - 1] + step);
    }
    return steps;
  };

  $scope.loadMoreActivities = function () {
    loadActivities('append');
  };

  $scope.pullToRefresh = function () {
    loadActivities('clearAndLoad');
  };

  $scope.$watch('filter.selectedGroup', refreshListOfActivities);
  $scope.$watch('loading', function () {
    if ($scope.loading) {
      $scope.showSpinner();
    } else if ($scope.loading === false) {
      $scope.hideSpinner();
    }
  });

  $scope.$on('notification.received', function () {
    loadActivities('refresh');
  });

  $scope.$on('activity.reload', function () {
    loadActivities('refresh');
  });

  //move scroll to top when filter is changed
  $scope.$watch('filter.selectedGroup', function (nVal) {
    if (typeof (nVal) !== undefined) {
      $ionicPlatform.ready(function () {
        if($ionicScrollDelegate){
          $ionicScrollDelegate.resize();
          $ionicScrollDelegate.scrollTop();
        }
      })
    }
  });

  //call this when this view is loaded because this view is cached
  $scope.$on('$ionicView.enter', function () {
    if (!profile.get()) {
      profile.load();
    }

    if (!homeCtrlParams.loaded || activity.shouldRefreshActivities()) {
      if (activityCollection.size() === 0) {
        $scope.isLoadMore = true;
      } else {
        loadActivities('refresh');
      }
    } else {
      prepare();
    }

  });

  $scope.$on('$ionicView.leave', function () {
    $scope.closeModalImageViewer()
  })

  //call this because cache may be loaded
  setFiltersData();
  refreshListOfActivities();
});

angular.module('app.controllers').run(function (homeCtrlParams, $document, $rootScope) {
  $document.bind('resume', function () {
    homeCtrlParams.loaded = false;
    $rootScope.$broadcast('activity.reload');
    $rootScope.execApply();
  });
});

angular.module('app.controllers').controller('preload', function (topBar, session, profile, $location, notifications) {
  if (session.token) {
    if (session.is_registration_complete) {
      notifications.init()
      profile.load().then(function () {
        profile.checkRemind();
      });
      if (!$location.path() || '/' === $location.path() || '/preload' === $location.path()) {
        $location.path('/main');
      }
    } else {
      $location.path('/profile-for-facebook-newscomers');
    }
  } else {
    $location.path('/login');
  }
});

angular.module('app.controllers').directive('iActivity', function ($rootScope, questions, petitions, discussion, elapsedFilter, follows, session, iParse, $sce, favorite, microPetitions, posts, userPetitions) {

  function eventCtrl($scope) {
    $scope.templateSrc = 'templates/home/activities/event.html';
  }

  function newsCtrl($scope) {
    $scope.templateSrc = 'templates/home/activities/news.html';
    $scope.entity = $scope.activity.get('entity');
    $scope.rate = function (action) {
      $scope.sending = true;
      discussion.loadTree('poll', $scope.entity.id).then(function (discussionTree) {
        var comment = discussionTree.root
        discussion.rate(comment, action).then(function (comment) {
          $scope.activity.set('rate_up', comment.rate_up).set('rate_down', comment.rate_down);
          $scope.sending = false;
          $rootScope.showToast((action === 'down' ? 'Down' : 'Up') + ' voted!');
        }, function () {
          $scope.sending = false;
        });
      });
    };
  }

  function paymentCtrl($scope) {
    $scope.templateSrc = 'templates/home/activities/payment.html';
  }

  function postCtrl($scope) {
    $scope.templateSrc = 'templates/home/activities/post.html';
    $scope.currentUserIsActivityOwner = $scope.activity.get('owner').id == session.user_id
    $scope.booster = $scope.activity.get('owner').type === 'group' ? 100 : $scope.activity.getQuorumCompletedPercent();

    $scope.upvote = function(){
      $scope.sending = true;
      $scope.activity.upvote().then(function(answer){
        $scope.sending = false;
        $scope.showToast('Post upvoted!');
      })
    }

    $scope.downvote = function(){
      $scope.sending = true;
      $scope.activity.downvote().then(function(answer){
        $scope.sending = false;
        $scope.showToast('Post downvoted!');
      })
    }

    $scope.undoVote = function(){
      $scope.sending = true;
      $scope.activity.undoVote().then(function(answer){
        $scope.sending = false;
        $scope.showToast('Post vote undo successful!');
      })
    }

  }

  function userPetitionCtrl($scope) {
    $scope.templateSrc = 'templates/home/activities/user-petition.html';

    $scope.sign = function () {
      $scope.sending = true
      $scope.activity.sign().then(function(){
          $scope.sending = false;
          $scope.showToast('User petition signed.');
      })
    };

    $scope.unsign = function () {
      $scope.sending = true;
      $scope.activity.unsign().then(function (response) {
        $scope.sending = false;
        $scope.showToast('User petition unsigned.');
      });
    };
  }

  function petitionCtrl($scope) {
    $scope.templateSrc = 'templates/home/activities/petition.html';

    $scope.sign = function () {
      $scope.sending = true
      $scope.activity.sign().then(function(){
          $scope.sending = false;
          $scope.showToast('Petition signed.');
      })
    };

    $scope.unsign = function () {
      $scope.sending = true
      $scope.activity.unsign().then(function(){
          $scope.sending = false;
          $scope.showToast('Petition unsigned.');
      })
    };
  }

  function questionCtrl($scope) {
    $scope.templateSrc = 'templates/home/activities/question.html';
  }

  var ctrlByType = {
    'leader-event': eventCtrl,
    'leader-news': newsCtrl,
    'crowdfunding-payment-request': paymentCtrl,
    'payment-request': paymentCtrl,
    'post': postCtrl,
    'user-petition': userPetitionCtrl,
    'petition': petitionCtrl,
    'question': questionCtrl
  };

  return {
    scope: {
      activity: '='
    },
    restrict: 'E',
    template: '<ng-include src="templateSrc"></ng-include>',
    controller: function ($scope) {
      $scope.activity.prepare()
      $scope.imageURLFittedToScreenWidth = function(url){
        if(url && url.indexOf('imgix.net') > 0)
          return(url +'&w=' + screen.width)
        else
          return url
      }
      $scope.screenWidth = screen.width;
      $scope.showToast = $rootScope.showToast;
      $scope.navigateTo = $rootScope.navigateTo;
      $scope.isBookmarked = function(){
        return favorite.isBookmarked($scope.activity)
      }
      $scope.bookmarkButtonClicked = function(){
        if($scope.isBookmarked()){
          favorite.removeBookmark($scope.activity)
          $scope.showToast('Removed from Favorites!');
        } else {
         favorite.addBookmark($scope.activity)
         $scope.showToast('Saved to Favorites!');
        }
      }
      $scope.navigateToActivity = function (activity, focus, e) {

        activity.setRead();
        if (e && e.target.tagName.toLowerCase() === 'hash-tag') {
          $rootScope.openTag(angular.element(e.target).text());
        } else {
          $rootScope.navigateTo('activity', activity, focus);
        }
      };

      // if($scope.activity.get('entity').id == 517)
      //    console.log(JSON.stringify($scope.activity))
      // else return

      $scope.title = $scope.activity.get('title');
      var description_raw = $scope.activity.get('description_html')
      if(description_raw == null || description_raw.length == 0)
        description_raw = $scope.activity.get('description')
      $scope.description = iParse.wrapHashTags(description_raw)
      $scope.avatar_file_path = $scope.activity.get('user').avatar_file_name;
      $scope.iconClass = $scope.activity.getIcon();
      $scope.sent_at_elapsed = elapsedFilter($scope.activity.get('sent_at'));
      $scope.responses_count = $scope.activity.get('responses_count');
      $scope.comments_count = $scope.activity.getCommentCount()
      $scope.isDefaultAvatar = $rootScope.isDefaultAvatar($scope.avatar_file_path);

      var activityOwnerID = null, activityOwnerFollow = null;

      if($scope.activity.getCreator()){
        activityOwnerID = $scope.activity.getCreator().id
        activityOwnerFollow = follows.getOrCreateUser(activityOwnerID);
      }

      $scope.showFollow = follows.loaded && !$scope.activity.isOwn()
      $scope.followClicked = function(){
        if(activityOwnerFollow && activityOwnerFollow.isFollowedByCurrentUser() && activityOwnerFollow.hasApprovedCurrentUser())
          $scope.showToast('You are following this user');
        else if (activityOwnerFollow && activityOwnerFollow.isFollowedByCurrentUser() && !activityOwnerFollow.hasApprovedCurrentUser())
          $scope.showToast('Waiting for user to approve...');
        else {
          $scope.sending = true;
          activityOwnerFollow.followByCurrentUser().then(function () {
            $scope.activity.followable = false;
            $scope.sending = false;
            follows.load().then(function(){
              activityOwnerFollow = follows.getOrCreateUser(activityOwnerID);
            })
          });
        }
      }

      $scope.openUrlInExternalBrowser = function(url){
        if(url.substring(0,4) != 'http')
          url = 'http://'+url
        $rootScope.openSystem(url)
      }

      $scope.showInModalImageViewer = function(url){
        $rootScope.modalImageUrl = url
      }

      $scope.followIcons = function(){
        if(activityOwnerFollow && activityOwnerFollow.isFollowedByCurrentUser() && activityOwnerFollow.hasApprovedCurrentUser())
          return ['icon ion-person calm', 'icon ion-minus-circled']
        else if(activityOwnerFollow && activityOwnerFollow.isFollowedByCurrentUser() && !activityOwnerFollow.hasApprovedCurrentUser())
          return ['icon ion-person', 'icon ion-android-time calm']
        else
          return ['icon ion-person', 'icon ion-plus-circled calm']
      }

      $scope.subscribeToNotifications = function(){
        $scope.activity.subscribeToNotifications().then(function (response) {
          $scope.showToast('Subscribed to item notifications.');
          // due to https://github.com/PowerlineApp/powerline-mobile/issues/248#issuecomment-248547358
          $rootScope.$emit('activity.mark-as-subscribed',$scope.activity.dataType(), $scope.activity.dataID());
        })
      }

      $scope.unsubscribeFromNotifications = function(){
        $scope.activity.unsubscribeFromNotifications().then(function (response) {
          $scope.showToast('Unsubscribed from item notifications.');
          $rootScope.$emit('activity.mark-as-unsubscribed',$scope.activity.dataType(), $scope.activity.dataID());
        })
      }

      var activityType = $scope.activity.dataType()
      if (ctrlByType[activityType]) {
        ctrlByType[activityType]($scope);
      } else {
        $scope.templateSrc = 'templates/home/activities/default.html';
      }
    }
  };
});<commit_msg>#462 Fix button action on notification<commit_after>angular.module('app.controllers').controller('home', function ($scope, $timeout, socialActivity, homeCtrlParams,
        profile, activity, groups, $ionicScrollDelegate, favorite, $ionicPlatform, $rootScope) {
  $scope.filter = homeCtrlParams.filter;

  $scope.isLoadMore = false;
  var activityCollection = activity.getActivities();

  $scope.changeGroupFilter = function(group){
    var isDifferentGroupThanCurrentlyActive = $scope.filter.selectedGroup != group
    if(!$scope.isSpinnerShow && isDifferentGroupThanCurrentlyActive)
      $scope.showSpinner();

    if(isDifferentGroupThanCurrentlyActive){
      // we want to make sure the spinner is displayed prior the rendering starts
      $timeout(function(){
        $scope.filter.selectedGroup = group
      }, 0);
    }

  }

  $scope.closeModalImageViewer = function(){
    $rootScope.modalImageUrl = null
  }

  $scope.canCreateLeaderContent = function(){
    var selectedGroupID = null
    if($scope.filter.selectedGroup)
      selectedGroupID = $scope.filter.selectedGroup.id
    return groups.canCreateLeaderContent(selectedGroupID)
  }

  function refreshListOfActivities() {
    if(homeCtrlParams.filter.selectedGroup)
      $scope.activities = homeCtrlParams.filter.selectedGroup.activities
    else
      $scope.activities = activityCollection.getFilteredModels();

    //we want to wait until rendering is finished
    $timeout(function(){
      $scope.hideSpinner()
    }, 0);
  }

  function setFiltersData() {
    homeCtrlParams.filter.groups = groups.groupsJoinedByCurrentUser();
    _(homeCtrlParams.filter.groups).each(function (group) {
      group.activities = activityCollection.getFilteredModels(group);
      group.inPriorityZoneCount = activityCollection.inPriorityZoneCount(group.activities);
      group.read = !_.some(group.activities, function (item) {
        return !item.get('read');
      });
      if (homeCtrlParams.filter.selectedGroup && homeCtrlParams.filter.selectedGroup.id === group.id) {
        homeCtrlParams.filter.selectedGroup = group;
      }
    });
    homeCtrlParams.filter.inPriorityZoneCount = activityCollection.inPriorityZoneCount(activityCollection.getFilteredModels());
  }

  function prepare() {
    homeCtrlParams.loaded = true;
    activityCollection.sort();
    setFiltersData();

    $scope.loading = false;
    $ionicScrollDelegate.resize();
  }

  function loadActivities(loadType) {
    var prevSize = activityCollection.size();
    activity.load(loadType).then(function () {
      if (loadType === 'append' && prevSize === activityCollection.size()) {
        $scope.isLoadMore = false;
      } else {
        $scope.isLoadMore = true;
      }
      prepare();

      $scope.$emit('home.activities-reloaded');
      $scope.$broadcast('scroll.refreshComplete');
      $scope.$broadcast('scroll.infiniteScrollComplete');
      refreshListOfActivities();
    }).finally(socialActivity.load);
  }

  $scope.togglePostWindow = function () {
    $scope.showPostWindow = !$scope.showPostWindow;
    $scope.execApply();
  };

  $scope.createNewContent = function (type) {
    var selectedGroup = homeCtrlParams.filter.selectedGroup ? homeCtrlParams.filter.selectedGroup.id : ''
    var p = '/'+type+'/create/' + selectedGroup
    $scope.path(p);
    $scope.showPostWindow = false;
  };

  $scope.filterLineStep = function () {
    return 5;
  };

  $scope.steps = function () {
    var items = homeCtrlParams.filter.groups.length - 3;
    items = items > 0 ? items : 0;
    var step = $scope.filterLineStep();
    var stepsCount = Math.ceil(items / step);
    var steps = [3];
    for (var i = 1; i < stepsCount; i++) {
      steps.push(i * step + 3);
    }
    if (items && 0 === items % step) {
      steps.push(steps[steps.length - 1] + step);
    }
    return steps;
  };

  $scope.loadMoreActivities = function () {
    loadActivities('append');
  };

  $scope.pullToRefresh = function () {
    loadActivities('clearAndLoad');
  };

  $scope.$watch('filter.selectedGroup', refreshListOfActivities);
  $scope.$watch('loading', function () {
    if ($scope.loading) {
      $scope.showSpinner();
    } else if ($scope.loading === false) {
      $scope.hideSpinner();
    }
  });

  $scope.$on('notification.received', function () {
    loadActivities('refresh');
  });

  $scope.$on('activity.reload', function () {
    loadActivities('refresh');
  });

  //move scroll to top when filter is changed
  $scope.$watch('filter.selectedGroup', function (nVal) {
    if (typeof (nVal) !== undefined) {
      $ionicPlatform.ready(function () {
        if($ionicScrollDelegate){
          $ionicScrollDelegate.resize();
          $ionicScrollDelegate.scrollTop();
        }
      })
    }
  });

  //call this when this view is loaded because this view is cached
  $scope.$on('$ionicView.enter', function () {
    if (!profile.get()) {
      profile.load();
    }

    if (!homeCtrlParams.loaded || activity.shouldRefreshActivities()) {
      if (activityCollection.size() === 0) {
        $scope.isLoadMore = true;
      } else {
        loadActivities('refresh');
      }
    } else {
      prepare();
    }

  });

  $scope.$on('$ionicView.leave', function () {
    $scope.closeModalImageViewer()
  })

  //call this because cache may be loaded
  setFiltersData();
  refreshListOfActivities();
});

angular.module('app.controllers').run(function (homeCtrlParams, $document, $rootScope) {
  $document.bind('resume', function () {
    homeCtrlParams.loaded = false;
    $rootScope.$broadcast('activity.reload');
    $rootScope.execApply();
  });
});

angular.module('app.controllers').controller('preload', function (topBar, session, profile, $location, notifications, $ionicPlatform) {
  if (session.token) {
    if (session.is_registration_complete) {
      $ionicPlatform.ready(function () {
      notifications.init()
      });
      profile.load().then(function () {
        profile.checkRemind();
      });
      if (!$location.path() || '/' === $location.path() || '/preload' === $location.path()) {
        $location.path('/main');
      }
    } else {
      $location.path('/profile-for-facebook-newscomers');
    }
  } else {
    $location.path('/login');
  }
});

angular.module('app.controllers').directive('iActivity', function ($rootScope, questions, petitions, discussion, elapsedFilter, follows, session, iParse, $sce, favorite, microPetitions, posts, userPetitions) {

  function eventCtrl($scope) {
    $scope.templateSrc = 'templates/home/activities/event.html';
  }

  function newsCtrl($scope) {
    $scope.templateSrc = 'templates/home/activities/news.html';
    $scope.entity = $scope.activity.get('entity');
    $scope.rate = function (action) {
      $scope.sending = true;
      discussion.loadTree('poll', $scope.entity.id).then(function (discussionTree) {
        var comment = discussionTree.root
        discussion.rate(comment, action).then(function (comment) {
          $scope.activity.set('rate_up', comment.rate_up).set('rate_down', comment.rate_down);
          $scope.sending = false;
          $rootScope.showToast((action === 'down' ? 'Down' : 'Up') + ' voted!');
        }, function () {
          $scope.sending = false;
        });
      });
    };
  }

  function paymentCtrl($scope) {
    $scope.templateSrc = 'templates/home/activities/payment.html';
  }

  function postCtrl($scope) {
    $scope.templateSrc = 'templates/home/activities/post.html';
    $scope.currentUserIsActivityOwner = $scope.activity.get('owner').id == session.user_id
    $scope.booster = $scope.activity.get('owner').type === 'group' ? 100 : $scope.activity.getQuorumCompletedPercent();

    $scope.upvote = function(){
      $scope.sending = true;
      $scope.activity.upvote().then(function(answer){
        $scope.sending = false;
        $scope.showToast('Post upvoted!');
      })
    }

    $scope.downvote = function(){
      $scope.sending = true;
      $scope.activity.downvote().then(function(answer){
        $scope.sending = false;
        $scope.showToast('Post downvoted!');
      })
    }

    $scope.undoVote = function(){
      $scope.sending = true;
      $scope.activity.undoVote().then(function(answer){
        $scope.sending = false;
        $scope.showToast('Post vote undo successful!');
      })
    }

  }

  function userPetitionCtrl($scope) {
    $scope.templateSrc = 'templates/home/activities/user-petition.html';

    $scope.sign = function () {
      $scope.sending = true
      $scope.activity.sign().then(function(){
          $scope.sending = false;
          $scope.showToast('User petition signed.');
      })
    };

    $scope.unsign = function () {
      $scope.sending = true;
      $scope.activity.unsign().then(function (response) {
        $scope.sending = false;
        $scope.showToast('User petition unsigned.');
      });
    };
  }

  function petitionCtrl($scope) {
    $scope.templateSrc = 'templates/home/activities/petition.html';

    $scope.sign = function () {
      $scope.sending = true
      $scope.activity.sign().then(function(){
          $scope.sending = false;
          $scope.showToast('Petition signed.');
      })
    };

    $scope.unsign = function () {
      $scope.sending = true
      $scope.activity.unsign().then(function(){
          $scope.sending = false;
          $scope.showToast('Petition unsigned.');
      })
    };
  }

  function questionCtrl($scope) {
    $scope.templateSrc = 'templates/home/activities/question.html';
  }

  var ctrlByType = {
    'leader-event': eventCtrl,
    'leader-news': newsCtrl,
    'crowdfunding-payment-request': paymentCtrl,
    'payment-request': paymentCtrl,
    'post': postCtrl,
    'user-petition': userPetitionCtrl,
    'petition': petitionCtrl,
    'question': questionCtrl
  };

  return {
    scope: {
      activity: '='
    },
    restrict: 'E',
    template: '<ng-include src="templateSrc"></ng-include>',
    controller: function ($scope) {
      $scope.activity.prepare()
      $scope.imageURLFittedToScreenWidth = function(url){
        if(url && url.indexOf('imgix.net') > 0)
          return(url +'&w=' + screen.width)
        else
          return url
      }
      $scope.screenWidth = screen.width;
      $scope.showToast = $rootScope.showToast;
      $scope.navigateTo = $rootScope.navigateTo;
      $scope.isBookmarked = function(){
        return favorite.isBookmarked($scope.activity)
      }
      $scope.bookmarkButtonClicked = function(){
        if($scope.isBookmarked()){
          favorite.removeBookmark($scope.activity)
          $scope.showToast('Removed from Favorites!');
        } else {
         favorite.addBookmark($scope.activity)
         $scope.showToast('Saved to Favorites!');
        }
      }
      $scope.navigateToActivity = function (activity, focus, e) {

        activity.setRead();
        if (e && e.target.tagName.toLowerCase() === 'hash-tag') {
          $rootScope.openTag(angular.element(e.target).text());
        } else {
          $rootScope.navigateTo('activity', activity, focus);
        }
      };

      // if($scope.activity.get('entity').id == 517)
      //    console.log(JSON.stringify($scope.activity))
      // else return

      $scope.title = $scope.activity.get('title');
      var description_raw = $scope.activity.get('description_html')
      if(description_raw == null || description_raw.length == 0)
        description_raw = $scope.activity.get('description')
      $scope.description = iParse.wrapHashTags(description_raw)
      $scope.avatar_file_path = $scope.activity.get('user').avatar_file_name;
      $scope.iconClass = $scope.activity.getIcon();
      $scope.sent_at_elapsed = elapsedFilter($scope.activity.get('sent_at'));
      $scope.responses_count = $scope.activity.get('responses_count');
      $scope.comments_count = $scope.activity.getCommentCount()
      $scope.isDefaultAvatar = $rootScope.isDefaultAvatar($scope.avatar_file_path);

      var activityOwnerID = null, activityOwnerFollow = null;

      if($scope.activity.getCreator()){
        activityOwnerID = $scope.activity.getCreator().id
        activityOwnerFollow = follows.getOrCreateUser(activityOwnerID);
      }

      $scope.showFollow = follows.loaded && !$scope.activity.isOwn()
      $scope.followClicked = function(){
        if(activityOwnerFollow && activityOwnerFollow.isFollowedByCurrentUser() && activityOwnerFollow.hasApprovedCurrentUser())
          $scope.showToast('You are following this user');
        else if (activityOwnerFollow && activityOwnerFollow.isFollowedByCurrentUser() && !activityOwnerFollow.hasApprovedCurrentUser())
          $scope.showToast('Waiting for user to approve...');
        else {
          $scope.sending = true;
          activityOwnerFollow.followByCurrentUser().then(function () {
            $scope.activity.followable = false;
            $scope.sending = false;
            follows.load().then(function(){
              activityOwnerFollow = follows.getOrCreateUser(activityOwnerID);
            })
          });
        }
      }

      $scope.openUrlInExternalBrowser = function(url){
        if(url.substring(0,4) != 'http')
          url = 'http://'+url
        $rootScope.openSystem(url)
      }

      $scope.showInModalImageViewer = function(url){
        $rootScope.modalImageUrl = url
      }

      $scope.followIcons = function(){
        if(activityOwnerFollow && activityOwnerFollow.isFollowedByCurrentUser() && activityOwnerFollow.hasApprovedCurrentUser())
          return ['icon ion-person calm', 'icon ion-minus-circled']
        else if(activityOwnerFollow && activityOwnerFollow.isFollowedByCurrentUser() && !activityOwnerFollow.hasApprovedCurrentUser())
          return ['icon ion-person', 'icon ion-android-time calm']
        else
          return ['icon ion-person', 'icon ion-plus-circled calm']
      }

      $scope.subscribeToNotifications = function(){
        $scope.activity.subscribeToNotifications().then(function (response) {
          $scope.showToast('Subscribed to item notifications.');
          // due to https://github.com/PowerlineApp/powerline-mobile/issues/248#issuecomment-248547358
          $rootScope.$emit('activity.mark-as-subscribed',$scope.activity.dataType(), $scope.activity.dataID());
        })
      }

      $scope.unsubscribeFromNotifications = function(){
        $scope.activity.unsubscribeFromNotifications().then(function (response) {
          $scope.showToast('Unsubscribed from item notifications.');
          $rootScope.$emit('activity.mark-as-unsubscribed',$scope.activity.dataType(), $scope.activity.dataID());
        })
      }

      var activityType = $scope.activity.dataType()
      if (ctrlByType[activityType]) {
        ctrlByType[activityType]($scope);
      } else {
        $scope.templateSrc = 'templates/home/activities/default.html';
      }
    }
  };
});<|endoftext|>