<commit_before>var RECORD_URL = "http://localhost/record?start=-6&duration=18";
var TWITTER_USERNAME = "GoalFlash";

var twitter = require('twitter')
  , humanize = require('humanize')
  , googl = require('goo.gl')
  , request = require('request');

var twit = new twitter(require('./settings.json').twitter);

var notify = function(url) {
  var text = lastTweet.replace(/http.*/i,'').replace(/^RT @[a-zA-Z]{1,15}:? ?/i,'').replace(/ $/,'');
  googl.shorten(url)
    .then(function (shortUrl) {
      twit.updateStatus(text + " - Video: "+shortUrl, function(data) {
        console.log("notify> ", data);
      });
    })
    .catch(function (err) {
        console.error(err.message);
    });
};

var lastTweet = '';

/* For testing:
setTimeout(function() {
  request(RECORD_URL, function(err, res, body) {
    console.log("body: ", body);
    notify(body);
  });

}, 1000);
*/

console.log(humanize.date("Y-m-d H:i:s")+" Connecting to the Twitter Stream for @"+TWITTER_USERNAME);
twit.stream('user', {track:TWITTER_USERNAME}, function(stream) {
    console.log(humanize.date("Y-m-d H:i:s")+" Connected");
    stream.on('data', function(data) {
      console.log(humanize.date("Y-m-d H:i:s")+" DATA: ", data);
      if(!data.text) return;
      if(data.user.screen_name != TWITTER_USERNAME) return;
      lastTweet = data.text;
      request(RECORD_URL, function(err, res, body) {
        console.log("body: ", body);
        if(body.match(/http/))
          notify(body);
      });
    });

    stream.on('error', function(error) {
      console.error("Error in the twitter stream: ", error);
      process.exit(1);
    });

    stream.on('end', function(error) {
      console.error("Twitter stream ended - exiting");
      process.exit(1);
    });
});
<commit_msg>starting at -7s<commit_after>var RECORD_URL = "http://localhost/record?start=-7&duration=18";
var TWITTER_USERNAME = "GoalFlash";

var twitter = require('twitter')
  , humanize = require('humanize')
  , googl = require('goo.gl')
  , request = require('request');

var twit = new twitter(require('./settings.json').twitter);

var notify = function(url) {
  var text = lastTweet.replace(/http.*/i,'').replace(/^RT @[a-zA-Z]{1,15}:? ?/i,'').replace(/ $/,'');
  googl.shorten(url)
    .then(function (shortUrl) {
      twit.updateStatus(text + " - Video: "+shortUrl, function(data) {
        console.log("notify> ", data);
      });
    })
    .catch(function (err) {
        console.error(err.message);
    });
};

var lastTweet = '';

/* For testing:
setTimeout(function() {
  request(RECORD_URL, function(err, res, body) {
    console.log("body: ", body);
    notify(body);
  });

}, 1000);
*/

console.log(humanize.date("Y-m-d H:i:s")+" Connecting to the Twitter Stream for @"+TWITTER_USERNAME);
twit.stream('user', {track:TWITTER_USERNAME}, function(stream) {
    console.log(humanize.date("Y-m-d H:i:s")+" Connected");
    stream.on('data', function(data) {
      console.log(humanize.date("Y-m-d H:i:s")+" DATA: ", data);
      if(!data.text) return;
      if(data.user.screen_name != TWITTER_USERNAME) return;
      lastTweet = data.text;
      request(RECORD_URL, function(err, res, body) {
        console.log("body: ", body);
        if(body.match(/http/))
          notify(body);
      });
    });

    stream.on('error', function(error) {
      console.error("Error in the twitter stream: ", error);
      process.exit(1);
    });

    stream.on('end', function(error) {
      console.error("Twitter stream ended - exiting");
      process.exit(1);
    });
});
<|endoftext|>


<commit_before>// Global variables
var csvFields;
var map;
var zoom;
var layer;
var percent;
var fieldSelect;
var fieldsById;
var stat;
var body;
var topology;
var carto;
var geometries;
var URL_TOPO;
var latitude = null;
var longitude = null;
var col = null;
var pScale = null;

/*
 * Main program instructions
 */
console.log("Running Cartograms 4 All Web App");

$(document).ready(function() {
  // if not already set, set new cookie.
  var session_id = generateSessionID(16);
  if( readCookie('user_session_cookie') === null ){
    createCookie('user_session_cookie', session_id, 10, '/');
  }else{
    //importUserSettings()
  }
  init();
});

/*
 * End of main program instructions
 */

function init() {
  run();
  // don't initialize until user has uploaded a .csv file
  if(document.getElementById('input_csv').files[0] == null){
    console.log("Cartograms 4 All: Waiting for user inputted CSV file");
    return;
  }
/*
  if(document.getElementById('input_topo').files[0] == null){
    console.log("Cartograms 4 All: Waiting for user inputted topojson file");
    return;
  }
 if(latitude == null){
    console.log("please enter the projection for latitude");
    return;
  }

  if(longitude == null){
    console.log("please enter the projection for longitude");
    return;
  }

  if(pScale == null){
    console.log("please enter the scale of projection");
    return;
  }
*/
  // CODE TO TEST FUNCTIONALITY OF writeToServer() and readFromServer()
  SESSION_ID = readCookie('user_session_cookie');

  //var send_text = "my_text_to_save";
  //writeToServer(SESSION_ID, send_text);
  //console.log(SESSION_ID);

  //var return_string = readFromServer(SESSION_ID);
  //console.log(return_string);
  // CODE TO TEST FUNCTIONALITY OF writeToServer() and readFromServer()

  USER_CSV = document.getElementById('input_csv').files[0];
  saveCSV(USER_CSV);

  USER_TOPO = document.getElementById('input_topo').files[0]
  if (USER_TOPO == null){
    URL_TOPO = "data/us-states.topojson";
  }

  console.log("Cartograms 4 All: Start init()");
  map = d3.select("#map");
  zoom = d3.behavior.zoom()
    .translate([-38, 32])
    .scale(.94)
    .scaleExtent([0.5, 10.0])
    .on("zoom", updateZoom);
  layer = map.append("g")
    .attr("id", "layer"),
    states = layer.append("g")
    .attr("id", "states")
    .selectAll("path");

  csvFields = getCSVFields(initCartogram);
var width = 1215,  //2100
    height = 600;

//var center = [38.996815, 34.802075];
var center = [latitude, longitude];

//d3.geo.albersUsa()
var latitude  = 1 // default to be USA
if (latitude == 1){

  var proj = d3.geo.albersUsa(),
      rawData,
    dataById = {};

}else{

  var proj = d3.geo.conicConformal()
    .center(center)
    .clipAngle(180)
    // Size of the map itself, you may want to play around with this in
    // relation to your canvas size
    .scale(pScale)
    // Center the map in the middle of the canvas
    .translate([width / 2, height / 2])
    .precision(.1),
    rawData,
    dataById = {};
 }
  console.log("CARTOGRAMS setup");
  carto = d3.cartogram()
    .projection(proj)
    .properties(function(d) {
      return dataById[d.id];
    })
    .value(function(d) {
      return +d.properties[field];
    });
      //URL_TOPO = URL.createObjectURL(USER_TOPO);

  console.log("Before state initlization");
  var URL_TOPO = DATA_DIRECTORY + "us-states.topojson";
  d3.json(URL_TOPO, function(topology) {
    this.topology = topology;
    geometries = topology.objects.states.geometries;
    d3.csv(CSV_URL, function(rawData) {
      dataById = d3.nest()
        .key(function(d) {
          return d.NAME;
        })
        .rollup(function(d) {
          return d[0];
        })
        .map(rawData);
      var features = carto.features(topology, geometries),
        path = d3.geo.path().projection(proj);

      states = states.data(features)
        .enter()
        .append("path")
        .attr("class", "state")
        .attr("id", function(d) {
          return d.properties.id;
        })
        .attr("fill", "#fff")
        .attr("d", path);
      states.append("title");

      // Waits until fields has been defined
      function waitForFields() {
        if (typeof someVariable !== "undefined") {

            console.log("calling PaserHash");

          parseHash(fieldsById);
        } else {
          setTimeout(waitForFields, 250);
        }
      }

      // Waits until fields has been defined
      function waitForTopology() {
        if (typeof someVariable !== "undefined") {
          console.log("calling PaserHash");

          initTopo();
        } else {
          setTimeout(topology, 250);
        }
      }
    });
  });

  console.log("Cartograms 4 All: Finished init()");
}

//initialization of the new cartogram,
//based on the csv fields passed in.
function initCartogram(csvFields) {
  fields = csvFields;
  // Data info for the cartogram
  percent = (function() {
      var fmt = d3.format(".2f");
      return function(n) {
        return fmt(n) + "%";
      };
    })(),
    fields = csvFields,
    // TODO: Make this customizable
    // NOTE: Might just have this detect if there are digits at the end of the column or beginning,
      // and if there are then use those as a year
    // TODO: Make a custom function getTimeInField() which will clear
    fieldsById = d3.nest()
    .key(function(d) {
      return d.id;
    })
    .rollup(function(d) {
      return d[0];
    })
    .map(fields),
    // TODO: Set default field to something that looks like data
    field = fields[1],
    // TODO: Allow for customization of map color
    colors = colorbrewer.RdYlBu[3]
    .reverse()
    .map(function(rgb) {
      return d3.hsl(rgb);
    });

  body = d3.select("body");
  stat = d3.select("#status");

  fieldSelect = d3.select("#field")
    .on("change", function(e) {
      field = fields[this.selectedIndex];
      location.hash = "#" + field.id;
    });

  fieldSelect.selectAll("option")
    .data(fields)
    .enter()
    .append("option")
    .attr("value", function(d) {
      return d.id;
    })
    .text(function(d) {
      return d.name;
    });

  /* TODO: Reincorporate year
  var yearSelect = d3.select("#year")
      .on("change", function(e) {
          year = years[this.selectedIndex];
          location.hash = "#" + [field.id, year].join("/");
      });

  yearSelect.selectAll("option")
      .data(years)
      .enter()
      .append("option")
      .attr("value", function(y) { return y; })
      .text(function(y) { return y; })
  */

  updateZoom();
}

