<commit_before>var WebNES = function(nes) {
  this.nes = nes;
  this.audio = new webkitAudioContext();

  // Initialize screen context
  this.screen = document.getElementById('screen');
  this.canvasContext = this.screen.getContext('2d');
  this.canvasContext.fillStyle = 'black';
  this.canvasContext.fillRect(0, 0, 256, 240);

  // Initialize framebuffer
  this.canvasData = this.canvasContext.getImageData(0, 0, 256, 240);
  for (var i = 3; i < this.canvasData.data.length - 3; i += 4) {
      this.canvasData.data[i] = 0xFF;
  }

  // Unlock audio
  var self = this;

  window.addEventListener('touchstart', function() {
    var source = self.audio.createBufferSource();
    source.buffer = self.audio.createBuffer(1, 1, 22050);
    source.connect(self.audio.destination);
    source.start(0);
  });

  this.screen.addEventListener('click', onCanvasTouchStart, false);
};

function onCanvasTouchStart() {
  alert("working motherfucker")
}
WebNES.prototype = {
  updateStatus: function(status) {
    console.log('JSNES: ' + status);
  },
  writeFrame: function(buffer, prevBuffer) {
    var data = this.canvasData.data;
    for (var i = 0; i < 256 * 240; i++) {
        var pixel = buffer[i];
        if (pixel != prevBuffer[i]) {
            var j = i * 4;
            data[j] = pixel & 0xFF;
            data[j + 1] = (pixel >> 8) & 0xFF;
            data[j + 2] = (pixel >> 16) & 0xFF;
            prevBuffer[i] = pixel;
        }
    }
    this.canvasContext.putImageData(this.canvasData, 0, 0);
  },
  writeAudio: function(leftSamples, rightSamples) {
  	var buffer = this.audio.createBuffer(2, leftSamples.length, this.nes.papu.sampleRate);
  	buffer.getChannelData(0).set(leftSamples);
    buffer.getChannelData(1).set(rightSamples);
    var source = this.audio.createBufferSource();
    source.buffer = buffer;
    source.connect(this.audio.destination);
    source.start(0);
  }
};

$(function() {
  var db = openDatabase('webnes', '1.0', 'Downloaded NES ROMs', 2 * 1024 * 1024);
  var nes = new JSNES({ 'ui': WebNES, fpsInterval: 2000, emulateSound: true });

  function renderItem(record) {
    var item = $('<li/>').text(record.name).attr('id', record.id);
    var alerted = false;
    var timeoutId = 0;
    item.mousedown(function() {
      alerted = false;
      timeoutId = window.setTimeout(function() {
        alerted = true;
        if (!confirm("Delete this ROM?")) return;
        db.transaction(function(tx){
          tx.executeSql('DELETE FROM roms WHERE id = ?', [record.id], function() {
            localStorage.removeItem(record.storage);
            item.remove();
          });
        });
      }, 1000);
    }).mouseup(function() {
      clearTimeout(timeoutId);
      if (alerted) return;
      $('#home').hide();
      $('#play').show();
      var rom = localStorage.getItem(record.storage);
      nes.loadRom(rom);
      nes.start();
    });

    return item;
  };

  db.transaction(function(tx) {
    tx.executeSql('CREATE TABLE IF NOT EXISTS roms (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, storage TEXT)');
    tx.executeSql('SELECT * FROM roms', [], function(tx, result) {
      for (var i = 0; i < result.rows.length; i++) {
        $('#scroll ul').append(renderItem(result.rows.item(i)));
      }
    });
  });

  $('#addROM').click(function() {
    Dropbox.choose({
      success: function(files) {
        $.ajax({
          type: 'GET',
          url: files[0].link,
          timeout: 3000,
          mimeType: 'text/plain; charset=x-user-defined',
          success: function(data) {
            var key = Math.random().toString(36).slice(2);
            localStorage.setItem(key, data);
            db.transaction(function(tx){
              tx.executeSql('INSERT INTO roms (id, name, storage) VALUES (?, ?, ?)', [null, files[0].name.replace('.nes', ''), key]);
              tx.executeSql('SELECT * FROM roms WHERE storage = ?', [key], function(tx, result) {
                $('#scroll ul').append(renderItem(result.rows.item(0)));
              });
            });
          }
        });
      },
      linkType: "direct",
      multiselect: false,
      extensions: ['.nes']
    });
  });

  //button functionality
  var x = new JSNES.Input();

  $("#portrait_up").click(function(e) {
    x.keyDown(38)
  });

  $("#portrait_right").click(function(e) {
    x.keyDown(39)
  });

  $("#portrait_down").click(function(e) {
    x.keyDown(40)
  });

  $("#portrait_left").click(function(e) {
    x.keyDown(37)
  });

  $("#portrait_select").click(function(e) {
    x.keyDown(17)
  });

  $("#portrait_start").click(function(e) {
    x.setButton(13, true)
  });

  $("#portrait_B").click(function(e) {
    x.keyDown(88)
  });

  $("#portrait_A").click(function(e) {
    x.keyDown(89)
  });
});

<commit_msg>Buttons work, motherfucker<commit_after>var WebNES = function(nes) {
  this.nes = nes;
  this.audio = new webkitAudioContext();

  // Initialize screen context
  this.screen = document.getElementById('screen');
  this.canvasContext = this.screen.getContext('2d');
  this.canvasContext.fillStyle = 'black';
  this.canvasContext.fillRect(0, 0, 256, 240);

  // Initialize framebuffer
  this.canvasData = this.canvasContext.getImageData(0, 0, 256, 240);
  for (var i = 3; i < this.canvasData.data.length - 3; i += 4) {
      this.canvasData.data[i] = 0xFF;
  }

  // Unlock audio
  var self = this;

  window.addEventListener('touchstart', function() {
    var source = self.audio.createBufferSource();
    source.buffer = self.audio.createBuffer(1, 1, 22050);
    source.connect(self.audio.destination);
    source.start(0);
  });

  this.screen.addEventListener('click', onCanvasTouchStart, false);
};

function onCanvasTouchStart() {
  alert("working motherfucker")
}
WebNES.prototype = {
  updateStatus: function(status) {
    console.log('JSNES: ' + status);
  },
  writeFrame: function(buffer, prevBuffer) {
    var data = this.canvasData.data;
    for (var i = 0; i < 256 * 240; i++) {
        var pixel = buffer[i];
        if (pixel != prevBuffer[i]) {
            var j = i * 4;
            data[j] = pixel & 0xFF;
            data[j + 1] = (pixel >> 8) & 0xFF;
            data[j + 2] = (pixel >> 16) & 0xFF;
            prevBuffer[i] = pixel;
        }
    }
    this.canvasContext.putImageData(this.canvasData, 0, 0);
  },
  writeAudio: function(leftSamples, rightSamples) {
  	var buffer = this.audio.createBuffer(2, leftSamples.length, this.nes.papu.sampleRate);
  	buffer.getChannelData(0).set(leftSamples);
    buffer.getChannelData(1).set(rightSamples);
    var source = this.audio.createBufferSource();
    source.buffer = buffer;
    source.connect(this.audio.destination);
    source.start(0);
  }
};

$(function() {
  var db = openDatabase('webnes', '1.0', 'Downloaded NES ROMs', 2 * 1024 * 1024);
  var nes = new JSNES({ 'ui': WebNES, fpsInterval: 2000, emulateSound: true });

  function renderItem(record) {
    var item = $('<li/>').text(record.name).attr('id', record.id);
    var alerted = false;
    var timeoutId = 0;
    item.mousedown(function() {
      alerted = false;
      timeoutId = window.setTimeout(function() {
        alerted = true;
        if (!confirm("Delete this ROM?")) return;
        db.transaction(function(tx){
          tx.executeSql('DELETE FROM roms WHERE id = ?', [record.id], function() {
            localStorage.removeItem(record.storage);
            item.remove();
          });
        });
      }, 1000);
    }).mouseup(function() {
      clearTimeout(timeoutId);
      if (alerted) return;
      $('#home').hide();
      $('#play').show();
      var rom = localStorage.getItem(record.storage);
      nes.loadRom(rom);
      nes.start();
    });

    return item;
  };

  db.transaction(function(tx) {
    tx.executeSql('CREATE TABLE IF NOT EXISTS roms (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, storage TEXT)');
    tx.executeSql('SELECT * FROM roms', [], function(tx, result) {
      for (var i = 0; i < result.rows.length; i++) {
        $('#scroll ul').append(renderItem(result.rows.item(i)));
      }
    });
  });

  $('#addROM').click(function() {
    Dropbox.choose({
      success: function(files) {
        $.ajax({
          type: 'GET',
          url: files[0].link,
          timeout: 3000,
          mimeType: 'text/plain; charset=x-user-defined',
          success: function(data) {
            var key = Math.random().toString(36).slice(2);
            localStorage.setItem(key, data);
            db.transaction(function(tx){
              tx.executeSql('INSERT INTO roms (id, name, storage) VALUES (?, ?, ?)', [null, files[0].name.replace('.nes', ''), key]);
              tx.executeSql('SELECT * FROM roms WHERE storage = ?', [key], function(tx, result) {
                $('#scroll ul').append(renderItem(result.rows.item(0)));
              });
            });
          }
        });
      },
      linkType: "direct",
      multiselect: false,
      extensions: ['.nes']
    });
  });

  var input = nes.input;
  var buttons = [ '#portrait_A', '#portrait_B', '#portrait_select','#portrait_start', '#portrait_up', '#portrait_down', '#portrait_left', '#portrait_right' ];
  buttons.forEach(function(selector) {
    $(selector).mousedown(function() {
      input.setButton(buttons.indexOf(selector), true);
    }).mouseup(function() {
      input.setButton(buttons.indexOf(selector), false);
    });
  });
});<|endoftext|>


