<commit_before>---

---
"use strict";
var grid;
var row;
var changes = [];
var values;
var Territory;
var Territories;
var columns
var rowNum;
var territories
function backgridTable(data){
   "use strict";
   $('#example-1-result').empty()
  	Territory = Backbone.Model.extend({});
    
  	Territories = Backbone.Collection.extend({
      comparator: 'index',
  	  model: Territory
  	});
    // console.log(JSON.stringify(data))
    $.each(data, function(i, row){
      row.index = i + 1
    })
  	territories = new Territories(data);
    var i = 0
    
  	columns = [
    {
      name: "index",
      label: "#",
      cell: "integer",
      editable: false, 
      // 
      sortable: false
    },
    {
      name: "Phase",
      label: "Phase",
      cell: 
      Backgrid.SelectCell.extend({
      // It's possible to render an option group or use a
      // function to provide option values too.
        optionValues: 
        [["PE", "PE"], ["CST", "CST"], ["SCP", "SCP"], ["ROW", "ROW"], ["UTL", "UTL"], ["ALL", "ALL"], ["PE-OV", "PE-OV"]]
      }),
      // editable: false,  false], [
      editable: edit,
      sortable: false
    },
    {
      name: "Auth",
      label: "Auth",
      cell: "string",
      editable: edit,
      sortable: false
    },
    {
      name: "FY",
      label: "FY",
      cell: "string",
      editable: edit,
      sortable: false
    },
    {
      name: "FundSource",
      label: "FundSource",
      cell: Backgrid.SelectCell.extend({
      // It's possible to render an option group or use a
      // function to provide option values too.
        optionValues:
      [["STP - Urban (>200K) (ARC) ", "STP - Urban (>200K) (ARC) "],
      ["Congestion Mitigation & Air Quality Improvement (CMAQ)", "Congestion Mitigation & Air Quality Improvement (CMAQ)"],
      ["Congestion Mitigation/Air Quality (100%)", "Congestion Mitigation/Air Quality (100%)"],
      ["STP - Enhancements", "STP - Enhancements"],
      ["Recreational Trails Program", "Recreational Trails Program"],
      ["National Highway Performance Program (NHPP)", "National Highway Performance Program (NHPP)"],
      ["STP - Statewide Flexible (GDOT)", "STP - Statewide Flexible (GDOT)"],
      ["National Highway Performance Program (NHPP) Exempt", "National Highway Performance Program (NHPP) Exempt"],
      ["Railway-Highway - Hazard Elimination", "Railway-Highway - Hazard Elimination"],
      ["Highway Safety Improvement Program (HSIP)", "Highway Safety Improvement Program (HSIP)"],
      ["Railway-Highway - Protective Devices", "Railway-Highway - Protective Devices"],
      ["State of Georgia", "State of Georgia"],
      ["National Highway System", "National Highway System"],
      ["Transit Fund (21533)", "Transit Fund (21533)"],
      ["STP - Urban (>200K) (ARC)", "STP - Urban (>200K) (ARC)"],
      ["New Starts", "New Starts"],
      ["Local Sources - PPP", "Local Sources - PPP"],
      ["Private Sources - PPP", "Private Sources - PPP"],
      ["State Sources - PPP", "State Sources - PPP"],
      ["Local Jurisdiction/Municipality Funds", "Local Jurisdiction/Municipality Funds"],
      ["TIGER V Discretionary Grant ", "TIGER V Discretionary Grant "],
      ["TAP - Urban (>200K) (ARC)", "TAP - Urban (>200K) (ARC)"],
      ["Transit Urbanized Area Formula Program", "Transit Urbanized Area Formula Program"],
      ["Rail Modern - Fixed Guideway (80/20)", "Rail Modern - Fixed Guideway (80/20)"],
      ["Enhanced Mobility of Seniors and Individuals with Disabilities", "Enhanced Mobility of Seniors and Individuals with Disabilities"],
      ["Transit Nonurbanized Area Formula", "Transit Nonurbanized Area Formula"],
      ["Job Access and Reverse Commute", "Job Access and Reverse Commute"],
      ["New Freedom", "New Freedom"],
      ["State of Good Repair Grants", "State of Good Repair Grants"],
      ["Bus and Bus Facilities Program", "Bus and Bus Facilities Program"],
      ["Transit Project Bond (2007) - State", "Transit Project Bond (2007) - State"],
      ["GRTA Funds (46001)", "GRTA Funds (46001)"],
      ["Bus - New (80/20)", "Bus - New (80/20)"],
      ["State Bonds", "State Bonds"],
      ["Toll Revenue Bonds", "Toll Revenue Bonds"],
      ["Interstate Maintenance", "Interstate Maintenance"],
      ["Fuel Funds", "Fuel Funds"],
      ["SAFETEA-LU Earmark", "SAFETEA-LU Earmark"],
      ["OTHER", "OTHER"],
      ["Public Private Partnership", "Public Private Partnership"],
      ["TIFIA Loan", "TIFIA Loan"],
      ["GRV BONDS (GARVEE Bond Program)", "GRV BONDS (GARVEE Bond Program)"],
      ["Bridge (Off-System)", "Bridge (Off-System)"],
      ["General Federal Aid - 2018-2040", "General Federal Aid - 2018-2040"],
      ["Bridge (On-System)", "Bridge (On-System)"],
      ["Transportation, Community and System Preservation", "Transportation, Community and System Preservation"],
      ["Surface Transportation Priorities (Earmark)", "Surface Transportation Priorities (Earmark)"],
      ["Public Land Discretionary", "Public Land Discretionary"],
      ["Georgia Transportation Infrastructure Bank", "Georgia Transportation Infrastructure Bank"],
      ["Transportation Enhancement", "Transportation Enhancement"],
      ["High Priority Projects from TEA-21", "High Priority Projects from TEA-21"],
      ["Federal Earmark Funding", "Federal Earmark Funding"],
      ["Federal Earmark", "Federal Earmark"],
      ["Certain Safety Projects (GRC)", "Certain Safety Projects (GRC)"],
      ["Bridge Discretionary", "Bridge Discretionary"],
      ["Congestion Mitigation and Air Quality", "Congestion Mitigation and Air Quality"],
      ["GA Department of Transportation Funds", "GA Department of Transportation Funds"],
      ["STP - Off-System Bridge", "STP - Off-System Bridge"],
      ["Clean Fuels Formula Program", "Clean Fuels Formula Program"],
      ["State of Good Repair Grant (5337)", "State of Good Repair Grant (5337)"],
      ["ARRA - Urban (>200K) (ARC)", "ARRA - Urban (>200K) (ARC)"],
      ["Appalachian Local Access", "Appalachian Local Access"]]
}),
      editable: edit,
      sortable: false
    },
    {
      name: "Federal",
      label: "Federal",
      cell: "string",
      editable: edit,
      sortable: false
    },
    {
      name: "State",
      label: "State",
      cell: "string",
      editable: edit,
      sortable: false
    },
    {
      name: "Local",
      label: "Local",
      cell: "string",
      editable: edit,
      sortable: false
    },
    {
      name: "Bond",
      label: "Bond",
      cell: "string",
      editable: edit,
      sortable: false
    },
    {
      name: "Total",
      label: "Total",
      cell: "string",
      editable: edit,
      sortable: false
    }];
  // Suppose you want to highlight the entire row when an editable field is focused
  var FocusableRow = Backgrid.Row.extend({
    highlightColor: 'lightYellow',
    events: {
      focusin: 'rowFocused',
      focusout: 'rowLostFocus'
    },
    rowFocused: function() {
      this.$el.css('background-color', this.highlightColor);
      // $('#delete-row').removeAttr('disabled')
      row = this
    },
    rowLostFocus: function() {
      this.$el.removeAttr('style');

      // $('#delete-row').attr('disabled', 'disabled')

      // Goofy way to handle the 
      // setTimeout(function(){
      //   row = undefined
      // }, 1000) 
    }
  });

  // Initialize a new Grid instance
  grid = new Backgrid.Grid({
    row: FocusableRow, // <-- Tell the Body class to use FocusableRow to render rows.
    columns: columns,
    collection: territories
  });
  var count = 0;
  grid.collection.on('backgrid:edited', function(model, selected) { 
     var field = selected.attributes.name
     var previous = model._previousAttributes[field]
     var current = model.attributes[field]
     var id = model.attributes['ARCID']
     var lineNumber = model.attributes.index + 1
     // console.log(lineNumber)
     console.log(selected)
     console.log(model)
     // These first two if statements need some work!
     if (previous === undefined && current === '')
        console.log("nothing changed!")
     else if (previous === undefined)
        console.log("nothing changed!")
     else if (previous != current){
        var message = model.attributes['Phase'] + " phase <strong>"+field+"</strong> changed from <em>"+previous+"</em> to <em>"+current +"</em>"
        console.log()
        var issueMessage = "* [" + strip(message) + "](https://github.com/landonreed/plan-it/blob/gh-pages/data/TIP/individual/"+ id +".csv#L" + lineNumber + ")"
        changes.push(newChange("edit-" + field, model, message, issueMessage))
        updateMessages(changes, false)
        $('.change').removeAttr('disabled')
        count++
     }
  });
  // Render the grid and attach the root to your HTML document
  grid.collection = grid.collection.sort("index", "descending")
  $("#example-1-result").append(grid.render().$el);

  // Fetch some countries from the url
  // territories.fetch({reset: true});
}

