<commit_before>/* global jsxc, oc_appswebroots, OC, $, oc_requesttoken */

/**
 * Make room for the roster inside the owncloud template.
 *
 * @param {type} event
 * @param {type} state State in which the roster is
 * @param {type} duration Time the roster needs to move
 * @returns {undefined}
 */
function onRosterToggle(event, state, duration) {
   "use strict";
   var wrapper = $('#content-wrapper');
   var control = $('#controls');

   var roster_width = (state === 'shown') ? $('#jsxc_roster').outerWidth() : 0;
   var navigation_width = $('#navigation').width();

   wrapper.animate({
      paddingRight: (roster_width) + 'px'
   }, duration);
   control.animate({
      paddingRight: (roster_width + navigation_width) + 'px'
   }, duration);
}

/**
 * Init owncloud template for roster.
 *
 * @returns {undefined}
 */
function onRosterReady() {
   "use strict";
   var roster_width = $('#jsxc_roster').outerWidth();
   var navigation_width = $('#navigation').width();
   var roster_right = parseFloat($('#jsxc_roster').css('right'));

   $('#content-wrapper').css('paddingRight', roster_width + roster_right);
   $('#controls').css('paddingRight', roster_width + navigation_width + roster_right);
}

// initialization
$(function() {
   "use strict";

   $(document).on('ready.roster.jsxc', onRosterReady);
   $(document).on('toggle.roster.jsxc', onRosterToggle);

   $(document).on('connected.jsxc', function() {
      // reset default avatar cache
      jsxc.storage.removeUserItem('defaultAvatars');
   });

   jsxc.log = "";
   jsxc.tmp = null;
   jsxc.init({
      loginForm: {
         form: '#body-login form',
         jid: '#user',
         pass: '#password',
         preJid: function(jid) {
            var data = null;

            $.ajax(OC.filePath('ojsxc', 'ajax', 'getsettings.php'), {
               async: false,
               success: function(d) {
                  data = d;
               }
            });

            var resource = (data.xmppResource) ? '/' + data.xmppResource : '';
            var domain = data.xmppDomain;

            jsxc.storage.setItem('boshUrl', data.boshUrl);

            if (jid.match(/@(.*)$/)) {
               return (jid.match(/\/(.*)$/)) ? jid : jid + resource;
            }

            return jid + '@' + domain + resource;
         }
      },
      logoutElement: $('#logout'),
      checkFlash: false,
      rosterAppend: 'body',
      root: oc_appswebroots.ojsxc,
      // @TODO: don't include get turn credentials routine into jsxc
      turnCredentialsPath: OC.filePath('ojsxc', 'ajax', 'getturncredentials.php'),
      displayRosterMinimized: function() {
         return OC.currentUser != null;
      },
      otr: {
         SEND_WHITESPACE_TAG: true,
         WHITESPACE_START_AKE: true
      },
      defaultAvatar: function(jid) {
         var cache = jsxc.storage.getUserItem('defaultAvatars') || {};

         $(this).each(function() {
            var user = jid.replace(/@.+/, '');
            var ie8fix = true;
            var $div = $(this).find('.jsxc_avatar');
            var size = $div.width();
            var key = user + '@' + size;

            var handleResponse = function(result) {
               if (typeof (result) === 'object') {
                  if (result.data && result.data.displayname) {
                     $div.imageplaceholder(user, result.data.displayname);
                  } else {
                     $div.imageplaceholder(user);
                  }
               } else {
                  $div.show();
                  if (ie8fix === true) {
                     $div.html('');
                  } else {
                     $div.html('');
                  }
               }
            };

            if (typeof cache[key] === 'undefined' || cache[key] === null) {
               OC.Router.registerLoadedCallback(function() {
                  var url = OC.Router.generate('core_avatar_get', {
                     user: user,
                     size: size
                  }) + '?requesttoken=' + oc_requesttoken;

                  $.get(url, function(result) {

                     var val = (typeof result === 'object') ? result : url;
                     handleResponse(val);

                     jsxc.storage.updateUserItem('defaultAvatars', key, val);
                  });
               });
            } else {
               handleResponse(cache[key]);
            }
         });
      }
   });

   // Add submit link without chat functionality
   if (jsxc.el_exists($('#body-login form'))) {

      var link = $('').text('Log in without chat').attr('href', '#').click(function() {
         jsxc.submitLoginForm();
      });

      var alt = $('
').append(link);
      $('#body-login form fieldset').append(alt);
   }
});<commit_msg>enable otr debugging<commit_after>/* global jsxc, oc_appswebroots, OC, $, oc_requesttoken */

/**
 * Make room for the roster inside the owncloud template.
 *
 * @param {type} event
 * @param {type} state State in which the roster is
 * @param {type} duration Time the roster needs to move
 * @returns {undefined}
 */
function onRosterToggle(event, state, duration) {
   "use strict";
   var wrapper = $('#content-wrapper');
   var control = $('#controls');

   var roster_width = (state === 'shown') ? $('#jsxc_roster').outerWidth() : 0;
   var navigation_width = $('#navigation').width();

   wrapper.animate({
      paddingRight: (roster_width) + 'px'
   }, duration);
   control.animate({
      paddingRight: (roster_width + navigation_width) + 'px'
   }, duration);
}

/**
 * Init owncloud template for roster.
 *
 * @returns {undefined}
 */
function onRosterReady() {
   "use strict";
   var roster_width = $('#jsxc_roster').outerWidth();
   var navigation_width = $('#navigation').width();
   var roster_right = parseFloat($('#jsxc_roster').css('right'));

   $('#content-wrapper').css('paddingRight', roster_width + roster_right);
   $('#controls').css('paddingRight', roster_width + navigation_width + roster_right);
}

// initialization
$(function() {
   "use strict";

   $(document).on('ready.roster.jsxc', onRosterReady);
   $(document).on('toggle.roster.jsxc', onRosterToggle);

   $(document).on('connected.jsxc', function() {
      // reset default avatar cache
      jsxc.storage.removeUserItem('defaultAvatars');
   });

   jsxc.log = "";
   jsxc.tmp = null;
   jsxc.init({
      loginForm: {
         form: '#body-login form',
         jid: '#user',
         pass: '#password',
         preJid: function(jid) {
            var data = null;

            $.ajax(OC.filePath('ojsxc', 'ajax', 'getsettings.php'), {
               async: false,
               success: function(d) {
                  data = d;
               }
            });

            var resource = (data.xmppResource) ? '/' + data.xmppResource : '';
            var domain = data.xmppDomain;

            jsxc.storage.setItem('boshUrl', data.boshUrl);

            if (jid.match(/@(.*)$/)) {
               return (jid.match(/\/(.*)$/)) ? jid : jid + resource;
            }

            return jid + '@' + domain + resource;
         }
      },
      logoutElement: $('#logout'),
      checkFlash: false,
      rosterAppend: 'body',
      root: oc_appswebroots.ojsxc,
      // @TODO: don't include get turn credentials routine into jsxc
      turnCredentialsPath: OC.filePath('ojsxc', 'ajax', 'getturncredentials.php'),
      displayRosterMinimized: function() {
         return OC.currentUser != null;
      },
      otr: {
         debug: true,
         SEND_WHITESPACE_TAG: true,
         WHITESPACE_START_AKE: true
      },
      defaultAvatar: function(jid) {
         var cache = jsxc.storage.getUserItem('defaultAvatars') || {};

         $(this).each(function() {
            var user = jid.replace(/@.+/, '');
            var ie8fix = true;
            var $div = $(this).find('.jsxc_avatar');
            var size = $div.width();
            var key = user + '@' + size;

            var handleResponse = function(result) {
               if (typeof (result) === 'object') {
                  if (result.data && result.data.displayname) {
                     $div.imageplaceholder(user, result.data.displayname);
                  } else {
                     $div.imageplaceholder(user);
                  }
               } else {
                  $div.show();
                  if (ie8fix === true) {
                     $div.html('');
                  } else {
                     $div.html('');
                  }
               }
            };

            if (typeof cache[key] === 'undefined' || cache[key] === null) {
               OC.Router.registerLoadedCallback(function() {
                  var url = OC.Router.generate('core_avatar_get', {
                     user: user,
                     size: size
                  }) + '?requesttoken=' + oc_requesttoken;

                  $.get(url, function(result) {

                     var val = (typeof result === 'object') ? result : url;
                     handleResponse(val);

                     jsxc.storage.updateUserItem('defaultAvatars', key, val);
                  });
               });
            } else {
               handleResponse(cache[key]);
            }
         });
      }
   });

   // Add submit link without chat functionality
   if (jsxc.el_exists($('#body-login form'))) {

      var link = $('').text('Log in without chat').attr('href', '#').click(function() {
         jsxc.submitLoginForm();
      });

      var alt = $('
').append(link);
      $('#body-login form fieldset').append(alt);
   }
});<|endoftext|>


<commit_before>function game_state(client_speed) {
	//const game values
	var player_speed = 250;
	var client_speed = 1/30;
	var world_x = 640;
	var world_y = 480;

	//game state
	var game_time;
	var pid;
	var player;

	//world snapshots
	var from;
	var to;
	var interp;

	//player movement history and prediction errors
	var past_moves;
	var predict_err;

	this.init = function(player_id, start_time) {
		console.log('initialising game state');
		pid = player_id;
		game_time = start_time;

		this.reset();
	}

	this.reset = function() {
		player = undefined;

		from = undefined;
		to = undefined;
		interp = undefined;

		past_moves = [];

		predict_err = {
			'x':0,
			'y':0,
		}
	}

	this.extend_history = function(history) {
		if (history.length < 1) return;

		history.forEach(function (entry) {
			if (player != undefined) {
				var commands = entry.commands;

				//apply game logic to input to determine predicted player state
				commands.forEach(function (cmd) {
					apply_move(player, cmd);
				})
				apply_mouse(player, entry.mouseX, entry.mouseY);

				past_moves.push({
					'cmd_id':entry.cmd_id,
					'timestamp':game_time,
					'state':clone(player)
				})
			}
		})
	}

	function update_history() {
		//update history with prediction offset
		past_moves.forEach(function (entry) {
			entry.state.x += predict_err.x;
			entry.state.y += predict_err.y;
		})
	}

	this.state_update = function(msg) {
		window.print_msg('status', 'new state: num_players='+Object.keys(msg.state.players).length+', num_entities='+Object.keys(msg.state.entities).length);

		var snapshot = parse(msg);
		game_time = snapshot.timestamp;

		if (to == undefined) {
			//instantiate local predicted player starting position
			var sp = snapshot.state.players[pid].state;
			player = new Object;
			player.x = sp.x;
			player.y = sp.y;
			player.a = sp.a;
		}

		if (past_moves.length != 0) {
			var last_id = snapshot.state.players[pid].last_id;
			var curr_id = past_moves[past_moves.length - 1].cmd_id;
			var index = past_moves.length - (curr_id - last_id) - 1;
		}

		//reconcile last input only if the last id we received exists in our past_moves array
		if (index >= 0 && index < past_moves.length) {
			window.print_msg('reconcile', 'unacked moves: '+past_moves.length);

			var client_state = past_moves[index].state;
			var server_state = snapshot.state.players[pid].state;

			//calculate prediction errors
			predict_err.x = (client_state.x - server_state.x) * -1;
			predict_err.y = (client_state.y - server_state.y) * -1;

			if (predict_err.x != 0 || predict_err.y != 0) {
				console.log('prediction error: client=[x:'+client_state.x+',y:'+client_state.y+'], server=[x:'+server_state.x+',y:'+server_state.y+'], predict_err[x:'+predict_err.x+',y:'+predict_err.y+']')
				//apply non-zero prediction errors and update past move history to match
				player.x += predict_err.x;
				player.y += predict_err.y;
				update_history();
			}

			window.print_msg('offset', 'current offset: x='+predict_err.x+', y='+predict_err.y);

			past_moves = past_moves.slice(index + 1);
		}

		from = clone(to);
		to = snapshot;
		interp = clone(from);
	}
	var elapsed = 1.2;
	this.next_frame = function(dt) {
		elapsed += dt;
		if (elapsed > 1.0) {
			window.print_msg('game_time', 'game_time='+Number(game_time).toFixed(2)+', fps='+Number(1/dt).toFixed(2));
			elapsed = 0.0;
		}

		game_time += dt;

		//we cannot return an interpolated frame if from and to snapshots don't exist
		if (from == undefined || to == undefined) return;

		//debug prediction info
		var debug_str = 'local: [x: ' + Math.floor(player.x) +
			', y: ' + Math.floor(player.y) +
			', angle: ' + player.a +
			', mouseX: ' + window.input.mouseX() +
			', mouseY: ' + window.input.mouseY() + ']';
		window.print_msg('local_predict', debug_str);

		interp.timestamp += dt;
		var frac_t = ((interp.timestamp - from.timestamp) / (to.timestamp - from.timestamp));

		//interpolate players
		for (var key in interp.state.players) {
			if (to.state.players.hasOwnProperty(key)) {
				//get player if it exists in both from and to
				var server_player = interp.state.players[key].state;
				var fp = from.state.players[key].state;
				var tp = to.state.players[key].state;

				//tween translation
				server_player.x = tween(fp.x, tp.x, frac_t);
				server_player.y = tween(fp.y, tp.y, frac_t);

				//tween rotation
				server_player.a = tween_rot(fp.a, tp.a, frac_t);
			}
		}

		var debug_key;
		//interpolate entities
		for (var key in interp.state.entities) {
			if (debug_key == undefined) debug_key = key;
			if (to.state.entities.hasOwnProperty(key)) {
				var server_entity = interp.state.entities[key];
				var fe = from.state.entities[key];
				var te = to.state.entities[key];

				server_entity.x = tween(fe.x, te.x, frac_t);
				server_entity.y = tween(fe.y, te.y, frac_t);
			}
		}

		//print out info on the debug key
		if (debug_key && to.state.entities.hasOwnProperty(debug_key)) {
			var ie = interp.state.entities[debug_key];
			fe = from.state.entities[debug_key];
			te = to.state.entities[debug_key];

			console.log('ie[x='+ie.x+',y='+ie.y+'], fe[x='+fe.x+',y='+fe.y+'], te[x='+te.x+',y='+te.y+']'+', frac_t='+frac_t);

		}

		//add predicted player to the frame object and interpolate errors
		var predicted_player = clone(player);
		predicted_player.pid = pid;
		interp.predicted_player = predicted_player;

		//TO DO: check collisions and update animations

		return interp;
	}

	function tween(f, t, frac) {
		if (frac > 1.0) return t;
		return Math.round(f + ((t - f) * frac));
	}

	function tween_rot(f, t, frac) {
		if (frac > 1.0) return t;
		var diff = t - f;
		if (diff < -Math.PI) diff += 2*Math.PI;
		if (diff > Math.PI) diff -= 2*Math.PI;
		return (f + (diff * frac));
	}

	function parse(msg) {
		if (typeof msg != 'string') {
			return msg;
		} else {
			//TO DO - only use if using a custom game state representation
			return;
		}
	}

	function apply_move(obj, move) {
		var dist = Math.floor(player_speed * client_speed);
		if (move == 'UP')    obj.y -= dist;
		if (move == 'DOWN')  obj.y += dist;
		if (move == 'LEFT')  obj.x -= dist;
		if (move == 'RIGHT') obj.x += dist;

		if (obj.x < 0)       obj.x = 0;
		if (obj.x > world_x) obj.x = world_x;
		if (obj.y < 0)       obj.y = 0;
		if (obj.y > world_y) obj.y = world_y;
	}

	function apply_mouse(obj, mx, my) {
		obj.a = Math.atan2((mx-obj.x), (my-obj.y));
	}

	function clone(obj) {
		if (obj != undefined) {
			return JSON.parse(JSON.stringify(obj));
		}
	}
}<commit_msg>comment out debug code<commit_after>function game_state(client_speed) {
	//const game values
	var player_speed = 250;
	var client_speed = 1/30;
	var world_x = 640;
	var world_y = 480;

	//game state
	var game_time;
	var pid;
	var player;

	//world snapshots
	var from;
	var to;
	var interp;

	//player movement history and prediction errors
	var past_moves;
	var predict_err;

	this.init = function(player_id, start_time) {
		console.log('initialising game state');
		pid = player_id;
		game_time = start_time;

		this.reset();
	}

	this.reset = function() {
		player = undefined;

		from = undefined;
		to = undefined;
		interp = undefined;

		past_moves = [];

		predict_err = {
			'x':0,
			'y':0,
		}
	}

	this.extend_history = function(history) {
		if (history.length < 1) return;

		history.forEach(function (entry) {
			if (player != undefined) {
				var commands = entry.commands;

				//apply game logic to input to determine predicted player state
				commands.forEach(function (cmd) {
					apply_move(player, cmd);
				})
				apply_mouse(player, entry.mouseX, entry.mouseY);

				past_moves.push({
					'cmd_id':entry.cmd_id,
					'timestamp':game_time,
					'state':clone(player)
				})
			}
		})
	}

	function update_history() {
		//update history with prediction offset
		past_moves.forEach(function (entry) {
			entry.state.x += predict_err.x;
			entry.state.y += predict_err.y;
		})
	}

	this.state_update = function(msg) {
		window.print_msg('status', 'new state: num_players='+Object.keys(msg.state.players).length+', num_entities='+Object.keys(msg.state.entities).length);

		var snapshot = parse(msg);
		game_time = snapshot.timestamp;

		if (to == undefined) {
			//instantiate local predicted player starting position
			var sp = snapshot.state.players[pid].state;
			player = new Object;
			player.x = sp.x;
			player.y = sp.y;
			player.a = sp.a;
		}

		if (past_moves.length != 0) {
			var last_id = snapshot.state.players[pid].last_id;
			var curr_id = past_moves[past_moves.length - 1].cmd_id;
			var index = past_moves.length - (curr_id - last_id) - 1;
		}

		//reconcile last input only if the last id we received exists in our past_moves array
		if (index >= 0 && index < past_moves.length) {
			window.print_msg('reconcile', 'unacked moves: '+past_moves.length);

			var client_state = past_moves[index].state;
			var server_state = snapshot.state.players[pid].state;

			//calculate prediction errors
			predict_err.x = (client_state.x - server_state.x) * -1;
			predict_err.y = (client_state.y - server_state.y) * -1;

			if (predict_err.x != 0 || predict_err.y != 0) {
				console.log('prediction error: client=[x:'+client_state.x+',y:'+client_state.y+'], server=[x:'+server_state.x+',y:'+server_state.y+'], predict_err[x:'+predict_err.x+',y:'+predict_err.y+']')
				//apply non-zero prediction errors and update past move history to match
				player.x += predict_err.x;
				player.y += predict_err.y;
				update_history();
			}

			window.print_msg('offset', 'current offset: x='+predict_err.x+', y='+predict_err.y);

			past_moves = past_moves.slice(index + 1);
		}

		from = clone(to);
		to = snapshot;
		interp = clone(from);
	}
	var elapsed = 1.2;
	this.next_frame = function(dt) {
		elapsed += dt;
		if (elapsed > 1.0) {
			window.print_msg('game_time', 'game_time='+Number(game_time).toFixed(2)+', fps='+Number(1/dt).toFixed(2));
			elapsed = 0.0;
		}

		game_time += dt;

		//we cannot return an interpolated frame if from and to snapshots don't exist
		if (from == undefined || to == undefined) return;

		//debug prediction info
		var debug_str = 'local: [x: ' + Math.floor(player.x) +
			', y: ' + Math.floor(player.y) +
			', angle: ' + player.a +
			', mouseX: ' + window.input.mouseX() +
			', mouseY: ' + window.input.mouseY() + ']';
		window.print_msg('local_predict', debug_str);

		interp.timestamp += dt;
		var frac_t = ((interp.timestamp - from.timestamp) / (to.timestamp - from.timestamp));

		//interpolate players
		for (var key in interp.state.players) {
			if (to.state.players.hasOwnProperty(key)) {
				//get player if it exists in both from and to
				var server_player = interp.state.players[key].state;
				var fp = from.state.players[key].state;
				var tp = to.state.players[key].state;

				//tween translation
				server_player.x = tween(fp.x, tp.x, frac_t);
				server_player.y = tween(fp.y, tp.y, frac_t);

				//tween rotation
				server_player.a = tween_rot(fp.a, tp.a, frac_t);
			}
		}

		var debug_key;
		//interpolate entities
		for (var key in interp.state.entities) {
			if (debug_key == undefined) debug_key = key;
			if (to.state.entities.hasOwnProperty(key)) {
				var server_entity = interp.state.entities[key];
				var fe = from.state.entities[key];
				var te = to.state.entities[key];

				server_entity.x = tween(fe.x, te.x, frac_t);
				server_entity.y = tween(fe.y, te.y, frac_t);
			}
		}

		//print out info on the debug key
		if (debug_key && to.state.entities.hasOwnProperty(debug_key)) {
			var ie = interp.state.entities[debug_key];
			fe = from.state.entities[debug_key];
			te = to.state.entities[debug_key];

			//console.log('ie[x='+ie.x+',y='+ie.y+'], fe[x='+fe.x+',y='+fe.y+'], te[x='+te.x+',y='+te.y+']'+', frac_t='+frac_t);

		}

		//add predicted player to the frame object and interpolate errors
		var predicted_player = clone(player);
		predicted_player.pid = pid;
		interp.predicted_player = predicted_player;

		//TO DO: check collisions and update animations

		return interp;
	}

	function tween(f, t, frac) {
		if (frac > 1.0) return t;
		return Math.round(f + ((t - f) * frac));
	}

	function tween_rot(f, t, frac) {
		if (frac > 1.0) return t;
		var diff = t - f;
		if (diff < -Math.PI) diff += 2*Math.PI;
		if (diff > Math.PI) diff -= 2*Math.PI;
		return (f + (diff * frac));
	}

	function parse(msg) {
		if (typeof msg != 'string') {
			return msg;
		} else {
			//TO DO - only use if using a custom game state representation
			return;
		}
	}

	function apply_move(obj, move) {
		var dist = Math.floor(player_speed * client_speed);
		if (move == 'UP')    obj.y -= dist;
		if (move == 'DOWN')  obj.y += dist;
		if (move == 'LEFT')  obj.x -= dist;
		if (move == 'RIGHT') obj.x += dist;

		if (obj.x < 0)       obj.x = 0;
		if (obj.x > world_x) obj.x = world_x;
		if (obj.y < 0)       obj.y = 0;
		if (obj.y > world_y) obj.y = world_y;
	}

	function apply_mouse(obj, mx, my) {
		obj.a = Math.atan2((mx-obj.x), (my-obj.y));
	}

	function clone(obj) {
		if (obj != undefined) {
			return JSON.parse(JSON.stringify(obj));
		}
	}
}<|endoftext|>


<commit_before>$(document).ready(function () {
    $('#orders-filter').change(function(){
        var string = $('#orders-filter').val();
        $.post( Yii.app.createUrl('admin/ajaxGetOrders'),
            {
                filter: string
            })
            .done(function(response){filter(response)});

    });
    $('#do-filter').click(function(e){
        var string = $('#orders-filter').val();
        doFiltration(string);

    });
    $(document).on('click', '.order-short', function(){
        orderShortClick($(this));
    });
    $(document).on('click', 'button.add-problem', function(){
        var orderId = $('table.order-details-table').attr('order-id');

        var data = {
            orderId: orderId,
            problemId: $('select.new-problem-select').val()
        };

        $.post( Yii.app.createUrl('order/ajaxAddProblemToOrder'),
            {
                data: JSON.stringify(data)
            })
            .done(function(response){problemAdded(response)});

    });
    $(document).on('click', '.save-order', function(){

        var problemStatuses = [];
        var orderId = $(this).attr('order-id');
        var mastakId = $('#mastak-id').val();

        var tbody = $('table[order-id=' + orderId + ']');

        $(tbody.find('.problem-status-select')).each(function(){
            var orderProblemId = $(this).attr('order-problem-id');

            problemStatuses.push({
                status: $(this).val(),
                discount: $('tr[order-problem-id=' + orderProblemId +'] input.discount').val(),
                id: orderProblemId
            });
        });

        var orderStatus = tbody.find('#orderStatus').val();
        var discount = tbody.find('.discount').val();

        var data = {
            orderId: orderId,
            mastakId: mastakId,
            problemStatuses: problemStatuses,
            orderStatus: orderStatus
        };

        $.post( Yii.app.createUrl('order/ajaxSaveOrder'),
            {
                data: JSON.stringify(data)
            })
            .done(function(response){orderSaved(response)});
    });

    $(document).on('click', '.delete-order-problem', function(){
        if (confirm('Удалить?')) {
            var orderProblem = $(this).parent().parent();
            var orderProblemId = $(this).attr('order-problem-id');

            $.post( Yii.app.createUrl('order/deleteOrderProblem'),
                {
                    orderProblemId: orderProblemId
                })
                .done(function(response){
                    response = JSON.parse(response);

                    var table = $('table.order-details-table[order-id="' + response.orderId + '"]');

                    table.find('span.price').text(response.totalPrice);
                    table.find('span.total-discount').text(response.totalDiscount);
                    orderProblem.remove();
                    $('td.main-td').attr('rowspan', parseInt($('td.main-td').attr('rowspan')) - 1);
                });
        }
    });

    $(document).on('click', '#order-add-comment', function(){
        $.post( Yii.app.createUrl('ajax/addOrderComment'),
            {
                id: $('.order-details-table').attr('order-id'),
                content: $('#order-comment-content').val()
            })
            .done(function(response){
                response = JSON.parse(response);

                if($('.order-comments table tr').length > 0)
                    $('.order-comments table tr:last').after('
'+ response.date + '	'+ response.content + '
');
                else
                    $('.order-comments table').html('
'+ response.date + '	'+ response.content + '
');

                $('#order-comment-content').val('');
            });
    });
});

function orderSaved(data)
{
    data = JSON.parse(data);

    if(data.result == 'SUCCESS')
    {
        $('table[order-id=' + data.orderId + '] span.price').text(data.newPrice);
        $('table[order-id=' + data.orderId + '] span.total-discount').text(data.newDiscount);
        $('table[order-id=' + data.orderId + '] a.save-order').attr('disabled', 'disabled').removeClass('btn-success').addClass('btn-default');
        doFiltration($('#orders-filter').val());
    }
}

function problemAdded(data)
{
    data = JSON.parse(data);
    $('td.main-td').attr('rowspan', parseInt($('td.main-td').attr('rowspan')) + 1);
    var html = '
' + data.position + '	' + data.device + '	' + data.name + '	' + data.price + '	' + data.discount + '	' + data.status + '
';

    $('table.order-details-table tr.problem-row:last').after(html);
}

function orderDetails(data)
{
    data = JSON.parse(data);
    $('.order-table-container').html(data.output);
    $('.order-comments').html(data.comments);
    $('.order-review-form').removeClass('hidden');

    drawProblemsDropdown(data.problems);

    $('.problem-status-select,.order-status-select,.discount,#mastak-id').change(function(){
        $('table.order-details-table a.save-order').removeAttr('disabled').removeClass('btn-default').addClass('btn-success');
    });
}

function orderShortClick(order)
{
    $.post( Yii.app.createUrl('order/ajaxGetOrder'),
        {
            id: order.attr('order-id')
        })
        .done(function(response){orderDetails(response)});
}

function doFiltration(string)
{

    $.post( Yii.app.createUrl('order/ajaxGetOrders'),
        {
            filter: string,
            status: $('#select-orders-status').val()
        })
        .done(function(response){$('.orders-table-container').html(response)});
}

function drawProblemsDropdown(problems)
{
    var html = '<button class="btn btn-warning add-problem col-md-2">Добавить работу</button>';
    html += '
<select class="form-control col-md-10 new-problem-select">';
    $.each(problems, function(key, value){
        html += '<option value="' + key + '">' + value + '</option>';
    });
    html += '</select>
';
    $('#problems-dropdown-container').html(html);
}<commit_msg>Фиксы<commit_after>$(document).ready(function () {
    $('#orders-filter').change(function(){
        var string = $('#orders-filter').val();
        $.post( Yii.app.createUrl('admin/ajaxGetOrders'),
            {
                filter: string
            })
            .done(function(response){filter(response)});

    });
    $('#do-filter').click(function(e){
        var string = $('#orders-filter').val();
        doFiltration(string);

    });
    $(document).on('click', '.order-short', function(){
        orderShortClick($(this));
    });
    $(document).on('click', 'button.add-problem', function(){
        var orderId = $('table.order-details-table').attr('order-id');

        var data = {
            orderId: orderId,
            problemId: $('select.new-problem-select').val()
        };

        $.post( Yii.app.createUrl('order/ajaxAddProblemToOrder'),
            {
                data: JSON.stringify(data)
            })
            .done(function(response){problemAdded(response)});

    });
    $(document).on('click', '.save-order', function(){

        var problemStatuses = [];
        var orderId = $(this).attr('order-id');
        var mastakId = $('#mastak-id').val();

        var tbody = $('table[order-id=' + orderId + ']');

        $(tbody.find('.problem-status-select')).each(function(){
            var orderProblemId = $(this).attr('order-problem-id');

            problemStatuses.push({
                status: $(this).val(),
                discount: $('tr[order-problem-id=' + orderProblemId +'] input.discount').val(),
                id: orderProblemId
            });
        });

        var orderStatus = tbody.find('#orderStatus').val();
        var discount = tbody.find('.discount').val();

        var data = {
            orderId: orderId,
            mastakId: mastakId,
            problemStatuses: problemStatuses,
            orderStatus: orderStatus
        };

        $.post( Yii.app.createUrl('order/ajaxSaveOrder'),
            {
                data: JSON.stringify(data)
            })
            .done(function(response){orderSaved(response)});
    });

    $(document).on('click', '.delete-order-problem', function(){
        if (confirm('Удалить?')) {
            var orderProblem = $(this).parent().parent();
            var orderProblemId = $(this).attr('order-problem-id');

            $.post( Yii.app.createUrl('order/deleteOrderProblem'),
                {
                    orderProblemId: orderProblemId
                })
                .done(function(response){
                    response = JSON.parse(response);

                    var table = $('table.order-details-table[order-id="' + response.orderId + '"]');

                    table.find('span.price').text(response.totalPrice);
                    table.find('span.total-discount').text(response.totalDiscount);
                    orderProblem.remove();
                    $('td.main-td').attr('rowspan', parseInt($('td.main-td').attr('rowspan')) - 1);
                });
        }
    });

    $(document).on('click', '#order-add-comment', function(){
        $.post( Yii.app.createUrl('ajax/addOrderComment'),
            {
                id: $('.order-details-table').attr('order-id'),
                content: $('#order-comment-content').val()
            })
            .done(function(response){
                response = JSON.parse(response);

                if($('.order-comments table tr').length > 0)
                    $('.order-comments table tr:last').after('
'+ response.date + '	'+ response.content + '
');
                else
                    $('.order-comments table').html('
'+ response.date + '	'+ response.content + '
');

                $('#order-comment-content').val('');
            });
    });

    $(document).on('change', '.problem-status-select,.order-status-select,.discount,#mastak-id', function(){
        $('table.order-details-table a.save-order').removeAttr('disabled').removeClass('btn-default').addClass('btn-success');
    });
});

function orderSaved(data)
{
    data = JSON.parse(data);

    if(data.result == 'SUCCESS')
    {
        $('table[order-id=' + data.orderId + '] span.price').text(data.newPrice);
        $('table[order-id=' + data.orderId + '] span.total-discount').text(data.newDiscount);
        $('table[order-id=' + data.orderId + '] a.save-order').attr('disabled', 'disabled').removeClass('btn-success').addClass('btn-default');
        doFiltration($('#orders-filter').val());
    }
}

function problemAdded(data)
{
    data = JSON.parse(data);
    $('td.main-td').attr('rowspan', parseInt($('td.main-td').attr('rowspan')) + 1);
    var html = '
' + data.position + '	' + data.device + '	' + data.name + '	' + data.price + '	' + data.discount + '	' + data.status + '
';

    $('table.order-details-table tr.problem-row:last').after(html);
}

function orderDetails(data)
{
    data = JSON.parse(data);
    $('.order-table-container').html(data.output);
    $('.order-comments').html(data.comments);
    $('.order-review-form').removeClass('hidden');

    drawProblemsDropdown(data.problems);
}

function orderShortClick(order)
{
    $.post( Yii.app.createUrl('order/ajaxGetOrder'),
        {
            id: order.attr('order-id')
        })
        .done(function(response){orderDetails(response)});
}

function doFiltration(string)
{

    $.post( Yii.app.createUrl('order/ajaxGetOrders'),
        {
            filter: string,
            status: $('#select-orders-status').val()
        })
        .done(function(response){$('.orders-table-container').html(response)});
}

function drawProblemsDropdown(problems)
{
    var html = '<button class="btn btn-warning add-problem col-md-2">Добавить работу</button>';
    html += '
<select class="form-control col-md-10 new-problem-select">';
    $.each(problems, function(key, value){
        html += '<option value="' + key + '">' + value + '</option>';
    });
    html += '</select>
';
    $('#problems-dropdown-container').html(html);
}<|endoftext|>


<commit_before>var pagination = require('hexo-pagination');
var _ = require('lodash');

hexo.extend.generator.register('category', function(locals) {
	var config = this.config;
	var categories = locals.data.categories;
	var result = [];

	_.each(categories, function(category, title) {
		_.each(category, function(data, lang) {
			var catData = getCategoryByName(locals.categories, data.category);
			result = result.concat(pagination(
				lang + '/' + data.slug,
				catData != null ? catData.posts : [], {
					perPage: _c('category_generator.per_page', lang, config, locals) || _c('per_page', lang, config, locals),
					layout: ['category', 'archive', 'index'],
					format: _c('pagination_dir', lang, config, locals) + '/%d/',
					data: {
						lang: lang,
						title: data.name,
						category: data.category,
						alternates: getAlternateCategories(category),
						is_category: true
					}
				}
			));
		});
	});

	return result;
});

hexo.extend.generator.register('posts', function(locals) {
	var posts = locals.posts.sort('-date').toArray();
	var length = posts.length;

	return posts.map(function(post, i) {
		var layout = post.layout;
		var path = post.path;

		if (!layout || layout === 'false') {
			return {
				path: path,
				data: post.content
			};
		} else {
			if (i) post.prev = posts[i - 1];
			if (i < length - 1) post.next = posts[i + 1];

			var layouts = ['post', 'page', 'index'];
			if (layout !== 'post') layouts.unshift(layout);

			if (post.label && post.lang) {
				post.alternates = getAlternatePosts(posts, post.label)
			}

			post.is_post = true;

			return {
				path: path,
				layout: layouts,
				data: post
			};
		}
	});
});

hexo.extend.generator.register('index', function(locals) {
	var result = [];
	var config = this.config;
	_.forEach(config.language, function(lang, n) {
		if (n == 0) {
			result = result.concat({
				path: '',
				data: {
					redirect: lang
				},
				layout: ['redirect']
			});
		}
		if (lang != 'default') {
			result = result.concat(
				pagination(lang, locals.posts.sort('-date').toArray().filter(
					function(post) {
						return post.lang == lang;
					}), {
					perPage: _c('per_page', lang, config, locals),
					layout: ['index'],
					format: _c('pagination_dir', lang, config, locals) + '/%d/',
					data: {
						lang: lang,
						title: _c('title', lang, config, locals),
						alternates: getAlternateIndices(config, locals),
						is_index: true
					}
				})
			);
		}
	});
	return result;
});

hexo.extend.generator.register('feed', function(locals) {
	var result = [];
	var config = this.config;
	_.forEach(config.language, function(lang) {
		if (lang != 'default') {
			result.push({
				path: lang + '/feed.xml',
				data: {
					title: _c('title', lang, config, locals),
					lang: lang,
					posts: locals.posts.sort('-updated').filter(function(post) {
						return post.lang == lang;
					}),
					is_feed: true
				},
				layout: ['rss2']
			})
		}
	});
	return result;
});

hexo.extend.generator.register('archive', function(locals) {
	var config = this.config;
	var archiveDir = config.archive_dir;
	var paginationDir = config.pagination_dir || 'page';
	var allPosts = locals.posts.sort('-date');
	var perPage = config.archive != undefined ? config.archive_generator.per_page : 0;
	var result = [];

	if (!allPosts.length) return;

	if (archiveDir[archiveDir.length - 1] !== '/') archiveDir += '/';

	function generate(path, posts, options){
		options = options || {};
		options.archive = true;

		result = result.concat(pagination(path, posts, {
			perPage: perPage,
			layout: ['archive', 'index'],
			format: paginationDir + '/%d/',
			data: options
		}));
	}

	generate(archiveDir, allPosts);

	if (config.archive_generator == undefined || !config.archive_generator.yearly) return result;

	var posts = {};

	// Organize posts by date
	allPosts.forEach(function(post){
		var date = post.date;
		var year = date.year();
		var month = date.month() + 1; // month is started from 0

		if (!posts.hasOwnProperty(year)){
			// 13 arrays. The first array is for posts in this year
			// and the other arrays is for posts in this month
			posts[year] = [
				[], [], [], [], [], [], [], [], [], [], [], [], []
			];
		}

		posts[year][0].push(post);
		posts[year][month].push(post);
	});

	var Query = this.model('Post').Query;
	var years = Object.keys(posts);
	var year, data, month, monthData, url;

	// Yearly
	for (var i = 0, len = years.length; i < len; i++){
		year = +years[i];
		data = posts[year];
		url = archiveDir + year + '/';
		if (!data[0].length) continue;

		generate(url, new Query(data[0]), {year: year});

		if (config.archive_generator == undefined || !config.archive_generator.monthly) continue;

		// Monthly
		for (month = 1; month <= 12; month++){
			monthData = data[month];
			if (!monthData.length) continue;

			generate(url + (month < 10 ? '0' + month : month) + '/', new Query(monthData), {
				year: year,
				month: month
			});
		}
	}

	return result;
});

function getCategoryByName(categories, name) {
	return categories.toArray().filter(function(category) {
		return category.name == name;
	})[0];
}

function getAlternateCategories(category) {
	var result = [];
	_.each(category, function(data, lang) {
		result.push({
			title: data.name,
			lang: lang,
			path: lang + '/' + data.slug
		});
	});
	return result;
}

function getAlternatePosts(posts, label) {
	var alternates = posts.filter(function(post) {
		return post.label == label;
	});
	var result = [];
	_.each(alternates, function(post) {
		result.push({
			title: post.title,
			lang: post.lang,
			path: post.path
		});
	});
	return result;
}

function getAlternateIndices(config, locals) {
	var result = [];
	_.each(config.language, function(lang) {
		if (lang != 'default') {
			result.push({
				title: _c('title', lang, config, locals),
				lang: lang,
				path: lang
			});
		}
	});
	return result;
}

function _c(string, lang, config, locals) {
	if (locals.data['config_' + lang] != null) {
		return path(locals.data['config_' + lang], string) || path(config, string);
	}
	return path(config, string);
}

/**
 * Retrieve nested item from object/array (http://stackoverflow.com/a/16190716)
 * @param {Object|Array} obj
 * @param {String} path dot separated
 * @param {*} def default value ( if result undefined )
 * @returns {*}
 */
function path(obj, path, def) {
	var i, len;
	for (i = 0, path = path.split('.'), len = path.length; i < len; i++) {
		if (!obj || typeof obj !== 'object') return def;
		obj = obj[path[i]];
	}
	if (obj === undefined) return def;
	return obj;
}
<commit_msg>Remove archive generator<commit_after>var pagination = require('hexo-pagination');
var _ = require('lodash');

hexo.extend.generator.register('category', function(locals) {
	var config = this.config;
	var categories = locals.data.categories;
	var result = [];

	_.each(categories, function(category, title) {
		_.each(category, function(data, lang) {
			var catData = getCategoryByName(locals.categories, data.category);
			result = result.concat(pagination(
				lang + '/' + data.slug,
				catData != null ? catData.posts : [], {
					perPage: _c('category_generator.per_page', lang, config, locals) || _c('per_page', lang, config, locals),
					layout: ['category', 'archive', 'index'],
					format: _c('pagination_dir', lang, config, locals) + '/%d/',
					data: {
						lang: lang,
						title: data.name,
						category: data.category,
						alternates: getAlternateCategories(category),
						is_category: true
					}
				}
			));
		});
	});

	return result;
});

hexo.extend.generator.register('posts', function(locals) {
	var posts = locals.posts.sort('-date').toArray();
	var length = posts.length;

	return posts.map(function(post, i) {
		var layout = post.layout;
		var path = post.path;

		if (!layout || layout === 'false') {
			return {
				path: path,
				data: post.content
			};
		} else {
			if (i) post.prev = posts[i - 1];
			if (i < length - 1) post.next = posts[i + 1];

			var layouts = ['post', 'page', 'index'];
			if (layout !== 'post') layouts.unshift(layout);

			if (post.label && post.lang) {
				post.alternates = getAlternatePosts(posts, post.label)
			}

			post.is_post = true;

			return {
				path: path,
				layout: layouts,
				data: post
			};
		}
	});
});

hexo.extend.generator.register('index', function(locals) {
	var result = [];
	var config = this.config;
	_.forEach(config.language, function(lang, n) {
		if (n == 0) {
			result = result.concat({
				path: '',
				data: {
					redirect: lang
				},
				layout: ['redirect']
			});
		}
		if (lang != 'default') {
			result = result.concat(
				pagination(lang, locals.posts.sort('-date').toArray().filter(
					function(post) {
						return post.lang == lang;
					}), {
					perPage: _c('per_page', lang, config, locals),
					layout: ['index'],
					format: _c('pagination_dir', lang, config, locals) + '/%d/',
					data: {
						lang: lang,
						title: _c('title', lang, config, locals),
						alternates: getAlternateIndices(config, locals),
						is_index: true
					}
				})
			);
		}
	});
	return result;
});

hexo.extend.generator.register('feed', function(locals) {
	var result = [];
	var config = this.config;
	_.forEach(config.language, function(lang) {
		if (lang != 'default') {
			result.push({
				path: lang + '/feed.xml',
				data: {
					title: _c('title', lang, config, locals),
					lang: lang,
					posts: locals.posts.sort('-updated').filter(function(post) {
						return post.lang == lang;
					}),
					is_feed: true
				},
				layout: ['rss2']
			})
		}
	});
	return result;
});

function getCategoryByName(categories, name) {
	return categories.toArray().filter(function(category) {
		return category.name == name;
	})[0];
}

function getAlternateCategories(category) {
	var result = [];
	_.each(category, function(data, lang) {
		result.push({
			title: data.name,
			lang: lang,
			path: lang + '/' + data.slug
		});
	});
	return result;
}

function getAlternatePosts(posts, label) {
	var alternates = posts.filter(function(post) {
		return post.label == label;
	});
	var result = [];
	_.each(alternates, function(post) {
		result.push({
			title: post.title,
			lang: post.lang,
			path: post.path
		});
	});
	return result;
}

function getAlternateIndices(config, locals) {
	var result = [];
	_.each(config.language, function(lang) {
		if (lang != 'default') {
			result.push({
				title: _c('title', lang, config, locals),
				lang: lang,
				path: lang
			});
		}
	});
	return result;
}

function _c(string, lang, config, locals) {
	if (locals.data['config_' + lang] != null) {
		return path(locals.data['config_' + lang], string) || path(config, string);
	}
	return path(config, string);
}

/**
 * Retrieve nested item from object/array (http://stackoverflow.com/a/16190716)
 * @param {Object|Array} obj
 * @param {String} path dot separated
 * @param {*} def default value ( if result undefined )
 * @returns {*}
 */
function path(obj, path, def) {
	var i, len;
	for (i = 0, path = path.split('.'), len = path.length; i < len; i++) {
		if (!obj || typeof obj !== 'object') return def;
		obj = obj[path[i]];
	}
	if (obj === undefined) return def;
	return obj;
}
<|endoftext|>


<commit_before>$(document).ready(function(){
    // the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered
    $('.modal').modal();
  });

function MenuItem(id,longName,price){
    this.id = id;
    this.longName = longName;
    this.price = price;
  }

var basket=[];
var ul = document.getElementById("basketItems");
var li = document.createElement("li");

var ribs = new MenuItem("ribs", "Spare Ribs in Barbecue Sauce", 4.60);
var ccm = new MenuItem("ccm", "Chicken Chow Mein", 4.20);
var cfr = new MenuItem("cfr", "Chicken Fried Rice", 4.20);
var cc = new MenuItem("cc", "Curry Chicken", 4.70);
var ssc = new MenuItem("ssc", "Sweet and Sour Chicken Crispy Balls", 4.00);

var basketTotal =document.getElementById("basketTotal");
var ribbutton=document.getElementById("ribs");
var ccmbutton=document.getElementById("ccm");
var cfrbutton=document.getElementById("cfr");
var ccbutton=document.getElementById("cc");
var sscbutton=document.getElementById("ssc");

ribbutton.onclick = function(){addToBasket(ribs)}
ccmbutton.onclick = function(){addToBasket(ccm)}
cfrbutton.onclick = function(){addToBasket(cfr)}
ccbutton.onclick = function(){addToBasket(cc)}
sscbutton.onclick = function(){addToBasket(ssc)}

function addToBasket(item){
    basket.push(item);
    Materialize.toast(item.longName + " added to basket", 4000);
    basketTotal.innerHTML=("("+basket.length+")")
    li.appendChild(document.createTextNode("Element 4"));
}
<commit_msg>basket<commit_after>$(document).ready(function(){
    // the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered
    $('.modal').modal();
  });

function MenuItem(id,longName,price){
    this.id = id;
    this.longName = longName;
    this.price = price;
  }

var basket=[];
var ul = document.getElementById("basketItems");
var li = document.createElement("li");

var ribs = new MenuItem("ribs", "Spare Ribs in Barbecue Sauce", 4.60);
var ccm = new MenuItem("ccm", "Chicken Chow Mein", 4.20);
var cfr = new MenuItem("cfr", "Chicken Fried Rice", 4.20);
var cc = new MenuItem("cc", "Curry Chicken", 4.70);
var ssc = new MenuItem("ssc", "Sweet and Sour Chicken Crispy Balls", 4.00);

var basketTotal =document.getElementById("basketTotal");
var ribbutton=document.getElementById("ribs");
var ccmbutton=document.getElementById("ccm");
var cfrbutton=document.getElementById("cfr");
var ccbutton=document.getElementById("cc");
var sscbutton=document.getElementById("ssc");

ribbutton.onclick = function(){addToBasket(ribs)}
ccmbutton.onclick = function(){addToBasket(ccm)}
cfrbutton.onclick = function(){addToBasket(cfr)}
ccbutton.onclick = function(){addToBasket(cc)}
sscbutton.onclick = function(){addToBasket(ssc)}

function addToBasket(item){
    basket.push(item);
    Materialize.toast(item.longName + " added to basket", 4000);
    basketTotal.innerHTML=("("+basket.length+")")
    li.appendChild(document.createTextNode("Element 4"));
    ul.appendChild(li);
}
<|endoftext|>


<commit_before>/* global MO5 */

MO5.modules["WSE.assets"] = "js/assets.js";
MO5.modules["WSE.assets.Animation"] = "js/assets/Animation.js";
MO5.modules["WSE.assets.Audio"] = "js/assets/Audio.js";
MO5.modules["WSE.assets.Background"] = "js/assets/Background.js";
MO5.modules["WSE.assets.Character"] = "js/assets/Character.js";
MO5.modules["WSE.assets.Curtain"] = "js/assets/Curtain.js";
MO5.modules["WSE.assets.Imagepack"] = "js/assets/Imagepack.js";
MO5.modules["WSE.assets.Textbox"] = "js/assets/Textbox.js";
MO5.modules["WSE.assets.mixins.displayable.flash"] = "js/assets/mixins/displayable/flash.js";
MO5.modules["WSE.assets.mixins.displayable.flicker"] = "js/assets/mixins/displayable/flicker.js";
MO5.modules["WSE.assets.mixins.displayable.hide"] = "js/assets/mixins/displayable/hide.js";
MO5.modules["WSE.assets.mixins.displayable.move"] = "js/assets/mixins/displayable/move.js";
MO5.modules["WSE.assets.mixins.displayable.shake"] = "js/assets/mixins/displayable/shake.js";
MO5.modules["WSE.assets.mixins.displayable.show"] = "js/assets/mixins/displayable/show.js";

MO5.modules["WSE.commands"] = "js/commands.js";
MO5.modules["WSE.commands.alert"] = "js/commands/alert.js";
MO5.modules["WSE.commands.break"] = "js/commands/break.js";
MO5.modules["WSE.commands.choice"] = "js/commands/choice.js";
MO5.modules["WSE.commands.confirm"] = "js/commands/confirm.js";
MO5.modules["WSE.commands.do"] = "js/commands/do.js";
MO5.modules["WSE.commands.fn"] = "js/commands/fn.js";
MO5.modules["WSE.commands.global"] = "js/commands/global.js";
MO5.modules["WSE.commands.globalize"] = "js/commands/globalize.js";
MO5.modules["WSE.commands.goto"] = "js/commands/goto.js";
MO5.modules["WSE.commands.line"] = "js/commands/line.js";
MO5.modules["WSE.commands.localize"] = "js/commands/localize.js";
MO5.modules["WSE.commands.prompt"] = "js/commands/prompt.js";
MO5.modules["WSE.commands.restart"] = "js/commands/restart.js";
MO5.modules["WSE.commands.set_vars"] = "js/commands/set_vars.js";
MO5.modules["WSE.commands.sub"] = "js/commands/sub.js";
MO5.modules["WSE.commands.trigger"] = "js/commands/trigger.js";
MO5.modules["WSE.commands.var"] = "js/commands/var.js";
MO5.modules["WSE.commands.wait"] = "js/commands/wait.js";
MO5.modules["WSE.commands.while"] = "js/commands/while.js";
MO5.modules["WSE.commands.with"] = "js/commands/with.js";

MO5.modules["WSE.dataSources"] = "js/dataSources.js";
MO5.modules["WSE.dataSources.LocalStorage"] = "js/dataSources/LocalStorage.js";

MO5.modules["WSE.functions"] = "js/functions.js";

MO5.modules["WSE.tools"] = "js/tools/tools.js";
MO5.modules["WSE.tools.ui"] = "js/tools/ui.js";

MO5.modules["WSE.Keys"] = "js/Keys.js";

MO5.modules["WSE.DisplayObject"] = "js/DisplayObject.js";
MO5.modules["WSE.Game"] = "js/Game.js";
MO5.modules["WSE.Interpreter"] = "js/Interpreter.js";
MO5.modules["WSE.Trigger"] = "js/Trigger.js";
MO5.modules["WSE"] = "js/WSE.js";
<commit_msg>Changed paths.js to work from any directory.<commit_after>/* global MO5 */

(function () {

    var base = MO5.path + "../../../";

    MO5.modules["WSE.assets"] = base + "js/assets.js";
    MO5.modules["WSE.assets.Animation"] = base + "js/assets/Animation.js";
    MO5.modules["WSE.assets.Audio"] = base + "js/assets/Audio.js";
    MO5.modules["WSE.assets.Background"] = base + "js/assets/Background.js";
    MO5.modules["WSE.assets.Character"] = base + "js/assets/Character.js";
    MO5.modules["WSE.assets.Curtain"] = base + "js/assets/Curtain.js";
    MO5.modules["WSE.assets.Imagepack"] = base + "js/assets/Imagepack.js";
    MO5.modules["WSE.assets.Textbox"] = base + "js/assets/Textbox.js";
    MO5.modules["WSE.assets.mixins.displayable.flash"] =
        base + "js/assets/mixins/displayable/flash.js";
    MO5.modules["WSE.assets.mixins.displayable.flicker"] =
        base + "js/assets/mixins/displayable/flicker.js";
    MO5.modules["WSE.assets.mixins.displayable.hide"] =
        base + "js/assets/mixins/displayable/hide.js";
    MO5.modules["WSE.assets.mixins.displayable.move"] =
        base + "js/assets/mixins/displayable/move.js";
    MO5.modules["WSE.assets.mixins.displayable.shake"] =
        base + "js/assets/mixins/displayable/shake.js";
    MO5.modules["WSE.assets.mixins.displayable.show"] =
        base + "js/assets/mixins/displayable/show.js";

    MO5.modules["WSE.commands"] = base + "js/commands.js";
    MO5.modules["WSE.commands.alert"] = base + "js/commands/alert.js";
    MO5.modules["WSE.commands.break"] = base + "js/commands/break.js";
    MO5.modules["WSE.commands.choice"] = base + "js/commands/choice.js";
    MO5.modules["WSE.commands.confirm"] = base + "js/commands/confirm.js";
    MO5.modules["WSE.commands.do"] = base + "js/commands/do.js";
    MO5.modules["WSE.commands.fn"] = base + "js/commands/fn.js";
    MO5.modules["WSE.commands.global"] = base + "js/commands/global.js";
    MO5.modules["WSE.commands.globalize"] = base + "js/commands/globalize.js";
    MO5.modules["WSE.commands.goto"] = base + "js/commands/goto.js";
    MO5.modules["WSE.commands.line"] = base + "js/commands/line.js";
    MO5.modules["WSE.commands.localize"] = base + "js/commands/localize.js";
    MO5.modules["WSE.commands.prompt"] = base + "js/commands/prompt.js";
    MO5.modules["WSE.commands.restart"] = base + "js/commands/restart.js";
    MO5.modules["WSE.commands.set_vars"] = base + "js/commands/set_vars.js";
    MO5.modules["WSE.commands.sub"] = base + "js/commands/sub.js";
    MO5.modules["WSE.commands.trigger"] = base + "js/commands/trigger.js";
    MO5.modules["WSE.commands.var"] = base + "js/commands/var.js";
    MO5.modules["WSE.commands.wait"] = base + "js/commands/wait.js";
    MO5.modules["WSE.commands.while"] = base + "js/commands/while.js";
    MO5.modules["WSE.commands.with"] = base + "js/commands/with.js";

    MO5.modules["WSE.dataSources"] = base + "js/dataSources.js";
    MO5.modules["WSE.dataSources.LocalStorage"] = base + "js/dataSources/LocalStorage.js";

    MO5.modules["WSE.functions"] = base + "js/functions.js";

    MO5.modules["WSE.tools"] = base + "js/tools/tools.js";
    MO5.modules["WSE.tools.ui"] = base + "js/tools/ui.js";

    MO5.modules["WSE.Keys"] = base + "js/Keys.js";

    MO5.modules["WSE.DisplayObject"] = base + "js/DisplayObject.js";
    MO5.modules["WSE.Game"] = base + "js/Game.js";
    MO5.modules["WSE.Interpreter"] = base + "js/Interpreter.js";
    MO5.modules["WSE.Trigger"] = base + "js/Trigger.js";
    MO5.modules["WSE"] = base + "js/WSE.js";

}());
<|endoftext|>


<commit_before>/*jshint globalstrict: true*/
"use strict";

var plist = {
    color_scheme: {},
    content: "",
    indentlevel: 0,

    get: function(file_name) {
        this.content = '<?xml version="1.0" encoding="UTF-8"?>\n' +
                        '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n' +
                        '<plist version="1.0">\n' +
                        '\n';
        this.parsedict(this.color_scheme);
        this.content += '</plist>\n';
        return this.content;
    },

    isinstance: function(obj, s) {
        return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase() === s;
    },

    indent: function() {
        var i;
        for (i = 0; i < this.indentlevel; i++) {
            this.content += "    ";
        }
    },

    parsekey: function(k) {
        this.indent();
        this.content += '<key>' + k + '</key>\n';
    },

    parseitem: function(obj) {
        if (this.isinstance(obj, "string")) {
            this.parsestring(obj);
        } else if (this.isinstance(obj, "array")) {
            this.parsearray(obj);
        } else if (this.isinstance(obj, "object")) {
            this.parsedict(obj);
        }
    },

    parsearray: function(obj) {
        var i, len = obj.length;
        this.indent();
        this.content += '<array>\n';
        this.indentlevel++;
        for (i = 0; i < len; i++) {
            this.parseitem(obj[i]);
        }
        this.indentlevel--;
        this.indent();
        this.content += '</array>\n';
    },

    parsestring: function(s) {
        this.indent();
        this.content += '<string>' + s + '</string>\n';
    },

    parsedict: function(obj) {
        var keys = Object.keys(obj),
            len = keys.length,
            k, i;
        keys.sort();

        this.indent();
        this.content += '<dict>\n';
        this.indentlevel++;
        for (i = 0; i < len; i++)
        {
            k = keys[i];
            this.parsekey(k);
            this.parseitem(obj[k]);
        }
        this.indentlevel--;
        this.indent();
        this.content += '</dict>\n';
    }
},

escape_html = {
    safe_chars: {
        "&": "&",
        "<": "<",
        ">": ">",
        '"': '"',
        "'": ''',
        "/": '/'
    },
    escape: function (s) {
        return String(s).replace(/[&<>"'\/]/g, function (c) {return escape_html.safe_chars[c];});
    }
};

function extract_theme(name) {
    var text, wnd, doc,
        a = document.createElement('a');
    window.URL = window.URL || window.webkitURL;

    if (window.Blob != null && a.download != null) {
        text = new Blob([plist.get(name)], {'type':'application/octet-stream'});
        a.href = window.URL.createObjectURL(text);
        a.download = name;
        a.click();
    } else {
        text = '
' + escape_html.escape(plist.get(name)) + '
',
        wnd  = window.open('', '_blank', "status=1,toolbar=0,scrollbars=1"),
        doc  = wnd.document;
        doc.write(text);
        doc.close();
        wnd.focus();
    }
}
<commit_msg>-sort keys in a way compatible with IE<9<commit_after>/*jshint globalstrict: true*/
"use strict";

var plist = {
    color_scheme: {},
    content: "",
    indentlevel: 0,

    get: function(file_name) {
        this.content = '<?xml version="1.0" encoding="UTF-8"?>\n' +
                        '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n' +
                        '<plist version="1.0">\n' +
                        '\n';
        this.parsedict(this.color_scheme);
        this.content += '</plist>\n';
        return this.content;
    },

    isinstance: function(obj, s) {
        return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase() === s;
    },

    sortkeys: function(obj) {
        var sorted = {},
            keys = [],
            key;

        for (key in obj) {
            if (obj.hasOwnProperty(key)) {
                keys.push(key);
            }
        }
        keys.sort();
        return keys;
    },

    indent: function() {
        var i;
        for (i = 0; i < this.indentlevel; i++) {
            this.content += "    ";
        }
    },

    parsekey: function(k) {
        this.indent();
        this.content += '<key>' + k + '</key>\n';
    },

    parseitem: function(obj) {
        if (this.isinstance(obj, "string")) {
            this.parsestring(obj);
        } else if (this.isinstance(obj, "array")) {
            this.parsearray(obj);
        } else if (this.isinstance(obj, "object")) {
            this.parsedict(obj);
        }
    },

    parsearray: function(obj) {
        var i, len = obj.length;
        this.indent();
        this.content += '<array>\n';
        this.indentlevel++;
        for (i = 0; i < len; i++) {
            this.parseitem(obj[i]);
        }
        this.indentlevel--;
        this.indent();
        this.content += '</array>\n';
    },

    parsestring: function(s) {
        this.indent();
        this.content += '<string>' + s + '</string>\n';
    },

    parsedict: function(obj) {
        var keys = this.sortkeys(obj),
            len = keys.length,
            k, i;

        this.indent();
        this.content += '<dict>\n';
        this.indentlevel++;
        for (i = 0; i < len; i++)
        {
            k = keys[i];
            this.parsekey(k);
            this.parseitem(obj[k]);
        }
        this.indentlevel--;
        this.indent();
        this.content += '</dict>\n';
    }
},

escape_html = {
    safe_chars: {
        "&": "&",
        "<": "<",
        ">": ">",
        '"': '"',
        "'": ''',
        "/": '/'
    },
    escape: function (s) {
        return String(s).replace(/[&<>"'\/]/g, function (c) {return escape_html.safe_chars[c];});
    }
};

function extract_theme(name) {
    var text, wnd, doc,
        a = document.createElement('a');
    window.URL = window.URL || window.webkitURL;

    if (window.Blob != null && a.download != null) {
        text = new Blob([plist.get(name)], {'type':'application/octet-stream'});
        a.href = window.URL.createObjectURL(text);
        a.download = name;
        a.click();
    } else {
        text = '
' + escape_html.escape(plist.get(name)) + '
',
        wnd  = window.open('', '_blank', "status=1,toolbar=0,scrollbars=1"),
        doc  = wnd.document;
        doc.write(text);
        doc.close();
        wnd.focus();
    }
}
<|endoftext|>


<commit_before>//Function to create an DOM with the provided message string
//
×msgString

function notesCreateMsgBoxDom(msgString) {
	return "
×"+ msgString + "
";
}

$(function(){

	//Get elements from background script
	var notesMessageList = chrome.extension.getBackgroundPage().notesMessageListShare;
	//Add notes to the popup window
	for(var i =0; i < notesMessageList.length; i++) {
		//Add message to the notesMessage DOM div
		$("#notesMessages").append(notesCreateMsgBoxDom(notesMessageList[i]));
		//Add the position of message as data to the DOM element
		$("#notesMessages > .msgbox:last").data("notesListIndex",i.toString());
	}

    //Add click listeners for delete button
	$(".deletebtn").click(function() {
		console.log($(this).parent().data("notesListIndex"));
	});

	$("form").submit(function(){
		console.log("Form submitted");
		return false;
	});
});<commit_msg>Use message is extracted from the input form<commit_after>//Function to create an DOM with the provided message string
//
×msgString

function notesCreateMsgBoxDom(msgString) {
	return "
×"+ msgString + "
";
}

$(function(){

	//Get elements from background script
	var notesMessageList = chrome.extension.getBackgroundPage().notesMessageListShare;
	//Add notes to the popup window
	for(var i =0; i < notesMessageList.length; i++) {
		//Add message to the notesMessage DOM div
		$("#notesMessages").append(notesCreateMsgBoxDom(notesMessageList[i]));
		//Add the position of message as data to the DOM element
		$("#notesMessages > .msgbox:last").data("notesListIndex",i.toString());
	}

    //Add click listeners for delete button
	$(".deletebtn").click(function() {
		console.log($(this).parent().data("notesListIndex"));
	});

	$("form").submit(function(){
		var notesUserMessage = $("input:first").val();
		if(notesUserMessage != "") {
			console.log(notesUserMessage);
		}
		return false;
	});
});<|endoftext|>


<commit_before>$().ready(function() {
    'use strict';

    $(window).blur(function() {
        window.close;
    });

    $(window).focus();
    printBookmarks();

    $("#sort, #group, #crop").click(function(e) {
        e.preventDefault();
        toggleAllButtons();
    });

    $("#sort").click(function(e) {
        previewFunction(sort);
    });

    $("#group").click(function(e) {
        previewFunction(group);
    });

    $("#crop").click(function(e) {
        previewFunction(crop);
    });

    $("#search").keyup(function() {
        if ($("#sort").hasClass("disabled"))
            return;
        if ($(this).val().trim().length === 0) {
            printBookmarks();
        } else {
            searchBookmark($(this).val().trim());
        }
    });

    $(document).click(function(event) {
        if ($(event.target).closest("#search, #tools, #desision").length) return;
        printBookmarks();
        $("#search").val('');
        event.stopPropagation();
    });

    $("#bookmarks").on('dblclick', 'li', function(e) {
        if ($('#bookmarks').find('.editSelectedVal').length != 0)
            return;
        e.stopPropagation();
        var oldVal;

        if ($(this).children().length > 0) {
            oldVal = $(this).clone().children().remove().end().text();
            return; //TODO enable renaming folders
        } else {
            oldVal = $(this).html();
        }
        updateVal($(this), oldVal);
    });
});

var ROOT_TABS;

function printBookmarks() {
    chrome.bookmarks.getTree(function(root) {
        //console.log(root);
        $('#bookmarks').empty();
        ROOT_TABS = root[0].children.length;
        root.forEach(function(folder) {
            $('#bookmarks').append(printBookmarkFolder(folder)
                .css('padding-right', "2px"));
        });
    });
}

function printBookmarkFolder(bookmarkFolder) {
    var list = $("
");
    bookmarkFolder.children.forEach(function(bookmark) {
        if (typeof bookmark.url != 'undefined') {
            list.append(printNode(bookmark));
        } else {
            if (bookmark.children.length != 0) {
                var folder = printNodeFolder(bookmark);

                var r = $("<button type=\"submit\" class=\"dropIcon\"></button>");
                folder.prepend(r);
                folder.append(printBookmarkFolder(bookmark));
                list.append(folder);

                $(r).click(function(e) {
                    e.stopPropagation();
                    if ($(folder).find('li').is(':visible')) {
                        $(folder).children().hide();
                        $(folder).find('.dropIcon').show();
                    } else {
                        $(folder).children().show();
                    }

                });
                if (bookmark.id > ROOT_TABS) {
                    $(folder).children().hide();
                    $(folder).find('.dropIcon').show();
                }
            } else if (bookmark.id > ROOT_TABS) {
                deleteFolder(bookmark);
            }
        }
    });
    return list;
}

function deleteFolder(bookmarkFolder) {
    chrome.bookmarks.remove(bookmarkFolder.id, function() {
        console.log(bookmarkFolder.title + " removed");
    });
}

function printNode(bookmark) {
    var li = $("
")
        .css('font-weight', 'normal')
        .addClass("bLink")
        .text(bookmark.title);
    return li;
}

function printNodeFolder(bookmark) {
    var li = $("
")
        .addClass("bFolder")
        .css('font-weight', 'bold')
        .text(bookmark.title);
    return li;
}

function getHostname(url) {
    var m = url.match(/^https?\:\/\/([^\/:?#]+)(?:[\/:?#]|$)/i);
    return m ? m[0] : null;
}

function getFolderName(hostname) {
    var m = hostname.match(/:\/\/(www\.)?(.*)\./);
    return m ? m[2] : null;
}

function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

function stripPunctuation(string) {
    var punctuationless = string.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g, "");
    var finalString = punctuationless.replace(/\s{2,}/g, " ");
    return finalString;
}

function addLinksToFolder(newFolder, list, printAfter) {
    var parentId = newFolder.id;
    var name = newFolder.title;

    var length = list.length;
    $.each(list, function(key, value) {
        var subli = $("
")
            .text = value.title;

        chrome.bookmarks.move(String(value.id), {
            'parentId': parentId,
            'index': key
        }, function(done) {
            if (key == length - 1 && printAfter)
                printBookmarks();
        });
    });

}

function sortByName(a, b) {
    var aName = a.title.toLowerCase();
    var bName = b.title.toLowerCase();
    return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
}

function addBookmark(parentId, title, url) {
    chrome.bookmarks.create({
        'parentId': parentId,
        'title': title,
        'url': url
    });
}

function updateVal(currentLi, oldVal) {
    $(currentLi).html('<input class="editSelectedVal" type="text" value="' + oldVal + '" />');
    $(".editSelectedVal").focus();
    $(".editSelectedVal").keyup(function(event) {
        if (event.keyCode == 13) {
            rename(oldVal, $(".editSelectedVal").val().trim());
            $(currentLi).html($(".editSelectedVal").val().trim());
        }
    });
    $(document).click("click", function(e) {
        if ($(e.target).is(".editSelectedVal")) {
            return;
        } else {
            $(".editSelectedVal").parent("li").html(oldVal);
            $(document).unbind("click");
        }
    });
}

function previewFunction(callbackFunction) {
    var keys = {
        children: []
    };
    chrome.bookmarks.getTree(function(root) {
        root[0].children.forEach(function(folder) {
            keys.children.push(folder);
        });

        callbackFunction(keys);
        updateBookmarkListBuffer(keys);
    });
}

function updateBookmarks(list, printAfter) {
    list.children.forEach(function(folder, key) {
        if (typeof folder.url === 'undefined') {
            if (folder.create) {
                chrome.bookmarks.create({
                    'parentId': folder.parentId,
                    'title': folder.title
                }, function(e) {
                    folder.children.forEach(function(bookmark) {
                        bookmark.parentId = e.id;
                    });
                    if (key === list.children.length - 1)
                        updateBookmarks(folder, true);
                    else
                        updateBookmarks(folder, false);
                });
                return;
            } else {
                updateBookmarks(folder, false);
            }
        }

        if (folder.id <= ROOT_TABS)
            return;

        if (folder.rename) {
            chrome.bookmarks.update(String(folder.id), {
                'title': folder.title
            });
        }

        chrome.bookmarks.move(String(folder.id), {
            'parentId': folder.parentId,
            'index': key
        }, function callback() {
            if (printAfter && key === list.children.length - 1)
                printBookmarks();
        });
    });
}

function sort(list) {
    list.children.sort(sortByName);
    list.children.forEach(function(folder) {
        if (typeof folder.url === 'undefined' && folder.children.length > 0)
            sort(folder);
    });
}

function group(list) {
    var dictionary = [];
    list.children.forEach(function(folder) {
        if (typeof folder.url === 'undefined' && folder.children.length > 0 && folder.id <= ROOT_TABS) {
            group(folder);
            return;
        }
        if (typeof folder.url != 'undefined') {
            var domain = getHostname(folder.url);
            if (domain === null)
                return;

            //creates an array of results, nly have 2 cases empty or 1 element
            var result = $.grep(dictionary, function(e) {
                return e.key == domain;
            });
            //for 0 create new entry, else increment excisting entry
            if (result == 0) {
                dictionary.push({
                    key: String(domain),
                    value: 1,
                    parentId: folder.parentId,
                    folderName: String(capitalizeFirstLetter(getFolderName(domain))),
                    bookmarkList: [folder]
                });
            } else {
                result[0].value++;
                result[0].bookmarkList.push(folder);
            }
        }
    });
    $.each(dictionary, function(key, value) {
        var folderFound = false;
        if (value.value > 1) {
            dictionary[key].bookmarkList.forEach(function(bookmark) {
                var index = list.children.indexOf(bookmark);
                if (index > -1) {
                    list.children.splice(index, 1);
                }
            });
            $.each(list.children, function(index, bookmark) {
                if (typeof bookmark.url === 'undefined' && bookmark.title === value.folderName) {
                    dictionary[key].bookmarkList.forEach(function(e) {
                        e.parentId = bookmark.id;
                        bookmark.children.push(e);
                    });
                    return false;
                } else if (index === list.children.length - 1) {
                    list.children.push({
                        title: value.folderName,
                        parentId: value.parentId,
                        create: true,
                        children: dictionary[key].bookmarkList
                    });
                }
            });
        }
    });
}

function crop(list) {
    list.children.forEach(function(folder) {
        if (typeof folder.url === 'undefined' && folder.children.length > 0)
            crop(folder);

        if (typeof folder.url != 'undefined') {
            var oldTitle = folder.title;
            oldTitle = stripPunctuation(oldTitle);
            while (oldTitle.length > 70) {
                var lastSpace = oldTitle.lastIndexOf(" ");
                var firstSpace = oldTitle.indexOf(" ");
                if (lastSpace != -1 && lastSpace != firstSpace) {
                    oldTitle = oldTitle.substring(0, lastSpace);
                    folder.rename = true;
                    folder.title = oldTitle;
                } else {
                    return;
                }
            }
        }

    });
}

function updateBookmarkListBuffer(keys) {
    $('#bookmarks').empty();
    $('#bookmarks').append(printBookmarkFolder(keys));

    $('#reject').one("click", function(e) {
        e.preventDefault();
        $('#apply').unbind("click");
        printBookmarks();
        toggleAllButtons();
    });
    $('#apply').one("click", function(e) {
        e.preventDefault();
        $('#reject').unbind("click");
        updateBookmarks(keys, true);
        toggleAllButtons();
    });
}

function toggleAllButtons() {
    if ($("#sort").hasClass("disabled")) {
        $('#bookmarks').animate({
            height: 505
        }, 600);
        $(".search").slideDown(600);
        $("#decision").slideUp(500,function(){$("#decision").css('display','none');});
        $('body').animate({
            scrollTop: 1
        }, 700);
    } else {
        $(".search").slideUp(600);
        $('#bookmarks').animate({
            height: 475
        }, 600);
        $("#decision").slideDown(500);
        $('body').animate({
            scrollTop: 300
        }, 700);
    }
    toggleButtons(["#reject", "#apply"]);
    toggleButtons(["#sort", "#group", "#crop"]);
}

function toggleButtons(idList) {
    idList.forEach(function(id) {
        var button = $(id);
        if (button.hasClass("disabled")) {
            button.removeClass("disabled");
            button.addClass("active");
        } else {
            button.removeClass("active");
            button.addClass("disabled");
        }
    });
}

function searchBookmark(text) {
    var keys = {
        children: []
    };
    chrome.bookmarks.search(text, function(results) {
        $('#bookmarks').empty();
        results.forEach(function(result) {
            if (typeof result.url != 'undefined') {
                keys.children.push(result);
            }
        });
        $('#bookmarks').append(printBookmarkFolder(keys));
    });
}
<commit_msg>Rename HOTFIX<commit_after>$().ready(function() {
    'use strict';

    $(window).blur(function() {
        window.close;
    });

    $(window).focus();
    printBookmarks();

    $("#sort, #group, #crop").click(function(e) {
        e.preventDefault();
        toggleAllButtons();
    });

    $("#sort").click(function(e) {
        previewFunction(sort);
    });

    $("#group").click(function(e) {
        previewFunction(group);
    });

    $("#crop").click(function(e) {
        previewFunction(crop);
    });

    $("#search").keyup(function() {
        if ($("#sort").hasClass("disabled"))
            return;
        if ($(this).val().trim().length === 0) {
            printBookmarks();
        } else {
            searchBookmark($(this).val().trim());
        }
    });

    $(document).click(function(event) {
        if ($(event.target).closest("#search, #tools, #desision").length) return;
        printBookmarks();
        $("#search").val('');
        event.stopPropagation();
    });

    $("#bookmarks").on('dblclick', 'li', function(e) {
        if ($('#bookmarks').find('.editSelectedVal').length != 0)
            return;
        e.stopPropagation();
        var oldVal;

        if ($(this).children().length > 0) {
            oldVal = $(this).clone().children().remove().end().text();
            return; //TODO enable renaming folders
        } else {
            oldVal = $(this).html();
        }
        updateVal($(this), oldVal);
    });
});

var ROOT_TABS;

function printBookmarks() {
    chrome.bookmarks.getTree(function(root) {
        //console.log(root);
        $('#bookmarks').empty();
        ROOT_TABS = root[0].children.length;
        root.forEach(function(folder) {
            $('#bookmarks').append(printBookmarkFolder(folder)
                .css('padding-right', "2px"));
        });
    });
}

function printBookmarkFolder(bookmarkFolder) {
    var list = $("
");
    bookmarkFolder.children.forEach(function(bookmark) {
        if (typeof bookmark.url != 'undefined') {
            list.append(printNode(bookmark));
        } else {
            if (bookmark.children.length != 0) {
                var folder = printNodeFolder(bookmark);

                var r = $("<button type=\"submit\" class=\"dropIcon\"></button>");
                folder.prepend(r);
                folder.append(printBookmarkFolder(bookmark));
                list.append(folder);

                $(r).click(function(e) {
                    e.stopPropagation();
                    if ($(folder).find('li').is(':visible')) {
                        $(folder).children().hide();
                        $(folder).find('.dropIcon').show();
                    } else {
                        $(folder).children().show();
                    }

                });
                if (bookmark.id > ROOT_TABS) {
                    $(folder).children().hide();
                    $(folder).find('.dropIcon').show();
                }
            } else if (bookmark.id > ROOT_TABS) {
                deleteFolder(bookmark);
            }
        }
    });
    return list;
}

function deleteFolder(bookmarkFolder) {
    chrome.bookmarks.remove(bookmarkFolder.id, function() {
        console.log(bookmarkFolder.title + " removed");
    });
}

function printNode(bookmark) {
    var li = $("
")
        .css('font-weight', 'normal')
        .addClass("bLink")
        .text(bookmark.title);
    return li;
}

function printNodeFolder(bookmark) {
    var li = $("
")
        .addClass("bFolder")
        .css('font-weight', 'bold')
        .text(bookmark.title);
    return li;
}

function getHostname(url) {
    var m = url.match(/^https?\:\/\/([^\/:?#]+)(?:[\/:?#]|$)/i);
    return m ? m[0] : null;
}

function getFolderName(hostname) {
    var m = hostname.match(/:\/\/(www\.)?(.*)\./);
    return m ? m[2] : null;
}

function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

function stripPunctuation(string) {
    var punctuationless = string.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g, "");
    var finalString = punctuationless.replace(/\s{2,}/g, " ");
    return finalString;
}

function addLinksToFolder(newFolder, list, printAfter) {
    var parentId = newFolder.id;
    var name = newFolder.title;

    var length = list.length;
    $.each(list, function(key, value) {
        var subli = $("
")
            .text = value.title;

        chrome.bookmarks.move(String(value.id), {
            'parentId': parentId,
            'index': key
        }, function(done) {
            if (key == length - 1 && printAfter)
                printBookmarks();
        });
    });

}

function sortByName(a, b) {
    var aName = a.title.toLowerCase();
    var bName = b.title.toLowerCase();
    return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
}

function addBookmark(parentId, title, url) {
    chrome.bookmarks.create({
        'parentId': parentId,
        'title': title,
        'url': url
    });
}

function rename(oldTitle, newTitle) {
    chrome.bookmarks.search(oldTitle, function callback(results) {
        chrome.bookmarks.update(String(results[0].id), {
            'title': newTitle
        });
    })
}

function updateVal(currentLi, oldVal) {
    $(currentLi).html('<input class="editSelectedVal" type="text" value="' + oldVal + '" />');
    $(".editSelectedVal").focus();
    $(".editSelectedVal").keyup(function(event) {
        if (event.keyCode == 13) {
            rename(oldVal, $(".editSelectedVal").val().trim());
            $(currentLi).html($(".editSelectedVal").val().trim());
        }
    });
    $(document).click("click", function(e) {
        if ($(e.target).is(".editSelectedVal")) {
            return;
        } else {
            $(".editSelectedVal").parent("li").html(oldVal);
            $(document).unbind("click");
        }
    });
}

function previewFunction(callbackFunction) {
    var keys = {
        children: []
    };
    chrome.bookmarks.getTree(function(root) {
        root[0].children.forEach(function(folder) {
            keys.children.push(folder);
        });

        callbackFunction(keys);
        updateBookmarkListBuffer(keys);
    });
}

function updateBookmarks(list, printAfter) {
    list.children.forEach(function(folder, key) {
        if (typeof folder.url === 'undefined') {
            if (folder.create) {
                chrome.bookmarks.create({
                    'parentId': folder.parentId,
                    'title': folder.title
                }, function(e) {
                    folder.children.forEach(function(bookmark) {
                        bookmark.parentId = e.id;
                    });
                    if (key === list.children.length - 1)
                        updateBookmarks(folder, true);
                    else
                        updateBookmarks(folder, false);
                });
                return;
            } else {
                updateBookmarks(folder, false);
            }
        }

        if (folder.id <= ROOT_TABS)
            return;

        if (folder.rename) {
            chrome.bookmarks.update(String(folder.id), {
                'title': folder.title
            });
        }

        chrome.bookmarks.move(String(folder.id), {
            'parentId': folder.parentId,
            'index': key
        }, function callback() {
            if (printAfter && key === list.children.length - 1)
                printBookmarks();
        });
    });
}

function sort(list) {
    list.children.sort(sortByName);
    list.children.forEach(function(folder) {
        if (typeof folder.url === 'undefined' && folder.children.length > 0)
            sort(folder);
    });
}

function group(list) {
    var dictionary = [];
    list.children.forEach(function(folder) {
        if (typeof folder.url === 'undefined' && folder.children.length > 0 && folder.id <= ROOT_TABS) {
            group(folder);
            return;
        }
        if (typeof folder.url != 'undefined') {
            var domain = getHostname(folder.url);
            if (domain === null)
                return;

            //creates an array of results, nly have 2 cases empty or 1 element
            var result = $.grep(dictionary, function(e) {
                return e.key == domain;
            });
            //for 0 create new entry, else increment excisting entry
            if (result == 0) {
                dictionary.push({
                    key: String(domain),
                    value: 1,
                    parentId: folder.parentId,
                    folderName: String(capitalizeFirstLetter(getFolderName(domain))),
                    bookmarkList: [folder]
                });
            } else {
                result[0].value++;
                result[0].bookmarkList.push(folder);
            }
        }
    });
    $.each(dictionary, function(key, value) {
        var folderFound = false;
        if (value.value > 1) {
            dictionary[key].bookmarkList.forEach(function(bookmark) {
                var index = list.children.indexOf(bookmark);
                if (index > -1) {
                    list.children.splice(index, 1);
                }
            });
            $.each(list.children, function(index, bookmark) {
                if (typeof bookmark.url === 'undefined' && bookmark.title === value.folderName) {
                    dictionary[key].bookmarkList.forEach(function(e) {
                        e.parentId = bookmark.id;
                        bookmark.children.push(e);
                    });
                    return false;
                } else if (index === list.children.length - 1) {
                    list.children.push({
                        title: value.folderName,
                        parentId: value.parentId,
                        create: true,
                        children: dictionary[key].bookmarkList
                    });
                }
            });
        }
    });
}

function crop(list) {
    list.children.forEach(function(folder) {
        if (typeof folder.url === 'undefined' && folder.children.length > 0)
            crop(folder);

        if (typeof folder.url != 'undefined') {
            var oldTitle = folder.title;
            oldTitle = stripPunctuation(oldTitle);
            while (oldTitle.length > 70) {
                var lastSpace = oldTitle.lastIndexOf(" ");
                var firstSpace = oldTitle.indexOf(" ");
                if (lastSpace != -1 && lastSpace != firstSpace) {
                    oldTitle = oldTitle.substring(0, lastSpace);
                    folder.rename = true;
                    folder.title = oldTitle;
                } else {
                    return;
                }
            }
        }

    });
}

function updateBookmarkListBuffer(keys) {
    $('#bookmarks').empty();
    $('#bookmarks').append(printBookmarkFolder(keys));

    $('#reject').one("click", function(e) {
        e.preventDefault();
        $('#apply').unbind("click");
        printBookmarks();
        toggleAllButtons();
    });
    $('#apply').one("click", function(e) {
        e.preventDefault();
        $('#reject').unbind("click");
        updateBookmarks(keys, true);
        toggleAllButtons();
    });
}

function toggleAllButtons() {
    if ($("#sort").hasClass("disabled")) {
        $('#bookmarks').animate({
            height: 505
        }, 600);
        $(".search").slideDown(600);
        $("#decision").slideUp(500,function(){$("#decision").css('display','none');});
        $('body').animate({
            scrollTop: 1
        }, 700);
    } else {
        $(".search").slideUp(600);
        $('#bookmarks').animate({
            height: 475
        }, 600);
        $("#decision").slideDown(500);
        $('body').animate({
            scrollTop: 300
        }, 700);
    }
    toggleButtons(["#reject", "#apply"]);
    toggleButtons(["#sort", "#group", "#crop"]);
}

function toggleButtons(idList) {
    idList.forEach(function(id) {
        var button = $(id);
        if (button.hasClass("disabled")) {
            button.removeClass("disabled");
            button.addClass("active");
        } else {
            button.removeClass("active");
            button.addClass("disabled");
        }
    });
}

function searchBookmark(text) {
    var keys = {
        children: []
    };
    chrome.bookmarks.search(text, function(results) {
        $('#bookmarks').empty();
        results.forEach(function(result) {
            if (typeof result.url != 'undefined') {
                keys.children.push(result);
            }
        });
        $('#bookmarks').append(printBookmarkFolder(keys));
    });
}
<|endoftext|>


<commit_before>"use strict";

(function () {
	function PopUpCtrl ($scope, $interval, EntityService, StorageService) {
		var addTimeInterval = function addTimeInterval (e) {
			$interval(function addTimeLoop () {
				$scope.linkEntities.forEach(function (e) {
					if (typeof e.disableTill === "undefined") throw "disableTill is undefined";

					if (e.disableTill !== "" && !e.disableTill.expired()) {
						e.disableTill.timeRemaining();
					}
				});
			}, 1000);
		},
		createUIElement = function updateUIOnCreate (result) {
			$scope.$apply(function updateUIOnCreateApply () { // Apply to force digest outside of cycle
				$scope.linkEntities.push(result);
				$scope.newLink = ""; // Clear input

				// Update block list
				chrome.extension.getBackgroundPage().BackgroundService.updateBlockList($scope.linkEntities);
			});
		},
		deleteFromUI = function deleteFromUI (id) {
			var updateUIArray = function updateUIArray () {
				$scope.linkEntities.forEach(function(item, idx) {
					if ($scope.linkEntities[idx].id == id) {
						$scope.linkEntities.splice(idx, 1);
					}
				});

				// Update block list
				chrome.extension.getBackgroundPage().BackgroundService.updateBlockList($scope.linkEntities);
			};

			$scope.$apply(updateUIArray); // Apply to force digest outside of cycle
		},
		updateHourCallback = function updateHourCallback (e) {
			e.disableTill = e.disableTill.addHours(1);
			return e;
		},
		updateMinutesCallback = function updateMinutesCallback (e) {
			e.disableTill = e.disableTill.addMinutes(1);
			return e;
		}

		$scope.create = function create (inputUrl) {
			var urlExists = function urlExists (element) {
				return element.link.toString() == inputUrl.toString();
			};

			// Filter for existing entries
			if (inputUrl && !$scope.linkEntities.some(urlExists)) {
				// Call storage service
				StorageService.create(inputUrl, createUIElement);
			} else {
				// If it already exists, help them find it.
				$scope.query = inputUrl;
			}
		};

		$scope.delete = function deleteCall (id) {
			StorageService.delete(id, deleteFromUI);
		};

		$scope.updateHour = function updateHour (e) {
			StorageService.update(e, updateHourCallback, function () {
				// Update block list
				$scope.$apply(function updateHourApply () {
					chrome.extension.getBackgroundPage().BackgroundService.updateBlockList($scope.linkEntities);
				});
			});
		};

		$scope.updateMinutes = function updateMinutes (e) {
			StorageService.update(e, updateMinutesCallback, function () {
				// Update block list
				$scope.$apply(function updateMinutesApply () {
					chrome.extension.getBackgroundPage().BackgroundService.updateBlockList($scope.linkEntities);
				});
			});
		};

		// Fetch initial data
		$scope.linkEntities = [];
		StorageService.read(null, function readCallback (items) {
			$scope.$apply(function addEntitiesToUI () { // Apply to force digest outside of cycle

				// chrome.storage.local.clear(null);

				for (var key in items) {
					var ent = EntityService.generateEntity(items[key]);
					$scope.linkEntities.push(ent)
				}

				addTimeInterval();

				// Update block list
				chrome.extension.getBackgroundPage().BackgroundService.updateBlockList($scope.linkEntities);
			});
		});
	};

	angular.module("LinkBlockerApp", []);

	angular
		.module("LinkBlockerApp")
		.controller("PopUpCtrl", PopUpCtrl);
})();<commit_msg>Changed UpdateMinutes back to 30, from 1 for testing.<commit_after>"use strict";

(function () {
	function PopUpCtrl ($scope, $interval, EntityService, StorageService) {
		var addTimeInterval = function addTimeInterval (e) {
			$interval(function addTimeLoop () {
				$scope.linkEntities.forEach(function (e) {
					if (typeof e.disableTill === "undefined") throw "disableTill is undefined";

					if (e.disableTill !== "" && !e.disableTill.expired()) {
						e.disableTill.timeRemaining();
					}
				});
			}, 1000);
		},
		createUIElement = function updateUIOnCreate (result) {
			$scope.$apply(function updateUIOnCreateApply () { // Apply to force digest outside of cycle
				$scope.linkEntities.push(result);
				$scope.newLink = ""; // Clear input

				// Update block list
				chrome.extension.getBackgroundPage().BackgroundService.updateBlockList($scope.linkEntities);
			});
		},
		deleteFromUI = function deleteFromUI (id) {
			var updateUIArray = function updateUIArray () {
				$scope.linkEntities.forEach(function(item, idx) {
					if ($scope.linkEntities[idx].id == id) {
						$scope.linkEntities.splice(idx, 1);
					}
				});

				// Update block list
				chrome.extension.getBackgroundPage().BackgroundService.updateBlockList($scope.linkEntities);
			};

			$scope.$apply(updateUIArray); // Apply to force digest outside of cycle
		},
		updateHourCallback = function updateHourCallback (e) {
			e.disableTill = e.disableTill.addHours(1);
			return e;
		},
		updateMinutesCallback = function updateMinutesCallback (e) {
			e.disableTill = e.disableTill.addMinutes(30);
			return e;
		}

		$scope.create = function create (inputUrl) {
			var urlExists = function urlExists (element) {
				return element.link.toString() == inputUrl.toString();
			};

			// Filter for existing entries
			if (inputUrl && !$scope.linkEntities.some(urlExists)) {
				// Call storage service
				StorageService.create(inputUrl, createUIElement);
			} else {
				// If it already exists, help them find it.
				$scope.query = inputUrl;
			}
		};

		$scope.delete = function deleteCall (id) {
			StorageService.delete(id, deleteFromUI);
		};

		$scope.updateHour = function updateHour (e) {
			StorageService.update(e, updateHourCallback, function () {
				// Update block list
				$scope.$apply(function updateHourApply () {
					chrome.extension.getBackgroundPage().BackgroundService.updateBlockList($scope.linkEntities);
				});
			});
		};

		$scope.updateMinutes = function updateMinutes (e) {
			StorageService.update(e, updateMinutesCallback, function () {
				// Update block list
				$scope.$apply(function updateMinutesApply () {
					chrome.extension.getBackgroundPage().BackgroundService.updateBlockList($scope.linkEntities);
				});
			});
		};

		// Fetch initial data
		$scope.linkEntities = [];
		StorageService.read(null, function readCallback (items) {
			$scope.$apply(function addEntitiesToUI () { // Apply to force digest outside of cycle

				// chrome.storage.local.clear(null);

				for (var key in items) {
					var ent = EntityService.generateEntity(items[key]);
					$scope.linkEntities.push(ent)
				}

				addTimeInterval();

				// Update block list
				chrome.extension.getBackgroundPage().BackgroundService.updateBlockList($scope.linkEntities);
			});
		});
	};

	angular.module("LinkBlockerApp", []);

	angular
		.module("LinkBlockerApp")
		.controller("PopUpCtrl", PopUpCtrl);
})();<|endoftext|>