window.onhashchange = function() {
  console.log("calling parseHash(fieldsById)")
  parseHash(fieldsById);
};

var deferredUpdate = (function() {
  var timeout;
  return function() {
    var args = arguments;
    clearTimeout(timeout);
    stat.text("calculating...");
    return timeout = setTimeout(function() {
      update.apply(null, arguments);
    }, 10);
  };
})();

var hashish = d3.selectAll("a.hashish")
  .datum(function() {
    return this.href;
  });
<commit_msg>Deploy<commit_after>// Global variables
var csvFields;
var map;
var zoom;
var layer;
var percent;
var fieldSelect;
var fieldsById;
var stat;
var body;
var topology;
var carto;
var geometries;
var URL_TOPO;
var latitude = null;
var longitude = null;
var col = null;
var pScale = null;

/*
 * Main program instructions
 */
console.log("Running Cartograms 4 All Web App");

$(document).ready(function() {
  // if not already set, set new cookie.
  var session_id = generateSessionID(16);
  if( readCookie('user_session_cookie') === null ){
    createCookie('user_session_cookie', session_id, 10, '/');
  }else{
    //importUserSettings()
  }
  init();
});

/*
 * End of main program instructions
 */

function init() {
  run();
  // don't initialize until user has uploaded a .csv file
  if(document.getElementById('input_csv').files[0] == null){
    console.log("Cartograms 4 All: Waiting for user inputted CSV file");
    return;
  }
/*
  if(document.getElementById('input_topo').files[0] == null){
    console.log("Cartograms 4 All: Waiting for user inputted topojson file");
    return;
  }
 if(latitude == null){
    console.log("please enter the projection for latitude");
    return;
  }

  if(longitude == null){
    console.log("please enter the projection for longitude");
    return;
  }

  if(pScale == null){
    console.log("please enter the scale of projection");
    return;
  }
*/
  // CODE TO TEST FUNCTIONALITY OF writeToServer() and readFromServer()
  SESSION_ID = readCookie('user_session_cookie');

  //var send_text = "my_text_to_save";
  //writeToServer(SESSION_ID, send_text);
  //console.log(SESSION_ID);

  //var return_string = readFromServer(SESSION_ID);
  //console.log(return_string);
  // CODE TO TEST FUNCTIONALITY OF writeToServer() and readFromServer()

  USER_CSV = document.getElementById('input_csv').files[0];
  saveCSV(USER_CSV);

  USER_TOPO = document.getElementById('input_topo').files[0]
  if (USER_TOPO == null){
    URL_TOPO = "data/us-states.topojson";
  }

  console.log("Cartograms 4 All: Start init()");
  map = d3.select("#map");
  zoom = d3.behavior.zoom()
    .translate([-38, 32])
    .scale(.94)
    .scaleExtent([0.5, 10.0])
    .on("zoom", updateZoom);
  layer = map.append("g")
    .attr("id", "layer"),
    states = layer.append("g")
    .attr("id", "states")
    .selectAll("path");

  csvFields = getCSVFields(initCartogram);
var width = 1215,  //2100
    height = 600;

//var center = [38.996815, 34.802075];
var center = [latitude, longitude];

//d3.geo.albersUsa()
var latitude  = 1 // default to be USA
if (latitude == 1){

  var proj = d3.geo.albersUsa(),
      rawData,
    dataById = {};

}else{

  var proj = d3.geo.conicConformal()
    .center(center)
    .clipAngle(180)
    // Size of the map itself, you may want to play around with this in
    // relation to your canvas size
    .scale(pScale)
    // Center the map in the middle of the canvas
    .translate([width / 2, height / 2])
    .precision(.1),
    rawData,
    dataById = {};
 }
  console.log("CARTOGRAMS setup");
  carto = d3.cartogram()
    .projection(proj)
    .properties(function(d) {
      return dataById[d.id];
    })
    .value(function(d) {
      return +d.properties[field];
    });
      //URL_TOPO = URL.createObjectURL(USER_TOPO);

  console.log("Before state initlization");
  var URL_TOPO = DATA_DIRECTORY + "us-states.topojson";
  d3.json(URL_TOPO, function(topology) {
    this.topology = topology;
    geometries = topology.objects.states.geometries;
    d3.csv(CSV_URL, function(rawData) {
      dataById = d3.nest()
        .key(function(d) {
          return d.NAME;
        })
        .rollup(function(d) {
          return d[0];
        })
        .map(rawData);
      var features = carto.features(topology, geometries),
        path = d3.geo.path().projection(proj);

      states = states.data(features)
        .enter()
        .append("path")
        .attr("class", "state")
        .attr("id", function(d) {
          return d.id;
        })
        .attr("fill", "#fff")
        .attr("d", path);
      states.append("title");

      // Waits until fields has been defined
      function waitForFields() {
        if (typeof someVariable !== "undefined") {

            console.log("calling PaserHash");

          parseHash(fieldsById);
        } else {
          setTimeout(waitForFields, 250);
        }
      }

      // Waits until fields has been defined
      function waitForTopology() {
        if (typeof someVariable !== "undefined") {
          console.log("calling PaserHash");

          initTopo();
        } else {
          setTimeout(topology, 250);
        }
      }
    });
  });

  console.log("Cartograms 4 All: Finished init()");
}

//initialization of the new cartogram,
//based on the csv fields passed in.
function initCartogram(csvFields) {
  fields = csvFields;
  // Data info for the cartogram
  percent = (function() {
      var fmt = d3.format(".2f");
      return function(n) {
        return fmt(n) + "%";
      };
    })(),
    fields = csvFields,
    // TODO: Make this customizable
    // NOTE: Might just have this detect if there are digits at the end of the column or beginning,
      // and if there are then use those as a year
    // TODO: Make a custom function getTimeInField() which will clear
    fieldsById = d3.nest()
    .key(function(d) {
      return d.id;
    })
    .rollup(function(d) {
      return d[0];
    })
    .map(fields),
    // TODO: Set default field to something that looks like data
    field = fields[1],
    // TODO: Allow for customization of map color
    colors = colorbrewer.RdYlBu[3]
    .reverse()
    .map(function(rgb) {
      return d3.hsl(rgb);
    });

  body = d3.select("body");
  stat = d3.select("#status");

  fieldSelect = d3.select("#field")
    .on("change", function(e) {
      field = fields[this.selectedIndex];
      location.hash = "#" + field.id;
    });

  fieldSelect.selectAll("option")
    .data(fields)
    .enter()
    .append("option")
    .attr("value", function(d) {
      return d.id;
    })
    .text(function(d) {
      return d.name;
    });

  /* TODO: Reincorporate year
  var yearSelect = d3.select("#year")
      .on("change", function(e) {
          year = years[this.selectedIndex];
          location.hash = "#" + [field.id, year].join("/");
      });

  yearSelect.selectAll("option")
      .data(years)
      .enter()
      .append("option")
      .attr("value", function(y) { return y; })
      .text(function(y) { return y; })
  */

  updateZoom();
}

window.onhashchange = function() {
  console.log("calling parseHash(fieldsById)")
  parseHash(fieldsById);
};

var deferredUpdate = (function() {
  var timeout;
  return function() {
    var args = arguments;
    clearTimeout(timeout);
    stat.text("calculating...");
    return timeout = setTimeout(function() {
      update.apply(null, arguments);
    }, 10);
  };
})();

var hashish = d3.selectAll("a.hashish")
  .datum(function() {
    return this.href;
  });
<|endoftext|>


<commit_before>function storage_budget_saveBudget(sYYYYMM, sAmount){
    var boolStatus = false;
    try{
        var nAmount = parseFloat(sAmount);
        localStorage.setItem(sYYYYMM, nAmount);
        boolStatus = true;

        var objTest = new Object();
        objTest.budgetDate = sYYYYMM;
        objTest.amount = nAmount;

        var sCheck = JSON.stringify(objTest);
        e_alert(sCheck);
    }
    catch(err){
        console.error('storage_budget_saveBudget() - ' + err.description);
        e_alert('Error: ' + err.description);
    }

    return boolStatus;
}

function storage_budget_retrieveBudget(sYYYYMM){
    return parseFloat(localStorage.getItem(sYYYYMM));
}
<commit_msg>Update storage.budget.js<commit_after>var BUDGET = 'budget-';

function storage_budget_saveBudget(sYYYYMM, sAmount){
    var boolStatus = false;
    try{
        var nAmount = parseFloat(sAmount);
        localStorage.setItem(BUDGET + sYYYYMM, nAmount);
        boolStatus = true;

        /*
        var objTest = new Object();
        objTest.budgetDate = sYYYYMM;
        objTest.amount = nAmount;

        var sCheck = JSON.stringify(objTest);
        e_alert(sCheck);
        */

    }
    catch(err){
        console.error('storage_budget_saveBudget() - ' + err.description);
        e_alert('Error: ' + err.description);
    }

    return boolStatus;
}

function storage_budget_retrieveBudget(sYYYYMM){
    return parseFloat(localStorage.getItem(BUDGET + sYYYYMM));
}
<|endoftext|>


