<commit_before>/* global QUnit, Oform */
$(function(){

  var w = window;

  w.beforeTest = false;

  var firstForm = new Oform({

    selector: '#form1',

    before: function(){

      w.beforeTest = true;

      return false;

    }

  });

  var secondForm = new Oform({

    selector: '#form2',

    errorHiddenClass: 'error-hidden-i',

    errorShownClass: 'error-show-i'

  });

  QUnit.test('initializations', function(){

    QUnit.expect(1);

    QUnit.assert.equal(secondForm.options.errorHiddenClass, 'error-hidden-i', 'instance override works');

  });

  QUnit.test('email validation', function(){

    var validEmails, invalidEmails, i;

    validEmails = [
      'kylerrush@gmail.com',
      'kylerrush+test@gmail.com',
      'kyle.r.rush@gmail.com'
    ];

    invalidEmails = [
      'kylerrush@gmail',
      '@gmail.com',
      '.kylerrush@gmail.com',
      'kylerrush.@gmail.com',
      'kylerrush@gmail..com',
      'kylerrush.gmail@com'
    ];

    QUnit.expect(validEmails.length + invalidEmails.length);

    for(i=0; i <= validEmails.length - 1; i++){

      QUnit.assert.ok(firstForm.options.validate.email(validEmails[i]), validEmails[i]);

    }

    for(i=0; i <= invalidEmails.length - 1; i++){

      QUnit.assert.ok(!firstForm.options.validate.email(invalidEmails[i]), invalidEmails[i]);

    }

  });

  QUnit.test('phone validation', function(){

    var validPhones, invalidPhones, i;

    validPhones = [
      //usa
      '8002529480',
      '(800) 252-9480',
      '800-252-9480',
      '+1 (800) 252-9480',
      '1-800-252-9480',
      //germamy
      '+49 (0)30 56796902',
      //france
      '+33 (0) 9 70 40 63 33'
    ];

    invalidPhones = [
      '123'
    ];

    QUnit.expect(validPhones.length + invalidPhones.length);

    for(i=0; i <= validPhones.length - 1; i++){

      QUnit.assert.ok(firstForm.options.validate.tel(validPhones[i]), validPhones[i]);

    }

    for(i=0; i <= invalidPhones.length - 1; i++){

      QUnit.assert.ok(!firstForm.options.validate.tel(invalidPhones[i]), invalidPhones[i]);

    }

  });

  QUnit.test('string validation', function(){

    QUnit.expect(2);

    var name = document.querySelector('#form1 input[name="name"]');

    name.value = 'test';

    QUnit.assert.ok(firstForm.options.validate.text(name), 'has value');

    name.value = '';

    QUnit.assert.ok(!firstForm.options.validate.text(name), 'blank string');

  });

  QUnit.test('checkbox validation', function(){

    QUnit.expect(2);

    var checkbox = document.querySelector('#form1 .checkbox');

    checkbox.checked = true;

    QUnit.assert.ok(firstForm.options.validate.checkbox(checkbox), 'checkbox is checked');

    checkbox.checked = false;

    QUnit.assert.ok(!firstForm.options.validate.checkbox(checkbox), 'checkbox is not checked');

  });

  QUnit.asyncTest('option: before', function(){

    QUnit.expect(2);

    firstForm.run({

      target: document.getElementById('form1'),

      preventDefault: function(){}

    });

    setTimeout(function(){

      QUnit.assert.ok(w.beforeTest, 'before function executed');

      QUnit.assert.ok(!$('#form1 input.name').hasClass('error-show'), 'form did not submit');

      QUnit.start();

    }, 500);

  });

  QUnit.asyncTest('option: customValidation', function(){

    QUnit.expect(1);

    $('#form3 .email').val('test@test.com');

    new Oform({

      selector: '#form3',

      customValidation: {

        email: function(){

          return false;

        }

      }

    }).run({

      target: document.getElementById('#form3'),

      preventDefault: function(){}

    });

    setTimeout(function(){

      QUnit.assert.ok($('#form3 input.email').hasClass('oform-error-show'), 'custom validation worked');

      QUnit.start();

    }, 500);

  });

  QUnit.asyncTest('test no attribute method on form', function(){

    QUnit.expect(2);

    w.noSubmissionSubmit = false;

    w.noSubmissionSuccess = false;

    $('#form9 .email').val('form6@test.com');

    $('#form9 .name').val('jane doe');

    $('#form9 .url').val('http://www.google.com');

    $('#form9 .phone').val('6489589837');

    $('#form9 .checkbox').attr('checked', true);

    new Oform({

      selector: '#form9'

    }).on('load', function(){

      w.noSubmissionSubmit = true;

    }).on('success', function(){

      w.noSubmissionSuccess = true;

    }).run({

      target: document.getElementById('form9'),

      preventDefault: function(){}

    });

    setTimeout(function(){

      QUnit.assert.ok(!w.noSubmissionSubmit, 'form didn\'t POST');

      QUnit.assert.ok(w.noSubmissionSuccess, 'success function executed');

      QUnit.start();

    }, 500);

  });

  QUnit.asyncTest('option: middleware', function(){

    QUnit.expect(3);

    new Oform({

      selector: '#form4',

      middleware: function(XhrObj){

        XhrObj.setRequestHeader('x-requested-with', 'Oform');

        return 'middleware=success';

      }

    }).on('load', function(response){

      w.middlewareData = JSON.parse(response.target.responseText);

    }).on('success', function(response){

      w.middlewareDataSuccess = JSON.parse(response.target.responseText);

    }).run({

      target: document.getElementById('form4'),

      preventDefault: function(){}

    });

    setTimeout(function(){

      QUnit.assert.equal(w.middlewareData.headers['x-requested-with'], 'Oform', 'middleware headers worked');

      QUnit.assert.equal(w.middlewareData.success, true, 'middleware xhr.load data succcess');

      //test that the success method function works as expeected
      QUnit.assert.equal(w.middlewareDataSuccess.success, true, 'middleware success data succcess');

      QUnit.start();

    }, 500);

  });

  QUnit.asyncTest('testing on handlers', function(){

    $('#form6 .email').val('form6@test.com');

    $('#form6 .name').val('jane doe');

    $('#form6 .url').val('http://www.google.com');

    $('#form6 .phone').val('6489589837');

    $('#form6 .checkbox').attr('checked', true);

    w.loadTest = false;

    w.loadendTest = false;

    w.loadStartTest = false;

    w.doneTest = false;

    window.form6 = new Oform({

      selector: '#form6'

    }).on('before', function(){
      //purposely blank so that the function returns undefined
      //this is to test that oform proceeds on either true or undefined
    }).on('load', function(){

      w.loadTest = true;

    }).on('loadend', function(){

      w.loadendTest = true;

    }).on('loadstart', function(){

      w.loadStartTest = true;

    }).on('done', function(){

      w.doneTest = true;

    }).on('success', function(event, data){

      w.successTest = data.data;

    }).run({

      target: document.getElementById('form6'),

      preventDefault: function(){}

    });

    setTimeout(function(){

      var fields = document.querySelectorAll('#form6 input[required]');

      fields = Array.prototype.slice.call(fields);

      fields.forEach(function(input){

        QUnit.assert.equal(input.getAttribute('required'), '', input.getAttribute('name') + ' onvalidationerror worked correctly');

      });

      QUnit.assert.ok(w.loadTest, 'xhr.load worked');

      QUnit.assert.ok(w.loadendTest, 'xhr.loadend worked');

      QUnit.assert.ok(w.loadStartTest, 'xhr.loadstart worked');

      QUnit.assert.ok(w.doneTest, 'on.done worked');

      QUnit.assert.equal(w.successTest.email, 'form6@test.com', 'form data argument worked');

      QUnit.assert.ok(!$('#form6 .name').hasClass(w.form6.options.errorShowClass), 'remove error class worked');

      QUnit.start();

    }, 500);

  });

  QUnit.asyncTest('remove method', function(){

    w.doneTest = false;

    var form6 = new Oform({

      selector: '#form6'

    }).on('done', function(){

      w.doneTest = true;

    });

    form6.remove();

    $('form6').submit();

    setTimeout(function(){

      QUnit.assert.ok(!w.doneTest, 'remove method worked');

      QUnit.start();

    }, 500);

  });

  QUnit.asyncTest('validation errors test', function(){

    QUnit.expect(4);

    w.invalidFieldsTest = true;

    w.validationErrors = [];

    w.form7 = new Oform({

      selector: '#form7'

    }).on('validationerror', function(){

      w.validationErrors.push('error');

    }).on('load', function(){

      w.invalidFieldsTest = false;

    }).on('done', function(){

    }).run({

      target: document.getElementById('form7'),

      preventDefault: function(){}

    });

    setTimeout(function(){

      QUnit.assert.ok(w.invalidFieldsTest, 'form didn\'t submit with errors');

      QUnit.assert.equal(w.validationErrors.length, 5, 'on validationerror worked');

      QUnit.assert.ok($('#form7 .name').hasClass(w.form7.options.errorShowClass), 'add error class worked');

      QUnit.assert.ok($('body').hasClass(w.form7.options.bodyErrorClass), 'body error class worked');

      QUnit.start();

    }, 500);

  });

  QUnit.asyncTest('before false, no validation errors, no submit', function(){

    QUnit.expect(1);

    w.beforeFalseNoErrorsNoSubmit = true;

    new Oform({

      selector: '#form8'

    }).on('before', function(){

      return false;

    }).on('load', function(){

      w.beforeFalseNoErrorsNoSubmit = false;

    }).run({

      target: document.getElementById('form8'),

      preventDefault: function(){}

    });

    setTimeout(function(){

      QUnit.assert.ok(w.beforeFalseNoErrorsNoSubmit, 'form didn\'t submit');

      QUnit.start();

    }, 500);

  });

});
<commit_msg>Update test.<commit_after>/* global QUnit, Oform */
$(function(){

  var w = window;

  w.beforeTest = false;

  var firstForm = new Oform({

    selector: '#form1',

    before: function(){

      w.beforeTest = true;

      return false;

    }

  });

  var secondForm = new Oform({

    selector: '#form2',

    errorHiddenClass: 'error-hidden-i',

    errorShownClass: 'error-show-i'

  });

  QUnit.test('initializations', function(){

    QUnit.expect(1);

    QUnit.assert.equal(secondForm.options.errorHiddenClass, 'error-hidden-i', 'instance override works');

  });

  QUnit.test('email validation', function(){

    var validEmails, invalidEmails, i;

    validEmails = [
      'kylerrush@gmail.com',
      'kylerrush+test@gmail.com',
      'kyle.r.rush@gmail.com'
    ];

    invalidEmails = [
      'kylerrush@gmail',
      '@gmail.com',
      '.kylerrush@gmail.com',
      'kylerrush.@gmail.com',
      'kylerrush@gmail..com',
      'kylerrush.gmail@com'
    ];

    QUnit.expect(validEmails.length + invalidEmails.length);

    for(i=0; i <= validEmails.length - 1; i++){

      QUnit.assert.ok(firstForm.options.validate.email(validEmails[i]), validEmails[i]);

    }

    for(i=0; i <= invalidEmails.length - 1; i++){

      QUnit.assert.ok(!firstForm.options.validate.email(invalidEmails[i]), invalidEmails[i]);

    }

  });

  QUnit.test('phone validation', function(){

    var validPhones, invalidPhones, i;

    validPhones = [
      //usa
      '8002529480',
      '(800) 252-9480',
      '800-252-9480',
      '+1 (800) 252-9480',
      '1-800-252-9480',
      //germamy
      '+49 (0)30 56796902',
      //france
      '+33 (0) 9 70 40 63 33'
    ];

    invalidPhones = [
      '123'
    ];

    QUnit.expect(validPhones.length + invalidPhones.length);

    for(i=0; i <= validPhones.length - 1; i++){

      QUnit.assert.ok(firstForm.options.validate.tel(validPhones[i]), validPhones[i]);

    }

    for(i=0; i <= invalidPhones.length - 1; i++){

      QUnit.assert.ok(!firstForm.options.validate.tel(invalidPhones[i]), invalidPhones[i]);

    }

  });

  QUnit.test('string validation', function(){

    QUnit.expect(2);

    var name = document.querySelector('#form1 input[name="name"]');

    name.value = 'test';

    QUnit.assert.ok(firstForm.options.validate.text(name), 'has value');

    name.value = '';

    QUnit.assert.ok(!firstForm.options.validate.text(name), 'blank string');

  });

  QUnit.test('checkbox validation', function(){

    QUnit.expect(2);

    var checkbox = document.querySelector('#form1 .checkbox');

    checkbox.checked = true;

    QUnit.assert.ok(firstForm.options.validate.checkbox(checkbox), 'checkbox is checked');

    checkbox.checked = false;

    QUnit.assert.ok(!firstForm.options.validate.checkbox(checkbox), 'checkbox is not checked');

  });

  QUnit.asyncTest('option: before', function(){

    QUnit.expect(2);

    firstForm.run({

      target: document.getElementById('form1'),

      preventDefault: function(){}

    });

    setTimeout(function(){

      QUnit.assert.ok(w.beforeTest, 'before function executed');

      QUnit.assert.ok(!$('#form1 input.name').hasClass('error-show'), 'form did not submit');

      QUnit.start();

    }, 500);

  });

  QUnit.asyncTest('option: customValidation', function(){

    QUnit.expect(1);

    $('#form3 .email').val('test@test.com');

    new Oform({

      selector: '#form3',

      customValidation: {

        email: function(){

          return false;

        }

      }

    }).run({

      target: document.getElementById('#form3'),

      preventDefault: function(){}

    });

    setTimeout(function(){

      QUnit.assert.ok($('#form3 input.email').hasClass('oform-error-show'), 'custom validation worked');

      QUnit.start();

    }, 500);

  });

  QUnit.asyncTest('test no attribute method on form', function(){

    QUnit.expect(2);

    w.noSubmissionSubmit = false;

    w.noSubmissionSuccess = false;

    $('#form9 .email').val('form6@test.com');

    $('#form9 .name').val('jane doe');

    $('#form9 .url').val('http://www.google.com');

    $('#form9 .phone').val('6489589837');

    $('#form9 .checkbox').attr('checked', true);

    new Oform({

      selector: '#form9'

    }).on('load', function(){

      w.noSubmissionSubmit = true;

    }).on('success', function(){

      w.noSubmissionSuccess = true;

    }).run({

      target: document.getElementById('form9'),

      preventDefault: function(){}

    });

    setTimeout(function(){

      QUnit.assert.ok(!w.noSubmissionSubmit, 'form didn\'t POST');

      QUnit.assert.ok(w.noSubmissionSuccess, 'success function executed');

      QUnit.start();

    }, 500);

  });

  QUnit.asyncTest('option: middleware', function(){

    QUnit.expect(3);

    new Oform({

      selector: '#form4',

      middleware: function(XhrObj){

        XhrObj.setRequestHeader('x-requested-with', 'Oform');

        return 'middleware=success';

      }

    }).on('load', function(response){

      w.middlewareData = JSON.parse(response.target.responseText);

    }).on('success', function(response){

      w.middlewareDataSuccess = JSON.parse(response.target.responseText);

    }).run({

      target: document.getElementById('form4'),

      preventDefault: function(){}

    });

    setTimeout(function(){

      QUnit.assert.equal(w.middlewareData.headers['x-requested-with'], 'Oform', 'middleware headers worked');

      QUnit.assert.equal(w.middlewareData.success, true, 'middleware xhr.load data succcess');

      //test that the success method function works as expeected
      QUnit.assert.equal(w.middlewareDataSuccess.success, true, 'middleware success data succcess');

      QUnit.start();

    }, 500);

  });

  QUnit.asyncTest('testing on handlers', function(){

    $('#form6 .email').val('form6@test.com');

    $('#form6 .name').val('jane doe');

    $('#form6 .url').val('http://www.google.com');

    $('#form6 .phone').val('6489589837');

    $('#form6 .checkbox').attr('checked', true);

    w.loadTest = false;

    w.loadendTest = false;

    w.loadStartTest = false;

    w.doneTest = false;

    window.form6 = new Oform({

      selector: '#form6'

    }).on('before', function(){
      //purposely blank so that the function returns undefined
      //this is to test that oform proceeds on either true or undefined
    }).on('load', function(){

      w.loadTest = true;

    }).on('loadend', function(){

      w.loadendTest = true;

    }).on('loadstart', function(){

      w.loadStartTest = true;

    }).on('done', function(){

      w.doneTest = true;

    }).on('success', function(event, data){

      w.successTest = data.data;

    }).run({

      target: document.getElementById('form6'),

      preventDefault: function(){}

    });

    setTimeout(function(){

      var fields = document.querySelectorAll('#form6 input[required]');

      fields = Array.prototype.slice.call(fields);

      fields.forEach(function(input){

        QUnit.assert.equal(input.getAttribute('required'), '', input.getAttribute('name') + ' onvalidationerror worked correctly');

      });

      QUnit.assert.ok(w.loadTest, 'xhr.load worked');

      QUnit.assert.ok(w.loadendTest, 'xhr.loadend worked (fails in ie9)');

      QUnit.assert.ok(w.loadStartTest, 'xhr.loadstart worked  (fails in ie9)');

      QUnit.assert.ok(w.doneTest, 'on.done worked');

      QUnit.assert.equal(w.successTest.email, 'form6@test.com', 'form data argument worked');

      QUnit.assert.ok(!$('#form6 .name').hasClass(w.form6.options.errorShowClass), 'remove error class worked');

      QUnit.start();

    }, 500);

  });

  QUnit.asyncTest('remove method', function(){

    w.doneTest = false;

    var form6 = new Oform({

      selector: '#form6'

    }).on('done', function(){

      w.doneTest = true;

    });

    form6.remove();

    $('form6').submit();

    setTimeout(function(){

      QUnit.assert.ok(!w.doneTest, 'remove method worked');

      QUnit.start();

    }, 500);

  });

  QUnit.asyncTest('validation errors test', function(){

    QUnit.expect(4);

    w.invalidFieldsTest = true;

    w.validationErrors = [];

    w.form7 = new Oform({

      selector: '#form7'

    }).on('validationerror', function(){

      w.validationErrors.push('error');

    }).on('load', function(){

      w.invalidFieldsTest = false;

    }).on('done', function(){

    }).run({

      target: document.getElementById('form7'),

      preventDefault: function(){}

    });

    setTimeout(function(){

      QUnit.assert.ok(w.invalidFieldsTest, 'form didn\'t submit with errors');

      QUnit.assert.equal(w.validationErrors.length, 5, 'on validationerror worked');

      QUnit.assert.ok($('#form7 .name').hasClass(w.form7.options.errorShowClass), 'add error class worked');

      QUnit.assert.ok($('body').hasClass(w.form7.options.bodyErrorClass), 'body error class worked');

      QUnit.start();

    }, 500);

  });

  QUnit.asyncTest('before false, no validation errors, no submit', function(){

    QUnit.expect(1);

    w.beforeFalseNoErrorsNoSubmit = true;

    new Oform({

      selector: '#form8'

    }).on('before', function(){

      return false;

    }).on('load', function(){

      w.beforeFalseNoErrorsNoSubmit = false;

    }).run({

      target: document.getElementById('form8'),

      preventDefault: function(){}

    });

    setTimeout(function(){

      QUnit.assert.ok(w.beforeFalseNoErrorsNoSubmit, 'form didn\'t submit');

      QUnit.start();

    }, 500);

  });

});
<|endoftext|>


