<commit_before>var JS_GAME = {};

JS_GAME.game = (function () {
  var isKeyDown = [];
  var context;
  var userData = [];
  var enemies = [];
  var enemyStride = 7;
  var frameLength = 1;// in milliseconds
  var socket;
  var connected = false;
  var user = "";
  var pass = "";
  var windowWidth = $(window).innerWidth();
  var windowHeight = $(window).innerHeight();
  var textures = new Object();

  function init() {
  	document.documentElement.style.overflow = 'hidden';  // firefox, chrome
    document.body.scroll = "no"; // ie only

    user = document.getElementById("loginInfo").user.value;
    pass = document.getElementById("loginInfo").pass.value;
    if (user.indexOf(",") >= 0 || user.indexOf(":") >= 0){
      document.getElementById("loginInfo").user.value = "INVALID INPUT";
      return;
    }

    socket = new WebSocket("ws:167.88.120.57:38734");

    socket.onopen = function() {
      connected = true;
      socket.send("login:" + user + "," + pass);
    };

    socket.onmessage = function(message) {
      if (message.data.indexOf("pos") == 0){
        userData = message.data.split(":")[1].split(",");
        for (i = 0; i < 4; i++) {
          userData[i] = Number(userData[i])|0;
        }
      } else if (message.data.indexOf("dat") == 0){
        enemies = message.data.split(":")[1].split(",");
        enemyStride = Number(message.data.split(":")[0].replace("dat", ""));
      }
    };

    socket.onclose = function() {
      window.location.reload(false);
    };

    socket.onerror = function() {

    };

    $("body").empty();

    for (i = 0; i < 256; i++){
      isKeyDown[i] = false;
    }
    $('body').append('<canvas id="GameCanvas">');
    canvasElement = $('#GameCanvas');
    canvasElement.attr({
      width: windowWidth,
      height: windowHeight,
      tabIndex: 0,
      onblur: clearInput,
    }).focus();
    window.onblur = clearInput;

    var canvas = canvasElement[0];

    window.addEventListener( "keydown", keyPress, false);
    window.addEventListener( "keyup", keyRelease, false);
    context = canvas.getContext('2d');
    context.globalCompositeOperation = "normal";
    gameLoop();

    $(window).resize(function() {
      windowWidth = $(window).innerWidth();
      windowHeight = $(window).innerHeight();
      canvasElement.attr({
        width: windowWidth,
        height: windowHeight,
      });
    });
  }

  function gameLoop() {
    var keyData = "";
    for (i = 0; i < 256; i++){
      keyData += isKeyDown[i] ? 1 : 0;
    }
    try {
      socket.send("keys:" + keyData);
    } catch (err) {
    }
    context.clearRect(0, 0, windowWidth, windowHeight);
    context.fillStyle = "#FFFFFF"
    context.fillRect(0, 0, windowWidth, windowHeight);
    //draw BG
    for (a = -2; a < 3; a++){
    	for (b = -2; b < 3; b++){
    		context.drawImage(getImage("BG"), (gPIVX(0) % 1000) + (1000 * a), (gPIVY(0) % 1000) + (1000 * b), 1000, 1000);
    	}
    }
    //draw enemies
    for (i = 0; i < enemies.length; i += enemyStride){
      context.fillStyle = enemies[i+4];
      context.drawImage(getImageMasked("player", enemies[i+4]),gPIVX(enemies[i]), gPIVY(enemies[i+1]), enemies[i+2], enemies[i+3]);
    }

    //draw enemy names
    for (i = 0; i < enemies.length; i += enemyStride){
      context.fillStyle = enemies[i+4];
      context.fillText(enemies[i+5],(gPIVX(enemies[i]) - (context.measureText(enemies[i+5]).width / 2)) + 15,gPIVY(enemies[i+1]) - 5);
    }

    //draw player name
    //context.fillStyle = userData[4];
    //context.font = "15px Arial";
    //context.fillText(userData[5],(gPIVX(userData[0]) - (context.measureText(userData[5]).width / 2)) + 15,gPIVY(userData[1]) - 5);

    setTimeout(gameLoop, frameLength);
  }

  function gPIVX(x){
    //getPositionInViewportX
    var ret = new Object();
    return ((x - (userData[0] + (userData[2] / 2))) + (windowWidth / 2.0));
  }
  function gPIVY(y){
    //getPositionInViewportY
    return ((y - (userData[1] + (userData[3] / 2))) + (windowHeight / 2.0));
  }

  function clearInput(){
    for (i = 0; i < 256; i++){
      isKeyDown[i] = false;
    }
  }

  function keyPress(e){
    e.preventDefault();
    isKeyDown[e.keyCode] = true;
    return false;
  }
  function keyRelease(e){
    e.preventDefault();
    isKeyDown[e.keyCode] = false;
  }
  function isKeyPressed(c){
    return isKeyDown[c.charCodeAt(0)];
  }

  function getImageData(image){
    var tempCanv = document.createElement('canvas');
    tempCanv.width = image.width;
    tempCanv.height = image.height;
    var tempCTX = tempCanv.getContext('2d');
    tempCTX.drawImage(image, 0, 0, image.width, image.height);
    return tempCTX.getImageData(0, 0, image.width, image.height);
  }

  function getImageFromData(data){
    var tempCanv = document.createElement('canvas');
    tempCanv.width = data.width;
    tempCanv.height = data.height;
    var tempCTX = tempCanv.getContext('2d');
    tempCTX.putImageData(data, 0, 0);
    var src = tempCanv.toDataURL("image/png");
    var img = new Image();
    img.src = src;
    return img;
  }

  function getImage(name){
  	if ((name) in textures){
  		return textures[name];
  	} else {
  		textures[name] = new Image;
  		textures[name].src = '/assets/images/' + name + '.png';
  		return textures[name];
  	}
  }
  function getImageMasked(name, color){
  	if ((name + "-mask" + color) in textures){
  		return textures[name + "-mask" + color];
  	}
    var image = getImage(name);
    var mask = getImage(name + "-mask");
    if (image.width == 0 || image.height == 0 || mask.width == 0 || mask.height == 0){
      return new Image();
    }
    var maskData = getImageData(mask);
    var regex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
    var colorRGBS = regex.exec(color);
    var colorRGB = [];
    for (i = 0; i < 3; i++){
      colorRGB[i] = parseInt(colorRGBS[i+1], 16);
    }
    for (i = 0; i < maskData.data.length; i+=4){
      maskData.data[i] =  colorRGB[0];
      maskData.data[i+1] =  colorRGB[1];
      maskData.data[i+2] =  colorRGB[2];
    }
    var tempCanv = document.createElement('canvas');
    tempCanv.width = image.width;
    tempCanv.height = image.height;
    var tempCTX=tempCanv.getContext("2d");
    tempCTX.drawImage(image,0,0,image.width, image.height);
    tempCTX.drawImage(getImageFromData(maskData),0,0,maskData.width, maskData.height);
    var ret = new Image();
    ret.src = tempCanv.toDataURL("image/png");
    textures[name + "-mask" + color] = ret;
    return ret;
  }

  return {
    init: init
  };
})();

$(document).ready(function() {
  $("#loginInfo").submit(function(e){
    e.preventDefault();
    JS_GAME.game.init();
    return false;
  });
});
<commit_msg>added pos text<commit_after>var JS_GAME = {};

JS_GAME.game = (function () {
  var isKeyDown = [];
  var context;
  var userData = [];
  var enemies = [];
  var enemyStride = 7;
  var frameLength = 1;// in milliseconds
  var socket;
  var connected = false;
  var user = "";
  var pass = "";
  var windowWidth = $(window).innerWidth();
  var windowHeight = $(window).innerHeight();
  var textures = new Object();

  function init() {
  	document.documentElement.style.overflow = 'hidden';  // firefox, chrome
    document.body.scroll = "no"; // ie only

    user = document.getElementById("loginInfo").user.value;
    pass = document.getElementById("loginInfo").pass.value;
    if (user.indexOf(",") >= 0 || user.indexOf(":") >= 0){
      document.getElementById("loginInfo").user.value = "INVALID INPUT";
      return;
    }

    socket = new WebSocket("ws:167.88.120.57:38734");

    socket.onopen = function() {
      connected = true;
      socket.send("login:" + user + "," + pass);
    };

    socket.onmessage = function(message) {
      if (message.data.indexOf("pos") == 0){
        userData = message.data.split(":")[1].split(",");
        for (i = 0; i < 4; i++) {
          userData[i] = Number(userData[i])|0;
        }
      } else if (message.data.indexOf("dat") == 0){
        enemies = message.data.split(":")[1].split(",");
        enemyStride = Number(message.data.split(":")[0].replace("dat", ""));
      }
    };

    socket.onclose = function() {
      window.location.reload(false);
    };

    socket.onerror = function() {

    };

    $("body").empty();

    for (i = 0; i < 256; i++){
      isKeyDown[i] = false;
    }
    $('body').append('<canvas id="GameCanvas">');
    canvasElement = $('#GameCanvas');
    canvasElement.attr({
      width: windowWidth,
      height: windowHeight,
      tabIndex: 0,
      onblur: clearInput,
    }).focus();
    window.onblur = clearInput;

    var canvas = canvasElement[0];

    window.addEventListener( "keydown", keyPress, false);
    window.addEventListener( "keyup", keyRelease, false);
    context = canvas.getContext('2d');
    context.globalCompositeOperation = "normal";
    gameLoop();

    $(window).resize(function() {
      windowWidth = $(window).innerWidth();
      windowHeight = $(window).innerHeight();
      canvasElement.attr({
        width: windowWidth,
        height: windowHeight,
      });
    });
  }

  function gameLoop() {
    var keyData = "";
    for (i = 0; i < 256; i++){
      keyData += isKeyDown[i] ? 1 : 0;
    }
    try {
      socket.send("keys:" + keyData);
    } catch (err) {
    }
    context.clearRect(0, 0, windowWidth, windowHeight);
    context.fillStyle = "#FFFFFF"
    context.fillRect(0, 0, windowWidth, windowHeight);
    //draw BG
    for (a = -2; a < 3; a++){
    	for (b = -2; b < 3; b++){
    		context.drawImage(getImage("BG"), (gPIVX(0) % 1000) + (1000 * a), (gPIVY(0) % 1000) + (1000 * b), 1000, 1000);
    	}
    }
    //draw enemies
    for (i = 0; i < enemies.length; i += enemyStride){
      context.fillStyle = enemies[i+4];
      context.drawImage(getImageMasked("player", enemies[i+4]),gPIVX(enemies[i]), gPIVY(enemies[i+1]), enemies[i+2], enemies[i+3]);
    }

    //draw enemy names
    for (i = 0; i < enemies.length; i += enemyStride){
      context.fillStyle = enemies[i+4];
      context.fillText(enemies[i+5],(gPIVX(enemies[i]) - (context.measureText(enemies[i+5]).width / 2)) + 15,gPIVY(enemies[i+1]) - 5);
    }

    context.fillText("Pos: (" + userData[0] + ", " + userData[1] + ")",5,5);

    setTimeout(gameLoop, frameLength);
  }

  function gPIVX(x){
    //getPositionInViewportX
    var ret = new Object();
    return ((x - (userData[0] + (userData[2] / 2))) + (windowWidth / 2.0));
  }
  function gPIVY(y){
    //getPositionInViewportY
    return ((y - (userData[1] + (userData[3] / 2))) + (windowHeight / 2.0));
  }

  function clearInput(){
    for (i = 0; i < 256; i++){
      isKeyDown[i] = false;
    }
  }

  function keyPress(e){
    e.preventDefault();
    isKeyDown[e.keyCode] = true;
    return false;
  }
  function keyRelease(e){
    e.preventDefault();
    isKeyDown[e.keyCode] = false;
  }
  function isKeyPressed(c){
    return isKeyDown[c.charCodeAt(0)];
  }

  function getImageData(image){
    var tempCanv = document.createElement('canvas');
    tempCanv.width = image.width;
    tempCanv.height = image.height;
    var tempCTX = tempCanv.getContext('2d');
    tempCTX.drawImage(image, 0, 0, image.width, image.height);
    return tempCTX.getImageData(0, 0, image.width, image.height);
  }

  function getImageFromData(data){
    var tempCanv = document.createElement('canvas');
    tempCanv.width = data.width;
    tempCanv.height = data.height;
    var tempCTX = tempCanv.getContext('2d');
    tempCTX.putImageData(data, 0, 0);
    var src = tempCanv.toDataURL("image/png");
    var img = new Image();
    img.src = src;
    return img;
  }

  function getImage(name){
  	if ((name) in textures){
  		return textures[name];
  	} else {
  		textures[name] = new Image;
  		textures[name].src = '/assets/images/' + name + '.png';
  		return textures[name];
  	}
  }
  function getImageMasked(name, color){
  	if ((name + "-mask" + color) in textures){
  		return textures[name + "-mask" + color];
  	}
    var image = getImage(name);
    var mask = getImage(name + "-mask");
    if (image.width == 0 || image.height == 0 || mask.width == 0 || mask.height == 0){
      return new Image();
    }
    var maskData = getImageData(mask);
    var regex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
    var colorRGBS = regex.exec(color);
    var colorRGB = [];
    for (i = 0; i < 3; i++){
      colorRGB[i] = parseInt(colorRGBS[i+1], 16);
    }
    for (i = 0; i < maskData.data.length; i+=4){
      maskData.data[i] =  colorRGB[0];
      maskData.data[i+1] =  colorRGB[1];
      maskData.data[i+2] =  colorRGB[2];
    }
    var tempCanv = document.createElement('canvas');
    tempCanv.width = image.width;
    tempCanv.height = image.height;
    var tempCTX=tempCanv.getContext("2d");
    tempCTX.drawImage(image,0,0,image.width, image.height);
    tempCTX.drawImage(getImageFromData(maskData),0,0,maskData.width, maskData.height);
    var ret = new Image();
    ret.src = tempCanv.toDataURL("image/png");
    textures[name + "-mask" + color] = ret;
    return ret;
  }

  return {
    init: init
  };
})();