<commit_before>angular.module('timer', [])
    .directive('timer', ['$compile', function ($compile) {
        return  {
            restrict: 'E',
            replace: false,
            scope: {
                interval: '=interval',
                startTimeAttr: '=startTime',
                countdownattr: '=countdown',
                autoStart: '=autoStart'
            },
            controller: function ($scope, $element) {
                if ($element.html().trim().length === 0) {
                    $element.append($compile('{{millis}}')($scope));
                }

                $scope.startTime = null;
                $scope.timeoutId = null;
                $scope.countdown = $scope.countdownattr && parseInt($scope.countdownattr, 10) > 0 ? parseInt($scope.countdownattr, 10) : undefined;
                $scope.isRunning = false;

                $scope.$on('timer-start', function () {
                    $scope.start();
                });

                $scope.$on('timer-resume', function () {
                    $scope.resume();
                });

                $scope.$on('timer-stop', function () {
                    $scope.stop();
                });

                function resetTimeout() {
                    if ($scope.timeoutId) {
                        clearTimeout($scope.timeoutId);
                    }
                }

                $scope.start = $element[0].start = function () {
                    $scope.startTime = $scope.startTimeAttr ? new Date($scope.startTimeAttr) : new Date();
                    $scope.countdown = $scope.countdownattr && parseInt($scope.countdownattr, 10) > 0 ? parseInt($scope.countdownattr, 10) : undefined;
                    resetTimeout();
                    tick();
                };

                $scope.resume = $element[0].resume = function () {
                    resetTimeout();
                    if($scope.countdownattr){
                        $scope.countdown += 1;
                    }
                    $scope.startTime = new Date() - ($scope.stoppedTime - $scope.startTime);
                    tick();
                };

                $scope.stop = $element[0].stop = function () {
                    $scope.stoppedTime = new Date();
                    resetTimeout();
                    $scope.$emit('timer-stopped', {millis: $scope.millis, seconds: $scope.seconds, minutes: $scope.minutes, hours: $scope.hours, days: $scope.days});
                    $scope.timeoutId = null;
                };

                $element.bind('$destroy', function () {
                    resetTimeout();
                });

                function calculateTimeUnits() {
                    $scope.seconds = Math.floor(($scope.millis / 1000) % 60);
                    $scope.minutes = Math.floor((($scope.millis / (1000 * 60)) % 60));
                    $scope.hours = Math.floor((($scope.millis / (1000 * 60 * 60)) % 24));
                    $scope.days = Math.floor((($scope.millis / (1000 * 60 * 60)) / 24));
                }

                //determine initial values of time units
                if($scope.countdownattr){
                    $scope.millis = $scope.countdownattr * 1000
                } else {
                    $scope.millis = 0
                }
                calculateTimeUnits()

                var tick = function () {

                    $scope.millis = new Date() - $scope.startTime;
                    adjustment = $scope.millis % 1000;

                    if ($scope.countdownattr) {
                        $scope.millis = $scope.countdown * 1000;
                    }

                    calculateTimeUnits();
                    if ($scope.countdown > 0) {
                        $scope.countdown--;
                    }
                    else if ($scope.countdown <= 0) {
                        $scope.stop();
                        return;
                    }

                    //We are not using $timeout for a reason. Please read here - https://github.com/siddii/angular-timer/pull/5
                    $scope.timeoutId = setTimeout(function () {
                        tick();
                        $scope.$apply();
                    }, $scope.interval - adjustment);

                    $scope.$emit('timer-tick', {timeoutId: $scope.timeoutId, millis: $scope.millis});
                };

                if ($scope.autoStart == undefined || $scope.autoStart == true) {
                    $scope.start();
                }
            }
        };
    }]);
<commit_msg>* code cleanup. * alias method for stop (pause)<commit_after>angular.module('timer', [])
    .directive('timer', ['$compile', function ($compile) {
        return  {
            restrict: 'E',
            replace: false,
            scope: {
                interval: '=interval',
                startTimeAttr: '=startTime',
                countdownattr: '=countdown',
                autoStart: '=autoStart'
            },
            controller: function ($scope, $element) {
                if ($element.html().trim().length === 0) {
                    $element.append($compile('{{millis}}')($scope));
                }

                $scope.startTime = null;
                $scope.timeoutId = null;
                $scope.countdown = $scope.countdownattr && parseInt($scope.countdownattr, 10) > 0 ? parseInt($scope.countdownattr, 10) : undefined;
                $scope.isRunning = false;

                $scope.$on('timer-start', function () {
                    $scope.start();
                });

                $scope.$on('timer-resume', function () {
                    $scope.resume();
                });

                $scope.$on('timer-stop', function () {
                    $scope.stop();
                });

                function resetTimeout() {
                    if ($scope.timeoutId) {
                        clearTimeout($scope.timeoutId);
                    }
                }

                $scope.start = $element[0].start = function () {
                    $scope.startTime = $scope.startTimeAttr ? new Date($scope.startTimeAttr) : new Date();
                    $scope.countdown = $scope.countdownattr && parseInt($scope.countdownattr, 10) > 0 ? parseInt($scope.countdownattr, 10) : undefined;
                    resetTimeout();
                    tick();
                };

                $scope.resume = $element[0].resume = function () {
                    resetTimeout();
                    if ($scope.countdownattr) {
                        $scope.countdown += 1;
                    }
                    $scope.startTime = new Date() - ($scope.stoppedTime - $scope.startTime);
                    tick();
                };

                $scope.stop = $scope.pause = $element[0].stop = $element[0].pause = function () {
                    $scope.stoppedTime = new Date();
                    resetTimeout();
                    $scope.$emit('timer-stopped', {millis: $scope.millis, seconds: $scope.seconds, minutes: $scope.minutes, hours: $scope.hours, days: $scope.days});
                    $scope.timeoutId = null;
                };

                $element.bind('$destroy', function () {
                    resetTimeout();
                });

                function calculateTimeUnits() {
                    $scope.seconds = Math.floor(($scope.millis / 1000) % 60);
                    $scope.minutes = Math.floor((($scope.millis / (60000)) % 60));
                    $scope.hours = Math.floor((($scope.millis / (3600000)) % 24));
                    $scope.days = Math.floor((($scope.millis / (3600000)) / 24));
                }

                //determine initial values of time units
                if ($scope.countdownattr) {
                    $scope.millis = $scope.countdownattr * 1000
                } else {
                    $scope.millis = 0
                }
                calculateTimeUnits();

                var tick = function () {

                    $scope.millis = new Date() - $scope.startTime;
                    var adjustment = $scope.millis % 1000;

                    if ($scope.countdownattr) {
                        $scope.millis = $scope.countdown * 1000;
                    }

                    calculateTimeUnits();
                    if ($scope.countdown > 0) {
                        $scope.countdown--;
                    }
                    else if ($scope.countdown <= 0) {
                        $scope.stop();
                        return;
                    }

                    //We are not using $timeout for a reason. Please read here - https://github.com/siddii/angular-timer/pull/5
                    $scope.timeoutId = setTimeout(function () {
                        tick();
                        $scope.$apply();
                    }, $scope.interval - adjustment);

                    $scope.$emit('timer-tick', {timeoutId: $scope.timeoutId, millis: $scope.millis});
                };

                if ($scope.autoStart == undefined || $scope.autoStart == true) {
                    $scope.start();
                }
            }
        };
    }]);
<|endoftext|>


<commit_before>// Copyright 2015 Christopher W. Smith (theupstairs@hotmail.com)

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

    // http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

function addListItem () {
	var liOrderNumber = 0;
	var newTaskTitle = document.getElementById("add-task");
	var ul = document.getElementById("task-list");
	var li = document.createElement("li");
	li.appendChild(document.createTextNode(newItem));
	li.setAttribute("id",liOrderNumber);
	liOrderNumber++;
	ul.appendChild(li);
	alert(li.id);
}

function testFunction (e) {
	var key = e.which || e.keycode || e.key;
	if ( key == 13) {
		window.alert("Enter key pressed");
	}
}

function loadTaskFramework() {

	// add the footer and confirm JScript is running
    var feet = document.getElementsByTagName('footer');
    feet[0].innerHTML = "Let's Do This";

    // register an event handler for the new task input element
	var objNewTask = document.getElementById("in-task-name");
	objNewTask.addEventListener('keydown', testFunction, false);
}
onload = loadTaskFramework;
<commit_msg>created addListItem function<commit_after>// Copyright 2015 Christopher W. Smith (theupstairs@hotmail.com)

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

    // http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

function addListItem () {

	var newTaskTitle = document.getElementById("in-task-name").value;
	if (newTaskTitle.trim() != '') {
		var ul = document.getElementById("task-list");
		var li = document.createElement("li");
		li.appendChild(document.createTextNode(newTaskTitle));
//		li.setAttribute("id",liOrderNumber);
		ul.appendChild(li);
	}
}

function keyEventNewTask (e) {

	// add the new task to the list if the enter key is pressed
	var key = e.which || e.keycode || e.key;
	if (key == 13) {
		addListItem();
	}
}

function loadTaskFramework() {

	// add the footer and confirm JScript is running
    var feet = document.getElementsByTagName('footer');
    feet[0].innerHTML = "Let's Do This";

    // register an event handler for the new task input element
	var objNewTask = document.getElementById("in-task-name");
	objNewTask.addEventListener('keydown', keyEventNewTask, false);
}
onload = loadTaskFramework;
<|endoftext|>


<commit_before>// Copyright 2018-2020, University of Colorado Boulder

/**
 * ObjectIO is the root of the IO Type hierarchy.  All IO types extend from ObjectIO.  This type can be subtyped or
 * used directly for types that only need toStateObject/fromStateObject.
 *
 * This type purposefully does not have a `parametricTypes` static member. The presence of this field marks that it is
 * a parametric type. ObjectIO is not.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Andrew Adare (PhET Interactive Simulations)
 * @author Michael Kauzmann (PhET Interactive Simulations)
 */

import validate from '../../../axon/js/validate.js';
import ValidatorDef from '../../../axon/js/ValidatorDef.js';
import tandemNamespace from '../tandemNamespace.js';

