<commit_before>function subscribeInnerChanges(target, observableGetter, innerSubscriber) {
  target.subscribe(function(changes) {
    changes.forEach(function(change) {
      if (change.status === 'added') {
        // Subscriber for sorting.
        observableGetter(change.value).subscribe(function(newValue) {
          innerSubscriber(newValue);
        })
      }
    });
  }, null, 'arrayChange');
}

ko.bindingHandlers['codeMirror'] = {
  init: function(element, valueAccessor, allBindings) {
    var value = valueAccessor();
    var mainCode = CodeMirror.fromTextArea(
      element,
      {
        mode: "markdown",
        lineNumbers: true
      }
    );
    mainCode.on('change', function (cm) {
      value(cm.getValue());
    });

    value.mainCode = mainCode;

    ko.bindingHandlers['value'].init(element, valueAccessor, allBindings);
  },
  update: function(element, valueAccessor, allBindings){
    var value = valueAccessor();
    if (value() != value.mainCode.getValue()) {
      value.mainCode.setValue(value());
    }
    ko.bindingHandlers['value'].update(element, valueAccessor, allBindings)
  }
};

ko.extenders['timestamp'] = function(target, option) {
  target.created = ko.observable(new Date());
  target.updated = ko.observable(new Date());

  target.subscribe(function() {
    target.updated(new Date());
  });
  return target
};

ko.extenders['sortedBy'] = function(target, option) {
  var observableGetter, order;

  if (option.observableGetter) {
    observableGetter = option.observableGetter;
  } else {
    observableGetter = function(value) { return value };
  }
  if (option.order) {
    order = option.order;
  } else {
    order = 'asc'
  }

  target._isSorting = false;  // Not to call recursive.

  // Subscribe added elements to apply subscriber for sorting.
  subscribeInnerChanges(target, observableGetter, function() {
    if (!target._isSorting) {  // Not to call recursive.

      // Get the current array value and try to sort.
      var originalArray = target();
      var sorted = originalArray.concat().sort(function(left, right) {
        if (observableGetter(left)() == observableGetter(right)){
          return 0
        }
        if (order === 'asc') {
          return observableGetter(left)() < observableGetter(right)() ? -1 : 1
        } else {
          return observableGetter(left)() > observableGetter(right)() ? -1 : 1
        }
      });

      // If the sorted value is as same as original, won't change the observable.
      var shouldBeSorted = false;
      sorted.forEach(function(sortedElement, idx) {
        if (sortedElement !== originalArray[idx]) {
          shouldBeSorted = true;
        }
      });
      if (shouldBeSorted) {
        target._isSorting = true;
        target(sorted);
        target._isSorting = false;
      }
    }
  });
  return target
};

ko.extenders['arrayLocalStorage'] = function(target, option) {
  var key = option.key || '';
  var innerClass = option.innerClass || undefined;
  var observableGetter = option.observableGetter || function(e) {return e};

  function applyValue(jsonValue) {
    var parsed = JSON.parse(jsonValue);
    return parsed.map(function(data) {
      if (innerClass) {
        return new innerClass(data)
      } else {
        return data
      }
    });
  }
  var initialValue = target();

  // Load existing value from localStorage if set
  if (key && localStorage.getItem(key) !== null) {
    try {
      initialValue = applyValue(localStorage.getItem(key));
    } catch (e) {
    }
  }
  // Subscribe to new values and add them to localStorage
  subscribeInnerChanges(target, observableGetter, function () {
    localStorage.setItem(key, ko.toJSON(target()));
  });

  target(initialValue);

  return target;
};

var Memo = function(data) {
  var self = this;

  self.text = ko.observable(data.text || "").extend({timestamp: ""});
  self.title = ko.pureComputed(function() {
    // FIXME: Take title from CodeMirror.title
    var title = self.text().split('\n')[0];
    if (!title.trim()) {
      return '(no title)'
    }
    return title
  });
};

var OtterViewModel = function() {
  var self = this;
  self.memos = ko.observableArray([new Memo({})]).
    extend({sortedBy: {observableGetter: function(memo) {return memo.text.updated},
                       order: 'desc'},
            arrayLocalStorage: {observableGetter: function(memo) {return memo.text},
                                key: "otterMemo-Array",
                                innerClass: Memo}});
  self.numMemos = ko.pureComputed(function() {
    return self.memos().length
  });
  // Use observable directly instead of computed,
  // not to flush the memo pad when the memos automatically sorted.
  // Actually this can be implemented by ko.computed with self.memos and self.chosenMemoIdx.
  self.chosenMemo = ko.observable();
  self.isShownDeleteConfirm = ko.observable(false);

  self.chooseMemo = function(memo) {
    self.chosenMemo(memo);
    return true
  };
  self.addMemo = function() {
    var memo = new Memo({});
    self.memos.unshift(memo);
    self.chosenMemo(memo);
    return true
  };
  self.deleteMemo = function() {
    //     +-- idx
    //     |
    // [a, b, c, d]
    //        |
    //        +-----last_idx
    var idx = self.memos.indexOf(self.chosenMemo());
    var last_idx = self.numMemos() - 2;

    self.memos.remove(self.chosenMemo());

    if (idx > last_idx) {
      self.chosenMemo(self.memos()[last_idx]);
    } else {
      self.chosenMemo(self.memos()[idx])
    }
    if (self.numMemos() == 0) {
      self.memos.removeAll();
      self.memos([new Memo({})]);
      self.chosenMemo(self.memos()[0]);
    }
    self.isShownDeleteConfirm(false);
  };

  self.showDeleteConfirm = function() {
    self.isShownDeleteConfirm(true);
  };
  self.hideDeleteConfirm = function() {
    self.isShownDeleteConfirm(false);
  };

  self.chosenMemo(self.memos()[0])
};

window.addEventListener("load", function() {
  ko.applyBindings(new OtterViewModel());
});
<commit_msg>Made it store changes even when memo added and deleted<commit_after>function subscribeInnerChanges(target, observableGetter, innerSubscriber) {
  target.subscribe(function(changes) {
    changes.forEach(function(change) {
      if (change.status === 'added') {
        // Subscriber for sorting.
        observableGetter(change.value).subscribe(function(newValue) {
          innerSubscriber(newValue);
        })
      }
    });
  }, null, 'arrayChange');
}

ko.bindingHandlers['codeMirror'] = {
  init: function(element, valueAccessor, allBindings) {
    var value = valueAccessor();
    var mainCode = CodeMirror.fromTextArea(
      element,
      {
        mode: "markdown",
        lineNumbers: true
      }
    );
    mainCode.on('change', function (cm) {
      value(cm.getValue());
    });

    value.mainCode = mainCode;

    ko.bindingHandlers['value'].init(element, valueAccessor, allBindings);
  },
  update: function(element, valueAccessor, allBindings){
    var value = valueAccessor();
    if (value() != value.mainCode.getValue()) {
      value.mainCode.setValue(value());
    }
    ko.bindingHandlers['value'].update(element, valueAccessor, allBindings)
  }
};

ko.extenders['timestamp'] = function(target, option) {
  target.created = ko.observable(new Date());
  target.updated = ko.observable(new Date());

  target.subscribe(function() {
    target.updated(new Date());
  });
  return target
};

ko.extenders['sortedBy'] = function(target, option) {
  var observableGetter, order;

  if (option.observableGetter) {
    observableGetter = option.observableGetter;
  } else {
    observableGetter = function(value) { return value };
  }
  if (option.order) {
    order = option.order;
  } else {
    order = 'asc'
  }

  target._isSorting = false;  // Not to call recursive.

  // Subscribe added elements to apply subscriber for sorting.
  subscribeInnerChanges(target, observableGetter, function() {
    if (!target._isSorting) {  // Not to call recursive.

      // Get the current array value and try to sort.
      var originalArray = target();
      var sorted = originalArray.concat().sort(function(left, right) {
        if (observableGetter(left)() == observableGetter(right)){
          return 0
        }
        if (order === 'asc') {
          return observableGetter(left)() < observableGetter(right)() ? -1 : 1
        } else {
          return observableGetter(left)() > observableGetter(right)() ? -1 : 1
        }
      });

      // If the sorted value is as same as original, won't change the observable.
      var shouldBeSorted = false;
      sorted.forEach(function(sortedElement, idx) {
        if (sortedElement !== originalArray[idx]) {
          shouldBeSorted = true;
        }
      });
      if (shouldBeSorted) {
        target._isSorting = true;
        target(sorted);
        target._isSorting = false;
      }
    }
  });
  return target
};

ko.extenders['arrayLocalStorage'] = function(target, option) {
  var key = option.key || '';
  var innerClass = option.innerClass || undefined;
  var observableGetter = option.observableGetter || function(e) {return e};

  function parseJsonWithClass(jsonValue) {
    var parsed = JSON.parse(jsonValue);
    return parsed.map(function(data) {
      if (innerClass) {
        return new innerClass(data)
      } else {
        return data
      }
    });
  }
  function saveArray() {
    localStorage.setItem(key, ko.toJSON(target()));
  }
  var initialValue = target();

  // Load existing value from localStorage if set
  if (key && localStorage.getItem(key) !== null) {
    try {
      initialValue = parseJsonWithClass(localStorage.getItem(key));
    } catch (e) {
    }
  }
  // Subscribe to new values and add them to localStorage
  target.subscribe(saveArray);
  subscribeInnerChanges(target, observableGetter, saveArray);

  target(initialValue);

  return target;
};

var Memo = function(data) {
  var self = this;

  self.text = ko.observable(data.text || "").extend({timestamp: ""});
  self.title = ko.pureComputed(function() {
    // FIXME: Take title from CodeMirror.title
    var title = self.text().split('\n')[0];
    if (!title.trim()) {
      return '(no title)'
    }
    return title
  });
};

