<commit_before>/* global app:true, io:false */

var clock_socket;
var currenttime;
var username='noname';

var width = 900,
	height = 500,
	cellWidth = 60,
	cellHeight = 58, // cell size
	gapWidth = 12,
	gapHeight = 16
	Dy = 64;

var hour = d3.time.format("%I"),
	minute = d3.time.format("%M"),
	month = d3.time.format("%b"),
	weekday = d3.time.format("%a"),
	date = d3.time.format("%d"),
	ampm = d3.time.format("%p"),
	format = d3.time.format("%b/%d %H:%M%p");

(function() {
  'use strict';

  var clockbar = $('#clock_bar');
  var myClock;
  function myTimer(){
		// >>>>>> socket: look clock
		read_socket.emit('lookclock');
  }
  read_socket = io.connect('http://171.65.102.132:3006');

  read_socket.on('server_clock', function(data){
  	var str = data.split(":");
  	if(str[1]=='00'){
  		if((str[0]=="2")||(str[0]=="5")) {
  			callBlocks(currenttime);
  		}
  	}
  	if(str[0]=="0"){
  		clockbar.html(""+data+"");
  	}
  	else{
  		clockbar.html(""+data+"");
  	}
  });

  read_socket.on('connect', function() {
	console.log("Connected!");
	currenttime = new Date();
	//callBlocks(currenttime);
	myClock=setInterval(function(){myTimer()},500);
  });

  read_socket.on('disconnect', function() {
	console.log('clock lost');
  }

  read_socket.on('postblocks', function(data){
  	blockdata = [];
  	var num_ele = 9;
	for (var i=0;i<=data.length/num_ele;i++){
		var block = new Object();
		block.id = i;

		var d = new Date(0);
		d.setTime(data[i*num_ele]);
		block.time = d;

		block.lock = data[i*num_ele+1];
		block.user_id = data[i*num_ele+2];
		block.exp_id = data[i*num_ele+3];
		block.pattern_id = data[i*num_ele+4];
		block.past = data[i*num_ele+5];
		block.admin = data[i*num_ele+6];
		block.current = data[i*num_ele+7];
		block.image = data[i*num_ele+8];

		blockdata.push(block);
	}
	blockdata.length = blockdata.length-2;
	console.dir(blockdata);
	draw(blockdata);
  });

  var blockdata = [];
  var infobox;
  var previewbox;

  var callBlocks = function(ticket){
	// +- 1 hour blocks range
	var beginT = d3.time.hour.floor(ticket);
	beginT = d3.time.hour.offset(beginT, -1);
	var endT = d3.time.hour.offset(beginT, 3);

	// >>>>>> socket: call blocks
	socket.emit('/timeline/#callblock');
	}

  var draw = function(blockdata){
    document.getElementById("btn_close").style.display="none"
    d3.select("svg")
       .remove();
	var tip = d3.tip()
		.attr('class', 'd3-tip')
		.direction('e')
		.offset([0,10])
		.html(function(d) {
			return "time: "+d.time;
		});

	var svg = d3.select("#d3Area").append("svg")
		.attr("width", width)
		.attr("height", height)
		.append("g")
		.attr("transform", "translate(4, 4)");

	svg.call(tip);

	var block = svg.selectAll(".block")
		.data(blockdata)
	.enter().append("g")
		.attr("class", "block")
		.attr("transform", function (d,i)
		{
			//var dx = (i-i%12)/12*(cellWidth+gapWidth);
			//var dy =  i%12 * (cellHeight+gapHeight);
			var dx = i%12 * (cellWidth+gapWidth);
			var dy = Dy+(i-i%12)/12*(cellHeight+gapHeight);
			return "translate(" + dx + ","+ dy + ")";
		})
		.on('mouseover', tip.show)
		.on('mouseout', tip.hide);

	block.append("rect")
		.attr("class", function (d)
		{
			if (d.lock==1){
				class_name="block-locked";
			}else{
				if (d.current==1){
					class_name="block-current";
				}else{
					var class_name="block-default";
				}
			}
			return class_name;
		})
		.attr("width", cellWidth)
		.attr("height", cellHeight)
		.attr("block-hour", function (d,i){
			var class_name;
			var hour = (i-i%12)/12;

			if (hour==1){
				class_name="current";
			}else{
				if (hour>1){
					class_name="future";
				}else{
					var class_name="past";
				}
			}
			return class_name;
		})
		.on('mouseover', tip.show)
		.on('mouseout', tip.hide)
		.on('click', mouseclick);

	block.append("text")
		.attr("class", "block-name")
		.attr("x",10)
		.attr("y",14)
		.attr("dy", ".3em")
		.text(function(d) {
			var h = d.time.getHours();
			var ampm = (h<12 ? "a":"p");
			//h=("0" + h%12).slice(-2);
			h=(h%12);
			if(h==0){h="12";}
			var m = d.time.getMinutes();
			m=("0" + m).slice(-2);
			return h+":"+m+ampm;
		})
		.on('mouseover', tip.show)
		.on('mouseout', tip.hide);
  }

  function mouseclick(d,i){
	document.getElementById("btn_enter").disabled = true;
    document.getElementById("btn_access").disabled = true;
    document.getElementById("btn_reserve").disabled = true;

  	// reset to default layout
  	d3.selectAll(".block rect").transition().duration(1000)
  		.attr("width", cellWidth)
  		.attr("height", cellHeight);

  	d3.selectAll(".block").transition().duration(1000)
  		.attr("transform", function (d,i)
		{
			var dx = i%12 * (cellWidth+gapWidth);
			var dy = Dy+(i-i%12)/12*(cellHeight+gapHeight);
			return "translate(" + dx + ","+ dy + ")";
		});

  	var data;
	d3.select(this.parentNode).transition().duration(1000)
		.attr("transform", function (d)
		{
			data = d;
			var dx = 200;
			var dy = 4;
			return "translate(" + dx + ","+ dy + ")";
		});

	// expand the selected block*/
  	d3.select(this).transition().duration(1000)
        .attr("width", (cellWidth+gapWidth)*4)
        .attr("height", (cellHeight+gapHeight)/2);

    switch(this.getAttribute("class"))
    {
    	case "block-locked":
    		document.getElementById("btn_enter").disabled = true;
    		document.getElementById("btn_access").disabled = false;
    		document.getElementById("btn_reserve").disabled = true;
    		document.getElementById("btn_pattern").disabled = true;
    		break;
    	case "block-current":
    		document.getElementById("btn_enter").disabled = false;
    		document.getElementById("btn_access").disabled = true;
    		document.getElementById("btn_reserve").disabled = true;
    		document.getElementById("btn_pattern").disabled = true;
    		break;
    	case "block-default":
    		document.getElementById("btn_enter").disabled = true;
    		document.getElementById("btn_access").disabled = true;
    		document.getElementById("btn_reserve").disabled = false;
    		document.getElementById("btn_pattern").disabled = false;
    		break;
    }

	// Display block information
  	/*block.time = d;
	block.lock = data[i*num_ele+1];
	block.user_id = data[i*num_ele+2];
	block.exp_id = data[i*num_ele+3];
	block.pattern_id = data[i*num_ele+4];
	block.past = data[i*num_ele+5];
	block.admin = data[i*num_ele+6];
	block.current = data[i*num_ele+7];
	block.image = data[i*num_ele+8];*/

	preloader();

    // preloading for block preview
    function preloader()
	{
		if(data.image<0){
			document.getElementById("btn_close").style.display="none";
			previewbox.html("[no preview]");
			writeInfo();
		}
		else
		{
			getPreview("http://171.65.102.132:3001/"+data.image, function(image) {
            	previewbox.html(image);
            	// width="50%" height="50%"
            	writeInfo();
            });
        }

    	function getPreview(path, callback) {
    		document.getElementById("btn_close").style.display="block";
            var image = new Image;
            image.id = "img_preview";
            image.src = path;
            image.setAttribute("class","img-responsive img-thumbnail");
            image.setAttribute("alt","Responsive image");
            image.onload = function() {
                callback(image);
            };
        }
	}

	// write block info to infobox
    function writeInfo(){
		var strInfo;
		strInfo = ""+data.time+"";
		strInfo = concatNewline(strInfo,"block id:"+data.id);
		if(data.user_id<0){
			strInfo = concatNewline(strInfo,"[not claimed]");
		}else{
			strInfo = concatNewline(strInfo,"owner: "+data.user_id);
		}
		infobox.html(strInfo);
    }
  }

  function concatNewline(str0,str1){
	var strHTML = str0.concat("
");
	strHTML = strHTML.concat(str1);
  	return strHTML
  }

  var addChatMessage = function(data) {
    $('
', { text: data }).appendTo('#date_picker');
    $("#date_picker").animate({ scrollTop: $('#date_picker')[0].scrollHeight}, 500);
  };

  socket = io.connect();
  socket.on('connect', function(){
  	socket.emit('/timeline/#join');
  	currenttime = new Date();
  	//callBlocks(currenttime);
  	myClock=setInterval(function(){myTimer()},500);
  	console.log('connected');
  });

  socket.on('/timeline/#blocks-delivery', function(data){
  	blockdata = [];
  	var num_ele = 9;
	for (var i=0;i<=data.length/num_ele;i++){
		var block = new Object();
		block.id = i;

		var d = new Date(0);
		d.setTime(data[i*num_ele]);
		block.time = d;

		block.lock = data[i*num_ele+1];
		block.user_id = data[i*num_ele+2];
		block.exp_id = data[i*num_ele+3];
		block.pattern_id = data[i*num_ele+4];
		block.past = data[i*num_ele+5];
		block.admin = data[i*num_ele+6];
		block.current = data[i*num_ele+7];
		block.image = data[i*num_ele+8];

		blockdata.push(block);
	}
	blockdata.length = blockdata.length-2;
	console.dir(blockdata);
	draw(blockdata);
  });

  socket.on('/about/#newVisitor', function(visitor) {
    addChatMessage(visitor +': joined');
  });

  socket.on('/timeline/#show-clock', function(data){
  	var str = data.split(":");
  	if(str[1]=='00'){
  		if((str[0]=="2")||(str[0]=="5")) {
  			callBlocks(currenttime);
  		}
  	}
  	if(str[0]=="0"){
  		clockbar.html(""+data+"");
  	}
  	else{
  		clockbar.html(""+data+"");
  	}
  });

  socket.on('disconnect', function() {
	console.log('disconnected');
  });

  app = app || {};

  app.Blocks = Backbone.Model.extend({
    url: '/account/timeline/',
    defaults: {
      username: '',
      timestamp: ''
    }
  });

  app.BlocksView = Backbone.View.extend({
    el: '#blocks_nav',
    template: _.template( $('#tmpl-blocks_nav').html() ),
    events: {
      'click .btn-prev': 'reqPrev',
      'click .btn-now': 'reqNow',
      'click .btn-next': 'reqNext'
    },
    initialize: function() {
      this.model = new app.Blocks();
      this.listenTo(this.model, 'sync', this.render);
      this.render();
    },
    render: function() {
      this.$el.html(this.template( this.model.attributes));
    },
    reqPrev: function() {
      currenttime.setHours(currenttime.getHours() - 1);
      callBlocks(currenttime);
    },
    reqNow: function() {
      currenttime = new Date();
      callBlocks(currenttime);
    },
    reqNext: function() {
      currenttime.setHours(currenttime.getHours() + 1);
      callBlocks(currenttime);
    }
  });

  app.MenuView = Backbone.View.extend({
    el: '#info_menu',
    template: _.template( $('#tmpl-info_menu').html() ),
    events: {
      'click .btn-reserve': 'reqReserve',
      'click .btn-pattern': 'reqSetPattern',
      'click .btn-enter': 'reqEnterFreeform',
      'click .btn-access': 'reqDataAccess'
    },
    initialize: function() {
      this.model = new app.Blocks();
      this.listenTo(this.model, 'sync', this.render);
      this.render();
      document.getElementById("btn_enter").disabled = true;
      document.getElementById("btn_access").disabled = true;
      document.getElementById("btn_reserve").disabled = true;
      document.getElementById("btn_pattern").disabled = true;
      infobox = $('#info_box');
      previewbox = $('#preview_box');
    },
    render: function() {
      this.$el.html(this.template( this.model.attributes));
    },
    reqReserve: function() {
    	console.log(user.username+": Reserve block");
    	console.log(user.id);
    	// >>>>>> socket: reserve block
    },
    reqSetPattern: function() {
    	console.log("Set Pattern");
    },
    reqDataAccess: function() {
    	console.log("Data Access");
    },
    reqEnterFreeform: function() {
    	console.log("Enter");
    }
  });

  $(document).ready(function() {
    app.blocksView = new app.BlocksView();
    app.menuView = new app.MenuView();
  });

  $('#d3Area').scroll(function() {
    $('#blockArea').css('top', $(this).scrollTop());
  });

  $('#btn_close').click(function(){
    $('#img_preview').css('display','none');
    document.getElementById("btn_close").style.display="none";
  });

}());
<commit_msg>socket migration<commit_after>/* global app:true, io:false */

var read_socket;
var currenttime;
var username='noname';

var width = 900,
	height = 500,
	cellWidth = 60,
	cellHeight = 58, // cell size
	gapWidth = 12,
	gapHeight = 16
	Dy = 64;

var hour = d3.time.format("%I"),
	minute = d3.time.format("%M"),
	month = d3.time.format("%b"),
	weekday = d3.time.format("%a"),
	date = d3.time.format("%d"),
	ampm = d3.time.format("%p"),
	format = d3.time.format("%b/%d %H:%M%p");

(function() {
  'use strict';

  var clockbar = $('#clock_bar');
  var myClock;
  function myTimer(){
		// >>>>>> socket: look clock
		read_socket.emit('lookclock');
  }
  read_socket = io.connect('http://171.65.102.132:3006');

  read_socket.on('server_clock', function(data){
  	var str = data.split(":");
  	if(str[1]=='00'){
  		if((str[0]=="2")||(str[0]=="5")) {
  			callBlocks(currenttime);
  		}
  	}
  	if(str[0]=="0"){
  		clockbar.html(""+data+"");
  	}
  	else{
  		clockbar.html(""+data+"");
  	}
  });

  read_socket.on('connect', function() {
	console.log("Connected!");
	currenttime = new Date();
	//callBlocks(currenttime);
	myClock=setInterval(function(){myTimer()},500);
  });

  read_socket.on('disconnect', function() {
	console.log('clock lost');
  }

  read_socket.on('postblocks', function(data){
  	blockdata = [];
  	var num_ele = 9;
	for (var i=0;i<=data.length/num_ele;i++){
		var block = new Object();
		block.id = i;

		var d = new Date(0);
		d.setTime(data[i*num_ele]);
		block.time = d;

		block.lock = data[i*num_ele+1];
		block.user_id = data[i*num_ele+2];
		block.exp_id = data[i*num_ele+3];
		block.pattern_id = data[i*num_ele+4];
		block.past = data[i*num_ele+5];
		block.admin = data[i*num_ele+6];
		block.current = data[i*num_ele+7];
		block.image = data[i*num_ele+8];

		blockdata.push(block);
	}
	blockdata.length = blockdata.length-2;
	console.dir(blockdata);
	draw(blockdata);
  });

  var blockdata = [];
  var infobox;
  var previewbox;

  var callBlocks = function(ticket){
	// +- 1 hour blocks range
	var beginT = d3.time.hour.floor(ticket);
	beginT = d3.time.hour.offset(beginT, -1);
	var endT = d3.time.hour.offset(beginT, 3);

	// >>>>>> socket: call blocks
	socket.emit('/timeline/#callblock');
	}

  var draw = function(blockdata){
    document.getElementById("btn_close").style.display="none"
    d3.select("svg")
       .remove();
	var tip = d3.tip()
		.attr('class', 'd3-tip')
		.direction('e')
		.offset([0,10])
		.html(function(d) {
			return "time: "+d.time;
		});

	var svg = d3.select("#d3Area").append("svg")
		.attr("width", width)
		.attr("height", height)
		.append("g")
		.attr("transform", "translate(4, 4)");

	svg.call(tip);

	var block = svg.selectAll(".block")
		.data(blockdata)
	.enter().append("g")
		.attr("class", "block")
		.attr("transform", function (d,i)
		{
			//var dx = (i-i%12)/12*(cellWidth+gapWidth);
			//var dy =  i%12 * (cellHeight+gapHeight);
			var dx = i%12 * (cellWidth+gapWidth);
			var dy = Dy+(i-i%12)/12*(cellHeight+gapHeight);
			return "translate(" + dx + ","+ dy + ")";
		})
		.on('mouseover', tip.show)
		.on('mouseout', tip.hide);

	block.append("rect")
		.attr("class", function (d)
		{
			if (d.lock==1){
				class_name="block-locked";
			}else{
				if (d.current==1){
					class_name="block-current";
				}else{
					var class_name="block-default";
				}
			}
			return class_name;
		})
		.attr("width", cellWidth)
		.attr("height", cellHeight)
		.attr("block-hour", function (d,i){
			var class_name;
			var hour = (i-i%12)/12;

			if (hour==1){
				class_name="current";
			}else{
				if (hour>1){
					class_name="future";
				}else{
					var class_name="past";
				}
			}
			return class_name;
		})
		.on('mouseover', tip.show)
		.on('mouseout', tip.hide)
		.on('click', mouseclick);

	block.append("text")
		.attr("class", "block-name")
		.attr("x",10)
		.attr("y",14)
		.attr("dy", ".3em")
		.text(function(d) {
			var h = d.time.getHours();
			var ampm = (h<12 ? "a":"p");
			//h=("0" + h%12).slice(-2);
			h=(h%12);
			if(h==0){h="12";}
			var m = d.time.getMinutes();
			m=("0" + m).slice(-2);
			return h+":"+m+ampm;
		})
		.on('mouseover', tip.show)
		.on('mouseout', tip.hide);
  }

  function mouseclick(d,i){
	document.getElementById("btn_enter").disabled = true;
    document.getElementById("btn_access").disabled = true;
    document.getElementById("btn_reserve").disabled = true;

  	// reset to default layout
  	d3.selectAll(".block rect").transition().duration(1000)
  		.attr("width", cellWidth)
  		.attr("height", cellHeight);

  	d3.selectAll(".block").transition().duration(1000)
  		.attr("transform", function (d,i)
		{
			var dx = i%12 * (cellWidth+gapWidth);
			var dy = Dy+(i-i%12)/12*(cellHeight+gapHeight);
			return "translate(" + dx + ","+ dy + ")";
		});

  	var data;
	d3.select(this.parentNode).transition().duration(1000)
		.attr("transform", function (d)
		{
			data = d;
			var dx = 200;
			var dy = 4;
			return "translate(" + dx + ","+ dy + ")";
		});

	// expand the selected block*/
  	d3.select(this).transition().duration(1000)
        .attr("width", (cellWidth+gapWidth)*4)
        .attr("height", (cellHeight+gapHeight)/2);

    switch(this.getAttribute("class"))
    {
    	case "block-locked":
    		document.getElementById("btn_enter").disabled = true;
    		document.getElementById("btn_access").disabled = false;
    		document.getElementById("btn_reserve").disabled = true;
    		document.getElementById("btn_pattern").disabled = true;
    		break;
    	case "block-current":
    		document.getElementById("btn_enter").disabled = false;
    		document.getElementById("btn_access").disabled = true;
    		document.getElementById("btn_reserve").disabled = true;
    		document.getElementById("btn_pattern").disabled = true;
    		break;
    	case "block-default":
    		document.getElementById("btn_enter").disabled = true;
    		document.getElementById("btn_access").disabled = true;
    		document.getElementById("btn_reserve").disabled = false;
    		document.getElementById("btn_pattern").disabled = false;
    		break;
    }

	// Display block information
  	/*block.time = d;
	block.lock = data[i*num_ele+1];
	block.user_id = data[i*num_ele+2];
	block.exp_id = data[i*num_ele+3];
	block.pattern_id = data[i*num_ele+4];
	block.past = data[i*num_ele+5];
	block.admin = data[i*num_ele+6];
	block.current = data[i*num_ele+7];
	block.image = data[i*num_ele+8];*/

	preloader();

    // preloading for block preview
    function preloader()
	{
		if(data.image<0){
			document.getElementById("btn_close").style.display="none";
			previewbox.html("[no preview]");
			writeInfo();
		}
		else
		{
			getPreview("http://171.65.102.132:3001/"+data.image, function(image) {
            	previewbox.html(image);
            	// width="50%" height="50%"
            	writeInfo();
            });
        }

    	function getPreview(path, callback) {
    		document.getElementById("btn_close").style.display="block";
            var image = new Image;
            image.id = "img_preview";
            image.src = path;
            image.setAttribute("class","img-responsive img-thumbnail");
            image.setAttribute("alt","Responsive image");
            image.onload = function() {
                callback(image);
            };
        }
	}

	// write block info to infobox
    function writeInfo(){
		var strInfo;
		strInfo = ""+data.time+"";
		strInfo = concatNewline(strInfo,"block id:"+data.id);
		if(data.user_id<0){
			strInfo = concatNewline(strInfo,"[not claimed]");
		}else{
			strInfo = concatNewline(strInfo,"owner: "+data.user_id);
		}
		infobox.html(strInfo);
    }
  }

  function concatNewline(str0,str1){
	var strHTML = str0.concat("
");
	strHTML = strHTML.concat(str1);
  	return strHTML
  }

  var addChatMessage = function(data) {
    $('
', { text: data }).appendTo('#date_picker');
    $("#date_picker").animate({ scrollTop: $('#date_picker')[0].scrollHeight}, 500);
  };

  socket = io.connect();
  socket.on('connect', function(){
  	socket.emit('/timeline/#join');
  	currenttime = new Date();
  	//callBlocks(currenttime);
  	myClock=setInterval(function(){myTimer()},500);
  	console.log('connected');
  });

  socket.on('/timeline/#blocks-delivery', function(data){
  	blockdata = [];
  	var num_ele = 9;
	for (var i=0;i<=data.length/num_ele;i++){
		var block = new Object();
		block.id = i;

		var d = new Date(0);
		d.setTime(data[i*num_ele]);
		block.time = d;

		block.lock = data[i*num_ele+1];
		block.user_id = data[i*num_ele+2];
		block.exp_id = data[i*num_ele+3];
		block.pattern_id = data[i*num_ele+4];
		block.past = data[i*num_ele+5];
		block.admin = data[i*num_ele+6];
		block.current = data[i*num_ele+7];
		block.image = data[i*num_ele+8];

		blockdata.push(block);
	}
	blockdata.length = blockdata.length-2;
	console.dir(blockdata);
	draw(blockdata);
  });

  socket.on('/about/#newVisitor', function(visitor) {
    addChatMessage(visitor +': joined');
  });

  socket.on('/timeline/#show-clock', function(data){
  	var str = data.split(":");
  	if(str[1]=='00'){
  		if((str[0]=="2")||(str[0]=="5")) {
  			callBlocks(currenttime);
  		}
  	}
  	if(str[0]=="0"){
  		clockbar.html(""+data+"");
  	}
  	else{
  		clockbar.html(""+data+"");
  	}
  });

  socket.on('disconnect', function() {
	console.log('disconnected');
  });

  app = app || {};

  app.Blocks = Backbone.Model.extend({
    url: '/account/timeline/',
    defaults: {
      username: '',
      timestamp: ''
    }
  });

  app.BlocksView = Backbone.View.extend({
    el: '#blocks_nav',
    template: _.template( $('#tmpl-blocks_nav').html() ),
    events: {
      'click .btn-prev': 'reqPrev',
      'click .btn-now': 'reqNow',
      'click .btn-next': 'reqNext'
    },
    initialize: function() {
      this.model = new app.Blocks();
      this.listenTo(this.model, 'sync', this.render);
      this.render();
    },
    render: function() {
      this.$el.html(this.template( this.model.attributes));
    },
    reqPrev: function() {
      currenttime.setHours(currenttime.getHours() - 1);
      callBlocks(currenttime);
    },
    reqNow: function() {
      currenttime = new Date();
      callBlocks(currenttime);
    },
    reqNext: function() {
      currenttime.setHours(currenttime.getHours() + 1);
      callBlocks(currenttime);
    }
  });

  app.MenuView = Backbone.View.extend({
    el: '#info_menu',
    template: _.template( $('#tmpl-info_menu').html() ),
    events: {
      'click .btn-reserve': 'reqReserve',
      'click .btn-pattern': 'reqSetPattern',
      'click .btn-enter': 'reqEnterFreeform',
      'click .btn-access': 'reqDataAccess'
    },
    initialize: function() {
      this.model = new app.Blocks();
      this.listenTo(this.model, 'sync', this.render);
      this.render();
      document.getElementById("btn_enter").disabled = true;
      document.getElementById("btn_access").disabled = true;
      document.getElementById("btn_reserve").disabled = true;
      document.getElementById("btn_pattern").disabled = true;
      infobox = $('#info_box');
      previewbox = $('#preview_box');
    },
    render: function() {
      this.$el.html(this.template( this.model.attributes));
    },
    reqReserve: function() {
    	console.log(user.username+": Reserve block");
    	console.log(user.id);
    	// >>>>>> socket: reserve block
    },
    reqSetPattern: function() {
    	console.log("Set Pattern");
    },
    reqDataAccess: function() {
    	console.log("Data Access");
    },
    reqEnterFreeform: function() {
    	console.log("Enter");
    }
  });

  $(document).ready(function() {
    app.blocksView = new app.BlocksView();
    app.menuView = new app.MenuView();
  });

  $('#d3Area').scroll(function() {
    $('#blockArea').css('top', $(this).scrollTop());
  });

  $('#btn_close').click(function(){
    $('#img_preview').css('display','none');
    document.getElementById("btn_close").style.display="none";
  });

}());
<|endoftext|>


<commit_before>var audio_context, oscillator, gainNode, volController;

var initialVol = 0.8;
var currentVol = initialVol;
var finalVol = 0;

  function stopSound() {
    clearInterval(volController);
    currentVol = initialVol;

    //oscillator.noteOff(0);
    gainNode.disconnect(audio_context.destination);
  }

  function playSound(freq) {
          if(gainNode != undefined){ stopSound(); }
          oscillator = audio_context.createOscillator();
          gainNode = audio_context.createGain();

          oscillator.connect(gainNode);
          gainNode.connect(audio_context.destination);

          oscillator.type = "triangle";
          oscillator.frequency.value = freq;
          oscillator.start();
          gainNode.gain.value = $("#oscillator-gain").val();

            $("#oscillator-gain").change(function(){
            gainNode.gain.value = $("#oscillator-gain").val();
          });
  }

 (function init(g){
 	try{
 		audio_context = new(g.AudioContext || g.webkitAudioContext);
 		oscillator = audio_context.createOscillator();
 	} catch(e){
 		alert("No web audio oscillator support in this browser. Use Chrome, fool!");
 		soundIssues = true;
 	}
 }(window));
<commit_msg>Update sound.js<commit_after>var audio_context, oscillator, gainNode, volController;

var initialVol = 0.8;
var currentVol = initialVol;
var finalVol = 0;

  function stopSound() {
    clearInterval(volController);
    currentVol = initialVol;

    //oscillator.noteOff(0);
    gainNode.disconnect(audio_context.destination);
  }

  function playSound(freq) {
          if(gainNode != undefined){ stopSound(); }
          oscillator = audio_context.createOscillator();
          gainNode = audio_context.createGain();

          oscillator.connect(gainNode);
          gainNode.connect(audio_context.destination);

          oscillator.type = "triangle";
          oscillator.frequency.value = freq;
          oscillator.start();
          gainNode.gain.value = $("#oscillator-gain").val();

            $("#oscillator-gain").change(function(){
            gainNode.gain.value = $("#oscillator-gain").val();
          });

          $("input[type='radio'][name='oscillator-gain']") // select the radio by its id
            .change(function(){ // bind a function to the change event
                if( $(this).is(":checked") ){ // check if the radio is checked
                    var oscillator.type = $(this).val(); // retrieve the value
                }
            });
  }

 (function init(g){
 	try{
 		audio_context = new(g.AudioContext || g.webkitAudioContext);
 		oscillator = audio_context.createOscillator();
 	} catch(e){
 		alert("No web audio oscillator support in this browser. Use Chrome, fool!");
 		soundIssues = true;
 	}
 }(window));
<|endoftext|>


<commit_before>'use strict';

var debug = require('debug')('MWS:AmazonMwsResource');
var http = require('http');
var https = require('https');
var objectAssign = require('object-assign');
var path = require('path');
var xml2json = require('xml2json');
var crypto = require('crypto');
var _ = require('lodash');
var qs = require('qs');
var csv = require('fast-csv');

var utils = require('./utils');
var Error = require('./Error');

var hasOwn = {}.hasOwnProperty;

var RESPONSE_CONTENT_TYPE = ['text/xml', 'text/xml;charset=utf-8'];
// Provide extension mechanism for AmazonMws Resource Sub-Classes
AmazonMwsResource.extend = utils.protoExtend;

// Expose method-creator & prepared (basic) methods
AmazonMwsResource.method = require('./AmazonMwsMethod');
AmazonMwsResource.BASIC_METHODS = require('./AmazonMwsMethod.basic.js');

/**
 * Encapsulates request logic for a AmazonMws Resource
 */
function AmazonMwsResource(AmazonMws, urlData) {
    this._AmazonMws = AmazonMws;
    this._urlData = urlData || {};

    this.basePath = utils.makeURLInterpolator(AmazonMws.getApiField('basePath'));
    this.path = utils.makeURLInterpolator(this.path);

    if (this.includeBasic) {
        this.includeBasic.forEach(function (methodName) {
            this[methodName] = AmazonMwsResource.BASIC_METHODS[methodName];
        }, this);
    }

    this.initialize.apply(this, arguments);
}

AmazonMwsResource.prototype = {

    path: '',
    requestBody: {},
    requestParamsJSON: {},
    initialize: function () {
    },

    // Function to override the default data processor. This allows full control
    // over how a AmazonMwsResource's request data will get converted into an HTTP
    // body. This is useful for non-standard HTTP requests. The function should
    // take method name, data, and headers as arguments.
    requestDataProcessor: null,

    // String that overrides the base API endpoint. If `overrideHost` is not null
    // then all requests for a particular resource will be sent to a base API
    // endpoint as defined by `overrideHost`.
    overrideHost: null,

    createFullPath: function (commandPath, urlData) {
        return path.join(
          this.basePath(urlData),
          this.path(urlData),
          typeof commandPath === 'function' ?
            commandPath(urlData) : commandPath
        ).replace(/\\/g, '/'); // ugly workaround for Windows
    },

    createUrlData: function () {
        var urlData = {};
        // Merge in baseData
        for (var i in this._urlData) {
            if (hasOwn.call(this._urlData, i)) {
                urlData[i] = this._urlData[i];
            }
        }
        return urlData;
    },

    wrapTimeout: function (promise, callback) {
        if (callback) {
            // Ensure callback is called outside of promise stack.
            return promise.then(function (res) {
                setTimeout(function () {
                    callback(null, res);
                }, 0);
            }, function (err) {
                setTimeout(function () {
                    callback(err, null);
                }, 0);
            });
        }

        return promise;
    },

    _timeoutHandler: function (timeout, req, callback) {
        var self = this;
        return function () {
            var timeoutErr = new Error('ETIMEDOUT');
            timeoutErr.code = 'ETIMEDOUT';

            req._isAborted = true;
            req.abort();

            callback.call(
              self,
              new Error.AmazonMwsConnectionError({
                  message: 'Request aborted due to timeout being reached (' + timeout + 'ms)',
                  detail: timeoutErr
              }),
              null
            );
        };
    },

    _responseHandler: function (requestParamsJSONCopy, req, callback) {
        var self = this;

        function processXml(o, action) {
            var type = typeof o;
            if (type === 'object') {
                for (var key in o) {
                    if (key.indexOf('ns2:') > -1) {
                        if (action === 'update') {
                            var temp = key.replace(/^ns2:/, '');
                            o[temp] = o[key];

                        } else if (action === 'delete') {
                            delete o[key];
                        }
                    }
                    if (key.indexOf('$t') > -1) {
                        if (action === 'update') {
                            o['Value'] = o[key];
                        }
                    }
                    var removeKeys = ['xmlns', 'xmlns:ns2', '$t'];
                    if (removeKeys.indexOf(key) > -1 && action === 'delete') {
                        if (action === 'delete') {
                            delete o[key];
                        }
                    }
                    processXml(o[key], action);
                }
            }
        }

        function parseCSVFile(res, responseString, delimiter, callback) {
            var data = [];
            csv.fromString(responseString, {headers: true, delimiter: delimiter, ignoreEmpty: true})
              .on('data', function (value) {
                  data.push(value);
              })
              .on('end', function () {
                  debug('response after parsing tab delimited file %o ', data);
                  var items = {};
                  items.data = data;
                  items.Headers = {
                      'x-mws-quota-max': res.headers['x-mws-quota-max'] || 'unknown',
                      'x-mws-quota-remaining': res.headers['x-mws-quota-remaining'] || 'unknown',
                      'x-mws-quota-resetson': res.headers['x-mws-quota-resetson'] || 'unknown',
                      'x-mws-timestamp': res.headers['x-mws-timestamp']
                  };
                  return callback(null, items);
              })
              .on('error', function (error) {
                  return callback(error);
              });
        }

        function processResponseType(res, responseString, callback) {
            //debug('response %o ', response);
            //debug('res.headers %o ', res.headers);
            if (RESPONSE_CONTENT_TYPE.indexOf(res.headers['content-type'].toLowerCase()) > -1) {
                debug('It is XML Response');
                var items = xml2json.toJson(responseString);
                //debug('response after parsing JSON %o ', response);
                items = JSON.parse(items);
                items.Headers = {
                    'x-mws-quota-max': res.headers['x-mws-quota-max'] || 'unknown',
                    'x-mws-quota-remaining': res.headers['x-mws-quota-remaining'] || 'unknown',
                    'x-mws-quota-resetson': res.headers['x-mws-quota-resetson'] || 'unknown',
                    'x-mws-timestamp': res.headers['x-mws-timestamp']
                };
                //debug('after adding header response', response);
                return callback(null, items);
            } else {
                debug('It is NON-XML Response');
                var TAB_DELIMITER = '\t';
                var COMMA_DELIMITER = ',';
                try {
                    parseCSVFile(res, responseString, TAB_DELIMITER, callback);
                } catch (Exception) {
                    debug('It is TAB_DELIMITER Exception ', Exception);
                    debug('Let us try to delimit using COMMA_DELIMITER');
                    try {
                        parseCSVFile(res, responseString, COMMA_DELIMITER, callback);
                    } catch (Exception) {
                        debug('It is COMMA_DELIMITER Exception ', Exception);
                        debug('Parsing using both TAB_DELIMITER & COMMA_DELIMITER Failed.');
                        debug('It may due to empty response or invalid request.');
                        return callback(new Error('Parsing fail.'));
                    }
                }

            }
        }

        return function (res) {
            var responseString = '';
            res.setEncoding('utf8');
            res.on('data', function (chunk) {
                responseString += chunk;
            });
            res.on('end', function () {
                try {
                    //debug('self.requestParamsJSON ', self.requestParamsJSON);

                    processResponseType(res, responseString, function (error, response) {

                        if (error) {
                            debug('Error ', error);
                            return callback.call(
                              self,
                              new Error.AmazonMwsAPIError({
                                  message: 'Failed to parse response received from the AmazonMws API',
                                  response: response,
                                  exception: error
                              }),
                              null
                            );
                        }

                        if (response.ErrorResponse) {
                            var errorResponse = response.ErrorResponse.Error;
                            errorResponse.RequestId = response.ErrorResponse.RequestID || response.ErrorResponse.RequestId;
                            return callback.call(self, errorResponse, null);
                        }

                        var ResponseMetadata = {};
                        var Headers = {};
                        debug('res.headers[content-type]', res.headers['content-type']);
                        if (RESPONSE_CONTENT_TYPE.indexOf(res.headers['content-type'].toLowerCase()) > -1) {
                            /*
                             * It should execute for only XML response
                             */
                            // debug('response.headers', response.headers);
                            debug('response Before Process %o ', JSON.stringify(response));
                            Headers = response.Headers;
                            if (response[requestParamsJSONCopy.Action + 'Response']) {
                                response = response[requestParamsJSONCopy.Action + 'Response'];
                            }
                            //debug('response', response);
                            try {
                                ResponseMetadata = response.ResponseMetadata;
                            } catch (exception) {
                                debug('exception', exception);
                                ResponseMetadata = {};
                            }
                            // debug('ResponseMetadata %o ', ResponseMetadata);
                            if (response[requestParamsJSONCopy.Action + 'Result']) {
                                response = response[requestParamsJSONCopy.Action + 'Result'];
                            }

                            response.ResponseMetadata = ResponseMetadata;
                            response.Headers = Headers;
                            debug('response before %o ', JSON.stringify(response));
                            processXml(response, 'update');
                            processXml(response, 'delete');
                            //debug('response after Process %o ', JSON.stringify(response));
                        }
                        debug('final response %o ', response);
                        // Expose res object
                        Object.defineProperty(response, 'lastResponse', {
                            enumerable: false,
                            writable: false,
                            value: res
                        });
                        callback.call(self, null, response);
                    });

                } catch (e) {
                    return callback.call(
                      self,
                      new Error.AmazonMwsAPIError({
                          message: 'Invalid JSON received from the AmazonMws API',
                          response: responseString,
                          exception: e
                      }),
                      null
                    );
                }
            });
        };
    },

    _errorHandler: function (req, callback) {
        var self = this;
        return function (error) {
            if (req._isAborted) {
                // already handled
                return;
            }
            callback.call(
              self,
              new Error.AmazonMwsConnectionError({
                  message: 'An error occurred with our connection to AmazonMws',
                  detail: error
              }),
              null
            );
        };
    },

    _request: function (method, path, data, auth, options, callback) {
        var self = this;
        //debug('path ', path);
        self.requestParams = data;
        self.body = '';
        if (!self.requestParams.Version) {
            return callback.call(
              self,
              new Error.AmazonMwsAPIError({
                  message: 'Please specify the Amazon MWS API Version',
                  detail: 'http://docs.developer.amazonservices.com',
                  type: 'GenericError',
                  code: '404',
                  param: self.requestParams
              }),
              null
            );
        } else if (!self._AmazonMws.getApiField('key')) {
            return callback.call(
              self,
              new Error.AmazonMwsAPIError({
                  message: '**Please specify the AWS_ACCESS_KEY_ID',
                  detail: 'http://docs.developer.amazonservices.com',
                  type: 'GenericError',
                  code: '404',
                  param: self.requestParams
              }),
              null
            );
        } else if (!self._AmazonMws.getApiField('secret')) {
            return callback.call(
              self,
              new Error.AmazonMwsAPIError({
                  message: 'Please specify the AWS_SECRET_ACCESS_KEY',
                  detail: 'http://docs.developer.amazonservices.com',
                  type: 'GenericError',
                  code: '404',
                  param: self.requestParams
              }),
              null
            );
        }
        if (self.requestParams.APIVersion) {
            path = path + '/' + self.requestParams.APIVersion;
            delete self.requestParams.APIVersion;
        } else {
            path = path + '/' + self.requestParams.Version;
        }

        if (self.requestParams.Action === 'SubmitFeed') {
            /*
             * Use Feed Content without modify it as querystring for the SubmitFeed API
             */
            self.body = self.requestParams.FeedContent;
            self.requestParams.ContentMD5Value = crypto.createHash('md5').update(self.body).digest('base64');
            delete self.requestParams.FeedContent;
        }
        //debug(' self.body %o ', self.body);
        self.requestParams.AWSAccessKeyId = this._AmazonMws.getApiField('key');
        self.requestParams.Timestamp = new Date();
        self.requestParams.SignatureVersion = '2';
        self.requestParams.SignatureMethod = 'HmacSHA256';
        var sorted = _.reduce(_.keys(self.requestParams).sort(), function (m, k) {
            m[k] = self.requestParams[k];
            return m;
        }, {});
        var stringToSign = [method, self._AmazonMws.getApiField('host'), path, qs.stringify(sorted)].join('\n');
        // An RFC (cannot remember which one) requires these characters also be changed:
        stringToSign = stringToSign.replace(/'/g, '%27');
        stringToSign = stringToSign.replace(/\*/g, '%2A');
        stringToSign = stringToSign.replace(/\(/g, '%28');
        self.requestParams.Signature = crypto.createHmac('sha256', this._AmazonMws.getApiField('secret')).update(stringToSign, 'utf8').digest('base64');

        self.requestParamsJSON = _.clone(self.requestParams);
        self.requestParams = qs.stringify(self.requestParams);
        /*
         * Use Feed Content without modify it as querystring for the SubmitFeed API
         */
        //self.body = qs.stringify(self.body);

        var headers = {
            'Accept': 'text/xml',
            'Content-Type': 'text/xml',
            'Content-MD5': crypto.createHash('md5').update(self.requestParams).digest('base64')
        };

        if (self.requestParamsJSON.Action === 'SubmitFeed') {
            headers['Content-Type'] = 'x-www-form-urlencoded';
            headers['Content-MD5'] = self.requestParamsJSON.ContentMD5Value;
        }

        // Make a deep copy of the request params, assign to block scoped variable
        var requestParamsCopy = JSON.parse(JSON.stringify(self.requestParams));
        var requestParamsJSONCopy = JSON.parse(JSON.stringify(self.requestParamsJSON));
        // Grab client-user-agent before making the request:
        this._AmazonMws.getClientUserAgent(function () {
            if (options.headers) {
                objectAssign(headers, options.headers);
            }
            makeRequest(requestParamsCopy);
        });

        function makeRequest(requestParamsCopy) {
            var timeout = self._AmazonMws.getApiField('timeout');
            var isInsecureConnection = self._AmazonMws.getApiField('protocol') === 'http';

            var host = self.overrideHost || self._AmazonMws.getApiField('host');
            var params = {
                host: host,
                port: self._AmazonMws.getApiField('port'),
                path: path,
                method: method,
                headers: headers
            };
            params.path = params.path + '?' + requestParamsCopy;

            debug('params %o ', params);
            debug('body %o ', self.body);
            var req = (isInsecureConnection ? http : https).request(params);

            req.setTimeout(timeout, self._timeoutHandler(timeout, req, callback));
            req.on('response', self._responseHandler(requestParamsJSONCopy, req, callback));
            req.on('error', self._errorHandler(req, callback));

            req.on('socket', function (socket) {
                socket.on((isInsecureConnection ? 'connect' : 'secureConnect'), function () {
                    // Send payload; we're safe:
                    //debug('body %o ', self.body);
                    /*
                     * Use Feed Content without modify it as querystring for the SubmitFeed API
                     */
                    req.write(self.body);
                    req.end();
                });
            });
        }
    }

};

module.exports = AmazonMwsResource;
<commit_msg>correct the callback for COMMA_DELIMITER parsing<commit_after>'use strict';

var debug = require('debug')('MWS:AmazonMwsResource');
var http = require('http');
var https = require('https');
var objectAssign = require('object-assign');
var path = require('path');
var xml2json = require('xml2json');
var crypto = require('crypto');
var _ = require('lodash');
var qs = require('qs');
var csv = require('fast-csv');

var utils = require('./utils');
var Error = require('./Error');

var hasOwn = {}.hasOwnProperty;

var RESPONSE_CONTENT_TYPE = ['text/xml', 'text/xml;charset=utf-8'];
// Provide extension mechanism for AmazonMws Resource Sub-Classes
AmazonMwsResource.extend = utils.protoExtend;

// Expose method-creator & prepared (basic) methods
AmazonMwsResource.method = require('./AmazonMwsMethod');
AmazonMwsResource.BASIC_METHODS = require('./AmazonMwsMethod.basic.js');

/**
 * Encapsulates request logic for a AmazonMws Resource
 */
function AmazonMwsResource(AmazonMws, urlData) {
    this._AmazonMws = AmazonMws;
    this._urlData = urlData || {};

    this.basePath = utils.makeURLInterpolator(AmazonMws.getApiField('basePath'));
    this.path = utils.makeURLInterpolator(this.path);

    if (this.includeBasic) {
        this.includeBasic.forEach(function (methodName) {
            this[methodName] = AmazonMwsResource.BASIC_METHODS[methodName];
        }, this);
    }

    this.initialize.apply(this, arguments);
}

AmazonMwsResource.prototype = {

    path: '',
    requestBody: {},
    requestParamsJSON: {},
    initialize: function () {
    },

    // Function to override the default data processor. This allows full control
    // over how a AmazonMwsResource's request data will get converted into an HTTP
    // body. This is useful for non-standard HTTP requests. The function should
    // take method name, data, and headers as arguments.
    requestDataProcessor: null,

    // String that overrides the base API endpoint. If `overrideHost` is not null
    // then all requests for a particular resource will be sent to a base API
    // endpoint as defined by `overrideHost`.
    overrideHost: null,

    createFullPath: function (commandPath, urlData) {
        return path.join(
          this.basePath(urlData),
          this.path(urlData),
          typeof commandPath === 'function' ?
            commandPath(urlData) : commandPath
        ).replace(/\\/g, '/'); // ugly workaround for Windows
    },

    createUrlData: function () {
        var urlData = {};
        // Merge in baseData
        for (var i in this._urlData) {
            if (hasOwn.call(this._urlData, i)) {
                urlData[i] = this._urlData[i];
            }
        }
        return urlData;
    },

    wrapTimeout: function (promise, callback) {
        if (callback) {
            // Ensure callback is called outside of promise stack.
            return promise.then(function (res) {
                setTimeout(function () {
                    callback(null, res);
                }, 0);
            }, function (err) {
                setTimeout(function () {
                    callback(err, null);
                }, 0);
            });
        }

        return promise;
    },

    _timeoutHandler: function (timeout, req, callback) {
        var self = this;
        return function () {
            var timeoutErr = new Error('ETIMEDOUT');
            timeoutErr.code = 'ETIMEDOUT';

            req._isAborted = true;
            req.abort();

            callback.call(
              self,
              new Error.AmazonMwsConnectionError({
                  message: 'Request aborted due to timeout being reached (' + timeout + 'ms)',
                  detail: timeoutErr
              }),
              null
            );
        };
    },

    _responseHandler: function (requestParamsJSONCopy, req, callback) {
        var self = this;

        function processXml(o, action) {
            var type = typeof o;
            if (type === 'object') {
                for (var key in o) {
                    if (key.indexOf('ns2:') > -1) {
                        if (action === 'update') {
                            var temp = key.replace(/^ns2:/, '');
                            o[temp] = o[key];

                        } else if (action === 'delete') {
                            delete o[key];
                        }
                    }
                    if (key.indexOf('$t') > -1) {
                        if (action === 'update') {
                            o['Value'] = o[key];
                        }
                    }
                    var removeKeys = ['xmlns', 'xmlns:ns2', '$t'];
                    if (removeKeys.indexOf(key) > -1 && action === 'delete') {
                        if (action === 'delete') {
                            delete o[key];
                        }
                    }
                    processXml(o[key], action);
                }
            }
        }

        function parseCSVFile(res, responseString, delimiter, callback) {
            var data = [];
            csv.fromString(responseString, {headers: true, delimiter: delimiter, ignoreEmpty: true})
              .on('data', function (value) {
                  data.push(value);
              })
              .on('end', function () {
                  debug('response after parsing file %o ', data);
                  var items = {};
                  items.data = data;
                  items.Headers = {
                      'x-mws-quota-max': res.headers['x-mws-quota-max'] || 'unknown',
                      'x-mws-quota-remaining': res.headers['x-mws-quota-remaining'] || 'unknown',
                      'x-mws-quota-resetson': res.headers['x-mws-quota-resetson'] || 'unknown',
                      'x-mws-timestamp': res.headers['x-mws-timestamp']
                  };
                  return callback(null, items);
              })
              .on('error', function (error) {
                  debug('error ', error);
                  return callback(error);
              });
        }

        function processResponseType(res, responseString, callback) {
            //debug('res %o ', res);
            //debug('res.headers %o ', res.headers);
            if (RESPONSE_CONTENT_TYPE.indexOf(res.headers['content-type'].toLowerCase()) > -1) {
                debug('It is XML Response');
                var items = xml2json.toJson(responseString);
                //debug('res after parsing JSON %o ', res);
                items = JSON.parse(items);
                items.Headers = {
                    'x-mws-quota-max': res.headers['x-mws-quota-max'] || 'unknown',
                    'x-mws-quota-remaining': res.headers['x-mws-quota-remaining'] || 'unknown',
                    'x-mws-quota-resetson': res.headers['x-mws-quota-resetson'] || 'unknown',
                    'x-mws-timestamp': res.headers['x-mws-timestamp']
                };
                //debug('after adding header res', res);
                return callback(null, items);
            } else {
                debug('It is NON-XML Response');
                var TAB_DELIMITER = '\t';
                var COMMA_DELIMITER = ',';
                parseCSVFile(res, responseString, TAB_DELIMITER, function (error, response) {
                    if (!_.isEmpty(error)) {
                        debug('It is TAB_DELIMITER failure.');
                        debug('Let us try to delimit using COMMA_DELIMITER');
                        return parseCSVFile(res, responseString, COMMA_DELIMITER, callback);
                    }
                    return callback(null, response);
                });
            }
        }

        return function (res) {
            var responseString = '';
            res.setEncoding('utf8');
            res.on('data', function (chunk) {
                responseString += chunk;
            });
            res.on('end', function () {
                try {
                    //debug('self.requestParamsJSON ', self.requestParamsJSON);

                    processResponseType(res, responseString, function (error, response) {

                        if (error) {
                            debug('Error ', error);
                            return callback.call(
                              self,
                              new Error.AmazonMwsAPIError({
                                  message: 'Failed to parse response received from the AmazonMws API',
                                  response: response,
                                  exception: error
                              }),
                              null
                            );
                        }

                        if (response.ErrorResponse) {
                            var errorResponse = response.ErrorResponse.Error;
                            errorResponse.RequestId = response.ErrorResponse.RequestID || response.ErrorResponse.RequestId;
                            return callback.call(self, errorResponse, null);
                        }

                        var ResponseMetadata = {};
                        var Headers = {};
                        debug('res.headers[content-type]', res.headers['content-type']);
                        if (RESPONSE_CONTENT_TYPE.indexOf(res.headers['content-type'].toLowerCase()) > -1) {
                            /*
                             * It should execute for only XML response
                             */
                            // debug('response.headers', response.headers);
                            debug('response Before Process %o ', JSON.stringify(response));
                            Headers = response.Headers;
                            if (response[requestParamsJSONCopy.Action + 'Response']) {
                                response = response[requestParamsJSONCopy.Action + 'Response'];
                            }
                            //debug('response', response);
                            try {
                                ResponseMetadata = response.ResponseMetadata;
                            } catch (exception) {
                                debug('exception', exception);
                                ResponseMetadata = {};
                            }
                            // debug('ResponseMetadata %o ', ResponseMetadata);
                            if (response[requestParamsJSONCopy.Action + 'Result']) {
                                response = response[requestParamsJSONCopy.Action + 'Result'];
                            }

                            response.ResponseMetadata = ResponseMetadata;
                            response.Headers = Headers;
                            debug('response before %o ', JSON.stringify(response));
                            processXml(response, 'update');
                            processXml(response, 'delete');
                            //debug('response after Process %o ', JSON.stringify(response));
                        }
                        debug('final response %o ', response);
                        // Expose res object
                        Object.defineProperty(response, 'lastResponse', {
                            enumerable: false,
                            writable: false,
                            value: res
                        });
                        callback.call(self, null, response);
                    });

                } catch (e) {
                    return callback.call(
                      self,
                      new Error.AmazonMwsAPIError({
                          message: 'Invalid JSON received from the AmazonMws API',
                          response: responseString,
                          exception: e
                      }),
                      null
                    );
                }
            });
        };
    },

    _errorHandler: function (req, callback) {
        var self = this;
        return function (error) {
            if (req._isAborted) {
                // already handled
                return;
            }
            callback.call(
              self,
              new Error.AmazonMwsConnectionError({
                  message: 'An error occurred with our connection to AmazonMws',
                  detail: error
              }),
              null
            );
        };
    },

    _request: function (method, path, data, auth, options, callback) {
        var self = this;
        //debug('path ', path);
        self.requestParams = data;
        self.body = '';
        if (!self.requestParams.Version) {
            return callback.call(
              self,
              new Error.AmazonMwsAPIError({
                  message: 'Please specify the Amazon MWS API Version',
                  detail: 'http://docs.developer.amazonservices.com',
                  type: 'GenericError',
                  code: '404',
                  param: self.requestParams
              }),
              null
            );
        } else if (!self._AmazonMws.getApiField('key')) {
            return callback.call(
              self,
              new Error.AmazonMwsAPIError({
                  message: '**Please specify the AWS_ACCESS_KEY_ID',
                  detail: 'http://docs.developer.amazonservices.com',
                  type: 'GenericError',
                  code: '404',
                  param: self.requestParams
              }),
              null
            );
        } else if (!self._AmazonMws.getApiField('secret')) {
            return callback.call(
              self,
              new Error.AmazonMwsAPIError({
                  message: 'Please specify the AWS_SECRET_ACCESS_KEY',
                  detail: 'http://docs.developer.amazonservices.com',
                  type: 'GenericError',
                  code: '404',
                  param: self.requestParams
              }),
              null
            );
        }
        if (self.requestParams.APIVersion) {
            path = path + '/' + self.requestParams.APIVersion;
            delete self.requestParams.APIVersion;
        } else {
            path = path + '/' + self.requestParams.Version;
        }

        if (self.requestParams.Action === 'SubmitFeed') {
            /*
             * Use Feed Content without modify it as querystring for the SubmitFeed API
             */
            self.body = self.requestParams.FeedContent;
            self.requestParams.ContentMD5Value = crypto.createHash('md5').update(self.body).digest('base64');
            delete self.requestParams.FeedContent;
        }
        //debug(' self.body %o ', self.body);
        self.requestParams.AWSAccessKeyId = this._AmazonMws.getApiField('key');
        self.requestParams.Timestamp = new Date();
        self.requestParams.SignatureVersion = '2';
        self.requestParams.SignatureMethod = 'HmacSHA256';
        var sorted = _.reduce(_.keys(self.requestParams).sort(), function (m, k) {
            m[k] = self.requestParams[k];
            return m;
        }, {});
        var stringToSign = [method, self._AmazonMws.getApiField('host'), path, qs.stringify(sorted)].join('\n');
        // An RFC (cannot remember which one) requires these characters also be changed:
        stringToSign = stringToSign.replace(/'/g, '%27');
        stringToSign = stringToSign.replace(/\*/g, '%2A');
        stringToSign = stringToSign.replace(/\(/g, '%28');
        self.requestParams.Signature = crypto.createHmac('sha256', this._AmazonMws.getApiField('secret')).update(stringToSign, 'utf8').digest('base64');

        self.requestParamsJSON = _.clone(self.requestParams);
        self.requestParams = qs.stringify(self.requestParams);
        /*
         * Use Feed Content without modify it as querystring for the SubmitFeed API
         */
        //self.body = qs.stringify(self.body);

        var headers = {
            'Accept': 'text/xml',
            'Content-Type': 'text/xml',
            'Content-MD5': crypto.createHash('md5').update(self.requestParams).digest('base64')
        };

        if (self.requestParamsJSON.Action === 'SubmitFeed') {
            headers['Content-Type'] = 'x-www-form-urlencoded';
            headers['Content-MD5'] = self.requestParamsJSON.ContentMD5Value;
        }

        // Make a deep copy of the request params, assign to block scoped variable
        var requestParamsCopy = JSON.parse(JSON.stringify(self.requestParams));
        var requestParamsJSONCopy = JSON.parse(JSON.stringify(self.requestParamsJSON));
        // Grab client-user-agent before making the request:
        this._AmazonMws.getClientUserAgent(function () {
            if (options.headers) {
                objectAssign(headers, options.headers);
            }
            makeRequest(requestParamsCopy);
        });

        function makeRequest(requestParamsCopy) {
            var timeout = self._AmazonMws.getApiField('timeout');
            var isInsecureConnection = self._AmazonMws.getApiField('protocol') === 'http';

            var host = self.overrideHost || self._AmazonMws.getApiField('host');
            var params = {
                host: host,
                port: self._AmazonMws.getApiField('port'),
                path: path,
                method: method,
                headers: headers
            };
            params.path = params.path + '?' + requestParamsCopy;

            debug('params %o ', params);
            debug('body %o ', self.body);
            var req = (isInsecureConnection ? http : https).request(params);

            req.setTimeout(timeout, self._timeoutHandler(timeout, req, callback));
            req.on('response', self._responseHandler(requestParamsJSONCopy, req, callback));
            req.on('error', self._errorHandler(req, callback));

            req.on('socket', function (socket) {
                socket.on((isInsecureConnection ? 'connect' : 'secureConnect'), function () {
                    // Send payload; we're safe:
                    //debug('body %o ', self.body);
                    /*
                     * Use Feed Content without modify it as querystring for the SubmitFeed API
                     */
                    req.write(self.body);
                    req.end();
                });
            });
        }
    }

};

module.exports = AmazonMwsResource;
<|endoftext|>


<commit_before>(function ($) {

  $.fn.rating = function () {

    var element;

    // A private function to highlight a star corresponding to a given value
    function _paintValue(ratingInput, value) {
      var selectedStar = $(ratingInput).find('[data-value=' + value + ']');
      selectedStar.removeClass('glyphicon-star-empty').addClass('glyphicon-star');
      selectedStar.prevAll('[data-value]').removeClass('glyphicon-star-empty').addClass('glyphicon-star');
      selectedStar.nextAll('[data-value]').removeClass('glyphicon-star').addClass('glyphicon-star-empty');
    }

    // A private function to remove the selected rating
    function _clearValue(ratingInput) {
      var self = $(ratingInput);
      self.find('[data-value]').removeClass('glyphicon-star').addClass('glyphicon-star-empty');
      self.find('.rating-clear').hide();
      self.find('input').val('').trigger('change');
    }

    // Iterate and transform all selected inputs
    for (element = this.length - 1; element >= 0; element--) {

      var el, i, ratingInputs,
        originalInput = $(this[element]),
        max = originalInput.data('max') || 5,
        min = originalInput.data('min') || 0,
        clearable = originalInput.data('clearable') || null,
        stars = '';

      // HTML element construction
      for (i = min; i <= max; i++) {
        // Create <max> empty stars
        stars += [''].join('');
      }
      // Add a clear link if clearable option is set
      if (clearable) {
        stars += [
          ' ',
          ' ',
          clearable,
          ''].join('');
      }

      el = [
        // Rating widget is wrapped inside a div
        '
',
        stars,
        // Value will be hold in a hidden input with same name and id than original input so the form will still work
        '<input type="hidden" name="',
        originalInput.attr('name'),
        '" value="',
        originalInput.val(),
        '" id="',
        originalInput.attr('id'),
        '" data-min="',
        min,
        '" data-max="',
        max,
        '" />',
        '
'].join('');

      // Replace original inputs HTML with the new one
      originalInput.replaceWith(el);

    }

    // Give live to the newly generated widgets
    $('.rating-input')
      // Highlight stars on hovering
      .on('mouseenter', '[data-value]', function () {
        var self = $(this);
        _paintValue(self.closest('.rating-input'), self.data('value'));
      })
      // View current value while mouse is out
      .on('mouseleave', '[data-value]', function () {
        var self = $(this);
        var val = self.siblings('input').val();
		var min = self.siblings('input').attr('data-min');
        if (val >= min && val <= max) {
          _paintValue(self.closest('.rating-input'), val);
        } else {
          _clearValue(self.closest('.rating-input'));
        }
      })
      // Set the selected value to the hidden field
      .on('click', '[data-value]', function (e) {
        var self = $(this);
        var val = self.data('value');
        self.siblings('input').val(val).trigger('change');
        self.siblings('.rating-clear').show();
        e.preventDefault();
        false
      })
      // Remove value on clear
      .on('click', '.rating-clear', function (e) {
        _clearValue($(this).closest('.rating-input'));
        e.preventDefault();
        false
      })
      // Initialize view with default value
      .each(function () {
        var val = $(this).find('input').val();
        if (val) {
          _paintValue(this, val);
          $(this).find('.rating-clear').show();
        }
      });

  };

  // Auto apply conversion of number fields with class 'rating' into rating-fields
  $(function () {
    if ($('input.rating[type=number]').length > 0) {
      $('input.rating[type=number]').rating();
    }
  });

}(jQuery));
<commit_msg>Space indentation instead of tabs<commit_after>(function ($) {

  $.fn.rating = function () {

    var element;

    // A private function to highlight a star corresponding to a given value
    function _paintValue(ratingInput, value) {
      var selectedStar = $(ratingInput).find('[data-value=' + value + ']');
      selectedStar.removeClass('glyphicon-star-empty').addClass('glyphicon-star');
      selectedStar.prevAll('[data-value]').removeClass('glyphicon-star-empty').addClass('glyphicon-star');
      selectedStar.nextAll('[data-value]').removeClass('glyphicon-star').addClass('glyphicon-star-empty');
    }

    // A private function to remove the selected rating
    function _clearValue(ratingInput) {
      var self = $(ratingInput);
      self.find('[data-value]').removeClass('glyphicon-star').addClass('glyphicon-star-empty');
      self.find('.rating-clear').hide();
      self.find('input').val('').trigger('change');
    }

    // Iterate and transform all selected inputs
    for (element = this.length - 1; element >= 0; element--) {

      var el, i, ratingInputs,
        originalInput = $(this[element]),
        max = originalInput.data('max') || 5,
        min = originalInput.data('min') || 0,
        clearable = originalInput.data('clearable') || null,
        stars = '';

      // HTML element construction
      for (i = min; i <= max; i++) {
        // Create <max> empty stars
        stars += [''].join('');
      }
      // Add a clear link if clearable option is set
      if (clearable) {
        stars += [
          ' ',
          ' ',
          clearable,
          ''].join('');
      }

      el = [
        // Rating widget is wrapped inside a div
        '
',
        stars,
        // Value will be hold in a hidden input with same name and id than original input so the form will still work
        '<input type="hidden" name="',
        originalInput.attr('name'),
        '" value="',
        originalInput.val(),
        '" id="',
        originalInput.attr('id'),
        '" data-min="',
        min,
        '" data-max="',
        max,
        '" />',
        '
'].join('');

      // Replace original inputs HTML with the new one
      originalInput.replaceWith(el);

    }

    // Give live to the newly generated widgets
    $('.rating-input')
      // Highlight stars on hovering
      .on('mouseenter', '[data-value]', function () {
        var self = $(this);
        _paintValue(self.closest('.rating-input'), self.data('value'));
      })
      // View current value while mouse is out
      .on('mouseleave', '[data-value]', function () {
        var self = $(this);
        var val = self.siblings('input').val();
        var min = self.siblings('input').attr('data-min');
        if (val >= min && val <= max) {
          _paintValue(self.closest('.rating-input'), val);
        } else {
          _clearValue(self.closest('.rating-input'));
        }
      })
      // Set the selected value to the hidden field
      .on('click', '[data-value]', function (e) {
        var self = $(this);
        var val = self.data('value');
        self.siblings('input').val(val).trigger('change');
        self.siblings('.rating-clear').show();
        e.preventDefault();
        false
      })
      // Remove value on clear
      .on('click', '.rating-clear', function (e) {
        _clearValue($(this).closest('.rating-input'));
        e.preventDefault();
        false
      })
      // Initialize view with default value
      .each(function () {
        var val = $(this).find('input').val();
        if (val) {
          _paintValue(this, val);
          $(this).find('.rating-clear').show();
        }
      });

  };

  // Auto apply conversion of number fields with class 'rating' into rating-fields
  $(function () {
    if ($('input.rating[type=number]').length > 0) {
      $('input.rating[type=number]').rating();
    }
  });

}(jQuery));
<|endoftext|>


<commit_before>/* global app:true */

var socket;
var currenttime;
var username='noname';

var width = 600,
	height = 1200,
	cellWidth = 80,
	cellHeight = 76, // cell size
	gapWidth = 60;
	gapHeight = 6;

var hour = d3.time.format("%I"),
	minute = d3.time.format("%M"),
	month = d3.time.format("%b"),
	weekday = d3.time.format("%a"),
	date = d3.time.format("%d"),
	ampm = d3.time.format("%p"),
	format = d3.time.format("%b/%d %H:%M%p");

(function() {
  'use strict';

	var myClock;

	function myTimer(){
		socket.emit('server_clock');
	}

  var blockdata = [];

  var callBlocks = function(ticket){
	// +- 1 hour blocks range
	var beginT = d3.time.hour.floor(ticket);
	beginT = d3.time.hour.offset(beginT, -1);
	var endT = d3.time.hour.offset(beginT, 3);

	socket.emit('timeline', { type: 'callblocks', user:username, begintime: beginT, endtime: endT});
  }

  var draw = function(blockdata){
    d3.select("svg")
       .remove();
	var tip = d3.tip()
		.attr('class', 'd3-tip')
		.direction('e')
		.offset([0,10])
		.html(function(d) {
			return "time: "+d.time;
		});

	var color = d3.scale.quantize()
    	.domain([-.05, .05])
    	.range(d3.range(11).map(function(d) { return "q" + d + "-11"; }));

	var svg = d3.select("#d3Area").append("svg")
		.attr("width", width)
		.attr("height", height)
		.attr("class", "RdYlGn")
	.append("g")
		.attr("transform", "translate(24, 24)");

	svg.call(tip);

	var column = svg.selectAll(".column")
		.data(blockdata)
	.enter().append("g")
		.attr("class", "column")
		.attr("transform", function (d,i)
		{ return "translate("+ (i-i%12)/12 * (cellWidth+gapWidth)+ ","+i%12 * (cellHeight+gapHeight) + ")"; })
		.on('mouseover', tip.show)
		.on('mouseout', tip.hide);

	column.append("rect")
		.attr("width", cellWidth)
		.attr("height", cellHeight);

	column.append("text")
		.attr("class", "block-name")
		.attr("x",cellWidth/2)
		.attr("y",cellHeight/2)
		.attr("dy", ".3em")
		.style("text-anchor", "middle")
		.text(function(d) {
			var h = d.time.getHours();
			var ampm = (h<12 ? "AM":"PM");
			//h=("0" + h%12).slice(-2);
			h=(h%12);
			if(h==0){h="12";}
			var m = d.time.getMinutes();
			m=("0" + m).slice(-2);
			return h+":"+m+" "+ampm;
		})
		.on('mouseover', tip.show)
		.on('mouseout', tip.hide);
  }

  socket = io.connect('http://171.65.102.132:3006');

  socket.on('postblocks', function(data){
  	blockdata = [];
	for (var i=0;i<=data.length/4;i++){
		var block = new Object();
		block.id = i;

		var d = new Date(0);
		d.setTime(data[i*4]);
		block.time = d;

		block.lock = data[i*4+1];
		block.userid = data[i*4+2];
		block.expid = data[i*4+3];
		blockdata.push(block);
	}
	blockdata.length = blockdata.length-2;
	console.dir(blockdata);
	draw(blockdata);
  });
  socket.on('server_clock', function(data){
  	console.log(data);
  });

  socket.on('message', function(msg){
	console.log(msg);
  });

  socket.on('connect', function() {
	console.log("Connected!");
	currenttime = new Date();
	callBlocks(currenttime);
	myClock=setInterval(function(){myTimer()},500);
  });

  socket.on('disconnect', function() {
	console.log('disconnected');
	chat.html("Disconnected!");
  });

  app = app || {};

  app.Blocks = Backbone.Model.extend({
    url: '/account/timeline/',
    defaults: {
      username: '',
      timestamp: ''
    }
  });

  app.BlocksView = Backbone.View.extend({
    el: '#blocks_nav',
    template: _.template( $('#tmpl-blocks_nav').html() ),
    events: {
      'click .btn-prev': 'reqPrev',
      'click .btn-now': 'reqNow',
      'click .btn-next': 'reqNext'
    },
    initialize: function() {
      this.model = new app.Blocks();
      this.listenTo(this.model, 'sync', this.render);
      this.render();
    },
    render: function() {
      this.$el.html(this.template( this.model.attributes));
    },
    reqPrev: function() {
      currenttime.setHours(currenttime.getHours() - 1);
      callBlocks(currenttime);
    },
    reqNow: function() {
      currenttime = new Date();
      callBlocks(currenttime);
    },
    reqNext: function() {
      currenttime.setHours(currenttime.getHours() + 1);
      callBlocks(currenttime);
    }
  });

  $(document).ready(function() {
    app.blocksView = new app.BlocksView();
  });

}());
<commit_msg>server clock<commit_after>/* global app:true */

var socket;
var currenttime;
var username='noname';

var width = 600,
	height = 1200,
	cellWidth = 80,
	cellHeight = 76, // cell size
	gapWidth = 60;
	gapHeight = 6;

var hour = d3.time.format("%I"),
	minute = d3.time.format("%M"),
	month = d3.time.format("%b"),
	weekday = d3.time.format("%a"),
	date = d3.time.format("%d"),
	ampm = d3.time.format("%p"),
	format = d3.time.format("%b/%d %H:%M%p");

(function() {
  'use strict';

	var myClock;

	function myTimer(){
		socket.emit('lookclock');
	}

  var blockdata = [];

  var callBlocks = function(ticket){
	// +- 1 hour blocks range
	var beginT = d3.time.hour.floor(ticket);
	beginT = d3.time.hour.offset(beginT, -1);
	var endT = d3.time.hour.offset(beginT, 3);

	socket.emit('timeline', { type: 'callblocks', user:username, begintime: beginT, endtime: endT});
  }

  var draw = function(blockdata){
    d3.select("svg")
       .remove();
	var tip = d3.tip()
		.attr('class', 'd3-tip')
		.direction('e')
		.offset([0,10])
		.html(function(d) {
			return "time: "+d.time;
		});

	var color = d3.scale.quantize()
    	.domain([-.05, .05])
    	.range(d3.range(11).map(function(d) { return "q" + d + "-11"; }));

	var svg = d3.select("#d3Area").append("svg")
		.attr("width", width)
		.attr("height", height)
		.attr("class", "RdYlGn")
	.append("g")
		.attr("transform", "translate(24, 24)");

	svg.call(tip);

	var column = svg.selectAll(".column")
		.data(blockdata)
	.enter().append("g")
		.attr("class", "column")
		.attr("transform", function (d,i)
		{ return "translate("+ (i-i%12)/12 * (cellWidth+gapWidth)+ ","+i%12 * (cellHeight+gapHeight) + ")"; })
		.on('mouseover', tip.show)
		.on('mouseout', tip.hide);

	column.append("rect")
		.attr("width", cellWidth)
		.attr("height", cellHeight);

	column.append("text")
		.attr("class", "block-name")
		.attr("x",cellWidth/2)
		.attr("y",cellHeight/2)
		.attr("dy", ".3em")
		.style("text-anchor", "middle")
		.text(function(d) {
			var h = d.time.getHours();
			var ampm = (h<12 ? "AM":"PM");
			//h=("0" + h%12).slice(-2);
			h=(h%12);
			if(h==0){h="12";}
			var m = d.time.getMinutes();
			m=("0" + m).slice(-2);
			return h+":"+m+" "+ampm;
		})
		.on('mouseover', tip.show)
		.on('mouseout', tip.hide);
  }

  socket = io.connect('http://171.65.102.132:3006');

  socket.on('postblocks', function(data){
  	blockdata = [];
	for (var i=0;i<=data.length/4;i++){
		var block = new Object();
		block.id = i;

		var d = new Date(0);
		d.setTime(data[i*4]);
		block.time = d;

		block.lock = data[i*4+1];
		block.userid = data[i*4+2];
		block.expid = data[i*4+3];
		blockdata.push(block);
	}
	blockdata.length = blockdata.length-2;
	console.dir(blockdata);
	draw(blockdata);
  });

  socket.on('server_clock', function(data){
  	console.log(data);
  });

  socket.on('message', function(msg){
	console.log(msg);
  });

  socket.on('connect', function() {
	console.log("Connected!");
	currenttime = new Date();
	callBlocks(currenttime);
	myClock=setInterval(function(){myTimer()},500);
  });

  socket.on('disconnect', function() {
	console.log('disconnected');
	chat.html("Disconnected!");
  });

  app = app || {};

  app.Blocks = Backbone.Model.extend({
    url: '/account/timeline/',
    defaults: {
      username: '',
      timestamp: ''
    }
  });

  app.BlocksView = Backbone.View.extend({
    el: '#blocks_nav',
    template: _.template( $('#tmpl-blocks_nav').html() ),
    events: {
      'click .btn-prev': 'reqPrev',
      'click .btn-now': 'reqNow',
      'click .btn-next': 'reqNext'
    },
    initialize: function() {
      this.model = new app.Blocks();
      this.listenTo(this.model, 'sync', this.render);
      this.render();
    },
    render: function() {
      this.$el.html(this.template( this.model.attributes));
    },
    reqPrev: function() {
      currenttime.setHours(currenttime.getHours() - 1);
      callBlocks(currenttime);
    },
    reqNow: function() {
      currenttime = new Date();
      callBlocks(currenttime);
    },
    reqNext: function() {
      currenttime.setHours(currenttime.getHours() + 1);
      callBlocks(currenttime);
    }
  });

  $(document).ready(function() {
    app.blocksView = new app.BlocksView();
  });

}());
<|endoftext|>


<commit_before>/* eslint-disable */
$.fn.drags = function(opt) {

	opt = $.extend({handle:"",cursor:"move"}, opt);

	if(opt.handle === "") {
		var $el = this;
	} else {
		var $el = this.find(opt.handle);
	}

	return $el.css('cursor', opt.cursor).on("mousedown", function(e) {
		if(opt.handle === "") {
			var $drag = $(this).addClass('draggable');
		} else {
			var $drag = $(this).addClass('active-handle').addClass('draggable');
		}
		var z_idx = $drag.css('z-index'),
			drg_h = $drag.outerHeight(),
			drg_w = $drag.outerWidth(),
			pos_y = $drag.offset().top + drg_h - e.pageY,
			pos_x = $drag.offset().left + drg_w - e.pageX;
		$drag.css('z-index', 9999).on("mousemove", function(e) {
			$('.draggable').offset({
				top:e.pageY + pos_y - drg_h,
				left:e.pageX + pos_x - drg_w
			}).on("mouseup", function() {
				$(this).removeClass('draggable').css('z-index', z_idx);
			});
		});
		e.preventDefault(); // disable selection
	}).on("mouseup", function() {
		if(opt.handle === "") {
			$(this).removeClass('draggable');
		} else {
			$(this).removeClass('active-handle').removeClass('draggable');
		}
	});

}

<commit_msg>Do not bring the summary panel on top<commit_after>/* eslint-disable */
$.fn.drags = function(opt) {

	opt = $.extend({handle:"",cursor:"move"}, opt);

	if(opt.handle === "") {
		var $el = this;
	} else {
		var $el = this.find(opt.handle);
	}

	return $el.css('cursor', opt.cursor).on("mousedown", function(e) {
		if(opt.handle === "") {
			var $drag = $(this).addClass('draggable');
		} else {
			var $drag = $(this).addClass('active-handle').addClass('draggable');
		}
		var drg_h = $drag.outerHeight(),
			drg_w = $drag.outerWidth(),
			pos_y = $drag.offset().top + drg_h - e.pageY,
			pos_x = $drag.offset().left + drg_w - e.pageX;
		$drag.on("mousemove", function(e) {
			$('.draggable').offset({
				top:e.pageY + pos_y - drg_h,
				left:e.pageX + pos_x - drg_w
			}).on("mouseup", function() {
				$(this).removeClass('draggable');
			});
		});
		e.preventDefault(); // disable selection
	}).on("mouseup", function() {
		if(opt.handle === "") {
			$(this).removeClass('draggable');
		} else {
			$(this).removeClass('active-handle').removeClass('draggable');
		}
	});

}

<|endoftext|>


<commit_before>/*
  * auth
*/
const jwt = require('jsonwebtoken')
const passport = require('passport')
const jwt_decode = require('jwt-decode')

/*
  * email
*/
const nodemailer = require('nodemailer')
const smtpTransport = require('nodemailer-smtp-transport');
// const ses = require('nodemailer-ses-transport')
/*
  * Models
*/
const models = require ('../models')
const Users = models.Users

const dotenv = require('dotenv')
dotenv.load()

/*
  * testing register enw user without send email
*/
let testingSignUp = (req, res, next) => {
  Users.register({
    userId: req.body.userId,
    email: req.body.email,
    // photo_URL: req.body.photo_URL,
    verify: false,
    name: req.body.name,
    isSuper: 'LOL'
  },req.body.password, (err, new_user) => {
    if(err){
      console.log('err', err);
      res.status(400).json(err)
    }else {
      res.json(new_user)
    }
  })
}

/*
  * end point : /api/auth/signup
  * method : POST
*/
let signUpUser = (req, res, next) => {
  if(req.body.password.length >= 8){
      //register users
      Users
        .register({
            userId: req.body.userId,
            email: req.body.email,
            name: req.body.name,
            verify: false,
            isSuper: 'user',
            status: 'baby'
          }, req.body.password, (err, new_user) => {
            if(err){
              console.log(err);
              res.status(400).json(err)
            }else {
              // res.json(new_user)
              var token = jwt.sign({
                            sub: new_user.id,
                            name: req.body.name,
                            email: req.body.email,
                            // photo_URL: req.body.photo_URL,
                            verify: false,
                            isSuper: 'super'
                        }, process.env.SECRET_TOKEN, { expiresIn: 60*60 }) // expire in 1 hour

              // console.log(process.env.SENDGRID_API_KEY);
              var sg = require('sendgrid')(process.env.SENDGRID_API_KEY);
              var request = sg.emptyRequest({
                method: 'POST',
                path: '/v3/mail/send',
                body: {
                  personalizations: [
                    {
                      to: [
                        {
                          email: req.body.email,
                        },
                      ],
                      subject: 'Hello '+req.body.name+' Welcome to partneran.net, please verify your account',
                    },
                  ],
                  from: {
                    email: 'no-reply@partneran.net',
                  },
                  content: [
                    {
                      type: 'text/html',
                      value: `Hello ${req.body.name}, Thankyou for register in partneran.net

                      Click this link below to verify:
 Verify Your Account`,
                    },
                  ],
                },
              });

            sg.API(request)
              .then(response => {
                // console.log(response.statusCode);
                // console.log(response.body);
                // console.log(response.headers);
                passport.authenticate('local', {}, (err, user, info) => {
                 if(err){
                   console.log(`error`);
                   console.log(err);
                   return res.status(400).json(err)
                 }else{
                   if(user != false){
                     // console.log(user);
                     return res.status(200).json({
                       token: jwt.sign({
                         sub: user.id,
                         name: user.name,
                         email: user.email,
                         photo_URL: user.photo_URL,
                         short_bio: user.short_bio,
                         verify: user.verify,
                         isSuper: user.isSuper,
                         status: user.status
                       }, process.env.SECRET_TOKEN, { expiresIn: 60*60 })
                     })
                   }else{
                     return res.status(400).json(info)
                   }
                 }
               })(req, res, next)
              })
              .catch(error => {
                //error is an instance of SendGridError
                //The full response is attached to error.response
                // console.log(error.response.statusCode);
                res.json(error)
              });
            }
          })
  }else{
    res.json({
      message: "Password must be 8 characters or more"
    })
  }

}

/*
  * end point : /api/auth/login
  * method : POST
*/
let loginUser = (req, res, next) => {
  passport.authenticate('local', {}, (err, user, info) => {
    if(err){
      console.log(`error`);
      console.log(err);
      return res.status(400).json(err)
    }else{
      if(user != false){
        // console.log(user);
        return res.status(200).json({
          token: jwt.sign({
            sub: user.id,
            email: user.email,
            name: user.name,
            photo_URL: user.photo_URL,
            short_bio: user.short_bio,
            verify: user.verify,
            isSuper: user.isSuper,
            status: user.status
          }, process.env.SECRET_TOKEN, { expiresIn: 60*60 })
        })
      }else{
        console.log(`info`);
        return res.status(400).json(info)
      }
    }
  })(req, res, next)
}

/*
  * end point : /api/auth/verification/:token
  * method : getOneUser
*/
let verificationNewUser = (req, res) => {
  var decoded = jwt_decode(req.params.token)
  // console.log(decoded);

  Users
    .findOne({
      where: {
        email: decoded.email
      }
    })
    .then((one_data, err) => {
      if(err){
        console.log("err", err);
        res.json(err)
      }else{
        // console.log(one_data);
        console.log(`verified`);
        one_data.verify = true
        one_data.save()

        return res.status(200).json({
          token: jwt.sign({
            sub: one_data.id,
            email: one_data.email,
            name: one_data.name,
            photo_URL: one_data.photo_URL,
            short_bio: one_data.short_bio,
            verify: one_data.verify,
            isSuper: one_data.isSuper,
            status: one_data.status
          }, process.env.SECRET_TOKEN, { expiresIn: 60*60 })
        })
      }
    })
}

/*
  * end point : /api/auth/verification/forgot/:token
  * method : GET
*/
let verificationForgotPassword = (req, res) => {
  var decoded = jwt_decode(req.params.token)
  // console.log(decoded);
  Users
    .findOne({
      where: {
        id: decoded.sub
      }
    })
    .then((one_data, err) => {
      if(err){
        console.log("err", err);
        res.json(err)
      }else{
        // console.log(one_data);
        res.json(one_data)
      }
    })
}

module.exports = {
  loginUser,
  signUpUser,
  verificationNewUser,
  verificationForgotPassword,
  testingSignUp
}
<commit_msg>remove console log in auth controller<commit_after>/*
  * auth
*/
const jwt = require('jsonwebtoken')
const passport = require('passport')
const jwt_decode = require('jwt-decode')

/*
  * email
*/
const nodemailer = require('nodemailer')
const smtpTransport = require('nodemailer-smtp-transport');
// const ses = require('nodemailer-ses-transport')
/*
  * Models
*/
const models = require ('../models')
const Users = models.Users

const dotenv = require('dotenv')
dotenv.load()

/*
  * testing register enw user without send email
*/
let testingSignUp = (req, res, next) => {
  Users.register({
    userId: req.body.userId,
    email: req.body.email,
    // photo_URL: req.body.photo_URL,
    verify: false,
    name: req.body.name,
    isSuper: 'LOL'
  },req.body.password, (err, new_user) => {
    if(err){
      console.log('err', err);
      res.status(400).json(err)
    }else {
      res.json(new_user)
    }
  })
}

/*
  * end point : /api/auth/signup
  * method : POST
*/
let signUpUser = (req, res, next) => {
  if(req.body.password.length >= 8){
      //register users
      Users
        .register({
            userId: req.body.userId,
            email: req.body.email,
            name: req.body.name,
            verify: false,
            isSuper: 'user',
            status: 'baby'
          }, req.body.password, (err, new_user) => {
            if(err){
              console.log(err);
              res.status(400).json(err)
            }else {
              // res.json(new_user)
              var token = jwt.sign({
                            sub: new_user.id,
                            name: req.body.name,
                            email: req.body.email,
                            // photo_URL: req.body.photo_URL,
                            verify: false,
                            isSuper: 'super'
                        }, process.env.SECRET_TOKEN, { expiresIn: 60*60 }) // expire in 1 hour

              var sg = require('sendgrid')(process.env.SENDGRID_API_KEY);
              var request = sg.emptyRequest({
                method: 'POST',
                path: '/v3/mail/send',
                body: {
                  personalizations: [
                    {
                      to: [
                        {
                          email: req.body.email,
                        },
                      ],
                      subject: 'Hello '+req.body.name+' Welcome to partneran.net, please verify your account',
                    },
                  ],
                  from: {
                    email: 'no-reply@partneran.net',
                  },
                  content: [
                    {
                      type: 'text/html',
                      value: `Hello ${req.body.name}, Thankyou for register in partneran.net

                      Click this link below to verify:
 Verify Your Account`,
                    },
                  ],
                },
              });

            sg.API(request)
              .then(response => {
                // console.log(response.statusCode);
                // console.log(response.body);
                // console.log(response.headers);
                passport.authenticate('local', {}, (err, user, info) => {
                 if(err){
                   console.log(`error`);
                   console.log(err);
                   return res.status(400).json(err)
                 }else{
                   if(user != false){
                     // console.log(user);
                     return res.status(200).json({
                       token: jwt.sign({
                         sub: user.id,
                         name: user.name,
                         email: user.email,
                         photo_URL: user.photo_URL,
                         short_bio: user.short_bio,
                         verify: user.verify,
                         isSuper: user.isSuper,
                         status: user.status
                       }, process.env.SECRET_TOKEN, { expiresIn: 60*60 })
                     })
                   }else{
                     return res.status(400).json(info)
                   }
                 }
               })(req, res, next)
              })
              .catch(error => {
                //error is an instance of SendGridError
                //The full response is attached to error.response
                res.json(error)
              });
            }
          })
  }else{
    res.json({
      message: "Password must be 8 characters or more"
    })
  }

}

/*
  * end point : /api/auth/login
  * method : POST
*/
let loginUser = (req, res, next) => {
  passport.authenticate('local', {}, (err, user, info) => {
    if(err){
      console.log(`error`);
      console.log(err);
      return res.status(400).json(err)
    }else{
      if(user != false){
        return res.status(200).json({
          token: jwt.sign({
            sub: user.id,
            email: user.email,
            name: user.name,
            photo_URL: user.photo_URL,
            short_bio: user.short_bio,
            verify: user.verify,
            isSuper: user.isSuper,
            status: user.status
          }, process.env.SECRET_TOKEN, { expiresIn: 60*60 })
        })
      }else{
        console.log(`info`);
        return res.status(400).json(info)
      }
    }
  })(req, res, next)
}

/*
  * end point : /api/auth/verification/:token
  * method : getOneUser
*/
let verificationNewUser = (req, res) => {
  var decoded = jwt_decode(req.params.token)
  // console.log(decoded);

  Users
    .findOne({
      where: {
        email: decoded.email
      }
    })
    .then((one_data, err) => {
      if(err){
        console.log("err", err);
        res.json(err)
      }else{
        one_data.verify = true
        one_data.save()

        return res.status(200).json({
          token: jwt.sign({
            sub: one_data.id,
            email: one_data.email,
            name: one_data.name,
            photo_URL: one_data.photo_URL,
            short_bio: one_data.short_bio,
            verify: one_data.verify,
            isSuper: one_data.isSuper,
            status: one_data.status
          }, process.env.SECRET_TOKEN, { expiresIn: 60*60 })
        })
      }
    })
}

/*
  * end point : /api/auth/verification/forgot/:token
  * method : GET
*/
let verificationForgotPassword = (req, res) => {
  var decoded = jwt_decode(req.params.token)
  Users
    .findOne({
      where: {
        id: decoded.sub
      }
    })
    .then((one_data, err) => {
      if(err){
        console.log("err", err);
        res.json(err)
      }else{f
        res.json(one_data)
      }
    })
}

module.exports = {
  loginUser,
  signUpUser,
  verificationNewUser,
  verificationForgotPassword,
  testingSignUp
}
<|endoftext|>