<commit_before>var winston = require('winston');
var sleep = require('sleep');

module.exports = function (skill, info, bot, message) {
    winston.log('info', 'Running code for \'about\'.');
    bot.startConversation(message, function (err, convo) {
        convo.say('Let me tell you a bit about myself.');
        sleep.sleep(2);
        convo.say('Actually, I can\'t be bothered to do that right now, ask me later.');
        convo.next();
    });
};
<commit_msg>add links to github and messages to samson<commit_after>var winston = require('winston');
var sleep = require('sleep');

module.exports = function (skill, info, bot, message) {
    var users = [];
    winston.log('info', 'Running code for \'about\'.');
    bot.startConversation(message, function (err, convo) {
        convo.say('Let me tell you a bit about myself.');
        sleep.sleep(2);
        convo.say('Actually, I can\'t be bothered to do that right now, ask me later.');
        convo.say('You can see the code and stuff though at https://github.com/MarsCapone/srbot.');
        bot.api.users.list({}, function (err, response) {
            if (response.hasOwnProperty('members') && response.ok) {
                response.members.forEach(function (member) {
                    users.push({name: member.name, id: member.id});
                });
                var me = users.filter(function (x) {
                    return /(samson|sdanziger|blueteeth)/.exec(x.name);
                })[0];
                convo.say('I guess if problems come up, or it turns out I\'m not online and you think I should be, you should message <@' + me.id + '|' + me.name + '>.');
                convo.next();
            }
        });
        convo.next();
    });
};
<|endoftext|>


<commit_before>var welderApiHost="localhost";
var welderApiPort=4000;
var welderApiScheme="http";
var welderApiRelative=false;
<commit_msg>Updated API port<commit_after>var welderApiHost="localhost";
var welderApiPort="/run/weldr/api.socket";
var welderApiScheme="http";
var welderApiRelative=false;
<|endoftext|>


<commit_before>jQuery.fn.extend({
    disable: function(state) {
        return this.each(function() {
            this.disabled = state;
        });
    }
});
var content = "<form id = 'form' method = 'post' action = '" + baseURL + "/scaffold/guipost/'><input type = 'hidden' name = '_token' value = '" + token + "'>\

\

\

\
            <input id = 'TableName' name='TableName' required='' aria-required='true' type='text'>\
            TableName	\

\

\

\
        <button type = 'submit' class = 'val btn green col s12'>doneDone</button>
\
        </form>";
var i = 0;
var j = 0;

function option(i) {
    var options = '
\
    <select id = "opt' + i + '" name = "opt' + i + '" data-id = "' + i + '">\
        <option value = "String">String</option>\
        <option value = "longText">longText</option>\
        <option value = "Date">Date</option>\
        <option value = "boolean">boolean</option>\
        <option value = "binary">binary</option>\
        <option value = "float">float</option>\
        <option value = "integer">integer</option>\
        <option value = "bigInteger">bigInteger</option>\
        <option value = "json">json</option>\
     </select>\
    Select Type\

'
    return options;
}

function relation(i) {
    var relations = '
\
    <select id = "tbl' + i + '" name = "tbl' + i + '" class = "parent" data-id = "' + i + '">\
        ';
    jQuery.each(TableData, function(index, item) {
        relations += '<option value = "' + index + '">' + index + '</option>'
    });
    relations += '\
     </select>\
    Select Model\

';
    return relations;
}
var actions = "
\

Rows
\

\
               addnew\
               deleteremove\
               layersready\