var OtterViewModel = function() {
  var self = this;
  self.memos = ko.observableArray([new Memo({})]).
    extend({sortedBy: {observableGetter: function(memo) {return memo.text.updated},
                       order: 'desc'},
            arrayLocalStorage: {observableGetter: function(memo) {return memo.text},
                                key: "otterMemo-Array",
                                innerClass: Memo}});
  self.numMemos = ko.pureComputed(function() {
    return self.memos().length
  });
  // Use observable directly instead of computed,
  // not to flush the memo pad when the memos automatically sorted.
  // Actually this can be implemented by ko.computed with self.memos and self.chosenMemoIdx.
  self.chosenMemo = ko.observable();
  self.isShownDeleteConfirm = ko.observable(false);

  self.chooseMemo = function(memo) {
    self.chosenMemo(memo);
    return true
  };
  self.addMemo = function() {
    var memo = new Memo({});
    self.memos.unshift(memo);
    self.chosenMemo(memo);
    return true
  };
  self.deleteMemo = function() {
    //     +-- idx
    //     |
    // [a, b, c, d]
    //        |
    //        +-----last_idx
    var idx = self.memos.indexOf(self.chosenMemo());
    var last_idx = self.numMemos() - 2;

    self.memos.remove(self.chosenMemo());

    if (idx > last_idx) {
      self.chosenMemo(self.memos()[last_idx]);
    } else {
      self.chosenMemo(self.memos()[idx])
    }
    if (self.numMemos() == 0) {
      self.memos.removeAll();
      self.memos([new Memo({})]);
      self.chosenMemo(self.memos()[0]);
    }
    self.isShownDeleteConfirm(false);
  };

  self.showDeleteConfirm = function() {
    self.isShownDeleteConfirm(true);
  };
  self.hideDeleteConfirm = function() {
    self.isShownDeleteConfirm(false);
  };

  self.chosenMemo(self.memos()[0])
};

window.addEventListener("load", function() {
  ko.applyBindings(new OtterViewModel());
});
<|endoftext|>


<commit_before>function initUserInfo() {
    if (localStorage.userInfo) {
        userInfo = JSON.parse(localStorage.userInfo);
    } else {
        userInfo = {
          evalComplete: false,
          userName: '',
          lastLevelIndex: 10,
          lastImageIndex: 0,
          panicImageIndex: 0,
          previousVisitLevels: [],
          previousVisitAnxiety: []
        }
    }
}

function processProgressForm() {
    var anxietyIndex = 0;
    for (var cc=1; cc<=5; cc++) {
        var qName = 'nq' + cc;
        var inputEls = document.getElementsByClassName(qName);
        for (var dd=0; dd<inputEls.length; dd++) {
            if (inputEls[dd].checked) {
                anxietyIndex += parseInt(inputEls[dd].value);
            }
        }
    }
    userInfo.previousVisitAnxiety.push(anxietyIndex);
    updateUserInfo();
}

function displayImage(level,index) {
    var imageEl = gebi('mainImage');
    var videoEl = gebi('video');
    var imgWrap = gebi('imgWrap');
    var imagePath = imageArray[level][index].path;
    if (level < 10) {
        imageEl.setAttribute('src',imagePath);
        imageEl.style.display="block";
        videoEl.style.display='none';
        imgWrap.style.backgroundColor="white";
    }  else {
        videoEl.setAttribute('src',imagePath);
        imageEl.style.display='none';
        videoEl.style.display='block';
        imgWrap.style.backgroundColor="black";
    }
}

function storeUserInfo() {
    localStorage.userInfo = JSON.stringify(userInfo);
}

//capitalize userName in case user didn't
function capitalizeName(name) {
    return name.charAt(0).toUpperCase() + name.slice(1);
}

function gebi(el) { // gleefully stolen from Al!
    return document.getElementById(el);
}

function showCharts() {
    hideEl(formPopup);
    showEl(chartContainer);
    createLevelChart (generateChartData(userInfo.previousVisitLevels));
    createPhobiaChart (generateChartData(userInfo.previousVisitAnxiety));
}

function processQuestionnaire() {
    var anxietyIndex = 0;
    for (var cc=1; cc<=5; cc++) {
        var qName = 'q' + cc;
        var inputEls = document.getElementsByClassName(qName);
        for (var dd=0; dd<inputEls.length; dd++) {
            if (inputEls[dd].checked) {
                anxietyIndex += parseInt(inputEls[dd].value);
            }
        }
    }
    userInfo.previousVisitAnxiety.push(anxietyIndex);
    storeUserInfo();
    showCharts();
}

function generateChartData(data) {
    var chartData = {};
    dataLength = data.length;
    var labels = [];
    var templabels = [];
    var tempdata = [];
    chartData.barColor = '#b2f9ed';
    chartData.dataPoints = [];

    templabels.push('Starting Point');
    for (var aa=1; aa <= dataLength; aa++) {
        templabels.push('Visit ' + aa);
    }
    if (dataLength >10) {
        labels[0] = templabels[0];
        labels = labels.concat(templabels.slice(-10));
        tempdata[0] = data[0];
        tempdata = tempdata.concat(data.slice(-10));    // Grab last 10 elements of the array.
    } else {
        tempdata = data;
        labels = templabels;
    }
    for (var i=0;i < Math.min(labels.length, tempdata.length) ;i++) {
        chartData.dataPoints.push([labels[i],tempdata[i]]);
    }

    return chartData;
}

function createLevelChart(data) {   // uses highcharts to display data, function taken from snippet on highcharts' website and modded.
    $('#levelChart').highcharts({
        chart: {
            Type: 'column',
            backgroundColor: '#E0CCD3'
        },
        title: {
            text: 'Highest Level Reached By Visit'
        },
        subtitle: {
            text: '(showing the last 10 visits)'
        },
        xAxis: {
            type: 'category',
            labels: {
                rotation: -45,
                style: {
                    fontSize: '13px',
                    fontFamily: 'Verdana, sans-serif'
                }

            },
            crosshair: true
        },
        yAxis: { // Primary yAxis
                labels: {
                    format: '{value}'
                    // style: {
                    //     fontSize: '13px',
                    //     color: Highcharts.getOptions().colors[1]
                    // }
                },
                title: {
                    text: 'Highest Level Reached',
                    style: {
                        color: '#E0CCD3'
                    }
                }
            },

        tooltip: {
            shared: true
        },
        legend: {
            enabled: false
        },
        series: [{
            name: 'Highest Level Reached',
            data: data.dataPoints,
            type: 'column',
            color: data.barColor,
            tooltip: {
                valueSuffix: ''
            },
            dataLabels: {
                enabled: true,
                rotation: -90,
                color: '#FFFFFF',
                align: 'right',
                format: '{point.y:.1f}', // one decimal
                y: 10, // 10 pixels down from the top
                style: {
                    fontSize: '13px',
                    fontFamily: 'Verdana, sans-serif'
                }
            }
        }]  // series
    });   // highcharts
}   // function

function createPhobiaChart(data) {   // uses highcharts to display data, function taken from snippet on highcharts' website and modded.
    $('#phobiaChart').highcharts({
        chart: {
            Type: 'column',
            backgroundColor: '#E0CCD3'
        },
        title: {
            text: 'Phobic Index By Visit'
        },
        subtitle: {
            text: '(showing the last 10 visits)'
        },
        xAxis: {
            type: 'category',
            labels: {
                rotation: -45,
                style: {
                    fontSize: '13px',
                    fontFamily: 'Verdana, sans-serif'
                }
            },
            crosshair: true
        },
        yAxis: { // Primary yAxis
                labels: {
                    format: '{value}'
                    // style: {
                    //     fontSize: '13px',
                    //     color: Highcharts.getOptions().colors[1]
                    // }
                },
                title: {
                    text: 'Phobic Index',
                    style: {
                        color: Highcharts.getOptions().colors[1]
                    }
                }
            },

        tooltip: {
            shared: true
        },
        legend: {
            enabled: false
        },
        series: [{
            name: 'Phobic Index',
            data: data.dataPoints,
            type: 'column',
            color: data.barColor,
            tooltip: {
                valueSuffix: ''
            },
            dataLabels: {
                enabled: true,
                rotation: -90,
                color: '#FFFFFF',
                align: 'right',
                format: '{point.y:.1f}', // one decimal
                y: 10, // 10 pixels down from the top
                style: {
                    fontSize: '13px',
                    fontFamily: 'Verdana, sans-serif'
                }
            }
        }]  // series
    });   // highcharts
}   // function

function hideEl(el) {
    el.style.display = 'none';
}

function showEl(el) {
    el.style.display = 'block';
}

function formHandler() {
    var userName = evalform.elements.inputName.value;
    var panicImageIndex = parseInt(evalform.elements.panicimage.value);
    var phobia = evalform.elements.phobia.value;
    if (phobia === 'other') {
        alert('We regret that currently, Conquer It! only addresses arachnophobia.');
        gebi('arach').checked = true;
    } else {
        if (!userName) {
            alert('Username is required!  Please fill out your first name.');
        } else {
            userInfo.userName = capitalizeName(userName);
            userInfo.panicImageIndex = panicImageIndex;
            userInfo.evalComplete = true;

            if (evalform.elements.q5.value === 'true') { userInfo.lastLevelIndex = 10;}
            if (evalform.elements.q4.value === 'true') { userInfo.lastLevelIndex = 8;}
            if (evalform.elements.q3.value === 'true') { userInfo.lastLevelIndex = 5;}
            if (evalform.elements.q2.value === 'true') { userInfo.lastLevelIndex = 2;}
            if (evalform.elements.q1.value === 'true') { userInfo.lastLevelIndex = 1;}

            userInfo.previousVisitLevels.push (userInfo.lastLevelIndex);
            var anxietyIndex = 0;
            for (var cc=1; cc<=5; cc++) {
                var qName = 'nq' + cc;
                var inputEls = document.getElementsByClassName(qName);
                for (var dd=0; dd<inputEls.length; dd++) {
                    if (inputEls[dd].checked) {
                        anxietyIndex += parseInt(inputEls[dd].value);
                    }
                }
            }
            userInfo.previousVisitAnxiety.push(anxietyIndex);
            storeUserInfo();
            hideForm();
            showBuffer();
            showExercise();
            displayImage(userInfo.lastLevelIndex,userInfo.lastImageIndex);
            indicateLevel();
        }
    }
}