/**
 * @param {Object} phetioObject
 * @param {string} phetioID
 * @constructor
 * @abstract
 */
class ObjectIO {

  constructor( phetioObject, phetioID ) {
    assert && assert( phetioObject, 'phetioObject should be truthy' );
    assert && assert( phetioID, 'phetioID should be truthy' );

    // @public (read-only)
    this.phetioObject = phetioObject;

    // @public (read-only)
    this.phetioID = phetioID;

    // Use the validator defined on the constructor to make sure the phetioObject is valid
    validate( phetioObject, this.constructor.validator );
  }

  /**
   * Return the serialized form of the wrapped PhetioObject. Most often this looks like a JSON object that holds the
   * data about the PhetioObject instance.  This can be overridden by subclasses, or types can use ObjectIO type directly
   * to use this implementation.
   * @param {PhetioObject} o
   * @returns {*}
   * @public
   */
  static toStateObject( o ) {
    // assert && assert( o instanceof Object, 'Should be serializing an Object' );
    return o;
  }

  /**
   * Decodes the object from a state, used in PhetioStateEngine.setState.  This can be overridden by subclasses, or types can
   * use ObjectIO type directly to use this implementation. The value returned by this function depends greatly on
   * what type of serialization an IO Type supports. Please read thoroughly and understand
   * https://github.com/phetsims/phet-io/blob/master/doc/phet-io-instrumentation-guide.md#serialization
   * before implementing a `fromStateObject` function.
   * @param {*} o - whatever was returned from the toStateObject method
   * @returns {Object} - depends on if using reference-type or data-type serialization.
   * @public
   */
  static fromStateObject( o ) {
    return o;
  }

  /**
   * Map the state (obtained by fromStateObject) to arguments that are passed to the `create` function in PhetioGroup.js.
   * Note that other non-serialized args (not dealt with here) may be supplied as closure variables. This function
   * only needs to be implemented on IO Types that are phetioDynamicElement: true, such as PhetioGroup or PhetioCapsule
   * members.
   * @param {Object} state - from a `fromStateObject` method
   * @returns {Array.<*>} - the array of arguments to be passed to the `create` function in the PhetioGroup element type schema.
   * @public
   */
  static stateToArgsForConstructor( state ) {
    return [];
  }

  /**
   * Applies the deserialized value to the object.  This is only called when setting the entire state of the simulation,
   * and hence also sets the initial values, so resets will return to the customized value instead of the simulation
   * default (uncustomized) value.
   * @param {PhetioObject} o
   * @param {Object} value - result from fromStateObject
   */
  static setValue( o, value ) {
  }

  /**
   * Get the supertype of the passed in IO type.
   * @example
   * ObjectIO.getSupertype( SliderIO )
   * --> NodeIO
   * ObjectIO.getSupertype( ObjectIO )
   * --> null
   *
   * @param {function(new:ObjectIO)} typeIO
   * @returns {function(new:ObjectIO)|null} - null if `typeIO` is ObjectIO, because that is the root of the IO hierarchy
   * @public
   */
  static getSupertype( typeIO ) {
    assert && assert( ObjectIO.isIOType( typeIO ), 'IO type expected' );

    // getPrototypeOf get's the typeIO's parent type, because the prototype is for the parent.
    const supertype = Object.getPrototypeOf( typeIO );
    return supertype === Object.getPrototypeOf( window.Object ) ? null : supertype;
  }

  /**
   * Make sure the ObjectIO subtype has all the required attributes.
   * @param {function(new:ObjectIO)} subtype - class to check
   * @public
   */
  static validateSubtype( subtype ) {

    const typeName = subtype.typeName;
    assert && assert( typeName.indexOf( '.' ) === -1, 'Dots should not appear in type names' );

    // Validate that parametric types look as expected
    if ( typeName.indexOf( '<' ) >= 0 ) {
      assert && assert( Array.isArray( subtype.parameterTypes ), 'angle bracket notation is only used for parametric IO Types that have parameter IO Types' );
      subtype.parameterTypes.forEach( parameterType => assert && assert( ObjectIO.isIOType( parameterType ), `parameter type should be an IO Type: ${parameterType}` ) );
    }

    const splitOnParameters = typeName.split( /[<(]/ )[ 0 ];
    assert && assert( splitOnParameters.indexOf( 'IO' ) === splitOnParameters.length - 'IO'.length, 'type name must end with IO' );

    assert && assert( !subtype.prototype.toStateObject, 'toStateObject should be a static method, not prototype one.' );
    assert && assert( !subtype.prototype.fromStateObject, 'fromStateObject should be a static method, not prototype one.' );
    assert && assert( !subtype.prototype.setValue, 'setValue should be a static method, not prototype one.' );
    assert && assert( !subtype.prototype.stateToArgsForConstructor, 'stateToArgsForConstructor should be a static method, not prototype one.' );

    // Prevent inheritance of methods, see https://github.com/phetsims/phet-io/issues/1623
    if ( !subtype.hasOwnProperty( 'methods' ) ) {
      subtype.methods = {};
    }

    // assert that each public method adheres to the expected schema
    for ( const method in subtype.methods ) {
      const methodObject = subtype.methods[ method ];
      if ( typeof methodObject === 'object' ) {
        assert && assert( ObjectIO.isIOType( methodObject.returnType ), 'return type must be of type IO: ' + methodObject.returnType );

        assert && assert( Array.isArray( methodObject.parameterTypes ),
          'parameter types must be an array: ' + methodObject.parameterTypes );

        methodObject.parameterTypes.forEach( parameterType => {
          assert && assert( ObjectIO.isIOType( parameterType ), 'parameter type must be of type IO: ' + parameterType );
        } );

        assert && assert( typeof methodObject.implementation === 'function',
          'implementation must be of type function: ' + methodObject.implementation );

        assert && assert( typeof methodObject.documentation === 'string',
          'documentation must be of type string: ' + methodObject.documentation );

        assert && methodObject.invocableForReadOnlyElements && assert( typeof methodObject.invocableForReadOnlyElements === 'boolean',
          'invocableForReadOnlyElements must be of type boolean: ' + methodObject.invocableForReadOnlyElements );
      }
    }

    assert && assert( subtype.validator, 'validator must be provided' );
    assert && assert( subtype.documentation, 'documentation must be provided' );
    assert && ValidatorDef.validateValidator( subtype.validator );

    subtype.hasOwnProperty( 'methodOrder' ) && subtype.methodOrder.forEach( function( methodName ) {
      assert && assert( subtype.methods[ methodName ], 'methodName not in public methods: ' + methodName );
    } );

    // TODO make this check recursive, see https://github.com/phetsims/phet-io/issues/1371
    // const supertype = ObjectIO.getSupertype( subtype );
    // const superEvents = [];
    // const getEvents = type => {
    //   if ( type.events ) {
    //     type.events.forEach( e => superEvents.push( e ) );
    //   }
    //   ObjectIO.getSupertype( type ) && getEvents( ObjectIO.getSupertype( type ) );
    // };
    // getEvents( supertype );
    //
    // assert && subtype.events && subtype.events.forEach( function( event ) {
    //   assert( superEvents.indexOf( event ) < 0, 'subtype should not declare event that parent also has.' );
    // } );
  }
}

/**
 * Checks if type is an IO type
 * @param {*} type
 * @public
 * @returns {boolean} - true if inherits from ObjectIO or is ObjectIO
 */
ObjectIO.isIOType = type => type === ObjectIO || type.prototype instanceof ObjectIO;

/**
 * @typeDef {Object} MethodObject
 * @property {string} documentation
 * @property {function()} implementation - the function to execute when this method is called
 * @property {function(new:ObjectIO)} returnType - the return IO type of the method
 * @property {Array.<function(new:ObjectIO)>} parameterTypes - the parameter IO types for the method
 * @property {boolean} [invocableForReadOnlyElements=true] - by default, all methods are invocable for all elements.
 *    However, for some read-only elements, certain methods should not be invocable. In that case, they are marked as
 *    invocableForReadOnlyElements: false.
 */

/**
 * The public methods available for this IO Type. Each method is not just a function, but a collection of metadata
 * about the method to be able to serialize parameters and return types and provide better documentation.
 * @type {Object.<string, MethodObject>}
 */
ObjectIO.methods = {};

/**
 * Documentation that appears in PhET-iO Studio, supports HTML markup.
 * @public
 */
ObjectIO.documentation = 'The root of the wrapper object hierarchy.';

/**
 * The name that this TypeIO will have in the public PhET-iO API. In general, this should only be word characters,
 * ending in "IO". Parameteric types are a special subset of TypeIOs that include their parameters in their typeName.
 * If a TypeIO's parameters are other IO type(s), then they should be included within angle brackets, like
 * "PropertyIO<Boolean>". Some other types use a more custom format for displaying their parameter types, in this case
 * the parameter section of the type name (immediately following "IO") should begin with an open paren, "(". Thus the
 * schema for a typeName could be defined (using regex) as `[A-Z]\w*IO([(<].*){0,1}`. In most cases, parameterized
 * types should also include a `parameterTypes` field on the TypeIO.
 * @type {string}
 */
ObjectIO.typeName = 'ObjectIO';

/**
 * A validator object to be used to validate the core types that IOTypes wrap.
 * @type {ValidatorDef}
 * @public
 * @override
 */
ObjectIO.validator = { valueType: Object };

/**
 * Most of the time, a typeName should be unique even for parametric types such that no two different IO types can
 * have the same typename. For some cases this breaks, like when two different Enumerations have the same keys, but are
 * different instances. If defined, this field will act as the Map key when caching IO types to make sure that IOTypes
 * don't overwrite each other in the cache. See the cache in PropertyIO for details and implementation.
 * @type {*|null}
 * @public
 */
ObjectIO.cacheKey = null;

ObjectIO.validateSubtype( ObjectIO );

tandemNamespace.register( 'ObjectIO', ObjectIO );
export default ObjectIO;<commit_msg>delete IO Type cacheKey field and use parameterType as key in PropertyIO, https://github.com/phetsims/phet-core/issues/79<commit_after>// Copyright 2018-2020, University of Colorado Boulder

/**
 * ObjectIO is the root of the IO Type hierarchy.  All IO types extend from ObjectIO.  This type can be subtyped or
 * used directly for types that only need toStateObject/fromStateObject.
 *
 * This type purposefully does not have a `parametricTypes` static member. The presence of this field marks that it is
 * a parametric type. ObjectIO is not.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Andrew Adare (PhET Interactive Simulations)
 * @author Michael Kauzmann (PhET Interactive Simulations)
 */

import validate from '../../../axon/js/validate.js';
import ValidatorDef from '../../../axon/js/ValidatorDef.js';
import tandemNamespace from '../tandemNamespace.js';

/**
 * @param {Object} phetioObject
 * @param {string} phetioID
 * @constructor
 * @abstract
 */
class ObjectIO {