$(document).ready(function() {
  $("#loginInfo").submit(function(e){
    e.preventDefault();
    JS_GAME.game.init();
    return false;
  });
});
<|endoftext|>


<commit_before>---
layout: null
---

$(function() {
  var toc     = $('.toc-link'),
      sidebar = $('#sidebar'),
      main    = $('#main'),
      menu    = $('#menu'),
      posttoc = $('#post-toc-menu'),
      x1, y1;

  // run this function after pjax load.
  var afterPjax = function() {
    // open links in new tab.
    $('#main').find('a').filter(function() {
      return this.hostname != window.location.hostname;
    }).attr('target', '_blank');

    // generate toc
    var toc = $('#post-toc-ul');
    // Empty TOC and generate an entry for h1
    toc.empty().append('
' + $('#post-title').text() + '
');

    // Generate entries for h2 and h3
    $('.post').children('h2,h3').each(function() {
      // Generate random ID for each heading
      $(this).attr('id', function() {
        var ID = "", alphabet = "abcdefghijklmnopqrstuvwxyz";

        for(var i=0; i < 5; i++) {
          ID += alphabet.charAt(Math.floor(Math.random() * alphabet.length));
        }
        return ID;
      });

      if ($(this).prop("tagName") == 'H2') {
        toc.append('
' + $(this).text() + '
');
      } else {
        toc.append('
' + $(this).text() + '
');
      }
    });

    // Smooth scrolling
    $('.js-anchor-link').on('click', function() {
      var target = $(this.hash);
      main.animate({scrollTop: target.offset().top + main.scrollTop() - 70}, 500);
    });

    // discus comment.
    {% if site.disqus.shortname %}
      var ds_loaded = false;
      window.disqus_shortname = "{{ site.disqus.shortname }}";
      main.scroll(function(){
        var nScrollHight = $(this)[0].scrollHeight;
        var nScrollTop = $(this)[0].scrollTop;
        if(!ds_loaded && nScrollTop + main.height() >= nScrollHight - 100) {
          $.ajax({
            type: 'GET',
            url: 'http://' + disqus_shortname + '.disqus.com/embed.js',
            dataType: 'script',
            cache: true
          });
          ds_loaded = true;
        }
      });
    {% endif %}
    // your scripts
  };
  afterPjax();

  // NProgress
  NProgress.configure({ showSpinner: false });

  // Pjax
  $(document).pjax('#sidebar-avatar, .toc-link', '#main', {
    fragment: '#main',
    timeout: 3000
  });

  $(document).on({
    'pjax:click': function() {
      NProgress.start();
      main.removeClass('fadeIn');
    },
    'pjax:end': function() {
      afterPjax();
      NProgress.done();
      main.scrollTop(0).addClass('fadeIn');
      // only remove open in small screen
      if($(window).width() <= 1024) {
        menu.add(sidebar).add(main).removeClass('open');
      }
    }
  });

  // Tags Filter
  $('#sidebar-tags').on('click', '.sidebar-tag', function() {
    var filter = $(this).data('filter');
    toc.hide();
    if (filter === 'recent') {
      toc.slice(0, {{ site.recent_num }}).fadeIn(350);
    } else {
      $('.toc-link[data-tags="' + filter + '"]').fadeIn(350);
    }
    $(this).addClass('active').siblings().removeClass('active');
  });
  // Only show recent
  toc.hide();
  toc.slice(0, {{ site.recent_num }}).fadeIn(350);

  // Menu
  menu.on('click', function() {
    $(this).add(sidebar).add(menu).add(main).toggleClass('open');
  });

  // right toc
  posttoc.on('click', function() {
    $('#post-toc').toggleClass('open');
  });

  // Search
  $('#search-input').on('input', function(e){
    var blogs = $(".toc-link").filter(function() {
      var reg = new RegExp($('#search-input').val(), "i");
      return reg.test($(this).text());
    });
    toc.hide();
    blogs.fadeIn(350);
  });

});
<commit_msg>fix javascript<commit_after>---
layout: null
---

$(function() {
  var toc     = $('.toc-link'),
      sidebar = $('#sidebar'),
      main    = $('#main'),
      menu    = $('#menu'),
      posttoc = $('#post-toc-menu'),
      x1, y1;

  // run this function after pjax load.
  var afterPjax = function() {
    // open links in new tab.
    $('#main').find('a').filter(function() {
      return this.hostname != window.location.hostname;
    }).attr('target', '_blank');

    // generate toc
    var toc = $('#post-toc-ul');
    // Empty TOC and generate an entry for h1
    toc.empty().append('
' + $('#post-title').text() + '
');

    // Generate entries for h2 and h3
    $('.post').children('h2,h3').each(function() {
      // Generate random ID for each heading
      $(this).attr('id', function() {
        var ID = "", alphabet = "abcdefghijklmnopqrstuvwxyz";

        for(var i=0; i < 5; i++) {
          ID += alphabet.charAt(Math.floor(Math.random() * alphabet.length));
        }
        return ID;
      });

      if ($(this).prop("tagName") == 'H2') {
        toc.append('
' + $(this).text() + '
');
      } else {
        toc.append('
' + $(this).text() + '
');
      }
    });

    // Smooth scrolling
    $('.js-anchor-link').on('click', function() {
      var target = $(this.hash);
      main.animate({scrollTop: target.offset().top + main.scrollTop() - 70}, 500);
    });

    main.scrollTop(0).addClass('fadeIn');
    // only remove open in small screen
    if($(window).width() <= 1024) {
      menu.add(sidebar).add(main).removeClass('open');
    }

    // discus comment.
    {% if site.disqus.shortname %}
      var ds_loaded = false;
      window.disqus_shortname = "{{ site.disqus.shortname }}";
      main.scroll(function(){
        var nScrollHight = $(this)[0].scrollHeight;
        var nScrollTop = $(this)[0].scrollTop;
        if(!ds_loaded && nScrollTop + main.height() >= nScrollHight - 100) {
          $.ajax({
            type: 'GET',
            url: 'http://' + disqus_shortname + '.disqus.com/embed.js',
            dataType: 'script',
            cache: true
          });
          ds_loaded = true;
        }
      });
    {% endif %}
    // your scripts
  };
  afterPjax();

  // NProgress
  NProgress.configure({ showSpinner: false });

  // Pjax
  $(document).pjax('#sidebar-avatar, .toc-link', '#main', {
    fragment: '#main',
    timeout: 3000
  });

  $(document).on({
    'pjax:click': function() {
      NProgress.start();
      main.removeClass('fadeIn');
    },
    'pjax:end': function() {
      afterPjax();
      NProgress.done();
    }
  });

  // Tags Filter
  $('#sidebar-tags').on('click', '.sidebar-tag', function() {
    var filter = $(this).data('filter');
    toc.hide();
    if (filter === 'recent') {
      toc.slice(0, {{ site.recent_num }}).fadeIn(350);
    } else {
      $('.toc-link[data-tags="' + filter + '"]').fadeIn(350);
    }
    $(this).addClass('active').siblings().removeClass('active');
  });
  // Only show recent
  toc.hide();
  toc.slice(0, {{ site.recent_num }}).fadeIn(350);

  // Menu
  menu.on('click', function() {
    $(this).add(sidebar).add(menu).add(main).toggleClass('open');
  });

  // right toc
  posttoc.on('click', function() {
    $('#post-toc').toggleClass('open');
  });

  // Search
  $('#search-input').on('input', function(e){
    var blogs = $(".toc-link").filter(function() {
      var reg = new RegExp($('#search-input').val(), "i");
      return reg.test($(this).text());
    });
    toc.hide();
    blogs.fadeIn(350);
  });

});
<|endoftext|>


<commit_before>require.config({

    paths: {
        jquery: 'http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min',
        backbone: '../js/components/backbone/backbone-min',
        jqueryui: 'components/jqueryui/jquery-ui-1.10.1.custom.min'
    },

    shim: {
        'backbone': {
            deps: ['../js/components/underscore/underscore-min', 'jquery'],
            exports: 'Backbone'
        },

        'jqueryui': ['jquery']
    }

});

require(['views/app'], function(App) {

    var router = Backbone.Router.extend({
        routes: {
            '': 'root',
            'year(/:year)/': 'year'
        },

        root: function() {
            new App();
        },

        year: function() {
            new App({
                // year: year
            });
        }
    });

    r = new router();
    Backbone.history.start({
        pushState: true
    });
});<commit_msg>changed paths of files, changed to local jq until I find a solution for r.js<commit_after>require.config({
    paths: {
        // jquery: 'http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min',
        jquery: 'components/jquery/jquery.min',
        underscore: 'components/underscore/underscore-min',
        backbone: 'components/backbone/backbone-min',
        jqueryui: 'components/jqueryui/jquery-ui-1.10.1.custom.min'
    },

    shim: {
        'backbone': {
            deps: ['underscore', 'jquery'],
            exports: 'Backbone'
        },

        'jqueryui': ['jquery']
    }
});

require(['views/app'], function(App) {

    var router = Backbone.Router.extend({
        routes: {
            '': 'root',
            'year(/:year)/': 'year'
        },

        root: function() {
            new App();
        },

        year: function() {
            new App({
                // year: year
            });
        }
    });

    r = new router();
    Backbone.history.start({
        pushState: true
    });
});<|endoftext|>


<commit_before>//global vars
//

var numPosts = 0;

function search(_query){
    var craigslistItems = findCraigslistProducts(_query);
    var ebayItems = findEbayProducts(_query);
    console.log(craigslistItems);
    console.log(ebayItems);

}

//////
//
//   START CRAIGSLIST STUFF
//
//////
function findCraigslistProducts(search){
    $.ajax({
        type: "GET",
        url: "assets/php/proxy.php?search=" + search,
        dataType: "xml",
        success: parseXml
     });
}

function parseXml(xml) {
    console.log(xml);
    $(xml).find("item").each(function() {
        var title = $(this).find("title").text();
        var link = $(this).find("link").text();
        //parse title down so it's not super long
        var prettyTitle = title.substr(0, title.indexOf("$"));
        //parse price out of title
        var price = title.substr(title.indexOf("$"), title.indexOf(" ") + 1);

        var priceInt = parseInt(price.substr(1));

        var items = new Array();
        //this will get rid of TRADE items
        if ( priceInt >= 0 ) {
            items.push( new Object(link, priceInt, prettyTitle));
        }

        return items;
    });
}

//////
//
//   END CRAIGSLIST STUFF
//
//////

//////
//
//   START EBAY STUFF
//
//////
function findEbayProducts(search){

           $.ajax({
		type: "GET",
		url: "assets/php/proxyEbay.php?search=" + search,
		dataType: "xml",
		success: parseEbayXml
	     });

        }

	function parseEbayXml(xml) {
	console.log(xml);

	var numItems = 0;
	var price = 0;
	var maxPrice = 0;
	var minPrice = 99999999;

	$(xml).find("item").each(function() {
	    var condition =  $(this).find("conditionDisplayName").text();
	    //console.log(condition);
	    if((condition == 'New') || (condition == 'New other (see details)') || (condition == 'Manufacturer refurbished') || (condition == 'Used')){
		var currentPrice = $(this).find("currentPrice").text();
		currentPrice = parseInt(currentPrice);

		if(currentPrice > maxPrice){
		    maxPrice = currentPrice;
		}
		if(currentPrice < minPrice){
		    minPrice = currentPrice;
		}
		price += currentPrice;
		numItems++;
	    }
	});
	var avgPrice = price / numItems;

        var item = new Array();
        item.push(maxPrice);
        item.push(avgPrice);
        item.push(minPrice);
	//console.log('Highest price: ' + maxPrice);
	//console.log('Average price: ' + avgPrice);
	//console.log('Lowest price: ' + minPrice);

	//console.log(numItems);

	//$('#content').append('
Highest price: '+ maxPrice + '
');
	//$('#content').append('
Average price: '+ avgPrice + '
');
	//$('#content').append('
Lowest price: '+ minPrice + '
');
//////
//
//   END EBAY STUFF
//
//////

//generates a post to append to the list
//then appends it to the list
// variables:
//  _link: standard href stuff, the entire post will link here so choose carefully
//  _price: the price to purchase the item
//  _title: title of the post
function generatePost(_link, _price, _title){

    //collapse code
    $("#list").append('

' + '$' + _price + ' - ' + _title +'

');

    var body = 'Link to Craigslist post';
    body += '
Ebay average price: $x
';
    body += '
Gas expenses: $x
';
    body += '
Profit: $x
';

    //item body
    $("#list").append('

' + body + '
<button class="btn" data-toggle="collapse" data-parent="#accordion" href="#collapse' + numPosts + '">Close</button>

');

    $("#list").append('');

    numPosts++;
}

}<commit_msg>hopefully....<commit_after>//global vars
//

var numPosts = 0;

function search(_query){
    var craigslistItems = findCraigslistProducts(_query);
    var ebayItem = findEbayProducts(_query);
    console.log(craigslistItems);
    console.log(ebayItem);

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

}

//////
//
//   START CRAIGSLIST STUFF
//
//////
function findCraigslistProducts(search){
    $.ajax({
        type: "GET",
        url: "assets/php/proxy.php?search=" + search,
        dataType: "xml",
        success: parseXml
     });
}

function parseXml(xml) {
    console.log(xml);
    $(xml).find("item").each(function() {
        var title = $(this).find("title").text();
        var link = $(this).find("link").text();
        //parse title down so it's not super long
        var prettyTitle = title.substr(0, title.indexOf("$"));
        //parse price out of title
        var price = title.substr(title.indexOf("$"), title.indexOf(" ") + 1);

        var priceInt = parseInt(price.substr(1));

        var items = new Array();
        //this will get rid of TRADE items
        if ( priceInt >= 0 ) {
            items.push( new Object(link, priceInt, prettyTitle));
        }
        console.log(items);
        return items;
    });
}

//////
//
//   END CRAIGSLIST STUFF
//
//////

//////
//
//   START EBAY STUFF
//
//////
function findEbayProducts(search){

           $.ajax({
		type: "GET",
		url: "assets/php/proxyEbay.php?search=" + search,
		dataType: "xml",
		success: parseEbayXml
	     });

        }

	function parseEbayXml(xml) {
	console.log(xml);

	var numItems = 0;
	var price = 0;
	var maxPrice = 0;
	var minPrice = 99999999;

	$(xml).find("item").each(function() {
	    var condition =  $(this).find("conditionDisplayName").text();
	    //console.log(condition);
	    if((condition == 'New') || (condition == 'New other (see details)') || (condition == 'Manufacturer refurbished') || (condition == 'Used')){
		var currentPrice = $(this).find("currentPrice").text();
		currentPrice = parseInt(currentPrice);

		if(currentPrice > maxPrice){
		    maxPrice = currentPrice;
		}
		if(currentPrice < minPrice){
		    minPrice = currentPrice;
		}
		price += currentPrice;
		numItems++;
	    }
	});
	var avgPrice = price / numItems;

        var item = new Array();
        item.push(maxPrice);
        item.push(avgPrice);
        item.push(minPrice);
        console.log(item);
	//console.log('Highest price: ' + maxPrice);
	//console.log('Average price: ' + avgPrice);
	//console.log('Lowest price: ' + minPrice);

	//console.log(numItems);

	//$('#content').append('
Highest price: '+ maxPrice + '
');
	//$('#content').append('
Average price: '+ avgPrice + '
');
	//$('#content').append('
Lowest price: '+ minPrice + '
');
//////
//
//   END EBAY STUFF
//
//////

//generates a post to append to the list
//then appends it to the list
// variables:
//  _link: standard href stuff, the entire post will link here so choose carefully
//  _price: the price to purchase the item
//  _title: title of the post
function generatePost(_link, _price, _title){

    //collapse code
    $("#list").append('

' + '$' + _price + ' - ' + _title +'

');

    var body = 'Link to Craigslist post';
    body += '
Ebay average price: $x
';
    body += '
Gas expenses: $x
';
    body += '
Profit: $x
';

    //item body
    $("#list").append('

' + body + '
<button class="btn" data-toggle="collapse" data-parent="#accordion" href="#collapse' + numPosts + '">Close</button>

');

    $("#list").append('');

    numPosts++;
}

}<|endoftext|>


<commit_before>module.exports = {
  'plugins': [
    'react',
  ],
  'parserOptions': {
    'ecmaFeatures': {
      'jsx': true,
    },
  },

  // View link below for react rules documentation
  // https://github.com/yannickcr/eslint-plugin-react#list-of-supported-rules
  'rules': {
    // enforce that class methods utilize this
    // http://eslint.org/docs/rules/class-methods-use-this
    'class-methods-use-this': ['error', {
      exceptMethods: [
        'render',
        'getInitialState',
        'getDefaultProps',
        'getChildContext',
        'componentWillMount',
        'componentDidMount',
        'componentWillReceiveProps',
        'shouldComponentUpdate',
        'componentWillUpdate',
        'componentDidUpdate',
        'componentWillUnmount',
      ],
    }],

    // Specify whether double or single quotes should be used in JSX attributes
    // http://eslint.org/docs/rules/jsx-quotes
    'jsx-quotes': ['error', 'prefer-single'],

    // Prevent missing displayName in a React component definition
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/display-name.md
    'react/display-name': ['off', { ignoreTranspilerName: false }],

    // Forbid certain props on Components
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/forbid-component-props.md
    'react/forbid-component-props': ['off', { forbid: [] }],

    // Forbid certain elements
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/forbid-elements.md
    'react/forbid-elements': 'off',

    // Forbid foreign propTypes
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/forbid-foreign-prop-types.md
    'react/forbid-foreign-prop-types': 'off',

    // Forbid certain propTypes (any, array, object)
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/forbid-prop-types.md
    'react/forbid-prop-types': ['error', { forbid: ['any', 'array', 'object'] }],

    // Enforce boolean attributes notation in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-boolean-value.md
    'react/jsx-boolean-value': ['error', 'never'],

    // Validate closing bracket location in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-closing-bracket-location.md
    'react/jsx-closing-bracket-location': ['error', 'line-aligned'],

    // Enforce or disallow spaces inside of curly braces in JSX attributes
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-curly-spacing.md
    'react/jsx-curly-spacing': ['error', 'never', { allowMultiline: true }],

    // Enforce spacing around jsx equals signs
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-equals-spacing.md
    'react/jsx-equals-spacing': ['error', 'never'],

    // only .jsx files may have JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-filename-extension.md
    'react/jsx-filename-extension': ['error', { extensions: ['.jsx'] }],

    // Require that the first prop in a JSX element be on a new line when the element is multiline
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-first-prop-new-line.md
    'react/jsx-first-prop-new-line': ['error', 'multiline'],

    // Enforce event handler naming conventions in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-handler-names.md
    'react/jsx-handler-names': ['off', {
      eventHandlerPrefix: 'handle',
      eventHandlerPropPrefix: 'on',
    }],

    // Enforce JSX indentation
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-indent.md
    'react/jsx-indent': ['error', 2],

    // Validate props indentation in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-indent-props.md
    'react/jsx-indent-props': ['error', 2],

    // Validate JSX has key prop when in array or iterator
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-key.md
    'react/jsx-key': 'off',

    // Limit maximum of props on a single line in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-max-props-per-line.md
    'react/jsx-max-props-per-line': ['off', { maximum: 1, when: 'always' }],

    // Prevent usage of .bind() in JSX props
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-bind.md
    'react/jsx-no-bind': ['error', {
      ignoreRefs: true,
      allowArrowFunctions: true,
      allowBind: false,
    }],

    // prevent accidental JS comments from being injected into JSX as text
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-comment-textnodes.md
    'react/jsx-no-comment-textnodes': 'error',

    // Prevent duplicate props in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-duplicate-props.md
    'react/jsx-no-duplicate-props': ['error', { ignoreCase: true }],

    // Prevent usage of unwrapped JSX strings
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-literals.md
    'react/jsx-no-literals': 'off',

    // Disallow target="_blank" on links
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-target-blank.md
    'react/jsx-no-target-blank': 'error',

    // Disallow undeclared variables in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-undef.md
    'react/jsx-no-undef': 'error',

    // Enforce PascalCase for user-defined JSX components
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-pascal-case.md
    'react/jsx-pascal-case': ['error', {
      allowAllCaps: true,
      ignore: [],
    }],

    // Enforce props alphabetical sorting
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-sort-props.md
    'react/jsx-sort-props': ['off', {
      ignoreCase: true,
      callbacksLast: false,
      shorthandFirst: false,
      shorthandLast: false,
    }],

    // Validate whitespace in and around the JSX opening and closing brackets
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-tag-spacing.md
    'react/jsx-tag-spacing': ['error', {
      closingSlash: 'never',
      beforeSelfClosing: 'always',
      afterOpening: 'never',
    }],

    // Prevent React to be incorrectly marked as unused
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-uses-react.md
    'react/jsx-uses-react': ['error'],

    // Prevent variables used in JSX to be incorrectly marked as unused
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-uses-vars.md
    'react/jsx-uses-vars': 'error',

    // Prevent missing parentheses around multilines JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-wrap-multilines.md
    'react/jsx-wrap-multilines': ['error', {
      declaration: true,
      assignment: true,
      return: true,
    }],

    // Prevent usage of Array index in keys
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-array-index-key.md
    'react/no-array-index-key': 'warn',

    // Prevent passing of children as props
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-children-prop.md
    'react/no-children-prop': 'error',

    // Prevent usage of dangerous JSX properties
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-danger.md
    'react/no-danger': 'warn',

    // Prevent problem with children and props.dangerouslySetInnerHTML
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-danger-with-children.md
    'react/no-danger-with-children': 'error',

    // Prevent usage of deprecated methods
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-deprecated.md
    'react/no-deprecated': ['error'],

    // Prevent usage of setState in componentDidMount
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-did-mount-set-state.md
    'react/no-did-mount-set-state': ['error'],

    // Prevent usage of setState in componentDidUpdate
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-did-update-set-state.md
    'react/no-did-update-set-state': ['error'],

    // Prevent direct mutation of this.state
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-direct-mutation-state.md
    'react/no-direct-mutation-state': 'off',

    // warn against using findDOMNode()
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-find-dom-node.md
    'react/no-find-dom-node': 'error',

    // Prevent usage of isMounted
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-is-mounted.md
    'react/no-is-mounted': 'error',

    // Prevent multiple component definition per file
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-multi-comp.md
    'react/no-multi-comp': ['error', { ignoreStateless: true }],

    // disallow using React.render/ReactDOM.render's return value
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-render-return-value.md
    'react/no-render-return-value': 'error',

    // Prevent usage of setState
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-set-state.md
    'react/no-set-state': 'off',

    // Prevent using string references
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-string-refs.md
    'react/no-string-refs': 'error',

    // Prevent invalid characters from appearing in markup
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-unescaped-entities.md
    'react/no-unescaped-entities': 'error',

    // Prevent usage of unknown DOM property
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-unknown-property.md
    'react/no-unknown-property': 'error',

    // Prevent unused propType definitions
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-unused-prop-types.md
    'react/no-unused-prop-types': ['error', {
      customValidators: [
      ],
      skipShapeProps: true,
    }],

    // Prevent usage of setState in componentWillUpdate
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-will-update-set-state.md
    'react/no-will-update-set-state': ['error', 'disallow-in-func'],

    // Require ES6 class declarations over React.createClass
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/prefer-es6-class.md
    'react/prefer-es6-class': ['error', 'always'],

    // Require stateless functions when not using lifecycle methods, setState or ref
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/prefer-stateless-function.md
    'react/prefer-stateless-function': 'error',

    // Prevent missing props validation in a React component definition
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/prop-types.md
    'react/prop-types': ['error', { ignore: [], customValidators: [], skipUndeclared: false }],

    // Prevent missing React when using JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/react-in-jsx-scope.md
    'react/react-in-jsx-scope': 'error',

    // Enforce a defaultProps definition for every prop that is not a required prop
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/require-default-props.md
    'react/require-default-props': 'warn',

    // require a shouldComponentUpdate method, or PureRenderMixin
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/require-optimization.md
    'react/require-optimization': ['off', { allowDecorators: [] }],

    // Require render() methods to return something
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/require-render-return.md
    'react/require-render-return': 'error',

    // Prevent extra closing tags for components without children
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/self-closing-comp.md
    'react/self-closing-comp': 'error',

    // Enforce component methods order
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/sort-comp.md
    'react/sort-comp': ['error', {
      order: [
        'static-methods',
        'lifecycle',
        '/^on.+$/',
        '/^(get|set)(?!(InitialState$|DefaultProps$|ChildContext$)).+$/',
        'everything-else',
        '/^render.+$/',
        'render',
      ],
    }],

    // Enforce propTypes declarations alphabetical sorting
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/sort-prop-types.md
    'react/sort-prop-types': ['off', {
      ignoreCase: true,
      callbacksLast: false,
      requiredFirst: false,
    }],

    // Require style prop value be an object or var
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/style-prop-object.md
    'react/style-prop-object': 'error',

    // Prevent void DOM elements (e.g. <img />, <br />) from receiving children
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/void-dom-elements-no-children.md
    'react/void-dom-elements-no-children': 'error',
  },

  'settings': {
    'import/resolver': {
      'node': {
        'extensions': ['.js', '.jsx', '.json'],
      },
    },
    'react': {
      'pragma': 'React',
      'version': '0.15',
    },
  },
};
<commit_msg>eslint react, allow setState in componentDidMount. Data fetch use case<commit_after>module.exports = {
  'plugins': [
    'react',
  ],
  'parserOptions': {
    'ecmaFeatures': {
      'jsx': true,
    },
  },

  // View link below for react rules documentation
  // https://github.com/yannickcr/eslint-plugin-react#list-of-supported-rules
  'rules': {
    // enforce that class methods utilize this
    // http://eslint.org/docs/rules/class-methods-use-this
    'class-methods-use-this': ['error', {
      exceptMethods: [
        'render',
        'getInitialState',
        'getDefaultProps',
        'getChildContext',
        'componentWillMount',
        'componentDidMount',
        'componentWillReceiveProps',
        'shouldComponentUpdate',
        'componentWillUpdate',
        'componentDidUpdate',
        'componentWillUnmount',
      ],
    }],

    // Specify whether double or single quotes should be used in JSX attributes
    // http://eslint.org/docs/rules/jsx-quotes
    'jsx-quotes': ['error', 'prefer-single'],

    // Prevent missing displayName in a React component definition
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/display-name.md
    'react/display-name': ['off', { ignoreTranspilerName: false }],

    // Forbid certain props on Components
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/forbid-component-props.md
    'react/forbid-component-props': ['off', { forbid: [] }],

    // Forbid certain elements
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/forbid-elements.md
    'react/forbid-elements': 'off',

    // Forbid foreign propTypes
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/forbid-foreign-prop-types.md
    'react/forbid-foreign-prop-types': 'off',

    // Forbid certain propTypes (any, array, object)
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/forbid-prop-types.md
    'react/forbid-prop-types': ['error', { forbid: ['any', 'array', 'object'] }],

    // Enforce boolean attributes notation in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-boolean-value.md
    'react/jsx-boolean-value': ['error', 'never'],

    // Validate closing bracket location in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-closing-bracket-location.md
    'react/jsx-closing-bracket-location': ['error', 'line-aligned'],

    // Enforce or disallow spaces inside of curly braces in JSX attributes
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-curly-spacing.md
    'react/jsx-curly-spacing': ['error', 'never', { allowMultiline: true }],

    // Enforce spacing around jsx equals signs
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-equals-spacing.md
    'react/jsx-equals-spacing': ['error', 'never'],

    // only .jsx files may have JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-filename-extension.md
    'react/jsx-filename-extension': ['error', { extensions: ['.jsx'] }],

    // Require that the first prop in a JSX element be on a new line when the element is multiline
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-first-prop-new-line.md
    'react/jsx-first-prop-new-line': ['error', 'multiline'],

    // Enforce event handler naming conventions in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-handler-names.md
    'react/jsx-handler-names': ['off', {
      eventHandlerPrefix: 'handle',
      eventHandlerPropPrefix: 'on',
    }],

    // Enforce JSX indentation
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-indent.md
    'react/jsx-indent': ['error', 2],

    // Validate props indentation in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-indent-props.md
    'react/jsx-indent-props': ['error', 2],

    // Validate JSX has key prop when in array or iterator
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-key.md
    'react/jsx-key': 'off',

    // Limit maximum of props on a single line in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-max-props-per-line.md
    'react/jsx-max-props-per-line': ['off', { maximum: 1, when: 'always' }],

    // Prevent usage of .bind() in JSX props
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-bind.md
    'react/jsx-no-bind': ['error', {
      ignoreRefs: true,
      allowArrowFunctions: true,
      allowBind: false,
    }],

    // prevent accidental JS comments from being injected into JSX as text
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-comment-textnodes.md
    'react/jsx-no-comment-textnodes': 'error',

    // Prevent duplicate props in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-duplicate-props.md
    'react/jsx-no-duplicate-props': ['error', { ignoreCase: true }],

    // Prevent usage of unwrapped JSX strings
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-literals.md
    'react/jsx-no-literals': 'off',

    // Disallow target="_blank" on links
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-target-blank.md
    'react/jsx-no-target-blank': 'error',

    // Disallow undeclared variables in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-undef.md
    'react/jsx-no-undef': 'error',

    // Enforce PascalCase for user-defined JSX components
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-pascal-case.md
    'react/jsx-pascal-case': ['error', {
      allowAllCaps: true,
      ignore: [],
    }],

    // Enforce props alphabetical sorting
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-sort-props.md
    'react/jsx-sort-props': ['off', {
      ignoreCase: true,
      callbacksLast: false,
      shorthandFirst: false,
      shorthandLast: false,
    }],

    // Validate whitespace in and around the JSX opening and closing brackets
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-tag-spacing.md
    'react/jsx-tag-spacing': ['error', {
      closingSlash: 'never',
      beforeSelfClosing: 'always',
      afterOpening: 'never',
    }],

    // Prevent React to be incorrectly marked as unused
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-uses-react.md
    'react/jsx-uses-react': 'error',

    // Prevent variables used in JSX to be incorrectly marked as unused
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-uses-vars.md
    'react/jsx-uses-vars': 'error',

    // Prevent missing parentheses around multilines JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-wrap-multilines.md
    'react/jsx-wrap-multilines': ['error', {
      declaration: true,
      assignment: true,
      return: true,
    }],

    // Prevent usage of Array index in keys
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-array-index-key.md
    'react/no-array-index-key': 'warn',

    // Prevent passing of children as props
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-children-prop.md
    'react/no-children-prop': 'error',

    // Prevent usage of dangerous JSX properties
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-danger.md
    'react/no-danger': 'warn',

    // Prevent problem with children and props.dangerouslySetInnerHTML
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-danger-with-children.md
    'react/no-danger-with-children': 'error',

    // Prevent usage of deprecated methods
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-deprecated.md
    'react/no-deprecated': 'error',

    // Prevent usage of setState in componentDidMount
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-did-mount-set-state.md
    'react/no-did-mount-set-state': 'off',

    // Prevent usage of setState in componentDidUpdate
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-did-update-set-state.md
    'react/no-did-update-set-state': 'error',

    // Prevent direct mutation of this.state
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-direct-mutation-state.md
    'react/no-direct-mutation-state': 'off',

    // warn against using findDOMNode()
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-find-dom-node.md
    'react/no-find-dom-node': 'error',

    // Prevent usage of isMounted
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-is-mounted.md
    'react/no-is-mounted': 'error',

    // Prevent multiple component definition per file
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-multi-comp.md
    'react/no-multi-comp': ['error', { ignoreStateless: true }],

    // disallow using React.render/ReactDOM.render's return value
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-render-return-value.md
    'react/no-render-return-value': 'error',

    // Prevent usage of setState
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-set-state.md
    'react/no-set-state': 'off',

    // Prevent using string references
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-string-refs.md
    'react/no-string-refs': 'error',

    // Prevent invalid characters from appearing in markup
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-unescaped-entities.md
    'react/no-unescaped-entities': 'error',

    // Prevent usage of unknown DOM property
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-unknown-property.md
    'react/no-unknown-property': 'error',

    // Prevent unused propType definitions
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-unused-prop-types.md
    'react/no-unused-prop-types': ['error', {
      customValidators: [
      ],
      skipShapeProps: true,
    }],

    // Prevent usage of setState in componentWillUpdate
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-will-update-set-state.md
    'react/no-will-update-set-state': ['error', 'disallow-in-func'],

    // Require ES6 class declarations over React.createClass
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/prefer-es6-class.md
    'react/prefer-es6-class': ['error', 'always'],

    // Require stateless functions when not using lifecycle methods, setState or ref
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/prefer-stateless-function.md
    'react/prefer-stateless-function': 'error',

    // Prevent missing props validation in a React component definition
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/prop-types.md
    'react/prop-types': ['error', { ignore: [], customValidators: [], skipUndeclared: false }],

    // Prevent missing React when using JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/react-in-jsx-scope.md
    'react/react-in-jsx-scope': 'error',

    // Enforce a defaultProps definition for every prop that is not a required prop
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/require-default-props.md
    'react/require-default-props': 'warn',

    // require a shouldComponentUpdate method, or PureRenderMixin
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/require-optimization.md
    'react/require-optimization': ['off', { allowDecorators: [] }],

    // Require render() methods to return something
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/require-render-return.md
    'react/require-render-return': 'error',

    // Prevent extra closing tags for components without children
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/self-closing-comp.md
    'react/self-closing-comp': 'error',

    // Enforce component methods order
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/sort-comp.md
    'react/sort-comp': ['error', {
      order: [
        'static-methods',
        'lifecycle',
        '/^on.+$/',
        '/^(get|set)(?!(InitialState$|DefaultProps$|ChildContext$)).+$/',
        'everything-else',
        '/^render.+$/',
        'render',
      ],
    }],

    // Enforce propTypes declarations alphabetical sorting
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/sort-prop-types.md
    'react/sort-prop-types': ['off', {
      ignoreCase: true,
      callbacksLast: false,
      requiredFirst: false,
    }],

    // Require style prop value be an object or var
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/style-prop-object.md
    'react/style-prop-object': 'error',

    // Prevent void DOM elements (e.g. <img />, <br />) from receiving children
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/void-dom-elements-no-children.md
    'react/void-dom-elements-no-children': 'error',
  },

  'settings': {
    'import/resolver': {
      'node': {
        'extensions': ['.js', '.jsx', '.json'],
      },
    },
    'react': {
      'pragma': 'React',
      'version': '0.15',
    },
  },
};
<|endoftext|>


<commit_before>/**
 * Created by Zero on 3/10/2017.
 */

if(Hls.isSupported()){

	var video = document.getElementById('video');
	var hls = new Hls();

	// attach video to hls api
	hls.attachMedia(video);
	hls.on(Hls.Events.MEDIA_ATTACHED, function(){

		hls.loadSource("https://playertest.longtailvideo.com/adaptive/bipbop/bipbop.m3u8");

		hls.on(Hls.Events.MANIFEST_PARSED, function(event, data){

		});
	});

	// wait for video to finish loading metadata
	video.onloadedmetadata = function(){
		document.getElementById("seek-bar").max = video.duration;
	};

	// control-bar time left
	video.addEventListener('timeupdate', function(){
		var time = this.currentTime;
		var seconds = Math.round(time);
		var minutes = Math.round(seconds / 60);
		var hours = Math.round(minutes / 60);

		document.getElementById("loadedPercent").textContent = ("0" + hours).slice(-2) + ":" + ("0" + minutes % 59).slice(-2) + ":" + ("0" + seconds % 59).slice(-2);

		//seekbar
		document.getElementById("seek-bar").value = video.currentTime;
	});

	// play pause button
	var playToggle = true;
	document.getElementById("play-pause").addEventListener("click", function(){
		if(playToggle)
			video.play();
		else
			video.pause();
		playToggle = !playToggle;
	});

	//config menu autoplay
	var autplayToggle = false;
	document.getElementById("autoplay").addEventListener("click", function(){
		autplayToggle = !autplayToggle;
	});

	(function(){
		if(autplayToggle)
			video.play();
	})();

	//user set time on seek bar
	function seekBar(bar){
		video.currentTime = bar.value;
	}

	//volume control
	var muteToggle = true;
	document.getElementById("mute").addEventListener("click", function(){
		video.muted = muteToggle;
		muteToggle = !muteToggle;
	});

	//user set volume bar
	function volumeBar(bar){
		video.volume = bar.value;
		console.log(bar.value);
	}

	//config menu quality dropdown
	hls.currentLevel = 0;
	function qualitySelector(selector){
		hls.currentLevel = selector.options[selector.selectedIndex].value;
	}

	var configToggle = true;
	document.getElementById("config").addEventListener("click", function(){
		var configMenu = document.getElementById("config-menu");

		if(configToggle)
			configMenu.style.display = "block";
		else
			configMenu.style.display = "none";

		configToggle = !configToggle;
	});

	//config menu speed dropdown
	function speedSelector(selector){
		video.playbackRate = selector.options[selector.selectedIndex].value;
	}

	//fullscreen button
	var fullscreen = document.getElementById("full-screen");
	var fullScreenEnabled = !!(document.fullscreenEnabled || document.mozFullScreenEnabled || document.msFullscreenEnabled || document.webkitSupportsFullscreen || document.webkitFullscreenEnabled || document.createElement('videos').webkitRequestFullScreen);
	if(!fullScreenEnabled){
		fullscreen.style.display = 'none';
	}

	var isFullScreen = function(){
		return !!(document.fullScreen || document.webkitIsFullScreen || document.mozFullScreen || document.msFullscreenElement || document.fullscreenElement);
	};

	fullscreen.addEventListener("click", function(){
		if(isFullScreen()){
			if(document.exitFullscreen) document.exitFullscreen();
			else if(document.mozCancelFullScreen) document.mozCancelFullScreen();
			else if(document.webkitCancelFullScreen) document.webkitCancelFullScreen();
			else if(document.msExitFullscreen) document.msExitFullscreen();
		}
		else{
			if(video.requestFullscreen) video.requestFullscreen();
			else if(video.mozRequestFullScreen) video.mozRequestFullScreen();
			else if(video.webkitRequestFullScreen) video.webkitRequestFullScreen();
			else if(video.msRequestFullscreen) video.msRequestFullscreen();
		}
	});
}

<commit_msg>Changed timing format - more youtube like<commit_after>/**
 * Created by Zero on 3/10/2017.
 */

if(Hls.isSupported()){

	var video = document.getElementById('video');
	var hls = new Hls();

	// attach video to hls api
	hls.attachMedia(video);
	hls.on(Hls.Events.MEDIA_ATTACHED, function(){

		hls.loadSource("https://playertest.longtailvideo.com/adaptive/bipbop/bipbop.m3u8");

		hls.on(Hls.Events.MANIFEST_PARSED, function(event, data){

		});
	});

	// wait for video to finish loading metadata
	video.onloadedmetadata = function(){
		document.getElementById("seek-bar").max = video.duration;
		document.getElementById("loadedTotal").textContent = calculatedTime(video.duration);
	};

	// control-bar time left
	video.addEventListener('timeupdate', function(){
		var videoTime = this.currentTime;

		document.getElementById("loadedPercent").textContent = calculatedTime(videoTime);

		//seekbar
		document.getElementById("seek-bar").value = video.currentTime;
	});

	function calculatedTime(time){
		var seconds = Math.round(time);
		var minutes = Math.round(seconds / 60);
		var hours = Math.round(minutes / 60);
		var totalTime = "";

		if(hours !== 0)
			totalTime += ("0" + hours).slice(-2) + ":";

		if(minutes == 0)
			totalTime += "0" + ":";
		else if (hours !== 0)
			totalTime += ("0" + minutes % 59).slice(-2) + ":";
		else
			totalTime += (minutes % 59) + ":";

		totalTime += ("0" + seconds % 59).slice(-2);

		return totalTime;
	}

	// play pause button
	var playToggle = true;
	document.getElementById("play-pause").addEventListener("click", function(){
		if(playToggle)
			video.play();
		else
			video.pause();
		playToggle = !playToggle;
	});

	//config menu autoplay
	var autplayToggle = false;
	document.getElementById("autoplay").addEventListener("click", function(){
		autplayToggle = !autplayToggle;
	});

	(function(){
		if(autplayToggle)
			video.play();
	})();

	//user set time on seek bar
	function seekBar(bar){
		video.currentTime = bar.value;
	}

	//volume control
	var muteToggle = true;
	document.getElementById("mute").addEventListener("click", function(){
		video.muted = muteToggle;
		muteToggle = !muteToggle;
	});

	//user set volume bar
	function volumeBar(bar){
		video.volume = bar.value;
	}

	//config menu quality dropdown
	hls.currentLevel = 0;
	function qualitySelector(selector){
		hls.currentLevel = selector.options[selector.selectedIndex].value;
	}

	var configToggle = true;
	document.getElementById("config").addEventListener("click", function(){
		var configMenu = document.getElementById("config-menu");

		if(configToggle)
			configMenu.style.display = "block";
		else
			configMenu.style.display = "none";

		configToggle = !configToggle;
	});

	//config menu speed dropdown
	function speedSelector(selector){
		video.playbackRate = selector.options[selector.selectedIndex].value;
	}

	//fullscreen button
	var fullscreen = document.getElementById("full-screen");
	var fullScreenEnabled = !!(document.fullscreenEnabled || document.mozFullScreenEnabled || document.msFullscreenEnabled || document.webkitSupportsFullscreen || document.webkitFullscreenEnabled || document.createElement('videos').webkitRequestFullScreen);
	if(!fullScreenEnabled){
		fullscreen.style.display = 'none';
	}

	var isFullScreen = function(){
		return !!(document.fullScreen || document.webkitIsFullScreen || document.mozFullScreen || document.msFullscreenElement || document.fullscreenElement);
	};

	fullscreen.addEventListener("click", function(){
		if(isFullScreen()){
			if(document.exitFullscreen) document.exitFullscreen();
			else if(document.mozCancelFullScreen) document.mozCancelFullScreen();
			else if(document.webkitCancelFullScreen) document.webkitCancelFullScreen();
			else if(document.msExitFullscreen) document.msExitFullscreen();
		}
		else{
			if(video.requestFullscreen) video.requestFullscreen();
			else if(video.mozRequestFullScreen) video.mozRequestFullScreen();
			else if(video.webkitRequestFullScreen) video.webkitRequestFullScreen();
			else if(video.msRequestFullscreen) video.msRequestFullscreen();
		}
	});
}

<|endoftext|>


<commit_before>const baseUrl = window.location.origin + '/task/';

var userId = null;
var authorId = null;
var taskType = null;
var userName = null;

function setAuthorId(id) { authorId = id; }

function getAuthorId() { return authorId; }

function setTaskType(type) { taskType = type; }

function getTaskType() { return taskType; }

function setUserId(id) { userId = id; }

function getUserId() { return userId; }

// Initiate
$(function() {

$(document).getUser(getUserId(), true).done(function(data) {
    userName = data['first_name'] + ' ' + data['last_name'];
});

});

// Store
function storeTask() {

    return $(document).getTask(null, true).responseJSON;
}

// Builder
function taskBuilder(task, actorIcon = true) {

    var taskString = "";
    var actorsAppend = "";
    var contributorsAppend = "";
    var iconAppend = "";

    if (actorIcon) {

        var actors = task['actors'];

        actorsAppend = "Contributor
";

        if(actors.length) {

            $.each(actors, function (i, actor) {
                actorsAppend += actor['first_name'] + " " + actor['last_name'] + "
";
            });
        } else {

            actorsAppend = "No Contributor";
        }

        contributorsAppend = `data-toggle="popover" data-trigger="hover" data-html="true" data-placement="right" data-content="${actorsAppend}"`;

        if (actors.length == 0) {
            iconAppend = ' ';
        } else if (actors.length == 1) {
            iconAppend = ' ';
        } else if (actors.length > 1) {
            iconAppend = ' ';
        }
    }

    var taskString =
    `

${iconAppend + task['title']}

`;

    return taskString;
}

function columnBuilder(column) {
    var columnString =
    `

                ${column['name']}

            <button type="button" class="btn btn-primary btn-lg btn-block my-2 task-create"
                data-toggle="modal" data-target="#taskModifyModal" data-parent="${column['id']}">
                 Add Task
            </button>

`;

    return columnString;
}

// Team
$.fn.displayMember = function(items, edit = false) {

    $.each(items, function(i, item) {

        if(edit) {

            $('.team-member').before(
                `<span class="badge badge-dark mx-1">${item['first_name']} ${item['last_name']} <a class="team-member-remove" data-value="${item['email_address']}">×</a></span>`
            );
            $('#teamModifyModal form').append(
                `<input type="hidden" name="members[]" value="${item['email_address']}" />`
            );
        } else

            $('.team-member-list').append(
                `<span class="badge badge-secondary">${item['first_name']} ${item['last_name']}</span>`
            );
    });
};

// Task
$.fn.resetForm = function() {

    $('#taskModifyModal').find('form')[0].reset();

    $('#taskModifyModal form').children('input').remove();
    $('#taskModifyModal').find('.task-tag').siblings('span.badge').remove();
    $('#taskModifyModal').find('.task-actor').siblings('span.badge').remove();
    $('#taskModifyModal').find('.btn-color').find('i').removeClass('fa fa-check fa-lg');
    $('#taskModifyModal').find(`button[data-value="#ffffff"] i`).addClass('fa fa-check fa-lg');
    $('#taskModifyModal .card').css('background-color', '#ffffff');
};

$.fn.displayTask = function(items) {

    $('.kanban-column .task-create').prevAll().remove();

    $.each(items, function(i, item) {

        $(`.kanban-column[data-value="${item['column_id']}"]>.card-body`).prepend(taskBuilder(item, getTaskType() == 'team'));
    });
};

$.fn.displayActor = function(items, edit = false) {

    $.each(items, function(i, item) {

        if(edit) {

            $('#taskModifyModal .task-actor').before(
                `<span class="badge badge-dark mx-1">${item['first_name'] + ' ' + item['last_name']} <a class="task-actor-remove" data-value="${item['email_address']}">×</a></span>`
            );

            $('#taskModifyModal form').append(
                `<input type="hidden" name="actors[]" value="${item['email_address']}" />`
            );
        } else

            $('.task-actor-list').append(
                `<span class="badge badge-dark mx-1">${item['first_name'] + ' ' + item['last_name']}</span>`
            );
    });
};

$.fn.displayTag = function(items, edit = false) {

    $.each(items, function(i, item) {

        if(edit) {

            $('#taskModifyModal .task-tag').before(
                `<span class="badge badge-dark badge-pill mx-1">${item['name']} <a class="task-tag-remove" data-value="${item['name']}">×</a></span>`
            );
            $('#taskModifyModal .task-tag').append(
                `<input type="hidden" name="tags[]" value="${item['name']}" />`
            );
        } else

            $('.task-tag-list').append(
                `<span class="badge badge-dark badge-pill mx-1">${item['name']}</span>`
            );
    });
};

$.fn.displayNote = function(items) {

    $.each(items, function(i, item){

        var user = $(document).getUser(item['user_id'], true).responseJSON;

        $('.task-note-list').append(
            `

                ${item['body']}

`
        );
    });
}

$.fn.searchTask = function(items, keyword) {

    $('#taskSearchList').html('');

    if(keyword != '') {

        $.each(items, function(i, item) {

            if(item['title'].toLowerCase().indexOf(keyword.toLowerCase()) != -1) {

                $('#taskSearchList').append(taskBuilder(item, getTaskType() == 'team'));
            }
        });
    }
};

// Kanban
$.fn.displayBoard = function(board) {

    $('#kanbanBoard .card-group').html('');

    $('#kanbanBoard .card-group').css(`width`, `${(board['columns'].length + 1) * 25}%`);

    $.each(board['columns'], function(i, column) {

        $('#kanbanBoard .card-group').append(columnBuilder(column));
    });

    $('#kanbanBoard .card-group').append(`

                Type Here

    `);
};

$.fn.addColumn = function(column) {

    $('#kanbanBoard .card-group').css(`width`,  `${(column['position'] + 1) * 25}%`);

    $('#addColumn').before(columnBuilder(column));
};

$.fn.highlightTask = function(userId) {

    userId = userId == null ? getUserId() : userId;

    $(document).getUserTeamTask(userId).done(function (data) {

        $.each(data, function(i, item) {
            $(`#kanbanBoard .kanban-task[data-value="${item['id']}"]`).toggleClass('active');
        })
    }).always(function () {

        $('#kanbanBoard').toggleClass('highlight');
    });
};  <commit_msg>Search Modal Dismissible<commit_after>const baseUrl = window.location.origin + '/task/';

var userId = null;
var authorId = null;
var taskType = null;
var userName = null;

function setAuthorId(id) { authorId = id; }

function getAuthorId() { return authorId; }

function setTaskType(type) { taskType = type; }

function getTaskType() { return taskType; }

function setUserId(id) { userId = id; }

function getUserId() { return userId; }

// Initiate
$(function() {

$(document).getUser(getUserId(), true).done(function(data) {
    userName = data['first_name'] + ' ' + data['last_name'];
});

});

// Store
function storeTask() {

    return $(document).getTask(null, true).responseJSON;
}

// Builder
function taskBuilder(task, actorIcon = true, modalDismiss = false) {

    var taskString = "";
    var actorsAppend = "";
    var contributorsAppend = "";
    var iconAppend = "";
    var modalDismissAppend = modalDismiss ? 'data-dismiss="modal"': '';

    if (actorIcon) {

        var actors = task['actors'];

        actorsAppend = "Contributor
";

        if(actors.length) {

            $.each(actors, function (i, actor) {
                actorsAppend += actor['first_name'] + " " + actor['last_name'] + "
";
            });
        } else {

            actorsAppend = "No Contributor";
        }

        contributorsAppend = `data-toggle="popover" data-trigger="hover" data-html="true" data-placement="right" data-content="${actorsAppend}"`;

        if (actors.length == 0) {
            iconAppend = ' ';
        } else if (actors.length == 1) {
            iconAppend = ' ';
        } else if (actors.length > 1) {
            iconAppend = ' ';
        }
    }

    var taskString =
    `

${iconAppend + task['title']}

`;

    return taskString;
}

function columnBuilder(column) {
    var columnString =
    `

                ${column['name']}

            <button type="button" class="btn btn-primary btn-lg btn-block my-2 task-create"
                data-toggle="modal" data-target="#taskModifyModal" data-parent="${column['id']}">
                 Add Task
            </button>

`;

    return columnString;
}

// Team
$.fn.displayMember = function(items, edit = false) {

    $.each(items, function(i, item) {

        if(edit) {

            $('.team-member').before(
                `<span class="badge badge-dark mx-1">${item['first_name']} ${item['last_name']} <a class="team-member-remove" data-value="${item['email_address']}">×</a></span>`
            );
            $('#teamModifyModal form').append(
                `<input type="hidden" name="members[]" value="${item['email_address']}" />`
            );
        } else

            $('.team-member-list').append(
                `<span class="badge badge-secondary">${item['first_name']} ${item['last_name']}</span>`
            );
    });
};

// Task
$.fn.resetForm = function() {

    $('#taskModifyModal').find('form')[0].reset();

    $('#taskModifyModal form').children('input').remove();
    $('#taskModifyModal').find('.task-tag').siblings('span.badge').remove();
    $('#taskModifyModal').find('.task-actor').siblings('span.badge').remove();
    $('#taskModifyModal').find('.btn-color').find('i').removeClass('fa fa-check fa-lg');
    $('#taskModifyModal').find(`button[data-value="#ffffff"] i`).addClass('fa fa-check fa-lg');
    $('#taskModifyModal .card').css('background-color', '#ffffff');
};

$.fn.displayTask = function(items) {

    $('.kanban-column .task-create').prevAll().remove();

    $.each(items, function(i, item) {

        $(`.kanban-column[data-value="${item['column_id']}"]>.card-body`).prepend(taskBuilder(item, getTaskType() == 'team'));
    });
};

$.fn.displayActor = function(items, edit = false) {

    $.each(items, function(i, item) {

        if(edit) {

            $('#taskModifyModal .task-actor').before(
                `<span class="badge badge-dark mx-1">${item['first_name'] + ' ' + item['last_name']} <a class="task-actor-remove" data-value="${item['email_address']}">×</a></span>`
            );

            $('#taskModifyModal form').append(
                `<input type="hidden" name="actors[]" value="${item['email_address']}" />`
            );
        } else

            $('.task-actor-list').append(
                `<span class="badge badge-dark mx-1">${item['first_name'] + ' ' + item['last_name']}</span>`
            );
    });
};

$.fn.displayTag = function(items, edit = false) {

    $.each(items, function(i, item) {

        if(edit) {

            $('#taskModifyModal .task-tag').before(
                `<span class="badge badge-dark badge-pill mx-1">${item['name']} <a class="task-tag-remove" data-value="${item['name']}">×</a></span>`
            );
            $('#taskModifyModal .task-tag').append(
                `<input type="hidden" name="tags[]" value="${item['name']}" />`
            );
        } else

            $('.task-tag-list').append(
                `<span class="badge badge-dark badge-pill mx-1">${item['name']}</span>`
            );
    });
};

$.fn.displayNote = function(items) {

    $.each(items, function(i, item){

        var user = $(document).getUser(item['user_id'], true).responseJSON;

        $('.task-note-list').append(
            `

                ${item['body']}

`
        );
    });
}

$.fn.searchTask = function(items, keyword) {

    $('#taskSearchList').html('');

    if(keyword != '') {

        $.each(items, function(i, item) {

            if(item['title'].toLowerCase().indexOf(keyword.toLowerCase()) != -1) {

                $('#taskSearchList').append(taskBuilder(item, getTaskType() == 'team', true));
            }
        });
    }
};

// Kanban
$.fn.displayBoard = function(board) {

    $('#kanbanBoard .card-group').html('');

    $('#kanbanBoard .card-group').css(`width`, `${(board['columns'].length + 1) * 25}%`);

    $.each(board['columns'], function(i, column) {

        $('#kanbanBoard .card-group').append(columnBuilder(column));
    });

    $('#kanbanBoard .card-group').append(`

                Type Here

    `);
};

$.fn.addColumn = function(column) {

    $('#kanbanBoard .card-group').css(`width`,  `${(column['position'] + 1) * 25}%`);

    $('#addColumn').before(columnBuilder(column));
};

$.fn.highlightTask = function(userId) {

    userId = userId == null ? getUserId() : userId;

    $(document).getUserTeamTask(userId).done(function (data) {

        $.each(data, function(i, item) {
            $(`#kanbanBoard .kanban-task[data-value="${item['id']}"]`).toggleClass('active');
        })
    }).always(function () {

        $('#kanbanBoard').toggleClass('highlight');
    });
};  <|endoftext|>


<commit_before>$(function() {

	$('a#print').on('click', function(e) {
		e.preventDefault();

		if ( $('#dpersonales ul').length > 0 && !confirm('¿Incluir datos personales del autor?')) {
			$('#dpersonales').hide();
		}

		if ( $('#comentarios li').length > 1 && !confirm('¿Incluir comentarios?')) {
			$('#comentarios').hide();
		}

		window.print();

		$('#dpersonales, #comentarios').show();
	})

	$('section#panel a#agrupar').on('click', function(e) {
		e.preventDefault();

		var pisados = $('.delegacion #pisados li');

		if (this.dataset['active'] == 'false') {
			var that = $(this);
			this.dataset['active'] = true;

			pisados.addClass('vibrate');
			$.each(pisados, function() {
				$(this).on('click', function(e) {
					e.preventDefault();
					that.html('Agrupar seleccionados');

					if ( !$(this).hasClass('selected') ) {
						if ( $(this).hasClass('vibrate') ) {
							var titulacion = $(this).data('titulacion'),
								curso = $(this).data('curso');

							pisados.removeClass('vibrate');
							pisados.filter('[data-titulacion='+titulacion+'][data-curso='+curso+']:not(.selected)', pisados).addClass('vibrate');
							$(this).removeClass('vibrate').addClass('selected');
						} else {
							$('.delegacion p.info.hide').slideDown();
						}
					} else {
						$(this).removeClass('selected');

						if (pisados.filter('.selected').length > 0) {
							var titulacion = pisados.filter('.selected').data('titulacion'),
								curso = pisados.filter('.selected').data('curso');

							pisados.removeClass('vibrate');
							pisados.filter('[data-titulacion='+titulacion+'][data-curso='+curso+']:not(.selected)', pisados).addClass('vibrate');
						} else {
							pisados.addClass('vibrate');
						}
					}
				})
			})
		} else {
			var pisados = $('.delegacion #pisados li.selected');
			if ( pisados.length > 1 ) {
				var form = $('<form>', {
					action: '?#delegacion',
					method: 'POST'
				});

				pisados.filter('#pisado').each(function() {
					form.append($('<input>', {
						name: 'pisado',
						value: $(this).data('id'),
						type: 'text'
					}))
				});

				pisados.filter('#group').each(function() {
					form.append($('<input>', {
						name: 'group',
						value: $(this).data('id'),
						type: 'text'
					}))
				})

				if (pisados.filter('#group').length != 1) {
					var name = $('<input>', {
						type: 'text',
						placeholder: 'Nombre del grupo',
						name: 'name'
					});

					$(this).parent().append(name);
					$(this).html('Agrupar');

					$(this).off('click');
					$(this).on('click', function(e) {
						e.preventDefault();

						form.append(name);
						form.submit();
					})
				} else {
					form.submit();
				}
			} else {
				$('.delegacion p.info.hide').slideDown();
			}
		}
	})

})
<commit_msg>debug<commit_after>$(function() {

	$('a#print').on('click', function(e) {
		e.preventDefault();

		if ( $('#dpersonales ul').length > 0 && !confirm('¿Incluir datos personales del autor?')) {
			$('#dpersonales').hide();
		}

		if ( $('#comentarios li').length > 1 && !confirm('¿Incluir comentarios?')) {
			$('#comentarios').hide();
		}

		window.print();

		$('#dpersonales, #comentarios').show();
	})

	$('section#panel a#agrupar').on('click', function(e) {
		e.preventDefault();

		var pisados = $('.delegacion #pisados li');

		if (this.dataset['active'] == 'false') {
			var that = $(this);
			this.dataset['active'] = true;

			pisados.addClass('vibrate');
			$.each(pisados, function() {
				$(this).on('click', function(e) {
					e.preventDefault();
					that.html('Agrupar seleccionados');

					if ( !$(this).hasClass('selected') ) {
						if ( $(this).hasClass('vibrate') ) {
							var titulacion = $(this).data('titulacion'),
								curso = $(this).data('curso');

							pisados.removeClass('vibrate');
							pisados.filter('[data-titulacion='+titulacion+'][data-curso='+curso+']:not(.selected)', pisados).addClass('vibrate');
							$(this).removeClass('vibrate').addClass('selected');
						} else {
							$('.delegacion p.info.hide').slideDown();
						}
					} else {
						$(this).removeClass('selected');

						if (pisados.filter('.selected').length > 0) {
							var titulacion = pisados.filter('.selected').data('titulacion'),
								curso = pisados.filter('.selected').data('curso');

							pisados.removeClass('vibrate');
							pisados.filter('[data-titulacion='+titulacion+'][data-curso='+curso+']:not(.selected)', pisados).addClass('vibrate');
						} else {
							pisados.addClass('vibrate');
						}
					}
				})
			})
		} else {
			var pisados = $('.delegacion #pisados li.selected');
			if ( pisados.length > 1 ) {
				var form = $('<form>', {
					action: '?#delegacion',
					method: 'POST'
				});

				pisados.filter('#pisado').each(function() {
					form.append($('<input>', {
						name: 'pisado[]',
						value: $(this).data('id'),
						type: 'text'
					}))
				});

				pisados.filter('#group').each(function() {
					form.append($('<input>', {
						name: 'group[]',
						value: $(this).data('id'),
						type: 'text'
					}))
				})

				if (pisados.filter('#group').length != 1) {
					var name = $('<input>', {
						type: 'text',
						placeholder: 'Nombre del grupo',
						name: 'name'
					});

					$(this).parent().append(name);
					$(this).html('Agrupar');

					$(this).off('click');
					$(this).on('click', function(e) {
						e.preventDefault();

						form.append(name);
						form.submit();
					})
				} else {
					form.submit();
				}
			} else {
				$('.delegacion p.info.hide').slideDown();
			}
		}
	})

})
<|endoftext|>


<commit_before>// var console = {
  // log: function(str) { return Ti.API.info(str); }
// };
// Create variable "win" to refer to current window

var osname = Ti.Platform.osname;

var win = Titanium.UI.currentWindow;

var tbl = Ti.UI.createTableView({
	backgroundColor:'#fff',
	minRowHeight: 70,
	selectionStyle: 'none'
});

var current_row; // this will hold the current row we swiped over, so we can reset it's state when we do any other gesture (scroll the table, swipe another row, click on another row)

// create the actions view - the one will be revealed on swipe
var create_sharing_options_view = function(where) {

	var view = Ti.UI.createView({
		height:Ti.UI.SIZE,
		width:Ti.UI.SIZE
	});

	for (var i = 0; i < 6; i++) {
		view.add(Ti.UI.createImageView({
			width: '50dp',
			left: (10 + (50 * i))+'dp',
			height: '50dp',
			image: 'KS_nav_ui.png',
			is_action: 'action ' + i
		}));
	};

	return view;
};

var make_content_view = function(content) {// create the content view - the one is displayed by default

	var view = Ti.UI.createView({
		backgroundColor: '#fff',
		height: Ti.UI.SIZE,
		width: Titanium.Platform.displayCaps.platformWidth
	});

	var img = Ti.UI.createImageView({
		height: '40dp',
		width: '40dp',
		left: '5dp',
		top: '5dp',
		image: 'https://si0.twimg.com/profile_images/2179402304/appc-fb_normal.png'
	});

	var label = Ti.UI.createLabel({
		text: content,
		color:'#000',
		top: 0,
		left: '50dp',
		right: '5dp',
		height: Ti.UI.SIZE
	});

	view.add(img);
	view.add(label);

	return view;

};

var allTitles = [];
var allContent = [];

function loadWordpress()
{
	var loader;
	function make_data_rows() { // some stub data for the rows.
		var data = [];

		// Empty array "rowData" for our tableview
		var rowData = [];

		// Create our HTTP Client and name it "loader"
		loader = Titanium.Network.createHTTPClient();
		// Sets the HTTP request method, and the URL to get data from

		loader.open("GET","http://dev.dohanews.co/?json=1&count=10&dev=1");
		// Runs the function when the data is ready for us to process

		loader.onload = function()
		{
			var wordpress = JSON.parse(this.responseText);

			for (var i = 0; i < wordpress.posts.length; i++)
			{
				var tweet = wordpress.posts[i].content; // The tweet message
				//var tweet = tweetOriginal.replace( /<[^>]+>/g, '' );
				var articleTitle = wordpress.posts[i].title; // The screen name of the user
				var avatar = wordpress.posts[i].user_avatar; // The profile image
				// Create a row and set its height to auto

				allTitles[i]={title: wordpress.posts[i].title};
				allContent[i]=tweet;

				var row = Ti.UI.createTableViewRow({
					height: Ti.UI.SIZE,
					backgroundColor:'#fff',
					font: {
			            fontSize: 10,
			            fontWeight: 'bold',
			            fontFamily: 'Arial'
			        },
				});

				var sharing_options = create_sharing_options_view();
				row.v2 = make_content_view(articleTitle);
				row.add(sharing_options);
				row.add(row.v2);
				row.className = "item"+i;

				// android behaves in a different way so we need to add the event to the row.
				row.addEventListener('swipe', function(e) {
					if (e.direction == 'left') {
						if (!!current_row) {
							current_row.v2.animate({
								left: 0,
								duration: 0
							});
						}

						current_row = Ti.Platform.osname == 'android' ? this : e.row; // it looks like android does not have the e.row property for this event.

						current_row.v2.animate({
							left: Titanium.Platform.displayCaps.platformWidth * -1,
							duration: 250});
					}
					else if (e.direction == 'right') {
						alert('swiped right');
					}

				});

				data.push(row);
			}

		tbl.setData(data);

		}
	}

	make_data_rows();

	if (Ti.Platform.osname == 'android') {

		var scrolled_times = 0;

		tbl.addEventListener('scrollEnd', function(e) {
			scrolled_times = 0;
		});

	}

	tbl.addEventListener('scroll', function(e) {

		if (!!current_row && (Ti.Platform.osname == 'android' ?  scrolled_times > 3 : true)) {
			current_row.v2.animate({
				left: 0,
				duration: 0
			});
			current_row = null;
		}

		scrolled_times++;
	});

	tbl.addEventListener('click', function(e) {
		if (e.source.is_action) {
			alert(e.source.is_action);
		} else {
			if (current_row) {

				current_row.v2.animate({
					left: 0,
					duration: 0
				});
				current_row = null;
			}

			var win = Ti.UI.createWindow({
    			backgroundColor:'#fff',
    			url: 'detail.js',
    			modal: true

    		})
    		win.content = allContent[e.index];
    		win.open({animated:true});
		}

	});

	var style;
	// if (Ti.Platform.name === 'iPhone OS'){
		// style = Ti.UI.iPhone.ActivityIndicatorStyle.DARK;
	// }
	// else {
		// style = Ti.UI.ActivityIndicatorStyle.DARK;
	// }

	var activityIndicator = Ti.UI.createActivityIndicator({
		style: Ti.UI.ActivityIndicatorStyle.DARK ,
		center:{x:Ti.Platform.displayCaps.platformWidth/2,
			y:Ti.Platform.displayCaps.platformHeight/2},
		height:Ti.UI.SIZE,
		width:Ti.UI.SIZE
	});

	win.add(tbl);
	win.add(activityIndicator);
	activityIndicator.show();
	win.open();
	loader.onreadystatechange = function(e){
		if (this.readyState == 4) {
			activityIndicator.hide();
		}
	};
	loader.send();
}

loadWordpress();<commit_msg>Loading Working on iOS<commit_after>// var console = {
  // log: function(str) { return Ti.API.info(str); }
// };
// Create variable "win" to refer to current window

var osname = Ti.Platform.osname;

var win = Titanium.UI.currentWindow;
win.backgroundColor='white';

var tbl = Ti.UI.createTableView({
	backgroundColor:'#fff',
	minRowHeight: 70,
	selectionStyle: 'none'
});

var current_row; // this will hold the current row we swiped over, so we can reset it's state when we do any other gesture (scroll the table, swipe another row, click on another row)

// create the actions view - the one will be revealed on swipe
var create_sharing_options_view = function(where) {

	var view = Ti.UI.createView({
		height:Ti.UI.SIZE,
		width:Ti.UI.SIZE
	});

	for (var i = 0; i < 6; i++) {
		view.add(Ti.UI.createImageView({
			width: '50dp',
			left: (10 + (50 * i))+'dp',
			height: '50dp',
			image: 'KS_nav_ui.png',
			is_action: 'action ' + i
		}));
	};

	return view;
};

var make_content_view = function(content) {// create the content view - the one is displayed by default

	var view = Ti.UI.createView({
		backgroundColor: '#fff',
		height: Ti.UI.SIZE,
		width: Titanium.Platform.displayCaps.platformWidth
	});

	var img = Ti.UI.createImageView({
		height: '40dp',
		width: '40dp',
		left: '5dp',
		top: '5dp',
		image: 'https://si0.twimg.com/profile_images/2179402304/appc-fb_normal.png'
	});

	var label = Ti.UI.createLabel({
		text: content,
		color:'#000',
		top: 0,
		left: '50dp',
		right: '5dp',
		height: Ti.UI.SIZE
	});

	view.add(img);
	view.add(label);

	return view;

};

var allTitles = [];
var allContent = [];

function loadWordpress()
{
	var loader;
	function make_data_rows() { // some stub data for the rows.
		var data = [];

		// Empty array "rowData" for our tableview
		var rowData = [];

		// Create our HTTP Client and name it "loader"
		loader = Titanium.Network.createHTTPClient();
		// Sets the HTTP request method, and the URL to get data from

		loader.open("GET","http://dev.dohanews.co/?json=1&count=10&dev=1");
		// Runs the function when the data is ready for us to process

		loader.onload = function()
		{
			var wordpress = JSON.parse(this.responseText);

			for (var i = 0; i < wordpress.posts.length; i++)
			{
				var tweet = wordpress.posts[i].content; // The tweet message
				//var tweet = tweetOriginal.replace( /<[^>]+>/g, '' );
				var articleTitle = wordpress.posts[i].title; // The screen name of the user
				var avatar = wordpress.posts[i].user_avatar; // The profile image
				// Create a row and set its height to auto

				allTitles[i]={title: wordpress.posts[i].title};
				allContent[i]=tweet;

				var row = Ti.UI.createTableViewRow({
					height: Ti.UI.SIZE,
					backgroundColor:'#fff',
					font: {
			            fontSize: 10,
			            fontWeight: 'bold',
			            fontFamily: 'Arial'
			        },
				});

				var sharing_options = create_sharing_options_view();
				row.v2 = make_content_view(articleTitle);
				row.add(sharing_options);
				row.add(row.v2);
				row.className = "item"+i;

				// android behaves in a different way so we need to add the event to the row.
				row.addEventListener('swipe', function(e) {
					if (e.direction == 'left') {
						if (!!current_row) {
							current_row.v2.animate({
								left: 0,
								duration: 0
							});
						}

						current_row = Ti.Platform.osname == 'android' ? this : e.row; // it looks like android does not have the e.row property for this event.

						current_row.v2.animate({
							left: Titanium.Platform.displayCaps.platformWidth * -1,
							duration: 250});
					}
					else if (e.direction == 'right') {
						alert('swiped right');
					}

				});

				data.push(row);
			}

		tbl.setData(data);

		}
	}

	make_data_rows();

	if (Ti.Platform.osname == 'android') {

		var scrolled_times = 0;

		tbl.addEventListener('scrollEnd', function(e) {
			scrolled_times = 0;
		});

	}

	tbl.addEventListener('scroll', function(e) {

		if (!!current_row && (Ti.Platform.osname == 'android' ?  scrolled_times > 3 : true)) {
			current_row.v2.animate({
				left: 0,
				duration: 0
			});
			current_row = null;
		}

		scrolled_times++;
	});

	tbl.addEventListener('click', function(e) {
		if (e.source.is_action) {
			alert(e.source.is_action);
		} else {
			if (current_row) {

				current_row.v2.animate({
					left: 0,
					duration: 0
				});
				current_row = null;
			}

			var win = Ti.UI.createWindow({
    			backgroundColor:'#fff',
    			url: 'detail.js',
    			modal: true

    		})
    		win.content = allContent[e.index];
    		win.open({animated:true});
		}

	});

	var style;
	if (Ti.Platform.name === 'iPhone OS'){
		style = Ti.UI.iPhone.ActivityIndicatorStyle.DARK;
	}
	else {
		style = Ti.UI.ActivityIndicatorStyle.DARK;
	}

	var activityIndicator = Ti.UI.createActivityIndicator({
		style: style,
		center:{x:Ti.Platform.displayCaps.platformWidth/2,
			y:Ti.Platform.displayCaps.platformHeight/2},
		height:Ti.UI.SIZE,
		width:Ti.UI.SIZE
	});

	win.add(activityIndicator);
	activityIndicator.show();
	win.open();
	loader.onreadystatechange = function(e){
		if (this.readyState == 4) {
			activityIndicator.hide();
			win.add(tbl);
		}
	};
	loader.send();
}

loadWordpress();<|endoftext|>