var userInfo = {};
var chartSection        = gebi('chartSection');
var formPopup           = gebi('formPopup');
var submitButton        = gebi('submitButton');
var chartContainer      = gebi('chartContainer');
var progressForm        = gebi('progressForm');
var progressFormButton  = gebi('submitProgressForm');
var evalform            = gebi('questionForm');
var evalformButton      = gebi('submitForm');

var spanEls = document.getElementsByClassName('userName');

/*****************************
    BEGINNING OF LOGIC
****************************/

if (submitButton) {
    submitButton.addEventListener('click', processQuestionnaire, false);
}

if (evalformButton) {
    evalformButton.addEventListener('click', formHandler);
}

initUserInfo();

//populate all spans with class 'userName' with (capitalized) user name
for (var bb=0; bb<spanEls.length; bb++) {
    spanEls[bb].textContent = userInfo.userName;
}
<commit_msg>Mo' betta' refactoring.<commit_after>function initUserInfo() {
    if (localStorage.userInfo) {
        userInfo = JSON.parse(localStorage.userInfo);
    } else {
        userInfo = {
          evalComplete: false,
          userName: '',
          lastLevelIndex: 10,
          lastImageIndex: 0,
          panicImageIndex: 0,
          previousVisitLevels: [],
          previousVisitAnxiety: []
        }
    }
}

function processProgressForm() {
    var anxietyIndex = 0;
    for (var cc=1; cc<=5; cc++) {
        var qName = 'nq' + cc;
        var inputEls = document.getElementsByClassName(qName);
        for (var dd=0; dd<inputEls.length; dd++) {
            if (inputEls[dd].checked) {
                anxietyIndex += parseInt(inputEls[dd].value);
            }
        }
    }
    userInfo.previousVisitAnxiety.push(anxietyIndex);
    updateUserInfo();
}

function displayImage(level,index) {
    var imageEl = gebi('mainImage');
    var videoEl = gebi('video');
    var imgWrap = gebi('imgWrap');
    var imagePath = imageArray[level][index].path;
    if (level < 10) {
        imageEl.setAttribute('src',imagePath);
        imageEl.style.display="block";
        videoEl.style.display='none';
        imgWrap.style.backgroundColor="white";
    }  else {
        videoEl.setAttribute('src',imagePath);
        imageEl.style.display='none';
        videoEl.style.display='block';
        imgWrap.style.backgroundColor="black";
    }
}

function storeUserInfo() {
    localStorage.userInfo = JSON.stringify(userInfo);
}

//capitalize userName in case user didn't
function capitalizeName(name) {
    return name.charAt(0).toUpperCase() + name.slice(1);
}

function gebi(el) { // gleefully stolen from Al!
    return document.getElementById(el);
}

function showCharts() {
    hideEl(formPopup);
    showEl(chartContainer);
    createLevelChart (generateChartData(userInfo.previousVisitLevels));
    createPhobiaChart (generateChartData(userInfo.previousVisitAnxiety));
}

function processQuestionnaire() {
    var anxietyIndex = 0;
    for (var cc=1; cc<=5; cc++) {
        var qName = 'q' + cc;
        var inputEls = document.getElementsByClassName(qName);
        for (var dd=0; dd<inputEls.length; dd++) {
            if (inputEls[dd].checked) {
                anxietyIndex += parseInt(inputEls[dd].value);
            }
        }
    }
    userInfo.previousVisitAnxiety.push(anxietyIndex);
    storeUserInfo();
    showCharts();
}

function generateChartData(data) {
    var chartData = {};
    dataLength = data.length;
    var labels = [];
    var templabels = [];
    var tempdata = [];
    chartData.barColor = '#b2f9ed';
    chartData.dataPoints = [];

    templabels.push('Starting Point');
    for (var aa=1; aa <= dataLength; aa++) {
        templabels.push('Visit ' + aa);
    }
    if (dataLength >10) {
        labels[0] = templabels[0];
        labels = labels.concat(templabels.slice(-10));
        tempdata[0] = data[0];
        tempdata = tempdata.concat(data.slice(-10));    // Grab last 10 elements of the array.
    } else {
        tempdata = data;
        labels = templabels;
    }
    for (var i=0;i < Math.min(labels.length, tempdata.length) ;i++) {
        chartData.dataPoints.push([labels[i],tempdata[i]]);
    }

    return chartData;
}

function createLevelChart(data) {   // uses highcharts to display data, function taken from snippet on highcharts' website and modded.
    $('#levelChart').highcharts({
        chart: {
            Type: 'column',
            backgroundColor: '#E0CCD3'
        },
        title: {
            text: 'Highest Level Reached By Visit'
        },
        subtitle: {
            text: '(showing the last 10 visits)'
        },
        xAxis: {
            type: 'category',
            labels: {
                rotation: -45,
                style: {
                    fontSize: '13px',
                    fontFamily: 'Verdana, sans-serif'
                }

            },
            crosshair: true
        },
        yAxis: { // Primary yAxis
                labels: {
                    format: '{value}'
                    // style: {
                    //     fontSize: '13px',
                    //     color: Highcharts.getOptions().colors[1]
                    // }
                },
                title: {
                    text: 'Highest Level Reached',
                    style: {
                        color: '#E0CCD3'
                    }
                }
            },

        tooltip: {
            shared: true
        },
        legend: {
            enabled: false
        },
        series: [{
            name: 'Highest Level Reached',
            data: data.dataPoints,
            type: 'column',
            color: data.barColor,
            tooltip: {
                valueSuffix: ''
            },
            dataLabels: {
                enabled: true,
                rotation: -90,
                color: '#FFFFFF',
                align: 'right',
                format: '{point.y:.1f}', // one decimal
                y: 10, // 10 pixels down from the top
                style: {
                    fontSize: '13px',
                    fontFamily: 'Verdana, sans-serif'
                }
            }
        }]  // series
    });   // highcharts
}   // function

function createPhobiaChart(data) {   // uses highcharts to display data, function taken from snippet on highcharts' website and modded.
    $('#phobiaChart').highcharts({
        chart: {
            Type: 'column',
            backgroundColor: '#E0CCD3'
        },
        title: {
            text: 'Phobic Index By Visit'
        },
        subtitle: {
            text: '(showing the last 10 visits)'
        },
        xAxis: {
            type: 'category',
            labels: {
                rotation: -45,
                style: {
                    fontSize: '13px',
                    fontFamily: 'Verdana, sans-serif'
                }
            },
            crosshair: true
        },
        yAxis: { // Primary yAxis
                labels: {
                    format: '{value}'
                    // style: {
                    //     fontSize: '13px',
                    //     color: Highcharts.getOptions().colors[1]
                    // }
                },
                title: {
                    text: 'Phobic Index',
                    style: {
                        color: Highcharts.getOptions().colors[1]
                    }
                }
            },

        tooltip: {
            shared: true
        },
        legend: {
            enabled: false
        },
        series: [{
            name: 'Phobic Index',
            data: data.dataPoints,
            type: 'column',
            color: data.barColor,
            tooltip: {
                valueSuffix: ''
            },
            dataLabels: {
                enabled: true,
                rotation: -90,
                color: '#FFFFFF',
                align: 'right',
                format: '{point.y:.1f}', // one decimal
                y: 10, // 10 pixels down from the top
                style: {
                    fontSize: '13px',
                    fontFamily: 'Verdana, sans-serif'
                }
            }
        }]  // series
    });   // highcharts
}   // function

function hideEl(el) {
    el.style.display = 'none';
}

function showEl(el) {
    el.style.display = 'block';
}

function formHandler() {
    var userName = evalform.elements.inputName.value;
    var panicImageIndex = parseInt(evalform.elements.panicimage.value);
    var phobia = evalform.elements.phobia.value;
    if (phobia === 'other') {
        alert('We regret that currently, Conquer It! only addresses arachnophobia.');
        gebi('arach').checked = true;
    } else {
        if (!userName) {
            alert('Username is required!  Please fill out your first name.');
        } else {
            userInfo.userName = capitalizeName(userName);
            userInfo.panicImageIndex = panicImageIndex;
            userInfo.evalComplete = true;

            if (evalform.elements.q5.value === 'true') { userInfo.lastLevelIndex = 10;}
            if (evalform.elements.q4.value === 'true') { userInfo.lastLevelIndex = 8;}
            if (evalform.elements.q3.value === 'true') { userInfo.lastLevelIndex = 5;}
            if (evalform.elements.q2.value === 'true') { userInfo.lastLevelIndex = 2;}
            if (evalform.elements.q1.value === 'true') { userInfo.lastLevelIndex = 1;}

            userInfo.previousVisitLevels.push (userInfo.lastLevelIndex);
            var anxietyIndex = 0;
            for (var cc=1; cc<=5; cc++) {
                var qName = 'nq' + cc;
                var inputEls = document.getElementsByClassName(qName);
                for (var dd=0; dd<inputEls.length; dd++) {
                    if (inputEls[dd].checked) {
                        anxietyIndex += parseInt(inputEls[dd].value);
                    }
                }
            }
            userInfo.previousVisitAnxiety.push(anxietyIndex);
            storeUserInfo();
            hideForm();
            showBuffer();
            showExercise();
            displayImage(userInfo.lastLevelIndex,userInfo.lastImageIndex);
            indicateLevel();
        }
    }
}

var userInfo = {};

var chartSection        = gebi('chartSection');
var formPopup           = gebi('formPopup');
var submitButton        = gebi('submitButton');
var chartContainer      = gebi('chartContainer');
var progressForm        = gebi('progressForm');
var progressFormButton  = gebi('submitProgressForm');
var evalform            = gebi('questionForm');
var evalformButton      = gebi('submitForm');

var spanEls = document.getElementsByClassName('userName');

/*****************************
    BEGINNING OF LOGIC
****************************/

if (submitButton) {
    submitButton.addEventListener('click', processQuestionnaire, false);
}

if (evalformButton) {
    evalformButton.addEventListener('click', formHandler);
}