<commit_before>module.exports = function(grunt) {
  var hljs = require('highlight.js');
  hljs.LANGUAGES['scss'] = require('./lib/scss.js')(hljs);

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    vendor: grunt.file.readJSON('.bowerrc').directory,

    foundation: {
      js: ['js/foundation/foundation.js', 'js/foundation/foundation.*.js'],
      scss: ['scss/foundation.scss','scss/settings.scss']

    },

    jst: {
      compile: {
        files: {
          'dist/docs/assets/js/templates.js': ['doc/templates/*.html']
        }
      }
    },

    assemble: {
      options: {
        marked: {
          highlight: function(code, lang) {
            if (lang === undefined) lang = 'bash';
            if (lang === 'html') lang = 'xml';
            if (lang === 'js') lang = 'javascript';
            return '
' + hljs.highlight(lang, code).value + '
';
          }
        }
      },
      dist: {
        options: {
          flatten: false,
          assets: 'dist/docs/assets',
          data: ['doc/data/*.json'],
          helpers: ['doc/helpers/*.js'],
          partials: ['doc/includes/**/*.{html,scss}'],
          layoutdir: 'doc/layouts',
          layout: 'default.html'
        },
        expand: true,
        cwd: 'doc/pages',
        src: '**/*.{html,md}',
        dest: 'dist/docs/'
      }
    },

    'string-replace': {
      dist: {
        files: {
          'dist/':'dist/**/*.*'
        },
        options: {
          replacements: [
            {pattern: /{{\s*VERSION\s*}}/g, replacement: '<%= pkg.version %>'}
          ]
        }
      }
    },

    sass: {
      dist: {
        options: {
          includePaths: ['scss'],
          sourceMap: true
        },
        files: {
          'dist/assets/css/foundation.css': '<%= foundation.scss %>',
          'dist/assets/css/normalize.css': 'scss/normalize.scss',
          'dist/docs/assets/css/docs.css': 'doc/assets/scss/docs.scss'
        }
      }
    },

    concat: {
      dist: {
        files: {
          'dist/assets/js/foundation.js':'<%= foundation.js %>'
        }
      }
    },

    uglify: {
      options: {
        preserveComments: 'some'
      },
      dist: {
        files: {
          'dist/assets/js/foundation.min.js': ['<%= foundation.js %>'],
          'dist/docs/assets/js/modernizr.js': ['<%= vendor %>/modernizr/modernizr.js'],
          'dist/docs/assets/js/all.js': ['<%= vendor %>/jquery/dist/jquery.js', 'vendor/lodash/dist/lodash.min.js','<%= vendor %>/fastclick/lib/fastclick.js', '<%= vendor %>/jquery-placeholder/jquery.placeholder.js', '<%= vendor %>/jquery.autocomplete/dist/jquery.autocomplete.js', '<%= foundation.js %>', 'doc/assets/js/docs.js']
        }
      },
      vendor: {
        files: {
          'dist/assets/js/vendor/placeholder.js': '<%= vendor %>/jquery-placeholder/jquery.placeholder.js',
          'dist/assets/js/vendor/fastclick.js': '<%= vendor %>/fastclick/lib/fastclick.js',
          'dist/assets/js/vendor/jquery.cookie.js': '<%= vendor %>/jquery.cookie/jquery.cookie.js',
          'dist/assets/js/vendor/jquery.js': '<%= vendor %>/jquery/dist/jquery.js',
          'dist/assets/js/vendor/modernizr.js': '<%= vendor %>/modernizr/modernizr.js'
        }
      }
    },

    copy: {
      dist: {
        files: [
          {expand:true, cwd: 'doc/assets/', src: ['**/*','!{scss,js}/**/*'], dest: 'dist/docs/assets/', filter:'isFile'},
          {expand:true, cwd: 'js/', src: ['foundation/*.js'], dest: 'dist/assets/js', filter: 'isFile'},
          {src: '<%= vendor %>/jquery/jquery.min.js', dest: 'dist/docs/assets/js/jquery.js'},
          {expand:true, cwd: 'scss/', src: '**/*.scss', dest: 'dist/assets/scss/', filter: 'isFile'},
          {src: 'bower.json', dest: 'dist/assets/'}
        ]
      }
    },

    clean: ['dist/'],

    connect: {
      server: {
        options: {
          port: 9001,
          base: 'dist/'
        }
      }
    },

    karma: {
      options: {
        configFile: 'karma.conf.js',
        runnerPort: 9999,
      },
      continuous: {
        singleRun: true,
        browsers: ['TinyPhantomJS', 'SmallPhantomJS']
      },
      dev: {
        singleRun: true,
        browsers: ['TinyPhantomJS', 'SmallPhantomJS', 'TinyChrome', 'Firefox'],
        reporters: 'dots'
      },
      dev_watch: {
        background: true,
        browsers: ['TinyPhantomJS', 'SmallPhantomJS', 'TinyChrome', 'Firefox']
      },
      mac: {
        singleRun: true,
        browsers: ['TinyPhantomJS', 'SmallPhantomJS', 'TinyChrome', 'Firefox', 'Safari'],
        reporters: 'dots'
      },
      win: {
        singleRun: true,
        browsers: ['TinyPhantomJS', 'SmallPhantomJS', 'TinyChrome', 'Firefox', 'IE'],
        reporters: 'dots'
      }
    },

    watch: {
      grunt: {
        options: {
          reload: true
        },
        files: ['Gruntfile.js']
      },
      karma: {
        files: [
          'dist/assets/js/*.js',
          'spec/**/*.js',
          'dist/assets/css/*.css'
        ],
        tasks: ['karma:dev_watch:run']
      },
      sass: {
        files: ['scss/**/*.scss', 'doc/assets/**/*.scss'],
        tasks: ['sass'],
        options: {
          livereload:true
        }
      },
      js: {
        files: ['js/**/*.js', 'doc/assets/js/**/*.js'],
        tasks: ['copy', 'concat', 'uglify'],
        options: {livereload:true}
      },
      assemble_all: {
        files: ['doc/{includes,layouts}/**/*.html'],
        tasks: ['assemble'],
        options: {livereload:true}
      },
      assemble_pages: {
        files: ['doc/pages/**/*.html'],
        tasks: ['newer:assemble'],
        options: {livereload:true}
      },
      assets: {
        options: {cwd: 'doc/assets/', livereload: true},
        files: ['**/*','!{scss,js}/**/*'],
        tasks: ['copy']
      },
      jst: {
        files: ['doc/templates/*.html'],
        tasks: ['jst'],
        options: {livereload:false}
      }
    },

    rsync: {
      dist: {
        options: {
          args: ["--verbose"],
          src: "./dist/docs/",
          recursive: true,
          dest: "/home/deployer/sites/foundation-docs/current",
          host: "deployer@72.32.134.77"
        }
      }
    }
  });

  grunt.loadNpmTasks('assemble');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-karma');
  grunt.loadNpmTasks('grunt-newer');
  grunt.loadNpmTasks('grunt-rsync');
  grunt.loadNpmTasks('grunt-sass');
  grunt.loadNpmTasks('grunt-contrib-jst');
  grunt.loadNpmTasks('grunt-string-replace');

  grunt.task.registerTask('watch_start', ['karma:dev_watch:start', 'watch']);
  grunt.registerTask('build:assets', ['clean', 'sass', 'concat', 'uglify', 'copy', 'jst', 'string-replace']);
  grunt.registerTask('build', ['build:assets', 'assemble']);
  grunt.registerTask('travis', ['build', 'karma:continuous']);
  grunt.registerTask('develop', ['travis', 'watch_start']);
  grunt.registerTask('deploy', ['build', 'rsync:dist']);
  grunt.registerTask('default', ['build', 'watch']);
  grunt.registerTask('server', ['connect:server:keepalive']);
};
<commit_msg>Removing PR code that broke some paths<commit_after>module.exports = function(grunt) {
  var hljs = require('highlight.js');
  hljs.LANGUAGES['scss'] = require('./lib/scss.js')(hljs);

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    vendor: grunt.file.readJSON('.bowerrc').directory,

    foundation: {
      js: ['js/foundation/foundation.js', 'js/foundation/foundation.*.js'],
      scss: ['scss/foundation.scss','scss/settings.scss']

    },

    jst: {
      compile: {
        files: {
          'dist/docs/assets/js/templates.js': ['doc/templates/*.html']
        }
      }
    },

    assemble: {
      options: {
        marked: {
          highlight: function(code, lang) {
            if (lang === undefined) lang = 'bash';
            if (lang === 'html') lang = 'xml';
            if (lang === 'js') lang = 'javascript';
            return '
' + hljs.highlight(lang, code).value + '
';
          }
        }
      },
      dist: {
        options: {
          flatten: false,
          assets: 'dist/docs/assets',
          data: ['doc/data/*.json'],
          helpers: ['doc/helpers/*.js'],
          partials: ['doc/includes/**/*.{html,scss}'],
          layoutdir: 'doc/layouts',
          layout: 'default.html'
        },
        expand: true,
        cwd: 'doc/pages',
        src: '**/*.{html,md}',
        dest: 'dist/docs/'
      }
    },

    sass: {
      dist: {
        options: {
          includePaths: ['scss'],
          sourceMap: true
        },
        files: {
          'dist/assets/css/foundation.css': '<%= foundation.scss %>',
          'dist/assets/css/normalize.css': 'scss/normalize.scss',
          'dist/docs/assets/css/docs.css': 'doc/assets/scss/docs.scss'
        }
      }
    },

    concat: {
      dist: {
        files: {
          'dist/assets/js/foundation.js':'<%= foundation.js %>'
        }
      }
    },

    uglify: {
      options: {
        preserveComments: 'some'
      },
      dist: {
        files: {
          'dist/assets/js/foundation.min.js': ['<%= foundation.js %>'],
          'dist/docs/assets/js/modernizr.js': ['<%= vendor %>/modernizr/modernizr.js'],
          'dist/docs/assets/js/all.js': ['<%= vendor %>/jquery/dist/jquery.js', 'vendor/lodash/dist/lodash.min.js','<%= vendor %>/fastclick/lib/fastclick.js', '<%= vendor %>/jquery-placeholder/jquery.placeholder.js', '<%= vendor %>/jquery.autocomplete/dist/jquery.autocomplete.js', '<%= foundation.js %>', 'doc/assets/js/docs.js']
        }
      },
      vendor: {
        files: {
          'dist/assets/js/vendor/placeholder.js': '<%= vendor %>/jquery-placeholder/jquery.placeholder.js',
          'dist/assets/js/vendor/fastclick.js': '<%= vendor %>/fastclick/lib/fastclick.js',
          'dist/assets/js/vendor/jquery.cookie.js': '<%= vendor %>/jquery.cookie/jquery.cookie.js',
          'dist/assets/js/vendor/jquery.js': '<%= vendor %>/jquery/dist/jquery.js',
          'dist/assets/js/vendor/modernizr.js': '<%= vendor %>/modernizr/modernizr.js'
        }
      }
    },

    copy: {
      dist: {
        files: [
          {expand:true, cwd: 'doc/assets/', src: ['**/*','!{scss,js}/**/*'], dest: 'dist/docs/assets/', filter:'isFile'},
          {expand:true, cwd: 'js/', src: ['foundation/*.js'], dest: 'dist/assets/js', filter: 'isFile'},
          {src: '<%= vendor %>/jquery/jquery.min.js', dest: 'dist/docs/assets/js/jquery.js'},
          {expand:true, cwd: 'scss/', src: '**/*.scss', dest: 'dist/assets/scss/', filter: 'isFile'},
          {src: 'bower.json', dest: 'dist/assets/'}
        ]
      }
    },

    clean: ['dist/'],

    connect: {
      server: {
        options: {
          port: 9001,
          base: 'dist/'
        }
      }
    },

    karma: {
      options: {
        configFile: 'karma.conf.js',
        runnerPort: 9999,
      },
      continuous: {
        singleRun: true,
        browsers: ['TinyPhantomJS', 'SmallPhantomJS']
      },
      dev: {
        singleRun: true,
        browsers: ['TinyPhantomJS', 'SmallPhantomJS', 'TinyChrome', 'Firefox'],
        reporters: 'dots'
      },
      dev_watch: {
        background: true,
        browsers: ['TinyPhantomJS', 'SmallPhantomJS', 'TinyChrome', 'Firefox']
      },
      mac: {
        singleRun: true,
        browsers: ['TinyPhantomJS', 'SmallPhantomJS', 'TinyChrome', 'Firefox', 'Safari'],
        reporters: 'dots'
      },
      win: {
        singleRun: true,
        browsers: ['TinyPhantomJS', 'SmallPhantomJS', 'TinyChrome', 'Firefox', 'IE'],
        reporters: 'dots'
      }
    },

    watch: {
      grunt: {
        options: {
          reload: true
        },
        files: ['Gruntfile.js']
      },
      karma: {
        files: [
          'dist/assets/js/*.js',
          'spec/**/*.js',
          'dist/assets/css/*.css'
        ],
        tasks: ['karma:dev_watch:run']
      },
      sass: {
        files: ['scss/**/*.scss', 'doc/assets/**/*.scss'],
        tasks: ['sass'],
        options: {
          livereload:true
        }
      },
      js: {
        files: ['js/**/*.js', 'doc/assets/js/**/*.js'],
        tasks: ['copy', 'concat', 'uglify'],
        options: {livereload:true}
      },
      assemble_all: {
        files: ['doc/{includes,layouts}/**/*.html'],
        tasks: ['assemble'],
        options: {livereload:true}
      },
      assemble_pages: {
        files: ['doc/pages/**/*.html'],
        tasks: ['newer:assemble'],
        options: {livereload:true}
      },
      assets: {
        options: {cwd: 'doc/assets/', livereload: true},
        files: ['**/*','!{scss,js}/**/*'],
        tasks: ['copy']
      },
      jst: {
        files: ['doc/templates/*.html'],
        tasks: ['jst'],
        options: {livereload:false}
      }
    },

    rsync: {
      dist: {
        options: {
          args: ["--verbose"],
          src: "./dist/docs/",
          recursive: true,
          dest: "/home/deployer/sites/foundation-docs/current",
          host: "deployer@72.32.134.77"
        }
      }
    }
  });

  grunt.loadNpmTasks('assemble');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-karma');
  grunt.loadNpmTasks('grunt-newer');
  grunt.loadNpmTasks('grunt-rsync');
  grunt.loadNpmTasks('grunt-sass');
  grunt.loadNpmTasks('grunt-contrib-jst');

  grunt.task.registerTask('watch_start', ['karma:dev_watch:start', 'watch']);
  grunt.registerTask('build:assets', ['clean', 'sass', 'concat', 'uglify', 'copy', 'jst']);
  grunt.registerTask('build', ['build:assets', 'assemble']);
  grunt.registerTask('travis', ['build', 'karma:continuous']);
  grunt.registerTask('develop', ['travis', 'watch_start']);
  grunt.registerTask('deploy', ['build', 'rsync:dist']);
  grunt.registerTask('default', ['build', 'watch']);
  grunt.registerTask('server', ['connect:server:keepalive']);
};
<|endoftext|>


