<commit_before>define(['text!./search.html',
		'app',
		'jquery',
		'lodash',
		"utilities/km-utilities",
		"./search-result",
		"./search-filter-keywords",
		"./search-filter-schemas",
		"./search-filter-countries",
		"./search-filter-regions",
		"./search-filter-facets",
		"./search-filter-themes",
		"./search-filter-dates",
		"./row-aichi-target",
		"./row-announcement",
		"./row-meeting",
		"./row-notification",
		"./row-press-release",
		"./row-national-assessment",
		"./row-statement"

	], function(template, app, $, _) { 'use strict';

	app.directive('search', ['$http', 'realm', '$q', '$timeout', '$location', function ($http, realm, $q, $timeout, $location) {
	    return {
	        restrict: 'EAC',
	        template: template,
	        replace: true,
	        scope: {},
					require: '^search',
			link : function($scope, $element, $attr, searchCtrl) {  // jshint ignore:line

	            var iconMap = {
	                'focalPoint'            : 'fa fa-user',
	                'notification'          : 'icon-envelope',
	                'pressRelease'          : 'icon-bullhorn',
	                'statement'             : 'icon-microphone',
	                'announcement'          : 'icon-rss',
	                'event'                 : 'icon-calendar',
	                'organization'          : 'icon-building',
	                'resource'              : 'fa fa-book',
	                'aichiTarget'           : 'fa fa-flag',
	                'strategicPlanIndicator': 'icon-signal',
	                'marineEbsa'            : 'icon-map-marker',
	                'meeting'               : 'icon-calendar',
	                'meetingDocument'       : 'fa fa-file-o',
	                'decision'              : 'icon-legal',
	                'recommendation'        : 'icon-legal',
	                'nationalReport'        : 'icon-quote-left',
	                'nationalTarget'        : 'fa fa-flag',
	                'nationalIndicator'     : 'icon-signal',
	                'nationalAssessment'    : 'icon-eye-open',
	                'implementationActivity': 'icon-retweet',
	                'nationalSupportTool'   : 'icon-wrench',
					'resourceMobilisation'  : 'fa fa-university'
	            };

	            $scope.loaded          = false;
	            $scope.itemsPerPage    = 25;
	            $scope.pageCount       = 0;
	            $scope.currentPage     = 0;
	            $scope.queryRegions    = '*:*'; // TODO replace with $scope.subQueries
	            $scope.queryTargets    = '*:*'; // TODO replace with $scope.subQueries
	            $scope.queryTheme      = '*:*'; // TODO replace with $scope.subQueries
	            $scope.queryDate       = '*:*'; // TODO replace with $scope.subQueries
	            $scope.queryKeywords   = '*:*'; // TODO replace with $scope.subQueries

				$scope.subQueries = {};

	            if($location.search().q) {
	                $scope.keywords = $location.search().q;
	                $location.replace();
	                $location.search({});
	            }

	            $scope.fixHtml = function (htmlText) {
	                htmlText = (htmlText || "").replace(/\r\n/g, '<br>');
					htmlText = (htmlText || "").replace(/href="\//g, 'href="https://www.cbd.int/');
					htmlText = (htmlText || "").replace(/href='\//g, "href='https://www.cbd.int/");

					var qHtml = $('<div/>').html(htmlText);

					qHtml.find("script,style").remove();

					return qHtml.html();
	            };

	            $scope.fixUrl = function (url) {
	                if(url) {
						     if(url.indexOf( "http://chm.cbd.int/")==0) url = url.substr("http://chm.cbd.int" .length); // jshint ignore:line
	                    else if(url.indexOf("https://chm.cbd.int/")==0) url = url.substr("https://chm.cbd.int".length); // jshint ignore:line
	                }

	                return url;
	            };

	            function readFacets2(solrArray) {

	                var facets = [];
					if(solrArray)
						for (var i = 0; i < solrArray.length; i += 2) {

							var facet = solrArray[i];

							facets.push({ symbol: facet, title: facet, count: solrArray[i + 1] });
						}

	                return facets;
	            }

				$scope.buildQuery = function()
				{
					// NOT version_s:* remove non-public records from resultset

					var q = 'NOT version_s:* AND realm_ss:' + realm.toLowerCase() + ' AND schema_s:* ';

					//TODO use:  $scope.subQueries

					var subQueries = _.compact([$scope.querySchema, $scope.queryGovernment, $scope.queryRegions, $scope.queryTheme, $scope.queryTargets, $scope.queryDate, $scope.queryKeywords]);

					if(subQueries.length)
						q += " AND " + subQueries.join(" AND ");
					return q;
				};

	            function query() {

	                var queryParameters = {
	                    'q': $scope.buildQuery(),
	                    'sort': 'createdDate_dt desc, title_t asc',
	                    'fl': 'id,title_t,description_t,url_ss,schema_EN_t,date_dt,government_EN_t,schema_s,number_d,aichiTarget_ss,reference_s,sender_s,meeting_ss,recipient_ss,symbol_s,eventCity_EN_t,eventCountry_EN_t,startDate_s,endDate_s,body_s,code_s,meeting_s,group_s,function_t,department_t,organization_t,summary_EN_t,reportType_EN_t,completion_EN_t,jurisdiction_EN_t,development_EN_t',
	                    'wt': 'json',
	                    'start': $scope.currentPage * $scope.itemsPerPage,
	                    'rows': 25,
						'facet': true,
						'facet.field': ['schema_s', 'government_s', 'government_REL_ss', 'aichiTarget_REL_ss', 'thematicArea_REL_ss'],
						'facet.limit': 999999,
						'facet.mincount' : 1
	                };

	                if (canceler) {
	                    console.log('trying to abort pending request...');
	                    canceler.resolve(true);
	                }

	                canceler = $q.defer();

	                $http.get('/api/v2013/index/select', { params: queryParameters, timeout: canceler.promise }).success(function (data) {

	                    canceler = null;

	                    $scope.count = data.response.numFound;
	                    $scope.start = data.response.start;
	                    $scope.stop  = data.response.start+data.response.docs.length-1;
	                    $scope.rows  = data.response.docs.length;

						$scope.schemas       = readFacets2(data.facet_counts.facet_fields.schema_s);
						$scope.governments   = readFacets2(data.facet_counts.facet_fields.government_s);
						$scope.regions       = readFacets2(data.facet_counts.facet_fields.government_REL_ss);
						$scope.aichiTargets  = readFacets2(data.facet_counts.facet_fields.aichiTarget_REL_ss);
						$scope.thematicAreas = readFacets2(data.facet_counts.facet_fields.thematicArea_REL_ss);

	                    $scope.documents = data.response.docs;

	                    $scope.pageCount = Math.ceil(data.response.numFound / $scope.itemsPerPage);

	                }).error(function (error) { console.log('onerror'); console.log(error); });
	            }

	            $scope.range = function (start, end) {

	                var ret = [];
	                if (!end) {
	                    end = start;
	                    start = 0;
	                }

	                var maxCount = 10;
	                var middle = 5;
	                var count = end - start;

	                if (count > maxCount) {
	                    if ($scope.currentPage > middle)
	                        start = $scope.currentPage - middle;

	                    end = Math.min(count, start + maxCount);
	                    start = Math.max(0, end - maxCount);
	                }

	                for (var i = start; i < end; i++) {
	                    ret.push(i);
	                }
	                return ret;
	            };

	            var queryScheduled = null;

	            function search() {

	                if(queryScheduled)
	                    $timeout.cancel($scope.queryScheduled);

	                queryScheduled = $timeout(function () { query(); }, 100);
	            }

	            $scope.$watch('currentPage',     search);
	            $scope.$watch('querySchema',     function() { $scope.currentPage=0; search(); }); // TODO delete and replace by $scope.subQueries
				$scope.$watch('queryGovernment', function() { $scope.currentPage=0; search(); }); // TODO delete and replace by $scope.subQueries
	            $scope.$watch('queryRegions',    function() { $scope.currentPage=0; search(); }); // TODO delete and replace by $scope.subQueries
	            $scope.$watch('queryTargets',    function() { $scope.currentPage=0; search(); }); // TODO delete and replace by $scope.subQueries
	            $scope.$watch('queryTheme',      function() { $scope.currentPage=0; search(); }); // TODO delete and replace by $scope.subQueries
	            $scope.$watch('queryDate',       function() { $scope.currentPage=0; search(); }); // TODO delete and replace by $scope.subQueries
	            $scope.$watch('queryKeywords',   function() { $scope.currentPage=0; search(); }); // TODO delete and replace by $scope.subQueries
	        },
			controller : ["$scope", function($scope) {

				this.fullQuery = function() {
					return $scope.buildQuery();
				};

				this.setSubQuery = function(name, query) {
					$scope.subQueries[name] = query;
				};

				this.getSubQuery = function(name) {
					return $scope.subQueries[name];
				};
			}]
	    };
	}]);

	//============================================================
	//
	//
	//============================================================
	app.directive('bindIndeterminate', [function () {
	    return {
	        restrict: 'A',
	        link: function (scope, element, attrs) {
	            scope.$watch(attrs.bindIndeterminate, function (value) {
	                element[0].indeterminate = value;
	            });
	        }
	    };
	}]);

	//============================================================
	//
	//
	//============================================================
	app.directive('toggle', [function () {
	    return {
	        restrict: 'A',
	        link: function (scope, element, attrs) {
	            if(attrs.toggle=='tooltip')
	                element.tooltip();
	        }
	    };
	}]);
});
<commit_msg>Git gave errors while staging chuncks.  Had to commit whole file.  Added parent functions for children to uses, Cleaned code.  Move most functions to controller from link.<commit_after>define(['text!./search.html',
		'app',
		'jquery',
		'lodash',
		"utilities/km-utilities",
		"./search-result",
		"./search-filter-keywords",
		"./search-filter-schemas",
		"./search-filter-countries",
		"./search-filter-regions",
		"./search-filter-facets",
		"./search-filter-themes",
		"./search-filter-dates",
		"./row-aichi-target",
		"./row-announcement",
		"./row-meeting",
		"./row-notification",
		"./row-press-release",
		"./row-national-assessment",
		"./row-statement"

	], function(template, app, $, _) { 'use strict';

	app.directive('search', ['$http', 'realm', '$q', '$timeout', '$location', function ($http, realm, $q, $timeout, $location) {
	    return {
	        restrict: 'EAC',
	        template: template,
	        replace: true,
	        scope: {},
					require: '^search',
			link : function($scope, $element, $attr, searchCtrl) {  // jshint ignore:line

	            var iconMap = {
	                'focalPoint'            : 'fa fa-user',
	                'notification'          : 'icon-envelope',
	                'pressRelease'          : 'icon-bullhorn',
	                'statement'             : 'icon-microphone',
	                'announcement'          : 'icon-rss',
	                'event'                 : 'icon-calendar',
	                'organization'          : 'icon-building',
	                'resource'              : 'fa fa-book',
	                'aichiTarget'           : 'fa fa-flag',
	                'strategicPlanIndicator': 'icon-signal',
	                'marineEbsa'            : 'icon-map-marker',
	                'meeting'               : 'icon-calendar',
	                'meetingDocument'       : 'fa fa-file-o',
	                'decision'              : 'icon-legal',
	                'recommendation'        : 'icon-legal',
	                'nationalReport'        : 'icon-quote-left',
	                'nationalTarget'        : 'fa fa-flag',
	                'nationalIndicator'     : 'icon-signal',
	                'nationalAssessment'    : 'icon-eye-open',
	                'implementationActivity': 'icon-retweet',
	                'nationalSupportTool'   : 'icon-wrench',
									'resourceMobilisation'  : 'fa fa-university'
	            };

	            $scope.loaded          = false;
	            $scope.itemsPerPage    = 25;
	            $scope.pageCount       = 0;
	            $scope.currentPage     = 0;
	            $scope.queryRegions    = '*:*'; // TODO replace with $scope.subQueries
	            $scope.queryTargets    = '*:*'; // TODO replace with $scope.subQueries
	            $scope.queryTheme      = '*:*'; // TODO replace with $scope.subQueries
	            $scope.queryDate       = '*:*'; // TODO replace with $scope.subQueries
	            $scope.queryKeywords   = '*:*'; // TODO replace with $scope.subQueries

							$scope.subQueries = {};

	            if($location.search().q) {
	                $scope.keywords = $location.search().q;
	                $location.replace();
	                $location.search({});
	            }

					//======================================================================
				  //
					//======================================================================
					$scope.icon = function (schema) {

              return iconMap[schema];
          };//$scope.icon

					//======================================================================
				  //
					//======================================================================
					$scope.actionSetPage = function (pageNumber) {

	            $scope.currentPage = Math.min($scope.pageCount-1, Math.max(0, pageNumber));
	        };//$scope.actionSetPage

				  //=======================================================================
				  //
					//=======================================================================
	        $scope.fixUrl = function (url) {

                if(url){
							     if(url.indexOf( "http://chm.cbd.int/")===0)
									 		url = url.substr("http://chm.cbd.int" .length); // jshint ignore:line
		               else if(url.indexOf("https://chm.cbd.int/")===0)
									 		url = url.substr("https://chm.cbd.int".length); // jshint ignore:line
								}
                return url;
	         };//$scope.fixUrl

					 //=======================================================================
				   //
					 //=======================================================================
			     $scope.readFacets2 = function (solrArray) {

				        var facets = [];
									if(solrArray)
											for (var i = 0; i < solrArray.length; i += 2) {
													var facet = solrArray[i];
													facets.push({ symbol: facet, title: facet, count: solrArray[i + 1] });
											}
				          return facets;
			      };//$scope.readFacets2

						//=======================================================================
						//
						//=======================================================================
						$scope.buildQuery = function()
						{
								// NOT version_s:* remove non-public records from resultset
								var q = 'NOT version_s:* AND realm_ss:' + realm.toLowerCase() + ' AND schema_s:* ';

								//TODO use:  $scope.subQueries
								var subQueries = _.compact([getFormatedSubQuery('schema_s'), getFormatedSubQuery('government_s'), $scope.queryRegions, $scope.queryTheme, $scope.queryTargets, $scope.queryDate, $scope.queryKeywords]);

								if(subQueries.length)
									q += " AND " + subQueries.join(" AND ");
								return q;
						};//$scope.buildQuery

						//=======================================================================
						//
						//=======================================================================
            $scope.range = function (start, end) {

                var ret = [];
                if (!end) {
                    end = start;
                    start = 0;
                }

                var maxCount = 10;
                var middle = 5;
                var count = end - start;

                if (count > maxCount) {
                    if ($scope.currentPage > middle)
                        start = $scope.currentPage - middle;

                    end = Math.min(count, start + maxCount);
                    start = Math.max(0, end - maxCount);
                }

                for (var i = start; i < end; i++) {
                    ret.push(i);
                }
                return ret;
	          };//$scope.range

						//=======================================================================
						//
						//=======================================================================
						function getFormatedSubQuery (name) {

								var subQ='';
								if($scope.subQueries[name] && _.isArray($scope.subQueries[name]) && $scope.subQueries[name].length){
									subQ +=  name+':'+$scope.subQueries[name].join(" OR "+name+":");
									subQ = '('+subQ+')';
								}
								return subQ;
						}//function getFormatedSubQuery (name)

	            $scope.$watch('currentPage',     searchCtrl.search());
	            $scope.$watch('queryRegions',    function() { $scope.currentPage=0; searchCtrl.search(); }); // TODO delete and replace by $scope.subQueries
	            $scope.$watch('queryTargets',    function() { $scope.currentPage=0; searchCtrl.search(); }); // TODO delete and replace by $scope.subQueries
	            $scope.$watch('queryTheme',      function() { $scope.currentPage=0; searchCtrl.search(); }); // TODO delete and replace by $scope.subQueries
	            $scope.$watch('queryDate',       function() { $scope.currentPage=0; searchCtrl.search(); }); // TODO delete and replace by $scope.subQueries
	            $scope.$watch('queryKeywords',   function() { $scope.currentPage=0; searchCtrl.search(); }); // TODO delete and replace by $scope.subQueries
	        }, //link

			//=======================================================================
			//
			//=======================================================================
			controller : ["$scope", function($scope) {
					var queryScheduled  = null;
					var canceler 				= null;

					//=======================================================================
					//
					//=======================================================================
				function query($scope) {

						readQueryString ();
						var queryParameters = {
								'q': $scope.buildQuery(),
								'sort': 'createdDate_dt desc, title_t asc',
								'fl': 'id,title_t,description_t,url_ss,schema_EN_t,date_dt,government_EN_t,schema_s,number_d,aichiTarget_ss,reference_s,sender_s,meeting_ss,recipient_ss,symbol_s,eventCity_EN_t,eventCountry_EN_t,startDate_s,endDate_s,body_s,code_s,meeting_s,group_s,function_t,department_t,organization_t,summary_EN_t,reportType_EN_t,completion_EN_t,jurisdiction_EN_t,development_EN_t',
								'wt': 'json',
								'start': $scope.currentPage * $scope.itemsPerPage,
								'rows': 25,
								'facet': true,
								'facet.field': ['schema_s', 'government_s', 'government_REL_ss', 'aichiTarget_REL_ss', 'thematicArea_REL_ss'],
								'facet.limit': 999999,
								'facet.mincount' : 1
						};

						if (canceler) {
								//console.log('trying to abort pending request...');
								canceler.resolve(true);
						}

						canceler = $q.defer();

						$http.get('/api/v2013/index/select', { params: queryParameters, timeout: canceler.promise }).success(function (data) {

								canceler = null;

								$scope.count = data.response.numFound;
								$scope.start = data.response.start;
								$scope.stop  = data.response.start+data.response.docs.length-1;
								$scope.rows  = data.response.docs.length;

								$scope.schemas       = $scope.readFacets2(data.facet_counts.facet_fields.schema_s);
								$scope.governments   = $scope.readFacets2(data.facet_counts.facet_fields.government_s);
								$scope.regions       = $scope.readFacets2(data.facet_counts.facet_fields.government_REL_ss);
								$scope.aichiTargets  = $scope.readFacets2(data.facet_counts.facet_fields.aichiTarget_REL_ss);
								$scope.thematicAreas = $scope.readFacets2(data.facet_counts.facet_fields.thematicArea_REL_ss);

								$scope.documents = data.response.docs;

								$scope.pageCount = Math.ceil(data.response.numFound / $scope.itemsPerPage);
								updateQueryString();
						});//$http.get('/ap
				}// query

				//=======================================================================
				//
				//=======================================================================
				function readQueryString () {

						var qsSchema = _([$location.search().schema_s]).flatten().compact().value(); // takes query string into array
						var qsCountry = _([$location.search().government_s]).flatten().compact().value(); // takes query string into array

						var qsArrByField = {'schema_s':qsSchema,'government_s':qsCountry};

						_.each(qsArrByField,function (idArr,schemaKey){
								_.each(idArr,function(id){
										addSubQuery(schemaKey,id);
								});//_.each
						});//_.each
				}//readQueryString

				//=======================================================================
				//
				//=======================================================================
				function updateQueryString () {

						_.each($scope.subQueries,function(itemIdArr,schemaKey){
											$location.replace();
											$location.search(schemaKey, itemIdArr);
						});
				}//getFormatedSubQuery

				//=======================================================================
				//
				//=======================================================================
				function search () {

						if(queryScheduled)
								$timeout.cancel($scope.queryScheduled);
						queryScheduled = $timeout(function () { query($scope); }, 100);
				}//search

				//=======================================================================
				//
				//=======================================================================
				function addSubQuery (name, query) {

						if(!$scope.subQueries) // if called from controler without link ex4ecuting first
							$scope.subQueries={};
						if(!_.isArray($scope.subQueries[name])) // initialize
							$scope.subQueries[name]=[];
						if($scope.subQueries[name].indexOf(query)<0) // if not already there add
							$scope.subQueries[name].push(query);
				}//addSubQuery

				//=======================================================================
				//
				//=======================================================================
				function deleteSubQuery(name, query) {

						var i = $scope.subQueries[name].indexOf(query);
						if(i !==-1)
							$scope.subQueries[name].splice(i,1);
				}//deleteSubQuery

				//=======================================================================
				//
				//@ data - raw country data taken from api call
				//@ terms -
				//@ qsSelection -
				//=======================================================================
				function updateTerms(terms,items,facet,data) {

						var qsSelection = _([$location.search()[facet]]).flatten().compact().value(); // takes query string into array
						var termsx = {};

						if(!data)data=terms;

						terms =  _.map(data, function(t) {
									if(qsSelection && !_.isEmpty(qsSelection))
											t.selected = qsSelection.indexOf(t.identifier)>=0; // adds query string frmo url into query

									termsx[t.identifier] = t;
									return t;
						});//_.map

						insertCounts(items,termsx);
						return termsx;
				}//updateTerms

				//=======================================================================
				// initiates all counts to 0 and then insert facit counts based on country
				//
				//=======================================================================
				function insertCounts(items,termsx) {
						if(termsx)
								_.each(termsx,function (item) {
										item.count = 0;
								});//  _.each
						//if(!items) items=$scope.items;
						if(items)
								items.forEach(function (item) {
										if(_.has(termsx, item.symbol))
												termsx[item.symbol].count = item.count;
								});//items.forEach
				}//insertCounts

				//=======================================================================
				//
				//=======================================================================
				function buildChildQuery (terms,items,facet,data) {

						if(!_.isEmpty(terms) )
								_.each(terms,function (item) {
										if(item.selected)
												addSubQuery(facet,item.identifier);
						});

						search();
						updateTerms(terms,items,facet,data);
				}//buildQuery

				this.buildChildQuery =buildChildQuery;
				this.updateTerms =updateTerms;
				this.deleteSubQuery =deleteSubQuery;
				this.search = search;
				this.addSubQuery= addSubQuery;
			}]//controlerr
		};//return
	}]); //directive

	//============================================================
	//
	//
	//============================================================
	app.directive('bindIndeterminate', [function () {
	    return {
	        restrict: 'A',
	        link: function (scope, element, attrs) {
	            scope.$watch(attrs.bindIndeterminate, function (value) {
	                element[0].indeterminate = value;
	            });
	        }
	    };
	}]); //directive

	//============================================================
	//
	//
	//============================================================
	app.directive('toggle', [function () {
	    return {
	        restrict: 'A',
	        link: function (scope, element, attrs) {
	            if(attrs.toggle=='tooltip')
	                element.tooltip();
	        }
	    };
	}]); //directive
});//define
<|endoftext|>


<commit_before>// controllers/posts/post-reader.js
// Copyright (C) 2014 Rob Colbert <rob.isConnected@gmail.com>

'use strict';

angular.module('robcolbertApp')
.controller('PostReaderCtrl', [
  '$scope',
  '$route',
  'Posts',
  function ($scope, $route, Posts) {
    $scope.$emit('setPageGroup', 'blog');
    $scope.post = Posts.get({'postId': $route.current.params.postId}, null, function ( ) {
      console.log('post loaded', $scope.post);
      setTimeout(twttr.widgets.load, 0);
    });

    $scope.comment = { }; // empty by default
    $scope.createComment = function ( ) {
      console.log('createComment', $scope.comment);
      Posts.createComment({'postId': $route.current.params.postId}, $scope.comment, function (newComment) {
        $scope.post.comments.push(newComment);
        $scope.comment = { }; // empty it out
      });
    };
  }
]);
<commit_msg>Adapted post reader controller to trust excerpt and content as HTML.<commit_after>// controllers/posts/post-reader.js
// Copyright (C) 2014 Rob Colbert <rob.isConnected@gmail.com>

'use strict';

angular.module('robcolbertApp')
.controller('PostReaderCtrl', [
  '$scope',
  '$route',
  '$sce',
  'Posts',
  function ($scope, $route, $sce, Posts) {
    $scope.$emit('setPageGroup', 'blog');
    $scope.post = Posts.get({'postId': $route.current.params.postId}, null, function ( ) {
      console.log('post loaded', $scope.post);
      $scope.post.excerpt = $sce.trustAsHtml($scope.post.excerpt);
      $scope.post.content = $sce.trustAsHtml($scope.post.content);
      setTimeout(twttr.widgets.load, 0);
    });

    $scope.comment = { }; // empty by default
    $scope.createComment = function ( ) {
      console.log('createComment', $scope.comment);
      Posts.createComment({'postId': $route.current.params.postId}, $scope.comment, function (newComment) {
        $scope.post.comments.push(newComment);
        $scope.comment = { }; // empty it out
      });
    };
  }
]);
<|endoftext|>


<commit_before>var resttp = require('resttp'),
    config = require('../config').config,
       sys = require('sys'),
      slog = sys.log;

function Mapi() {
  this.paramCache = {};
  this.client = resttp.using(config.mapiUrl).as(config.user, config.password);
  this.logging = true;
}
exports.Mapi = Mapi;

Mapi.prototype.logRequest = function(method, args, code, body) {
  if (!this.logging) {
    return;
  }
  slog("MAPI: " + method + ": returned " + code + "\n" +
      "== args ==\n" + sys.inspect(args) +
      "\n== body ==\n" + sys.inspect(body) + "\n==\n");
}

Mapi.prototype.logError = function(err, resp, body) {
  if (!this.logging) {
    return;
  }
  slog("MAPI error\n== err ==\n" + sys.inspect(err) +
       "\n== resp ==\n" + sys.inspect(resp) +
       "\n== body ==\n" + sys.inspect(body) + "\n==\n");
}

Mapi.prototype.log = function(str) {
  if (!this.logging) {
    return;
  }
  slog(str);
}

Mapi.prototype.parseJSON = function (body) {
  try {
    var json = JSON.parse(body);
  } catch (err) {
    this.log("Error parsing JSON: " + err + "\n== json ==\n" + body + "\n==\n");
    return null;
  }
  return json;
}

Mapi.prototype.getBootParams = function(mac, previousIp, cb) {
  var self = this;
  this.client.errcallback = function(err, resp, body) {
    self.logError(err, resp, body);
    cb(null, body);
  }

  var getArgs = { pathname: "admin/boot/" + mac };
  if (previousIp != "0.0.0.0") {
    getArgs['ip'] = previousIp;
  }

  this.client.GET(getArgs, function(code, body) {
    self.logRequest('GET', getArgs, code, body);
    if (code == 200) {
      return cb(self.parseJSON(body));
    }

    // 404 means "I don't know about that MAC address yet."  Anything else is
    // an error.
    if (code != 404) {
      self.log("ERROR: MAPI returned code " + code + ".  Not POSTing MAC address.");
      if (mac in self.paramCache) {
        slog("[" + mac + "] " + "Using cached copy of boot params");
        return cb(self.paramCache[mac])
      }
      return cb(null, body);
    }
    // XXX: If 404, should delete the mac out of the param cache

    var postArgs = {
      pathname : "admin/nics",
      params: { address: mac, nic_tag_names: "admin" },
    };

    self.client.POST(postArgs, function(code, body) {
      self.logRequest('POST', postArgs, code, body);
      if (code == 201) {
        self.client.GET(getArgs, function(code, body) {
          self.logRequest('GET (2)', getArgs, code, body);
          if (code == 200) {
            return cb(self.parseJSON(body));
          }
          return cb(null, body);
        });
      } else {
          return cb(null, body);
      }
    });
  });
}

/*
  this.getBootParams(mac, function(c) {
      self.paramCache[mac] = c;
    }
    */
<commit_msg>Remove extraneous comment<commit_after>var resttp = require('resttp'),
    config = require('../config').config,
       sys = require('sys'),
      slog = sys.log;

function Mapi() {
  this.paramCache = {};
  this.client = resttp.using(config.mapiUrl).as(config.user, config.password);
  this.logging = true;
}
exports.Mapi = Mapi;

Mapi.prototype.logRequest = function(method, args, code, body) {
  if (!this.logging) {
    return;
  }
  slog("MAPI: " + method + ": returned " + code + "\n" +
      "== args ==\n" + sys.inspect(args) +
      "\n== body ==\n" + sys.inspect(body) + "\n==\n");
}

Mapi.prototype.logError = function(err, resp, body) {
  if (!this.logging) {
    return;
  }
  slog("MAPI error\n== err ==\n" + sys.inspect(err) +
       "\n== resp ==\n" + sys.inspect(resp) +
       "\n== body ==\n" + sys.inspect(body) + "\n==\n");
}

Mapi.prototype.log = function(str) {
  if (!this.logging) {
    return;
  }
  slog(str);
}

Mapi.prototype.parseJSON = function (body) {
  try {
    var json = JSON.parse(body);
  } catch (err) {
    this.log("Error parsing JSON: " + err + "\n== json ==\n" + body + "\n==\n");
    return null;
  }
  return json;
}

Mapi.prototype.getBootParams = function(mac, previousIp, cb) {
  var self = this;
  this.client.errcallback = function(err, resp, body) {
    self.logError(err, resp, body);
    cb(null, body);
  }

  var getArgs = { pathname: "admin/boot/" + mac };
  if (previousIp != "0.0.0.0") {
    getArgs['ip'] = previousIp;
  }

  this.client.GET(getArgs, function(code, body) {
    self.logRequest('GET', getArgs, code, body);
    if (code == 200) {
      return cb(self.parseJSON(body));
    }

    // 404 means "I don't know about that MAC address yet."  Anything else is
    // an error.
    if (code != 404) {
      self.log("ERROR: MAPI returned code " + code + ".  Not POSTing MAC address.");
      if (mac in self.paramCache) {
        slog("[" + mac + "] " + "Using cached copy of boot params");
        return cb(self.paramCache[mac])
      }
      return cb(null, body);
    }
    // XXX: If 404, should delete the mac out of the param cache

    var postArgs = {
      pathname : "admin/nics",
      params: { address: mac, nic_tag_names: "admin" },
    };

    self.client.POST(postArgs, function(code, body) {
      self.logRequest('POST', postArgs, code, body);
      if (code == 201) {
        self.client.GET(getArgs, function(code, body) {
          self.logRequest('GET (2)', getArgs, code, body);
          if (code == 200) {
            return cb(self.parseJSON(body));
          }
          return cb(null, body);
        });
      } else {
          return cb(null, body);
      }
    });
  });
}

<|endoftext|>


<commit_before>var fs = require('fs');

var Mine = (function() {

  function Mine() {
    this._dict = {};
    this._ordered = [];
    this._preparedDict = {};
  }

  var search = Mine.prototype;

  search.parseText = function(text, options, callback) {

    text = text
      .replace(/(\r\n|\n|\r)/gm,' ') // Remove line break
      .replace(/\s+/g,' ') // Remove extra whitespace
      .replace(/\W/g, ' '); // Remove non alphanumerical

    var words = text.split(' ');
    var self = this;

    words.forEach(function(word) {

      word = word.toLowerCase();

      self._dict[word] = self._dict[word]
      ? ++self._dict[word]
      : 1;

    });

    delete this._dict['']; // Remove empty space

    if(arguments.length === 2) {
      callback = options;
    } else {

      if(options['order']) {
        this._sort();
      }

    }

    this._prepareResponse();
    return callback(this._preparedDict);

  };

  search.parseFile = function(files, options, callback) {

    if(typeof files === 'string') {
      files = [files];
    }

    callback = arguments.length === 2
      ? options
      : callback;

    this._mineFile(files, callback);

  };

  search._mineFile = function(files, callback, i, bigData) {

    if(!i) {
      i = 0;
    }

    if(bigData) {
      bigData += bigData;
    }

    var self = this;

    fs.readFile(files[i], 'utf8', function(err, data) {

      if(err) {
        console.log(err);
      }

      if(i < files.length - 1) {
        return self._mineFile(files, callback, ++i, data);
      }

      bigData += data;

      return self.parseText(bigData, callback);

    });

  };

  search._prepareResponse = function() {

    var keys = Object.keys(this._dict);

    for (var i = keys.length - 1; i >= 0; i--) {

      var key = keys[i];
      var prep = this._preparedDict[i] = {};
      prep[key] = this._dict[key];

    };

  };

  search._sort = function() {

    for(var word in this._dict) {
      this._ordered.push([word, this._dict[word]]);
    }
    this._ordered.sort(function(a, b) {
      return b[1] - a[1];
    });

    return this._dict = this._ordered;

  };

  return Mine;

})();

exports = module.exports = new Mine();<commit_msg>Order words with array-like object key<commit_after>var fs = require('fs');

var Mine = (function() {

  function Mine() {
    this._dict = {};
    this._preparedDict = {};
  }

  var search = Mine.prototype;

  search.parseText = function(text, options, callback) {

    text = text
      .replace(/(\r\n|\n|\r)/gm,' ') // Remove line break
      .replace(/\s+/g,' ') // Remove extra whitespace
      .replace(/\W/g, ' '); // Remove non alphanumerical

    var words = text.split(' ');
    var self = this;

    words.forEach(function(word) {

      word = word.toLowerCase();

      self._dict[word] = self._dict[word]
      ? ++self._dict[word]
      : 1;

    });

    delete this._dict['']; // Remove empty space

    if(arguments.length === 2) {
      callback = options;
    } else {

      if(options['order']) {
        this._sort();
      }

    }

    this._prepareResponse();
    return callback(this._preparedDict);

  };

  search.parseFile = function(files, options, callback) {

    if(typeof files === 'string') {
      files = [files];
    }

    callback = arguments.length === 2
      ? options
      : callback;

    this._mineFile(files, callback);

  };

  search._mineFile = function(files, callback, i, bigData) {

    if(!i) {
      i = 0;
    }

    if(bigData) {
      bigData += bigData;
    }

    var self = this;

    fs.readFile(files[i], 'utf8', function(err, data) {

      if(err) {
        console.log(err);
      }

      if(i < files.length - 1) {
        return self._mineFile(files, callback, ++i, data);
      }

      bigData += data;

      return self.parseText(bigData, callback);

    });

  };

  search._prepareResponse = function() {

    var keys = Object.keys(this._dict);

    for (var i = keys.length - 1; i >= 0; i--) {

      var key = keys[i];
      var prep = this._preparedDict[i] = {};
      prep[key] = this._dict[key];

    };

  };

  search._sort = function() {

    var self = this;
    var ordered = [];
    var orderedDict = {};

    for(var word in this._dict) {
      ordered.push([word, this._dict[word]]);
    }

    ordered.sort(function(a, b) {
      return b[1] - a[1];
    });

    ordered.forEach(function(w) {
      var key = w[0];

      orderedDict[key] = w[1];

    });

    return this._dict = orderedDict;

  };

  return Mine;

})();

exports = module.exports = new Mine();<|endoftext|>


<commit_before>
/*
  1. admin: Spawn a web-server (ws)
  2. user: Connect a web socket to it (browser)
  3. user: Send a `connect` message
  4. server: Spawn the electron app on `connect` message
  5. electron: Load the webview and wait for it to load
  6. electron: Send `ipcRenderer` message back to the main script
  7. electron: Load the electron-server on `connect` message
  8. server: On electron-server loaded connect a web socket to it
  9. server: After ws connection is established send back a `connected` message to the user
*/

var config = require('../config')[process.env.NODE_ENV || 'development']
var t = require('assert')
var path = require('path')
var cp = require('child_process')
var engine = require('engine.io-client')

describe('browser-server-electron', () => {
  var server, client

  before((done) => {
    server = cp.spawn('node', [path.join(process.cwd(), 'lib/ws-server')])
    server.stdout.on('data', (e) => {
      var output = e.toString().trim()
      console.log(output)

      if (/ws-server/.test(output)) {
        client = engine('ws://localhost:' + config.ws)
        client.on('open', () => done())
      }
    })

    server.stderr.on('data', (e) => console.log(e.toString().trim()))
  })

  it('connect', (done) => {
    client.send(JSON.stringify({message: 'connect'}))

    client.once('message', (req) => {
      t.deepEqual(JSON.parse(req), {message: 'connected'})
      done()
    })
  })

  it('send message', (done) => {
    client.send(JSON.stringify({message: 'test'}))

    client.once('message', (req) => {
      t.deepEqual(JSON.parse(req), {message: 'test', body: 'webview'})
      done()
    })
  })

  after((done) => {
    server.kill('SIGHUP')
    done()
  })
})
<commit_msg>Update flow comment<commit_after>
/*
  1. admin: start a web-server (ws)
  2. user: connect a web socket to it (browser)
  3. user: send a `connect` message
  4. server: spawn Electron process on `connect` message
  5. electron: load the webview and wait for it to load
  6. electron: send `connect` message back to the electron-server
  7. electron: write to stdout to indicate that the electron-server is ready
  8. server: on electron-server ready, connect a web socket to it
  9. server: after ws connection is established send back a `connected` message to the user
*/

var config = require('../config')[process.env.NODE_ENV || 'development']
var t = require('assert')
var path = require('path')
var cp = require('child_process')
var engine = require('engine.io-client')

describe('browser-server-electron', () => {
  var server, client

  before((done) => {
    server = cp.spawn('node', [path.join(process.cwd(), 'lib/ws-server')])
    server.stdout.on('data', (e) => {
      var output = e.toString().trim()
      console.log(output)

      if (/ws-server/.test(output)) {
        client = engine('ws://localhost:' + config.ws)
        client.on('open', () => done())
      }
    })

    server.stderr.on('data', (e) => console.log(e.toString().trim()))
  })

  it('connect', (done) => {
    client.send(JSON.stringify({message: 'connect'}))

    client.once('message', (req) => {
      t.deepEqual(JSON.parse(req), {message: 'connected'})
      done()
    })
  })

  it('send message', (done) => {
    client.send(JSON.stringify({message: 'test'}))

    client.once('message', (req) => {
      t.deepEqual(JSON.parse(req), {message: 'test', body: 'webview'})
      done()
    })
  })

  after((done) => {
    server.kill('SIGHUP')
    done()
  })
})
<|endoftext|>


<commit_before>/**
 * Created by Ady on 2/20/2015.
 */

var mongoose = require('mongoose');
var Q = require('q');
var _ = require('underscore');
require('./mongoData.js');

var NodeCache = require( "node-cache" );
var myCache = new NodeCache( { stdTTL: 300 , useClones:false} ); //5m default cache time

module.exports = function () {

    var RoomPrefs = mongoose.model('RoomPrefs', {
        roomId: Number,
        guildId: String,
        warData: {
            inWar: Boolean,
            guildName: String,
            warTime: Date

        },
        playersPrefs: [{
            id: Number,
            mini: String,
            minis: [{player: String, idx: Number}],
            risk: {type: Number, default: 0}
        }],
        settings: [],
        matches:[{
            guildName: String,
            warTime: Date,
            warResult:String
        }]
    });

    var createRoomPrefs = function (roomId) {
        var r = new RoomPrefs({
            roomId: roomId,
            warData: {
                inWar: false,
                guildName: '',
                warTime: null
            },
            playersPrefs: [],
            settings: [],
            matches: []

        });
        return r;
    }

    var updateMini = function (minis, idx, mini) {
        minis = _.filter(minis, function (el) {
            return el.idx != idx;
        });
        minis.push({
            idx: idx,
            player: mini
        })
        return minis;
    };

    return {
        getRoomPrefs: function (roomId, deepObj) {
            deepObj = deepObj === undefined ? false : deepObj;
            var defered = Q.defer();
            var cacheKey='room_'+roomId;
            var cacheItem = myCache.get(cacheKey);
            if (cacheItem && deepObj === false){
              //  console.log('room pref from cache');
                defered.resolve(cacheItem);
            }else {
              //  console.log('no cache',cacheItem)
                RoomPrefs.find({roomId: roomId}, function (err, rooms) {
                    var item;
                    if (rooms.length == 0) {
                        item = createRoomPrefs(roomId);
                    } else {
                        item = rooms[0];
                    }

                    if (deepObj === false) {
                        myCache.set(cacheKey, item.toObject(), 600);
                        defered.resolve(item.toObject());
                    }
                    else{
                        item._save = item.save;
                        item._cacheKey=cacheKey;
                        item.save = function (cb) {
                            // console.log('SAVING !!!', this);
                            myCache.set(this._cacheKey,this,600);
                            this._save(cb);
                        };
                        defered.resolve(item);
                    }

                });
            }
            return defered.promise;
        },
        getAllRoomPrefs: function () {
            var defered = Q.defer();

                RoomPrefs.find({}, function (err, rooms) {
                    //myCache.set(rooms.toObject(),item,600);
                    defered.resolve(rooms);
                });

            return defered.promise;
        },
        getRoomPlayer: function (roomId,userId) {
            var defered = Q.defer();
            this.getRoomPrefs(roomId).then(function (roomPref) {
                var player = this.getRoomPlayerFromRoomPref( roomPref,userId);
                defered.resolve(player);
            }.bind(this));
            return defered.promise;
        },
        getRoomPlayerFromRoomPref: function (roomPref,userId) {
            var players = roomPref.playersPrefs || [];
            var player = _.find(players, function (p) {
                return p.id == userId;
            });
            if (player == undefined) {
                player = {
                    id: Number(userId),
                    minis: [],
                    risk: 0
                }
            }
            if (player.mini != undefined && player.mini != '') {
                player.minis = [];
                if (player.mini != undefined && player.mini != '') {
                    player.minis.push({
                        idx: 1,
                        player: player.mini
                    });
                    player.mini = undefined;
                    delete player.mini;
                }
            }
            return player;
        }, updatePlayerRisk: function (roomId, userId, name, risk) {
            var defered= Q.defer();
            this.getRoomPrefs(roomId, true).then(function (roomPref) {

                    var player = this.getRoomPlayerFromRoomPref(roomPref,userId);
                    var players = _.filter(roomPref.playersPrefs || [], function (el) {
                        return el.id != userId;
                    });
                    player.risk = risk;
                    players.push(player);

                    roomPref.playersPrefs = players;
                    roomPref.save();
                    defered.resolve('updated risk for ' + name + ' to ' + risk);
                }.bind(this)
            );
            return defered.promise;
        },
        addUpdateMini: function (roomId,userId, idx, miniPlayer) {
            var defered = Q.defer();
            this.getRoomPrefs(roomId, true).then(function (roomPref) {
                var player = this.getRoomPlayerFromRoomPref(roomPref,userId);
                var players = _.filter(roomPref.playersPrefs || [], function (el) {
                    return el.id != userId;
                });
                var playerMinis = (player == undefined) ? [] : player.minis || [];
                playerMinis = updateMini(playerMinis, idx, miniPlayer);
                player.minis = playerMinis;
                players.push(player);

                roomPref.playersPrefs = players;

                roomPref.save();
                defered.resolve('updated Mini #' + idx + ' : ' + miniPlayer);
            }.bind(this))
            ;
            return defered.promise;
        }
        ,
        getRoomSettingFromRoomPref: function (roomPref, settingName) {
            var settings = roomPref.settings || [];
            var setting = _.find(settings, function (s) {
                return s.key == settingName;
            });

            return setting == undefined ? null : setting.val;
        },
        setRoomSetting: function (roomPref, settingName, settingVal) {
            var settings = roomPref.settings || [];
            settings = _.filter(settings, function (s) {
                return s.key != settingName;
            });
            settings.push({
                'key': settingName,
                'val': settingVal
            });
            roomPref.settings = settings;
            roomPref.save();
        }
    };
}();
<commit_msg>lean all prefs<commit_after>/**
 * Created by Ady on 2/20/2015.
 */

var mongoose = require('mongoose');
var Q = require('q');
var _ = require('underscore');
require('./mongoData.js');

var NodeCache = require( "node-cache" );
var myCache = new NodeCache( { stdTTL: 300 , useClones:false} ); //5m default cache time

module.exports = function () {

    var RoomPrefs = mongoose.model('RoomPrefs', {
        roomId: Number,
        guildId: String,
        warData: {
            inWar: Boolean,
            guildName: String,
            warTime: Date

        },
        playersPrefs: [{
            id: Number,
            mini: String,
            minis: [{player: String, idx: Number}],
            risk: {type: Number, default: 0}
        }],
        settings: [],
        matches:[{
            guildName: String,
            warTime: Date,
            warResult:String
        }]
    });

    var createRoomPrefs = function (roomId) {
        var r = new RoomPrefs({
            roomId: roomId,
            warData: {
                inWar: false,
                guildName: '',
                warTime: null
            },
            playersPrefs: [],
            settings: [],
            matches: []

        });
        return r;
    }

    var updateMini = function (minis, idx, mini) {
        minis = _.filter(minis, function (el) {
            return el.idx != idx;
        });
        minis.push({
            idx: idx,
            player: mini
        })
        return minis;
    };

    return {
        getRoomPrefs: function (roomId, deepObj) {
            deepObj = deepObj === undefined ? false : deepObj;
            var defered = Q.defer();
            var cacheKey='room_'+roomId;
            var cacheItem = myCache.get(cacheKey);
            if (cacheItem && deepObj === false){
              //  console.log('room pref from cache');
                defered.resolve(cacheItem);
            }else {
              //  console.log('no cache',cacheItem)
                RoomPrefs.find({roomId: roomId}, function (err, rooms) {
                    var item;
                    if (rooms.length == 0) {
                        item = createRoomPrefs(roomId);
                    } else {
                        item = rooms[0];
                    }

                    if (deepObj === false) {
                        myCache.set(cacheKey, item.toObject(), 600);
                        defered.resolve(item.toObject());
                    }
                    else{
                        item._save = item.save;
                        item._cacheKey=cacheKey;
                        item.save = function (cb) {
                            // console.log('SAVING !!!', this);
                            myCache.set(this._cacheKey,this,600);
                            this._save(cb);
                        };
                        defered.resolve(item);
                    }

                });
            }
            return defered.promise;
        },
        getAllRoomPrefs: function () {
            var defered = Q.defer();
                RoomPrefs.findOne().lean().exec(function (err, rooms) {
                    //myCache.set(rooms.toObject(),item,600);
                    defered.resolve(rooms);
                });
            return defered.promise;
        },
        getRoomPlayer: function (roomId,userId) {
            var defered = Q.defer();
            this.getRoomPrefs(roomId).then(function (roomPref) {
                var player = this.getRoomPlayerFromRoomPref( roomPref,userId);
                defered.resolve(player);
            }.bind(this));
            return defered.promise;
        },
        getRoomPlayerFromRoomPref: function (roomPref,userId) {
            var players = roomPref.playersPrefs || [];
            var player = _.find(players, function (p) {
                return p.id == userId;
            });
            if (player == undefined) {
                player = {
                    id: Number(userId),
                    minis: [],
                    risk: 0
                }
            }
            if (player.mini != undefined && player.mini != '') {
                player.minis = [];
                if (player.mini != undefined && player.mini != '') {
                    player.minis.push({
                        idx: 1,
                        player: player.mini
                    });
                    player.mini = undefined;
                    delete player.mini;
                }
            }
            return player;
        }, updatePlayerRisk: function (roomId, userId, name, risk) {
            var defered= Q.defer();
            this.getRoomPrefs(roomId, true).then(function (roomPref) {

                    var player = this.getRoomPlayerFromRoomPref(roomPref,userId);
                    var players = _.filter(roomPref.playersPrefs || [], function (el) {
                        return el.id != userId;
                    });
                    player.risk = risk;
                    players.push(player);

                    roomPref.playersPrefs = players;
                    roomPref.save();
                    defered.resolve('updated risk for ' + name + ' to ' + risk);
                }.bind(this)
            );
            return defered.promise;
        },
        addUpdateMini: function (roomId,userId, idx, miniPlayer) {
            var defered = Q.defer();
            this.getRoomPrefs(roomId, true).then(function (roomPref) {
                var player = this.getRoomPlayerFromRoomPref(roomPref,userId);
                var players = _.filter(roomPref.playersPrefs || [], function (el) {
                    return el.id != userId;
                });
                var playerMinis = (player == undefined) ? [] : player.minis || [];
                playerMinis = updateMini(playerMinis, idx, miniPlayer);
                player.minis = playerMinis;
                players.push(player);

                roomPref.playersPrefs = players;

                roomPref.save();
                defered.resolve('updated Mini #' + idx + ' : ' + miniPlayer);
            }.bind(this))
            ;
            return defered.promise;
        }
        ,
        getRoomSettingFromRoomPref: function (roomPref, settingName) {
            var settings = roomPref.settings || [];
            var setting = _.find(settings, function (s) {
                return s.key == settingName;
            });

            return setting == undefined ? null : setting.val;
        },
        setRoomSetting: function (roomPref, settingName, settingVal) {
            var settings = roomPref.settings || [];
            settings = _.filter(settings, function (s) {
                return s.key != settingName;
            });
            settings.push({
                'key': settingName,
                'val': settingVal
            });
            roomPref.settings = settings;
            roomPref.save();
        }
    };
}();
<|endoftext|>


<commit_before>$(document).ready(function() {
  $('#heading').addClass('animated fadeIn').removeClass('hidden');
  // $('.landing>#button').addClass('animated slideInRight').removeClass('hidden');
  $('#heading a#button').addClass('animated slideInUp').removeClass('hidden');
  $('#scroll-indicator').addClass('animated bounce').removeClass('hidden');
  $('#mc_embed_signup').find('form').ajaxChimp();

  $('body').addClass('js');
  var $menu = $('.sidebar'),
      $menulink = $('.menu-toggle');

  $menulink.click(function() {
      $menulink.toggleClass('active');
      $menu.toggleClass('active');
      $('#page-content-wrapper').toggleClass('active');
      if ($(window).width() >= 750 && $(window).width() < 1200 ) {
        setWidth();
      }
      return false;
  });

});

$(function() {
    setNavigation();
    setWidth();
});

$(window).resize(function() {
  setWidth();
});

// current page indicator
function setNavigation() {
    var path = window.location.pathname;
    path = path.replace(/\/$/, "");

    $('#main-nav>a').each(function() {
        var href = $(this).attr('href');

        if (path.substring(0, href.length) === href) {
            if (href.length > 1) {
                $(this).addClass('active');
            }
        } else if (href.length == 1) {
            $(this).addClass('active');
        }
    });
}

// define #page-content-wrapper width
function setWidth() {

// TODO
// i know this is shitty, needs to be rewritten
    if ($(window).width() < 1200) {

        if ($(".sidebar").is(".active"))  {
          if ($(window).width() < 750) {
            var contentWrapperWidth = $(window).width() - $('.sidebar').width();
          } else {
            var contentWrapperWidth = 'inherit';
          }
        } else {
            var contentWrapperWidth = $(window).width();
        }

    } else {
        var contentWrapperWidth = $(window).width() - $('.sidebar').width();
    }

    $('#page-content-wrapper').css('width', contentWrapperWidth);
}

// clouds
function moveClouds(e, s, d) {
    $(e).css('right', '-20%');
    var wait = window.setTimeout(function() {
        $(e).animate({
            right: '120%'
        }, s, 'linear', function() {
            moveClouds(e, s, d);
        });
    }, d);
}

// mailchimp
(function($) {
    'use strict';

    $.ajaxChimp = {
        responses: {
            'We have sent you a confirmation email': 0,
            'Please enter a valid email': 1,
            'An email address must contain a single @': 2,
            'The domain portion of the email address is invalid (the portion after the @: )': 3,
            'The username portion of the email address is invalid (the portion before the @: )': 4,
            'This email address looks fake or invalid. Please enter a real email address': 5
        },
        translations: {
            'en': null
        },
        init: function(selector, options) {
            $(selector).ajaxChimp(options);
        }
    };

    $.fn.ajaxChimp = function(options) {
        $(this).each(function(i, elem) {
            var form = $(elem);
            var email = form.find('input[type=email]');
            var label = form.find('.info');

            var settings = $.extend({
                'url': form.attr('action'),
                'language': 'en'
            }, options);

            var url = settings.url.replace('/post?', '/post-json?').concat('&c=?');

            form.attr('novalidate', 'true');
            email.attr('name', 'EMAIL');

            form.submit(function() {
                var msg;

                function successCallback(resp) {
                    if (resp.result === 'success') {
                        msg = 'We have sent you a confirmation email';
                        label.removeClass('error').addClass('valid');
                        email.removeClass('error').addClass('valid');
                    } else {
                        email.removeClass('valid').addClass('error');
                        label.removeClass('valid').addClass('error');
                        var index = -1;
                        try {
                            var parts = resp.msg.split(' - ', 2);
                            if (parts[1] === undefined) {
                                msg = resp.msg;
                            } else {
                                var i = parseInt(parts[0], 10);
                                if (i.toString() === parts[0]) {
                                    index = parts[0];
                                    msg = parts[1];
                                } else {
                                    index = -1;
                                    msg = resp.msg;
                                }
                            }
                        } catch (e) {
                            index = -1;
                            msg = resp.msg;
                        }
                    }

                    // Translate and display message
                    if (
                        settings.language !== 'en' && $.ajaxChimp.responses[msg] !== undefined && $.ajaxChimp.translations && $.ajaxChimp.translations[settings.language] && $.ajaxChimp.translations[settings.language][$.ajaxChimp.responses[msg]]
                    ) {
                        msg = $.ajaxChimp.translations[settings.language][$.ajaxChimp.responses[msg]];
                    }
                    label.html(msg);

                    label.show(2000);
                    if (settings.callback) {
                        settings.callback(resp);
                    }
                }

                var data = {};
                var dataArray = form.serializeArray();
                $.each(dataArray, function(index, item) {
                    data[item.name] = item.value;
                });

                $.ajax({
                    url: url,
                    data: data,
                    success: successCallback,
                    dataType: 'jsonp',
                    error: function(resp, text) {
                        console.log('mailchimp ajax submit error: ' + text);
                    }
                });

                // Translate and display submit message
                var submitMsg = 'Submitting...';
                if (
                    settings.language !== 'en' && $.ajaxChimp.translations && $.ajaxChimp.translations[settings.language] && $.ajaxChimp.translations[settings.language]['submit']
                ) {
                    submitMsg = $.ajaxChimp.translations[settings.language]['submit'];
                }
                label.html(submitMsg).show(2000);

                return false;
            });
        });
        return this;
    };
})(jQuery);

// icon flat shadows
! function(e) {
    function s(e, t) {
        e = e.replace("#", "");
        r = parseInt(e.substring(0, 2), 16);
        g = parseInt(e.substring(2, 4), 16);
        b = parseInt(e.substring(4, 6), 16);
        result = "rgba(" + r + "," + g + "," + b + "," + t / 100 + ")";
        return result
    }

    function o(e, t) {
        e = String(e).replace(/[^0-9a-f]/gi, "");
        if (e.length < 6) {
            e = e[0] + e[0] + e[1] + e[1] + e[2] + e[2]
        }
        t = t || 0;
        var n = "#",
            r, i;
        for (i = 0; i < 3; i++) {
            r = parseInt(e.substr(i * 2, 2), 16);
            r = Math.round(Math.min(Math.max(0, r + r * t), 255)).toString(16);
            n += ("00" + r).substr(r.length)
        }
        return n
    }
    var t = new Array("#1ABC9C", "#2ecc71", "#3498db", "#9b59b6", "#34495e", "#f1c40f", "#e67e22", "#e74c3c");
    var n = new Array("NE", "SE", "SW", "NW");
    var i = {
        fade: false,
        color: "random",
        boxShadow: false,
        angle: "random"
    };
    e.fn.flatshadow = function(r) {
        var u = e.extend({}, i, r);
        return this.each(function() {
            el = e(this);
            if (u.fade == true) {
                width = Math.round(el.outerWidth() / 3);
                height = Math.round(el.outerHeight() / 3)
            } else {
                width = Math.round(el.outerWidth());
                height = Math.round(el.outerHeight())
            }
            if (u.boxShadow != false) {
                var r = u.boxShadow
            }
            if (u.color != "random" && !el.attr("data-color")) {
                var i = u.color
            } else {
                var i = t[Math.floor(Math.random() * t.length)];
                if (el.attr("data-color")) {
                    var i = el.attr("data-color")
                }
            }
            if (u.angle != "random" && !el.attr("data-angle")) {
                var a = u.angle
            } else {
                var a = n[Math.floor(Math.random() * n.length)];
                if (el.attr("data-angle")) {
                    var a = el.attr("data-angle")
                }
            }
            var f = o(i, -.3);
            var l = "";
            if (u.boxShadow != false) {
                var c = ""
            } else {
                var c = "none"
            }
            switch (a) {
                case "N":
                    for (var h = 1; h <= height; h++) {
                        if (u.boxShadow != false) c += "0px " + h * 2 * -1 + "px 0px " + s(r, 50 - h / height * 100);
                        if (u.fade != false) {
                            var p = s(f, 100 - h / height * 100)
                        } else {
                            var p = f
                        }
                        l += "0px " + h * -1 + "px 0px " + p;
                        if (h != height) {
                            l += ", ";
                            c += ", "
                        }
                    }
                    break;
                case "NE":
                    for (var h = 1; h <= height; h++) {
                        if (u.boxShadow != false) c += h * 2 + "px " + h * 2 * -1 + "px 0px " + s(r, 50 - h / height * 100);
                        if (u.fade != false) {
                            var p = s(f, 100 - h / height * 100)
                        } else {
                            var p = f
                        }
                        l += h + "px " + h * -1 + "px 0px " + p;
                        if (h != height) {
                            l += ", ";
                            c += ", "
                        }
                    }
                    break;
                case "E":
                    for (var h = 1; h <= width; h++) {
                        if (u.boxShadow != false) c += h * 2 + "px " + "0px 0px " + s(r, 50 - h / width * 100);
                        if (u.fade != false) {
                            var p = s(f, 100 - h / height * 100)
                        } else {
                            var p = f
                        }
                        l += h + "px " + "0px 0px " + p;
                        if (h != width) {
                            l += ", ";
                            c += ", "
                        }
                    }
                    break;
                case "SE":
                    for (var h = 0.1; h <= height; h++) {
                        if (u.boxShadow != false) c += h * 2 + "px " + h * 2 + "px 0px " + s(r, 50 - h / height * 100);
                        if (u.fade != false) {
                            var p = s(f, 100 - h / height * 100)
                        } else {
                            var p = f
                        }
                        l += h + "px " + h + "px 0px " + p;
                        if (h != height) {
                            l += ", ";
                            c += ", "
                        }
                    }
                    break;
                case "S":
                    for (var h = 1; h <= height; h++) {
                        if (u.boxShadow != false) c += "0px " + h * 2 + "px 0px " + s(r, 50 - h / height * 100);
                        if (u.fade != false) {
                            var p = s(f, 100 - h / height * 100)
                        } else {
                            var p = f
                        }
                        l += "0px " + h + "px 0px " + p;
                        if (h != height) {
                            l += ", ";
                            c += ", "
                        }
                    }
                    break;
                case "SW":
                    for (var h = 1; h <= height; h++) {
                        if (u.boxShadow != false) c += h * 2 * -1 + "px " + h * 2 + "px 0px " + s(r, 50 - h / height * 100);
                        if (u.fade != false) {
                            var p = s(f, 100 - h / height * 100)
                        } else {
                            var p = f
                        }
                        l += h * -1 + "px " + h + "px 0px " + p;
                        if (h != height) {
                            l += ", ";
                            c += ", "
                        }
                    }
                    break;
                case "W":
                    for (var h = 1; h <= height; h++) {
                        if (u.boxShadow != false) c += h * 2 * -1 + "px " + "0px 0px " + s(r, 50 - h / height * 100);
                        if (u.fade != false) {
                            var p = s(f, 100 - h / height * 100)
                        } else {
                            var p = f
                        }
                        l += h * -1 + "px " + "0px 0px " + p;
                        if (h != height) {
                            l += ", ";
                            c += ", "
                        }
                    }
                    break;
                case "NW":
                    for (var h = 1; h <= height; h++) {
                        if (u.boxShadow != false) c += h * 2 * -1 + "px " + h * 2 * -1 + "px 0px " + s(r, 50 - h / height * 100);
                        if (u.fade != false) {
                            var p = s(f, 100 - h / height * 100)
                        } else {
                            var p = f
                        }
                        l += h * -1 + "px " + h * -1 + "px 0px " + p;
                        if (h != height) {
                            l += ", ";
                            c += ", "
                        }
                    }
                    break
            }
            el.css({
                "text-shadow": l
            })
        })
    }
}(window.jQuery);
$(document).ready(function() {
    RandHexVal = "#" + ("000000" + (Math.random() * 16777215 << 0).toString(16)).slice(-6);
    $("[class*='flat']").flatshadow({
      color: "#c0392b",
      angle: "SE",
      fade: false,
      boxShadow: "#222"
    });
    $(".flat-blue").flatshadow({
      color: "#34495e",
      angle: "SE",
      fade: false,
      boxShadow: "#333"
    });
    $(".flat-turq").flatshadow({
      color: "#3498db",
      angle: "SE",
      fade: false,
      boxShadow: "#333"
    });
    $(".flat-grey").flatshadow({
      color: "#ccc",
      angle: "SE",
      fade: false,
      boxShadow: "#333"
    });
    $(".flat-pink").flatshadow({
      color: "#8e44ad",
      angle: "SE",
      fade: false,
      boxShadow: "#333"
    });
    $(".flat-orange").flatshadow({
      color: "#e67e22",
      angle: "SE",
      fade: false,
      boxShadow: "#333"
    });
    $(".flat-green").flatshadow({
      color: "#2ecc71",
      angle: "SE",
      fade: false,
      boxShadow: "#333"
    });
    $(".flat-random").flatshadow({
      color: RandHexVal,
      angle: "SE",
      fade: false,
      boxShadow: "#333"
    })

})
<commit_msg>commented out logo animation to make noscript users happy :unamused:<commit_after>$(document).ready(function() {
  // $('#heading').addClass('animated fadeIn').removeClass('hidden');
  // $('.landing>#button').addClass('animated slideInRight').removeClass('hidden');
  // $('#heading a#button').addClass('animated slideInUp').removeClass('hidden');
  $('#scroll-indicator').addClass('animated bounce').removeClass('hidden');
  $('#mc_embed_signup').find('form').ajaxChimp();

  $('body').addClass('js');
  var $menu = $('.sidebar'),
      $menulink = $('.menu-toggle');

  $menulink.click(function() {
      $menulink.toggleClass('active');
      $menu.toggleClass('active');
      $('#page-content-wrapper').toggleClass('active');
      if ($(window).width() >= 750 && $(window).width() < 1200 ) {
        setWidth();
      }
      return false;
  });

});

$(function() {
    setNavigation();
    setWidth();
});

$(window).resize(function() {
  setWidth();
});

// current page indicator
function setNavigation() {
    var path = window.location.pathname;
    path = path.replace(/\/$/, "");

    $('#main-nav>a').each(function() {
        var href = $(this).attr('href');

        if (path.substring(0, href.length) === href) {
            if (href.length > 1) {
                $(this).addClass('active');
            }
        } else if (href.length == 1) {
            $(this).addClass('active');
        }
    });
}

// define #page-content-wrapper width
function setWidth() {

// TODO
// i know this is shitty, needs to be rewritten
    if ($(window).width() < 1200) {

        if ($(".sidebar").is(".active"))  {
          if ($(window).width() < 750) {
            var contentWrapperWidth = $(window).width() - $('.sidebar').width();
          } else {
            var contentWrapperWidth = 'inherit';
          }
        } else {
            var contentWrapperWidth = $(window).width();
        }

    } else {
        var contentWrapperWidth = $(window).width() - $('.sidebar').width();
    }

    $('#page-content-wrapper').css('width', contentWrapperWidth);
}

// clouds
function moveClouds(e, s, d) {
    $(e).css('right', '-20%');
    var wait = window.setTimeout(function() {
        $(e).animate({
            right: '120%'
        }, s, 'linear', function() {
            moveClouds(e, s, d);
        });
    }, d);
}

// mailchimp
(function($) {
    'use strict';

    $.ajaxChimp = {
        responses: {
            'We have sent you a confirmation email': 0,
            'Please enter a valid email': 1,
            'An email address must contain a single @': 2,
            'The domain portion of the email address is invalid (the portion after the @: )': 3,
            'The username portion of the email address is invalid (the portion before the @: )': 4,
            'This email address looks fake or invalid. Please enter a real email address': 5
        },
        translations: {
            'en': null
        },
        init: function(selector, options) {
            $(selector).ajaxChimp(options);
        }
    };

    $.fn.ajaxChimp = function(options) {
        $(this).each(function(i, elem) {
            var form = $(elem);
            var email = form.find('input[type=email]');
            var label = form.find('.info');

            var settings = $.extend({
                'url': form.attr('action'),
                'language': 'en'
            }, options);

            var url = settings.url.replace('/post?', '/post-json?').concat('&c=?');

            form.attr('novalidate', 'true');
            email.attr('name', 'EMAIL');

            form.submit(function() {
                var msg;

                function successCallback(resp) {
                    if (resp.result === 'success') {
                        msg = 'We have sent you a confirmation email';
                        label.removeClass('error').addClass('valid');
                        email.removeClass('error').addClass('valid');
                    } else {
                        email.removeClass('valid').addClass('error');
                        label.removeClass('valid').addClass('error');
                        var index = -1;
                        try {
                            var parts = resp.msg.split(' - ', 2);
                            if (parts[1] === undefined) {
                                msg = resp.msg;
                            } else {
                                var i = parseInt(parts[0], 10);
                                if (i.toString() === parts[0]) {
                                    index = parts[0];
                                    msg = parts[1];
                                } else {
                                    index = -1;
                                    msg = resp.msg;
                                }
                            }
                        } catch (e) {
                            index = -1;
                            msg = resp.msg;
                        }
                    }

                    // Translate and display message
                    if (
                        settings.language !== 'en' && $.ajaxChimp.responses[msg] !== undefined && $.ajaxChimp.translations && $.ajaxChimp.translations[settings.language] && $.ajaxChimp.translations[settings.language][$.ajaxChimp.responses[msg]]
                    ) {
                        msg = $.ajaxChimp.translations[settings.language][$.ajaxChimp.responses[msg]];
                    }
                    label.html(msg);

                    label.show(2000);
                    if (settings.callback) {
                        settings.callback(resp);
                    }
                }

                var data = {};
                var dataArray = form.serializeArray();
                $.each(dataArray, function(index, item) {
                    data[item.name] = item.value;
                });

                $.ajax({
                    url: url,
                    data: data,
                    success: successCallback,
                    dataType: 'jsonp',
                    error: function(resp, text) {
                        console.log('mailchimp ajax submit error: ' + text);
                    }
                });

                // Translate and display submit message
                var submitMsg = 'Submitting...';
                if (
                    settings.language !== 'en' && $.ajaxChimp.translations && $.ajaxChimp.translations[settings.language] && $.ajaxChimp.translations[settings.language]['submit']
                ) {
                    submitMsg = $.ajaxChimp.translations[settings.language]['submit'];
                }
                label.html(submitMsg).show(2000);

                return false;
            });
        });
        return this;
    };
})(jQuery);

// icon flat shadows
! function(e) {
    function s(e, t) {
        e = e.replace("#", "");
        r = parseInt(e.substring(0, 2), 16);
        g = parseInt(e.substring(2, 4), 16);
        b = parseInt(e.substring(4, 6), 16);
        result = "rgba(" + r + "," + g + "," + b + "," + t / 100 + ")";
        return result
    }

    function o(e, t) {
        e = String(e).replace(/[^0-9a-f]/gi, "");
        if (e.length < 6) {
            e = e[0] + e[0] + e[1] + e[1] + e[2] + e[2]
        }
        t = t || 0;
        var n = "#",
            r, i;
        for (i = 0; i < 3; i++) {
            r = parseInt(e.substr(i * 2, 2), 16);
            r = Math.round(Math.min(Math.max(0, r + r * t), 255)).toString(16);
            n += ("00" + r).substr(r.length)
        }
        return n
    }
    var t = new Array("#1ABC9C", "#2ecc71", "#3498db", "#9b59b6", "#34495e", "#f1c40f", "#e67e22", "#e74c3c");
    var n = new Array("NE", "SE", "SW", "NW");
    var i = {
        fade: false,
        color: "random",
        boxShadow: false,
        angle: "random"
    };
    e.fn.flatshadow = function(r) {
        var u = e.extend({}, i, r);
        return this.each(function() {
            el = e(this);
            if (u.fade == true) {
                width = Math.round(el.outerWidth() / 3);
                height = Math.round(el.outerHeight() / 3)
            } else {
                width = Math.round(el.outerWidth());
                height = Math.round(el.outerHeight())
            }
            if (u.boxShadow != false) {
                var r = u.boxShadow
            }
            if (u.color != "random" && !el.attr("data-color")) {
                var i = u.color
            } else {
                var i = t[Math.floor(Math.random() * t.length)];
                if (el.attr("data-color")) {
                    var i = el.attr("data-color")
                }
            }
            if (u.angle != "random" && !el.attr("data-angle")) {
                var a = u.angle
            } else {
                var a = n[Math.floor(Math.random() * n.length)];
                if (el.attr("data-angle")) {
                    var a = el.attr("data-angle")
                }
            }
            var f = o(i, -.3);
            var l = "";
            if (u.boxShadow != false) {
                var c = ""
            } else {
                var c = "none"
            }
            switch (a) {
                case "N":
                    for (var h = 1; h <= height; h++) {
                        if (u.boxShadow != false) c += "0px " + h * 2 * -1 + "px 0px " + s(r, 50 - h / height * 100);
                        if (u.fade != false) {
                            var p = s(f, 100 - h / height * 100)
                        } else {
                            var p = f
                        }
                        l += "0px " + h * -1 + "px 0px " + p;
                        if (h != height) {
                            l += ", ";
                            c += ", "
                        }
                    }
                    break;
                case "NE":
                    for (var h = 1; h <= height; h++) {
                        if (u.boxShadow != false) c += h * 2 + "px " + h * 2 * -1 + "px 0px " + s(r, 50 - h / height * 100);
                        if (u.fade != false) {
                            var p = s(f, 100 - h / height * 100)
                        } else {
                            var p = f
                        }
                        l += h + "px " + h * -1 + "px 0px " + p;
                        if (h != height) {
                            l += ", ";
                            c += ", "
                        }
                    }
                    break;
                case "E":
                    for (var h = 1; h <= width; h++) {
                        if (u.boxShadow != false) c += h * 2 + "px " + "0px 0px " + s(r, 50 - h / width * 100);
                        if (u.fade != false) {
                            var p = s(f, 100 - h / height * 100)
                        } else {
                            var p = f
                        }
                        l += h + "px " + "0px 0px " + p;
                        if (h != width) {
                            l += ", ";
                            c += ", "
                        }
                    }
                    break;
                case "SE":
                    for (var h = 0.1; h <= height; h++) {
                        if (u.boxShadow != false) c += h * 2 + "px " + h * 2 + "px 0px " + s(r, 50 - h / height * 100);
                        if (u.fade != false) {
                            var p = s(f, 100 - h / height * 100)
                        } else {
                            var p = f
                        }
                        l += h + "px " + h + "px 0px " + p;
                        if (h != height) {
                            l += ", ";
                            c += ", "
                        }
                    }
                    break;
                case "S":
                    for (var h = 1; h <= height; h++) {
                        if (u.boxShadow != false) c += "0px " + h * 2 + "px 0px " + s(r, 50 - h / height * 100);
                        if (u.fade != false) {
                            var p = s(f, 100 - h / height * 100)
                        } else {
                            var p = f
                        }
                        l += "0px " + h + "px 0px " + p;
                        if (h != height) {
                            l += ", ";
                            c += ", "
                        }
                    }
                    break;
                case "SW":
                    for (var h = 1; h <= height; h++) {
                        if (u.boxShadow != false) c += h * 2 * -1 + "px " + h * 2 + "px 0px " + s(r, 50 - h / height * 100);
                        if (u.fade != false) {
                            var p = s(f, 100 - h / height * 100)
                        } else {
                            var p = f
                        }
                        l += h * -1 + "px " + h + "px 0px " + p;
                        if (h != height) {
                            l += ", ";
                            c += ", "
                        }
                    }
                    break;
                case "W":
                    for (var h = 1; h <= height; h++) {
                        if (u.boxShadow != false) c += h * 2 * -1 + "px " + "0px 0px " + s(r, 50 - h / height * 100);
                        if (u.fade != false) {
                            var p = s(f, 100 - h / height * 100)
                        } else {
                            var p = f
                        }
                        l += h * -1 + "px " + "0px 0px " + p;
                        if (h != height) {
                            l += ", ";
                            c += ", "
                        }
                    }
                    break;
                case "NW":
                    for (var h = 1; h <= height; h++) {
                        if (u.boxShadow != false) c += h * 2 * -1 + "px " + h * 2 * -1 + "px 0px " + s(r, 50 - h / height * 100);
                        if (u.fade != false) {
                            var p = s(f, 100 - h / height * 100)
                        } else {
                            var p = f
                        }
                        l += h * -1 + "px " + h * -1 + "px 0px " + p;
                        if (h != height) {
                            l += ", ";
                            c += ", "
                        }
                    }
                    break
            }
            el.css({
                "text-shadow": l
            })
        })
    }
}(window.jQuery);
$(document).ready(function() {
    RandHexVal = "#" + ("000000" + (Math.random() * 16777215 << 0).toString(16)).slice(-6);
    $("[class*='flat']").flatshadow({
      color: "#c0392b",
      angle: "SE",
      fade: false,
      boxShadow: "#222"
    });
    $(".flat-blue").flatshadow({
      color: "#34495e",
      angle: "SE",
      fade: false,
      boxShadow: "#333"
    });
    $(".flat-turq").flatshadow({
      color: "#3498db",
      angle: "SE",
      fade: false,
      boxShadow: "#333"
    });
    $(".flat-grey").flatshadow({
      color: "#ccc",
      angle: "SE",
      fade: false,
      boxShadow: "#333"
    });
    $(".flat-pink").flatshadow({
      color: "#8e44ad",
      angle: "SE",
      fade: false,
      boxShadow: "#333"
    });
    $(".flat-orange").flatshadow({
      color: "#e67e22",
      angle: "SE",
      fade: false,
      boxShadow: "#333"
    });
    $(".flat-green").flatshadow({
      color: "#2ecc71",
      angle: "SE",
      fade: false,
      boxShadow: "#333"
    });
    $(".flat-random").flatshadow({
      color: RandHexVal,
      angle: "SE",
      fade: false,
      boxShadow: "#333"
    })

})
<|endoftext|>


<commit_before>$(document).ready(function onReady() {
	$("span.network-name").html(GCMRC.Networks[CONFIG.networkName].displayName);
	var upstreamStation = GCMRC.Stations[CONFIG.upstreamStationName];
	var downstreamStation = GCMRC.Stations[CONFIG.downstreamStationName];
	var upstreamSecondaryStation = GCMRC.Stations[GCMRC.Page.reach.upstreamSecondaryStation];

	$('#station-title').html(GCMRC.Page.reach.reachName);

	$('#loading').hide();
	$('#parameterLoading').hide();

	GCMRC.Page.addCredits();

	GCMRC.Page.createMiniMap({
		upstreamStationName: (!upstreamStation) ? null : upstreamStation.siteName,
		downstreamStationName: (!downstreamStation) ? null : downstreamStation.siteName,
		upstreamSecondaryStation: (!upstreamSecondaryStation) ? null : upstreamSecondaryStation.siteName
	});

	GCMRC.Page.buildPORView($('#porContainer'), GCMRC.Page.earliestPositionISO, GCMRC.Page.latestPositionISO);

        if (GCMRC.isDinoNetwork(CONFIG.networkName)) {
			$('#bedloadSlider').children().first().text('Sand Bedload Included in Sand Budget');
			GCMRC.Page.buildRadioInfo($('#bedloadList'));
			$("input[name=bedloadToggle][value=1]").prop('checked', true);
			GCMRC.Page.isBedloadIncluded = Boolean(parseFloat($("input[name=bedloadToggle]:checked").val()));
			GCMRC.Page.bedloadToggleChange(GCMRC.Page.isBedloadIncluded);
			$('#bedloadSlider').change(function(){
			    GCMRC.Page.isBedloadIncluded = Boolean(parseFloat($("input[name=bedloadToggle]:checked").val()));
			    GCMRC.Page.bedloadToggleChange(GCMRC.Page.isBedloadIncluded);
			});
        } else {

        var bedloadList = [GCMRC.Page.sliderConfig.bedLoad];

        GCMRC.Page.createParameterList($('#bedloadList'), bedloadList);
	}

	GCMRC.Page.createDateList($('#lastSedDates'), GCMRC.Page.reach);

	var getParamList = function() {
		var result = [

		];

		var addToResult = {
			sandRiverLoad : false,
			finesRiverLoad : false,
			sandMajor : false,
			finesMajor : false,
			sandMinor : false,
			finesMinor : false,
			bedloadCoeff: false
		}

		GCMRC.Page.reachDetail.each(function(el) {
			if (el.reachGroup === "S Sand Cumul Load") {
				addToResult["sandRiverLoad"] = true;
				if (el.majorStation) {
					addToResult["sandMajor"] = true;
				}
				if (el.minorStation) {
					addToResult["sandMinor"] = true;
				}
			}
			if (el.reachGroup === "S Fines Cumul Load") {
				addToResult["finesRiverLoad"] = true;
				if (el.majorStation) {
					addToResult["finesMajor"] = true;
				}
				if (el.minorStation) {
					addToResult["finesMinor"] = true;
				}
			}
		});

		if (addToResult["sandRiverLoad"]) {
			result.push(GCMRC.Page.sliderConfig.riverLoad);
		}
		if (addToResult["finesRiverLoad"]) {
			result.push(GCMRC.Page.sliderConfig.riverFinesLoad);
		}
		if (addToResult["sandMajor"]) {
			result.push(GCMRC.Page.sliderConfig.majorTribLoad);
		}
		if (addToResult["finesMajor"]) {
			result.push(GCMRC.Page.sliderConfig.majorTribFinesLoad);
		}
		if (addToResult["sandMinor"]) {
			result.push(GCMRC.Page.sliderConfig.minorTribLoad);
		}
		if (addToResult["finesMinor"]) {
			result.push(GCMRC.Page.sliderConfig.minorTribFinesLoad);
		}

		return result;
	}

	GCMRC.Page.createParameterList($('#parameterList'), getParamList());

	$('#buildGraph').click(GCMRC.Page.buildGraphClicked);
	$('#downloadData').click(GCMRC.Page.downloadDataClicked);

	$('#beginDatePicker').attr('value', new Date(GCMRC.Page.latestPosition).utc().addMonths(-1).format('{yyyy}-{MM}-{dd}'));
	$('#beginDatePicker').datepicker({
		format: 'yyyy-mm-dd',
		startDate: new Date(GCMRC.Page.earliestPosition),
		endDate: new Date(GCMRC.Page.latestPosition),
		startView: 0
	});
	$('#endDatePicker').attr('value', new Date(GCMRC.Page.latestPosition).utc().format('{yyyy}-{MM}-{dd}'));
	$('#endDatePicker').datepicker({
		format: 'yyyy-mm-dd',
		startDate: new Date(GCMRC.Page.earliestPosition),
		endDate: new Date(GCMRC.Page.latestPosition),
		startView: 0
	});

	$('#resetDefaults').click(GCMRC.Page.resetSliders);

	$('#loading').ajaxStart(function() {
		$(this).show();
	}).ajaxStop(function() {
		$(this).hide();
	});
});<commit_msg>removing accidental change<commit_after>$(document).ready(function onReady() {
	$("span.network-name").html(GCMRC.Networks[CONFIG.networkName].displayName);
	var upstreamStation = GCMRC.Stations[CONFIG.upstreamStationName];
	var downstreamStation = GCMRC.Stations[CONFIG.downstreamStationName];
	var upstreamSecondaryStation = GCMRC.Stations[GCMRC.Page.reach.upstreamSecondaryStation];

	$('#station-title').html(GCMRC.Page.reach.reachName);

	$('#loading').hide();
	$('#parameterLoading').hide();

	GCMRC.Page.addCredits();

	GCMRC.Page.createMiniMap({
		upstreamStationName: (!upstreamStation) ? null : upstreamStation.siteName,
		downstreamStationName: (!downstreamStation) ? null : downstreamStation.siteName,
		upstreamSecondaryStation: (!upstreamSecondaryStation) ? null : upstreamSecondaryStation.siteName
	});

	GCMRC.Page.buildPORView($('#porContainer'), GCMRC.Page.earliestPositionISO, GCMRC.Page.latestPositionISO);

        if (GCMRC.isDinoNetwork(CONFIG.networkName)) {
			$('#bedloadSlider').children().first().text('Sand Bedload Included in Sand Budget');
			GCMRC.Page.buildRadioInfo($('#bedloadList'));
			$("input[name=bedloadToggle][value=1]").prop('checked', true);
			GCMRC.Page.isBedloadIncluded = Boolean(parseFloat($("input[name=bedloadToggle]:checked").val()));
			GCMRC.Page.bedloadToggleChange(GCMRC.Page.isBedloadIncluded);
			$('#bedloadSlider').change(function(){
			    GCMRC.Page.isBedloadIncluded = Boolean(parseFloat($("input[name=bedloadToggle]:checked").val()));
			    GCMRC.Page.bedloadToggleChange(GCMRC.Page.isBedloadIncluded);
			});
        } else {

        var bedloadList = [GCMRC.Page.sliderConfig.bedLoad];

        GCMRC.Page.createParameterList($('#bedloadList'), bedloadList);
	}

	GCMRC.Page.createDateList($('#lastSedDates'), GCMRC.Page.reach);

	var getParamList = function() {
		var result = [

		];

		var addToResult = {
			sandRiverLoad : false,
			finesRiverLoad : false,
			sandMajor : false,
			finesMajor : false,
			sandMinor : false,
			finesMinor : false,
			bedloadCoeff: false
		}

		GCMRC.Page.reachDetail.each(function(el) {
			if (el.reachGroup === "S Sand Cumul Load") {
				addToResult["sandRiverLoad"] = true;
				if (el.majorStation) {
					addToResult["sandMajor"] = true;
				}
				if (el.minorStation) {
					addToResult["sandMinor"] = true;
				}
			}
			if (el.reachGroup === "S Fines Cumul Load") {
				addToResult["finesRiverLoad"] = true;
				if (el.majorStation) {
					addToResult["finesMajor"] = true;
				}
				if (el.minorStation) {
					addToResult["finesMinor"] = true;
				}
			}
		});

		if (addToResult["sandRiverLoad"]) {
			result.push(GCMRC.Page.sliderConfig.riverLoad);
		}
		if (addToResult["finesRiverLoad"]) {
			result.push(GCMRC.Page.sliderConfig.riverFinesLoad);
		}
		if (addToResult["sandMajor"]) {
			result.push(GCMRC.Page.sliderConfig.majorTribLoad);
		}
		if (addToResult["finesMajor"]) {
			result.push(GCMRC.Page.sliderConfig.majorTribFinesLoad);
		}
		if (addToResult["sandMinor"]) {
			result.push(GCMRC.Page.sliderConfig.minorTribLoad);
		}
		if (addToResult["finesMinor"]) {
			result.push(GCMRC.Page.sliderConfig.minorTribFinesLoad);
		}

		return result;
	}

	GCMRC.Page.createParameterList($('#parameterList'), getParamList());

	$('#buildGraph').click(GCMRC.Page.buildGraphClicked);
	$('#downloadData').click(GCMRC.Page.downloadDataClicked);

	$('#beginDatePicker').attr('value', new Date(GCMRC.Page.latestPosition).utc().addMonths(-1).format('{yyyy}-{MM}-{dd}'));
	$('#beginDatePicker').datepicker({
		format: 'yyyy-mm-dd',
		startDate: new Date(GCMRC.Page.earliestPosition),
		endDate: new Date(GCMRC.Page.latestPosition),
		startView: 0
	});
	$('#endDatePicker').attr('value', new Date(GCMRC.Page.latestPosition).utc().format('{yyyy}-{MM}-{dd}'));
	$('#endDatePicker').datepicker({
		format: 'yyyy-mm-dd',
		startDate: new Date(GCMRC.Page.earliestPosition),
		endDate: new Date(GCMRC.Page.latestPosition),
		startView: 0
	});

	$('#resetDefaults').click(GCMRC.Page.resetSliders);

	$('#loading').ajaxStart(function() {
		$(this).show();
	}).ajaxStop(function() {
		$(this).hide();
	});
});
<|endoftext|>