initUserInfo();

//populate all spans with class 'userName' with (capitalized) user name
for (var bb=0; bb<spanEls.length; bb++) {
    spanEls[bb].textContent = userInfo.userName;
}
<|endoftext|>


<commit_before>'use strict';

var categoryImg = [];
var parentElement;
var imageParent;

//create a user and grab it from the welcome page
var user = document.getElementById('userName');

//========================================SPORT QUIZ===============================================

function sportQuiz() {

  var sportsQuestions = [
    'Who won the last soccer world cup in Brazil 2014? Your choices are: a, b, c',
    'How many times did USA made it to the world cup?',
    'Who won the MLS cup in 2016?',
    'Which famous player helped Napoli win their first ever championship?',
    'Who won the champions league this year?'
  ];
  var sportsAnswers = ['Germany', '10', 'Seattle Sounders', 'Diego Maradona', 'Real Madrid'];
  var text;
  for (var i = 0; i < sportsQuestions.length; i++) {

    parentElement = document.getElementById('quiz');

    sportsAnswers.forEach(function() {
      text = document.createElement('input');
      text.setAttribute('id', sportsAnswers[i]);
    });

    console.log(text.id);

    var p = document.createElement('p');

    p.textContent = sportsQuestions[i];

    parentElement.append(p);
    parentElement.append(text);

  }
}

// sportQuiz();
//========================================TRAVEL QUIZ===============================================

function travelQuiz() {

  var travelQuestions = [
    'What country is mt everest in? Your choices are: a, b, c',
    'What is mt st helens famous for',
    'What famous art museum is in Paris France?',
    'Where are the most famous pyramids located?',
    'What famous landmark that can be seen from space is in China?'
  ];
  var travelAnswers = ['Nepal', 'Being a volcano', 'Le Louvre', 'Egypt', 'The Great Wall'];
  var text;
  for (var i = 0; i < travelQuestions.length; i++) {

    parentElement = document.getElementById('quiz');

    travelAnswers.forEach(function() {
      text = document.createElement('input');
      text.setAttribute('id', travelAnswers[i]);
    });

    console.log(text.id);

    var p = document.createElement('p');

    p.textContent = travelQuestions[i];

    parentElement.append(p);
    parentElement.append(text);

  }
}

// travelQuiz();

//========================================POP-CULTURE QUIZ===============================================

function popQuiz() {

  var popQuestions = [
    'This singer sat in a Blank Space while trying to shake it off as she sang We are never getting back together. Who is she?',
    'In the Big Bang Sheldon Cooper and Leonard Hofstadter lived next door to a pretty waitress named?',
    'Queen Daenerys Targaryen is also known as the mother of ?',
    'What famous actress plays Katniss Everdeen in the hunger games?',
    'Doctor who thinks these are cool?'
  ];
  var popAnswers = ['Taylor Swift', 'Penny', 'Dragons', 'Jennifer Lawrence', 'Bow ties'];
  var text;
  for (var i = 0; i < popQuestions.length; i++) {

    parentElement = document.getElementById('quiz');

    popAnswers.forEach(function() {
      text = document.createElement('input');
      text.setAttribute('id', popAnswers[i]);
    });

    console.log(text.id);

    var p = document.createElement('p');

    p.textContent = popQuestions[i];

    parentElement.append(p);
    parentElement.append(text);

  }
}

// popQuiz();

//=================================LINK EACH IMAGE TO APPROPRIATE QUIZ================================

//========================================EVENT LISTENER===============================================

//set the images section to be linked to the event
imageParent = document.getElementById('imageContainer');

//add the event listener to listen for images IDs
imageParent.addEventListener('click', clickHandler);

function clickHandler() {
  var clicked = event.target.getAttribute('id');
  console.log('clicked ' + clicked);
  if (clicked === 'img1') {
    sportQuiz();
    imageParent.removeEventListener('click', clickHandler);
  } else if (clicked === 'img2') {
    popQuiz();
    imageParent.removeEventListener('click', clickHandler);
  } else {
    travelQuiz();
    imageParent.removeEventListener('click', clickHandler);
  }
  //add the two button for the score and to reset:
  var resetButton = document.createElement('button');
  resetButton.innerHTML = 'Reset';
  var scoreButton = document.createElement('button');
  scoreButton.innerHTML = 'Score';
  parentElement.append(resetButton);
  parentElement.append(scoreButton);
}

// parentElement = document.getElementById('quiz');
//   var p = document.createElement('p');
//   p.textContent = sports[0].q1;
//   parentElement.append(p);
// sports[0].q1

//===================================================================
//second attempt

//function for each of the three quizes to create the questions and answers and render it to the page.

//quiz 1

// function sportsQuiz () {
//
// }

//===================================================================
//first attempt

//function to populate the quiz field render()

// function render() {
//   parentElement = document.getElementById('quiz');
//   var h1 = document.createElement('h1');
//   h1.textContent = 'This is the first question?';
//   parentElement.append(h1);
// }
//
// render();
//event listener
//=====================================================================

function User(name, score, correct, wrong) {
  this.name = name,
    this.score = score,
    this.correct = 0,
    this.wrong = 0;
};

function ImageForCat(imgName, path, category) {
  this.imgName = imgName;
  this.path = path;
  this.category = category;
  categoryImg.push(this);
};
new ImageForCat('sports', 'img/sports.jpg', 'sports');
new ImageForCat('geography', 'img/geography.jpg', 'geography');
new ImageForCat('pop-culture', 'img/popculture.jpg', 'popculture');
<commit_msg>finished coding reset button and also reload button in quiz<commit_after>'use strict';

var categoryImg = [];
var parentElement;
var imageParent;

//create a user and grab it from the welcome page
var user = document.getElementById('userName');

//========================================SPORT QUIZ===============================================

function sportQuiz() {

  var sportsQuestions = [
    'Who won the last soccer world cup in Brazil 2014? Your choices are: a, b, c',
    'How many times did USA made it to the world cup?',
    'Who won the MLS cup in 2016?',
    'Which famous player helped Napoli win their first ever championship?',
    'Who won the champions league this year?'
  ];
  var sportsAnswers = ['Germany', '10', 'Seattle Sounders', 'Diego Maradona', 'Real Madrid'];
  var text;
  for (var i = 0; i < sportsQuestions.length; i++) {

    parentElement = document.getElementById('quiz');

    sportsAnswers.forEach(function() {
      text = document.createElement('input');
      text.setAttribute('id', sportsAnswers[i]);
    });

    console.log(text.id);

    var p = document.createElement('p');

    p.textContent = sportsQuestions[i];

    parentElement.append(p);
    parentElement.append(text);

  }
}

// sportQuiz();
//========================================TRAVEL QUIZ===============================================

function travelQuiz() {

  var travelQuestions = [
    'What country is mt everest in? Your choices are: a, b, c',
    'What is mt st helens famous for',
    'What famous art museum is in Paris France?',
    'Where are the most famous pyramids located?',
    'What famous landmark that can be seen from space is in China?'
  ];
  var travelAnswers = ['Nepal', 'Being a volcano', 'Le Louvre', 'Egypt', 'The Great Wall'];
  var text;
  for (var i = 0; i < travelQuestions.length; i++) {

    parentElement = document.getElementById('quiz');

    travelAnswers.forEach(function() {
      text = document.createElement('input');
      text.setAttribute('id', travelAnswers[i]);
    });

    console.log(text.id);

    var p = document.createElement('p');

    p.textContent = travelQuestions[i];

    parentElement.append(p);
    parentElement.append(text);

  }
}

// travelQuiz();

//========================================POP-CULTURE QUIZ===============================================

function popQuiz() {

  var popQuestions = [
    'This singer sat in a Blank Space while trying to shake it off as she sang We are never getting back together. Who is she?',
    'In the Big Bang Sheldon Cooper and Leonard Hofstadter lived next door to a pretty waitress named?',
    'Queen Daenerys Targaryen is also known as the mother of ?',
    'What famous actress plays Katniss Everdeen in the hunger games?',
    'Doctor who thinks these are cool?'
  ];
  var popAnswers = ['Taylor Swift', 'Penny', 'Dragons', 'Jennifer Lawrence', 'Bow ties'];
  var text;
  for (var i = 0; i < popQuestions.length; i++) {

    parentElement = document.getElementById('quiz');

    popAnswers.forEach(function() {
      text = document.createElement('input');
      text.setAttribute('id', popAnswers[i]);
    });

    console.log(text.id);

    var p = document.createElement('p');

    p.textContent = popQuestions[i];

    parentElement.append(p);
    parentElement.append(text);

  }
}

// popQuiz();

//=================================LINK EACH IMAGE TO APPROPRIATE QUIZ================================

//========================================EVENT LISTENER===============================================

//set the images section to be linked to the event
imageParent = document.getElementById('imageContainer');

//add the event listener to listen for images IDs
imageParent.addEventListener('click', clickHandler);

function clickHandler() {
  var clicked = event.target.getAttribute('id');
  console.log('clicked ' + clicked);
  if (clicked === 'img1') {
    sportQuiz();
    imageParent.removeEventListener('click', clickHandler);
  } else if (clicked === 'img2') {
    popQuiz();
    imageParent.removeEventListener('click', clickHandler);
  } else {
    travelQuiz();
    imageParent.removeEventListener('click', clickHandler);
  }
  //add the two button for the score and to reset:
  var resetButton = document.createElement('button');
  resetButton.innerHTML = 'Reset';

  //set the reset button to reload the page
  resetButton.addEventListener('click', function() {
    location.reload();
  });

  //set the score button to take us to score page
  var scoreButton = document.createElement('button');
  scoreButton.innerHTML = 'Score';
  scoreButton.addEventListener('click', function() {
    window.location.href = 'scoreboard.html';
  });
  parentElement.append(resetButton);
  parentElement.append(scoreButton);
}

// parentElement = document.getElementById('quiz');
//   var p = document.createElement('p');
//   p.textContent = sports[0].q1;
//   parentElement.append(p);
// sports[0].q1

//===================================================================
//second attempt