<commit_before>var config = require('config');
var log = require('./client/log')('geocode');
var get = require('./client/request').get;

var southWest = [-123.099060058594, 36.745486924699];
var northEast = [-121.192932128906, 38.182068998322];

/**********tismart **********************/
var dev_amigo_token = "A:m8SOB7KwYWuuWAeYEHHjBf7U9VIZFrMuH2LLjS";
var url_search_amigo = "https://www.amigocloud.com/api/v1/me/geocoder/search";
var data_boundary = {
    "min_lat" : 36.155617833819,
    "min_lon" : -123.607177734375,
    "max_lat" : 38.826870521381,
    "max_lon" : -120.701293945312
};

/**
 * Geocode
 */

module.exports = geocode;
module.exports.reverse = reverse;
module.exports.suggest = suggest;
module.exports.suggestAmigo = suggestAmigo;

/**
 * Geocode
 */

function geocode(address, callback) {
  log('--> geocoding %s', address);
  get('/geocode/' + address, function(err, res) {
    if (err) {
      log('<-- geocoding error %s', err);
      callback(err, res);
    } else {
      log('<-- geocoding complete %j', res.body);
      callback(null, res.body);
    }
  });
}

/**
 * Reverse geocode
 */

function reverse(ll, callback) {

  console.log("reserve ll", ll);
  console.log("reserve callback", callback);
  log('--> reverse geocoding %s', ll);
  get('/geocode/reverse/' + ll[0] + ',' + ll[1], function(err, res) {
    if (err) {
      log('<-- geocoding error %e', err);
      callback(err, res);
    } else {
      log('<-- geocoding complete %j', res.body);
      callback(null, res.body);
    }
  });
}