<commit_before>window.addEvent('domready', function() {
  // Close button for alert messages
  $$('.alert-error, .alert-info, .alert-success').each(function(e) {
    var button = new Element('button', {
      type: 'button',
      html: '×',
      events: {
        click: function() {
          var fx = new Fx.Tween(this.parentNode, {
            property: 'opacity',
            onComplete: function() {
              this.parentNode.dispose();
            }.bind(this)
          });

          fx.start(1, 0);
        }
      }
    });

    button.inject(e, 'top');
  });

  { // Highlight current module
    var module = window.location.pathname;
    if (module == '/' || module == '/app_dev.php/') {
      module += 'news/';
    }

    $$('body > header nav li a').each(function(a) {
      var p = a.pathname;
      if (p == '/' || p == '/app_dev.php/') {
        p += 'news/';
      }

      if (p.startsWith(module)) {
        a.parentNode.addClass('active');
      }
    });
  }
});
<commit_msg>Fixed current module highlighting<commit_after>window.addEvent('domready', function() {
  // Close button for alert messages
  $$('.alert-error, .alert-info, .alert-success').each(function(e) {
    var button = new Element('button', {
      type: 'button',
      html: '×',
      events: {
        click: function() {
          var fx = new Fx.Tween(this.parentNode, {
            property: 'opacity',
            onComplete: function() {
              this.parentNode.dispose();
            }.bind(this)
          });

          fx.start(1, 0);
        }
      }
    });

    button.inject(e, 'top');
  });

  { // Highlight current module
    var module = window.location.pathname;
    if (module == '/' || module == '/app_dev.php/') {
      module += 'news/';
    }

    $$('body > header nav li a').each(function(a) {
      var p = a.pathname;
      if (p == '/' || p == '/app_dev.php/') {
        p += 'news/';
      }

      if (module.startsWith(p)) {
        a.parentNode.addClass('active');
      }
    });
  }
});
<|endoftext|>


<commit_before>/*****************************************************************************
 * FILE:    Manage Watersheds
 * DATE:    2/26/2015
 * AUTHOR:  Alan Snow
 * COPYRIGHT: (c) 2015 Brigham Young University
 * LICENSE: BSD 2-Clause
 *****************************************************************************/

/*****************************************************************************
 *                      LIBRARY WRAPPER
 *****************************************************************************/

var ERFP_MANAGE_WATERSHEDS = (function() {
    // Wrap the library in a package function
    "use strict"; // And enable strict mode for this library

    /************************************************************************
    *                      MODULE LEVEL / GLOBAL VARIABLES
    *************************************************************************/
    var m_uploading_data;

    /************************************************************************
    *                  INITIALIZATION / CONSTRUCTOR
    *************************************************************************/

    $(function() {
        //modlule variable
        m_uploading_data = false;
        //turn the select options into select2
        $(".data-store-select").each(function() {
            $(this).select2();
        });
        $(".geoserver-select").each(function() {
            $(this).select2();
        });

        //manage on change event for geoserver select
        $(".geoserver-select").change(function() {
            var geoserver_id = $(this).val();
            var row_container = $(this).parent().parent();
            if(geoserver_id == 1) {
                row_container.find('.bootstrap-switch-id-shp-upload-toggle').addClass('hidden');
                row_container.find('.shapefile').addClass('hidden');
                row_container.find('.kml').removeClass('hidden');
            } else {
                row_container.find('.bootstrap-switch-id-shp-upload-toggle').removeClass('hidden');
                if(row_container.find('#shp-upload-toggle').bootstrapSwitch('state')){
                    row_container.find('.shapefile').addClass('hidden');
                    row_container.find('.shapefile.upload').removeClass('hidden');
                } else {
                    row_container.find('.shapefile').removeClass('hidden');
                    row_container.find('.shapefile.upload').addClass('hidden');
                }
                row_container.find('.kml').addClass('hidden');
            }
        });
        //trigger change event to initialize page
        $(".geoserver-select").change();

        //show hide elements based on shape upload toggle selection
        $('.bootstrap-switch-id-shp-upload-toggle').on('switchChange.bootstrapSwitch', function(event, state) {
            var parent_row = $(this).parent().parent();
            if(state) {
                //show file upload
                parent_row.find('.shapefile').addClass('hidden');
                parent_row.find('.shapefile.upload').removeClass('hidden');
            } else {
                parent_row.find('.shapefile').removeClass('hidden');
                parent_row.find('.shapefile.upload').addClass('hidden');
            }

        });

        //handle the submit event
        $('.submit-update-watershed').click(function(){
            var safe_to_submit = {val: true};
            var parent_row = $(this).parent().parent().parent();
            //check data store input
            var watershed_id = parent_row.find('.watershed-id').text();
            var watershed_name = checkTableCellInputWithError(parent_row.find('.watershed-name'),safe_to_submit);
            var subbasin_name = checkTableCellInputWithError(parent_row.find('.subbasin-name'),safe_to_submit);
            var data_store_id = checkInputWithError(parent_row.find('.data-store-select'),safe_to_submit, true, true);
            var geoserver_id = checkInputWithError(parent_row.find('.geoserver-select'),safe_to_submit, true, true);
            //initialize values
            var geoserver_drainage_line_layer = "";
            var geoserver_catchment_layer = "";
            var geoserver_gage_layer = "";
            var kml_drainage_line_layer = "";
            var kml_catchment_layer = "";
            var kml_gage_layer = "";
            var drainage_line_shp_files = [];
            var catchment_shp_files = [];
            var gage_shp_files = [];
            var drainage_line_kml_file = null;
            var catchment_kml_file = null;
            var gage_kml_file = null;

            if(geoserver_id==1){
                //kml upload
                drainage_line_kml_file = parent_row.find('.drainage-line-kml-upload-input')[0].files[0];
                catchment_kml_file = parent_row.find('.catchment-kml-upload-input')[0].files[0];
                gage_kml_file = parent_row.find('.gage-kml-upload-input')[0].files[0];

            } else if (!parent_row.find('#shp-upload-toggle').bootstrapSwitch('state')) {
                //geoserver update
                geoserver_drainage_line_layer = checkTableCellInputWithError(parent_row.find('.geoserver-drainage-line-input'),safe_to_submit);
                geoserver_catchment_layer = parent_row.find('.geoserver-catchment-input').val(); //optional
                geoserver_gage_layer = parent_row.find('.geoserver-gage-input').val(); //optional
            } else {
                geoserver_drainage_line_layer = parent_row.find('.geoserver-drainage-line-input').val(); //optional if file uploaded
                geoserver_catchment_layer = parent_row.find('.geoserver-catchment-input').val(); //optional
                geoserver_gage_layer = parent_row.find('.geoserver-gage-input').val(); //optional
                //geoserver upload
                drainage_line_shp_files = parent_row.find('.drainage-line-shp-upload-input')[0].files;
                catchment_shp_files = parent_row.find('.catchment-shp-upload-input')[0].files;
                gage_shp_files = parent_row.find('.gage-shp-upload-input')[0].files;
            }

            //submit if it form is ok
            if(safe_to_submit.val && !m_uploading_data) {
                if (window.confirm("You Are you sure? You will delete prediction files " +
                    "if the watershed or subbasin name are changed.")) {

                    var submit_button = $(this);
                    var submit_button_html = submit_button.html();
                    //give user information
                    addInfoMessage("Submiting data. Please be patient! "+
                                   "This may take a few minutes due to downloading prediction datasets.");
                    submit_button.text('Submitting ...');
                    //update database
                    if(geoserver_id==1 || parent_row.find('#shp-upload-toggle').bootstrapSwitch('state')){
                        //local upload
                        var data = new FormData();
                        data.append("watershed_id",watershed_id);
                        data.append("watershed_name",watershed_name);
                        data.append("subbasin_name",subbasin_name);
                        data.append("data_store_id",data_store_id);
                        data.append("geoserver_id",geoserver_id);
                        data.append("geoserver_drainage_line_layer",geoserver_drainage_line_layer);
                        data.append("geoserver_catchment_layer",geoserver_catchment_layer);
                        data.append("geoserver_gage_layer",geoserver_gage_layer);
                        data.append("drainage_line_kml_file",drainage_line_kml_file);
                        data.append("catchment_kml_file",catchment_kml_file);
                        data.append("gage_kml_file",gage_kml_file);
                        for(var i = 0; i < drainage_line_shp_files.length; i++) {
                            data.append("drainage_line_shp_file",drainage_line_shp_files[i]);
                        }
                        for(var i = 0; i < catchment_shp_files.length; i++) {
                            data.append("catchment_shp_file",catchment_shp_files[i]);
                        }
                        for(var i = 0; i < gage_shp_files.length; i++) {
                            data.append("gage_shp_file",gage_shp_files[i]);
                        }
                        var xhr = ajax_update_database_with_file("submit",data);
                    } else {
                        var data = {
                                watershed_id: watershed_id,
                                watershed_name: watershed_name,
                                subbasin_name: subbasin_name,
                                data_store_id: data_store_id,
                                geoserver_id: geoserver_id,
                                geoserver_drainage_line_layer: geoserver_drainage_line_layer,
                                geoserver_catchment_layer: geoserver_catchment_layer,
                                geoserver_gage_layer: geoserver_gage_layer,
                                };

                        var xhr = ajax_update_database("submit",data);
                    }
                    m_uploading_data = true;
                    xhr.done(function(data) {
                            parent_row.find('.drainage-line-layer').find('.help-block.upload').text('Current: ' + data['kml_drainage_line_layer']);
                            parent_row.find('.catchment-layer').find('.help-block.upload').text('Current: ' + data['kml_catchment_layer']);
                            parent_row.find('.gage-layer').find('.help-block.upload').text('Current: ' + data['kml_gage_layer']);
                        })
                       .always(function(){
                            submit_button.html(submit_button_html);
                            m_uploading_data = false;
                    });
                } //window confirm
            }  else if (m_uploading_data) {
                addWarningMessage("Submitting Data. Please Wait.");
            } else {
                addErrorMessage("Not submitted. Please fix form errors to proceed.");
            }

        });

        //handle the submit update event
        $('.submit-delete-watershed').click(function(){
            var data = {
                    watershed_id: $(this).parent().parent().parent()
                                    .find('.watershed-id').text(),
                    };
            //update database
            deleteRowData($(this),data);
        });
    }); //document ready
}()); // End of package wrapper
<commit_msg>Fixed typo in update message.<commit_after>/*****************************************************************************
 * FILE:    Manage Watersheds
 * DATE:    2/26/2015
 * AUTHOR:  Alan Snow
 * COPYRIGHT: (c) 2015 Brigham Young University
 * LICENSE: BSD 2-Clause
 *****************************************************************************/

/*****************************************************************************
 *                      LIBRARY WRAPPER
 *****************************************************************************/