(function($) {
      
        var app = $.sammy('#proj', function() {
      //    this.get('#/', function(context) {
        //     context.log('Yo yo yo');
        // });
        this.get('{{ site.baseurl }}/data/#/:id', function() {
        // alert(this.params['name']);
        id = this.params['id']
        if (id !== '')
          $('#project-splash').hide()
        document.title = id + " {{ page.title }} | Plan-It"
        $('#'+id+'-link').closest('tr').addClass(color).siblings().removeClass(color);
        
        
        $('#history').empty()
        $('#edit-message').hide()
        grabD3Data(id)
        grid.remove()
        changes = []
        $('.change').attr('disabled', 'disabled')
      });
        });
        $(function() {
          app.run('#/');
        });
      
      })(jQuery);
var messages = []
var tables = {}
var edit = false
  $(document).ready(function(){
    var url = window.location.href
    var hash = _.last(url.split('/'))
    console.log(hash)
    if (hash === ''){
      $('#project-splash').show()
    }
    $('#' + hash + '-row').addClass('active')
    // runFilter()
    // $("#new-phase-form").validate({
    //   rules: {
    //             "new-phase-type": "required",
    //             "new-fund-source": {
    //               required: true,
    //               minlength: 1
    //             }
    //           },
    //           highlight: function(element) {
    //             console.log("highlight")
    //             $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
    //           },
    //           success: function(element) {
    //             console.log("success")
    //             element
    //             .closest('.form-group').removeClass('has-error').addClass('has-success');
                
    //           },
    //           submitHandler: function(form){
    //             addPhase();
    //           }
              
    // });
    
  })
  $('#issue-title').tooltip({title:'don\'t change this!'})
  $('#begin-edits').tooltip({title:'Click to toggle editing mode'})
  // $('.tooltip').tooltip()
  $('#myTab a').click(function (e) {
    e.preventDefault()
    $(this).tab('show')
  })
  $('#project-pill a').click(function (e) {
    e.preventDefault()
    $(this).tab('show')
  })
  $('#issues-tab').click(function () {
    console.log("issues tab")
    if($('#issue-list').is(':empty')){
      $.get("https://api.github.com/repos/landonreed/plan-it/issues?", function (issues) {
        console.log(issues)
        $.each(issues, function(i, issue){
          $("#issue-list").append('<p><a href="'+issue.user.url+'" title="'+issue.user.login+'"><img src="'+issue.user.avatar_url+'" height="30" width="30"></a> <a href="' + issue.url + '">' + issue.title + '' + '</a></p><p>'+issue.body+'</p>');
        })
      });
    }
  })
  var previous;
  var id;
  var historyClick = false
    $("select").focus(function () {
        // Store the current value on focus and on change
        previous = this.value;
    })

  var router = new Router().init();
  $('.fiscal-year').change(function(){
    var value = $('.fiscal-year').val()
    if (value != previous){
      $('#issue-title').attr('placeholder', id + ': change fiscal year from ' + previous + ' to ' + value)
      $('.issue').attr("disabled", true)
      $('#delay').attr('disabled', false)
    }
    else{
      $('#issue-title').attr('placeholder', id)
      $('.issue').attr("disabled", false)
    }

  })
  $('td').live('click', function(){
    var col = $(this).parent().children().index($(this));
    var row = $(this).parent().parent().children().index($(this).parent());
    // alert('Row: ' + parseInt(row+2) + ', Column: ' + col);
    rowNum = parseInt(row+2)
  });
  $('.issue').click(function(){
    var title = ($('#issue-title').val()) ? $('#issue-title').val() : $('#issue-title').attr('placeholder')
    var body = ($('#issue-body').val()) ? $('#issue-body').val() : ''

    // Properly transmit new lines to github issues
    body = body.replace(/\n/g, '%0A');
    body = body.replace(/#/g, '%23');
    window.location='https://github.com/landonreed/plan-it/issues/new?title='+title+'&body='+body+'&labels='+this.id
  })
  $('#begin-edits').click(function(){
    edit = !edit
    if(edit){
      $('.edit').fadeIn(250)
      $('#begin-edits').addClass('active')
    }
    else{
      $('.edit').fadeOut(250)
      $('#begin-edits').removeClass('active')
    }
    $.each(grid.columns.models, function(i, col){
      if (col.attributes.name !== "index")
        col.attributes.editable = ! col.attributes.editable
    })
  })
  // $('.btn').button()
  $('#issueModal').on('hidden.bs.modal', function () {
    $('#submit-issue').text('Submit')
    $('#submit-issue').removeAttr('disabled')
    $('#issue-modal-success').hide()
  })
  $('#submit-issue').click(function(){
    $(this).text('Submitted')
    $(this).attr('disabled','disabled')

    var title = ($('#issue-title').val()) ? $('#issue-title').val() : $('#issue-title').attr('placeholder')
    var body = ($('#issue-body').val()) ? $('#issue-body').val() : ''
    var comments = $('#issue-comments').val()
    if (comments !== ""){
      comments = "**Comments**\n"+comments
      body = body + '\n\n' + comments
    }
    // Properly transmit new lines to github issues ***only for sending in old method!
    // body = body.replace(/\n/g, '%0A');
    // body = body.replace(/#/g, '%23');

    // Old method sends user to issues page
    // window.location='https://github.com/landonreed/plan-it/issues/new?title='+title+'&body='+body// +'&labels='+this.id

    // New method creates an issue directly!
    // Code to create a new issue
    var url = 'https://api.github.com/repos/landonreed/plan-it/issues?access_token='+$.cookie('token')
    var data = JSON.stringify({
      "title": title, 
      "body": body
    })
    // $.post("https://api.github.com/repos/landonreed/plan-it/git/refs", data, function(data){console.log(data)})
    var repo = github.getRepo('landonreed', 'plan-it');
    var newHead = 'landonreed-tester-1'
    repo.show(function(err, repo) {console.log(repo)});
    var copy = grid.collection.slice();
    
    // removes index attribute from grid.collection copy
    // $.each(copy, function(i, row){
    //   delete row.attributes["index"]; 
    //   console.log(row)

    // })

    // convert json to csv
    
    repo.write(newHead, 'data/TIP/individual/'+id+'.csv', 'test data!!!', JSON2CSV(copy), function(err) {
      var pull = {
        "title": title,
        "body": body,
        "base": "gh-pages",
        "head": newHead
      };
      repo.createPullRequest(pull, function(err, pullRequest) {
        $(this).button('reset')
        console.log(data)
        $.each(changes, function(i, change){undoChange()})
        $('#issue-modal-title').html('Success!')
        $('#modal-edits').hide()
        $('#issue-modal-success').show()
        $('#issue-modal-success-link').html('See your issue <a href="' + pullRequest.html_url + '">here</a>.')  
      });
    });
    
    // $.post(url, data, function(data){
      

    //   // $('#issueModal').modal('hide')
      
    // })
  })
  $('#save').click(function(){
    $('#issue-tab').trigger({
      type: "click"
    })<commit_msg>added error logging<commit_after>---

---
"use strict";
var grid;
var row;
var changes = [];
var values;
var Territory;
var Territories;
var columns
var rowNum;
var territories
function backgridTable(data){
   "use strict";
   $('#example-1-result').empty()
  	Territory = Backbone.Model.extend({});
    
  	Territories = Backbone.Collection.extend({
      comparator: 'index',
  	  model: Territory
  	});
    // console.log(JSON.stringify(data))
    $.each(data, function(i, row){
      row.index = i + 1
    })
  	territories = new Territories(data);
    var i = 0
    
  	columns = [
    {
      name: "index",
      label: "#",
      cell: "integer",
      editable: false, 
      // 
      sortable: false
    },
    {
      name: "Phase",
      label: "Phase",
      cell: 
      Backgrid.SelectCell.extend({
      // It's possible to render an option group or use a
      // function to provide option values too.
        optionValues: 
        [["PE", "PE"], ["CST", "CST"], ["SCP", "SCP"], ["ROW", "ROW"], ["UTL", "UTL"], ["ALL", "ALL"], ["PE-OV", "PE-OV"]]
      }),
      // editable: false,  false], [
      editable: edit,
      sortable: false
    },
    {
      name: "Auth",
      label: "Auth",
      cell: "string",
      editable: edit,
      sortable: false
    },
    {
      name: "FY",
      label: "FY",
      cell: "string",
      editable: edit,
      sortable: false
    },
    {
      name: "FundSource",
      label: "FundSource",
      cell: Backgrid.SelectCell.extend({
      // It's possible to render an option group or use a
      // function to provide option values too.
        optionValues:
      [["STP - Urban (>200K) (ARC) ", "STP - Urban (>200K) (ARC) "],
      ["Congestion Mitigation & Air Quality Improvement (CMAQ)", "Congestion Mitigation & Air Quality Improvement (CMAQ)"],
      ["Congestion Mitigation/Air Quality (100%)", "Congestion Mitigation/Air Quality (100%)"],
      ["STP - Enhancements", "STP - Enhancements"],
      ["Recreational Trails Program", "Recreational Trails Program"],
      ["National Highway Performance Program (NHPP)", "National Highway Performance Program (NHPP)"],
      ["STP - Statewide Flexible (GDOT)", "STP - Statewide Flexible (GDOT)"],
      ["National Highway Performance Program (NHPP) Exempt", "National Highway Performance Program (NHPP) Exempt"],
      ["Railway-Highway - Hazard Elimination", "Railway-Highway - Hazard Elimination"],
      ["Highway Safety Improvement Program (HSIP)", "Highway Safety Improvement Program (HSIP)"],
      ["Railway-Highway - Protective Devices", "Railway-Highway - Protective Devices"],
      ["State of Georgia", "State of Georgia"],
      ["National Highway System", "National Highway System"],
      ["Transit Fund (21533)", "Transit Fund (21533)"],
      ["STP - Urban (>200K) (ARC)", "STP - Urban (>200K) (ARC)"],
      ["New Starts", "New Starts"],
      ["Local Sources - PPP", "Local Sources - PPP"],
      ["Private Sources - PPP", "Private Sources - PPP"],
      ["State Sources - PPP", "State Sources - PPP"],
      ["Local Jurisdiction/Municipality Funds", "Local Jurisdiction/Municipality Funds"],
      ["TIGER V Discretionary Grant ", "TIGER V Discretionary Grant "],
      ["TAP - Urban (>200K) (ARC)", "TAP - Urban (>200K) (ARC)"],
      ["Transit Urbanized Area Formula Program", "Transit Urbanized Area Formula Program"],
      ["Rail Modern - Fixed Guideway (80/20)", "Rail Modern - Fixed Guideway (80/20)"],
      ["Enhanced Mobility of Seniors and Individuals with Disabilities", "Enhanced Mobility of Seniors and Individuals with Disabilities"],
      ["Transit Nonurbanized Area Formula", "Transit Nonurbanized Area Formula"],
      ["Job Access and Reverse Commute", "Job Access and Reverse Commute"],
      ["New Freedom", "New Freedom"],
      ["State of Good Repair Grants", "State of Good Repair Grants"],
      ["Bus and Bus Facilities Program", "Bus and Bus Facilities Program"],
      ["Transit Project Bond (2007) - State", "Transit Project Bond (2007) - State"],
      ["GRTA Funds (46001)", "GRTA Funds (46001)"],
      ["Bus - New (80/20)", "Bus - New (80/20)"],
      ["State Bonds", "State Bonds"],
      ["Toll Revenue Bonds", "Toll Revenue Bonds"],
      ["Interstate Maintenance", "Interstate Maintenance"],
      ["Fuel Funds", "Fuel Funds"],
      ["SAFETEA-LU Earmark", "SAFETEA-LU Earmark"],
      ["OTHER", "OTHER"],
      ["Public Private Partnership", "Public Private Partnership"],
      ["TIFIA Loan", "TIFIA Loan"],
      ["GRV BONDS (GARVEE Bond Program)", "GRV BONDS (GARVEE Bond Program)"],
      ["Bridge (Off-System)", "Bridge (Off-System)"],
      ["General Federal Aid - 2018-2040", "General Federal Aid - 2018-2040"],
      ["Bridge (On-System)", "Bridge (On-System)"],
      ["Transportation, Community and System Preservation", "Transportation, Community and System Preservation"],
      ["Surface Transportation Priorities (Earmark)", "Surface Transportation Priorities (Earmark)"],
      ["Public Land Discretionary", "Public Land Discretionary"],
      ["Georgia Transportation Infrastructure Bank", "Georgia Transportation Infrastructure Bank"],
      ["Transportation Enhancement", "Transportation Enhancement"],
      ["High Priority Projects from TEA-21", "High Priority Projects from TEA-21"],
      ["Federal Earmark Funding", "Federal Earmark Funding"],
      ["Federal Earmark", "Federal Earmark"],
      ["Certain Safety Projects (GRC)", "Certain Safety Projects (GRC)"],
      ["Bridge Discretionary", "Bridge Discretionary"],
      ["Congestion Mitigation and Air Quality", "Congestion Mitigation and Air Quality"],
      ["GA Department of Transportation Funds", "GA Department of Transportation Funds"],
      ["STP - Off-System Bridge", "STP - Off-System Bridge"],
      ["Clean Fuels Formula Program", "Clean Fuels Formula Program"],
      ["State of Good Repair Grant (5337)", "State of Good Repair Grant (5337)"],
      ["ARRA - Urban (>200K) (ARC)", "ARRA - Urban (>200K) (ARC)"],
      ["Appalachian Local Access", "Appalachian Local Access"]]
}),
      editable: edit,
      sortable: false
    },
    {
      name: "Federal",
      label: "Federal",
      cell: "string",
      editable: edit,
      sortable: false
    },
    {
      name: "State",
      label: "State",
      cell: "string",
      editable: edit,
      sortable: false
    },
    {
      name: "Local",
      label: "Local",
      cell: "string",
      editable: edit,
      sortable: false
    },
    {
      name: "Bond",
      label: "Bond",
      cell: "string",
      editable: edit,
      sortable: false
    },
    {
      name: "Total",
      label: "Total",
      cell: "string",
      editable: edit,
      sortable: false
    }];
  // Suppose you want to highlight the entire row when an editable field is focused
  var FocusableRow = Backgrid.Row.extend({
    highlightColor: 'lightYellow',
    events: {
      focusin: 'rowFocused',
      focusout: 'rowLostFocus'
    },
    rowFocused: function() {
      this.$el.css('background-color', this.highlightColor);
      // $('#delete-row').removeAttr('disabled')
      row = this
    },
    rowLostFocus: function() {
      this.$el.removeAttr('style');

      // $('#delete-row').attr('disabled', 'disabled')

      // Goofy way to handle the 
      // setTimeout(function(){
      //   row = undefined
      // }, 1000) 
    }
  });

  // Initialize a new Grid instance
  grid = new Backgrid.Grid({
    row: FocusableRow, // <-- Tell the Body class to use FocusableRow to render rows.
    columns: columns,
    collection: territories
  });
  var count = 0;
  grid.collection.on('backgrid:edited', function(model, selected) { 
     var field = selected.attributes.name
     var previous = model._previousAttributes[field]
     var current = model.attributes[field]
     var id = model.attributes['ARCID']
     var lineNumber = model.attributes.index + 1
     // console.log(lineNumber)
     console.log(selected)
     console.log(model)
     // These first two if statements need some work!
     if (previous === undefined && current === '')
        console.log("nothing changed!")
     else if (previous === undefined)
        console.log("nothing changed!")
     else if (previous != current){
        var message = model.attributes['Phase'] + " phase <strong>"+field+"</strong> changed from <em>"+previous+"</em> to <em>"+current +"</em>"
        console.log()
        var issueMessage = "* [" + strip(message) + "](https://github.com/landonreed/plan-it/blob/gh-pages/data/TIP/individual/"+ id +".csv#L" + lineNumber + ")"
        changes.push(newChange("edit-" + field, model, message, issueMessage))
        updateMessages(changes, false)
        $('.change').removeAttr('disabled')
        count++
     }
  });
  // Render the grid and attach the root to your HTML document
  grid.collection = grid.collection.sort("index", "descending")
  $("#example-1-result").append(grid.render().$el);

  // Fetch some countries from the url
  // territories.fetch({reset: true});
}

(function($) {
      
        var app = $.sammy('#proj', function() {
      //    this.get('#/', function(context) {
        //     context.log('Yo yo yo');
        // });
        this.get('{{ site.baseurl }}/data/#/:id', function() {
        // alert(this.params['name']);
        id = this.params['id']
        if (id !== '')
          $('#project-splash').hide()
        document.title = id + " {{ page.title }} | Plan-It"
        $('#'+id+'-link').closest('tr').addClass(color).siblings().removeClass(color);
        
        
        $('#history').empty()
        $('#edit-message').hide()
        grabD3Data(id)
        grid.remove()
        changes = []
        $('.change').attr('disabled', 'disabled')
      });
        });
        $(function() {
          app.run('#/');
        });
      
      })(jQuery);
var messages = []
var tables = {}
var edit = false
  $(document).ready(function(){
    var url = window.location.href
    var hash = _.last(url.split('/'))
    console.log(hash)
    if (hash === ''){
      $('#project-splash').show()
    }
    $('#' + hash + '-row').addClass('active')
    // runFilter()
    // $("#new-phase-form").validate({
    //   rules: {
    //             "new-phase-type": "required",
    //             "new-fund-source": {
    //               required: true,
    //               minlength: 1
    //             }
    //           },
    //           highlight: function(element) {
    //             console.log("highlight")
    //             $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
    //           },
    //           success: function(element) {
    //             console.log("success")
    //             element
    //             .closest('.form-group').removeClass('has-error').addClass('has-success');
                
    //           },
    //           submitHandler: function(form){
    //             addPhase();
    //           }
              
    // });
    
  })
  $('#issue-title').tooltip({title:'don\'t change this!'})
  $('#begin-edits').tooltip({title:'Click to toggle editing mode'})
  // $('.tooltip').tooltip()
  $('#myTab a').click(function (e) {
    e.preventDefault()
    $(this).tab('show')
  })
  $('#project-pill a').click(function (e) {
    e.preventDefault()
    $(this).tab('show')
  })
  $('#issues-tab').click(function () {
    console.log("issues tab")
    if($('#issue-list').is(':empty')){
      $.get("https://api.github.com/repos/landonreed/plan-it/issues?", function (issues) {
        console.log(issues)
        $.each(issues, function(i, issue){
          $("#issue-list").append('<p><a href="'+issue.user.url+'" title="'+issue.user.login+'"><img src="'+issue.user.avatar_url+'" height="30" width="30"></a> <a href="' + issue.url + '">' + issue.title + '' + '</a></p><p>'+issue.body+'</p>');
        })
      });
    }
  })
  var previous;
  var id;
  var historyClick = false
    $("select").focus(function () {
        // Store the current value on focus and on change
        previous = this.value;
    })

  var router = new Router().init();
  $('.fiscal-year').change(function(){
    var value = $('.fiscal-year').val()
    if (value != previous){
      $('#issue-title').attr('placeholder', id + ': change fiscal year from ' + previous + ' to ' + value)
      $('.issue').attr("disabled", true)
      $('#delay').attr('disabled', false)
    }
    else{
      $('#issue-title').attr('placeholder', id)
      $('.issue').attr("disabled", false)
    }

  })
  $('td').live('click', function(){
    var col = $(this).parent().children().index($(this));
    var row = $(this).parent().parent().children().index($(this).parent());
    // alert('Row: ' + parseInt(row+2) + ', Column: ' + col);
    rowNum = parseInt(row+2)
  });
  $('.issue').click(function(){
    var title = ($('#issue-title').val()) ? $('#issue-title').val() : $('#issue-title').attr('placeholder')
    var body = ($('#issue-body').val()) ? $('#issue-body').val() : ''

    // Properly transmit new lines to github issues
    body = body.replace(/\n/g, '%0A');
    body = body.replace(/#/g, '%23');
    window.location='https://github.com/landonreed/plan-it/issues/new?title='+title+'&body='+body+'&labels='+this.id
  })
  $('#begin-edits').click(function(){
    edit = !edit
    if(edit){
      $('.edit').fadeIn(250)
      $('#begin-edits').addClass('active')
    }
    else{
      $('.edit').fadeOut(250)
      $('#begin-edits').removeClass('active')
    }
    $.each(grid.columns.models, function(i, col){
      if (col.attributes.name !== "index")
        col.attributes.editable = ! col.attributes.editable
    })
  })
  // $('.btn').button()
  $('#issueModal').on('hidden.bs.modal', function () {
    $('#submit-issue').text('Submit')
    $('#submit-issue').removeAttr('disabled')
    $('#issue-modal-success').hide()
  })
  $('#submit-issue').click(function(){
    $(this).text('Submitted')
    $(this).attr('disabled','disabled')

    var title = ($('#issue-title').val()) ? $('#issue-title').val() : $('#issue-title').attr('placeholder')
    var body = ($('#issue-body').val()) ? $('#issue-body').val() : ''
    var comments = $('#issue-comments').val()
    if (comments !== ""){
      comments = "**Comments**\n"+comments
      body = body + '\n\n' + comments
    }
    // Properly transmit new lines to github issues ***only for sending in old method!
    // body = body.replace(/\n/g, '%0A');
    // body = body.replace(/#/g, '%23');

    // Old method sends user to issues page
    // window.location='https://github.com/landonreed/plan-it/issues/new?title='+title+'&body='+body// +'&labels='+this.id

    // New method creates an issue directly!
    // Code to create a new issue
    var url = 'https://api.github.com/repos/landonreed/plan-it/issues?access_token='+$.cookie('token')
    var data = JSON.stringify({
      "title": title, 
      "body": body
    })
    // $.post("https://api.github.com/repos/landonreed/plan-it/git/refs", data, function(data){console.log(data)})
    var repo = github.getRepo('landonreed', 'plan-it');
    var newHead = 'landonreed-tester-1'
    repo.show(function(err, repo) {console.log(repo)});
    var copy = grid.collection.slice();

    // removes index attribute from grid.collection copy
    // $.each(copy, function(i, row){
    //   delete row.attributes["index"]; 
    //   console.log(row)

    // })

    // convert json to csv
    
    repo.write(newHead, 'data/TIP/individual/'+id+'.csv', 'test data!!!', JSON2CSV(copy), function(err) {
      console.log(err)
      var pull = {
        "title": title,
        "body": body,
        "base": "gh-pages",
        "head": newHead
      };
      repo.createPullRequest(pull, function(err, pullRequest) {
        $(this).button('reset')
        console.log(pullRequest)
        $.each(changes, function(i, change){undoChange()})
        $('#issue-modal-title').html('Success!')
        $('#modal-edits').hide()
        $('#issue-modal-success').show()
        $('#issue-modal-success-link').html('See your issue <a href="' + pullRequest.html_url + '">here</a>.')  
      });
    });
    
    // $.post(url, data, function(data){
      

    //   // $('#issueModal').modal('hide')
      
    // })
  })
  $('#save').click(function(){
    $('#issue-tab').trigger({
      type: "click"
    })
{'fraction_non_alphanumeric': 0.18969217561932794, 'fraction_numerical': 0.0082168260976208, 'mean_word_length': 2.604486683611449, 'pattern_counts': {'":': 16, '<': 39, '<?xml version=': 0, '>': 53, 'https://': 12, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2534291', 'n_tokens_mistral': 10283, 'n_tokens_neox': 9805, 'n_words': 2381}