/**
 * Suggestions!
 */

function suggestAmigo(text, callback) {

    var lista_direcciones;

    //get('https://www.amigocloud.com/api/v1/me/geocoder/autocomplete?text=' + text +'&token=' + dev_amigo_token,
    get(url_search_amigo + '?token=' + config.realtime_access_token()+'&boundary.rect.min_lat='+data_boundary.min_lat+'&boundary.rect.min_lon='+data_boundary.min_lon+'&boundary.rect.max_lat='+data_boundary.max_lat+'&boundary.rect.max_lon='+data_boundary.max_lon+'&sources=osm,oa&text=' + text,

        function(err, res) {

            if(err) {
                console.log("Error amigo cloud");
                log("Amigo Cloud Response Error ->", err);

            }else{
                if(res.body.features) {

                    var lista_direcciones = res.body.features;
                    if (lista_direcciones.length > 0) {
                         callback(
                            null,
                            lista_direcciones
                        );
                    }else {
                        callback(true, res);
                    }

                }
            }
    });
}

function suggest(text, callback) {
  var bingSuggestions, nominatimSuggestions, totalSuggestions;
  log('--> getting suggestion for %s', text);

  get('/geocode/suggest/'+ text, function(err, res){

    if (err) {
      log('<-- suggestion error %s', err);
      callback(err, res);
    } else {
      log('<-- got %s suggestions', res.body.length);

	bingSuggestions = res.body;

    console.log("------------API GEOCODE---------------");
    console.log("res ->", res.body);
    console.log("res.body ->", res);

//      callback(null, res.body);
	get('http://nominatim.openstreetmap.org/search' +
	    '?format=json&addressdetails=1&' +
	    'viewbox=' + southWest[0] + ',' +
	    northEast[1] + ',' + northEast[0] + ',' + southWest[1] +
	    '&bounded=1' +
	    'countrycodes=us&q=' + text, function (err, nRes) {
		var inside = false;
	    nominatimSuggestions = [];
            for (var i = 0; i < nRes.body.length; i++) {
//		inside = inside && (nRes.body[i].lng > southWest[0]);
//		inside = inside && (nRes.body[i].lng < northEast[0]);
//		inside = inside && (nRes.body[i].lat > southWest[1]);
//		inside = inside && (nRes.body[i].lat < northEast[1]);
//		if (inside) {
                    nominatimSuggestions.push(nRes.body[i]);
//		}
            }

            console.log('======data enviada===============');
            console.log(nominatimSuggestions.slice(0,2).concat(bingSuggestions.slice(0,3)));
            callback(
		null,
		nominatimSuggestions.slice(0,2).concat(bingSuggestions.slice(0,3))
	    );
	});
    }
  });

}

<commit_msg>debug amigocloud<commit_after>var config = require('config');
var log = require('./client/log')('geocode');
var get = require('./client/request').get;

var southWest = [-123.099060058594, 36.745486924699];
var northEast = [-121.192932128906, 38.182068998322];

/**********tismart **********************/
var dev_amigo_token = "A:m8SOB7KwYWuuWAeYEHHjBf7U9VIZFrMuH2LLjS";
var url_search_amigo = "https://www.amigocloud.com/api/v1/me/geocoder/search";
var data_boundary = {
    "min_lat" : 36.155617833819,
    "min_lon" : -123.607177734375,
    "max_lat" : 38.826870521381,
    "max_lon" : -120.701293945312
};

/**
 * Geocode
 */

module.exports = geocode;
module.exports.reverse = reverse;
module.exports.suggest = suggest;
module.exports.suggestAmigo = suggestAmigo;

/**
 * Geocode
 */

function geocode(address, callback) {
  log('--> geocoding %s', address);
  get('/geocode/' + address, function(err, res) {
    if (err) {
      log('<-- geocoding error %s', err);
      callback(err, res);
    } else {
      log('<-- geocoding complete %j', res.body);
      callback(null, res.body);
    }
  });
}

/**
 * Reverse geocode
 */

function reverse(ll, callback) {

  console.log("reserve ll", ll);
  console.log("reserve callback", callback);
  log('--> reverse geocoding %s', ll);
  get('/geocode/reverse/' + ll[0] + ',' + ll[1], function(err, res) {
    if (err) {
      log('<-- geocoding error %e', err);
      callback(err, res);
    } else {
      log('<-- geocoding complete %j', res.body);
      callback(null, res.body);
    }
  });
}

/**
 * Suggestions!
 */

function suggestAmigo(text, callback) {

    var lista_direcciones;

    //get('https://www.amigocloud.com/api/v1/me/geocoder/autocomplete?text=' + text +'&token=' + dev_amigo_token,
    get(url_search_amigo + '?token=' + config.realtime_access_token()+'&boundary.rect.min_lat='+data_boundary.min_lat+'&boundary.rect.min_lon='+data_boundary.min_lon+'&boundary.rect.max_lat='+data_boundary.max_lat+'&boundary.rect.max_lon='+data_boundary.max_lon+'&sources=osm,oa&text=' + text,

        function(err, res) {

            console.log("new resp amigo cloud" -> res);

            if(err) {
                console.log("Error amigo cloud");
                log("Amigo Cloud Response Error ->", err);

            }else{
                if(res.body.features) {

                    var lista_direcciones = res.body.features;
                    if (lista_direcciones.length > 0) {
                         callback(
                            null,
                            lista_direcciones
                        );
                    }else {
                        callback(true, res);
                    }

                }
            }
    });
}

function suggest(text, callback) {
  var bingSuggestions, nominatimSuggestions, totalSuggestions;
  log('--> getting suggestion for %s', text);

  get('/geocode/suggest/'+ text, function(err, res){

    if (err) {
      log('<-- suggestion error %s', err);
      callback(err, res);
    } else {
      log('<-- got %s suggestions', res.body.length);

	bingSuggestions = res.body;

    console.log("------------API GEOCODE---------------");
    console.log("res ->", res.body);
    console.log("res.body ->", res);

//      callback(null, res.body);
	get('http://nominatim.openstreetmap.org/search' +
	    '?format=json&addressdetails=1&' +
	    'viewbox=' + southWest[0] + ',' +
	    northEast[1] + ',' + northEast[0] + ',' + southWest[1] +
	    '&bounded=1' +
	    'countrycodes=us&q=' + text, function (err, nRes) {
		var inside = false;
	    nominatimSuggestions = [];
            for (var i = 0; i < nRes.body.length; i++) {
//		inside = inside && (nRes.body[i].lng > southWest[0]);
//		inside = inside && (nRes.body[i].lng < northEast[0]);
//		inside = inside && (nRes.body[i].lat > southWest[1]);
//		inside = inside && (nRes.body[i].lat < northEast[1]);
//		if (inside) {
                    nominatimSuggestions.push(nRes.body[i]);
//		}
            }

            console.log('======data enviada===============');
            console.log(nominatimSuggestions.slice(0,2).concat(bingSuggestions.slice(0,3)));
            callback(
		null,
		nominatimSuggestions.slice(0,2).concat(bingSuggestions.slice(0,3))
	    );
	});
    }
  });

}

<|endoftext|>


<commit_before>// Task.js
//
// Logic for client interactions with the MuckRock task system.

function authenticateAjax() {
    // Sets up authentication for AJAX transactions
    var csrftoken = $.cookie('csrftoken');
    function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }
    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    });
}

function ajaxPost(task, endpoint, data) {
    var pendingOverlay = $(task).children('.pending.overlay');
    var errorOverlay = $(task).children('.error.overlay');
    $(document).ajaxStart(function(){
        $(pendingOverlay).addClass('visible');
    }).ajaxError(function(event, response){
        $(pendingOverlay).removeClass('visible');
        $(errorOverlay).addClass('visible');
        setTimeout(function(){
            $(errorOverlay).removeClass('visible');
        }, 3000);
        $(document).off('ajaxStart').off('ajaxError').off('ajaxComplete');
    }).ajaxComplete(function(){
        $(pendingOverlay).removeClass('visible');
        markAsResolved(task);
        $(document).off('ajaxStart').off('ajaxError').off('ajaxComplete');
    });
    $.ajax({
        url: endpoint,
        type: 'post',
        data: data,
        success: null,
        dataType: 'json'
    });
}

/*
Need to add the action as a value since the button is being overridden.
In a non-JS form submission, the button would also include its value in the posted data.
*/

function resolve(taskForm) {
    var taskID = '#' + getTaskID($(taskForm).serializeArray()) + '-task';
    var taskData = $(taskForm).serialize() + '&resolve=true';
    var taskEndpoint = $(taskForm).attr('action');
    ajaxPost(taskID, taskEndpoint, taskData);
}

function reject(taskForm) {
    var taskID = '#' + getTaskID($(taskForm).serializeArray()) + '-task';
    var taskData = $(taskForm).serialize() + '&reject=true';
    var taskEndpoint = $(taskForm).attr('action');
    ajaxPost(taskID, taskEndpoint, taskData);
}

function getTaskID(taskFormData) {
    // Gets the task ID from a task form
    var taskID;
    $.each(taskFormData, function(i, input){
        if (input.name == 'task') {
            taskID = input.value;
        }
    });
    return taskID;
}

function markAsResolved(task) {
    $(task).addClass('resolved');
    $(task).find(':input').attr('disabled', true).addClass('disabled');
    $(task).find('.task-type').text('Resolved');
}

function formHasAction(taskForm, action) {
    // checks whether the task form has a 'Resolve' action or not
    var actionExists = false;
    var actionButton = 'button[name="' + action + '"]';
    if (!!$(taskForm).children(actionButton).length) {
        actionExists = true;
    }
    return actionExists;
}

function rebindCheckboxes(){
    // Rebinds the toggle all checkbox to only select checkboxes in task headers
    $('#toggle-all').off('click');
    $('#toggle-all').click(function(){
        var toggleAll = this;
        $('.task header :checkbox').not('#toggle-all').not('.list-filters-fields').each(function(){
            $(this).click(function(){
                toggleAll.checked = false;
            });
            if (!$(this).data('ignore-toggle-all')) {
                this.checked = toggleAll.checked;
                toggleBatchedButtons();
            }
        });
    });
}

////////////////////////////////////////////////////////////////////////////////

authenticateAjax();
rebindCheckboxes();

var tasks = $('.task');

// Hide all the resolved tasks
$('.resolved.task')
    .each(function(){
        markAsResolved(this);
    })
    .addClass('collapsed');

$('button[name="resolve"]').click(function(e){
    /* If the button clicked is the "resolve all" button, then get forms
    for all the currently checked tasks. Else, just get the form for the
    task that owns the button. */
    e.preventDefault();
    var forms = [];
    if ($(this).attr('id') == 'batched-resolve') {
        $(':checked[form=batched]').each(function() {
            var taskForm = $(this).closest('.task').find('form');
            // the form needs to have a resolve action in order to be added
            if (formHasAction(taskForm, 'resolve')) {
                forms.push(taskForm);
            }
        });
    } else {
        forms.push($(this).closest('form'));
    }
    $(forms).each(function(){
        resolve(this);
    });
    return false;
});

$('button[name="reject"]').click(function(e){
    e.preventDefault();
    var forms = [];
    if ($(this).attr('id') == 'batched-reject') {
        $(':checked[form=batched]').each(function() {
            var taskForm = $(this).closest('.task').find('form');
            if (formHasAction(taskForm, 'reject')) {
                forms.push(taskForm);
            }
        });
    } else {
        forms.push($(this).closest('form'));
    }
    $(forms).each(function(){
        console.log($(this));
        reject(this);
    });
    return false;
});

tasks.find('header').click(function() {
    $(this).parent().toggleClass('collapsed');
});

$('.task .permalink').click(function(e) {
    e.stopPropagation();
});