//function for each of the three quizes to create the questions and answers and render it to the page.

//quiz 1

// function sportsQuiz () {
//
// }

//===================================================================
//first attempt

//function to populate the quiz field render()

// function render() {
//   parentElement = document.getElementById('quiz');
//   var h1 = document.createElement('h1');
//   h1.textContent = 'This is the first question?';
//   parentElement.append(h1);
// }
//
// render();
//event listener
//=====================================================================

function User(name, score, correct, wrong) {
  this.name = name,
    this.score = score,
    this.correct = 0,
    this.wrong = 0;
};

function ImageForCat(imgName, path, category) {
  this.imgName = imgName;
  this.path = path;
  this.category = category;
  categoryImg.push(this);
};
new ImageForCat('sports', 'img/sports.jpg', 'sports');
new ImageForCat('geography', 'img/geography.jpg', 'geography');
new ImageForCat('pop-culture', 'img/popculture.jpg', 'popculture');
<|endoftext|>


<commit_before>// Script for Campfire Coffee business analytics

var lbsPerCup = 0.05;
var hoursString = ['6:00am','7:00am','8:00am','9:00am','10:00am','11:00am','12 noon','1:00pm','2:00pm','3:00pm','4:00pm','5:00pm','6:00pm','7:00pm','8:00pm'];

function shopLocData(location,minCustomers,maxCustomers,cupsPer,poundsPer) {
  this.location = location;
  this.minCustomers = minCustomers;
  this.maxCustomers = maxCustomers;
  this.cupsPer = cupsPer;
  this.poundsPer = poundsPer;

  var customers = [];
  var cups = [];
  var cupLbs = [];
  var rawLbs = [];
  var totLbs = [];
  for (i = 0; i < hoursString.length; i++) {
    var randomCustomers = Math.floor(Math.random() * (maxCustomers - minCustomers)) + minCustomers;
    var tempCups = randomCustomers * cupsPer;
    var tempCupLbs = tempCups * lbsPerCup;
    var tempRawLbs = randomCustomers * poundsPer;
    var tempTotLbs = tempCupLbs + tempRawLbs;
    customers[i] = randomCustomers;
    cups[i] = tempCups.toFixed(1);
    cupLbs[i] = tempCupLbs.toFixed(1);
    rawLbs[i] = tempRawLbs.toFixed(1);
    totLbs[i] = tempTotLbs.toFixed(1);
  }
  this.customers = customers;
  this.cups = cups;
  this.cupLbs = cupLbs;
  this.rawLbs = rawLbs;
  this.totLbs = totLbs;
}

var pikePlaceMarket = new shopLocData('Pike Place Market',14,55,1.2,3.7);
var capitolHill = new shopLocData('Capitol Hill',32,48,3.2,0.4);
var seattlePublicLibrary = new shopLocData('Seattle Public Library',49,75,2.6,0.2);
var southLakeUnion = new shopLocData('South Lake Union',35,88,1.3,3.7);
var seaTacAirport = new shopLocData('SeaTac Airport',68,124,1.1,2.7);
var websiteSales = new shopLocData('Website Sales',3,6,0,6.7);

function appendData(location) {
  var paragraphEl = document.createElement('p');
  var parId = 'parId';
  paragraphEl.textContent = location.location;
  document.body.appendChild(paragraphEl);

  var unorderedListEl = document.createElement('ul');
  var ulId = location.location + 'ulId';
  unorderedListEl.id = ulId;
  document.body.appendChild(unorderedListEl);

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

    var listEl = document.createElement('li');
    listEl.textContent = hoursString[i] + ': ' + location.totLbs[i] + ' lbs [' + location.customers[i] + ' customers, ' + location.cups[i] + ' cups (' + location.cupLbs[i] + ' lbs), ' + location.rawLbs[i] + ' lbs to-go]';
    document.getElementById(ulId).appendChild(listEl);

  }
}

appendData(pikePlaceMarket);
appendData(capitolHill);
appendData(seattlePublicLibrary);
appendData(southLakeUnion);
appendData(seaTacAirport);
appendData(websiteSales);
<commit_msg>made lists into table<commit_after>// Script for Campfire Coffee business analytics
'use strict';
/* jshint -W117 */
/* jshint -W040 */
/* jshint -W097 */

var lbsPerCup = 0.05;
var hoursString = ['6:00am','7:00am','8:00am','9:00am','10:00am','11:00am','12 noon','1:00pm','2:00pm','3:00pm','4:00pm','5:00pm','6:00pm','7:00pm','8:00pm'];

function shopLocData(location,minCustomers,maxCustomers,cupsPer,poundsPer) {
  this.location = location;
  this.minCustomers = minCustomers;
  this.maxCustomers = maxCustomers;
  this.cupsPer = cupsPer;
  this.poundsPer = poundsPer;

  var customers = [];
  var cups = [];
  var cupLbs = [];
  var rawLbs = [];
  var totLbs = [];
  for (var i = 0; i < hoursString.length; i++) {
    var randomCustomers = Math.floor(Math.random() * (maxCustomers - minCustomers)) + minCustomers;
    var tempCups = randomCustomers * cupsPer;
    var tempCupLbs = tempCups * lbsPerCup;
    var tempRawLbs = randomCustomers * poundsPer;
    var tempTotLbs = tempCupLbs + tempRawLbs;
    customers[i] = randomCustomers;
    cups[i] = tempCups.toFixed(1);
    cupLbs[i] = tempCupLbs.toFixed(1);
    rawLbs[i] = tempRawLbs.toFixed(1);
    totLbs[i] = tempTotLbs.toFixed(1);
  }
  this.customers = customers;
  this.cups = cups;
  this.cupLbs = cupLbs;
  this.rawLbs = rawLbs;
  this.totLbs = totLbs;
}

var pikePlaceMarket = new shopLocData('Pike Place Market',14,55,1.2,3.7);
var capitolHill = new shopLocData('Capitol Hill',32,48,3.2,0.4);
var seattlePublicLibrary = new shopLocData('Seattle Public Library',49,75,2.6,0.2);
var southLakeUnion = new shopLocData('South Lake Union',35,88,1.3,3.7);
var seaTacAirport = new shopLocData('SeaTac Airport',68,124,1.1,2.7);
var websiteSales = new shopLocData('Website Sales',3,6,0,6.7);

function tableData(location) {
  var tableEl = document.createElement('table');
  var tabId = 'tableId' + location.location;
  tableEl.id = tabId;
  document.body.appendChild(tableEl);

  var theadEl = document.createElement('thead');
  var theadId = 'theadId' + location.location;
  theadEl.id = theadId;
  document.getElementById(tabId).appendChild(theadEl);

  var trEl = document.createElement('tr');
  var trId = 'trId' + location.location;
  trEl.id = trId;
  document.getElementById(theadId).appendChild(trEl);

  var th1El = document.createElement('th');
  var th1Id = 'th1Id' + location.location;
  th1El.id = th1Id;
  th1El.textContent = 'Location';
  document.getElementById(trId).appendChild(th1El);

  var th2El = document.createElement('th');
  var th2Id = 'th2Id' + location.location;
  th2El.id = th2Id;
  th2El.textContent = 'Hours';
  document.getElementById(trId).appendChild(th2El);

  var th3El = document.createElement('th');
  var th3Id = 'th3Id' + location.location;
  th3El.id = th3Id;
  th3El.textContent = 'Total Pounds(lbs)';
  document.getElementById(trId).appendChild(th2El);

  var th4El = document.createElement('th');
  var th4Id = 'th4Id' + location.location;
  th4El.id = th4Id;
  th4El.textContent = 'Customers';
  document.getElementById(trId).appendChild(th4El);

  var th5El = document.createElement('th');
  var th5Id = 'th5Id' + location.location;
  th5El.id = th5Id;
  th5El.textContent = 'Total Cups';
  document.getElementById(trId).appendChild(th5El);

  var th6El = document.createElement('th');
  var th6Id = 'th6Id' + location.location;
  th6El.id = th2Id;
  th6El.textContent = 'Cup Pounds (lbs)';
  document.getElementById(trId).appendChild(th6El);

  var th7El = document.createElement('th');
  var th7Id = 'th2Id' + location.location;
  th7El.id = th2Id;
  th7El.textContent = 'To-go Pounds (lbs)';
  document.getElementById(trId).appendChild(th7El);

  for (var i = 0; i < hoursString.length; i++) {
    var tempTrEl = document.createElement('tr');
    var tempTrId = 'tempTrId_' + i + '_' + location.location;
    tempTrEl.id = tempTrId;
    document.getElementById(tabId).appendChild(tempTrEl);

    var tempTdEl1 = document.createElement('td');
    tempTdEl1.textContent = location.location;
    tempTdEl1.rowspan = '15';
    document.getElementById(tempTrId).appendChild(tempTdEl1);

    var tempTdEl2 = document.createElement('td');
    tempTdEl2.textContent = hoursString[i];
    document.getElementById(tempTrId).appendChild(tempTdEl2);

    var tempTdEl3 = document.createElement('td');
    tempTdEl3.textContent = location.customers[i];
    document.getElementById(tempTrId).appendChild(tempTdEl3);

    var tempTdEl4 = document.createElement('td');
    tempTdEl4.textContent = location.cups[i];
    document.getElementById(tempTrId).appendChild(tempTdEl4);

    var tempTdEl5 = document.createElement('td');
    tempTdEl5.textContent = location.cupLbs[i];
    document.getElementById(tempTrId).appendChild(tempTdEl5);

    var tempTdEl6 = document.createElement('td');
    tempTdEl6.textContent = location.rawLbs[i];
    document.getElementById(tempTrId).appendChild(tempTdEl6);
  }
}

tableData(pikePlaceMarket);
tableData(capitolHill);
tableData(seattlePublicLibrary);
tableData(southLakeUnion);
tableData(seaTacAirport);
tableData(websiteSales);