";
$(document).on('click', '.createNewTable', function() {
    $('.new').html(content);
    $('.actions').html(actions);
    $('#form').validate();
    $('.val').hide();
    $('.readyy').hide();
})
$(document).on('click', '.newattr', function() {
    $('select').material_select();
    $('.t tr:last').after("
" + option(i) + "
<input id = 'atr" + i + "' name = 'atr" + i + "' type='text'>Attribute

\
    ")
    i++;
    $('select').material_select();
    $('.readyy').show();
})
$(document).on('click', '.readyy', function() {
    $('.val').show();
    $('.actionRow').html('')
    $('.actionRow').html("arrow_backback\
        device_hubOne To Many
");
})
$(document).on('click', '.relations', function() {
    $('.t tr:last').after("
" + relation(j) + "
<select class = 'class' id = 'on" + j + "' name = 'on" + j + "'><option></option>Select Attributes</select>

");
    j++;
    $('select').material_select();
})
$(document).on('click', '.rmattr', function() {
    $('.t tr:last').remove();
})
$(document).on('click', '.editt', function() {
    $('.actions').html(actions);
    $('.val').hide();
})
$(document).ready(function() {
    $('.valide').hide();
    $('.newattr').hide();
    $('.rmattr').hide();
    $('.rollback').hide();
    $('select').material_select();
});
$(document).on('dblclick', '.msg', function() {
    $('.msg').remove();
});
$.validator.setDefaults({
    errorClass: 'invalid',
    validClass: "valid",
    errorPlacement: function(error, element) {
        $(element).closest("#form").find("label[for='" + element.attr("id") + "']").attr('data-error', error.text());
    }
});
$("#form").validate({
    rules: {
        dateField: {
            date: true
        }
    }
});
$(document).on("change", ".parent", function() {
    var value = $(this).val()
    var id = $(this).data('id')
    $.ajax({
        async: true,
        type: 'get',
        url: baseURL + '/scaffold/getAttributes/' + value + '/',
        success: function(response) {
            $("#on" + id).html(Attributes(response));
            $("#on" + id).material_select();
        }
    })
})
$(document).on("click", ".index", function() {
    $.ajax({
        async: true,
        type: 'get',
        url: baseURL + $(this).data('link'),
        success: function(response) {
            window.location.replace(response)
            if (response.error) {
                // handle the error
                throw response.error.msg;
            }
            window.location.replace(response)
        }
    })
})
$(document).on("click", ".deleteIndex", function() {
    $.ajax({
        async: true,
        type: 'get',
        url: baseURL + $(this).data('link'),
        success: function(response) {

            if (response.error) {
                // handle the error
                throw response.error.msg;
            }
            window.location.replace(response)
        }
    })
})

function Attributes(TableData) {
    var relations = '';
    jQuery.each(TableData, function(index, item) {
        relations += '<option value = "' + item + '">' + item + '</option>'
    });
    return relations;
}<commit_msg>redirects to the new location<commit_after>jQuery.fn.extend({
    disable: function(state) {
        return this.each(function() {
            this.disabled = state;
        });
    }
});
var content = "<form id = 'form' method = 'post' action = '" + baseURL + "/scaffold/guipost/'><input type = 'hidden' name = '_token' value = '" + token + "'>\

\

\

\
            <input id = 'TableName' name='TableName' required='' aria-required='true' type='text'>\
            TableName	\

\

\

\
        <button type = 'submit' class = 'val btn green col s12'>doneDone</button>
\
        </form>";
var i = 0;
var j = 0;

function option(i) {
    var options = '
\
    <select id = "opt' + i + '" name = "opt' + i + '" data-id = "' + i + '">\
        <option value = "String">String</option>\
        <option value = "longText">longText</option>\
        <option value = "Date">Date</option>\
        <option value = "boolean">boolean</option>\
        <option value = "binary">binary</option>\
        <option value = "float">float</option>\
        <option value = "integer">integer</option>\
        <option value = "bigInteger">bigInteger</option>\
        <option value = "json">json</option>\
     </select>\
    Select Type\

'
    return options;
}

function relation(i) {
    var relations = '
\
    <select id = "tbl' + i + '" name = "tbl' + i + '" class = "parent" data-id = "' + i + '">\
        ';
    jQuery.each(TableData, function(index, item) {
        relations += '<option value = "' + index + '">' + index + '</option>'
    });
    relations += '\
     </select>\
    Select Model\

';
    return relations;
}
var actions = "
\

Rows
\

\
               addnew\
               deleteremove\
               layersready\

";
$(document).on('click', '.createNewTable', function() {
    $('.new').html(content);
    $('.actions').html(actions);
    $('#form').validate();
    $('.val').hide();
    $('.readyy').hide();
})
$(document).on('click', '.newattr', function() {
    $('select').material_select();
    $('.t tr:last').after("
" + option(i) + "
<input id = 'atr" + i + "' name = 'atr" + i + "' type='text'>Attribute

\
    ")
    i++;
    $('select').material_select();
    $('.readyy').show();
})
$(document).on('click', '.readyy', function() {
    $('.val').show();
    $('.actionRow').html('')
    $('.actionRow').html("arrow_backback\
        device_hubOne To Many
");
})
$(document).on('click', '.relations', function() {
    $('.t tr:last').after("
" + relation(j) + "
<select class = 'class' id = 'on" + j + "' name = 'on" + j + "'><option></option>Select Attributes</select>

");
    j++;
    $('select').material_select();
})
$(document).on('click', '.rmattr', function() {
    $('.t tr:last').remove();
})
$(document).on('click', '.editt', function() {
    $('.actions').html(actions);
    $('.val').hide();
})
$(document).ready(function() {
    $('.valide').hide();
    $('.newattr').hide();
    $('.rmattr').hide();
    $('.rollback').hide();
    $('select').material_select();
});
$(document).on('dblclick', '.msg', function() {
    $('.msg').remove();
});
$.validator.setDefaults({
    errorClass: 'invalid',
    validClass: "valid",
    errorPlacement: function(error, element) {
        $(element).closest("#form").find("label[for='" + element.attr("id") + "']").attr('data-error', error.text());
    }
});
$("#form").validate({
    rules: {
        dateField: {
            date: true
        }
    }
});
$(document).on("change", ".parent", function() {
    var value = $(this).val()
    var id = $(this).data('id')
    $.ajax({
        async: true,
        type: 'get',
        url: baseURL + '/scaffold/getAttributes/' + value + '/',
        success: function(response) {
            $("#on" + id).html(Attributes(response));
            $("#on" + id).material_select();
        }
    })
})
$(document).on("click", ".index", function() {
    $.ajax({
        async: true,
        type: 'get',
        url: baseURL + $(this).data('link'),
        success: function(response) {
            if (response.error) {
                throw response.error.msg;
            }
            window.location = response;
        }
    })
})
$(document).on("click", ".deleteIndex", function() {
    $.ajax({
        async: true,
        type: 'get',
        url: baseURL + $(this).data('link'),
        success: function(response) {
            if (response.error) {
                throw response.error.msg;
            }
            window.location = response;
        }
    })
})

function Attributes(TableData) {
    var relations = '';
    jQuery.each(TableData, function(index, item) {
        relations += '<option value = "' + item + '">' + item + '</option>'
    });
    return relations;
}<|endoftext|>


<commit_before>/*

slack-notify
https://github.com/andrewchilds/slack-notify

*/

var request = require('request');
var _ = require('lodash');

module.exports = function (url) {
  var pub = {};

  pub.request = function (data, done) {
    if (!url) {
      console.log('No Slack URL configured.');
      return false;
    }

    if (!done) {
      done = function(){};
    }

    request.post(url, {
      form: {
        payload: JSON.stringify(data)
      }
    }, function(err, response) {
      if (err) {
        return done(err);
      }
      if (response.body != 'ok') {
        return done(new Error(response.body));
      }

      done();
    });
  };

  pub.send = function (options, done) {
    if (_.isString(options)) {
      options = { text: options };
    }

    // Merge options with defaults
    var defaults = {
      channel: '#general',
      username: 'Robot',
      text: '',
      icon_emoji: ':bell:'
    };
    var data = _.assign(defaults, options);

    // Move the fields into attachments
    if (options.fields) {
      if (!data.attachments) {
        data.attachments = [];
      }

      data.attachments.push({
        fallback: 'Alert details',
        fields: _.map(options.fields, function (value, title) {
          return {
            title: title,
            value: value,
            short: (value + '').length < 25
          };
        })
      });

      delete(data.fields);
    }

    // Remove the default icon_emoji if icon_url was set in options. Otherwise the default emoji will always override the url
    if (options.icon_url && !options.icon_emoji) {
      delete(data.icon_emoji);
    }

    pub.request(data, done);
  };

  pub.extend = function (defaults) {
    return function (options, done) {
      if (_.isString(options)) {
        options = { text: options };
      }

      pub.send(_.extend(defaults, options), done);
    };
  };

  pub.bug = pub.extend({
    channel: '#bugs',
    icon_emoji: ':bomb:',
    username: 'Bug'
  });

  pub.alert = pub.extend({
    channel: '#alerts',
    icon_emoji: ':warning:',
    username: 'Alert'
  });

  pub.note = pub.extend({
    channel: '#alerts',
    icon_emoji: ':bulb:',
    username: 'Note'
  });

  pub.success = pub.extend({
    channel: '#alerts',
    icon_emoji: ':trophy:',
    username: 'Hoorah'
  });

  return pub;
};
<commit_msg>Using strict comparison<commit_after>/*

slack-notify
https://github.com/andrewchilds/slack-notify

*/

var request = require('request');
var _ = require('lodash');

module.exports = function (url) {
  var pub = {};

  pub.request = function (data, done) {
    if (!url) {
      console.log('No Slack URL configured.');
      return false;
    }

    if (!_.isFunction(done)) {
      done = _.noop;
    }

    request.post(url, {
      form: {
        payload: JSON.stringify(data)
      }
    }, function(err, response) {
      if (err) {
        return done(err);
      }
      if (response.body !== 'ok') {
        return done(new Error(response.body));
      }

      done();
    });
  };

  pub.send = function (options, done) {
    if (_.isString(options)) {
      options = { text: options };
    }

    // Merge options with defaults
    var defaults = {
      channel: '#general',
      username: 'Robot',
      text: '',
      icon_emoji: ':bell:'
    };
    var data = _.assign(defaults, options);

    // Move the fields into attachments
    if (options.fields) {
      if (!data.attachments) {
        data.attachments = [];
      }

      data.attachments.push({
        fallback: 'Alert details',
        fields: _.map(options.fields, function (value, title) {
          return {
            title: title,
            value: value,
            short: (value + '').length < 25
          };
        })
      });

      delete(data.fields);
    }

    // Remove the default icon_emoji if icon_url was set in options. Otherwise the default emoji will always override the url
    if (options.icon_url && !options.icon_emoji) {
      delete(data.icon_emoji);
    }

    pub.request(data, done);
  };

  pub.extend = function (defaults) {
    return function (options, done) {
      if (_.isString(options)) {
        options = { text: options };
      }

      pub.send(_.extend(defaults, options), done);
    };
  };

  pub.bug = pub.extend({
    channel: '#bugs',
    icon_emoji: ':bomb:',
    username: 'Bug'
  });

  pub.alert = pub.extend({
    channel: '#alerts',
    icon_emoji: ':warning:',
    username: 'Alert'
  });

  pub.note = pub.extend({
    channel: '#alerts',
    icon_emoji: ':bulb:',
    username: 'Note'
  });

  pub.success = pub.extend({
    channel: '#alerts',
    icon_emoji: ':trophy:',
    username: 'Hoorah'
  });

  return pub;
};
<|endoftext|>


<commit_before>//room: {players: [list of player Objects], turn: player object}
function Game(room) {
	this.room = room;
	this.grid = this.newBoard();
};

var directions = {
	upRight : 0,
	up : 1,
	upLeft : 2,
	downLeft : 3,
	down : 4,
	downRight : 5
}
// Util
Game.prototype.newBoard = function() {
	var grid = new Array(9);
	for (var i = 0; i < 9; i++) {
		grid[i] = new Array(8);
		for (var j = 0; j < 8; j++) {
			if (j == 0 && (i < 2 || i > 6)) {
				grid[i][j] = -2;

			} else if ((j == 1 || j == 5 || j == 6) && (i == 0 || i == 8)) {
				grid[i][j] = -2;

			} else if (j == 7 && !(i == 3 || i == 5)) {
				grid[i][j] = -2;

			} else {
				grid[i][j] = -1;
			}
		}
	}
	return grid;
}

Game.prototype.newGame = function() {
	this.grid = this.newBoard();
	this.grid[3][3] = this.room.players[0];
	this.grid[5][4] = this.room.players[0];
	this.grid[4][2] = this.room.players[1];
	this.grid[4][4] = this.room.players[1];
	this.grid[3][4] = this.room.players[2];
	this.grid[5][3] = this.room.players[2];
}

Game.prototype.spaceInDirection = function(start, direction) {

	var space = {
		i : start.i,
		j : start.j
	};

	if (direction === directions.upRight) {
		if (space.i % 2 === 1) {
			space.j -= 1;
		}
		space.i += 1;
	} else if (direction === directions.up) {
		space.j -= 1;
	} else if (direction === directions.upLeft) {
		if (space.i % 2 === 1) {
			space.j -= 1;
		}
		space.i -= 1;
	} else if (direction === directions.downLeft) {
		if (space.i % 2 === 0) {
			space.j += 1;
		}
		space.i -= 1;
	} else if (direction === directions.down) {
		space.j += 1;
	} else if (direction === directions.downRight) {
		if (space.i % 2 === 0) {
			space.j += 1;
		}
		space.i += 1;
	} else {
		return undefined;
	}

	return space;
}

Game.prototype.directionFrom = function(start, end) {

	var di = end.i - start.i;
	var dj = end.j - start.j;

	if (di === 0) {
		if (start.j < end.j) {
			return directions.down;
		} else if (start.j > end.j) {
			return directions.up;
		}
	} else if (di < 0) {
		// up-left
		if (dj < 0) {
			if (di % 2 === 0) {
				if (dj === di / 2) {
					return directions.upLeft;
				}
			} else {
				if (start.i % 2 === 1) {
					if (dj === (di - 1) / 2) {
						return directions.upLeft;
					}
				} else {
					if (dj === (di + 1) / 2) {
						return directions.upLeft;
					}
				}
			}
		}
		// down-left
        else if (dj > 0) {
			if (di % 2 === 0) {
				if (dj == di / -2) {
					return directions.downLeft;
				}
			} else {
				if (start.i % 2 === 1) {
					if (dj === (di + 1) / -2) {
						return directions.downLeft;
					}
				} else {
					if (dj === (di - 1) / -2) {
						return directions.downLeft;
					}
				}
			}
		}
	} else {
		// up-right
		if (dj < 0) {
			if (di % 2 === 0) {
				if (dj == di / -2) {
					return directions.upRight;
				}
			} else {
				if (start.i % 2 === 1) {
					if (dj === (di + 1) / -2) {
						return directions.upRight;
					}
				} else {
					if (dj === (di - 1) / -2) {
						return directions.upRight;
					}
				}
			}
		}
		// down-right
        else if (dj > 0) {
			if (di % 2 === 0) {
				if (dj == di / 2) {
					return directions.downRight;
				}
			} else {
				if (start.i % 2 === 1) {
					if (dj == (di - 1) / 2) {
						return directions.downRight;
					}
				} else {
					if (dj == (di + 1) / 2) {
						return directions.downRight;
					}
				}
			}
		}
	}

	return undefined;
}

// returns possible move in direction
Game.prototype.generateMoveInDirection = function(start, direction) {

    if (direction >= 6 || direction <= 0) {
        return undefined;
    }

    var space = {
        i : start.i,
        j : start.j
    };
    var nextSpace = {}, nextValue;
	nextSpace = this.spaceInDirection(space, direction);
    while (nextSpace) {

        nextValue = this.grid[nextSpace.i][nextSpace.j];
        nextSpace = this.spaceInDirection(space, direction);
        if (nextValue == this.room.turn || nextValue == -2) {
            nextSpace = undefined;
        } else {
            space = nextSpace;
        }

        if (nextValue == -1) {
            break;
        }
    }
    return space;
}

//returns list of possible moves
Game.prototype.generateMoves = function(start) {

    if (this.room.turn !== this.room.me) {
    	console.log("not your turn");
        return undefined;
    }

    var spaces = {};

    for (var direction in directions) {
        var move = this.generateMoveInDirection(start, direction);
        spaces[[move.i, move.j]] = true;
    }
    return spaces;
}

// returns array of spaces in straight line from start to end, if possible
Game.prototype.spacesFrom = function(start, end) {

    var direction = this.directionFrom(start, end);
    if (!direction) {
        return undefined;
    }

    var space = {
        i : start.i,
        j : start.j
    };
    var spaces = [space];
    var nextSpace = {}, nextValue;

    while (true) {
        nextSpace = spaceInDirection(space, direction);
        nextValue = this.grid[nextSpace.i][nextSpace.j];

        if (nextValue == this.room.turn || nextValue == -2) {
            nextSpace = undefined;
            spaces = undefined;
            break;
        } else {
            spaces.push(nextSpace);
            space = nextSpace;
        }

        if (nextValue == -1) {
            break;
        }
    }
    return spaces;
}

Game.prototype.validateMove = function(start, end) {
	if (this.grid[start.i][start.j] !== this.room.turn) {
		return false;
	}
	if (this.grid[end.i][end.j] !== -1) {
		return false;
	}

    var direction = this.directionFrom(start, end);
    if (!direction) {
        return false;
    }

    var space = generateMoveInDirection(start, direction);
    if (space.i === end.i && space.j === end.j) {
        return true;
    }

    return false;
}

Game.prototype.move = function(start, end) {
	// Make grid changes
    var spaces = spacesFrom(start, end);
    for (var space in spaces) {
        this.grid[space.i][space.j] = this.room.turn;
    }

	//tell room move
	// if game end, tell room
}

//return player score (go through grid and calc, dont keep track)
Game.prototype.getScore = function(player) {
    var score = 0;
    for (var i = 0; i < 9; i++) {
        for (var j = 0; j < 8; j++) {
            if (this.grid[i][j] === player) {
                score++;
            }
        }
    }
    return score;
}

//replace grid instances of playerFrom, to playerTO
Game.prototype.replacePlayer = function(playerFrom, playerTo){
    for (var i = 0; i < 9; i++) {
        for (var j = 0; j < 8; j++) {
            if (this.grid[i][j] === playerFrom) {
                this.grid[i][j] === playerTo;
            }
        }
    }
}

<commit_msg>updated buggy method<commit_after>//room: {players: [list of player Objects], turn: player object}
function Game(room) {
	this.room = room;
	this.grid = this.newBoard();
};

var directions = {
	upRight : 0,
	up : 1,
	upLeft : 2,
	downLeft : 3,
	down : 4,
	downRight : 5
}
// Util
Game.prototype.newBoard = function() {
	var grid = new Array(9);
	for (var i = 0; i < 9; i++) {
		grid[i] = new Array(8);
		for (var j = 0; j < 8; j++) {
			if (j == 0 && (i < 2 || i > 6)) {
				grid[i][j] = -2;

			} else if ((j == 1 || j == 5 || j == 6) && (i == 0 || i == 8)) {
				grid[i][j] = -2;

			} else if (j == 7 && !(i == 3 || i == 5)) {
				grid[i][j] = -2;

			} else {
				grid[i][j] = -1;
			}
		}
	}
	return grid;
}

Game.prototype.newGame = function() {
	this.grid = this.newBoard();
	this.grid[3][3] = this.room.players[0];
	this.grid[5][4] = this.room.players[0];
	this.grid[4][2] = this.room.players[1];
	this.grid[4][4] = this.room.players[1];
	this.grid[3][4] = this.room.players[2];
	this.grid[5][3] = this.room.players[2];
}

Game.prototype.spaceInDirection = function(start, direction) {

	var space = {
		i : start.i,
		j : start.j
	};

	if (direction === directions.upRight) {
		if (space.i % 2 === 1) {
			space.j -= 1;
		}
		space.i += 1;
	} else if (direction === directions.up) {
		space.j -= 1;
	} else if (direction === directions.upLeft) {
		if (space.i % 2 === 1) {
			space.j -= 1;
		}
		space.i -= 1;
	} else if (direction === directions.downLeft) {
		if (space.i % 2 === 0) {
			space.j += 1;
		}
		space.i -= 1;
	} else if (direction === directions.down) {
		space.j += 1;
	} else if (direction === directions.downRight) {
		if (space.i % 2 === 0) {
			space.j += 1;
		}
		space.i += 1;
	} else {
		return undefined;
	}

	return space;
}

Game.prototype.directionFrom = function(start, end) {

	var di = end.i - start.i;
	var dj = end.j - start.j;

	if (di === 0) {
		if (start.j < end.j) {
			return directions.down;
		} else if (start.j > end.j) {
			return directions.up;
		}
	} else if (di < 0) {
		// up-left
		if (dj < 0) {
			if (di % 2 === 0) {
				if (dj === di / 2) {
					return directions.upLeft;
				}
			} else {
				if (start.i % 2 === 1) {
					if (dj === (di - 1) / 2) {
						return directions.upLeft;
					}
				} else {
					if (dj === (di + 1) / 2) {
						return directions.upLeft;
					}
				}
			}
		}
		// down-left
        else if (dj > 0) {
			if (di % 2 === 0) {
				if (dj == di / -2) {
					return directions.downLeft;
				}
			} else {
				if (start.i % 2 === 1) {
					if (dj === (di + 1) / -2) {
						return directions.downLeft;
					}
				} else {
					if (dj === (di - 1) / -2) {
						return directions.downLeft;
					}
				}
			}
		}
	} else {
		// up-right
		if (dj < 0) {
			if (di % 2 === 0) {
				if (dj == di / -2) {
					return directions.upRight;
				}
			} else {
				if (start.i % 2 === 1) {
					if (dj === (di + 1) / -2) {
						return directions.upRight;
					}
				} else {
					if (dj === (di - 1) / -2) {
						return directions.upRight;
					}
				}
			}
		}
		// down-right
        else if (dj > 0) {
			if (di % 2 === 0) {
				if (dj == di / 2) {
					return directions.downRight;
				}
			} else {
				if (start.i % 2 === 1) {
					if (dj == (di - 1) / 2) {
						return directions.downRight;
					}
				} else {
					if (dj == (di + 1) / 2) {
						return directions.downRight;
					}
				}
			}
		}
	}

	return undefined;
}

// returns possible move in direction
Game.prototype.generateMoveInDirection = function(start, direction) {

    if (direction >= 6 || direction <= 0) {
        return undefined;
    }

    var space = {
        i : start.i,
        j : start.j
    };
    var nextSpace = {}, nextValue;
    while (nextSpace) {
        nextSpace = this.spaceInDirection(space, direction);
        if(!nextSpace)
        	break;
        nextValue = this.grid[nextSpace.i][nextSpace.j];

        if (nextValue == this.room.turn || nextValue == -2) {
            nextSpace = undefined;
        } else {
            space = nextSpace;
        }

        if (nextValue == -1) {
            break;
        }
    }
    return space;
}

//returns list of possible moves
Game.prototype.generateMoves = function(start) {

    if (this.room.turn !== this.room.me) {
    	console.log("not your turn");
        return undefined;
    }

    var spaces = {};

    for (var direction in directions) {
        var move = this.generateMoveInDirection(start, direction);
        spaces[[move.i, move.j]] = true;
    }
    return spaces;
}

// returns array of spaces in straight line from start to end, if possible
Game.prototype.spacesFrom = function(start, end) {

    var direction = this.directionFrom(start, end);
    if (!direction) {
        return undefined;
    }

    var space = {
        i : start.i,
        j : start.j
    };
    var spaces = [space];
    var nextSpace = {}, nextValue;

    while (true) {
        nextSpace = spaceInDirection(space, direction);
        nextValue = this.grid[nextSpace.i][nextSpace.j];

        if (nextValue == this.room.turn || nextValue == -2) {
            nextSpace = undefined;
            spaces = undefined;
            break;
        } else {
            spaces.push(nextSpace);
            space = nextSpace;
        }

        if (nextValue == -1) {
            break;
        }
    }
    return spaces;
}

Game.prototype.validateMove = function(start, end) {
	if (this.grid[start.i][start.j] !== this.room.turn) {
		return false;
	}
	if (this.grid[end.i][end.j] !== -1) {
		return false;
	}

    var direction = this.directionFrom(start, end);
    if (!direction) {
        return false;
    }

    var space = generateMoveInDirection(start, direction);
    if (space.i === end.i && space.j === end.j) {
        return true;
    }

    return false;
}

Game.prototype.move = function(start, end) {
	// Make grid changes
    var spaces = spacesFrom(start, end);
    for (var space in spaces) {
        this.grid[space.i][space.j] = this.room.turn;
    }

	//tell room move
	// if game end, tell room
}

//return player score (go through grid and calc, dont keep track)
Game.prototype.getScore = function(player) {
    var score = 0;
    for (var i = 0; i < 9; i++) {
        for (var j = 0; j < 8; j++) {
            if (this.grid[i][j] === player) {
                score++;
            }
        }
    }
    return score;
}

//replace grid instances of playerFrom, to playerTO
Game.prototype.replacePlayer = function(playerFrom, playerTo){
    for (var i = 0; i < 9; i++) {
        for (var j = 0; j < 8; j++) {
            if (this.grid[i][j] === playerFrom) {
                this.grid[i][j] === playerTo;
            }
        }
    }
}

<|endoftext|>


<commit_before>var mergeCompleted = function(userId, playlistId) {

	var footerInfo = $("#footer-info");
	var mergeButton = $("#merge-button");

	$('#loggedin').hide();
	$('#userplaylists').hide();
	$('#playlist-created').show();
	$('#embedded-playlist').show();

	var playlistUri = "spotify:user:" + userId + ":playlist:" + playlistId;
	var playlistName = $("#playlist-name").val();

	var playlistEmbedHtml = '';

	$('#playlist-embed').append(playlistEmbedHtml);

	$('iframe[src*="embed.spotify.com"]').each( function() {
		$(this).css('width',$(this).parent(1).css('width'));
		$(this).attr('src',$(this).attr('src'));
  	});

	var playlistShareText = 'I just created a new merged playlist using mergeyoplaylists.today! #mergeyoplaylists #spotify #music';
	var playlistShareUrl = 'https://open.spotify.com/user/' + userId + '/playlist/' + playlistId;

	//set share button links

	//facebook - example:
	$("#facebook-share").prop('href', 'https://www.facebook.com/sharer/sharer.php?u=' +
		playlistShareUrl
	);

	//twitter - example:
	$("#twitter-share").prop('href', 'http://twitter.com/share?text=' +
		playlistShareText + '&url=' + playlistShareUrl
	);

	//tumblr - example:
	$("#tumblr-share").prop('href', 'http://www.tumblr.com/share/link?url=' +
		playlistShareUrl + '&description=I just created a new merged playlist using mergeyoplaylists.today!'
	);

	//reddit - example:
	$("#reddit-share").prop('href', 'https://www.reddit.com/submit?url=' +
		playlistShareUrl + '&title=' + playlistName + ' - created with mergeyoplaylists.today!'
	);

	mergeButton.prop('disabled', 'disabled');
	footerInfo.animate( { height:"0px" }, { queue:false, duration:500 });

};

var applyEventListeners = function(userId, access_token) {

	$( ".playlist-grid-cell img" ).off('mouseenter');
	$( ".playlist-grid-cell" ).off('click');
	$('#merge-button').off('click');

	$( ".playlist-grid-cell img" ).mouseenter(

		function() {

			var title = $(this).data('name');
			var tracks = $(this).data('trackcount');

			$( this ).parents('div').find('.layer').remove();
			$( this ).parent().append( $( "
" +
			"

" +
			title +
			"
" +
			"
	" +
			"

" +
			tracks +
			" tracks
" +
			"
" +
			"
" ) );

		}
	);

	$( ".playlist-grid-cell" ).click(

		function() {

			var mergeButton = $("#merge-button");
			var albumCount = $("#album-count");
			var trackCount = $("#track-count");
			var footerInfo = $("#footer-info");
			var dataTrackCount = parseInt($( this ).find('img').data('trackcount'));

			if ( $( this ).find('.selected').length ) {

				$( this ).find('.selected').remove();

				var count = parseInt(albumCount.text()) - 1;
				albumCount.text(count);

				var trackCountVal = parseInt(trackCount.text()) - dataTrackCount;
				trackCount.text(trackCountVal);

				if (count == 0 || trackCountVal == 0) {
					mergeButton.prop('disabled', 'disabled');
					footerInfo.animate( { height:"0px" }, { queue:false, duration:500 });
				}

			} else {

				$( this ).parents('div').find('.layer').remove();
				$( this ).children('a').append( $("

Selected!
" +
				"

" ) );

				//albumCount.text() will be '0' by default
				if (albumCount.text() !== '0') {
					var count = parseInt(albumCount.text()) + 1;
					albumCount.text(count);

					var trackCountVal = parseInt(trackCount.text()) + dataTrackCount;
					trackCount.text(trackCountVal);

				} else {
					albumCount.text('1');
					trackCount.text(dataTrackCount);

					//animate in footer with info - TRIGGERED
					footerInfo.animate( { height:"0px" }, { queue:false, duration:0 });
					footerInfo.prop('hidden', false);
					footerInfo.animate( { height:"70px" }, { queue:false, duration:500 });
				}

				mergeButton.prop('disabled', false);

			}

		}
	);

	$('#merge-button').click(

		function() {

			var playlistResults = $("#playlist-results");
			var playlistName = $("#playlist-name").val();

			$( this ).prop('disabled', true);
			$("#playlist-name").prop('disabled', true);

			//create new playlist with name provided
			var playlistId = createPlaylist(userId, access_token, playlistName);

			playlistId.then(function(id){

				var playlistId = id;

				//get tracks for each playlist, add to big array
				Promise.map(playlistResults.find('.selected').toArray(), function(playlistResult) {

					var playlist = $(playlistResult).parent();
					var tracksURL = $(playlist.children('img')).data('trackurl');

					return Promise.delay(2000).then(function(){
						return getPlaylistTracks(userId, access_token, tracksURL);
					});

				}).then(function(allTracks){

					var mergedList = [].concat.apply([], allTracks);
					var filteredList = mergedList.concat();

					for(var i=0; i<filteredList.length; ++i) {
						for(var j=i+1; j<filteredList.length; ++j) {
							if(filteredList[i] === filteredList[j])
								filteredList.splice(j--, 1);
						}
					}

					//add all tracks to new playlist - with playlistId
					var addTracks = addTracksToPlaylist(userId, access_token, playlistId, filteredList);

					addTracks.then(function(playlistId){
						mergeCompleted(userId, playlistId);
					});

				});

			});

		}
	);
};<commit_msg>Removed hashtags from twitter share message<commit_after>var mergeCompleted = function(userId, playlistId) {

	var footerInfo = $("#footer-info");
	var mergeButton = $("#merge-button");

	$('#loggedin').hide();
	$('#userplaylists').hide();
	$('#playlist-created').show();
	$('#embedded-playlist').show();

	var playlistUri = "spotify:user:" + userId + ":playlist:" + playlistId;
	var playlistName = $("#playlist-name").val();

	var playlistEmbedHtml = '';

	$('#playlist-embed').append(playlistEmbedHtml);

	$('iframe[src*="embed.spotify.com"]').each( function() {
		$(this).css('width',$(this).parent(1).css('width'));
		$(this).attr('src',$(this).attr('src'));
  	});

	var playlistShareText = 'I just created a new merged playlist using mergeyoplaylists.today!';
	var playlistShareUrl = 'https://open.spotify.com/user/' + userId + '/playlist/' + playlistId;

	//set share button links

	//facebook - example:
	$("#facebook-share").prop('href', 'https://www.facebook.com/sharer/sharer.php?u=' +
		playlistShareUrl
	);

	//twitter - example:
	$("#twitter-share").prop('href', 'http://twitter.com/share?text=' +
		playlistShareText + '&url=' + playlistShareUrl
	);

	//tumblr - example:
	$("#tumblr-share").prop('href', 'http://www.tumblr.com/share/link?url=' +
		playlistShareUrl + '&description=I just created a new merged playlist using mergeyoplaylists.today!'
	);

	//reddit - example:
	$("#reddit-share").prop('href', 'https://www.reddit.com/submit?url=' +
		playlistShareUrl + '&title=' + playlistName + ' - created with mergeyoplaylists.today!'
	);

	mergeButton.prop('disabled', 'disabled');
	footerInfo.animate( { height:"0px" }, { queue:false, duration:500 });

};

var applyEventListeners = function(userId, access_token) {

	$( ".playlist-grid-cell img" ).off('mouseenter');
	$( ".playlist-grid-cell" ).off('click');
	$('#merge-button').off('click');

	$( ".playlist-grid-cell img" ).mouseenter(

		function() {

			var title = $(this).data('name');
			var tracks = $(this).data('trackcount');

			$( this ).parents('div').find('.layer').remove();
			$( this ).parent().append( $( "
" +
			"

" +
			title +
			"
" +
			"
	" +
			"

" +
			tracks +
			" tracks
" +
			"
" +
			"
" ) );

		}
	);

	$( ".playlist-grid-cell" ).click(

		function() {

			var mergeButton = $("#merge-button");
			var albumCount = $("#album-count");
			var trackCount = $("#track-count");
			var footerInfo = $("#footer-info");
			var dataTrackCount = parseInt($( this ).find('img').data('trackcount'));

			if ( $( this ).find('.selected').length ) {

				$( this ).find('.selected').remove();

				var count = parseInt(albumCount.text()) - 1;
				albumCount.text(count);

				var trackCountVal = parseInt(trackCount.text()) - dataTrackCount;
				trackCount.text(trackCountVal);

				if (count == 0 || trackCountVal == 0) {
					mergeButton.prop('disabled', 'disabled');
					footerInfo.animate( { height:"0px" }, { queue:false, duration:500 });
				}

			} else {

				$( this ).parents('div').find('.layer').remove();
				$( this ).children('a').append( $("

Selected!
" +
				"

" ) );

				//albumCount.text() will be '0' by default
				if (albumCount.text() !== '0') {
					var count = parseInt(albumCount.text()) + 1;
					albumCount.text(count);

					var trackCountVal = parseInt(trackCount.text()) + dataTrackCount;
					trackCount.text(trackCountVal);

				} else {
					albumCount.text('1');
					trackCount.text(dataTrackCount);

					//animate in footer with info - TRIGGERED
					footerInfo.animate( { height:"0px" }, { queue:false, duration:0 });
					footerInfo.prop('hidden', false);
					footerInfo.animate( { height:"70px" }, { queue:false, duration:500 });
				}

				mergeButton.prop('disabled', false);

			}

		}
	);

	$('#merge-button').click(

		function() {

			var playlistResults = $("#playlist-results");
			var playlistName = $("#playlist-name").val();

			$( this ).prop('disabled', true);
			$("#playlist-name").prop('disabled', true);

			//create new playlist with name provided
			var playlistId = createPlaylist(userId, access_token, playlistName);

			playlistId.then(function(id){

				var playlistId = id;

				//get tracks for each playlist, add to big array
				Promise.map(playlistResults.find('.selected').toArray(), function(playlistResult) {

					var playlist = $(playlistResult).parent();
					var tracksURL = $(playlist.children('img')).data('trackurl');

					return Promise.delay(2000).then(function(){
						return getPlaylistTracks(userId, access_token, tracksURL);
					});

				}).then(function(allTracks){

					var mergedList = [].concat.apply([], allTracks);
					var filteredList = mergedList.concat();

					for(var i=0; i<filteredList.length; ++i) {
						for(var j=i+1; j<filteredList.length; ++j) {
							if(filteredList[i] === filteredList[j])
								filteredList.splice(j--, 1);
						}
					}

					//add all tracks to new playlist - with playlistId
					var addTracks = addTracksToPlaylist(userId, access_token, playlistId, filteredList);

					addTracks.then(function(playlistId){
						mergeCompleted(userId, playlistId);
					});

				});

			});

		}
	);
};<|endoftext|>


<commit_before>var triggerEvents = function(context) {
    args = _.chain(arguments).flatten().rest().value() || [];
    return context.trigger.apply(context, args);
};

var Track = Backbone.Model.extend({
    defaults: {
        siteMediaID: "",
        siteCode: "",
        icon: "",
        permalink: "",
        url: "",
        uploader: "",
        siteName: "",
        mediaName: "",
        type: ""
    },
    destruct: function() {
        triggerEvents(this, 'destruct', Array.prototype.slice.call(arguments));
    },
    end: function() {
        triggerEvents(this, 'end', Array.prototype.slice.call(arguments));
    },
    mute: function() {
        triggerEvents(this, 'mute', Array.prototype.slice.call(arguments));
    },
    play: function() {
        triggerEvents(this, 'play', Array.prototype.slice.call(arguments));
    },
    play: function() {
        triggerEvents(this, 'play', Array.prototype.slice.call(arguments));
    },
    seek: function() {
        triggerEvents(this, 'progress', Array.prototype.slice.call(arguments));
    },
    setMute: function(mute) {
        var event = mute ? 'mute' : 'unmute';
        triggerEvents(this, event, _.rest(arguments));
    },
    setVolume: function() {
        triggerEvents(this, 'volume', Array.prototype.slice.call(arguments));
    },
    stop: function() {
        triggerEvents(this, 'stop', Array.prototype.slice.call(arguments));
    },
    togglePause: function(playing) {
        var event = playing ? 'pause' : 'resume';
        triggerEvents(this, event, this, _.rest(arguments));
    },
    triggerProgress: function() {
        triggerEvents(this, event, this, {percent: 0, time: 0}, Array.prototype.slice.call(arguments));
    }
}, {
    getMediaObject: function(mediaData, options) {
        var mediaObject = null;
        options || (options = {});
        if (mediaData) {
            switch (mediaData.siteCode) {
                case 'sct':
                    mediaObject = new SoundCloudTrack({
                        siteMediaID: mediaData.siteMediaID,
                        url: mediaData.url,
                        permalink: mediaData.permalink,
                        uploader: mediaData.author,
                        mediaName: mediaData.mediaName,
                        duration: mediaData.duration,
                        soundManager: soundManager
                    }, options);
                    break;
                case 'jmt':
                    mediaObject = new JamendoTrack({
                        siteMediaID: mediaData.siteMediaID,
                        url: mediaData.url,
                        permalink: mediaData.permalink,
                        uploader: mediaData.author,
                        mediaName: mediaData.mediaName,
                        duration: mediaData.duration,
                        soundManager: soundManager
                    }, options);
                    break;
                case 'ytv':
                    mediaObject = new YouTubeTrack({
                        siteMediaID: mediaData.siteMediaID,
                        uploader: mediaData.author,
                        mediaName: mediaData.mediaName,
                        duration: mediaData.duration,
                    }, options);
                    break;
            }
        }
        return mediaObject;
    }
});

var SoundTrack = Track.extend({
    defaults: _.extend({}, Track.prototype.defaults, {
        soundManager: null,
        duration: 0.0,
        sound: null,
        type: "audio"
    }),
    initialize: function(options) {

        if (options.silent) {
            return;
        }

        var audio = null, sm = (soundManager != undefined && soundManager != null)
            ? soundManager
            : null;
        if (sm) {
            audio = sm.createSound({
                id: this.get("siteMediaID"),
                url: this.get("url")
            });
        }
        this.set({
            soundManager: sm,
            sound: audio
        });
    },
    destruct: function() {
        this.get("sound").destruct();
        triggerEvents(this, 'progress', {percent: 0, time: 0}, Array.prototype.slice.call(arguments));
        triggerEvents(this, 'destruct', Array.prototype.slice.call(arguments));
    },
    end: function() {
        this.get("sound").stop();
        triggerEvents(this, 'progress', {percent: 0, time: 0}, Array.prototype.slice.call(arguments));
        triggerEvents(this, 'end', Array.prototype.slice.call(arguments));
    },
    getDuration: function() {
        return this.get("duration");
    },
    getVolume: function() {
        return this.get('sound').volume;
    },
    isMuted: function() {
        return this.get("sound").muted;
    },
    isPaused: function() {
        return this.get("sound").paused;
    },
    isPlaying: function() {
        return this.get("sound").playState === 1;
    },
    isStopped: function() {
        return this.get("sound").playState === 0;
    },
    play: function(options) {
        this.get('soundManager').play(this.get("siteMediaID"), options);
        triggerEvents(this, 'play', Array.prototype.slice.call(arguments));
    },
    seek: function(decimalPercent) {
        var time = Math.floor(decimalPercent * this.get("sound").duration);
        this.get("sound").setPosition(time);
        triggerEvents(this, 'progress', {percent: decimalPercent, time: time}, _.rest(arguments));
    },
    setMute: function(mute) {
        var event = mute ? 'mute' : 'unmute';
        if (mute) {
            this.get("sound").mute();
        }
        else {
            this.get("sound").unmute();
        }
        triggerEvents(this, event, this, _.rest(arguments));
    },

    setVolume: function(intPercent) {
        this.setMute(intPercent == 0);
        this.get("sound").setVolume(intPercent);
        triggerEvents(this, 'volume', Array.prototype.slice.call(arguments));
    },

    stop: function() {
        this.get("sound").stop();
        triggerEvents(this, 'stop', Array.prototype.slice.call(arguments));
    },

    togglePause: function() {
        var playing = this.isPlaying();
        var sound = this.get("sound");
        sound.togglePause();
        var event = playing ? 'pause' : 'resume';
        triggerEvents(this, event, this, Array.prototype.slice.call(arguments));
    },

    toggleMute: function() {
        var mute = !this.isMuted();
        this.setMute(mute);
    },

    triggerProgress: function() {
        var time = this.get('sound').position / 1000;
        var percent = (time * 100.0) / this.get('duration');
        triggerEvents(this, 'progress', {percent: percent, time: time}, Array.prototype.slice.call(arguments));
    }
});

var JamendoTrack = SoundTrack.extend({
    defaults: _.extend({}, SoundTrack.prototype.defaults, {
        site: 'Jamendo',
        siteCode: 'jmt',
        // Icon by Oliver Schultz, used under Creative Commons SA NC
        //http://www.iconfinder.com/iconsets/humano2#readme
        icon: 'img/jamendo_16.png'
    })
});

var SoundCloudTrack = SoundTrack.extend({
    defaults: _.extend({}, SoundTrack.prototype.defaults, {
        site: "SoundCloud",
        siteCode: "sct",
        icon: "img/soundcloud_orange_white_16.png"
    })
});

var VideoTrack = Track.extend({
    defaults: _.extend({}, Track.prototype.defaults, {
        type: "video"
    })
});

var YouTubeTrack = VideoTrack.extend({
    defaults: _.extend({}, VideoTrack.prototype.defaults, {
        siteName: "YouTube",
        siteCode: "ytv",
        icon: "img/youtube.png",
    }),
    initialize: function() {
        var id = this.get('siteMediaID');
        var permalink = 'http://www.youtube.com/watch?v=' + id;
        this.set({
            url: permalink,
            permalink: permalink,
        })
    },
    destruct: function() {
        var self = this, args = Array.prototype.slice.call(arguments);
        return YouTube.reset().then(function() {
            self._stopped = true;
            triggerEvents(self, 'progress', {percent: 0, time: 0}, Array.prototype.slice.call(arguments));
            triggerEvents(self, 'destruct', args);
        });
    },
    end: function() {
        var self = this, args = Array.prototype.slice.call(arguments);;
        return this.destruct().then(function() {
            triggerEvents(self, 'end', args);
        });
    },
    getVolume: function() {
        return YouTube.getVolume();
    },
    idInPlayer: function() {
        return YouTube.videoId() == this.get('siteMediaID');
    },
    isBuffering: function() {
        return this.idInPlayer() && YouTube.state == 3;
    },
    isMuted: function() {
        return this.idInPlayer() && YouTube.isMuted();
    },
    isPaused: function() {
        return this.idInPlayer() && !this._stopped && YouTube.state == 2;
    },
    isPlaying: function() {
        return this.idInPlayer() && !this._stopped &&
            (YouTube.hasPlayer() || YouTube.state === 1 || this.isPaused() || this.isBuffering());
    },
    isStopped: function() {
        return this._stopped || !this.isPlaying();
    },
    play: function(options) {
        var self = this, args = Array.prototype.slice.call(arguments);
        if (this.isPaused()) {
            this.togglePause();
        } else {
            YouTube.reset();
            YouTube.load(_.extend({autoPlay: true}, options, {
                initialVideo: this.get('siteMediaID')
            })).then(function() {
                self._stopped = false;
                self.listenTo(YouTube, 'progress', function(progress) {
                    triggerEvents(self, 'progress', progress, args);
                });
                YouTube.once('end error', function() {
                    self.stopListening(YouTube, 'progress');
                    self.end();
                });
                triggerEvents(self, 'play', args);
            });
        }
    },
    seek: function(decimalPercent) {
        var duration = this.get('duration'),
            self = this,
            time = Math.floor(decimalPercent * duration),
            args = Array.prototype.slice.call(arguments);
        YouTube.seek(time).then(function() {
            self._stopped = false;
            triggerEvents(self, 'progress', {percent: decimalPercent, time: time}, _.rest(args));
        });
    },
    setMute: function(mute, silent) {
        var self = this, dfd, event, args = _.rest(arguments, 2);
        if (mute) {
            event = 'mute';
            dfd = YouTube.mute();
        } else {
            dfd = YouTube.unmute();
            event = 'unmute';
        }
        dfd.then(function() {
            if (silent) {
                return;
            }
            triggerEvents(self, event, self, args);
        });
    },
    setVolume: function(percent) {
        var muted = this.isMuted(), dfd, self = this, args = Array.prototype.slice.call(arguments);
        dfd = YouTube.setVolume(percent);
        if (percent == 0 && !muted) {
            dfd.then(function() {
                return self.setMute(true, true);
            });
        } else if (percent > 0 && muted) {
            dfd.then(function() {
                return self.setMute(false, true);
            });
        }
        dfd.then(function() {
            triggerEvents(self, 'volume', args);
        });
    },
    stop: function() {
        var self = this, args = Array.prototype.slice.call(arguments);
        YouTube.pause();
        YouTube.seek(0).then(function() {
            self._stopped = true;
            triggerEvents(self, 'stop', args);
        });
    },
    togglePause: function() {
        var self = this;
        var state = YouTube.state;
        var playing = this.isPlaying();
        var dfd = playing ? YouTube.pause() : YouTube.play();
        var event = playing ? 'pause' : 'resume', args = Array.prototype.slice.call(arguments);
        dfd.then(function() {
            self._stopped = false;
            triggerEvents(self, event, self, args);
        });
    },
    toggleMute: function() {
        var mute = !this.isMuted();
        this.setMute(mute);
    },
    triggerProgress: function() {
        var args = Array.prototype.slice.call(arguments);
        YouTube.getData().then(function(data) {
            var time = data.currentTime,
                duration = data.duration,
                percent = (time * 100.0) / duration;
            triggerEvents(self, 'progress', {percent: percent, time: time}, args);
        });
    }
});<commit_msg>Code to create tracks based on site code is now shorter.<commit_after>var triggerEvents = function(context) {
    args = _.chain(arguments).flatten().rest().value() || [];
    return context.trigger.apply(context, args);
};

var Track = Backbone.Model.extend({
    defaults: {
        siteMediaID: "",
        siteCode: "",
        icon: "",
        permalink: "",
        url: "",
        uploader: "",
        siteName: "",
        mediaName: "",
        type: ""
    },
    destruct: function() {
        triggerEvents(this, 'destruct', Array.prototype.slice.call(arguments));
    },
    end: function() {
        triggerEvents(this, 'end', Array.prototype.slice.call(arguments));
    },
    mute: function() {
        triggerEvents(this, 'mute', Array.prototype.slice.call(arguments));
    },
    play: function() {
        triggerEvents(this, 'play', Array.prototype.slice.call(arguments));
    },
    play: function() {
        triggerEvents(this, 'play', Array.prototype.slice.call(arguments));
    },
    seek: function() {
        triggerEvents(this, 'progress', Array.prototype.slice.call(arguments));
    },
    setMute: function(mute) {
        var event = mute ? 'mute' : 'unmute';
        triggerEvents(this, event, _.rest(arguments));
    },
    setVolume: function() {
        triggerEvents(this, 'volume', Array.prototype.slice.call(arguments));
    },
    stop: function() {
        triggerEvents(this, 'stop', Array.prototype.slice.call(arguments));
    },
    togglePause: function(playing) {
        var event = playing ? 'pause' : 'resume';
        triggerEvents(this, event, this, _.rest(arguments));
    },
    triggerProgress: function() {
        triggerEvents(this, event, this, {percent: 0, time: 0}, Array.prototype.slice.call(arguments));
    }
}, {
    getMediaObject: function(mediaData, options) {
        var mediaObject = null;
        options || (options = {});
        if (mediaData) {
            var proto,
                params = _(mediaData).pick('siteMediaID', 'url', 'permalink', 'mediaName', 'duration');

            params.uploader = mediaData.author;
            switch (mediaData.siteCode) {
                case 'sct':
                    proto = SoundCloudTrack;
                    params.soundManager = soundManager;
                    break;
                case 'jmt':
                    proto = JamendoTrack;
                    params.soundManager = soundManager;
                    break;
                case 'ytv':
                    proto = YouTubeTrack;
                    break;
            }
            mediaObject = new proto(params, options);
        }
        return mediaObject;
    }
});

var SoundTrack = Track.extend({
    defaults: _.extend({}, Track.prototype.defaults, {
        soundManager: null,
        duration: 0.0,
        sound: null,
        type: "audio"
    }),
    initialize: function(options) {

        if (options.silent) {
            return;
        }

        var audio = null, sm = (soundManager != undefined && soundManager != null)
            ? soundManager
            : null;
        if (sm) {
            audio = sm.createSound({
                id: this.get("siteMediaID"),
                url: this.get("url")
            });
        }
        this.set({
            soundManager: sm,
            sound: audio
        });
    },
    destruct: function() {
        this.get("sound").destruct();
        triggerEvents(this, 'progress', {percent: 0, time: 0}, Array.prototype.slice.call(arguments));
        triggerEvents(this, 'destruct', Array.prototype.slice.call(arguments));
    },
    end: function() {
        this.get("sound").stop();
        triggerEvents(this, 'progress', {percent: 0, time: 0}, Array.prototype.slice.call(arguments));
        triggerEvents(this, 'end', Array.prototype.slice.call(arguments));
    },
    getDuration: function() {
        return this.get("duration");
    },
    getVolume: function() {
        return this.get('sound').volume;
    },
    isMuted: function() {
        return this.get("sound").muted;
    },
    isPaused: function() {
        return this.get("sound").paused;
    },
    isPlaying: function() {
        return this.get("sound").playState === 1;
    },
    isStopped: function() {
        return this.get("sound").playState === 0;
    },
    play: function(options) {
        this.get('soundManager').play(this.get("siteMediaID"), options);
        triggerEvents(this, 'play', Array.prototype.slice.call(arguments));
    },
    seek: function(decimalPercent) {
        var time = Math.floor(decimalPercent * this.get("sound").duration);
        this.get("sound").setPosition(time);
        triggerEvents(this, 'progress', {percent: decimalPercent, time: time}, _.rest(arguments));
    },
    setMute: function(mute) {
        var event = mute ? 'mute' : 'unmute';
        if (mute) {
            this.get("sound").mute();
        }
        else {
            this.get("sound").unmute();
        }
        triggerEvents(this, event, this, _.rest(arguments));
    },

    setVolume: function(intPercent) {
        this.setMute(intPercent == 0);
        this.get("sound").setVolume(intPercent);
        triggerEvents(this, 'volume', Array.prototype.slice.call(arguments));
    },

    stop: function() {
        this.get("sound").stop();
        triggerEvents(this, 'stop', Array.prototype.slice.call(arguments));
    },

    togglePause: function() {
        var playing = this.isPlaying();
        var sound = this.get("sound");
        sound.togglePause();
        var event = playing ? 'pause' : 'resume';
        triggerEvents(this, event, this, Array.prototype.slice.call(arguments));
    },

    toggleMute: function() {
        var mute = !this.isMuted();
        this.setMute(mute);
    },

    triggerProgress: function() {
        var time = this.get('sound').position / 1000;
        var percent = (time * 100.0) / this.get('duration');
        triggerEvents(this, 'progress', {percent: percent, time: time}, Array.prototype.slice.call(arguments));
    }
});

var JamendoTrack = SoundTrack.extend({
    defaults: _.extend({}, SoundTrack.prototype.defaults, {
        site: 'Jamendo',
        siteCode: 'jmt',
        // Icon by Oliver Schultz, used under Creative Commons SA NC
        //http://www.iconfinder.com/iconsets/humano2#readme
        icon: 'img/jamendo_16.png'
    })
});

var SoundCloudTrack = SoundTrack.extend({
    defaults: _.extend({}, SoundTrack.prototype.defaults, {
        site: "SoundCloud",
        siteCode: "sct",
        icon: "img/soundcloud_orange_white_16.png"
    })
});

var VideoTrack = Track.extend({
    defaults: _.extend({}, Track.prototype.defaults, {
        type: "video"
    })
});

var YouTubeTrack = VideoTrack.extend({
    defaults: _.extend({}, VideoTrack.prototype.defaults, {
        siteName: "YouTube",
        siteCode: "ytv",
        icon: "img/youtube.png",
    }),
    initialize: function() {
        var id = this.get('siteMediaID');
        var permalink = 'http://www.youtube.com/watch?v=' + id;
        this.set({
            url: permalink,
            permalink: permalink,
        })
    },
    destruct: function() {
        var self = this, args = Array.prototype.slice.call(arguments);
        return YouTube.reset().then(function() {
            self._stopped = true;
            triggerEvents(self, 'progress', {percent: 0, time: 0}, Array.prototype.slice.call(arguments));
            triggerEvents(self, 'destruct', args);
        });
    },
    end: function() {
        var self = this, args = Array.prototype.slice.call(arguments);;
        return this.destruct().then(function() {
            triggerEvents(self, 'end', args);
        });
    },
    getVolume: function() {
        return YouTube.getVolume();
    },
    idInPlayer: function() {
        return YouTube.videoId() == this.get('siteMediaID');
    },
    isBuffering: function() {
        return this.idInPlayer() && YouTube.state == 3;
    },
    isMuted: function() {
        return this.idInPlayer() && YouTube.isMuted();
    },
    isPaused: function() {
        return this.idInPlayer() && !this._stopped && YouTube.state == 2;
    },
    isPlaying: function() {
        return this.idInPlayer() && !this._stopped &&
            (YouTube.hasPlayer() || YouTube.state === 1 || this.isPaused() || this.isBuffering());
    },
    isStopped: function() {
        return this._stopped || !this.isPlaying();
    },
    play: function(options) {
        var self = this, args = Array.prototype.slice.call(arguments);
        if (this.isPaused()) {
            this.togglePause();
        } else {
            YouTube.reset();
            YouTube.load(_.extend({autoPlay: true}, options, {
                initialVideo: this.get('siteMediaID')
            })).then(function() {
                self._stopped = false;
                self.listenTo(YouTube, 'progress', function(progress) {
                    triggerEvents(self, 'progress', progress, args);
                });
                YouTube.once('end error', function() {
                    self.stopListening(YouTube, 'progress');
                    self.end();
                });
                triggerEvents(self, 'play', args);
            });
        }
    },
    seek: function(decimalPercent) {
        var duration = this.get('duration'),
            self = this,
            time = Math.floor(decimalPercent * duration),
            args = Array.prototype.slice.call(arguments);
        YouTube.seek(time).then(function() {
            self._stopped = false;
            triggerEvents(self, 'progress', {percent: decimalPercent, time: time}, _.rest(args));
        });
    },
    setMute: function(mute, silent) {
        var self = this, dfd, event, args = _.rest(arguments, 2);
        if (mute) {
            event = 'mute';
            dfd = YouTube.mute();
        } else {
            dfd = YouTube.unmute();
            event = 'unmute';
        }
        dfd.then(function() {
            if (silent) {
                return;
            }
            triggerEvents(self, event, self, args);
        });
    },
    setVolume: function(percent) {
        var muted = this.isMuted(), dfd, self = this, args = Array.prototype.slice.call(arguments);
        dfd = YouTube.setVolume(percent);
        if (percent == 0 && !muted) {
            dfd.then(function() {
                return self.setMute(true, true);
            });
        } else if (percent > 0 && muted) {
            dfd.then(function() {
                return self.setMute(false, true);
            });
        }
        dfd.then(function() {
            triggerEvents(self, 'volume', args);
        });
    },
    stop: function() {
        var self = this, args = Array.prototype.slice.call(arguments);
        YouTube.pause();
        YouTube.seek(0).then(function() {
            self._stopped = true;
            triggerEvents(self, 'stop', args);
        });
    },
    togglePause: function() {
        var self = this;
        var state = YouTube.state;
        var playing = this.isPlaying();
        var dfd = playing ? YouTube.pause() : YouTube.play();
        var event = playing ? 'pause' : 'resume', args = Array.prototype.slice.call(arguments);
        dfd.then(function() {
            self._stopped = false;
            triggerEvents(self, event, self, args);
        });
    },
    toggleMute: function() {
        var mute = !this.isMuted();
        this.setMute(mute);
    },
    triggerProgress: function() {
        var args = Array.prototype.slice.call(arguments);
        YouTube.getData().then(function(data) {
            var time = data.currentTime,
                duration = data.duration,
                percent = (time * 100.0) / duration;
            triggerEvents(self, 'progress', {percent: percent, time: time}, args);
        });
    }
});<|endoftext|>


<commit_before>var b = document.documentElement;
b.setAttribute('data-useragent', navigator.userAgent);
b.setAttribute('data-platform', navigator.platform);
var toastr = require('./toastr.min');

jQuery(function($) {

    var supportsAudio = !!document.createElement('audio').canPlayType;

    if (supportsAudio) {
        $.get("/api/music", function(data) {
            var time;
            $(".duration_dial").knob({
                'change': function(value) {
                    audio.currentTime = value;
                },
                format: function(value) {
                    return time;
                }
            });
            $(".vol_dial").knob({
                change: function(value) {
                    audio.volume = '0.' + Math.floor(value);
                }
            });

            var index = 0,
                playing = false,
                tracks = data,
                buildPlaylist = $.each(tracks, function(key, value) {
                    var trackNumber = value.id,
                        trackName = value.name,
                        trackLength = value.length;
                    if (trackNumber.toString().length === 1) {
                        trackNumber = '0' + trackNumber;
                    } else {
                        trackNumber = '' + trackNumber;
                    }
                    $('.library').append('
' + trackName + '
');
                    $('.queue-library').append('' +
                        '
' + trackName + '
'
                    );
                }),
                trackCount = tracks.length,
                npAction = $('#npAction'),
                npTitle = $('#npTitle'),
                audio = $('#audio1').bind('play', function() {
                    playing = true;
                    npAction.text('Now Playing...');
                }).bind('pause', function() {
                    playing = false;
                    npAction.text('Paused...');
                }).bind('ended', function() {
                    npAction.text('Paused...');
                    if ((index + 1) < trackCount) {
                        index++;
                        loadTrack(index);
                        audio.play();
                    } else {
                        audio.pause();
                        index = 0;
                        loadTrack(index);
                    }
                }).get(0),
                btnPrev = $('#previous').click(function() {
                    if ((index - 1) > -1) {
                        index--;
                        loadTrack(index);
                        if (playing) {
                            audio.play();
                        }
                    } else {
                        audio.pause();
                        index = 0;
                        loadTrack(index);
                    }
                }),
                btnNext = $('#next').click(function() {
                    if ((index + 1) < trackCount) {
                        index++;
                        loadTrack(index);
                        if (playing) {
                            audio.play();
                        }
                    } else {
                        audio.pause();
                        index = 0;
                        loadTrack(index);
                    }
                }),
                btnPlay = $('#play').click(function() {
                    if (playing) {
                        audio.pause();
                    } else {
                        audio.play();
                    }
                    var $this = $(this);
                    $this.toggleClass('btn-cmd');
                    if ($this.hasClass('btn-cmd')) {
                        $('#play').html('');
                    } else {
                        $('#play').html('');
                    }
                }),
                btnStop = $('#stop').click(function() {
                    audio.pause();
                    audio.currentTime = 0;
                }),
                volume_down = $('#volume_down').click(function() {
                    var vol = Math.min(audio.volume - 0.005, 1);
                    $(".vol_dial").val(vol * 100).trigger('change');
                    audio.volume = Math.min(audio.volume - 0.005, 1);
                }),
                volume_off = $('#volume_off').click(function() {
                    var $this = $(this);
                    $this.toggleClass('btn-volume');
                    if ($this.hasClass('btn-volume')) {
                        audio.volume = 0;
                        $('#volume_off').html('');
                    } else {
                        audio.volume = 1;
                        $('#volume_off').html('');
                    }

                    var vol = 0;
                    $(".vol_dial").val(vol).trigger('change');
                    audio.volume = 0;
                }),
                volume_up = $('#volume_up').click(function() {
                    var vol = Math.min(audio.volume + 0.005, 1);
                    $(".vol_dial").val(vol * 100).trigger('change');
                    audio.volume = Math.min(audio.volume + 0.005, 1);
                }),
                repeat = $('#repeat').click(function() {
                    audio.loop = true;
                }),
                single = $('#single').click(function() {
                    audio.loop = false;
                }),
                random = $('#random').click(function() {
                    var song = tracks[Math.floor(Math.random() * tracks.length)];
                    playing = true;
                    npTitle.text(song.name);
                    audio.src = song.song;
                    audio.play();
                }),
                li = $('#plList li').click(function() {
                    var id = parseInt($(this).index());
                    if (id !== index) {
                        playTrack(id);
                    }
                }),
                loadTrack = function(id) {
                    $('.plSel').removeClass('plSel');
                    $('#plList li:eq(' + id + ')').addClass('plSel');
                    npTitle.text(tracks[id].name);
                    index = id;
                    audio.src = tracks[id].song;
                },
                playTrack = function(id) {
                    loadTrack(id);
                    audio.play();
                },
                currentTime = audio.addEventListener('timeupdate', function() {
                    var currentTime = audio.currentTime;
                    var sec = new Number();
                    var min = new Number();
                    sec = Math.floor(currentTime);
                    min = Math.floor(sec / 60);
                    min = min >= 10
                        ? min
                        : '0' + min;
                    sec = Math.floor(sec % 60);
                    sec = sec >= 10
                        ? sec
                        : '0' + sec;

                    $('.duration_dial').val(currentTime).trigger('change');
                    time = min + ":" + sec;
                }, false);
                extension = audio.canPlayType('audio/mpeg')
                    ? '.mp3'
                    : audio.canPlayType('audio/ogg')
                    ? '.ogg'
                    : '';
                    loadTrack(index);

                    // $('.info').addClass('hidden');
                edit = function(id) {
                    $('.queue-library').addClass('hidden');
                    $('#info').removeClass('hiddden');
                    $.get('/api/edit/' + id, function(data) {
                        $('#info').html('<form id="updateForm" class="col-md-8" method="post">' +
                            '
' + '<lable>name</lable>' +
                            '<input class="form-control" type="text" name="name" value="' + data.name +
                            '"></input>' + '
' + '<button type=submit class="form-control btn btn-primary">update</button>' +
                            '</form>
<button id="delete" class="form-control btn btn-secondary">delete</button>'
                        );
                        $('#updateForm').submit(function(e) {
                            e.preventDefault();
                            var updatedName = {
                                name: $('input[name=name]').val()
                            };
                            $.post('/api/update/' + data.id, updatedName, function(resp) {
                                $('#info').addClass('hidden');
                                $('.queue-library').removeClass('hidden');
                            });
                        });
                        $('#delete').click(function(){
                            $.post('/api/delete/' + data.id, function(resp) {
                                $('#info').addClass('hidden');
                                $('.queue-library').removeClass('hidden');
                            });
                        });
                    });
                }
            });
        }

        $('#submit').attr('disabled', true);

        $('#file').change(function() {
            $('#submit').removeAttr('disabled');
        });

        $('#library-section, #queue-section').addClass('hidden');

        $('#library').click(function(e) {
            e.preventDefault();
            $('#playback-section, #queue-section').addClass('hidden');
            $('#library-section').removeClass('hidden');

            $('#addForm').submit(function(e) {
                e.preventDefault();
                toastr.info('Song added!', 'Success');

                var form = new FormData($("#addForm")[0]);

                $.ajax({
                    url: '/api/music',
                    method: "POST",
                    dataType: 'json',
                    data: form,
                    processData: false,
                    contentType: false,
                    success: function(result){
                        console.log(result);
                    },
                    error: function(er){}
                });
            });
        });

        $('#playback').click(function(e) {
            e.preventDefault();
            $('#library-section, #queue-section').addClass('hidden');
            $('#playback-section').removeClass('hidden');
        });

        $('#queue').click(function(e) {
            e.preventDefault();
            $('#playback-section, #library-section').addClass('hidden');
            $('#queue-section').removeClass('hidden');
        });
});
<commit_msg>delete alert<commit_after>var b = document.documentElement;
b.setAttribute('data-useragent', navigator.userAgent);
b.setAttribute('data-platform', navigator.platform);
var toastr = require('./toastr')

jQuery(function($) {

    var supportsAudio = !!document.createElement('audio').canPlayType;

    if (supportsAudio) {
        $.get("/api/music", function(data) {
            var time;
            $(".duration_dial").knob({
                'change': function(value) {
                    audio.currentTime = value;
                },
                format: function(value) {
                    return time;
                }
            });
            $(".vol_dial").knob({
                change: function(value) {
                    audio.volume = '0.' + Math.floor(value);
                }
            });

            var index = 0,
                playing = false,
                tracks = data,
                buildPlaylist = $.each(tracks, function(key, value) {
                    var trackNumber = value.id,
                        trackName = value.name,
                        trackLength = value.length;
                    if (trackNumber.toString().length === 1) {
                        trackNumber = '0' + trackNumber;
                    } else {
                        trackNumber = '' + trackNumber;
                    }
                    $('.library').append('
' + trackName + '
');
                    $('.queue-library').append('' +
                        '
' + trackName + '
'
                    );
                }),
                trackCount = tracks.length,
                npAction = $('#npAction'),
                npTitle = $('#npTitle'),
                audio = $('#audio1').bind('play', function() {
                    playing = true;
                    npAction.text('Now Playing...');
                }).bind('pause', function() {
                    playing = false;
                    npAction.text('Paused...');
                }).bind('ended', function() {
                    npAction.text('Paused...');
                    if ((index + 1) < trackCount) {
                        index++;
                        loadTrack(index);
                        audio.play();
                    } else {
                        audio.pause();
                        index = 0;
                        loadTrack(index);
                    }
                }).get(0),
                btnPrev = $('#previous').click(function() {
                    if ((index - 1) > -1) {
                        index--;
                        loadTrack(index);
                        if (playing) {
                            audio.play();
                        }
                    } else {
                        audio.pause();
                        index = 0;
                        loadTrack(index);
                    }
                }),
                btnNext = $('#next').click(function() {
                    if ((index + 1) < trackCount) {
                        index++;
                        loadTrack(index);
                        if (playing) {
                            audio.play();
                        }
                    } else {
                        audio.pause();
                        index = 0;
                        loadTrack(index);
                    }
                }),
                btnPlay = $('#play').click(function() {
                    if (playing) {
                        audio.pause();
                    } else {
                        audio.play();
                    }
                    var $this = $(this);
                    $this.toggleClass('btn-cmd');
                    if ($this.hasClass('btn-cmd')) {
                        $('#play').html('');
                    } else {
                        $('#play').html('');
                    }
                }),
                btnStop = $('#stop').click(function() {
                    audio.pause();
                    audio.currentTime = 0;
                }),
                volume_down = $('#volume_down').click(function() {
                    var vol = Math.min(audio.volume - 0.005, 1);
                    $(".vol_dial").val(vol * 100).trigger('change');
                    audio.volume = Math.min(audio.volume - 0.005, 1);
                }),
                volume_off = $('#volume_off').click(function() {
                    var $this = $(this);
                    $this.toggleClass('btn-volume');
                    if ($this.hasClass('btn-volume')) {
                        audio.volume = 0;
                        $('#volume_off').html('');
                    } else {
                        audio.volume = 1;
                        $('#volume_off').html('');
                    }

                    var vol = 0;
                    $(".vol_dial").val(vol).trigger('change');
                    audio.volume = 0;
                }),
                volume_up = $('#volume_up').click(function() {
                    var vol = Math.min(audio.volume + 0.005, 1);
                    $(".vol_dial").val(vol * 100).trigger('change');
                    audio.volume = Math.min(audio.volume + 0.005, 1);
                }),
                repeat = $('#repeat').click(function() {
                    audio.loop = true;
                }),
                single = $('#single').click(function() {
                    audio.loop = false;
                }),
                random = $('#random').click(function() {
                    var song = tracks[Math.floor(Math.random() * tracks.length)];
                    playing = true;
                    npTitle.text(song.name);
                    audio.src = song.song;
                    audio.play();
                }),
                li = $('#plList li').click(function() {
                    var id = parseInt($(this).index());
                    if (id !== index) {
                        playTrack(id);
                    }
                }),
                loadTrack = function(id) {
                    $('.plSel').removeClass('plSel');
                    $('#plList li:eq(' + id + ')').addClass('plSel');
                    npTitle.text(tracks[id].name);
                    index = id;
                    audio.src = tracks[id].song;
                },
                playTrack = function(id) {
                    loadTrack(id);
                    audio.play();
                },
                currentTime = audio.addEventListener('timeupdate', function() {
                    var currentTime = audio.currentTime;
                    var sec = new Number();
                    var min = new Number();
                    sec = Math.floor(currentTime);
                    min = Math.floor(sec / 60);
                    min = min >= 10
                        ? min
                        : '0' + min;
                    sec = Math.floor(sec % 60);
                    sec = sec >= 10
                        ? sec
                        : '0' + sec;

                    $('.duration_dial').val(currentTime).trigger('change');
                    time = min + ":" + sec;
                }, false);
                extension = audio.canPlayType('audio/mpeg')
                    ? '.mp3'
                    : audio.canPlayType('audio/ogg')
                    ? '.ogg'
                    : '';
                    loadTrack(index);

                    // $('.info').addClass('hidden');
                edit = function(id) {
                    $('.queue-library').addClass('hidden');
                    $('#info').removeClass('hiddden');
                    $.get('/api/edit/' + id, function(data) {
                        $('#info').html('<form id="updateForm" class="col-md-8" method="post">' +
                            '
' + '<lable>name</lable>' +
                            '<input class="form-control" type="text" name="name" value="' + data.name +
                            '"></input>' + '
' + '<button type=submit class="form-control btn btn-primary">update</button>' +
                            '</form>
<button id="delete" class="form-control btn btn-secondary">delete</button>'
                        );
                        $('#updateForm').submit(function(e) {
                            e.preventDefault();
                            var updatedName = {
                                name: $('input[name=name]').val()
                            };
                            $.post('/api/update/' + data.id, updatedName, function(resp) {
                                $('#info').addClass('hidden');
                                $('.queue-library').removeClass('hidden');
                            });
                        });
                        $('#delete').click(function(){
                            $.post('/api/delete/' + data.id, function(resp) {
                                $('#info').addClass('hidden');
                                $('.queue-library').removeClass('hidden');
                                toastr.info('Song deleted!', 'Success');
                            });
                        });
                    });
                }
            });
        }

        $('#submit').attr('disabled', true);

        $('#file').change(function() {
            $('#submit').removeAttr('disabled');
        });

        $('#library-section, #queue-section').addClass('hidden');

        $('#library').click(function(e) {
            e.preventDefault();
            $('#playback-section, #queue-section').addClass('hidden');
            $('#library-section').removeClass('hidden');

            $('#addForm').submit(function(e) {
                e.preventDefault();
                toastr.info('Song added!', 'Success');

                var form = new FormData($("#addForm")[0]);

                $.ajax({
                    url: '/api/music',
                    method: "POST",
                    dataType: 'json',
                    data: form,
                    processData: false,
                    contentType: false,
                    success: function(result){
                        console.log(result);
                    },
                    error: function(er){}
                });
            });
        });

        $('#playback').click(function(e) {
            e.preventDefault();
            $('#library-section, #queue-section').addClass('hidden');
            $('#playback-section').removeClass('hidden');
        });

        $('#queue').click(function(e) {
            e.preventDefault();
            $('#playback-section, #library-section').addClass('hidden');
            $('#queue-section').removeClass('hidden');
        });
});
<|endoftext|>