$('.task .checkbox').click(function(e) {
    e.stopPropagation();
});

var checkboxes = $('.task header').find(':checkbox');
var batchedButtons = $('#batched button').not('#collapse-all');
function toggleBatchedButtons() {
    if ($('.task header').find(':checkbox:checked').length > 0) {
        batchedButtons.attr('disabled', false);
    } else {
        batchedButtons.attr('disabled', true);
    }
}
batchedButtons.attr('disabled', true);
checkboxes.click(function(){
    toggleBatchedButtons();
});

$('#collapse-all').click(function(e){
    e.preventDefault();
    if ($(this).text() == "Collapse All") {
        $(this).text("Reveal All");
        $('.task').addClass('collapsed');
    } else {
        $(this).text("Collapse All");
        $('.task').removeClass('collapsed');
    }
});

$('.reveal-extra-context').click(function(e){
    e.preventDefault();
    if ($(this).data['state']) {
        // if on, turn off
        $(this).data['state'] = 0;
        $(this).text("More Info");
        $(this).next().addClass('hidden');
    } else {
        // if off, turn on
        $(this).data['state'] = 1;
        $(this).text("Less Info");
        $(this).next().removeClass('hidden');
    }
});
<commit_msg>does not disable resolved task inputs<commit_after>// Task.js
//
// Logic for client interactions with the MuckRock task system.

function authenticateAjax() {
    // Sets up authentication for AJAX transactions
    var csrftoken = $.cookie('csrftoken');
    function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }
    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    });
}

function ajaxPost(task, endpoint, data) {
    var pendingOverlay = $(task).children('.pending.overlay');
    var errorOverlay = $(task).children('.error.overlay');
    $(document).ajaxStart(function(){
        $(pendingOverlay).addClass('visible');
    }).ajaxError(function(event, response){
        $(pendingOverlay).removeClass('visible');
        $(errorOverlay).addClass('visible');
        setTimeout(function(){
            $(errorOverlay).removeClass('visible');
        }, 3000);
        $(document).off('ajaxStart').off('ajaxError').off('ajaxComplete');
    }).ajaxComplete(function(){
        $(pendingOverlay).removeClass('visible');
        markAsResolved(task);
        $(document).off('ajaxStart').off('ajaxError').off('ajaxComplete');
    });
    $.ajax({
        url: endpoint,
        type: 'post',
        data: data,
        success: null,
        dataType: 'json'
    });
}

/*
Need to add the action as a value since the button is being overridden.
In a non-JS form submission, the button would also include its value in the posted data.
*/

function resolve(taskForm) {
    var taskID = '#' + getTaskID($(taskForm).serializeArray()) + '-task';
    var taskData = $(taskForm).serialize() + '&resolve=true';
    var taskEndpoint = $(taskForm).attr('action');
    ajaxPost(taskID, taskEndpoint, taskData);
}

function reject(taskForm) {
    var taskID = '#' + getTaskID($(taskForm).serializeArray()) + '-task';
    var taskData = $(taskForm).serialize() + '&reject=true';
    var taskEndpoint = $(taskForm).attr('action');
    ajaxPost(taskID, taskEndpoint, taskData);
}

function getTaskID(taskFormData) {
    // Gets the task ID from a task form
    var taskID;
    $.each(taskFormData, function(i, input){
        if (input.name == 'task') {
            taskID = input.value;
        }
    });
    return taskID;
}

function markAsResolved(task) {
    $(task).addClass('resolved');
}

function formHasAction(taskForm, action) {
    // checks whether the task form has a 'Resolve' action or not
    var actionExists = false;
    var actionButton = 'button[name="' + action + '"]';
    if (!!$(taskForm).children(actionButton).length) {
        actionExists = true;
    }
    return actionExists;
}

function rebindCheckboxes(){
    // Rebinds the toggle all checkbox to only select checkboxes in task headers
    $('#toggle-all').off('click');
    $('#toggle-all').click(function(){
        var toggleAll = this;
        $('.task header :checkbox').not('#toggle-all').not('.list-filters-fields').each(function(){
            $(this).click(function(){
                toggleAll.checked = false;
            });
            if (!$(this).data('ignore-toggle-all')) {
                this.checked = toggleAll.checked;
                toggleBatchedButtons();
            }
        });
    });
}

////////////////////////////////////////////////////////////////////////////////

authenticateAjax();
rebindCheckboxes();

var tasks = $('.task');

// Hide all the resolved tasks
$('.resolved.task')
    .each(function(){
        markAsResolved(this);
    })
    .addClass('collapsed');

$('button[name="resolve"]').click(function(e){
    /* If the button clicked is the "resolve all" button, then get forms
    for all the currently checked tasks. Else, just get the form for the
    task that owns the button. */
    e.preventDefault();
    var forms = [];
    if ($(this).attr('id') == 'batched-resolve') {
        $(':checked[form=batched]').each(function() {
            var taskForm = $(this).closest('.task').find('form');
            // the form needs to have a resolve action in order to be added
            if (formHasAction(taskForm, 'resolve')) {
                forms.push(taskForm);
            }
        });
    } else {
        forms.push($(this).closest('form'));
    }
    $(forms).each(function(){
        resolve(this);
    });
    return false;
});

$('button[name="reject"]').click(function(e){
    e.preventDefault();
    var forms = [];
    if ($(this).attr('id') == 'batched-reject') {
        $(':checked[form=batched]').each(function() {
            var taskForm = $(this).closest('.task').find('form');
            if (formHasAction(taskForm, 'reject')) {
                forms.push(taskForm);
            }
        });
    } else {
        forms.push($(this).closest('form'));
    }
    $(forms).each(function(){
        console.log($(this));
        reject(this);
    });
    return false;
});

tasks.find('header').click(function() {
    $(this).parent().toggleClass('collapsed');
});

$('.task .permalink').click(function(e) {
    e.stopPropagation();
});

$('.task .checkbox').click(function(e) {
    e.stopPropagation();
});

var checkboxes = $('.task header').find(':checkbox');
var batchedButtons = $('#batched button').not('#collapse-all');
function toggleBatchedButtons() {
    if ($('.task header').find(':checkbox:checked').length > 0) {
        batchedButtons.attr('disabled', false);
    } else {
        batchedButtons.attr('disabled', true);
    }
}
batchedButtons.attr('disabled', true);
checkboxes.click(function(){
    toggleBatchedButtons();
});

$('#collapse-all').click(function(e){
    e.preventDefault();
    if ($(this).text() == "Collapse All") {
        $(this).text("Reveal All");
        $('.task').addClass('collapsed');
    } else {
        $(this).text("Collapse All");
        $('.task').removeClass('collapsed');
    }
});

$('.reveal-extra-context').click(function(e){
    e.preventDefault();
    if ($(this).data['state']) {
        // if on, turn off
        $(this).data['state'] = 0;
        $(this).text("More Info");
        $(this).next().addClass('hidden');
    } else {
        // if off, turn on
        $(this).data['state'] = 1;
        $(this).text("Less Info");
        $(this).next().removeClass('hidden');
    }
});
<|endoftext|>


<commit_before>module('glow.util');

test('apply', 3, function() {
	var objA = {foo: 'hello', bar: 'world'},
		objB = {bar: 'everyone', mof: 42};

	equal(typeof glow.util.apply, 'function', 'Function exists');

	var returnObj = glow.util.apply(objA, objB);

	equal(objA, returnObj, 'Returns destniation object');

	same(objA, {
		foo: 'hello',
		bar: 'everyone',
		mof: 42
	}, 'Properties copied');
});

test('apply ignores properties on prototype', 1, function() {
	function MyObj() {}
	MyObj.prototype.foobar = 'foobar';

	var objA = {foo: 'hello'},
		objB = new MyObj();

	objB.bar = 'world';

	glow.util.apply(objA, objB);

	same(objA, {
		foo: 'hello',
		bar: 'world'
	}, 'Properties copied');
});

test("extend", 12, function() {
	equal(typeof glow.util.extend, 'function', 'Function exists');

	var BaseClass = function() {
		this.a = "From Base";
		this.b = "From Base";
	}
	BaseClass.prototype = {
		c: function() {
			return "From Base";
		},
		d: function() {
			return "From Base";
		}
	};
	var SubClass = function() {
		BaseClass.call(this);
		this.b = "From Sub";
		this.e = "From Sub";
	}
	glow.util.extend(SubClass, BaseClass, {
		d: function() {
			return "From Sub";
		},
		f: function() {
			return "From Sub";
		}
	});

	var myBase = new BaseClass();
	var mySub = new SubClass();

	equals(myBase.a, "From Base", "Base a prop");
	equals(myBase.b, "From Base", "Base b prop");
	equals(myBase.c(), "From Base", "Base c function");
	equals(myBase.d(), "From Base", "Base d function");
	equals(mySub.a, "From Base", "Sub a prop (inherited)");
	equals(mySub.b, "From Sub", "Sub b prop (overwritten)");
	equals(mySub.c(), "From Base", "Sub c function (inherited)");
	equals(mySub.d(), "From Sub", "Sub d function (overwritten)");
	equals(mySub.e, "From Sub", "Sub e prop (new)");
	equals(mySub.f(), "From Sub", "Sub f function (new)");
	equals(SubClass.base, BaseClass, "sub.base property set");
});

test('escapeRegex', 100, function() {
	equal(typeof glow.util.escapeRegex, 'function', 'escapeRegex is function');
	equal(
		glow.util.escapeRegex('[Hello. Is | this* escaped?]'),
		'\\[Hello\\. Is \\| this\\* escaped\\?\\]',
		'Basic escaping test'
	);
});<commit_msg>util: Fixing error in escapeRegex unit test<commit_after>module('glow.util');

test('apply', 3, function() {
	var objA = {foo: 'hello', bar: 'world'},
		objB = {bar: 'everyone', mof: 42};

	equal(typeof glow.util.apply, 'function', 'Function exists');

	var returnObj = glow.util.apply(objA, objB);

	equal(objA, returnObj, 'Returns destniation object');

	same(objA, {
		foo: 'hello',
		bar: 'everyone',
		mof: 42
	}, 'Properties copied');
});

test('apply ignores properties on prototype', 1, function() {
	function MyObj() {}
	MyObj.prototype.foobar = 'foobar';

	var objA = {foo: 'hello'},
		objB = new MyObj();

	objB.bar = 'world';

	glow.util.apply(objA, objB);

	same(objA, {
		foo: 'hello',
		bar: 'world'
	}, 'Properties copied');
});

test("extend", 12, function() {
	equal(typeof glow.util.extend, 'function', 'Function exists');

	var BaseClass = function() {
		this.a = "From Base";
		this.b = "From Base";
	}
	BaseClass.prototype = {
		c: function() {
			return "From Base";
		},
		d: function() {
			return "From Base";
		}
	};
	var SubClass = function() {
		BaseClass.call(this);
		this.b = "From Sub";
		this.e = "From Sub";
	}
	glow.util.extend(SubClass, BaseClass, {
		d: function() {
			return "From Sub";
		},
		f: function() {
			return "From Sub";
		}
	});

	var myBase = new BaseClass();
	var mySub = new SubClass();

	equals(myBase.a, "From Base", "Base a prop");
	equals(myBase.b, "From Base", "Base b prop");
	equals(myBase.c(), "From Base", "Base c function");
	equals(myBase.d(), "From Base", "Base d function");
	equals(mySub.a, "From Base", "Sub a prop (inherited)");
	equals(mySub.b, "From Sub", "Sub b prop (overwritten)");
	equals(mySub.c(), "From Base", "Sub c function (inherited)");
	equals(mySub.d(), "From Sub", "Sub d function (overwritten)");
	equals(mySub.e, "From Sub", "Sub e prop (new)");
	equals(mySub.f(), "From Sub", "Sub f function (new)");
	equals(SubClass.base, BaseClass, "sub.base property set");
});

test('escapeRegex', 2, function() {
	equal(typeof glow.util.escapeRegex, 'function', 'escapeRegex is function');
	equal(
		glow.util.escapeRegex('[Hello. Is | this* escaped?]'),
		'\\[Hello\\. Is \\| this\\* escaped\\?\\]',
		'Basic escaping test'
	);
});<|endoftext|>