// function appendData(location) {
//   var paragraphEl = document.createElement('p');
//   var parId = 'parId';
//   paragraphEl.textContent = location.location;
//   document.body.appendChild(paragraphEl);
//
//   var unorderedListEl = document.createElement('ul');
//   var ulId = location.location + 'ulId';
//   unorderedListEl.id = ulId;
//   document.body.appendChild(unorderedListEl);
//
//   for (var i = 0; i < hoursString.length; i++) {
//
//     var listEl = document.createElement('li');
//     listEl.textContent = hoursString[i] + ': ' + location.totLbs[i] + ' lbs [' + location.customers[i] + ' customers, ' + location.cups[i] + ' cups (' + location.cupLbs[i] + ' lbs), ' + location.rawLbs[i] + ' lbs to-go]';
//     document.getElementById(ulId).appendChild(listEl);
//
//   }
// }
//
// appendData(pikePlaceMarket);
// appendData(capitolHill);
// appendData(seattlePublicLibrary);
// appendData(southLakeUnion);
// appendData(seaTacAirport);
// appendData(websiteSales);
<|endoftext|>


<commit_before>'use strict';

var products = ['img/bag.jpg', 'img/banana.jpg', 'img/boots.jpg', 'img/chair.jpg', 'img/cthulhu.jpg', 'img/dragon.jpg', 'img/pen.jpg', 'img/scissors.jpg', 'img/shark.jpg', 'img/sweep.jpg', 'img/unicorn.jpg','img/usb.jpg', 'img/water-can.jpg', 'img/wine-glass.jpg'];

var prodArray=[];
var counterClicks = 0;
var resultsButton = document.getElementById('buttonResults');
resultsButton.className = 'hideButton';
var barChartLabels = [];
var barChartData = [];

var firstPic = document.getElementById('first');
var secondPic = document.getElementById('second');
var thirdPic = document.getElementById('third');
var results = document.getElementById('results');

var clicksOnFirst = 0;
var clicksOnSecond = 0;
var clicksOnThird = 0;

firstPic.addEventListener('click', handleClick);
secondPic.addEventListener('click', handleClick);
thirdPic.addEventListener('click', handleClick);

function Product(filePath) {
  this.filePath = filePath;
  this.clicks = 0;
}

function initObjArray() {
  for(var i = 0; i < products.length; i++) {
    var image = new Product(products[i]);
    prodArray.push(image);
  }
}

function getRandomImage() {
  var i = 0;
  var a = Math.floor(Math.random()*products.length);
  var b = Math.floor(Math.random()*products.length);
  var c= Math.floor(Math.random()*products.length);

  while(a==b) {
    b = Math.floor(Math.random()*products.length);}

  while((a==c) || (b==c)) {
    c = Math.floor(Math.random()*products.length);
  }
  firstPic.src = prodArray[a].filePath;
  secondPic.src = prodArray[b].filePath;
  thirdPic.src = prodArray[c].filePath;
}

function handleClick() {
  ++counterClicks;
  for (var i = 0; i < prodArray.length;i++) {
    if(this.src.indexOf(prodArray[i].filePath) >= 0 ) {
      prodArray[i].clicks++;
    }
  }
  getRandomImage();

  if (counterClicks == 15) {
    resultsButton.className = 'showButton';
  }
}

function showResult() {
  // var tblEl = document.createElement('table');
  // var trEl = document.createElement('tr');
  // var thEl = document.createElement('th');
  // thEl.textContent = 'Product';
  // trEl.appendChild(thEl);
  // thEl = document.createElement('th');
  // thEl.textContent = 'Votes';
  // trEl.appendChild(thEl);
  // tblEl.appendChild(trEl);
  // results.appendChild(tblEl);
  //
  // for(var i = 0; i < prodArray.length; i++) {
  //   var trEl = document.createElement('tr');
  //   var thEl = document.createElement('th');
  //   thEl.innerHTML = '';
  //   trEl.appendChild(thEl);
  //   tblEl.appendChild(trEl);
  //   results.appendChild(tblEl);
  //
  //   var tdEl = document.createElement('td');
  //   tdEl.textContent = prodArray[i].clicks;
  //   trEl.appendChild(tdEl);
  //   tblEl.appendChild(trEl);
  //   results.appendChild(tblEl);
  // }
  barChart();
}

function barChart() {
  var ctx = document.getElementById('votes').getContext('2d');
  for(var i = 0; i < prodArray.length; i++) {
    barChartLabels.push(prodArray[i].filePath);
    barChartData.push(prodArray[i].clicks);
  }
  for(var i = 0; i < products.length; i++) {
    barChartLabels[i] = barChartLabels[i].replace('img/','');
    barChartLabels[i] = barChartLabels[i].replace('.jpg','');
  }
  var  data = {
    labels: barChartLabels,
    datasets: [
      {
        fillColor: '#48A497',
        highlightFill: 'rgba(220,220,220,0.75)',
        highlightStroke: 'rgba(220,220,220,1)',
        data: barChartData
      }
    ]
  };

  var myBarChart = new Chart(ctx).Bar(data);
}

initObjArray();
getRandomImage();
<commit_msg>experimenting with charts<commit_after>'use strict';

var products = ['img/bag.jpg', 'img/banana.jpg', 'img/boots.jpg', 'img/chair.jpg', 'img/cthulhu.jpg', 'img/dragon.jpg', 'img/pen.jpg', 'img/scissors.jpg', 'img/shark.jpg', 'img/sweep.jpg', 'img/unicorn.jpg','img/usb.jpg', 'img/water-can.jpg', 'img/wine-glass.jpg'];

var prodArray=[];
var counterClicks = 0;
var resultsButton = document.getElementById('buttonResults');
resultsButton.className = 'hideButton';
var barChartLabels = [];
var barChartData = [];

var firstPic = document.getElementById('first');
var secondPic = document.getElementById('second');
var thirdPic = document.getElementById('third');
var results = document.getElementById('results');

var clicksOnFirst = 0;
var clicksOnSecond = 0;
var clicksOnThird = 0;

firstPic.addEventListener('click', handleClick);
secondPic.addEventListener('click', handleClick);
thirdPic.addEventListener('click', handleClick);

function Product(filePath) {
  this.filePath = filePath;
  this.clicks = 0;
}

function initObjArray() {
  for(var i = 0; i < products.length; i++) {
    var image = new Product(products[i]);
    prodArray.push(image);
  }
}

function getRandomImage() {
  var i = 0;
  var a = Math.floor(Math.random()*products.length);
  var b = Math.floor(Math.random()*products.length);
  var c= Math.floor(Math.random()*products.length);

  while(a==b) {
    b = Math.floor(Math.random()*products.length);}

  while((a==c) || (b==c)) {
    c = Math.floor(Math.random()*products.length);
  }
  firstPic.src = prodArray[a].filePath;
  secondPic.src = prodArray[b].filePath;
  thirdPic.src = prodArray[c].filePath;
}

function handleClick() {
  ++counterClicks;
  for (var i = 0; i < prodArray.length;i++) {
    if(this.src.indexOf(prodArray[i].filePath) >= 0 ) {
      prodArray[i].clicks++;
    }
  }
  getRandomImage();

  if (counterClicks == 15) {
    resultsButton.className = 'showButton';
  }
}

function showResult() {
  // var tblEl = document.createElement('table');
  // var trEl = document.createElement('tr');
  // var thEl = document.createElement('th');
  // thEl.textContent = 'Product';
  // trEl.appendChild(thEl);
  // thEl = document.createElement('th');
  // thEl.textContent = 'Votes';
  // trEl.appendChild(thEl);
  // tblEl.appendChild(trEl);
  // results.appendChild(tblEl);
  //
  // for(var i = 0; i < prodArray.length; i++) {
  //   var trEl = document.createElement('tr');
  //   var thEl = document.createElement('th');
  //   thEl.innerHTML = '';
  //   trEl.appendChild(thEl);
  //   tblEl.appendChild(trEl);
  //   results.appendChild(tblEl);
  //
  //   var tdEl = document.createElement('td');
  //   tdEl.textContent = prodArray[i].clicks;
  //   trEl.appendChild(tdEl);
  //   tblEl.appendChild(trEl);
  //   results.appendChild(tblEl);
  // }
  barChart();
}

function barChart() {
  var ctx = document.getElementById('votes').getContext('2d');
  for(var i = 0; i < prodArray.length; i++) {
    barChartLabels.push(prodArray[i].filePath);
    barChartData.push(prodArray[i].clicks);
  }
  for(var i = 0; i < products.length; i++) {
    barChartLabels[i] = barChartLabels[i].replace('img/','');
    barChartLabels[i] = barChartLabels[i].replace('.jpg','');
  }
  var  data = {
    labels: barChartLabels,
    datasets: [
      {
        fillColor: 'darkblue',
        responsive: true,
        scaleLineColor: 'rgba(0,0,0,.1)',
        scaleFontColor: '##2d2d20',
        highlightFill: 'rgba(220,220,220,0.75)',
        highlightStroke: 'rgba(220,220,220,1)',
        data: barChartData
      }
    ]
  };
  var myBarChart = new Chart(ctx).Bar(data);
}

initObjArray();
getRandomImage();
<|endoftext|>