  constructor( phetioObject, phetioID ) {
    assert && assert( phetioObject, 'phetioObject should be truthy' );
    assert && assert( phetioID, 'phetioID should be truthy' );

    // @public (read-only)
    this.phetioObject = phetioObject;

    // @public (read-only)
    this.phetioID = phetioID;

    // Use the validator defined on the constructor to make sure the phetioObject is valid
    validate( phetioObject, this.constructor.validator );
  }

  /**
   * Return the serialized form of the wrapped PhetioObject. Most often this looks like a JSON object that holds the
   * data about the PhetioObject instance.  This can be overridden by subclasses, or types can use ObjectIO type directly
   * to use this implementation.
   * @param {PhetioObject} o
   * @returns {*}
   * @public
   */
  static toStateObject( o ) {
    // assert && assert( o instanceof Object, 'Should be serializing an Object' );
    return o;
  }

  /**
   * Decodes the object from a state, used in PhetioStateEngine.setState.  This can be overridden by subclasses, or types can
   * use ObjectIO type directly to use this implementation. The value returned by this function depends greatly on
   * what type of serialization an IO Type supports. Please read thoroughly and understand
   * https://github.com/phetsims/phet-io/blob/master/doc/phet-io-instrumentation-guide.md#serialization
   * before implementing a `fromStateObject` function.
   * @param {*} o - whatever was returned from the toStateObject method
   * @returns {Object} - depends on if using reference-type or data-type serialization.
   * @public
   */
  static fromStateObject( o ) {
    return o;
  }

  /**
   * Map the state (obtained by fromStateObject) to arguments that are passed to the `create` function in PhetioGroup.js.
   * Note that other non-serialized args (not dealt with here) may be supplied as closure variables. This function
   * only needs to be implemented on IO Types that are phetioDynamicElement: true, such as PhetioGroup or PhetioCapsule
   * members.
   * @param {Object} state - from a `fromStateObject` method
   * @returns {Array.<*>} - the array of arguments to be passed to the `create` function in the PhetioGroup element type schema.
   * @public
   */
  static stateToArgsForConstructor( state ) {
    return [];
  }

  /**
   * Applies the deserialized value to the object.  This is only called when setting the entire state of the simulation,
   * and hence also sets the initial values, so resets will return to the customized value instead of the simulation
   * default (uncustomized) value.
   * @param {PhetioObject} o
   * @param {Object} value - result from fromStateObject
   */
  static setValue( o, value ) {
  }

  /**
   * Get the supertype of the passed in IO type.
   * @example
   * ObjectIO.getSupertype( SliderIO )
   * --> NodeIO
   * ObjectIO.getSupertype( ObjectIO )
   * --> null
   *
   * @param {function(new:ObjectIO)} typeIO
   * @returns {function(new:ObjectIO)|null} - null if `typeIO` is ObjectIO, because that is the root of the IO hierarchy
   * @public
   */
  static getSupertype( typeIO ) {
    assert && assert( ObjectIO.isIOType( typeIO ), 'IO type expected' );

    // getPrototypeOf get's the typeIO's parent type, because the prototype is for the parent.
    const supertype = Object.getPrototypeOf( typeIO );
    return supertype === Object.getPrototypeOf( window.Object ) ? null : supertype;
  }