var ERFP_MANAGE_WATERSHEDS = (function() {
    // Wrap the library in a package function
    "use strict"; // And enable strict mode for this library

    /************************************************************************
    *                      MODULE LEVEL / GLOBAL VARIABLES
    *************************************************************************/
    var m_uploading_data;

    /************************************************************************
    *                  INITIALIZATION / CONSTRUCTOR
    *************************************************************************/

    $(function() {
        //modlule variable
        m_uploading_data = false;
        //turn the select options into select2
        $(".data-store-select").each(function() {
            $(this).select2();
        });
        $(".geoserver-select").each(function() {
            $(this).select2();
        });

        //manage on change event for geoserver select
        $(".geoserver-select").change(function() {
            var geoserver_id = $(this).val();
            var row_container = $(this).parent().parent();
            if(geoserver_id == 1) {
                row_container.find('.bootstrap-switch-id-shp-upload-toggle').addClass('hidden');
                row_container.find('.shapefile').addClass('hidden');
                row_container.find('.kml').removeClass('hidden');
            } else {
                row_container.find('.bootstrap-switch-id-shp-upload-toggle').removeClass('hidden');
                if(row_container.find('#shp-upload-toggle').bootstrapSwitch('state')){
                    row_container.find('.shapefile').addClass('hidden');
                    row_container.find('.shapefile.upload').removeClass('hidden');
                } else {
                    row_container.find('.shapefile').removeClass('hidden');
                    row_container.find('.shapefile.upload').addClass('hidden');
                }
                row_container.find('.kml').addClass('hidden');
            }
        });
        //trigger change event to initialize page
        $(".geoserver-select").change();

        //show hide elements based on shape upload toggle selection
        $('.bootstrap-switch-id-shp-upload-toggle').on('switchChange.bootstrapSwitch', function(event, state) {
            var parent_row = $(this).parent().parent();
            if(state) {
                //show file upload
                parent_row.find('.shapefile').addClass('hidden');
                parent_row.find('.shapefile.upload').removeClass('hidden');
            } else {
                parent_row.find('.shapefile').removeClass('hidden');
                parent_row.find('.shapefile.upload').addClass('hidden');
            }

        });

        //handle the submit event
        $('.submit-update-watershed').click(function(){
            var safe_to_submit = {val: true};
            var parent_row = $(this).parent().parent().parent();
            //check data store input
            var watershed_id = parent_row.find('.watershed-id').text();
            var watershed_name = checkTableCellInputWithError(parent_row.find('.watershed-name'),safe_to_submit);
            var subbasin_name = checkTableCellInputWithError(parent_row.find('.subbasin-name'),safe_to_submit);
            var data_store_id = checkInputWithError(parent_row.find('.data-store-select'),safe_to_submit, true, true);
            var geoserver_id = checkInputWithError(parent_row.find('.geoserver-select'),safe_to_submit, true, true);
            //initialize values
            var geoserver_drainage_line_layer = "";
            var geoserver_catchment_layer = "";
            var geoserver_gage_layer = "";
            var kml_drainage_line_layer = "";
            var kml_catchment_layer = "";
            var kml_gage_layer = "";
            var drainage_line_shp_files = [];
            var catchment_shp_files = [];
            var gage_shp_files = [];
            var drainage_line_kml_file = null;
            var catchment_kml_file = null;
            var gage_kml_file = null;

            if(geoserver_id==1){
                //kml upload
                drainage_line_kml_file = parent_row.find('.drainage-line-kml-upload-input')[0].files[0];
                catchment_kml_file = parent_row.find('.catchment-kml-upload-input')[0].files[0];
                gage_kml_file = parent_row.find('.gage-kml-upload-input')[0].files[0];

            } else if (!parent_row.find('#shp-upload-toggle').bootstrapSwitch('state')) {
                //geoserver update
                geoserver_drainage_line_layer = checkTableCellInputWithError(parent_row.find('.geoserver-drainage-line-input'),safe_to_submit);
                geoserver_catchment_layer = parent_row.find('.geoserver-catchment-input').val(); //optional
                geoserver_gage_layer = parent_row.find('.geoserver-gage-input').val(); //optional
            } else {
                geoserver_drainage_line_layer = parent_row.find('.geoserver-drainage-line-input').val(); //optional if file uploaded
                geoserver_catchment_layer = parent_row.find('.geoserver-catchment-input').val(); //optional
                geoserver_gage_layer = parent_row.find('.geoserver-gage-input').val(); //optional
                //geoserver upload
                drainage_line_shp_files = parent_row.find('.drainage-line-shp-upload-input')[0].files;
                catchment_shp_files = parent_row.find('.catchment-shp-upload-input')[0].files;
                gage_shp_files = parent_row.find('.gage-shp-upload-input')[0].files;
            }

            //submit if it form is ok
            if(safe_to_submit.val && !m_uploading_data) {
                if (window.confirm("Are you sure? You will delete prediction files " +
                    "if the watershed or subbasin name are changed.")) {

                    var submit_button = $(this);
                    var submit_button_html = submit_button.html();
                    //give user information
                    addInfoMessage("Submiting data. Please be patient! "+
                                   "This may take a few minutes due to downloading prediction datasets.");
                    submit_button.text('Submitting ...');
                    //update database
                    if(geoserver_id==1 || parent_row.find('#shp-upload-toggle').bootstrapSwitch('state')){
                        //local upload
                        var data = new FormData();
                        data.append("watershed_id",watershed_id);
                        data.append("watershed_name",watershed_name);
                        data.append("subbasin_name",subbasin_name);
                        data.append("data_store_id",data_store_id);
                        data.append("geoserver_id",geoserver_id);
                        data.append("geoserver_drainage_line_layer",geoserver_drainage_line_layer);
                        data.append("geoserver_catchment_layer",geoserver_catchment_layer);
                        data.append("geoserver_gage_layer",geoserver_gage_layer);
                        data.append("drainage_line_kml_file",drainage_line_kml_file);
                        data.append("catchment_kml_file",catchment_kml_file);
                        data.append("gage_kml_file",gage_kml_file);
                        for(var i = 0; i < drainage_line_shp_files.length; i++) {
                            data.append("drainage_line_shp_file",drainage_line_shp_files[i]);
                        }
                        for(var i = 0; i < catchment_shp_files.length; i++) {
                            data.append("catchment_shp_file",catchment_shp_files[i]);
                        }
                        for(var i = 0; i < gage_shp_files.length; i++) {
                            data.append("gage_shp_file",gage_shp_files[i]);
                        }
                        var xhr = ajax_update_database_with_file("submit",data);
                    } else {
                        var data = {
                                watershed_id: watershed_id,
                                watershed_name: watershed_name,
                                subbasin_name: subbasin_name,
                                data_store_id: data_store_id,
                                geoserver_id: geoserver_id,
                                geoserver_drainage_line_layer: geoserver_drainage_line_layer,
                                geoserver_catchment_layer: geoserver_catchment_layer,
                                geoserver_gage_layer: geoserver_gage_layer,
                                };

                        var xhr = ajax_update_database("submit",data);
                    }
                    m_uploading_data = true;
                    xhr.done(function(data) {
                            parent_row.find('.drainage-line-layer').find('.help-block.upload').text('Current: ' + data['kml_drainage_line_layer']);
                            parent_row.find('.catchment-layer').find('.help-block.upload').text('Current: ' + data['kml_catchment_layer']);
                            parent_row.find('.gage-layer').find('.help-block.upload').text('Current: ' + data['kml_gage_layer']);
                        })
                       .always(function(){
                            submit_button.html(submit_button_html);
                            m_uploading_data = false;
                    });
                } //window confirm
            }  else if (m_uploading_data) {
                addWarningMessage("Submitting Data. Please Wait.");
            } else {
                addErrorMessage("Not submitted. Please fix form errors to proceed.");
            }

        });

        //handle the submit update event
        $('.submit-delete-watershed').click(function(){
            var data = {
                    watershed_id: $(this).parent().parent().parent()
                                    .find('.watershed-id').text(),
                    };
            //update database
            deleteRowData($(this),data);
        });
    }); //document ready
}()); // End of package wrapper
<|endoftext|>


<commit_before>'use strict';

var Sequelize = require('sequelize');
var diff = require('deep-diff').diff;
var jsdiff = require('diff');
var _ = require('lodash');
var helpers = require('./helpers');
var cls = require('continuation-local-storage');

var failHard = false;