<commit_before>import camelToDashCase from '../utils/camelToDashCase'

const alternativeValues = {
  'space-around': 'justify',
  'space-between': 'justify',
  'flex-start': 'start',
  'flex-end': 'end',
  'wrap-reverse': 'multiple',
  wrap: 'multiple'
}

const alternativeProps = {
  alignItems: 'WebkitBoxAlign',
  justifyContent: 'WebkitBoxPack',
  flexWrap: 'WebkitBoxLines',
  alignContent: 'alignContent',
  alignSelf: 'alignSelf'
}

export default function flexboxOld(property, value) {
  if (property === 'flexDirection') {
    return {
      WebkitBoxOrient: value.indexOf('column') > -1 ? 'vertical' : 'horizontal',
      WebkitBoxDirection: value.indexOf('reverse') > -1 ? 'reverse' : 'normal'
    }
  }
  if (alternativeProps[property]) {
    return {
      [alternativeProps[property]]: alternativeValues[value] || value
    }
  }
}
<commit_msg>#4 preventing alignSelf, alignContent from using alternative values<commit_after>import camelToDashCase from '../utils/camelToDashCase'

const alternativeValues = {
  'space-around': 'justify',
  'space-between': 'justify',
  'flex-start': 'start',
  'flex-end': 'end',
  'wrap-reverse': 'multiple',
  wrap: 'multiple'
}

const alternativeProps = {
  alignItems: 'WebkitBoxAlign',
  justifyContent: 'WebkitBoxPack',
  flexWrap: 'WebkitBoxLines'
}

export default function flexboxOld(property, value) {
  if (property === 'flexDirection') {
    return {
      WebkitBoxOrient: value.indexOf('column') > -1 ? 'vertical' : 'horizontal',
      WebkitBoxDirection: value.indexOf('reverse') > -1 ? 'reverse' : 'normal'
    }
  }
  if (alternativeProps[property]) {
    return {
      [alternativeProps[property]]: alternativeValues[value] || value
    }
  }
}
<|endoftext|>


<commit_before>'use strict';

var config = require( './config.json' );

var util = require('util');
var Promise = require('promise');

var mongoUtils = require('../utilities/mongoUtils')

var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');

var axios = require('axios');

var troubleTicketStates = require('../utilities/troubleTicketStates')

// Mongo URL

var argv = require('minimist')(process.argv);
var dbhost = argv.dbhost ? argv.dbhost : config.db_host;
const mongourl = config.db_prot+"://"+dbhost+":"
        +config.db_port+"/"+config.db_name

/*
 Once you 'require' a module you can reference the things that it exports.  These are defined in module.exports.

 For a controller in a127 (which this is) you should export the functions referenced in your Swagger document by name.

 Either:
  - The HTTP Verb of the corresponding operation (get, put, post, delete, etc)
  - Or the operationId associated with the operation in your Swagger document

  In the starter/skeleton project the 'get' operation on the '/hello' path has an operationId named 'hello'.  Here,
  we specify that in the exports of this module that 'hello' maps to the function named 'hello'
 */

module.exports = {
  troubleTicketFindHAL,
  troubleTicketFindHeader,
  troubleTicketGetHAL,
  troubleTicketPatchHAL,
  troubleTicketCreateHAL };

  // Update troubleTicket by Id: PATCH /v2/troubleTicket/{id}

  function troubleTicketPatchHAL(req, res) {

  var troubleTicket = req.swagger.params.troubleTicket.value;
  var troubleTicketId = parseInt(req.swagger.params.troubleTicketId.value);

  // Use connect method to connect to the server
  MongoClient.connect(mongourl, function(err, db) {
    assert.equal(null, err);

    // Get the documents collection

    var collection = db.collection('troubleTicket');

    const query = { id: troubleTicketId.toString() }

    var patchDoc = { $set: troubleTicket }

    collection.update( query, patchDoc, function(err, doc) {
        assert.equal(err, null);

        // Find one document
        collection.findOne( query, function(err, doc) {
            doc = generateTroubleTicketDoc( doc );

            res.json( doc );
         })

        });
    })
  }

  // Find a troubleTicket: GET /v2/hal/troubleTicket/

  function troubleTicketFindHAL(req, res) {

  // Use connect method to connect to the server
  MongoClient.connect(mongourl, function(err, db) {
    assert.equal(null, err);

    var pageno = req.swagger.params.page.value ? parseInt(req.swagger.params.page.value) : 1;

    // Fixed page size for now

    const pagesize = 5

    const firstitem = (pageno-1)*pagesize
    const lastitem = firstitem + pagesize

    const baseURL = req.url.slice( 0, req.url.indexOf("?") )

    // Get the documents collection

    var collection = db.collection('troubleTicket');

    // Find some documents
    collection.find({},
        mongoUtils.fieldFilter(req.swagger.params.fields.value)).toArray(function(err, docs) {
        assert.equal(err, null);

        const totalsize = docs.length

        // slice page
        docs = docs.slice( firstitem, lastitem )

        // Generate Trouble Ticket
        docs.forEach( function( item ) {
          item = generateTroubleTicketDoc( item, baseURL.concat( "/" ).concat( item.id ) )
        })

        // create HAL response

        var halresp = {};

        // support v2 backward compatiblity if requested

        if ( req.swagger.params.embed.value == "v2" ) {
          halresp.troubleTicket = docs
          }

        halresp._links = {
            self: { href: req.url },
            item: []
        }

        // add embedded resources if requested

       if ( req.swagger.params.embed.value == "true" ) {
          halresp._embedded = {item: []}
          halresp._embedded.item = docs
          }

        // Add array of links
        docs.forEach( function( item ) {
            halresp._links.item.push( {
                  href: baseURL.concat( "/" ).concat( item.id )
                } )
        })

        // Pagination attributes

        halresp.page = pageno
        halresp.totalrecords = totalsize
        halresp.pagesize = pagesize
        halresp.totalpages = Math.ceil(totalsize/pagesize)

        // Create pagination links

        if ( totalsize > (pageno * pagesize) ) {
          halresp._links.next = { href: baseURL.concat("?page=").concat(pageno+1)}
        }

        halresp._links.first = { href: baseURL.concat("?page=1")}

        if ( pageno > 1 ) {
          halresp._links.previous = { href: baseURL.concat("?page=").concat(pageno-1)}
        }

        halresp._links.last = { href: baseURL.concat("?page=").concat(Math.ceil(totalsize/pagesize)) }

        res.json( halresp );
        });
    })
  }

  function troubleTicketFindHeader(req, res) {

  // Use connect method to connect to the server
  MongoClient.connect(mongourl, function(err, db) {
    assert.equal(null, err);

    var pageno = req.swagger.params.page.value ? parseInt(req.swagger.params.page.value) : 1;

    // Fixed page size for now

    const pagesize = 5

    const firstitem = (pageno-1)*pagesize
    const lastitem = firstitem + pagesize

    const baseURL = req.url.slice( 0, req.url.indexOf("?") )

    // Get the documents collection

    var collection = db.collection('troubleTicket');

    // Find some documents
    collection.find({},
        mongoUtils.fieldFilter(req.swagger.params.fields.value)).toArray(function(err, docs) {
        assert.equal(err, null);

        const totalsize = docs.length

        // slice page
        docs = docs.slice( firstitem, lastitem )

        // Generate Trouble Ticket
        docs.forEach( function( item ) {
          item = generateTroubleTicketDoc( item, baseURL.concat( "/" ).concat( item.id ) )
        })

        var links = {
            self: { href: req.url }
        }

        // Pagination attributes

        //halresp.page = pageno
        //halresp.totalrecords = totalsize
        //halresp.pagesize = pagesize
        //halresp.totalpages = Math.ceil(totalsize/pagesize)

        // Create pagination links

        if ( totalsize > (pageno * pagesize) ) {
          links.next = { href: baseURL.concat("?page=").concat(pageno+1)}
        }

        links.first = { href: baseURL.concat("?page=1")}

        if ( pageno > 1 ) {
          links.previous = { href: baseURL.concat("?page=").concat(pageno-1)}
        }

        links.last = { href: baseURL.concat("?page=").concat(Math.ceil(totalsize/pagesize)) }

        res.header( "x-links", JSON.stringify(links))

        res.json( docs );
        });
    })
  }

  // Get one troubleTicket by Id: GET /v2/hal/troubleTicket/{id}

  function troubleTicketGetHAL(req, res) {

    var troubleTicketId = parseInt(req.swagger.params.troubleTicketId.value);

    // Use connect method to connect to the server
    MongoClient.connect(mongourl, function(err, db) {
      assert.equal(null, err);

      // Get the documents collection
      var collection = db.collection('troubleTicket');
      const query = { id: troubleTicketId.toString() }

      // Find one document
      collection.findOne( query,
        mongoUtils.fieldFilter(req.swagger.params.fields.value), function(err, doc) {

        assert.equal(err, null);

        if ( doc != undefined  ) {
          const halDoc = generateTroubleTicketDoc( doc, req.url );

          if ( req.swagger.params.embed.value == "party" && doc.relatedParty != undefined ) {
            // embed party instance in _embedded element

            halDoc._embedded = []

            var partyPromises = []

            // Create array of promises to get party instances
            doc.relatedParty.forEach( function(party){
              partyPromises.push( generatePartyDoc(config.tt_host + party.href, halDoc._embedded));
            })

            // Request instances
            Promise.all( partyPromises ).then( function(){ res.json( halDoc )} )
          }
          else {
            res.json( halDoc )
          }
        } else {
          res.json( "{}")
        }
      })
    });
  }

function generatePartyDoc( partyUrl, embeddedDoc ) {
  return new Promise( function( resolve) {
          axios.get( partyUrl, {
            dataType: 'json',
            headers: {
              'Accept': 'application/hal+json'
            },
            mode: 'no-cors'
          }).then(function (response) {
              embeddedDoc.push( response.data )
              resolve();
          }).catch(function (error) {
              console.log(error)
              reject();
          })
    });
}

  // Create a new troubleTicket: POST /v2/troubleTicket

  function troubleTicketCreateHAL(req, res) {
  var troubleTicket = req.swagger.params.troubleTicket.value;

  var self = req.url.slice( 0, req.url.indexOf("?") ) + "/" + troubleTicket.id

  // Use connect method to connect to the server
  MongoClient.connect(mongourl, function(err, db) {
    assert.equal(null, err);

    // Get the documents collection
    var collection = db.collection('troubleTicket');
    // Insert some documents
    collection.insert( troubleTicket, function(err, result) {
      assert.equal(err, null)
      });
    db.close();
    });
    res.json( generateTroubleTicketDoc( troubleTicket, self ));
   }

function generateTroubleTicketDoc( doc, url ) {
  // delete the mongodb _id attribute from the JSON document
  delete doc["_id"]

  // create _links

  doc._links= {
            self: {
                href: url
                }
            }

  // create _actions

  doc._actions = [];

  var targetStates = troubleTicketStates.nextStates( doc.status );

  targetStates.forEach( function( state ) {
    doc._actions.push( {
      name: state,
      title: state,
      method: "PATCH",
      href: url,
      fields: [
        {
          name: "status",
          value: state
        },
        {
          name: "statusChangeReason",
          type: "string"
        }
      ]
    })
  })

  return doc;
}<commit_msg>generate id for hal create<commit_after>'use strict';

var config = require( './config.json' );

var util = require('util');
var Promise = require('promise');

var mongoUtils = require('../utilities/mongoUtils')

var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');

var axios = require('axios');

var troubleTicketStates = require('../utilities/troubleTicketStates')

// Mongo URL

var argv = require('minimist')(process.argv);
var dbhost = argv.dbhost ? argv.dbhost : config.db_host;
const mongourl = config.db_prot+"://"+dbhost+":"
        +config.db_port+"/"+config.db_name