<commit_before>$(document).ready(function() {

    /*
     * Data Tables
     */

    // Setup - add a text input to each footer cell
    $('#table-maplist tfoot th').each( function () {
        var title = $(this).text();
        if (title != "mapshot?") {
            $(this).html( '<input type="text" placeholder="filter '+title+'" />' );
        }
    } );

    var table = $('#table-maplist').DataTable( {
        "ajax": "data/maps.json",
        "lengthMenu": [[50, 100, 250, 500, 1000], [50, 100, 250, 500, 1000]],
        "pageLength": 250,
        "colReorder": true,
        "stateSave": true,
        "fixedHeader": true,
        "processing": true,
        "deferRender": true,
        "language": {
           "processing": "Processing a large file, this might take a second."
        },
        "buttons": [
            {
                "extend": "csvHtml5",
                "text": ' Download CSV',
            },
            {
                "extend": "colvis",
                "postfixButtons": [ 'colvisRestore' ],
                "text": ' Toggle Columns'
            }
        ],
        "dom": "<'row'<'col-sm-6'l><'col-sm-6'<'pull-right'B>>>" +
                "<'row'<'col-sm-12'tr>>" +
                "<'row'<'col-sm-5'i><'col-sm-7'p>>",
        "columns": [
            { "data": "pk3" },
            { "data": "bsp[
 ]" },
            { "data": "filesize" },
            { "data": "filesize" },
            { "data": "shasum" },
            { "data": "title" },
            { "data": "author" },
            { "data": "mapshot" },
            { "data": "gametypes[, ]" },
            { "data": "map[, ]" },
            { "data": "radar[, ]" },
            { "data": "waypoints[, ]" },
            { "data": "license" },
            { "data": "date" }
        ],
        "columnDefs": [
            {   // pk3
                "targets": 0,
                "render": function ( data, type, full, meta ) {
                    var pk3 = data;
                    if (type === 'display' && data.length > 40) {
                        data = ''+data.substr( 0, 38 )+'...';
                    }
                    return '' + data + '';
                }
            },
            {   // bsp
                "targets": 1,
                "render": function ( data, type, full, meta ) {
                    if (data != false && data.length > 0) {
            			if (data.length > 40 && data.indexOf('
') == -1) {
                            data = ''+data.substr( 0, 38 )+'...';
        		    	}
        		    }
                    return data;
                }
            },
            {   // filesize
                "targets": 2,
                "orderData": 3,
                "render": function ( data, type, full, meta ) {
                    return(bytesToSize(data));
                }
            },
            {   // filesize for sorting
                "targets": 3,
                "visible": false,
                "searchable": false
            },
            {   // mapshot file
                "targets": 7,
                "render": function ( data, type, full, meta ) {
                    var string = "";
                    if (data.length > 0) {
                        data.forEach(function(value, index, array) {
                            string += '';
                        });
                    }
                    return string;
                }
            },
            {   // map file
                "targets": 9,
                "render": function ( data, type, full, meta ) {
                    return (data != false) ? true : false;
                }
            },
            {   // radar file
                "targets": 10,
                "render": function ( data, type, full, meta ) {
                    return (data != false) ? true : false;
                }
            },
            {   // waypoints file
                "targets": 11,
                "render": function ( data, type, full, meta ) {
                    return (data != false) ? true : false;
                }
            },
            {
                // date
                "targets": 13,
                "render": function ( data, type, full, meta ) {
                    d = new Date(0);
                    d.setUTCSeconds(data);
                    return d.toISOString().slice(0,10);
                }
            }
        ],
        "initComplete": function( settings, json ) {
            // clear filters on page load
            $("tfoot input").val('').trigger('change');
        },
        "drawCallback": function( settings) {
            $('a[rel=popover]').popover({
                html: true,
                trigger: 'hover',
                content: function () {
                    return '';
                }
            });
        }
    } );

    // Apply the search
    table.columns().every( function () {
        var that = this;

        $( 'input', this.footer() ).on( 'keyup change', function () {
            if ( that.search() !== this.value ) {
                that
                    .search( this.value )
                    .draw();
            }
        } );
    } );

    table.on( 'column-reorder', function ( e, settings, details ) {
        table.draw();
    } );

    /*
     * Charts
     */

    // Need to hide datatables when changing tabs for fixedHeader
    var visible = true;
    var tableContainer = $(table.table().container());

    // Bootstrap tab shown event
    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {

        tableContainer.css( 'display', visible ? 'none' : 'block' );
        table.fixedHeader.adjust();

        visible = ! visible;

        $("#charts").hide();
        $("#loading-charts").show();

        $.get('data/charts.json', function(data) {

            $("#loading-charts").hide();
            $("#charts").show();

            // Pie
            c3.generate(data.mapinfos);
            c3.generate(data.mapshots);
            c3.generate(data.maps);
            c3.generate(data.radars);
            c3.generate(data.waypoints);
            c3.generate(data.licenses);

            // Scatter
            var filesizes = {
                axis: { x: { show: false }, rotated: true },
                tooltip: {
                    format: {
                        title: function (x) { return; },
                        name: function (name, ratio, id, index) { return "size"; },
                        value: function (value, ratio, id, index) { return bytesToSize(value); }
                    }
                }
            };

            $.extend(filesizes, data.filesizes);
            c3.generate(filesizes);

            // Line
            c3.generate(data.mapsbyyear);

        });

    });

} );

function bytesToSize(bytes) {
   var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
   if (bytes == 0) return '0 Byte';
   var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
   return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
};

<commit_msg>similar style to datatables processing<commit_after>$(document).ready(function() {

    /*
     * Data Tables
     */

    // Setup - add a text input to each footer cell
    $('#table-maplist tfoot th').each( function () {
        var title = $(this).text();
        if (title != "mapshot?") {
            $(this).html( '<input type="text" placeholder="filter '+title+'" />' );
        }
    } );

    var table = $('#table-maplist').DataTable( {
        "ajax": "data/maps.json",
        "lengthMenu": [[50, 100, 250, 500, 1000], [50, 100, 250, 500, 1000]],
        "pageLength": 250,
        "colReorder": true,
        "stateSave": true,
        "fixedHeader": true,
        "processing": true,
        "deferRender": true,
        "language": {
           "processing": '
Processing a large file, this might take a second

'
        },
        "buttons": [
            {
                "extend": "csvHtml5",
                "text": ' Download CSV',
            },
            {
                "extend": "colvis",
                "postfixButtons": [ 'colvisRestore' ],
                "text": ' Toggle Columns'
            }
        ],
        "dom": "<'row'<'col-sm-6'l><'col-sm-6'<'pull-right'B>>>" +
                "<'row'<'col-sm-12'tr>>" +
                "<'row'<'col-sm-5'i><'col-sm-7'p>>",
        "columns": [
            { "data": "pk3" },
            { "data": "bsp[
 ]" },
            { "data": "filesize" },
            { "data": "filesize" },
            { "data": "shasum" },
            { "data": "title" },
            { "data": "author" },
            { "data": "mapshot" },
            { "data": "gametypes[, ]" },
            { "data": "map[, ]" },
            { "data": "radar[, ]" },
            { "data": "waypoints[, ]" },
            { "data": "license" },
            { "data": "date" }
        ],
        "columnDefs": [
            {   // pk3
                "targets": 0,
                "render": function ( data, type, full, meta ) {
                    var pk3 = data;
                    if (type === 'display' && data.length > 40) {
                        data = ''+data.substr( 0, 38 )+'...';
                    }
                    return '' + data + '';
                }
            },
            {   // bsp
                "targets": 1,
                "render": function ( data, type, full, meta ) {
                    if (data != false && data.length > 0) {
            			if (data.length > 40 && data.indexOf('
') == -1) {
                            data = ''+data.substr( 0, 38 )+'...';
        		    	}
        		    }
                    return data;
                }
            },
            {   // filesize
                "targets": 2,
                "orderData": 3,
                "render": function ( data, type, full, meta ) {
                    return(bytesToSize(data));
                }
            },
            {   // filesize for sorting
                "targets": 3,
                "visible": false,
                "searchable": false
            },
            {   // mapshot file
                "targets": 7,
                "render": function ( data, type, full, meta ) {
                    var string = "";
                    if (data.length > 0) {
                        data.forEach(function(value, index, array) {
                            string += '';
                        });
                    }
                    return string;
                }
            },
            {   // map file
                "targets": 9,
                "render": function ( data, type, full, meta ) {
                    return (data != false) ? true : false;
                }
            },
            {   // radar file
                "targets": 10,
                "render": function ( data, type, full, meta ) {
                    return (data != false) ? true : false;
                }
            },
            {   // waypoints file
                "targets": 11,
                "render": function ( data, type, full, meta ) {
                    return (data != false) ? true : false;
                }
            },
            {
                // date
                "targets": 13,
                "render": function ( data, type, full, meta ) {
                    d = new Date(0);
                    d.setUTCSeconds(data);
                    return d.toISOString().slice(0,10);
                }
            }
        ],
        "initComplete": function( settings, json ) {
            // clear filters on page load
            $("tfoot input").val('').trigger('change');
        },
        "drawCallback": function( settings) {
            $('a[rel=popover]').popover({
                html: true,
                trigger: 'hover',
                content: function () {
                    return '';
                }
            });
        }
    } );

    // Apply the search
    table.columns().every( function () {
        var that = this;

        $( 'input', this.footer() ).on( 'keyup change', function () {
            if ( that.search() !== this.value ) {
                that
                    .search( this.value )
                    .draw();
            }
        } );
    } );

    table.on( 'column-reorder', function ( e, settings, details ) {
        table.draw();
    } );

    /*
     * Charts
     */

    // Need to hide datatables when changing tabs for fixedHeader
    var visible = true;
    var tableContainer = $(table.table().container());

    // Bootstrap tab shown event
    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {

        tableContainer.css( 'display', visible ? 'none' : 'block' );
        table.fixedHeader.adjust();

        visible = ! visible;

        $("#charts").hide();
        $("#loading-charts").show();

        $.get('data/charts.json', function(data) {

            $("#loading-charts").hide();
            $("#charts").show();

            // Pie
            c3.generate(data.mapinfos);
            c3.generate(data.mapshots);
            c3.generate(data.maps);
            c3.generate(data.radars);
            c3.generate(data.waypoints);
            c3.generate(data.licenses);

            // Scatter
            var filesizes = {
                axis: { x: { show: false }, rotated: true },
                tooltip: {
                    format: {
                        title: function (x) { return; },
                        name: function (name, ratio, id, index) { return "size"; },
                        value: function (value, ratio, id, index) { return bytesToSize(value); }
                    }
                }
            };

            $.extend(filesizes, data.filesizes);
            c3.generate(filesizes);

            // Line
            c3.generate(data.mapsbyyear);

        });

    });

} );

function bytesToSize(bytes) {
   var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
   if (bytes == 0) return '0 Byte';
   var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
   return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
};

<|endoftext|>


<commit_before>var times = ['6am', '8am', '9am', '10am', '11am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm'];