exports.init = function (sequelize, optionsArg) {
  // In case that options is being parsed as a readonly attribute.
  var options = _.cloneDeep(optionsArg);
  var defaultAttributes = {
    documentId: 'documentId',
    revisionId: 'revisionId'
  };

  if (optionsArg.defaultAttributes) {
    if (optionsArg.defaultAttributes.documentId) {
      defaultAttributes.documentId = optionsArg.defaultAttributes.documentId;
    }
    if (optionsArg.defaultAttributes.revisionId) {
      defaultAttributes.revisionId = optionsArg.defaultAttributes.revisionId;
    }
  }

  // if no options are passed the function
  if (!options) {
    options = {};
  }
  // enable debug logging
  var debug = false;
  if (options.debug) {
    debug = options.debug;
  }

  // TODO: implement logging option
  var log = options.log || console.log;

  // show the current sequelize and options objects
  if (debug) {
    // log('sequelize object:');
    // log(sequelize);
    log('options object:');
    log(options);
  }

  // attribute name for revision number in the models
  if (!options.revisionAttribute) {
    options.revisionAttribute = "revision";
  }

  // fields we want to exclude from audit trails
  if (!options.exclude) {
    options.exclude = ["id", "createdAt", "updatedAt", "deletedAt", // if the model is paranoid
      "created_at", "updated_at", "deleted_at", options.revisionAttribute];
  }

  // model name for revision table
  if (!options.revisionModel) {
    options.revisionModel = "Revision";
  }

  // model name for revision changes tables
  if (!options.revisionChangeModel) {
    options.revisionChangeModel = "RevisionChange";
  }

  if (!options.enableRevisionChangeModel) {
    options.enableRevisionChangeModel = false;
  }
  // support UUID for postgresql
  if (options.UUID === undefined) {
    options.UUID = false;
  }

  // underscored created and updated attributes
  if (!options.underscored) {
    options.underscored = false;
  }

  if (!options.underscoredAttributes) {
    options.underscoredAttributes = false;
    options.defaultAttributes = defaultAttributes;
  } else {
    options.defaultAttributes = helpers.toUnderscored(defaultAttributes);
  }

  // To track the user that made the changes
  if (!options.userModel) {
    options.userModel = false;
  }

  // full revisions or compressed revisions (track only the difference in models)
  // default: full revisions
  if (!options.enableCompression) {
    options.enableCompression = false;
  }

  // add the column to the database if it doesn't exist
  if (!options.enableMigration) {
    options.enableMigration = false;
  }

  // enable strict diff
  // when true: 10 !== '10'
  // when false: 10 == '10'
  // default: true
  if (!options.enableStrictDiff) {
    options.enableStrictDiff = true;
  }

  var ns;
  if (options.continuationNamespace) {
    ns = cls.getNamespace(options.continuationNamespace);
    if (!ns) {
      ns = cls.createNamespace(options.continuationNamespace);
    }

    if (!options.continuationKey) {
      options.continuationKey = 'userId';
    }

    if (!options.extraDataContinuationKey) {
      options.extraDataContinuationKey = 'extraData';
    }
  }

  if (debug) {
    log('parsed options:');
    log(options);
  }

  // order in which sequelize processes the hooks
  // (1)
  // beforeBulkCreate(instances, options, fn)
  // beforeBulkDestroy(instances, options, fn)
  // beforeBulkUpdate(instances, options, fn)
  // (2)
  // beforeValidate(instance, options, fn)
  // (-)
  // validate
  // (3)
  // afterValidate(instance, options, fn)
  // - or -
  // validationFailed(instance, options, error, fn)
  // (4)
  // beforeCreate(instance, options, fn)
  // beforeDestroy(instance, options, fn)
  // beforeUpdate(instance, options, fn)
  // (-)
  // create
  // destroy
  // update
  // (5)
  // afterCreate(instance, options, fn)
  // afterDestroy(instance, options, fn)
  // afterUpdate(instance, options, fn)
  // (6)
  // afterBulkCreate(instances, options, fn)
  // afterBulkDestroy(instances, options, fn)
  // afterBulkUpdate(instances, options, fn)

  // Extend model prototype with "hasPaperTrail" function
  // Call model.hasPaperTrail() to enable revisions for model
  _.extend(sequelize.Model, {
    hasPaperTrail: function hasPaperTrail() {
      if (debug) {
        log('Enabling paper trail on', this.name);
      }

      this.attributes[options.revisionAttribute] = {
        type: Sequelize.INTEGER,
        defaultValue: 0
      };
      this.revisionable = true;
      this.refreshAttributes();

      if (options.enableMigration) {
        var tableName = this.getTableName();
        sequelize.getQueryInterface().describeTable(tableName).then(function (attributes) {
          if (!attributes[options.revisionAttribute]) {
            if (debug) {
              log('adding revision attribute to the database');
            }
            sequelize.getQueryInterface().addColumn(tableName, options.revisionAttribute, {
              type: Sequelize.INTEGER,
              defaultValue: 0
            }).then(function () {
              return null;
            }).catch(function (err) {
              log('something went really wrong..');
              log(err);
              return null;
            });
          }
          return null;
        });
      }

      this.addHook("beforeCreate", createBeforeHook('create'));
      this.addHook("beforeUpdate", createBeforeHook('update'));
      this.addHook("beforeDestroy", createBeforeHook('destroy'));
      this.addHook("afterCreate", createAfterHook('create'));
      this.addHook("afterUpdate", createAfterHook('update'));
      this.addHook("afterDestroy", createAfterHook('destroy'));

      // create association
      return this.hasMany(sequelize.models[options.revisionModel], {
        foreignKey: options.defaultAttributes.documentId,
        constraints: false,
        scope: {
          model: this.name
        }
      });
    }
  });

  function createBeforeHook(operation) {
    var beforeHook = function beforeHook(instance, opt) {
      if (debug) {
        log('beforeHook called');
        log('instance:');
        log(instance);
        log('opt:');
        log(opt);
      }

      var destroyOperation = operation === 'destroy';

      if (!destroyOperation && options.enableCompression) {
        var previousVersion = {};
        var currentVersion = {};

        _.forEach(opt.defaultFields, function (a) {
          const previousDataValuesOfA = instance._previousDataValues[a] === undefined ? null : instance._previousDataValues[a];
          previousVersion[a] = instance._previousDataValues[a];
          previousVersion[a] = instance._previousDataValues[a];
          currentVersion[a] = instance.dataValues[a];
          currentVersion[a] = instance.dataValues[a];
        });
      } else {
        var previousVersion = instance._previousDataValues;
        var currentVersion = instance.dataValues;
      }
      // Supported nested models.
      previousVersion = _.omitBy(previousVersion, function (i) {
        return typeof i === 'object'
      });
      currentVersion = _.omitBy(currentVersion, function (i) {
        return typeof i === 'object'
      });

      // Disallow change of revision
      instance.set(options.revisionAttribute, instance._previousDataValues[options.revisionAttribute]);

      // Get diffs
      var delta = helpers.calcDelta(previousVersion, currentVersion, options.exclude, options.enableStrictDiff);
      var currentRevisionId = instance.get(options.revisionAttribute);
      if (failHard && !currentRevisionId && opt.type === 'UPDATE') {
        throw new Error('Revision Id was undefined');
      }
      if (debug) {
        log('delta:');
        log(delta);
        log('revisionId', currentRevisionId);
      }

      if (destroyOperation || delta && delta.length > 0) {
        var revisionId = (currentRevisionId || 0) + 1;
        instance.set(options.revisionAttribute, revisionId);

        if (!instance.context) {
          instance.context = {};
        }
        instance.context.delta = delta;
      }
      if (debug) {
        log('end of beforeHook');
      }
    };
    return beforeHook;
  }

  function createAfterHook(operation) {
    var afterHook = function afterHook(instance, opt) {
      if (debug) {
        log('afterHook called');
        log('instance:', instance);
        log('opt:', opt);
        if (ns) {
          log(`CLS ${options.continuationKey}:`, ns.get(options.continuationKey));
          log(`CLS ${options.extraDataFields}:`, ns.get(options.extraDataContinuationKey));
        }
      }

      var destroyOperation = operation === 'destroy';

      if (instance.context && (instance.context.delta && instance.context.delta.length > 0 || destroyOperation)) {
        var Revision = sequelize.model(options.revisionModel);
        if (options.enableRevisionChangeModel) {
          var RevisionChange = sequelize.model(options.revisionChangeModel);
        }
        var delta = instance.context.delta;

        if (!destroyOperation && options.enableCompression) {
          var previousVersion = {};
          var currentVersion = {};

          _.forEach(opt.defaultFields, function (a) {
            previousVersion[a] = instance._previousDataValues[a];
            currentVersion[a] = instance.dataValues[a];
          });
        } else {
          var previousVersion = instance._previousDataValues;
          var currentVersion = instance.dataValues;
        }

        // Supported nested models.
        previousVersion = _.omitBy(previousVersion, function (i) {
          return typeof i === 'object'
        });
        currentVersion = _.omitBy(currentVersion, function (i) {
          return typeof i === 'object'
        });

        if (failHard && !ns.get(options.continuationKey)) {
          throw new Error('The CLS continuationKey ' + options.continuationKey + ' was not defined.');
        }

        var document = currentVersion;

        if (options.mysql) {
          document = JSON.stringify(document);
        }

        // Build revision
        var query = {
          model: this.name,
          document: document,
          userId: ns && ns.get(options.continuationKey) || opt['userId'],
          operation: operation
        };
        query[options.defaultAttributes.documentId] = instance.id;

        // Add all extra data fields to the query object
        if (options.extraDataFields) {
          var extraData = ns && ns.get(options.extraDataContinuationKey) || opt['extraData'];
          if (extraData) {
            _.forEach(options.extraDataFields, function (field) {
              var value = extraData[field];
              if (debug) {
                log(`Adding extraData field to Revision - ${field} => ${value}`);
              }
              if (!query.hasOwnProperty(field)) {
                query[field] = falue;
              } else {
                log(`Revision object already has a value at ${field} => ${query[field]}`);
                log('Not overwriting the original value');
              }
            });
          }
        }

        var revision = Revision.build(query);

        revision[options.revisionAttribute] = instance.get(options.revisionAttribute);

        // Save revision
        return revision.save({transaction: opt.transaction}).then(function (revision) {
          // Loop diffs and create a revision-diff for each
          if (options.enableRevisionChangeModel) {
            _.forEach(delta, function (difference) {
              var o = helpers.diffToString(difference.item ? difference.item.lhs : difference.lhs);
              var n = helpers.diffToString(difference.item ? difference.item.rhs : difference.rhs);

              var document = difference;
              var diff = o || n ? jsdiff.diffChars(o, n) : []

              if (options.mysql) {
                document = JSON.stringify(document);
                diff = JSON.stringify(diff)
              }

              var d = RevisionChange.build({
                path: difference.path[0],
                document: document,
                //revisionId: data.id,
                diff: diff
              });

              d.save({transaction: opt.transaction}).then(function (d) {
                // Add diff to revision
                revision['add' + helpers.capitalizeFirstLetter(options.revisionChangeModel)](d);

                return null;
              }).catch(function (err) {
                log('RevisionChange save error');
                log(err);
                throw err;
              });
            });
          }
          return null;
        }).catch(function (err) {
          log('Revision save error');
          log(err);
          throw err;
        });
      }

      if (debug) {
        log('end of afterHook');
      }
    };
    return afterHook;
  };

  return {
    // Return defineModels()
    defineModels: function defineModels(db) {
      var attributes = {
        model: {
          type: Sequelize.TEXT,
          allowNull: false
        },
        document: {
          type: Sequelize.JSON,
          allowNull: false
        },
        operation: Sequelize.STRING(7)
      };

      if (options.mysql) {
        attributes.document.type = Sequelize.TEXT('MEDIUMTEXT');
      }

      attributes[options.defaultAttributes.documentId] = {
        type: Sequelize.INTEGER,
        allowNull: false
      };

      attributes[options.revisionAttribute] = {
        type: Sequelize.INTEGER,
        allowNull: false
      };

      if (debug) {
        log('attributes');
        log(attributes);
      }
      if (options.UUID) {
        attributes.id = {
          primaryKey: true,
          type: Sequelize.UUID,
          defaultValue: Sequelize.UUIDV4
        };
        attributes[options.defaultAttributes.documentId].type = Sequelize.UUID;
      }
      // Revision model
      var Revision = sequelize.define(options.revisionModel, attributes, {
        underscored: options.underscored
      });
      Revision.associate = function associate(models) {
        Revision.belongsTo(sequelize.model(options.userModel), options.belongsToUserOptions);
      };

      attributes = {
        path: {
          type: Sequelize.TEXT,
          allowNull: false
        },
        document: {
          type: Sequelize.JSON,
          allowNull: false
        },
        diff: {
          type: Sequelize.JSON,
          allowNull: false
        }
      };
      if (options.mysql) {
        attributes.document.type = Sequelize.TEXT('MEDIUMTEXT');
        attributes.diff.type = Sequelize.TEXT('MEDIUMTEXT');
      }
      if (options.UUID) {
        attributes.id = {
          primaryKey: true,
          type: Sequelize.UUID,
          defaultValue: Sequelize.UUIDV4
        };
      }

      if (options.enableRevisionChangeModel) {
        // RevisionChange model
        var RevisionChange = sequelize.define(options.revisionChangeModel, attributes, {
          underscored: options.underscored
        });

        // Set associations
        Revision.hasMany(RevisionChange, {
          foreignKey: options.defaultAttributes.revisionId,
          constraints: false
        });

        RevisionChange.belongsTo(Revision);
        if (db) db[RevisionChange.name] = RevisionChange;
      }

      if (db) db[Revision.name] = Revision;

      if (options.userModel) {
        Revision.belongsTo(sequelize.model(options.userModel), options.belongsToUserOptions);
      }
      return Revision;
    }
  };
};