/*
 Once you 'require' a module you can reference the things that it exports.  These are defined in module.exports.

 For a controller in a127 (which this is) you should export the functions referenced in your Swagger document by name.

 Either:
  - The HTTP Verb of the corresponding operation (get, put, post, delete, etc)
  - Or the operationId associated with the operation in your Swagger document

  In the starter/skeleton project the 'get' operation on the '/hello' path has an operationId named 'hello'.  Here,
  we specify that in the exports of this module that 'hello' maps to the function named 'hello'
 */

module.exports = {
  troubleTicketFindHAL,
  troubleTicketFindHeader,
  troubleTicketGetHAL,
  troubleTicketPatchHAL,
  troubleTicketCreateHAL };

  // Update troubleTicket by Id: PATCH /v2/troubleTicket/{id}

  function troubleTicketPatchHAL(req, res) {

  var troubleTicket = req.swagger.params.troubleTicket.value;
  var troubleTicketId = parseInt(req.swagger.params.troubleTicketId.value);

  // Use connect method to connect to the server
  MongoClient.connect(mongourl, function(err, db) {
    assert.equal(null, err);

    // Get the documents collection

    var collection = db.collection('troubleTicket');

    const query = { id: troubleTicketId.toString() }

    var patchDoc = { $set: troubleTicket }

    collection.update( query, patchDoc, function(err, doc) {
        assert.equal(err, null);

        // Find one document
        collection.findOne( query, function(err, doc) {
            doc = generateTroubleTicketDoc( doc );

            res.json( doc );
         })

        });
    })
  }

  // Find a troubleTicket: GET /v2/hal/troubleTicket/

  function troubleTicketFindHAL(req, res) {

  // Use connect method to connect to the server
  MongoClient.connect(mongourl, function(err, db) {
    assert.equal(null, err);

    var pageno = req.swagger.params.page.value ? parseInt(req.swagger.params.page.value) : 1;

    // Fixed page size for now

    const pagesize = 5

    const firstitem = (pageno-1)*pagesize
    const lastitem = firstitem + pagesize

    const baseURL = req.url.slice( 0, req.url.indexOf("?") )

    // Get the documents collection

    var collection = db.collection('troubleTicket');

    // Find some documents
    collection.find({},
        mongoUtils.fieldFilter(req.swagger.params.fields.value)).toArray(function(err, docs) {
        assert.equal(err, null);

        const totalsize = docs.length

        // slice page
        docs = docs.slice( firstitem, lastitem )

        // Generate Trouble Ticket
        docs.forEach( function( item ) {
          item = generateTroubleTicketDoc( item, baseURL.concat( "/" ).concat( item.id ) )
        })

        // create HAL response

        var halresp = {};

        // support v2 backward compatiblity if requested

        if ( req.swagger.params.embed.value == "v2" ) {
          halresp.troubleTicket = docs
          }

        halresp._links = {
            self: { href: req.url },
            item: []
        }

        // add embedded resources if requested

       if ( req.swagger.params.embed.value == "true" ) {
          halresp._embedded = {item: []}
          halresp._embedded.item = docs
          }

        // Add array of links
        docs.forEach( function( item ) {
            halresp._links.item.push( {
                  href: baseURL.concat( "/" ).concat( item.id )
                } )
        })

        // Pagination attributes

        halresp.page = pageno
        halresp.totalrecords = totalsize
        halresp.pagesize = pagesize
        halresp.totalpages = Math.ceil(totalsize/pagesize)

        // Create pagination links

        if ( totalsize > (pageno * pagesize) ) {
          halresp._links.next = { href: baseURL.concat("?page=").concat(pageno+1)}
        }

        halresp._links.first = { href: baseURL.concat("?page=1")}

        if ( pageno > 1 ) {
          halresp._links.previous = { href: baseURL.concat("?page=").concat(pageno-1)}
        }

        halresp._links.last = { href: baseURL.concat("?page=").concat(Math.ceil(totalsize/pagesize)) }

        res.json( halresp );
        });
    })
  }

  function troubleTicketFindHeader(req, res) {

  // Use connect method to connect to the server
  MongoClient.connect(mongourl, function(err, db) {
    assert.equal(null, err);

    var pageno = req.swagger.params.page.value ? parseInt(req.swagger.params.page.value) : 1;

    // Fixed page size for now

    const pagesize = 5

    const firstitem = (pageno-1)*pagesize
    const lastitem = firstitem + pagesize

    const baseURL = req.url.slice( 0, req.url.indexOf("?") )

    // Get the documents collection

    var collection = db.collection('troubleTicket');

    // Find some documents
    collection.find({},
        mongoUtils.fieldFilter(req.swagger.params.fields.value)).toArray(function(err, docs) {
        assert.equal(err, null);

        const totalsize = docs.length

        // slice page
        docs = docs.slice( firstitem, lastitem )

        // Generate Trouble Ticket
        docs.forEach( function( item ) {
          item = generateTroubleTicketDoc( item, baseURL.concat( "/" ).concat( item.id ) )
        })

        var links = {
            self: { href: req.url }
        }

        // Pagination attributes

        //halresp.page = pageno
        //halresp.totalrecords = totalsize
        //halresp.pagesize = pagesize
        //halresp.totalpages = Math.ceil(totalsize/pagesize)

        // Create pagination links

        if ( totalsize > (pageno * pagesize) ) {
          links.next = { href: baseURL.concat("?page=").concat(pageno+1)}
        }

        links.first = { href: baseURL.concat("?page=1")}

        if ( pageno > 1 ) {
          links.previous = { href: baseURL.concat("?page=").concat(pageno-1)}
        }

        links.last = { href: baseURL.concat("?page=").concat(Math.ceil(totalsize/pagesize)) }

        res.header( "x-links", JSON.stringify(links))

        res.json( docs );
        });
    })
  }

  // Get one troubleTicket by Id: GET /v2/hal/troubleTicket/{id}

  function troubleTicketGetHAL(req, res) {

    var troubleTicketId = parseInt(req.swagger.params.troubleTicketId.value);

    // Use connect method to connect to the server
    MongoClient.connect(mongourl, function(err, db) {
      assert.equal(null, err);

      // Get the documents collection
      var collection = db.collection('troubleTicket');
      const query = { id: troubleTicketId.toString() }

      // Find one document
      collection.findOne( query,
        mongoUtils.fieldFilter(req.swagger.params.fields.value), function(err, doc) {

        assert.equal(err, null);

        if ( doc != undefined  ) {
          const halDoc = generateTroubleTicketDoc( doc, req.url );

          if ( req.swagger.params.embed.value == "party" && doc.relatedParty != undefined ) {
            // embed party instance in _embedded element

            halDoc._embedded = []

            var partyPromises = []

            // Create array of promises to get party instances
            doc.relatedParty.forEach( function(party){
              partyPromises.push( generatePartyDoc(config.tt_host + party.href, halDoc._embedded));
            })

            // Request instances
            Promise.all( partyPromises ).then( function(){ res.json( halDoc )} )
          }
          else {
            res.json( halDoc )
          }
        } else {
          res.json( "{}")
        }
      })
    });
  }

function generatePartyDoc( partyUrl, embeddedDoc ) {
  return new Promise( function( resolve) {
          axios.get( partyUrl, {
            dataType: 'json',
            headers: {
              'Accept': 'application/hal+json'
            },
            mode: 'no-cors'
          }).then(function (response) {
              embeddedDoc.push( response.data )
              resolve();
          }).catch(function (error) {
              console.log(error)
              reject();
          })
    });
}

  // Create a new troubleTicket: POST /v2/troubleTicket

  function troubleTicketCreateHAL(req, res) {
  var troubleTicket = req.swagger.params.troubleTicket.value;

  if (troubleTicket.id == undefined) {
    troubleTicket.id = guid();
  }

  var self = req.url.slice( 0, req.url.indexOf("?") ) + "/" + troubleTicket.id

  // Use connect method to connect to the server
  MongoClient.connect(mongourl, function(err, db) {
    assert.equal(null, err);

    // Get the documents collection
    var collection = db.collection('troubleTicket');
    // Insert some documents
    collection.insert( troubleTicket, function(err, result) {
      assert.equal(err, null)
      });
    db.close();
    });
    res.json( generateTroubleTicketDoc( troubleTicket, self ));
   }

function guid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }
  return s4() + s4() + '-' + s4();
}

function generateTroubleTicketDoc( doc, url ) {
  // delete the mongodb _id attribute from the JSON document
  delete doc["_id"]

  // create _links

  doc._links= {
            self: {
                href: url
                }
            }

  // create _actions

  doc._actions = [];

  var targetStates = troubleTicketStates.nextStates( doc.status );

  targetStates.forEach( function( state ) {
    doc._actions.push( {
      name: state,
      title: state,
      method: "PATCH",
      href: url,
      fields: [
        {
          name: "status",
          value: state
        },
        {
          name: "statusChangeReason",
          type: "string"
        }
      ]
    })
  })

  return doc;
}<|endoftext|>


<commit_before>var path = require('path');
var webpack = require('webpack');

module.exports = {
    devtool: 'eval',
    entry: [
        'bootstrap-loader',
        'webpack-material-design-icons',
        './src/index.js'
    ],
    output: {
        path: path.join(process.env.PWD||process.cwd(), 'dist'),
        filename: 'bundle.js',
        publicPath: '/static/',
        libraryTarget: 'umd'
    },
    externals: {
        'react': { commonjs: 'react', commonjs2: 'react', amd: 'react', root: 'React' },
        'react-dom': { commonjs: 'react-dom', commonjs2: 'react-dom', amd: 'react-dom', root: 'ReactDOM' },
        'react-addons-css-transition-group': { commonjs: 'react-addons-css-transition-group', commonjs2: 'react-addons-css-transition-group', amd: 'react-addons-css-transition-group', root: ['React','addons','CSSTransitionGroup']},
        'react-i18next':  { commonjs: 'react-i18next', commonjs2:'react-i18next', amd: 'react-i18next', root: 'react-i18next' }
    },
    module: {
        rules: [{
            test: /\.jsx?$/,
            loader: 'babel-loader',
            query: {
                presets: ['es2015', 'stage-0', 'react']
            },
            include: [
                path.join(process.env.PWD||process.cwd(), './src'),
                path.join(process.env.PWD||process.cwd(), './test'),
            ]
        }, {
            test: /\.(styl)$/,
            use: [
                'style-loader',
                'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]',
                {
                    loader: 'stylus-loader?paths=node_modules/bootstrap-stylus/stylus/',
                    options: {
                        use: [require('nib')()],
                        import: ['~nib/index.styl', path.join(__dirname, 'styl/app.styl')]
                    },
                },
            ],
        }, {
            test: /\.(css)$/,
            use: [
                'style-loader',
                'css-loader?importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]',
            ]
        }, {
            test: /\.(jpg|png|svg|woff2?|eot|ttf).*$/,
            loader: 'url-loader?limit=100000'
        }, {
            test:/bootstrap-sass[\/\\]assets[\/\\]javascripts[\/\\]/,
            loader: 'imports-loader?jQuery=jquery'
        }]
    }
};
<commit_msg>Extract styles -> styles.css<commit_after>var path = require('path');
var webpack = require('webpack');
var ExtractStyle = require("extract-text-webpack-plugin");