  /**
   * Make sure the ObjectIO subtype has all the required attributes.
   * @param {function(new:ObjectIO)} subtype - class to check
   * @public
   */
  static validateSubtype( subtype ) {

    const typeName = subtype.typeName;
    assert && assert( typeName.indexOf( '.' ) === -1, 'Dots should not appear in type names' );

    // Validate that parametric types look as expected
    if ( typeName.indexOf( '<' ) >= 0 ) {
      assert && assert( Array.isArray( subtype.parameterTypes ), 'angle bracket notation is only used for parametric IO Types that have parameter IO Types' );
      subtype.parameterTypes.forEach( parameterType => assert && assert( ObjectIO.isIOType( parameterType ), `parameter type should be an IO Type: ${parameterType}` ) );
    }

    const splitOnParameters = typeName.split( /[<(]/ )[ 0 ];
    assert && assert( splitOnParameters.indexOf( 'IO' ) === splitOnParameters.length - 'IO'.length, 'type name must end with IO' );

    assert && assert( !subtype.prototype.toStateObject, 'toStateObject should be a static method, not prototype one.' );
    assert && assert( !subtype.prototype.fromStateObject, 'fromStateObject should be a static method, not prototype one.' );
    assert && assert( !subtype.prototype.setValue, 'setValue should be a static method, not prototype one.' );
    assert && assert( !subtype.prototype.stateToArgsForConstructor, 'stateToArgsForConstructor should be a static method, not prototype one.' );

    // Prevent inheritance of methods, see https://github.com/phetsims/phet-io/issues/1623
    if ( !subtype.hasOwnProperty( 'methods' ) ) {
      subtype.methods = {};
    }

    // assert that each public method adheres to the expected schema
    for ( const method in subtype.methods ) {
      const methodObject = subtype.methods[ method ];
      if ( typeof methodObject === 'object' ) {
        assert && assert( ObjectIO.isIOType( methodObject.returnType ), 'return type must be of type IO: ' + methodObject.returnType );

        assert && assert( Array.isArray( methodObject.parameterTypes ),
          'parameter types must be an array: ' + methodObject.parameterTypes );

        methodObject.parameterTypes.forEach( parameterType => {
          assert && assert( ObjectIO.isIOType( parameterType ), 'parameter type must be of type IO: ' + parameterType );
        } );

        assert && assert( typeof methodObject.implementation === 'function',
          'implementation must be of type function: ' + methodObject.implementation );

        assert && assert( typeof methodObject.documentation === 'string',
          'documentation must be of type string: ' + methodObject.documentation );

        assert && methodObject.invocableForReadOnlyElements && assert( typeof methodObject.invocableForReadOnlyElements === 'boolean',
          'invocableForReadOnlyElements must be of type boolean: ' + methodObject.invocableForReadOnlyElements );
      }
    }

    assert && assert( subtype.validator, 'validator must be provided' );
    assert && assert( subtype.documentation, 'documentation must be provided' );
    assert && ValidatorDef.validateValidator( subtype.validator );

    subtype.hasOwnProperty( 'methodOrder' ) && subtype.methodOrder.forEach( function( methodName ) {
      assert && assert( subtype.methods[ methodName ], 'methodName not in public methods: ' + methodName );
    } );

    // TODO make this check recursive, see https://github.com/phetsims/phet-io/issues/1371
    // const supertype = ObjectIO.getSupertype( subtype );
    // const superEvents = [];
    // const getEvents = type => {
    //   if ( type.events ) {
    //     type.events.forEach( e => superEvents.push( e ) );
    //   }
    //   ObjectIO.getSupertype( type ) && getEvents( ObjectIO.getSupertype( type ) );
    // };
    // getEvents( supertype );
    //
    // assert && subtype.events && subtype.events.forEach( function( event ) {
    //   assert( superEvents.indexOf( event ) < 0, 'subtype should not declare event that parent also has.' );
    // } );
  }
}

/**
 * Checks if type is an IO type
 * @param {*} type
 * @public
 * @returns {boolean} - true if inherits from ObjectIO or is ObjectIO
 */
ObjectIO.isIOType = type => type === ObjectIO || type.prototype instanceof ObjectIO;

/**
 * @typeDef {Object} MethodObject
 * @property {string} documentation
 * @property {function()} implementation - the function to execute when this method is called
 * @property {function(new:ObjectIO)} returnType - the return IO type of the method
 * @property {Array.<function(new:ObjectIO)>} parameterTypes - the parameter IO types for the method
 * @property {boolean} [invocableForReadOnlyElements=true] - by default, all methods are invocable for all elements.
 *    However, for some read-only elements, certain methods should not be invocable. In that case, they are marked as
 *    invocableForReadOnlyElements: false.
 */

/**
 * The public methods available for this IO Type. Each method is not just a function, but a collection of metadata
 * about the method to be able to serialize parameters and return types and provide better documentation.
 * @type {Object.<string, MethodObject>}
 */
ObjectIO.methods = {};

/**
 * Documentation that appears in PhET-iO Studio, supports HTML markup.
 * @public
 */
ObjectIO.documentation = 'The root of the wrapper object hierarchy.';

/**
 * The name that this TypeIO will have in the public PhET-iO API. In general, this should only be word characters,
 * ending in "IO". Parameteric types are a special subset of TypeIOs that include their parameters in their typeName.
 * If a TypeIO's parameters are other IO type(s), then they should be included within angle brackets, like
 * "PropertyIO<Boolean>". Some other types use a more custom format for displaying their parameter types, in this case
 * the parameter section of the type name (immediately following "IO") should begin with an open paren, "(". Thus the
 * schema for a typeName could be defined (using regex) as `[A-Z]\w*IO([(<].*){0,1}`. In most cases, parameterized
 * types should also include a `parameterTypes` field on the TypeIO.
 * @type {string}
 */
ObjectIO.typeName = 'ObjectIO';

/**
 * A validator object to be used to validate the core types that IOTypes wrap.
 * @type {ValidatorDef}
 * @public
 * @override
 */
ObjectIO.validator = { valueType: Object };

ObjectIO.validateSubtype( ObjectIO );

tandemNamespace.register( 'ObjectIO', ObjectIO );
export default ObjectIO;<|endoftext|>


<commit_before>define(
    ["js/ui/View"], function (View) {

        var findPlaceholders = function (str) {
            var placeholders = [], p;
            var stack = [], c, indexPos = 0;
            for (var i = 0; i < str.length; i++) {
                c = str.charAt(i);

                if (c == "[" && stack.length === 0) {
                    p = {};
                    p["start"] = i;
                    stack.push(i);
                } else if (c == "|") {
                    indexPos = i;
                } else if (c == "]" && stack.length > 0 && indexPos > 0) {
                    p["index"] = parseInt(str.substring(indexPos + 1, i));
                    p["end"] = i;
                    p["text"] = str.substring(p.start + 1, indexPos);
                    placeholders.push(p);
                    stack.pop();
                }
            }

            return placeholders;
        };

        return View.inherit({
            defaults: {
                tagName: "span"
            },
            _getChildrenFromDescriptor: function (descriptor) {
                return [];
            },
            _renderChildren: function () {

            },
            _renderContentChildren: function () {

            },
            _renderString: function (string, oldString) {
                this.$el.innerHTML = "";

                if (string) {
                    var placeholders = findPlaceholders(string);
                    var ph, start = -1;
                    for (var i = 0; i < placeholders.length; i++) {
                        ph = placeholders[i];

                        if (ph.start > start) {
                            this.$el.appendChild(this.$systemManager.$document.createTextNode(string.substring(start + 1, ph.start)));
                        }

                        start = ph.end;
                        if (!this.$viewMap) {
                            this.$viewMap = {};
                        }
                        var key = ph.index + ":" + i;
                        var childView = this.$viewMap[key];
                        if (!childView) {
                            childView = this._createComponentForNode(this.$descriptor.childNodes[ph.index]);
                            if (childView) {
                                childView.$parentScope = this.$parentScope;
                                childView.$rootScope = this.$rootScope;

                                this.$viewMap[key] = childView;
                            }
                        }
                        if (childView) {
                            childView.set("$text", ph.text);
                            childView._initialize("auto", true);
                            if (!childView.isRendered()) {
                                childView.render();
                            }
                            this.$childViews.push(childView);
                            this.$el.appendChild(childView.$el);
                        } else {
                            this.$el.appendChild(this.$systemManager.$document.createTextNode(ph.text));
                        }
                    }
                    if (start < string.length) {
                        this.$el.appendChild(this.$systemManager.$document.createTextNode(string.substr(start + 1)));
                    }

                }
            }
        });
    }
);<commit_msg>fixed removing of childNodes for IE8<commit_after>define(
    ["js/ui/View"], function (View) {

        var findPlaceholders = function (str) {
            var placeholders = [], p;
            var stack = [], c, indexPos = 0;
            for (var i = 0; i < str.length; i++) {
                c = str.charAt(i);

                if (c == "[" && stack.length === 0) {
                    p = {};
                    p["start"] = i;
                    stack.push(i);
                } else if (c == "|") {
                    indexPos = i;
                } else if (c == "]" && stack.length > 0 && indexPos > 0) {
                    p["index"] = parseInt(str.substring(indexPos + 1, i));
                    p["end"] = i;
                    p["text"] = str.substring(p.start + 1, indexPos);
                    placeholders.push(p);
                    stack.pop();
                }
            }

            return placeholders;
        };

        return View.inherit({
            defaults: {
                tagName: "span"
            },
            _getChildrenFromDescriptor: function (descriptor) {
                return [];
            },
            _renderChildren: function () {

            },
            _renderContentChildren: function () {

            },
            _renderString: function (string, oldString) {
                for(var k = 0; k < this.$el.childNodes.length; k++){
                    this.$el.removeChild(this.$el.childNodes[k]);
                }
                if (string) {
                    var placeholders = findPlaceholders(string);
                    var ph, start = -1;
                    for (var i = 0; i < placeholders.length; i++) {
                        ph = placeholders[i];

                        if (ph.start > start) {
                            this.$el.appendChild(this.$systemManager.$document.createTextNode(string.substring(start + 1, ph.start)));
                        }

                        start = ph.end;
                        if (!this.$viewMap) {
                            this.$viewMap = {};
                        }
                        var key = ph.index + ":" + i;
                        var childView = this.$viewMap[key];
                        if (!childView) {
                            childView = this._createComponentForNode(this.$descriptor.childNodes[ph.index]);
                            if (childView) {
                                childView.$parentScope = this.$parentScope;
                                childView.$rootScope = this.$rootScope;
                                this.$viewMap[key] = childView;
                            }
                        }
                        if (childView) {
                            childView.set("$text", ph.text);
                            childView._initialize("auto", true);
                            if (!childView.isRendered()) {
                                childView.render();
                            }
                            this.$childViews.push(childView);
                            this.$el.appendChild(childView.$el);
                        } else {
                            this.$el.appendChild(this.$systemManager.$document.createTextNode(ph.text));
                        }
                    }
                    if (start < string.length) {
                        this.$el.appendChild(this.$systemManager.$document.createTextNode(string.substr(start + 1)));
                    }

                }
            }
        });
    }
);<|endoftext|>


<commit_before>var $ = require('jquery');

function hexToRgb(hex) {
  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : null;
}

function shadeColor2(color, percent) {
  var f=parseInt(color.slice(1),16),t=percent<0?0:255,p=percent<0?percent*-1:percent,R=f>>16,G=f>>8&0x00FF,B=f&0x0000FF;
  return "#"+(0x1000000+(Math.round((t-R)*p)+R)*0x10000+(Math.round((t-G)*p)+G)*0x100+(Math.round((t-B)*p)+B)).toString(16).slice(1);
}

module.exports = function(primaryColor, secondaryColor, backgroundColor, textColor) {
  "use strict";
  var opaque = hexToRgb(backgroundColor);
  var customStyleTag = document.getElementById('customStyle') || document.createElement('style');
  customStyleTag.setAttribute('id', 'customStyle');

  // if text is white the highlight color needs to darken instead of lighten
  if (textColor == 'undefined' || textColor == "#ffffff"){
    customStyleTag.innerHTML = "#ov1 #userPage .txtField:focus, " +
        "#ov1 #userPage .fieldItem:focus, " +
        "#ov1 #userPage .fieldItem-textarea:focus { outline: 1px solid " + shadeColor2("#ffffff", -0.5) + " ;}";
  }else{
    customStyleTag.innerHTML = "#ov1 #userPage .txtField:focus, " +
        "#ov1 #userPage .fieldItem:focus, " +
        "#ov1 #userPage .fieldItem-textarea:focus { outline: 1px solid " + shadeColor2(textColor, 0.5) + " ;}";
  }

  customStyleTag.innerHTML +=
      "#ov1 #userPage .custCol-background { background-color: " + backgroundColor + ";}" +
      "#ov1 #userPage .custCol-primary-light { transition: background-color .3s cubic-bezier(0, 0, 0.0, 1);  background-color: " + shadeColor2(primaryColor, 0.05) + ";}" +
      "#ov1 #userPage .custCol-primary, #ov1 #userPage .chosen-drop, #ov1 #userPage .no-results { transition: background-color .3s cubic-bezier(0, 0, 0.0, 1); background-color: " + primaryColor + ";}" +
      "#ov1 #userPage .btn-tab.active { transition: background-color .3s cubic-bezier(0, 0, 0.0, 1); background-color: " + primaryColor + ";}" +
      "#ov1 #userPage .btn:active { -webkit-box-shadow: inset 0px 0px 6px 0px " + shadeColor2(primaryColor, -0.35) +  ";}" +
      "#ov1 #userPage .btn-tab:active { -webkit-box-shadow: none;}" +
      "#ov1 #userPage .custCol-secondary { transition: background-color .3s cubic-bezier(0, 0, 0.0, 1); background-color: " + secondaryColor + ";}" +
      "#ov1 #userPage .custCol-border { border-color: " + shadeColor2(primaryColor, 0.1) + ";}" +
      "#ov1 #userPage .custCol-border-secondary { border-color: " + secondaryColor + ";}" +
      "#ov1 #userPage .custCol-border-primary { border-color: " + primaryColor + ";}" +
      "#ov1 #userPage .radioLabel:before { border-color: " + textColor + ";}" +
      "#ov1 #userPage .checkboxLabel:before { border-color: " + textColor + "; opacity: .75;}" +
      "#ov1 #userPage .user-page-header-slim { background: " + shadeColor2(primaryColor, -0.15) + ";}" +
      "#ov1 #userPage .mainSearchWrapper .txtField:focus { box-shadow: 0 0 0 2px " + shadeColor2(primaryColor, -0.35) + ";}" +
      "#ov1 #userPage .fieldItem { color: " + textColor + ";}" +
      "#ov1 #userPage input[type='radio'].fieldItem:checked + label:before { background: " + textColor + "; box-shadow: inset 0 0 0 4px " + primaryColor + ";}" +
      "#ov1 #userPage input[type='checkbox'].fieldItem:checked + label:before { background: " + textColor + "; box-shadow: inset 0 0 0 3px " + primaryColor + ";}" +
      "#ov1 #userPage input[type='number'].fieldItem { color: " + textColor + ";}" +
      "#ov1 #userPage input[type='number'].spinButtons::-webkit-inner-spin-button:before { color: " + textColor + ";}" +
      "#ov1 #userPage input[type='number'].spinButtons::-webkit-inner-spin-button:after { color: " + textColor + ";}" +
      "#ov1 #userPage input::-webkit-input-placeholder { color: " + textColor + ";}" +
      "#ov1 #userPage .txtFieldWrapper-bar:before { color: " + textColor + ";}" +
      "#ov1 #userPage .container .txtField { color: " + textColor + ";}" +
      "#ov1 #userPage .custCol-font-secondary { color: " + secondaryColor + ";}" +
      "#ov1 #userPage .custCol-text::-webkit-input-placeholder { color: " + textColor + ";}" +
      "#ov1 #userPage .chosen-choices { background-color: " + shadeColor2(primaryColor, 0.04) + "; border: 0; background-image: none; box-shadow: none; padding: 5px 7px}" +
      "#ov1 #userPage .search-choice { background-color: " + secondaryColor + "; background-image: none; border: none; padding: 10px; color: " + textColor + " ; font-size: 13px; box-shadow: none; border-radius: 3px;}" +
      "#ov1 #userPage .custCol-border-background { border-color: " + backgroundColor + " }" +
      "#ov1 #userPage .chosen-results li { border-bottom: solid 1px " + secondaryColor + "}" +
      "#ov1 #userPage .fieldItem .fieldItem-selectWrapper .chosen-single, #ov1 #userPage .fieldItem .fieldItem-selectWrapper .chosen-drop .chosen-results li { color:" + textColor + " }" +
      "#ov1 #userPage .fieldItem .fieldItem-selectWrapper .chosen-drop .chosen-results li.highlighted { background:" + secondaryColor + " }" +
      "#ov1 #userPage .custCol-primary-darken { background: " + shadeColor2(primaryColor, -0.35) + ";}" +
      "#ov1 #userPage .custCol-text, #ov1 #userPage .search-field input { color: " + textColor + ";}" +
      "#ov1 #userPage .modal-opaque { background-color: rgba(" + opaque.r + ", " + opaque.g + ", " + opaque.b + ", 0.85);}" +
      "#ov1 #userPage .txtField:focus, #ov1 #userPage .fieldItem:focus , #ov1 #userPage .fieldItem-textarea:focus { border: 2px solid " + shadeColor2(primaryColor, 0.15) + ";}" +
      "#ov1 #userPage #obContainer::-webkit-scrollbar-thumb { background: " + shadeColor2(backgroundColor, 0.25) + ";}" +
      "#ov1 #userPage #overlay { background-color: rgba(" + opaque.r + ", " + opaque.g + ", " + opaque.b + ", 0.65);}";

    // colorbox stuffs
    customStyleTag.innerHTML +=
      "#ov1 #userPage #cboxContent { background-color: " + primaryColor + "; color: " + textColor + ";}" +
      "#ov1 #userPage #cboxCurrent { color: " + textColor + ";}" +
      "#ov1 #userPage #cboxClose { background-color: " + secondaryColor + "; color: " + textColor + "}" +
      "#ov1 #userPage #cboxOverlay { background-color: rgba(" + opaque.r + ", " + opaque.g + ", " + opaque.b + ", 1);}";

  document.body.appendChild(customStyleTag);
};<commit_msg>Prevent top search bar text to move a bit on focus<commit_after>var $ = require('jquery');

function hexToRgb(hex) {
  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : null;
}

function shadeColor2(color, percent) {
  var f=parseInt(color.slice(1),16),t=percent<0?0:255,p=percent<0?percent*-1:percent,R=f>>16,G=f>>8&0x00FF,B=f&0x0000FF;
  return "#"+(0x1000000+(Math.round((t-R)*p)+R)*0x10000+(Math.round((t-G)*p)+G)*0x100+(Math.round((t-B)*p)+B)).toString(16).slice(1);
}

module.exports = function(primaryColor, secondaryColor, backgroundColor, textColor) {
  "use strict";
  var opaque = hexToRgb(backgroundColor);
  var customStyleTag = document.getElementById('customStyle') || document.createElement('style');
  customStyleTag.setAttribute('id', 'customStyle');

  // if text is white the highlight color needs to darken instead of lighten
  if (textColor == 'undefined' || textColor == "#ffffff"){
    customStyleTag.innerHTML = "#ov1 #userPage .txtField:focus, " +
        "#ov1 #userPage .fieldItem:focus, " +
        "#ov1 #userPage .fieldItem-textarea:focus { outline: 1px solid " + shadeColor2("#ffffff", -0.5) + " ;}";
  }else{
    customStyleTag.innerHTML = "#ov1 #userPage .txtField:focus, " +
        "#ov1 #userPage .fieldItem:focus, " +
        "#ov1 #userPage .fieldItem-textarea:focus { outline: 1px solid " + shadeColor2(textColor, 0.5) + " ;}";
  }

  customStyleTag.innerHTML +=
      "#ov1 #userPage .custCol-background { background-color: " + backgroundColor + ";}" +
      "#ov1 #userPage .custCol-primary-light { transition: background-color .3s cubic-bezier(0, 0, 0.0, 1);  background-color: " + shadeColor2(primaryColor, 0.05) + ";}" +
      "#ov1 #userPage .custCol-primary, #ov1 #userPage .chosen-drop, #ov1 #userPage .no-results { transition: background-color .3s cubic-bezier(0, 0, 0.0, 1); background-color: " + primaryColor + ";}" +
      "#ov1 #userPage .btn-tab.active { transition: background-color .3s cubic-bezier(0, 0, 0.0, 1); background-color: " + primaryColor + ";}" +
      "#ov1 #userPage .btn:active { -webkit-box-shadow: inset 0px 0px 6px 0px " + shadeColor2(primaryColor, -0.35) +  ";}" +
      "#ov1 #userPage .btn-tab:active { -webkit-box-shadow: none;}" +
      "#ov1 #userPage .custCol-secondary { transition: background-color .3s cubic-bezier(0, 0, 0.0, 1); background-color: " + secondaryColor + ";}" +
      "#ov1 #userPage .custCol-border { border-color: " + shadeColor2(primaryColor, 0.1) + ";}" +
      "#ov1 #userPage .custCol-border-secondary { border-color: " + secondaryColor + ";}" +
      "#ov1 #userPage .custCol-border-primary { border-color: " + primaryColor + ";}" +
      "#ov1 #userPage .radioLabel:before { border-color: " + textColor + ";}" +
      "#ov1 #userPage .checkboxLabel:before { border-color: " + textColor + "; opacity: .75;}" +
      "#ov1 #userPage .user-page-header-slim { background: " + shadeColor2(primaryColor, -0.15) + ";}" +
      "#ov1 #userPage .mainSearchWrapper .txtField:focus { box-shadow: 0 0 0 2px " + shadeColor2(primaryColor, -0.35) + ";}" +
      "#ov1 #userPage .fieldItem { color: " + textColor + ";}" +
      "#ov1 #userPage input[type='radio'].fieldItem:checked + label:before { background: " + textColor + "; box-shadow: inset 0 0 0 4px " + primaryColor + ";}" +
      "#ov1 #userPage input[type='checkbox'].fieldItem:checked + label:before { background: " + textColor + "; box-shadow: inset 0 0 0 3px " + primaryColor + ";}" +
      "#ov1 #userPage input[type='number'].fieldItem { color: " + textColor + ";}" +
      "#ov1 #userPage input[type='number'].spinButtons::-webkit-inner-spin-button:before { color: " + textColor + ";}" +
      "#ov1 #userPage input[type='number'].spinButtons::-webkit-inner-spin-button:after { color: " + textColor + ";}" +
      "#ov1 #userPage input::-webkit-input-placeholder { color: " + textColor + ";}" +
      "#ov1 #userPage .txtFieldWrapper-bar:before { color: " + textColor + ";}" +
      "#ov1 #userPage .container .txtField { color: " + textColor + ";}" +
      "#ov1 #userPage .custCol-font-secondary { color: " + secondaryColor + ";}" +
      "#ov1 #userPage .custCol-text::-webkit-input-placeholder { color: " + textColor + ";}" +
      "#ov1 #userPage .chosen-choices { background-color: " + shadeColor2(primaryColor, 0.04) + "; border: 0; background-image: none; box-shadow: none; padding: 5px 7px}" +
      "#ov1 #userPage .search-choice { background-color: " + secondaryColor + "; background-image: none; border: none; padding: 10px; color: " + textColor + " ; font-size: 13px; box-shadow: none; border-radius: 3px;}" +
      "#ov1 #userPage .custCol-border-background { border-color: " + backgroundColor + " }" +
      "#ov1 #userPage .chosen-results li { border-bottom: solid 1px " + secondaryColor + "}" +
      "#ov1 #userPage .fieldItem .fieldItem-selectWrapper .chosen-single, #ov1 #userPage .fieldItem .fieldItem-selectWrapper .chosen-drop .chosen-results li { color:" + textColor + " }" +
      "#ov1 #userPage .fieldItem .fieldItem-selectWrapper .chosen-drop .chosen-results li.highlighted { background:" + secondaryColor + " }" +
      "#ov1 #userPage .custCol-primary-darken { background: " + shadeColor2(primaryColor, -0.35) + ";}" +
      "#ov1 #userPage .custCol-text, #ov1 #userPage .search-field input { color: " + textColor + ";}" +
      "#ov1 #userPage .modal-opaque { background-color: rgba(" + opaque.r + ", " + opaque.g + ", " + opaque.b + ", 0.85);}" +
      "#ov1 #userPage .fieldItem:focus , #ov1 #userPage .fieldItem-textarea:focus { border: 2px solid " + shadeColor2(primaryColor, 0.15) + ";}" +
      "#ov1 #userPage #obContainer::-webkit-scrollbar-thumb { background: " + shadeColor2(backgroundColor, 0.25) + ";}" +
      "#ov1 #userPage #overlay { background-color: rgba(" + opaque.r + ", " + opaque.g + ", " + opaque.b + ", 0.65);}";

    // colorbox stuffs
    customStyleTag.innerHTML +=
      "#ov1 #userPage #cboxContent { background-color: " + primaryColor + "; color: " + textColor + ";}" +
      "#ov1 #userPage #cboxCurrent { color: " + textColor + ";}" +
      "#ov1 #userPage #cboxClose { background-color: " + secondaryColor + "; color: " + textColor + "}" +
      "#ov1 #userPage #cboxOverlay { background-color: rgba(" + opaque.r + ", " + opaque.g + ", " + opaque.b + ", 1);}";

  document.body.appendChild(customStyleTag);
};
<|endoftext|>


<commit_before>(function(angular) {
  var app = angular.module('ForumApp');
  app.config(['$stateProvider', '$urlRouterProvider','$mdThemingProvider', stateParams])

  function stateParams($stateProvider, $urlRouterProvider,$mdThemingProvider) {

$mdThemingProvider.theme("default")
                  .primaryPalette("blue")

    $urlRouterProvider.otherwise('404')

    $stateProvider.state('home', {
      url: '',
<<<<<<< HEAD:app/app.config.js
      templateUrl: 'app/components/home/home.html',
=======
      templateUrl: 'views/home.html',
>>>>>>> f0ad963ad1cdaef62f8fc70355d5af7e736899f7:config/mainConfig.js
      controller: 'homeCtrl',
    })
    $stateProvider.state('auth', {
      url: '/auth',
      templateUrl: 'app/components/auth/auth.html',
      controller: 'authCtrl',
    })

    $stateProvider.state('authHome', {
      url: '/authHome',
      templateUrl: 'app/components/authHome/authHome.html',
      controller: 'authHome',
      resolve: {
        // controller will not be loaded until $waitForAuth resolves
        // Auth refers to our $firebaseAuth wrapper in the example above
      }
    })

    $stateProvider.state('authHome.desc', {
      url: '/desc',
      templateUrl: 'app/components/authDesc/authDesc.html',
      controller: 'authDescCtrl',
      resolve: {
        // controller will not be loaded until $waitForAuth resolves
        // Auth refers to our $firebaseAuth wrapper in the example above
        "currentAuth": ["refService", function(refService) {
        }]
      }
    })

    $stateProvider.state('authHome.topic', {
      url: '/topic/:POST/:USERNAME',
<<<<<<< HEAD:app/app.config.js
      templateUrl: 'app/components/topic/topicDesc.html',
=======
      templateUrl: 'views/topicDesc.html',
>>>>>>> f0ad963ad1cdaef62f8fc70355d5af7e736899f7:config/mainConfig.js
      controller: 'topicCtrl',
      resolve: {
        // controller will not be loaded until $waitForAuth resolves
        // Auth refers to our $firebaseAuth wrapper in the example above
      }
    })
    $stateProvider.state('authHome.profile', {
      url: '/profile/:UID',
<<<<<<< HEAD:app/app.config.js
      templateUrl: 'app/components/profile/profile.html',
=======
      templateUrl: 'views/profile.html',
>>>>>>> f0ad963ad1cdaef62f8fc70355d5af7e736899f7:config/mainConfig.js
      controller: 'profileCtrl',
      resolve: {
        // controller will not be loaded until $waitForAuth resolves
        // Auth refers to our $firebaseAuth wrapper in the example above
      }
    })

  $stateProvider.state('authHome.settings', {
      url: '/settings?UID?USERNAME',
      templateUrl: 'app/components/settings/settings.html',
      controller: 'settingsCtrl',
      resolve: {
        // controller will not be loaded until $waitForAuth resolves
        // Auth refers to our $firebaseAuth wrapper in the example above
      }
    })

     $stateProvider.state('authHome.otherUser', {
      url: '/otherUser?DATE?UID',
      templateUrl: 'app/components/otherUserProfile/otherUserProfile.html',
      controller: 'otherUserProfileCtrl',
      resolve: {
        // controller will not be loaded until $waitForAuth resolves
        // Auth refers to our $firebaseAuth wrapper in the example above
      }
    })

    $stateProvider.state('ErrorFourOFour', {
      url: '/404',
<<<<<<< HEAD:app/app.config.js
      templateUrl: 'app/components/404/404.html',
=======
      templateUrl: 'views/404.html',
>>>>>>> f0ad963ad1cdaef62f8fc70355d5af7e736899f7:config/mainConfig.js
      controller: '404Controller',
      resolve: {
        // controller will not be loaded until $waitForAuth resolves
        // Auth refers to our $firebaseAuth wrapper in the example above
      }
    })
<<<<<<< HEAD:app/app.config.js
    $stateProvider.state('loading', {
      url:'/loading',
      templateUrl:'app/components/loading/loading.html',
      controller: 'loadingCtrl',
       resolve: {
        // controller will not be loaded until $waitForAuth resolves
        // Auth refers to our $firebaseAuth wrapper in the example above
      }
    })

     $stateProvider.state('authHome.otherUserPage', {
      url: '/:USERNAME/Activity',
      templateUrl: 'app/components/otherUserProfilePage/otherUserProfilePage.html',
=======

     $stateProvider.state('authHome.otherUserPage', {
      url: '/:USERNAME/Activity',
      templateUrl: 'views/otherUserProfilePage.html',
>>>>>>> f0ad963ad1cdaef62f8fc70355d5af7e736899f7:config/mainConfig.js
      controller: 'otherUserProfilePageCtrl',
      resolve: {
        // controller will not be loaded until $waitForAuth resolves
        // Auth refers to our $firebaseAuth wrapper in the example above
      }
    })

  }
})(angular);<commit_msg>Update<commit_after>(function(angular) {
  var app = angular.module('ForumApp');
  app.config(['$stateProvider', '$urlRouterProvider','$mdThemingProvider', stateParams])

  function stateParams($stateProvider, $urlRouterProvider,$mdThemingProvider) {

$mdThemingProvider.theme("default")
                  .primaryPalette("blue")

    $urlRouterProvider.otherwise('404')

    $stateProvider.state('home', {
      url: '',
      templateUrl: 'app/components/home/home.html',
      controller: 'homeCtrl',
    })
    $stateProvider.state('auth', {
      url: '/auth',
      templateUrl: 'app/components/auth/auth.html',
      controller: 'authCtrl',
    })

    $stateProvider.state('authHome', {
      url: '/authHome',
      templateUrl: 'app/components/authHome/authHome.html',
      controller: 'authHome',
      resolve: {
        // controller will not be loaded until $waitForAuth resolves
        // Auth refers to our $firebaseAuth wrapper in the example above
      }
    })

    $stateProvider.state('authHome.desc', {
      url: '/desc',
      templateUrl: 'app/components/authDesc/authDesc.html',
      controller: 'authDescCtrl',
      resolve: {
        // controller will not be loaded until $waitForAuth resolves
        // Auth refers to our $firebaseAuth wrapper in the example above
        "currentAuth": ["refService", function(refService) {
        }]
      }
    })

    $stateProvider.state('authHome.topic', {
      url: '/topic/:POST/:USERNAME',
      templateUrl: 'app/components/topic/topicDesc.html',
      controller: 'topicCtrl',
      resolve: {
        // controller will not be loaded until $waitForAuth resolves
        // Auth refers to our $firebaseAuth wrapper in the example above
      }
    })
    $stateProvider.state('authHome.profile', {
      url: '/profile/:UID',
      templateUrl: 'app/components/profile/profile.html',
      controller: 'profileCtrl',
      resolve: {
        // controller will not be loaded until $waitForAuth resolves
        // Auth refers to our $firebaseAuth wrapper in the example above
      }
    })

  $stateProvider.state('authHome.settings', {
      url: '/settings?UID?USERNAME',
      templateUrl: 'app/components/settings/settings.html',
      controller: 'settingsCtrl',
      resolve: {
        // controller will not be loaded until $waitForAuth resolves
        // Auth refers to our $firebaseAuth wrapper in the example above
      }
    })

     $stateProvider.state('authHome.otherUser', {
      url: '/otherUser?DATE?UID',
      templateUrl: 'app/components/otherUserProfile/otherUserProfile.html',
      controller: 'otherUserProfileCtrl',
      resolve: {
        // controller will not be loaded until $waitForAuth resolves
        // Auth refers to our $firebaseAuth wrapper in the example above
      }
    })

    $stateProvider.state('ErrorFourOFour', {
      url: '/404',
      templateUrl: 'app/components/404/404.html',
      controller: '404Controller',
      resolve: {
        // controller will not be loaded until $waitForAuth resolves
        // Auth refers to our $firebaseAuth wrapper in the example above
      }
    })
    $stateProvider.state('loading', {
      url:'/loading',
      templateUrl:'app/components/loading/loading.html',
      controller: 'loadingCtrl',
       resolve: {
        // controller will not be loaded until $waitForAuth resolves
        // Auth refers to our $firebaseAuth wrapper in the example above
      }
    })

     $stateProvider.state('authHome.otherUserPage', {
      url: '/:USERNAME/Activity',
      templateUrl: 'app/components/otherUserProfilePage/otherUserProfilePage.html',
      controller: 'otherUserProfilePageCtrl',
      resolve: {
        // controller will not be loaded until $waitForAuth resolves
        // Auth refers to our $firebaseAuth wrapper in the example above
      }
    })

  }
})(angular);<|endoftext|>