/**
 * Throw exceptions when the user identifier from CLS is not set or if the
 * revisionAttribute was not loaded on the model.
 */
exports.enableFailHard = function () {
  failHard = true;
},

module.exports = exports;
<commit_msg>:bug: Fix other typoes<commit_after>'use strict';

var Sequelize = require('sequelize');
var diff = require('deep-diff').diff;
var jsdiff = require('diff');
var _ = require('lodash');
var helpers = require('./helpers');
var cls = require('continuation-local-storage');

var failHard = false;

exports.init = function (sequelize, optionsArg) {
  // In case that options is being parsed as a readonly attribute.
  var options = _.cloneDeep(optionsArg);
  var defaultAttributes = {
    documentId: 'documentId',
    revisionId: 'revisionId'
  };

  if (optionsArg.defaultAttributes) {
    if (optionsArg.defaultAttributes.documentId) {
      defaultAttributes.documentId = optionsArg.defaultAttributes.documentId;
    }
    if (optionsArg.defaultAttributes.revisionId) {
      defaultAttributes.revisionId = optionsArg.defaultAttributes.revisionId;
    }
  }

  // if no options are passed the function
  if (!options) {
    options = {};
  }
  // enable debug logging
  var debug = false;
  if (options.debug) {
    debug = options.debug;
  }

  // TODO: implement logging option
  var log = options.log || console.log;

  // show the current sequelize and options objects
  if (debug) {
    // log('sequelize object:');
    // log(sequelize);
    log('options object:');
    log(options);
  }

  // attribute name for revision number in the models
  if (!options.revisionAttribute) {
    options.revisionAttribute = "revision";
  }

  // fields we want to exclude from audit trails
  if (!options.exclude) {
    options.exclude = ["id", "createdAt", "updatedAt", "deletedAt", // if the model is paranoid
      "created_at", "updated_at", "deleted_at", options.revisionAttribute];
  }

  // model name for revision table
  if (!options.revisionModel) {
    options.revisionModel = "Revision";
  }

  // model name for revision changes tables
  if (!options.revisionChangeModel) {
    options.revisionChangeModel = "RevisionChange";
  }

  if (!options.enableRevisionChangeModel) {
    options.enableRevisionChangeModel = false;
  }
  // support UUID for postgresql
  if (options.UUID === undefined) {
    options.UUID = false;
  }

  // underscored created and updated attributes
  if (!options.underscored) {
    options.underscored = false;
  }

  if (!options.underscoredAttributes) {
    options.underscoredAttributes = false;
    options.defaultAttributes = defaultAttributes;
  } else {
    options.defaultAttributes = helpers.toUnderscored(defaultAttributes);
  }

  // To track the user that made the changes
  if (!options.userModel) {
    options.userModel = false;
  }

  // full revisions or compressed revisions (track only the difference in models)
  // default: full revisions
  if (!options.enableCompression) {
    options.enableCompression = false;
  }

  // add the column to the database if it doesn't exist
  if (!options.enableMigration) {
    options.enableMigration = false;
  }

  // enable strict diff
  // when true: 10 !== '10'
  // when false: 10 == '10'
  // default: true
  if (!options.enableStrictDiff) {
    options.enableStrictDiff = true;
  }

  var ns;
  if (options.continuationNamespace) {
    ns = cls.getNamespace(options.continuationNamespace);
    if (!ns) {
      ns = cls.createNamespace(options.continuationNamespace);
    }

    if (!options.continuationKey) {
      options.continuationKey = 'userId';
    }

    if (!options.extraDataContinuationKey) {
      options.extraDataContinuationKey = 'extraData';
    }
  }

  if (debug) {
    log('parsed options:');
    log(options);
  }

  // order in which sequelize processes the hooks
  // (1)
  // beforeBulkCreate(instances, options, fn)
  // beforeBulkDestroy(instances, options, fn)
  // beforeBulkUpdate(instances, options, fn)
  // (2)
  // beforeValidate(instance, options, fn)
  // (-)
  // validate
  // (3)
  // afterValidate(instance, options, fn)
  // - or -
  // validationFailed(instance, options, error, fn)
  // (4)
  // beforeCreate(instance, options, fn)
  // beforeDestroy(instance, options, fn)
  // beforeUpdate(instance, options, fn)
  // (-)
  // create
  // destroy
  // update
  // (5)
  // afterCreate(instance, options, fn)
  // afterDestroy(instance, options, fn)
  // afterUpdate(instance, options, fn)
  // (6)
  // afterBulkCreate(instances, options, fn)
  // afterBulkDestroy(instances, options, fn)
  // afterBulkUpdate(instances, options, fn)

  // Extend model prototype with "hasPaperTrail" function
  // Call model.hasPaperTrail() to enable revisions for model
  _.extend(sequelize.Model, {
    hasPaperTrail: function hasPaperTrail() {
      if (debug) {
        log('Enabling paper trail on', this.name);
      }

      this.attributes[options.revisionAttribute] = {
        type: Sequelize.INTEGER,
        defaultValue: 0
      };
      this.revisionable = true;
      this.refreshAttributes();

      if (options.enableMigration) {
        var tableName = this.getTableName();
        sequelize.getQueryInterface().describeTable(tableName).then(function (attributes) {
          if (!attributes[options.revisionAttribute]) {
            if (debug) {
              log('adding revision attribute to the database');
            }
            sequelize.getQueryInterface().addColumn(tableName, options.revisionAttribute, {
              type: Sequelize.INTEGER,
              defaultValue: 0
            }).then(function () {
              return null;
            }).catch(function (err) {
              log('something went really wrong..');
              log(err);
              return null;
            });
          }
          return null;
        });
      }

      this.addHook("beforeCreate", createBeforeHook('create'));
      this.addHook("beforeUpdate", createBeforeHook('update'));
      this.addHook("beforeDestroy", createBeforeHook('destroy'));
      this.addHook("afterCreate", createAfterHook('create'));
      this.addHook("afterUpdate", createAfterHook('update'));
      this.addHook("afterDestroy", createAfterHook('destroy'));

      // create association
      return this.hasMany(sequelize.models[options.revisionModel], {
        foreignKey: options.defaultAttributes.documentId,
        constraints: false,
        scope: {
          model: this.name
        }
      });
    }
  });

  function createBeforeHook(operation) {
    var beforeHook = function beforeHook(instance, opt) {
      if (debug) {
        log('beforeHook called');
        log('instance:');
        log(instance);
        log('opt:');
        log(opt);
      }

      var destroyOperation = operation === 'destroy';

      if (!destroyOperation && options.enableCompression) {
        var previousVersion = {};
        var currentVersion = {};

        _.forEach(opt.defaultFields, function (a) {
          const previousDataValuesOfA = instance._previousDataValues[a] === undefined ? null : instance._previousDataValues[a];
          previousVersion[a] = instance._previousDataValues[a];
          previousVersion[a] = instance._previousDataValues[a];
          currentVersion[a] = instance.dataValues[a];
          currentVersion[a] = instance.dataValues[a];
        });
      } else {
        var previousVersion = instance._previousDataValues;
        var currentVersion = instance.dataValues;
      }
      // Supported nested models.
      previousVersion = _.omitBy(previousVersion, function (i) {
        return typeof i === 'object'
      });
      currentVersion = _.omitBy(currentVersion, function (i) {
        return typeof i === 'object'
      });

      // Disallow change of revision
      instance.set(options.revisionAttribute, instance._previousDataValues[options.revisionAttribute]);

      // Get diffs
      var delta = helpers.calcDelta(previousVersion, currentVersion, options.exclude, options.enableStrictDiff);
      var currentRevisionId = instance.get(options.revisionAttribute);
      if (failHard && !currentRevisionId && opt.type === 'UPDATE') {
        throw new Error('Revision Id was undefined');
      }
      if (debug) {
        log('delta:');
        log(delta);
        log('revisionId', currentRevisionId);
      }

      if (destroyOperation || delta && delta.length > 0) {
        var revisionId = (currentRevisionId || 0) + 1;
        instance.set(options.revisionAttribute, revisionId);

        if (!instance.context) {
          instance.context = {};
        }
        instance.context.delta = delta;
      }
      if (debug) {
        log('end of beforeHook');
      }
    };
    return beforeHook;
  }

  function createAfterHook(operation) {
    var afterHook = function afterHook(instance, opt) {
      if (debug) {
        log('afterHook called');
        log('instance:', instance);
        log('opt:', opt);
        if (ns) {
          log(`CLS ${options.continuationKey}:`, ns.get(options.continuationKey));
          log(`CLS ${options.extraDataFields}:`, ns.get(options.extraDataContinuationKey));
        }
      }

      var destroyOperation = operation === 'destroy';

      if (instance.context && (instance.context.delta && instance.context.delta.length > 0 || destroyOperation)) {
        var Revision = sequelize.model(options.revisionModel);
        if (options.enableRevisionChangeModel) {
          var RevisionChange = sequelize.model(options.revisionChangeModel);
        }
        var delta = instance.context.delta;

        if (!destroyOperation && options.enableCompression) {
          var previousVersion = {};
          var currentVersion = {};

          _.forEach(opt.defaultFields, function (a) {
            previousVersion[a] = instance._previousDataValues[a];
            currentVersion[a] = instance.dataValues[a];
          });
        } else {
          var previousVersion = instance._previousDataValues;
          var currentVersion = instance.dataValues;
        }

        // Supported nested models.
        previousVersion = _.omitBy(previousVersion, function (i) {
          return typeof i === 'object'
        });
        currentVersion = _.omitBy(currentVersion, function (i) {
          return typeof i === 'object'
        });

        if (failHard && !ns.get(options.continuationKey)) {
          throw new Error('The CLS continuationKey ' + options.continuationKey + ' was not defined.');
        }

        var document = currentVersion;

        if (options.mysql) {
          document = JSON.stringify(document);
        }

        // Build revision
        var query = {
          model: this.name,
          document: document,
          userId: ns && ns.get(options.continuationKey) || opt['userId'],
          operation: operation
        };
        query[options.defaultAttributes.documentId] = instance.id;

        // Add all extra data fields to the query object
        if (options.extraDataFields) {
          var extraData = ns && ns.get(options.extraDataContinuationKey) || opt['extraData'];
          if (extraData) {
            _.forEach(options.extraDataFields, function (field) {
              var value = extraData[field];
              if (debug) {
                log(`Adding extraData field to Revision - ${field} => ${value}`);
              }
              if (!query.hasOwnProperty(field)) {
                query[field] = value;
              } else if (debug) {
                log(`Revision object already has a value at ${field} => ${query[field]}`);
                log('Not overwriting the original value');
              }
            });
          }
        }

        var revision = Revision.build(query);

        revision[options.revisionAttribute] = instance.get(options.revisionAttribute);

        // Save revision
        return revision.save({transaction: opt.transaction}).then(function (revision) {
          // Loop diffs and create a revision-diff for each
          if (options.enableRevisionChangeModel) {
            _.forEach(delta, function (difference) {
              var o = helpers.diffToString(difference.item ? difference.item.lhs : difference.lhs);
              var n = helpers.diffToString(difference.item ? difference.item.rhs : difference.rhs);

              var document = difference;
              var diff = o || n ? jsdiff.diffChars(o, n) : []

              if (options.mysql) {
                document = JSON.stringify(document);
                diff = JSON.stringify(diff)
              }

              var d = RevisionChange.build({
                path: difference.path[0],
                document: document,
                //revisionId: data.id,
                diff: diff
              });

              d.save({transaction: opt.transaction}).then(function (d) {
                // Add diff to revision
                revision['add' + helpers.capitalizeFirstLetter(options.revisionChangeModel)](d);

                return null;
              }).catch(function (err) {
                log('RevisionChange save error');
                log(err);
                throw err;
              });
            });
          }
          return null;
        }).catch(function (err) {
          log('Revision save error');
          log(err);
          throw err;
        });
      }

      if (debug) {
        log('end of afterHook');
      }
    };
    return afterHook;
  };

  return {
    // Return defineModels()
    defineModels: function defineModels(db) {
      var attributes = {
        model: {
          type: Sequelize.TEXT,
          allowNull: false
        },
        document: {
          type: Sequelize.JSON,
          allowNull: false
        },
        operation: Sequelize.STRING(7)
      };

      if (options.mysql) {
        attributes.document.type = Sequelize.TEXT('MEDIUMTEXT');
      }

      attributes[options.defaultAttributes.documentId] = {
        type: Sequelize.INTEGER,
        allowNull: false
      };

      attributes[options.revisionAttribute] = {
        type: Sequelize.INTEGER,
        allowNull: false
      };

      if (debug) {
        log('attributes');
        log(attributes);
      }
      if (options.UUID) {
        attributes.id = {
          primaryKey: true,
          type: Sequelize.UUID,
          defaultValue: Sequelize.UUIDV4
        };
        attributes[options.defaultAttributes.documentId].type = Sequelize.UUID;
      }
      // Revision model
      var Revision = sequelize.define(options.revisionModel, attributes, {
        underscored: options.underscored
      });
      Revision.associate = function associate(models) {
        Revision.belongsTo(sequelize.model(options.userModel), options.belongsToUserOptions);
      };

      attributes = {
        path: {
          type: Sequelize.TEXT,
          allowNull: false
        },
        document: {
          type: Sequelize.JSON,
          allowNull: false
        },
        diff: {
          type: Sequelize.JSON,
          allowNull: false
        }
      };
      if (options.mysql) {
        attributes.document.type = Sequelize.TEXT('MEDIUMTEXT');
        attributes.diff.type = Sequelize.TEXT('MEDIUMTEXT');
      }
      if (options.UUID) {
        attributes.id = {
          primaryKey: true,
          type: Sequelize.UUID,
          defaultValue: Sequelize.UUIDV4
        };
      }

      if (options.enableRevisionChangeModel) {
        // RevisionChange model
        var RevisionChange = sequelize.define(options.revisionChangeModel, attributes, {
          underscored: options.underscored
        });

        // Set associations
        Revision.hasMany(RevisionChange, {
          foreignKey: options.defaultAttributes.revisionId,
          constraints: false
        });

        RevisionChange.belongsTo(Revision);
        if (db) db[RevisionChange.name] = RevisionChange;
      }

      if (db) db[Revision.name] = Revision;

      if (options.userModel) {
        Revision.belongsTo(sequelize.model(options.userModel), options.belongsToUserOptions);
      }
      return Revision;
    }
  };
};