module.exports = {
    devtool: 'eval',
    entry: [
        'bootstrap-loader',
        'webpack-material-design-icons',
        './src/index.js'
    ],
    output: {
        path: path.join(process.env.PWD||process.cwd(), 'dist'),
        filename: 'bundle.js',
        publicPath: '/static/',
        libraryTarget: 'umd'
    },
    externals: {
        'react': { commonjs: 'react', commonjs2: 'react', amd: 'react', root: 'React' },
        'react-dom': { commonjs: 'react-dom', commonjs2: 'react-dom', amd: 'react-dom', root: 'ReactDOM' },
        'react-addons-css-transition-group': { commonjs: 'react-addons-css-transition-group', commonjs2: 'react-addons-css-transition-group', amd: 'react-addons-css-transition-group', root: 'react-addons-css-transition-group'},
        'react-i18next':  { commonjs: 'react-i18next', commonjs2:'react-i18next', amd: 'react-i18next', root: 'react-i18next' }
    },

    module: {
        rules: [{
            test: /\.jsx?$/,
            loader: 'babel-loader',
            query: {
                presets: ['es2015', 'stage-0', 'react']
            },
            include: [
                path.join(process.env.PWD||process.cwd(), './src'),
                path.join(process.env.PWD||process.cwd(), './test'),
            ]
        }, {
            test: /\.(styl)$/,
            loader: ExtractStyle.extract({
                fallback:  "style-loader",
                loader: [
                    "css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]",
                    {
                        loader: 'stylus-loader?paths=node_modules/bootstrap-stylus/stylus/',
                        options: {
                            use: [require('nib')()],
                            import: ['~nib/index.styl', path.join(__dirname, 'styl/app.styl')]
                        }
                    }
                ]

            })
        }, {
            test: /\.css$/,
            loader: ExtractStyle.extract({
                fallback:  "style-loader",
                loader: "css-loader?importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]"
            })
        }, {
            test: /\.(jpg|png|svg|woff2?|eot|ttf).*$/,
            loader: 'url-loader?limit=100000'
        }, {
            test:/bootstrap-sass[\/\\]assets[\/\\]javascripts[\/\\]/,
            loader: 'imports-loader?jQuery=jquery'
        }]
    },
    plugins: [
        new ExtractStyle('styles.css')
    ]
};
<|endoftext|>


<commit_before>'use strict';
var LIVERELOAD_PORT = 35729;
var lrSnippet = require('connect-livereload')({ port: LIVERELOAD_PORT });
var mountFolder = function (connect, dir) {
  return connect.static(require('path').resolve(dir));
};
var babel = require('rollup-plugin-babel');

module.exports = function (grunt) {
  // load all grunt tasks
  require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
  grunt.loadNpmTasks('assemble');

  grunt.initConfig({
    watch: {
      grunt: {
        files: [ 'Gruntfile.js' ]
      },
      livereload: {
        options: {
          livereload: LIVERELOAD_PORT
        },
        files: [
          'build/{,*/}*.html',
          '{,site/**/}*.css',
          '{,test/**/,site/**/}*.js'
        ]
      },
      js: {
        files: [
          'src/{,*/}*.js',
          'test/{,*/}*.js'
        ],
        tasks: [
          'rollup'
        ]
      },
      stylus: {
        files: [
          'src/{,*/}*.styl'
        ],
        tasks: [ 'stylus:server' ]
      },
      assemble: {
        files: [
          'site/{,*/}*.{hbs,html,md}'
        ],
        tasks: [ 'assemble' ]
      }
    },
    connect: {
      options: {
        port: 9000,
        hostname: '0.0.0.0'
      },
      livereload: {
        options: {
          middleware: function (connect) {
            return [
              lrSnippet,
              mountFolder(connect, './site/'),
              mountFolder(connect, './build/'),
              mountFolder(connect, './')
            ];
          }
        }
      },
      dist: {
        options: {
          middleware: function (connect) {
            return [
              mountFolder(connect, './build/')
            ];
          }
        }
      },
      test: {
        options: {
          middleware: function (connect) {
            return [
              mountFolder(connect, './')
            ];
          }
        }
      }
    },
    standard: {
      options: {
        parser: 'babel-eslint'
      },
      server: {
        src: [
          '{src,test}/{,*/}*.js'
        ]
      }
    },
    stylus: {
      server: {
        options: {
          compress: false
        },
        files: {
          'jotted.css': 'src/core.styl'
        }
      },
      dist: {
        options: {
          compress: true,
        },
        files: {
          'jotted.min.css': 'src/core.styl'
        }
      }
    },
    rollup: {
      options: {
        sourceMap: true,
        plugins: [
          babel({
            exclude: 'node_modules/**'
          })
        ],
        format: 'umd',
        moduleName: 'Jotted'
      },
      files: {
        src: 'src/core.js',
        dest: 'jotted.js'
      }
    },
    uglify: {
      dist: {
        files: {
          'jotted.min.js': 'jotted.js'
        }
      }
    },
    'saucelabs-jasmine': {
      all: {
        options: {
          urls: [ 'http://127.0.0.1:9000/test' ],
          detailedError: true,
          browsers: [
            {
              browserName: 'chrome',
              platform: 'Linux'
            }, {
              browserName: 'firefox',
              platform: 'Linux'
            }, {
              browserName: 'android',
              platform: 'Linux',
              version: '5.1'
            }, {
              browserName: 'internet explorer',
              platform: 'Windows 7',
              version: '9.0'
            }, {
              browserName: 'internet explorer',
              platform: 'Windows 8',
              version: '10.0'
            }, {
              browserName: 'microsoftedge',
              platform: 'Windows 10'
            }, {
              browserName: 'safari',
              platform: 'OS X 10.11',
              version: '9.0'
            }, {
              browserName: 'iphone',
              platform: 'OS X 10.10',
              version: '9.2'
            }
          ]
        }
      }
    },
    assemble: {
      options: {
        layoutdir: 'site/layouts',
        partials: 'site/partials/*.md'
      },
      site: {
        files: [{
          expand: true,
          cwd: 'site',
          src: '{,*/}*.{hbs,md}',
          dest: 'build'
        }]
      }
    },
    clean: {
      site: {
        src: [
          'build/',
          './jotted.*'
        ]
      }
    },
    copy: {
      site: {
        files: [
          {
            expand: true,
            cwd: 'site/',
            src: [
              '**/*',
              '!**/*.{html,hbs,md}'
            ],
            dest: 'build/'
          },
          {
            expand: true,
            src: [
              'bower_components/**/*'
            ],
            dest: 'build/'
          },
          {
            expand: true,
            src: [
              'build/**/*'
            ],
            dest: 'build/'
          },
          {
            expand: true,
            src: [
              'jotted*'
            ],
            dest: 'build/'
          }
        ]
      }
    },
    buildcontrol: {
      options: {
        dir: 'build',
        commit: true,
        push: true
      },
      site: {
        options: {
          remote: 'git@github.com:ghinda/jotted.git',
          branch: 'gh-pages'
        }
      }
    }
  });

  grunt.registerTask('server', function (target) {
    if (target === 'dist') {
      return grunt.task.run([
        'default',
        'copy',
        'connect:dist:keepalive'
      ]);
    }

    grunt.task.run([
      'default',
      'connect:livereload',
      'watch'
    ]);
  });

  grunt.registerTask('test', [
    'default',
    'connect:test',
    'saucelabs-jasmine'
  ]);

  grunt.registerTask('default', [
    'clean',
    'standard',
    'rollup',
    'uglify',
    'stylus',
    'assemble'
  ]);

  grunt.registerTask('deploy', [
    'test',
    'copy',
    'buildcontrol'
  ]);

};
<commit_msg>Fix copy task issue with copying static html files.<commit_after>'use strict';
var LIVERELOAD_PORT = 35729;
var lrSnippet = require('connect-livereload')({ port: LIVERELOAD_PORT });
var mountFolder = function (connect, dir) {
  return connect.static(require('path').resolve(dir));
};
var babel = require('rollup-plugin-babel');

module.exports = function (grunt) {
  // load all grunt tasks
  require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
  grunt.loadNpmTasks('assemble');

  grunt.initConfig({
    watch: {
      grunt: {
        files: [ 'Gruntfile.js' ]
      },
      livereload: {
        options: {
          livereload: LIVERELOAD_PORT
        },
        files: [
          'build/{,*/}*.html',
          '{,site/**/}*.css',
          '{,test/**/,site/**/}*.js'
        ]
      },
      js: {
        files: [
          'src/{,*/}*.js',
          'test/{,*/}*.js'
        ],
        tasks: [
          'rollup'
        ]
      },
      stylus: {
        files: [
          'src/{,*/}*.styl'
        ],
        tasks: [ 'stylus:server' ]
      },
      assemble: {
        files: [
          'site/{,*/}*.{hbs,html,md}'
        ],
        tasks: [ 'assemble' ]
      }
    },
    connect: {
      options: {
        port: 9000,
        hostname: '0.0.0.0'
      },
      livereload: {
        options: {
          middleware: function (connect) {
            return [
              lrSnippet,
              mountFolder(connect, './site/'),
              mountFolder(connect, './build/'),
              mountFolder(connect, './')
            ];
          }
        }
      },
      dist: {
        options: {
          middleware: function (connect) {
            return [
              mountFolder(connect, './build/')
            ];
          }
        }
      },
      test: {
        options: {
          middleware: function (connect) {
            return [
              mountFolder(connect, './')
            ];
          }
        }
      }
    },
    standard: {
      options: {
        parser: 'babel-eslint'
      },
      server: {
        src: [
          '{src,test}/{,*/}*.js'
        ]
      }
    },
    stylus: {
      server: {
        options: {
          compress: false
        },
        files: {
          'jotted.css': 'src/core.styl'
        }
      },
      dist: {
        options: {
          compress: true,
        },
        files: {
          'jotted.min.css': 'src/core.styl'
        }
      }
    },
    rollup: {
      options: {
        sourceMap: true,
        plugins: [
          babel({
            exclude: 'node_modules/**'
          })
        ],
        format: 'umd',
        moduleName: 'Jotted'
      },
      files: {
        src: 'src/core.js',
        dest: 'jotted.js'
      }
    },
    uglify: {
      dist: {
        files: {
          'jotted.min.js': 'jotted.js'
        }
      }
    },
    'saucelabs-jasmine': {
      all: {
        options: {
          urls: [ 'http://127.0.0.1:9000/test' ],
          detailedError: true,
          browsers: [
            {
              browserName: 'chrome',
              platform: 'Linux'
            }, {
              browserName: 'firefox',
              platform: 'Linux'
            }, {
              browserName: 'android',
              platform: 'Linux',
              version: '5.1'
            }, {
              browserName: 'internet explorer',
              platform: 'Windows 7',
              version: '9.0'
            }, {
              browserName: 'internet explorer',
              platform: 'Windows 8',
              version: '10.0'
            }, {
              browserName: 'microsoftedge',
              platform: 'Windows 10'
            }, {
              browserName: 'safari',
              platform: 'OS X 10.11',
              version: '9.0'
            }, {
              browserName: 'iphone',
              platform: 'OS X 10.10',
              version: '9.2'
            }
          ]
        }
      }
    },
    assemble: {
      options: {
        layoutdir: 'site/layouts',
        partials: 'site/partials/*.md'
      },
      site: {
        files: [{
          expand: true,
          cwd: 'site',
          src: '{,*/}*.{hbs,md}',
          dest: 'build'
        }]
      }
    },
    clean: {
      site: {
        src: [
          'build/',
          './jotted.*'
        ]
      }
    },
    copy: {
      site: {
        files: [
          {
            expand: true,
            cwd: 'site/',
            src: [
              '**/*',
              '!**/*.{hbs,md}'
            ],
            dest: 'build/'
          },
          {
            expand: true,
            src: [
              'bower_components/**/*'
            ],
            dest: 'build/'
          },
          {
            expand: true,
            src: [
              'build/**/*'
            ],
            dest: 'build/'
          },
          {
            expand: true,
            src: [
              'jotted*'
            ],
            dest: 'build/'
          }
        ]
      }
    },
    buildcontrol: {
      options: {
        dir: 'build',
        commit: true,
        push: true
      },
      site: {
        options: {
          remote: 'git@github.com:ghinda/jotted.git',
          branch: 'gh-pages'
        }
      }
    }
  });

  grunt.registerTask('server', function (target) {
    if (target === 'dist') {
      return grunt.task.run([
        'default',
        'copy',
        'connect:dist:keepalive'
      ]);
    }

    grunt.task.run([
      'default',
      'connect:livereload',
      'watch'
    ]);
  });

  grunt.registerTask('test', [
    'default',
    'connect:test',
    'saucelabs-jasmine'
  ]);

  grunt.registerTask('default', [
    'clean',
    'standard',
    'rollup',
    'uglify',
    'stylus',
    'assemble'
  ]);

  grunt.registerTask('deploy', [
    'test',
    'copy',
    'buildcontrol'
  ]);

};
<|endoftext|>