var appendBody = document.getElementById('append-table-row');
var wholeTable = document.getElementById('whole-table');

var stores = [];

function getRandomIntInclusive(min,max){
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function storeLocation(name, min, max, avgCooksPerCustomer){
  this.name = name;
  this.min = min;
  this.max = max;
  this.avgCooksPerCustomer = avgCooksPerCustomer;
  this.arrayA = [];
  this.storeCount = 0;
  this.avgPurchasePerHr = function(){
    for(var i = 0; i < times.length - 1; i++) {
      var randomInt = getRandomIntInclusive(this.min,this.max);
      var results = Math.floor(randomInt * this.avgCooksPerCustomer);
      this.arrayA.push(results);
      this.storeCount += results;
    };
  };
  this.avgPurchasePerHr();
}

function makeLocationRow(storeObj){
  var tr = document.createElement('tr');
  var th = document.createElement('th');
  th.textContent = storeObj.name;
  tr.appendChild(th);
  for(var i = 0; i < storeObj.arrayA.length; i++){
    var td = document.createElement('td');
    td.textContent = storeObj.arrayA[i];
    tr.appendChild(td);
  }
  var td = document.createElement('td');
  td.textContent = storeObj.storeCount;
  tr.appendChild(td);
  appendBody.appendChild(tr);
}

stores.push(new storeLocation('Pike Place',17,88,5.2));
stores.push(new storeLocation('Seatac Airport',6,24,1.2));
stores.push(new storeLocation('Southcenter',11,38,1.9));
stores.push(new storeLocation('Bellevue Square',20,48,3.3));
stores.push(new storeLocation('Alki',3,24,2.6));

for(var i = 0; i < stores.length; i++) {
  makeLocationRow(stores[i]);
}

var salesForm = document.getElementById('submission_form');

function handleFormInputs(event){
  event.preventDefault();

  var location = event.target.storLocation.value;
  var minCusty = event.target.minCustomer.value;
  var maxCusty = event.target.maxCustomer.value;
  var avgCusty = event.target.avgCustomer.value;
  var storeFound = false;

  for(var i = 0; i < stores.length; i++){
    if(location === stores[i].name){
      stores[i].min = minCusty;
      stores[i].max = maxCusty;
      stores[i].avgCooksPerCustomer = avgCusty;
      storeFound = true;
    }
  }
  if(storeFound === true){
    console.log(appendBody);
    var tableBody = document.getElementById('append-table-row');
    wholeTable.innerHTML = '';
    for(var i = 0; i < stores.length; i++){
      makeLocationRow(stores[i]);
    }
  }

  if(!storeFound){
    var newObj = new storeLocation(location,minCusty,maxCusty,avgCusty);
    stores.push(newObj);
    makeLocationRow(newObj);
  }
}

salesForm.addEventListener('submit', handleFormInputs);
<commit_msg>lets try this again<commit_after>var times = ['6am', '8am', '9am', '10am', '11am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm'];

var appendBody = document.getElementById('append-table-row');
var wholeTable = document.getElementById('whole-table');

var stores = [];

function getRandomIntInclusive(min,max){
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function storeLocation(name, min, max, avgCooksPerCustomer){
  this.name = name;
  this.min = min;
  this.max = max;
  this.avgCooksPerCustomer = avgCooksPerCustomer;
  this.arrayA = [];
  this.storeCount = 0;
  this.avgPurchasePerHr = function(){
    for(var i = 0; i < times.length - 1; i++) {
      var randomInt = getRandomIntInclusive(this.min,this.max);
      var results = Math.floor(randomInt * this.avgCooksPerCustomer);
      this.arrayA.push(results);
      this.storeCount += results;
    };
  };
  this.avgPurchasePerHr();
}

function makeLocationRow(storeObj){
  var tr = document.createElement('tr');
  var th = document.createElement('th');
  th.textContent = storeObj.name;
  tr.appendChild(th);
  for(var i = 0; i < storeObj.arrayA.length; i++){
    var td = document.createElement('td');
    td.textContent = storeObj.arrayA[i];
    tr.appendChild(td);
  }
  var td = document.createElement('td');
  td.textContent = storeObj.storeCount;
  tr.appendChild(td);
  console.log('tr ' + tr);
  appendBody.appendChild(tr);
}

stores.push(new storeLocation('Pike Place',17,88,5.2));
stores.push(new storeLocation('Seatac Airport',6,24,1.2));
stores.push(new storeLocation('Southcenter',11,38,1.9));
stores.push(new storeLocation('Bellevue Square',20,48,3.3));
stores.push(new storeLocation('Alki',3,24,2.6));

for(var i = 0; i < stores.length; i++) {
  makeLocationRow(stores[i]);
}

var salesForm = document.getElementById('submission_form');

function handleFormInputs(event){
  event.preventDefault();

  var location = event.target.storLocation.value;
  var minCusty = event.target.minCustomer.value;
  var maxCusty = event.target.maxCustomer.value;
  var avgCusty = event.target.avgCustomer.value;
  var storeFound = false;

  for(var i = 0; i < stores.length; i++){
    if(location === stores[i].name){
      stores[i].min = minCusty;
      stores[i].max = maxCusty;
      stores[i].avgCooksPerCustomer = avgCusty;
      storeFound = true;
    }
  }
  if(storeFound === true){
    console.log(appendBody);
    var tableBody = document.getElementById('append-table-row');
    appendBody.innerHTML = '';
    for(var i = 0; i < stores.length; i++){
      console.log('the table loop fired',i);
      makeLocationRow(stores[i]);
    }
  }

  if(!storeFound){
    var newObj = new storeLocation(location,minCusty,maxCusty,avgCusty);
    stores.push(newObj);
    makeLocationRow(newObj);
  }
}

salesForm.addEventListener('submit', handleFormInputs);
<|endoftext|>


<commit_before>var app = angular.module('chatApp', ['ngRoute']);

var ath;
var socket = io();

app.controller('ChatCtrl', ['$scope', '$http', '$timeout', '$location', function($scope, $http, $timeout, $location){
	if(!ath){
		$location.path('/');
	}
	$scope.chatItems = [];

	$scope.send = function(){
		var msg = $scope.message;
		if(msg){
			var d = new Date();
			///$scope.chatItems.push({author: ath.getName(), text: msg, date: d.getTime()});
			socket.emit('chat message', {author: ath.getName(), text: msg, date: d.getTime()});
			$scope.message = '';
		}

	};

	$scope.enter = function($event){
		$event.keyCode === 13 ? $scope.send() : 0;
	};

	socket.on('chat message', function(data){
		$scope.chatItems.push(data);
		$scope.message = '';
		$scope.$apply();
	});
}]);

app.controller('WelcomeCtrl', ['$scope', '$location', function($scope, $location){
	$scope.go = function(path) {
		if($scope.username){
			ath = (function() {
				var name = $scope.username;
				return {
					getName : function(){
						return name;
					}
				};
			})();
			$location.path(path);
		}
	}

	$scope.enter = function($event){
		$event.keyCode === 13 ? $scope.go('/chat') : 0;
	};
}])

app.directive('chatItem', function(){
	// Runs during compile
	return {
		restrict: 'E',
		templateUrl: 'temp/chatItem.html',
	};
});

app.directive('scroller', function() {
	return {
		 priority: 1,
		 restrict: 'A',
		link: function($scope, iElm, iAttrs, controller) {
			$scope.$watchCollection('chatItems', function() {
				//console.log('scrolling down...');
				iElm.scrollTop(iElm[0].scrollHeight);
			});
		}
	};
});

app.config(['$routeProvider',
	function($routeProvider) {
		$routeProvider.
			when('/',{
				templateUrl: 'temp/welcome.html',
				controller: 'WelcomeCtrl'
			}).
			when('/chat', {
				templateUrl: 'temp/chat.html',
				controller: 'ChatCtrl'
			}).
			otherwise({redirectTo: '/'});
}]);

<commit_msg>minor improvement, works allright now :3<commit_after>var app = angular.module('chatApp', ['ngRoute']);

var ath;
var socket = io();

app.controller('ChatCtrl', ['$scope', '$http', '$timeout', '$location', function($scope, $http, $timeout, $location){
	if(!ath){
		$location.path('/');
	}
	$scope.chatItems = [];

	$scope.send = function(){
		var msg = $scope.message;
		if(msg){
			var d = new Date();
			///$scope.chatItems.push({author: ath.getName(), text: msg, date: d.getTime()});
			socket.emit('chat message', {author: ath.getName(), text: msg, date: d.getTime()});
			$scope.message = '';
		}

	};

	$scope.enter = function($event){
		$event.keyCode === 13 ? $scope.send() : 0;
	};

	socket.on('chat message', function(data){
		$scope.chatItems.push(data);
		//$scope.message = '';
		$scope.$apply();
	});
}]);

app.controller('WelcomeCtrl', ['$scope', '$location', function($scope, $location){
	$scope.go = function(path) {
		if($scope.username){
			ath = (function() {
				var name = $scope.username;
				return {
					getName : function(){
						return name;
					}
				};
			})();
			$location.path(path);
		}
	}

	$scope.enter = function($event){
		$event.keyCode === 13 ? $scope.go('/chat') : 0;
	};
}])

app.directive('chatItem', function(){
	// Runs during compile
	return {
		restrict: 'E',
		templateUrl: 'temp/chatItem.html',
	};
});

app.directive('scroller', function() {
	return {
		 priority: 1,
		 restrict: 'A',
		link: function($scope, iElm, iAttrs, controller) {
			$scope.$watchCollection('chatItems', function() {
				//console.log('scrolling down...');
				iElm.scrollTop(iElm[0].scrollHeight);
			});
		}
	};
});

app.config(['$routeProvider',
	function($routeProvider) {
		$routeProvider.
			when('/',{
				templateUrl: 'temp/welcome.html',
				controller: 'WelcomeCtrl'
			}).
			when('/chat', {
				templateUrl: 'temp/chat.html',
				controller: 'ChatCtrl'
			}).
			otherwise({redirectTo: '/'});
}]);

<|endoftext|>