/**
 * Throw exceptions when the user identifier from CLS is not set or if the
 * revisionAttribute was not loaded on the model.
 */
exports.enableFailHard = function () {
  failHard = true;
},

module.exports = exports;
<|endoftext|>


<commit_before>'use strict';

var express = require( 'express'),
    app = express.createServer(),
    crypto = require( 'crypto' ),
    fs = require( 'fs' ),
    exec = require( 'child_process' ).exec,
    path = require( 'path' ),
    querystring = require( 'querystring' ),
    regexp = require( './lib/regexp' ),
    requirejs = require( './lib/r.js' );

var repoBaseDir = process.env.REPO_BASE_DIR,
    workBaseDir = process.env.WORK_BASE_DIR;

app.configure('development', function(){
    app.use( express.errorHandler({ dumpExceptions: true, showStack: true }) );
});

app.configure('production', function(){
});

app.use(express.bodyParser());

app.get( '/', function ( req, res ) {
    res.send( "
ZOMG JQM-BUILDER
" );
});

app.get( '/:repo/fetch', function ( req, res ) {
    exec( "git fetch",
        {
            encoding:'utf8',
            timeout:0,
            cwd: bareRepo,
            env:null
        },
        function ( error, stdout, stderr ) {
            //console.log('stdout: ' + stdout);
            //console.log('stderr: ' + stderr);
            if ( error !== null ) {
                res.send( error, 500 );
            } else {
                res.send( stdout );
            }
        }
    );
});

app.post( '/post_receive', function ( req, res ) {
    var payload = req.body.payload;

    if ( payload ) {
        try {
            payload = JSON.parse( payload );

            if ( payload.repository && payload.repository.name ) {
                var repoDir = repoBaseDir + payload.repository.name + ".git";
                path.exists( repoDir , function( exists ) {
                    if ( exists ) {
                        exec( "git fetch",
                            {
                                encoding:'utf8',
                                timeout:0,
                                cwd: repoDir,
                                env:null
                            },
                            function ( error, stdout, stderr ) {
                                if ( error !== null ) {
                                    res.send( error, 500 );
                                } else {
                                    res.send( stdout );
                                }
                            }
                        );
                    } else {
                        res( "Wrong door!", 404 );
                    }
                });
            } else {
                res( "Wrong door!", 404 );
            }
        } catch( e ) {
            res.send( e, 500 );
        }
    } else {
        res.send( "No Payload!", 400 );
    }
});

app.get( '/:tag/checkout', function ( req, res ) {
    var dstDir = dstDirBase + req.params.tag;
    fs.mkdir( dstDir, function () {
        exec( "git --work-tree=" + dstDir + " checkout -f " + req.params.tag,
            {
                encoding:'utf8',
                timeout:0,
                cwd:bareRepo,
                env:null
            },
            function ( error, stdout, stderr ) {
                console.log( 'stdout: ' + stdout );
                console.log( 'stderr: ' + stderr );
                if ( error !== null ) {
                    res.send( error, 500 );
                } else {
                    res.send( stdout );
                }
            }
        );
    });
});

app.get( '/:repo/:tag/make', function ( req, res ) {
    var include = req.param( "include", "main" ).split( "," ).sort(),
        exclude = req.param( "exclude", "" ).split( "," ).sort(),
        optimize = req.param( "optimize", "none" ),
        baseUrl = req.param( "baseUrl", "." ),
        hasPragmas = !!req.param( "pragmas", false ),
        pragmas = hasPragmas?querystring.stringify( JSON.parse( req.param( "pragmas" ) ), ",", "=" ).split( "," ).map( function(val) { return "pragmas." + val; } ):[],
        hasPragmasOnSave = !!req.param( "pragmasOnSave", false ),
        pragmasOnSave = hasPragmasOnSave?querystring.stringify( JSON.parse( req.param( "pragmasOnSave" ) ), ",", "=" ).split( "," ).map( function(val) { return "pragmasOnSave." + val; } ):[],
        name = path.basename( req.param( "name", req.params.repo ), ".js" ),
        wsDir   = workBaseDir + "/" + req.params.repo + "." + req.params.tag,
        dstDir  = wsDir + "/compiled/" + include.join( "+" ),
        dstFile = dstDir + "/" + name + (optimize !== "none" ? ".min" : "") + ".js";

    path.exists( dstFile, function ( exists ) {
        if ( exists ) {
            res.download( dstFile, path.basename( dstFile ) );
        } else {
            exec( [ process.execPath,
                __dirname + '/node_modules/.bin/r.js',
                '-o',
                'baseUrl=' + baseUrl,
                'include=' + include.join( "," ),
                exclude?'exclude=' + exclude.join( "," ):"",
                'out=' + dstFile,
                'optimize=' + optimize ]
                .concat( pragmas )
                .concat( pragmasOnSave )
                .join( " " ),
                {
                    encoding:'utf8',
                    timeout:0,
                    cwd: wsDir,
                    env:null
                },
                function ( error, stdout, stderr ) {
                    console.log( 'stdout: ' + stdout );
                    console.log( 'stderr: ' + stderr );
                    if ( error !== null ) {
                        res.send( error, 500 );
                    } else {
                        res.download( dstFile, path.basename( dstFile ) );
                    }
                }
            );
        }
    });
});

app.get( '/:repo/:tag/dependencies', function ( req, res ) {
    var wsDir   = workBaseDir + "/" + req.params.repo + "." + req.params.tag,
        exclude = req.param( "exclude", "" ).split( "," ).sort(),
        names = path.basename( req.param( "names", req.params.repo ), ".js" ).split( "," ).sort(),
        baseUrl = wsDir + "/" + req.param( "baseUrl", "." ),
        shasum = crypto.createHash( 'sha1' ),
        filename = wsDir + "/deps-";

    // Generate a sha on the sorted names
    shasum.update( names.join( "," ) );
    filename += shasum.digest( 'hex' ) + ".json";

    path.exists( filename, function( exists ) {
        if ( exists ){
            res.sendfile( filename );
        } else {
            requirejs.tools.traceFiles( {
                    baseUrl: baseUrl,
                    modules: names.map( function( name ) { return { name: path.basename( name, ".js" ) } } ),
                    optimize: "none"
                },
                function( deps ) {
                    // Walk through the dep map and remove baseUrl and js extention
                    var module, baseUrlRE = new RegExp( "^" + regexp.escapeString( baseUrl ) );
                    for ( module in deps ) {
                        deps[ module ].files = deps[ module ].files.map(
                            function( file ) {
                                return path.basename( file.replace( baseUrlRE, "" ), ".js" );
                            })
                    }
                    fs.writeFile( filename, JSON.stringify( deps ),
                        function (err) {
                            if (err) throw err;
                        }
                    );
                    res.json( deps );
                }
            );
        }
    });
});

app.listen( process.env.NODE_HTTP_PORT || 80 );<commit_msg>console.log http port<commit_after>'use strict';

var express = require( 'express'),
    app = express.createServer(),
    crypto = require( 'crypto' ),
    fs = require( 'fs' ),
    exec = require( 'child_process' ).exec,
    path = require( 'path' ),
    querystring = require( 'querystring' ),
    regexp = require( './lib/regexp' ),
    requirejs = require( './lib/r.js' );

var httpPort = process.env.NODE_HTTP_PORT || 80,
    repoBaseDir = process.env.REPO_BASE_DIR,
    workBaseDir = process.env.WORK_BASE_DIR;

app.configure('development', function(){
    app.use( express.errorHandler({ dumpExceptions: true, showStack: true }) );
});

app.configure('production', function(){
});

app.use(express.bodyParser());

app.get( '/', function ( req, res ) {
    res.send( "
ZOMG JQM-BUILDER
" );
});

app.get( '/:repo/fetch', function ( req, res ) {
    exec( "git fetch",
        {
            encoding:'utf8',
            timeout:0,
            cwd: bareRepo,
            env:null
        },
        function ( error, stdout, stderr ) {
            //console.log('stdout: ' + stdout);
            //console.log('stderr: ' + stderr);
            if ( error !== null ) {
                res.send( error, 500 );
            } else {
                res.send( stdout );
            }
        }
    );
});

app.post( '/post_receive', function ( req, res ) {
    var payload = req.body.payload;

    if ( payload ) {
        try {
            payload = JSON.parse( payload );

            if ( payload.repository && payload.repository.name ) {
                var repoDir = repoBaseDir + payload.repository.name + ".git";
                path.exists( repoDir , function( exists ) {
                    if ( exists ) {
                        exec( "git fetch",
                            {
                                encoding:'utf8',
                                timeout:0,
                                cwd: repoDir,
                                env:null
                            },
                            function ( error, stdout, stderr ) {
                                if ( error !== null ) {
                                    res.send( error, 500 );
                                } else {
                                    res.send( stdout );
                                }
                            }
                        );
                    } else {
                        res( "Wrong door!", 404 );
                    }
                });
            } else {
                res( "Wrong door!", 404 );
            }
        } catch( e ) {
            res.send( e, 500 );
        }
    } else {
        res.send( "No Payload!", 400 );
    }
});

app.get( '/:tag/checkout', function ( req, res ) {
    var dstDir = dstDirBase + req.params.tag;
    fs.mkdir( dstDir, function () {
        exec( "git --work-tree=" + dstDir + " checkout -f " + req.params.tag,
            {
                encoding:'utf8',
                timeout:0,
                cwd:bareRepo,
                env:null
            },
            function ( error, stdout, stderr ) {
                console.log( 'stdout: ' + stdout );
                console.log( 'stderr: ' + stderr );
                if ( error !== null ) {
                    res.send( error, 500 );
                } else {
                    res.send( stdout );
                }
            }
        );
    });
});

app.get( '/:repo/:tag/make', function ( req, res ) {
    var include = req.param( "include", "main" ).split( "," ).sort(),
        exclude = req.param( "exclude", "" ).split( "," ).sort(),
        optimize = req.param( "optimize", "none" ),
        baseUrl = req.param( "baseUrl", "." ),
        hasPragmas = !!req.param( "pragmas", false ),
        pragmas = hasPragmas?querystring.stringify( JSON.parse( req.param( "pragmas" ) ), ",", "=" ).split( "," ).map( function(val) { return "pragmas." + val; } ):[],
        hasPragmasOnSave = !!req.param( "pragmasOnSave", false ),
        pragmasOnSave = hasPragmasOnSave?querystring.stringify( JSON.parse( req.param( "pragmasOnSave" ) ), ",", "=" ).split( "," ).map( function(val) { return "pragmasOnSave." + val; } ):[],
        name = path.basename( req.param( "name", req.params.repo ), ".js" ),
        wsDir   = workBaseDir + "/" + req.params.repo + "." + req.params.tag,
        dstDir  = wsDir + "/compiled/" + include.join( "+" ),
        dstFile = dstDir + "/" + name + (optimize !== "none" ? ".min" : "") + ".js";

    path.exists( dstFile, function ( exists ) {
        if ( exists ) {
            res.download( dstFile, path.basename( dstFile ) );
        } else {
            exec( [ process.execPath,
                __dirname + '/node_modules/.bin/r.js',
                '-o',
                'baseUrl=' + baseUrl,
                'include=' + include.join( "," ),
                exclude?'exclude=' + exclude.join( "," ):"",
                'out=' + dstFile,
                'optimize=' + optimize ]
                .concat( pragmas )
                .concat( pragmasOnSave )
                .join( " " ),
                {
                    encoding:'utf8',
                    timeout:0,
                    cwd: wsDir,
                    env:null
                },
                function ( error, stdout, stderr ) {
                    console.log( 'stdout: ' + stdout );
                    console.log( 'stderr: ' + stderr );
                    if ( error !== null ) {
                        res.send( error, 500 );
                    } else {
                        res.download( dstFile, path.basename( dstFile ) );
                    }
                }
            );
        }
    });
});

app.get( '/:repo/:tag/dependencies', function ( req, res ) {
    var wsDir   = workBaseDir + "/" + req.params.repo + "." + req.params.tag,
        exclude = req.param( "exclude", "" ).split( "," ).sort(),
        names = path.basename( req.param( "names", req.params.repo ), ".js" ).split( "," ).sort(),
        baseUrl = wsDir + "/" + req.param( "baseUrl", "." ),
        shasum = crypto.createHash( 'sha1' ),
        filename = wsDir + "/deps-";

    // Generate a sha on the sorted names
    shasum.update( names.join( "," ) );
    filename += shasum.digest( 'hex' ) + ".json";

    path.exists( filename, function( exists ) {
        if ( exists ){
            res.sendfile( filename );
        } else {
            requirejs.tools.traceFiles( {
                    baseUrl: baseUrl,
                    modules: names.map( function( name ) { return { name: path.basename( name, ".js" ) } } ),
                    optimize: "none"
                },
                function( deps ) {
                    // Walk through the dep map and remove baseUrl and js extention
                    var module, baseUrlRE = new RegExp( "^" + regexp.escapeString( baseUrl ) );
                    for ( module in deps ) {
                        deps[ module ].files = deps[ module ].files.map(
                            function( file ) {
                                return path.basename( file.replace( baseUrlRE, "" ), ".js" );
                            })
                    }
                    fs.writeFile( filename, JSON.stringify( deps ),
                        function (err) {
                            if (err) throw err;
                        }
                    );
                    res.json( deps );
                }
            );
        }
    });
});

console.log( "listening on port:", httpPort );
app.listen( httpPort );<|endoftext|>


<commit_before>var SLIDER = function(){
    window.requestAnimationFrame = window.requestAnimationFrame       ||
                                   window.webkitRequestAnimationFrame ||
                                   window.mozRequestAnimationFrame    ||
                                   function( callback ){window.setTimeout(callback, 1000 / 60)};
    var slides,
        transformName = 'transform';
    //Finds the relevant items and corrects classes and putts it all in an array
    var init = function(){
        requestAnimationFrame(function(){
            slides = [];
            slides.active = null;
            slides.parrent = {all: document.getElementById('slide'),
                              images:document.getElementById('slider-images'),
                              texts:document.getElementById('slider-info').getElementsByClassName('texts')[0]};
            var images = slides.parrent.images.children;
            var texts = slides.parrent.texts.children;

            for(var i=0;i<images.length || i<texts.length;i++){
                images[i].classList.remove('relative');
                images[i].sliderIndex = i;
                texts[i].classList.remove('vissible');

                if(images[i].classList.contains('active')){
                    if(slides.active===null)slides.active = i,texts[i].classList.add('vissible');
                    else images[i].classList.remove('active');
                }

                slides.push({image:images[i],text:texts[i]});
                if(i>=images.length || i>=texts.length){
                    if(i>=images.length)images[i].style.display = 'none';
                    if(i>=texts.length)texts[i].style.display = 'none';
                    console.warn('images and texts does not match. Removes overflow');
                }
            }
            if(!slides.active)slides.active = 0;
            slides.parrent.images.style.height = slides[slides.active].image.getBoundingClientRect().height + 'px';

            if('ontouchstart' in window)enableTouch(slides.parrent.all);

            console.log('I\'m running');
        });
    };
    var getActive = function(){return slides.parrent.images.getElementsByClassName('active')[0].sliderIndex};
    var goTo = function(pos, direction,startHere){
        var prev = getActive();
        var main = function(){
            if(!slides[pos])throw new Error('Slide not existing');
            slides[prev].image.classList.remove('active');
            slides[pos].image.classList.add('active');
            //Change size of container
            slides.parrent.images.style.height = slides[pos].image.getBoundingClientRect().height + 'px';

            //texts-stuff
            slides[prev].text.style[transformName] = 'translate('+(direction == 1 ? '-':'')+'150%, 0)';
            slides[pos].text.style[transformName] = 'translate(0, 0)';
        };
        var makeVissible = function(){
            slides[pos].text.classList.add('vissible');
            requestAnimationFrame(main);
        };
        if(startHere){
            requestAnimationFrame(makeVissible);
            return
        }

        slides[pos].text.classList.remove('vissible');
        requestAnimationFrame(function(){
            slides[pos].text.style[transformName] = 'translate('+(direction == 1 ? '':'-')+'150%, 0)';
            requestAnimationFrame(makeVissible);
        });
    };
    var next = function(){
        var pos=getActive()+1;
        if(pos>=slides.length)pos=0;
        goTo(pos,1);
    };
    var prev = function(){
        var pos=getActive()-1;
        if(pos<0)pos=slides.length-1;
        goTo(pos,0);
    };

    //Hej och hoj!
    var enableTouch = function(container){
        var startX,
            startY,
            start,
            timeThreshold = 0.8, //pixels per milisec
            lengthThreshold = 0.4, //length relative to screenwidth
            ratio = 3; //length/height;

        container.addEventListener('touchstart', function(e){
            startX = e.changedTouches[0].pageX;
            startY = e.changedTouches[0].pageY;
            start = e.timeStamp;
        }, false);

        container.addEventListener('touchend', function(e){
            var x = e.changedTouches[0].pageX-startX,
                y = e.changedTouches[0].pageY-startY,
                time = (e.timeStamp-start);

            if(((Math.abs(x)/time)>timeThreshold /*|| (Math.abs(x)-window.innerWidth*lengthThreshold)>0*/) && Math.abs(x/y)>ratio){
                if(x<0)next();
                else prev();
            }
        }, false);
    }

    return {init:init, goTo:goTo, next:next, prev:prev};
}();
window.onload=SLIDER.init;<commit_msg>Animations - basic support<commit_after>var SLIDER = function(){
    window.requestAnimationFrame = window.requestAnimationFrame       ||
                                   window.webkitRequestAnimationFrame ||
                                   window.mozRequestAnimationFrame    ||
                                   function( callback ){window.setTimeout(callback, 1000 / 60)};
    var slides,
        transformName = 'transform';
    //Finds the relevant items and corrects classes and putts it all in an array
    var init = function(){
        requestAnimationFrame(function(){
            slides = [];
            slides.active = null;
            slides.parent = {all: document.getElementById('slide'),
                              images:document.getElementById('slider-images'),
                              texts:document.getElementById('slider-info').getElementsByClassName('texts')[0]};
            var images = slides.parent.images.children;
            var texts = slides.parent.texts.children;

            for(var i=0;i<images.length || i<texts.length;i++){
                images[i].classList.remove('relative');
                images[i].sliderIndex = i;
                texts[i].classList.remove('vissible');
                texts[i].style[transformName] = 'translate(0%, 0)';

                if(images[i].classList.contains('active')){
                    if(slides.active===null)slides.active = i,texts[i].classList.add('vissible');
                    else images[i].classList.remove('active');
                }

                slides.push({image:images[i],text:texts[i]});
                if(i>=images.length || i>=texts.length){
                    if(i>=images.length)images[i].style.display = 'none';
                    if(i>=texts.length)texts[i].style.display = 'none';
                    console.warn('images and texts does not match. Removes overflow');
                }
            }
            if(!slides.active)slides.active = 0;
            slides.parent.images.style.height = slides[slides.active].image.getBoundingClientRect().height + 'px';

            if('ontouchstart' in window)enableTouch(slides.parent.all);
            window.addEventListener('keydown',function(e){
                switch(e.keyCode){
                    case 37:
                        prev();
                        break;
                    case 39:
                        next();
                        break;
                }
            },true);

            console.log('I\'m running');
        });
    };
    var getActive = function(){return slides.parent.images.getElementsByClassName('active')[0].sliderIndex};
    var place = function(pos, direction, val){
        slides[pos].text.style[transformName] = 'translate('+(direction == 1 ? '':'-')+(val||150)+'%, 0)';
    };
    var goTo = function(pos, direction,startHere){
        var prev = getActive();
        var main = function(){
            if(!slides[pos])throw new Error('Slide not existing');
            slides[prev].image.classList.remove('active');
            slides[pos].image.classList.add('active');
            //Change size of container
            slides.parent.images.style.height = slides[pos].image.getBoundingClientRect().height + 'px';

            //texts-stuff
            slides[prev].text.style[transformName] = 'translate('+(direction == 1 ? '-':'')+'150%, 0)';
            slides[pos].text.style[transformName] = 'translate(0%, 0)';
        };
        var makeVissible = function(){
            slides[pos].text.classList.add('vissible');
            requestAnimationFrame(main);
        };
        if(startHere){
            requestAnimationFrame(makeVissible);
            return
        }

        slides[pos].text.classList.remove('vissible');
        requestAnimationFrame(function(){
            place(pos,direction);
            requestAnimationFrame(makeVissible);
        });
    };
    var next = function(){
        var pos=getActive()+1;
        if(pos>=slides.length)pos=0;
        goTo(pos,1);
    };
    var prev = function(){
        var pos=getActive()-1;
        if(pos<0)pos=slides.length-1;
        goTo(pos,0);
    };

    //Hej och hoj!
    var enableTouch = function(container){
        var startX,
            startY,
            start,
            timeThreshold = 0.8, //pixels per milisec
            lengthThreshold = 0.4, //length relative to screenwidth
            ratio = 3, //length/height
            elmntPos = [];

        container.addEventListener('touchstart', function(e){
            startX = e.changedTouches[0].pageX;
            startY = e.changedTouches[0].pageY;
            start = e.timeStamp;

            elmntPos = [];
            for(var i=-1,j=getActive()-2;i<=1;i++){
                if(++j>=slides.length)j=0;
                else if(j<0)j=slides.length-1;
                elmntPos.push(j);
                if(i)place(j,i);
            }
            /*stuff(-150);
            place(i,0);
            stuff(0);
            stuff(150);
            place(i,1);*/

                //var match = new RegExp('translate\\(((?:-|)\\d+)%,').exec(slides[i].text.style[transformName]);
                //elmntPos.push({pos:parseInt((match[1]))});
            console.log(elmntPos);
        }, false);

        container.addEventListener('touchmove',function(e){
            //THIS NEEDS TO BE DONE WITH JS-ANIMATIONS
            /*requestAnimationFrame(function(){
                var x = e.changedTouches[0].pageX-startX;
                place(elmntPos[0],1,x-150);
                place(elmntPos[1],1,x);
                place(elmntPos[2],1,150-x);
                console.log('WE MOVAED!');
            });*/
        },false);

        container.addEventListener('touchend', function(e){
            var x = e.changedTouches[0].pageX-startX,
                y = e.changedTouches[0].pageY-startY,
                time = (e.timeStamp-start);

            if(((Math.abs(x)/time)>timeThreshold /*|| (Math.abs(x)-window.innerWidth*lengthThreshold)>0*/) && Math.abs(x/y)>ratio){
                if(x<0)next();
                else prev();
            }
        }, false);
    }

    return {init:init, goTo:goTo, next:next, prev:prev};
}();
window.onload=SLIDER.init;<|endoftext|>


<commit_before>'use strict';

var cssnext = require('gulp-cssnext');
var del = require('del');
var gulp = require('gulp');
var header = require('gulp-header');
var jshint = require('gulp-jshint');
var pkg = require('./package.json');
var rename = require('gulp-rename');
var runSequence = require('run-sequence');
var stylish = require('jshint-stylish');
var uglify = require('gulp-uglify');

var banner = [
'/*!',
' * <%= pkg.name %> v<%= pkg.version %>',
' * <%= pkg.description %>',
' * <%= pkg.homepage %>',
' * License : <%= pkg.license %>',
' * Author : <%= pkg.author %>',
' */',
''].join('\n');

var dirs = {
  src:'./src',
  dist:'./dist'
};

gulp.task('css', function () {
  return gulp
    .src(dirs.src + '/css/drawer.css')
    .pipe(header(banner, {
      pkg: pkg
    }))
    .pipe(cssnext({
      browsers: ['last 2 versions'],
      sourcemap: true
    }))
    .pipe(gulp.dest(dirs.dist + '/css'))
    .pipe(cssnext({
      compress: true,
      sourcemap: false
    }))
    .pipe(rename({ suffix: '.min' }))
    .pipe(gulp.dest(dirs.dist + '/css'));
});

gulp.task('js', function(){
  return gulp
    .src(dirs.src + '/js/drawer.js')
    .pipe(jshint())
    .pipe(jshint.reporter(stylish))
    .pipe(header(banner, { pkg:pkg }))
    .pipe(rename({prefix: 'jquery.'}))
    .pipe(gulp.dest(dirs.dist + '/js'))
    .pipe(uglify())
    .pipe(rename({suffix: '.min'}))
    .pipe(header(banner, { pkg:pkg }))
    .pipe(gulp.dest(dirs.dist + '/js'));
});

gulp.task('cleanup', function(){
  return del([ './dist' ]);
});

gulp.task('default',['build'], function(){
  gulp.watch(['./src/css/**/*.css'], ['css']);
  gulp.watch(['./src/js/*.js'], ['js']);
});

gulp.task('build', function(){
  runSequence(
    'cleanup',
    ['js'],
    'css'
  );
});
<commit_msg>add serve task & tweaks<commit_after>'use strict';

var browserSync = require('browser-sync');
var browserReload = browserSync.reload;
var cssnext = require('gulp-cssnext');
var del = require('del');
var gulp = require('gulp');
var header = require('gulp-header');
var jshint = require('gulp-jshint');
var pkg = require('./package.json');
var rename = require('gulp-rename');
var runSequence = require('run-sequence');
var stylish = require('jshint-stylish');
var uglify = require('gulp-uglify');
var banner = [
'/*!',
' * <%= pkg.name %> v<%= pkg.version %>',
' * <%= pkg.description %>',
' * <%= pkg.homepage %>',
' * License : <%= pkg.license %>',
' * Author : <%= pkg.author %>',
' */',
''].join('\n');

var dirs = {
  src:'./src',
  dist:'./dist',
  sandbox:'./sandbox'
};

gulp.task('css', function () {
  return gulp
    .src(dirs.src + '/css/drawer.css')
    .pipe(header(banner, {
      pkg: pkg
    }))
    .pipe(cssnext({
      browsers: ['last 2 versions'],
      sourcemap: true
    }))
    .pipe(gulp.dest(dirs.dist + '/css'))
    .pipe(cssnext({
      compress: true,
      sourcemap: false
    }))
    .pipe(rename({ suffix: '.min' }))
    .pipe(gulp.dest(dirs.dist + '/css'));
});

gulp.task('js', function(){
  return gulp
    .src(dirs.src + '/js/drawer.js')
    .pipe(jshint())
    .pipe(jshint.reporter(stylish))
    .pipe(header(banner, { pkg:pkg }))
    .pipe(rename({prefix: 'jquery.'}))
    .pipe(gulp.dest(dirs.dist + '/js'))
    .pipe(uglify())
    .pipe(rename({suffix: '.min'}))
    .pipe(header(banner, { pkg:pkg }))
    .pipe(gulp.dest(dirs.dist + '/js'));
});

gulp.task('cleanup', function(cb){
  return del([ dirs.dist ], cb);
});

gulp.task('serve', function() {
  browserSync.init({
    server: {
      baseDir: '.',
      index: dirs.sandbox + "/index.html"
    }
  });
  gulp.watch([ dirs.src + '/css/**/*.css'], ['css']);
  gulp.watch([ dirs.src + '/js/*.js'], ['js']);
  gulp.watch([
    dirs.dist + '/**/*.min.{css,js}',
    dirs.sandbox + '/*.{css,html}'
  ]).on('change', browserReload);
});

gulp.task('default', ['build'], function(cb) {
  runSequence('serve', cb);
});

gulp.task('build', ['cleanup'], function(cb){
  runSequence('js', 'css', cb);
});
<|endoftext|>