<commit_before>$(document).ready(function() {
	var Obj = function(buttn, audio, normalColor, activeColor) {
		this.buttn = buttn;
		this.audio = audio;
		this.normalColor = normalColor;
		this.activeColor = activeColor;
	}
	var topLeftAudio = new Audio('https://s3.amazonaws.com/freecodecamp/simonSound1.mp3');
	var topRightAudio = new Audio('https://s3.amazonaws.com/freecodecamp/simonSound2.mp3');
	var bottomLeftAudio = new Audio('https://s3.amazonaws.com/freecodecamp/simonSound3.mp3');
	var bottomRightAudio = new Audio('https://s3.amazonaws.com/freecodecamp/simonSound4.mp3');
	var computerSequence = [];
	var playerSequence = [];
	var on = false;
	var strict = false;
	var topLeft = new Obj($('.outter-btn-top-left'), topLeftAudio, 'green', '#0F0');
	var topRight = new Obj($('.outter-btn-top-right'), topRightAudio, 'darkred', '#F00');
	var bottomLeft = new Obj($('.outter-btn-bottom-left'), bottomLeftAudio, '#CC0', '#FF3');
	var bottomRight = new Obj($('.outter-btn-bottom-right'), bottomRightAudio, 'darkblue', '#22F');

	function buttonPressed(obj) {
		obj.audio.play();
		obj.buttn.css({'background-color': obj.activeColor});
    setTimeout(function() {
         obj.buttn.css({'background-color': obj.normalColor});
    }, 350);
	}

	function checkPlay() {
		var index = playerSequence.length - 1;
		if (playerSequence[index] !== computerSequence[index]) {
			removeEvents();
			$('#step').text('XX');
			playerSequence = [];
			topLeft.buttn.css({'background-color': topLeft.activeColor});
			topRight.buttn.css({'background-color': topRight.activeColor});
			bottomLeft.buttn.css({'background-color': bottomLeft.activeColor});
			bottomRight.buttn.css({'background-color': bottomRight.activeColor});
			setTimeout(function() {
				topLeft.buttn.css({'background-color': topLeft.normalColor});
				topRight.buttn.css({'background-color': topRight.normalColor});
				bottomLeft.buttn.css({'background-color': bottomLeft.normalColor});
				bottomRight.buttn.css({'background-color': bottomRight.normalColor});
				if (strict) {
					$('#step').text('00');
					computerSequence = [];
					addEvents();
				} else {
					$('#step').text(computerSequence.length < 10 ?
													'0' + computerSequence.length :
													computerSequence.length);
					playComputerMoves();
				}
			}, 1500);
		} else {
			return true;
		}
	}

	function playerButtonPressed() {
    buttonPressed(this);
		if (computerSequence.length) {
			playerSequence.push(this);
			if (checkPlay()) {
				if (computerSequence.length === 20 && playerSequence.length === 20) {
					$('#step').text('00');
					playerSequence = [];
					computerSequence = [];
					alert(strict ? 'Congratulations, you have beaten the game in strict mode!' : 'Congratulations, you have beaten the game in normal mode. For a bigger challenge activate strict mode next time you play');
				} else {
					if (playerSequence.length === computerSequence.length) {
						playerSequence = [];
						setTimeout(computerMove(), 500);
					}
				}
			}
		}
	}

	function strictStatus() {
		strict = strict ? false : true;
		$('#led').css({'background-color': strict ? 'red' : '#303030'});
	}

	function playComputerMoves() {
		removeEvents();
		for (let i = 0, length = computerSequence.length; i < length; i++) {
			setTimeout(function() {
				buttonPressed(computerSequence[i]);
			}, 700 * (i + 1));
		}
		setTimeout(function() {
			if (on) {
				addEvents();
			}
		}, 700 * (computerSequence.length + 1));
	}

	function computerMove() {
		var random = Math.floor(Math.random() * 4);
		var whichObj;
		switch(random) {
			case 0:
				whichObj = topLeft;
				break;
			case 1:
				whichObj = topRight;
				break;
			case 2:
				whichObj = bottomLeft;
				break;
			case 3:
				whichObj = bottomRight;
		}
		computerSequence.push(whichObj);
		$('#step').text(computerSequence.length < 10 ?
										'0' + computerSequence.length :
										computerSequence.length);
		playComputerMoves();
	}

	function addEvents() {
		if (!computerSequence.length) {
			$('#start').on('click', computerMove);
		}
		if (!computerSequence.length) {
			$('#strict').on('click', strictStatus);
		}
		topLeft.buttn.on('mousedown',
										 playerButtonPressed.bind(topLeft));
		topRight.buttn.on('mousedown',
											playerButtonPressed.bind(topRight));
		bottomLeft.buttn.on('mousedown',
												playerButtonPressed.bind(bottomLeft));
		bottomRight.buttn.on('mousedown',
												 playerButtonPressed.bind(bottomRight));
	}

	function removeEvents() {
		$('#start').off('click');
		$('#strict').off('click');
		topLeft.buttn.off('mousedown');
		topRight.buttn.off('mousedown');
		bottomLeft.buttn.off('mousedown');
		bottomRight.buttn.off('mousedown');
	}

	$('.toggle').on('click', function() {
		if (on) {
			on = false;
			$('.toggle').css({left: '2px'});
			$('#step').text('');
			strict = false;
			$('#led').css({'background-color': '#303030'});
			removeEvents();
		} else {
			on = true;
			$('.toggle').css({left: '27px'});
			$('#step').css({color: 'red'});
			$('#step').text('00');
			addEvents();
		}
		computerSequence = [];
		playerSequence = [];
	});
});<commit_msg>Update index.js<commit_after>$(document).ready(function() {
	var Obj = function(buttn, audio, normalColor, activeColor) {
		this.buttn = buttn;
		this.audio = audio;
		this.normalColor = normalColor;
		this.activeColor = activeColor;
	}
	var topLeftAudio = new Audio('https://s3.amazonaws.com/freecodecamp/simonSound1.mp3');
	var topRightAudio = new Audio('https://s3.amazonaws.com/freecodecamp/simonSound2.mp3');
	var bottomLeftAudio = new Audio('https://s3.amazonaws.com/freecodecamp/simonSound3.mp3');
	var bottomRightAudio = new Audio('https://s3.amazonaws.com/freecodecamp/simonSound4.mp3');
	var computerSequence = [];
	var playerSequence = [];
	var on = false;
	var strict = false;
	var topLeft = new Obj($('.outter-btn-top-left'), topLeftAudio, 'green', '#0F0');
	var topRight = new Obj($('.outter-btn-top-right'), topRightAudio, 'darkred', '#F00');
	var bottomLeft = new Obj($('.outter-btn-bottom-left'), bottomLeftAudio, '#CC0', '#FF3');
	var bottomRight = new Obj($('.outter-btn-bottom-right'), bottomRightAudio, 'darkblue', '#22F');

	function buttonPressed(obj) {
		obj.audio.play();
		obj.buttn.css({'background-color': obj.activeColor});
		setTimeout(function() {
			obj.buttn.css({'background-color': obj.normalColor});
		}, 350);
	}

	function checkPlay() {
		var index = playerSequence.length - 1;
		if (playerSequence[index] !== computerSequence[index]) {
			removeEvents();
			$('#step').text('XX');
			playerSequence = [];
			topLeft.buttn.css({'background-color': topLeft.activeColor});
			topRight.buttn.css({'background-color': topRight.activeColor});
			bottomLeft.buttn.css({'background-color': bottomLeft.activeColor});
			bottomRight.buttn.css({'background-color': bottomRight.activeColor});
			setTimeout(function() {
				topLeft.buttn.css({'background-color': topLeft.normalColor});
				topRight.buttn.css({'background-color': topRight.normalColor});
				bottomLeft.buttn.css({'background-color': bottomLeft.normalColor});
				bottomRight.buttn.css({'background-color': bottomRight.normalColor});
				if (strict) {
					$('#step').text('00');
					computerSequence = [];
					addEvents();
				} else {
					$('#step').text(computerSequence.length < 10 ?
										'0' + computerSequence.length :
										computerSequence.length);
					playComputerMoves();
				}
			}, 1500);
		} else {
			return true;
		}
	}

	function playerButtonPressed() {
		buttonPressed(this);
		if (computerSequence.length) {
			playerSequence.push(this);
			if (checkPlay()) {
				if (computerSequence.length === 20 && playerSequence.length === 20) {
					$('#step').text('00');
					playerSequence = [];
					computerSequence = [];
					alert(strict ? 'Congratulations, you have beaten the game in strict mode!' :
							'Congratulations, you have beaten the game in normal mode. For a bigger challenge activate strict mode next time you play');
				} else {
					if (playerSequence.length === computerSequence.length) {
						playerSequence = [];
						setTimeout(computerMove(), 500);
					}
				}
			}
		}
	}

	function strictStatus() {
		strict = strict ? false : true;
		$('#led').css({'background-color': strict ? 'red' : '#303030'});
	}

	function playComputerMoves() {
		removeEvents();
		for (let i = 0, length = computerSequence.length; i < length; i++) {
			setTimeout(function() {
				buttonPressed(computerSequence[i]);
			}, 700 * (i + 1));
		}
		setTimeout(function() {
			if (on) {
				addEvents();
			}
		}, 700 * (computerSequence.length + 1));
	}

	function computerMove() {
		var random = Math.floor(Math.random() * 4);
		var whichObj;
		switch(random) {
			case 0:
				whichObj = topLeft;
				break;
			case 1:
				whichObj = topRight;
				break;
			case 2:
				whichObj = bottomLeft;
				break;
			case 3:
				whichObj = bottomRight;
		}
		computerSequence.push(whichObj);
		$('#step').text(computerSequence.length < 10 ?
							'0' + computerSequence.length :
							computerSequence.length);
		playComputerMoves();
	}

	function addEvents() {
		if (!computerSequence.length) {
			$('#start').on('click', computerMove);
		}
		if (!computerSequence.length) {
			$('#strict').on('click', strictStatus);
		}
		topLeft.buttn.on('mousedown', playerButtonPressed.bind(topLeft));
		topRight.buttn.on('mousedown', playerButtonPressed.bind(topRight));
		bottomLeft.buttn.on('mousedown', playerButtonPressed.bind(bottomLeft));
		bottomRight.buttn.on('mousedown', playerButtonPressed.bind(bottomRight));
	}

	function removeEvents() {
		$('#start').off('click');
		$('#strict').off('click');
		topLeft.buttn.off('mousedown');
		topRight.buttn.off('mousedown');
		bottomLeft.buttn.off('mousedown');
		bottomRight.buttn.off('mousedown');
	}

	$('.toggle').on('click', function() {
		if (on) {
			on = false;
			$('.toggle').css({left: '2px'});
			$('#step').text('');
			strict = false;
			$('#led').css({'background-color': '#303030'});
			removeEvents();
		} else {
			on = true;
			$('.toggle').css({left: '27px'});
			$('#step').css({color: 'red'});
			$('#step').text('00');
			addEvents();
		}
		computerSequence = [];
		playerSequence = [];
	});
});
<|endoftext|>


<commit_before>var GameInputFactory = function (renderer) {
  var canvas = renderer.canvas;
  var camera = renderer.camera;

  var pressedKeys = {};
  var mousePos = new THREE.Vector3();

  var gamePlaneRaycaster = new THREE.Raycaster();

  function setKey(event, status) {
    var code = event.keyCode;
    var key;

    switch(code) {
      case 32:
        key = 'SPACE'; break;
      case 37:
        key = 'LEFT'; break;
      case 38:
        key = 'UP'; break;
      case 39:
        key = 'RIGHT'; break;
      case 40:
        key = 'DOWN'; break;
      default:
        // Convert ASCII codes to letters
        key = String.fromCharCode(event.keyCode);
    }

    pressedKeys[key] = status;
  }

  document.addEventListener('keydown', function(e) {
    setKey(e, true);
  });

  document.addEventListener('keyup', function(e) {
    setKey(e, false);
  });

  ['mousemove', 'touchmove', 'touchstart'].forEach(type => canvas.addEventListener(type, function (e) {
    // Scale position to NDC
    let coords = new THREE.Vector2();
    coords.x = e.offsetX / parseFloat(e.target.style.width) * 2 - 1;
    coords.y = -(e.offsetY / parseFloat(e.target.style.height) * 2 - 1);

    // Update raycaster
    gamePlaneRaycaster.setFromCamera(coords, camera);

    // Compute ray-plane intersection with ground plane (z=0)
    let N = new THREE.Vector3(0, 0, -1);
    let t = -gamePlaneRaycaster.ray.origin.dot(N) / gamePlaneRaycaster.ray.direction.dot(N);
    mousePos.copy(gamePlaneRaycaster.ray.direction).multiplyScalar(t).add(gamePlaneRaycaster.ray.origin);
  }));

  ['mousedown', 'touchstart'].forEach(type => canvas.addEventListener(type, function(e) {
    pressedKeys['MOUSE'] = true;
  }));

  ['mouseup', 'touchend'].forEach(type => canvas.addEventListener(type, function(e) {
    pressedKeys['MOUSE'] = false;
  }));

  window.addEventListener('blur', function() {
    pressedKeys = {};
  });

  function isDown(key) {
    return pressedKeys[key];
  }

  function getMousePos() {
    return mousePos;
  }

  /**
   * Update the given raycaster with the current mouse position.
   * @param raycaster {THREE.Raycaster}
   */
  function updateRaycaster(raycaster) {
    raycaster.set(camera.position, getMousePos().clone().sub(camera.position).normalize());
  }

  return {
    isDown: isDown,
    getMousePos: getMousePos,
    updateRaycaster: updateRaycaster
  };

};
<commit_msg>Working mobile touch input<commit_after>var GameInputFactory = function (renderer) {
  var canvas = renderer.canvas;
  var camera = renderer.camera;

  var pressedKeys = {};
  var mousePos = new THREE.Vector3();

  var gamePlaneRaycaster = new THREE.Raycaster();

  function setKey(event, status) {
    var code = event.keyCode;
    var key;

    switch(code) {
      case 32:
        key = 'SPACE'; break;
      case 37:
        key = 'LEFT'; break;
      case 38:
        key = 'UP'; break;
      case 39:
        key = 'RIGHT'; break;
      case 40:
        key = 'DOWN'; break;
      default:
        // Convert ASCII codes to letters
        key = String.fromCharCode(event.keyCode);
    }

    pressedKeys[key] = status;
  }

  function updateMouse(x, y) {
    // Scale position to NDC
    let coords = new THREE.Vector2();
    coords.x = x / parseFloat(canvas.style.width) * 2 - 1;
    coords.y = -(y / parseFloat(canvas.style.height) * 2 - 1);

    // Update raycaster
    gamePlaneRaycaster.setFromCamera(coords, camera);

    // Compute ray-plane intersection with ground plane (z=0)
    let N = new THREE.Vector3(0, 0, -1);
    let t = -gamePlaneRaycaster.ray.origin.dot(N) / gamePlaneRaycaster.ray.direction.dot(N);
    mousePos.copy(gamePlaneRaycaster.ray.direction).multiplyScalar(t).add(gamePlaneRaycaster.ray.origin);
  }

  document.addEventListener('keydown', function(e) {
    setKey(e, true);
  });

  document.addEventListener('keyup', function(e) {
    setKey(e, false);
  });

  ['touchstart', 'touchmove'].forEach(type => canvas.addEventListener(type, function (e) {
    updateMouse(e.touches[0].pageX, e.touches[0].pageY);
  }));

  canvas.addEventListener("mousemove", function (e) {
    updateMouse(e.offsetX, e.offsetY);
  });

  ['mousedown', 'touchstart'].forEach(type => canvas.addEventListener(type, function(e) {
    pressedKeys['MOUSE'] = true;
  }));

  ['mouseup', 'touchend'].forEach(type => canvas.addEventListener(type, function(e) {
    pressedKeys['MOUSE'] = false;
  }));

  window.addEventListener('blur', function() {
    pressedKeys = {};
  });

  function isDown(key) {
    return pressedKeys[key];
  }

  function getMousePos() {
    return mousePos;
  }

  /**
   * Update the given raycaster with the current mouse position.
   * @param raycaster {THREE.Raycaster}
   */
  function updateRaycaster(raycaster) {
    raycaster.set(camera.position, getMousePos().clone().sub(camera.position).normalize());
  }

  return {
    isDown: isDown,
    getMousePos: getMousePos,
    updateRaycaster: updateRaycaster
  };

};
<|endoftext|>


<commit_before>import numberToSignedString from 'binary-utils/lib/numberToSignedString';

export const internalTradeModelToServerTradeModel = tradeObj => {
    const {
        amount,
        basis,
        type,
        dateStart,
        duration,
        durationUnit,
        symbol,
        barrier,
        barrier2,
        amountPerPoint,
        stopType,
        stopProfit,
        stopLoss,
        barrierType,
    } = tradeObj;

    const b1 = barrier && (barrierType === 'relative' ? numberToSignedString(barrier) : barrier);
    const b2 = barrier2 && (barrierType === 'relative' ? numberToSignedString(barrier2) : barrier2);

    const serverModel = {
        amount,
        basis,
        contract_type: type,
        duration,
        date_start: dateStart,
        duration_unit: durationUnit,
        symbol,
        barrier: b1,
        barrier2: b2,
        amount_per_point: amountPerPoint,
        stop_type: stopType,
        stop_profit: stopProfit,
        stop_loss: stopLoss,
    };

    return serverModel;
};
<commit_msg>Add param required (#256)<commit_after>import numberToSignedString from 'binary-utils/lib/numberToSignedString';

export const internalTradeModelToServerTradeModel = tradeObj => {
    const {
        amount,
        basis,
        type,
        dateStart,
        duration,
        durationUnit,
        symbol,
        barrier,
        barrier2,
        amountPerPoint,
        stopType,
        stopProfit,
        stopLoss,
        barrierType,
        pipSize,
    } = tradeObj;

    const b1 = barrier && (barrierType === 'relative' ? numberToSignedString(barrier) : barrier);
    const b2 = barrier2 && (barrierType === 'relative' ? numberToSignedString(barrier2) : barrier2);

    const serverModel = {
        amount,
        amount_per_point: amountPerPoint,
        basis,
        contract_type: type,
        duration,
        date_start: dateStart,
        duration_unit: durationUnit,
        symbol,
        barrier: b1,
        barrier2: b2,
        barrierType,
        pipSize,
        stop_type: stopType,
        stop_profit: stopProfit,
        stop_loss: stopLoss,
    };

    return serverModel;
};
<|endoftext|>


<commit_before>/**
 * Juxta 0.0.1
 *
 * Copyright (c) 2010-2011 Alexey Golovnya
 * Licensed under the MIT license
 * http://juxta.ru
 */

/**
 * @class Juxta base application
 */
Juxta = function() {

	/**
	 * Cache
	 * @type Juxta.Cache
	 */
	this.cache = new Juxta.Cache();

	/**
	 * Request/response
	 * @type Juxta.Request
	 */
	this.request = new Juxta.Request(this.cache, {
		request: {
			beforeSend: function() {
				Jux.loading();
			},
			complete: function() {
				Jux.loading(false);
			},
			error: function(xhr, status) {
				if (status == 'parsererror') {
					Jux.error('Answer parsing error');
				} else {
					Jux.error(xhr.status + ' ' + xhr.statusText);
				}
			}
		},
		response: {
			connectionError: function(response) { Jux.error(response.error); Jux.auth.show(); },
			sessionNotFound: function() { document.location.hash = '#login'; },
			error: function(response) { Jux.error(response.error); },
			unknowStatus: function() { Jux.error('Response with unknow status recived'); }
		}
	});

	this.connection = null;

	this.notification = new Juxta.Notification();
	this.sidebar = new Juxta.Sidebar();
	this.explorer = new Juxta.Explorer('#explorer', this.request);
	this.exchange = new Juxta.BackupRestore('#backup-restore');
	this.browser = new Juxta.Browser('#data-browser', this.request);
	this.tableEditor = new Juxta.TableEditor('#table-editor');
	this.dummy = new Juxta.Dummy('#dummy');
	this.server = new Juxta.ServerInformation('#server-info', this.request);
	this.auth = new Juxta.Auth('#login', this.request);
	this.messageBox = new Juxta.FloatBox('#message');

	var that = this;

	$('#header a[name=about]').bind('click', function() { that.about(); return false; });

	if (location.hash == '') {
		location.hash = 'databases';
	}
	this.state = 'default';
	setInterval($.proxy(this.checkLocation, this), 200);

	$('.float-box').draggable({scroll: false, handle: 'h3'});
	$(document.body).bind('click', function(event) {
		$('.context:visible').trigger('hide').hide();
	});
}

Juxta.prototype = {

	/**
	 *
	 */
	checkLocation: function() {
		var hash = window.location.hash.replace(/#/g, ''),
			params = hash.split('/'),
			action = params.pop();
		if (hash != this.state) {
			switch (action) {
				case 'databases':
				case 'processlist':
				case 'users':
					this.explore({show: action});
					break;
				case 'status':
				case 'status-full':
				case 'variables':
				case 'charsets':
				case 'engines':
					this.info({show: action});
					break;
				case 'backup':
					this.sidebar.highlight('backup');
					this.exchange.show();
					break;
				case 'restore':
					this.sidebar.highlight('restore');
					this.dummy.show({header: 'Restore'});
					break;
				case 'login':
					this.auth.show();
					break;
				//
				case 'tables':
				case 'views':
				case 'routines':
				case 'triggers':
					this.explore({show: action, from: params[0]});
					break;
				//
				case 'browse':
					this.browse({browse: params[1], from: params[0]});
					break;
				case 'columns':
					this.sidebar.highlight('columns', {'database': params[0], 'table': params[1]});
					this.tableEditor.show({header: {title: 'Table', name: params[1]}});
					break;
				case 'foreign':
					this.sidebar.highlight('foreign', {'database': params[0], 'table': params[1]});
					this.dummy.show();
					break;
				case 'options':
					this.sidebar.highlight('options', {'database': params[0], 'table': params[1]});
					this.dummy.show({header: 'Options'});
					break;
				case 'maintenance':
					this.sidebar.highlight('maintenance', {'database': params[0], 'table': params[1]});
					this.dummy.show({header: {title: 'Maintenance Table', name: params[1]}});
					break;
				case 'flush':
					this.cache.flush();
				default:
					window.location = '#databases';
			}
			this.state = hash;
		}
	},

	/**
	 *
	 */
	show: function() {
		$('#sidebar:not(.minimized)').slideDown(250);
		$('.float-box').hide();
		if ($('#applications').not(':visible')) {
			$('#applications').fadeIn(250);
			$('#header h1, #header ul').fadeIn(250);
		}
	},

	/**
	 *
	 */
	hide: function() {
		$('#header h1, #header ul, #sidebar, #applications, .float-box').hide();
	},

	/**
	 *
	 */
	explore: function(params) {
		if (params.from) {
			this.sidebar.highlight(params.show, {'database': params.from});
			this.explorer.explore(params);
		} else {
			this.sidebar.highlight(params.show);
			this.explorer.explore(params);
		}
	},

	/**
	 *
	 */
	drop: function(params) {
		this.explorer.drop(params);
	},

	/**
	 *
	 */
	kill: function(params) {
		this.explorer.kill(params);
	},

	/**
	 *
	 */
	confirm: function(message) {
		return confirm(message);
	},

	/**
	 *
	 */
	info: function(params) {
		this.sidebar.highlight('status');
		this.server.info(params);
	},

	/**
	 *
	 */
	browse: function(params) {
		this.sidebar.path({'database': params.from, 'table': params.browse});
		this.browser.browse(params);
	},

	/**
	 * Notifications shortcuts
	 */
	notify: function(message, options) {
		return this.notification.show(message, options);
	},

	/**
	 *
	 */
	loading: function(message, options) {
		return this.notification.loading(message, options);
	},

	/**
	 *
	 */
	error: function(message, options) {
		return this.notification.show(message, $.extend({}, {type: 'error', hide: false, fast: true}, options));
	},

	/**
	 *
	 */
	message: function(message, options) {
		this.messageBox.show(options, message);
	},

	/**
	 *
	 */
	about: function() {
		this.message($('#about').html(), {title: ''});
	}

};

$(document).ready(function() {
	window.Jux = new Juxta();
});<commit_msg>Remove some of globals<commit_after>/**
 * Juxta 0.0.1
 *
 * Copyright (c) 2010-2011 Alexey Golovnya
 * Licensed under the MIT license
 * http://juxta.ru
 */

/**
 * @class Juxta base application
 */
Juxta = function() {

	var that = this;

	/**
	 * Cache
	 * @type Juxta.Cache
	 */
	this.cache = new Juxta.Cache();

	/**
	 * Request/response
	 * @type Juxta.Request
	 */
	this.request = new Juxta.Request(this.cache, {
		request: {
			beforeSend: function() {
				that.loading();
			},
			complete: function() {
				that.loading(false);
			},
			error: function(xhr, status) {
				if (status == 'parsererror') {
					that.error('Answer parsing error');
				} else {
					that.error(xhr.status + ' ' + xhr.statusText);
				}
			}
		},
		response: {
			connectionError: function(response) {
				that.error(response.error);
				that.auth.show();
			},
			sessionNotFound: function() {
				document.location.hash = '#login';
			},
			error: function(response) {
				that.error(response.error);
			},
			unknowStatus: function() {
				that.error('Response with unknow status recived');
			}
		}
	});

	this.connection = null;

	this.notification = new Juxta.Notification();
	this.sidebar = new Juxta.Sidebar();
	this.explorer = new Juxta.Explorer('#explorer', this.request);
	this.exchange = new Juxta.BackupRestore('#backup-restore');
	this.browser = new Juxta.Browser('#data-browser', this.request);
	this.tableEditor = new Juxta.TableEditor('#table-editor');
	this.dummy = new Juxta.Dummy('#dummy');
	this.server = new Juxta.ServerInformation('#server-info', this.request);
	this.auth = new Juxta.Auth('#login', this.request);
	this.messageBox = new Juxta.FloatBox('#message');

	var that = this;

	$('#header a[name=about]').bind('click', function() { that.about(); return false; });

	if (location.hash == '') {
		location.hash = 'databases';
	}
	this.state = 'default';
	setInterval($.proxy(this.checkLocation, this), 200);

	$('.float-box').draggable({scroll: false, handle: 'h3'});
	$(document.body).bind('click', function(event) {
		$('.context:visible').trigger('hide').hide();
	});
}

Juxta.prototype = {

	/**
	 *
	 */
	checkLocation: function() {
		var hash = window.location.hash.replace(/#/g, ''),
			params = hash.split('/'),
			action = params.pop();
		if (hash != this.state) {
			switch (action) {
				case 'databases':
				case 'processlist':
				case 'users':
					this.explore({show: action});
					break;
				case 'status':
				case 'status-full':
				case 'variables':
				case 'charsets':
				case 'engines':
					this.info({show: action});
					break;
				case 'backup':
					this.sidebar.highlight('backup');
					this.exchange.show();
					break;
				case 'restore':
					this.sidebar.highlight('restore');
					this.dummy.show({header: 'Restore'});
					break;
				case 'login':
					this.auth.show();
					break;
				//
				case 'tables':
				case 'views':
				case 'routines':
				case 'triggers':
					this.explore({show: action, from: params[0]});
					break;
				//
				case 'browse':
					this.browse({browse: params[1], from: params[0]});
					break;
				case 'columns':
					this.sidebar.highlight('columns', {'database': params[0], 'table': params[1]});
					this.tableEditor.show({header: {title: 'Table', name: params[1]}});
					break;
				case 'foreign':
					this.sidebar.highlight('foreign', {'database': params[0], 'table': params[1]});
					this.dummy.show();
					break;
				case 'options':
					this.sidebar.highlight('options', {'database': params[0], 'table': params[1]});
					this.dummy.show({header: 'Options'});
					break;
				case 'maintenance':
					this.sidebar.highlight('maintenance', {'database': params[0], 'table': params[1]});
					this.dummy.show({header: {title: 'Maintenance Table', name: params[1]}});
					break;
				case 'flush':
					this.cache.flush();
				default:
					window.location = '#databases';
			}
			this.state = hash;
		}
	},

	/**
	 *
	 */
	show: function() {
		$('#sidebar:not(.minimized)').slideDown(250);
		$('.float-box').hide();
		if ($('#applications').not(':visible')) {
			$('#applications').fadeIn(250);
			$('#header h1, #header ul').fadeIn(250);
		}
	},

	/**
	 *
	 */
	hide: function() {
		$('#header h1, #header ul, #sidebar, #applications, .float-box').hide();
	},

	/**
	 *
	 */
	explore: function(params) {
		if (params.from) {
			this.sidebar.highlight(params.show, {'database': params.from});
			this.explorer.explore(params);
		} else {
			this.sidebar.highlight(params.show);
			this.explorer.explore(params);
		}
	},

	/**
	 *
	 */
	drop: function(params) {
		this.explorer.drop(params);
	},

	/**
	 *
	 */
	kill: function(params) {
		this.explorer.kill(params);
	},

	/**
	 *
	 */
	confirm: function(message) {
		return confirm(message);
	},

	/**
	 *
	 */
	info: function(params) {
		this.sidebar.highlight('status');
		this.server.info(params);
	},

	/**
	 *
	 */
	browse: function(params) {
		this.sidebar.path({'database': params.from, 'table': params.browse});
		this.browser.browse(params);
	},

	/**
	 * Notifications shortcuts
	 */
	notify: function(message, options) {
		return this.notification.show(message, options);
	},

	/**
	 *
	 */
	loading: function(message, options) {
		return this.notification.loading(message, options);
	},

	/**
	 *
	 */
	error: function(message, options) {
		return this.notification.show(message, $.extend({}, {type: 'error', hide: false, fast: true}, options));
	},

	/**
	 *
	 */
	message: function(message, options) {
		this.messageBox.show(options, message);
	},

	/**
	 *
	 */
	about: function() {
		this.message($('#about').html(), {title: ''});
	}

};

$(document).ready(function() {
	window.Jux = new Juxta();
});<|endoftext|>


<commit_before>/*global document, window, setInterval */

/**
 * Juxta 0.0.1
 *
 * Copyright (c) 2010-2011 Alexey Golovnya
 * Licensed under the MIT license
 * http://juxta.ru
 */

/**
 * @class Juxta
 */
var Juxta = function() {

	/**
	 * @type {String}
	 */
	this._state = null;

	/**
	 * @type {Juxta.Cache}
	 */
	this._cache = new Juxta.Cache();

	/**
	 * @type {Juxta.Connection}
	 */
	this._connection = new Juxta.Connection();

	/**
	 * @type {Juxta.Sidebar}
	 */
	this._sidebar = new Juxta.Sidebar('#sidebar', this._connection);

	/**
	 * Request/response
	 *
	 * @type Juxta.Request
	 */
	this._request = new Juxta.Request(this._connection, this._cache, {
		request: {
			beforeSend: this.loading.bind(this, null),
			complete: this.loading.bind(this, false),
			error: (function(xhr, status) {
				if (status == 'parsererror') {
					this.error('Parse error');
				} else {
					this.error(xhr.status + ' ' + xhr.statusText);
				}
			}).bind(this)
		},
		response: {
			connectionError: (function(response) { this.error(response.errormsg); this._auth.show();}).bind(this),
			sessionNotFound: this.redirect.bind(this, 'login', undefined),
			queryError: (function(response) { this.error(response.errormsg); }).bind(this),
			error: this.error.bind(this, 'An error has occured')
		}
	});

	/**
	 * Notification messages
	 *
	 * @type {Juxta.Notification}
	 */
	this._notification = new Juxta.Notification($('.notifications').eq(0));

	/**
	 * @type {Juxta.Explorer}
	 */
	this._explorer = new Juxta.Explorer('.application.explorer', this._request);

	/**
	 * Table data browser
	 *
	 * @type {Juxta.Browser}
	 */
	this.browser = new Juxta.Browser('#data-browser', this._request);

	/**
	 * Table editor
	 *
	 * @type {Juxta.Table}
	 */
	this.table = new Juxta.Table('#table', this._request);

	/**
	 * Server information
	 *
	 * @type {Juxta.Server}
	 */
	this._server = new Juxta.Server('#server-info', this._request);

	/**
	 * Connect to server form
	 *
	 * @type {Juxta.Auth}
	 */
	this._auth = new Juxta.Auth('#login', this._request);

	/**
	 * Modal window for dialogs
	 *
	 * @type {Juxta.Modal}
	 */
	this.messageBox = new Juxta.Modal('#message');

	//
	$('.header-change-connection').on('click', function() {
		//
		var container = $('.header-connections-container'),
			list = container.find('.header-connections');

		container.css({right: ''}).toggle();

		if (container.is(':visible') && $('body').width() - container.offset().left < container.width()) {
			container.css({right: 7});
		}

		list.toggleClass('scroll', list.prop('scrollHeight') > list.prop('offsetHeight'));

		return false;
	});

	//
	this._connection.on('change', this._changeConnectionCallback.bind(this));

	// Show Juxta when application ready to show
	$.each([this._explorer, this._server, this.browser, this.table], (function(i, application) {
		application.on('ready', this.show.bind(this))
			.on('maximize', function() { $('#sidebar').addClass('_hidden'); })
			.on('restore', function() {
				$('#sidebar').removeClass('_hidden');
				if ($('#applications').is(':visible')) {
					$('#sidebar').show();
				}
			});
	}).bind(this));

	//
	this._explorer.on('alert', this.message.bind(this))
		.on('modal-hide', this._notification.hide.bind(this._notification));

	//
	this._auth
		.on('before-show', (function() { this.hide()._updateWindowTitle(); this._connection.reset(); }).bind(this))
		.on('login', (function(connection) {
			this._connection.set(connection.cid, connection);
			this.redirect('databases', connection.cid);
		}).bind(this))
		.on('logout', (function() { this._cache.flush(); this._updateWindowTitle().redirect('login'); }).bind(this))
		.on('change', (function(cid) { this.redirect('', cid); }).bind(this));

	// Notifications
	this._auth.on('notify', (function(message, type, options) {
		if (type === 'error') {
			this.error(message, options);
		} else if (type === 'loading') {
			this.loading(message, options);
		} else {
			this.notify(message, options);
		}
	}).bind(this));

	//
	$('#header a[name=about]').on('click', (function() { this.message($('#about').html(), {title: ''}); return false; }).bind(this));

	//
	$('#header .sql a').on('click', (function() {
		//
		if (this.browser.is(':visible') && this.browser.mode == 'browse') {
			this.browser.toggleEditor();
		}

		return false;

	}).bind(this));

	$('#header a[name=logout]').on('click', (function() { this._auth.logout(); return false; }).bind(this));

	// @todo Remove this from here
	$(document.body).on('click', function() {
		$('.context:visible').trigger('hide').hide();
	});

	this.run();

};

/**
 * Default MySQL port
 *
 * @constant {Number}
 */
Juxta.DEFAULT_PORT = 3306;

/**
 * Run application
 *
 * @return {Juxta}
 */
Juxta.prototype.run = function() {
	//
	setInterval($.proxy(this.route, this), 200);

	return this;
};

/**
 *
 */
Juxta.prototype.route = function() {
	//
	var hash = window.location.hash.replace(/#\/?/g, '').split('?'),
		query = hash[0].split('/'),
		paramsString = hash[1],
		params = [],
		pathParams = [],
		cid,
		action;

	function parseParamsString(str) {
		//
		var ret = {},
			seg = str.replace(/^\?/,'').split('&'),
			len = seg.length, i = 0, s;

		for (; i<len; i++) {
			if (!seg[i]) {
				continue;
			}
			s = seg[i].split('=');
			ret[decodeURIComponent(s[0])] = decodeURIComponent(s[1]);
		}

		return ret;
	}

	if (paramsString) {
		params = parseParamsString(paramsString);
	}

	if (/^\d+$/.test(query[0])) {
		cid = Number(query.shift());
	}

	if (query.length > 0) {
		action = query.pop();
		pathParams = query;
	}

	if (cid === undefined && action !== 'login') {
		this.redirect('login');
		return;
	}

	if (hash[0] != this._state) {
		switch (action) {
			case 'databases':
			case 'processlist':
			case 'users':
				this.explore({cid: cid, show: action});
				break;
			case 'status':
			case 'variables':
			case 'charsets':
			case 'engines':
				this._sidebar.highlight('status');
				this._server.info({cid: cid, show: action});
				break;
			case 'login':
				this._auth.show(params.id);
				break;
			//
			case 'tables':
			case 'views':
			case 'triggers':
			case 'routines':
				this.explore({cid: cid, show: action, from: pathParams[0]});
				break;
			//
			case 'browse':
				this.browser.browse({cid: cid, browse: pathParams[1], from: pathParams[0]});
				break;
			case 'sql':
				this.browser.sql({cid: cid, db: pathParams[0]});
				break;
			case 'columns':
				this._sidebar.highlight('columns', {'database': pathParams[0], 'table': pathParams[1]});
				this.table.edit({cid: cid, table: pathParams[1], from: pathParams[0]});
				break;
			case 'flush':
				this._cache.flush();
				this.redirect('databases', cid);
				return;
			default:
				this.redirect('databases', cid);
				return;
		}

		this._state = hash[0];
	}
};

/**
 * Change window title
 *
 * @param {Object} connection
 * @return {Juxta}
 */
Juxta.prototype._updateWindowTitle = function(connection) {
	//
	var title = '';

	if (connection) {
		//
		title = this._connection.get('name');

		if (!title) {
			title = connection.user + '@' +  connection.host;

			if (Number(connection.port) != Juxta.DEFAULT_PORT) {
				title += ':' + connection.port;
			}
		}
	}

	window.document.title = (title ? title + ' - '  : '')  + 'Juxta';

	return this;
};

/**
 * Fix header links href attr
 *
 * @param {Object} connection
 * @return {Juxta}
 */
Juxta.prototype._repairHeaderLinks = function(connection) {
	//
	$('.header a[name]').each(function(i, link) {
		$(link).attr('href', '#/' + connection.cid + '/' + $(link).attr('name'));
	});

	return this;
};

/**
 * Show the appliaction
 *
 * @return {Juxta}
 */
Juxta.prototype.show = function() {
	$('#sidebar:not(._hidden)').slideDown(250);
	$('.modal').hide();
	if ($('#applications').not(':visible')) {
		$('#applications').fadeIn(250);
		$('#header h1, #header .header-links').fadeIn(250);
	}

	return this;
};

/**
 * Hide
 *
 * @return {Juxta}
 */
Juxta.prototype.hide = function() {
	//
	$('#header h1, #header .header-links, #sidebar, #applications, .modal, .context').hide();

	return this;
};

/**
 * @param {Object} params
 * @return {jqXHR}
 */
Juxta.prototype.explore = function(params) {
	//
	if (params.from) {
		this._sidebar.highlight(params.show, {'database': params.from});
		return this._explorer.explore(params);

	} else {
		this._sidebar.highlight(params.show);
		return this._explorer.explore(params);
	}
};

/**
 * Notifications shortcuts
 */
Juxta.prototype.notify = function(message, options) {
	return this._notification.show(message, options);
};

/**
 * Show the notification on loading
 *
 * @param {String} message
 * @param {Object} options
 */
Juxta.prototype.loading = function(message, options) {
	return this._notification.loading(message, options);
};

/**
 * Show error notification
 *
 * @param {String} message
 * @param {Object} options
 * @return {jQuery}
 */
Juxta.prototype.error = function(message, options) {
	return this._notification.show(message, $.extend({}, {type: 'error', hide: false, fast: true}, options));
};

/**
 * Show dialog box with message
 *
 * @param {String} message
 * @param {Object} options
 * @return {Juxta.Modal}
 */
Juxta.prototype.message = function(message, options) {
	return this.messageBox.show(options, message);
};

/**
 * Redirect
 *
 * @param {String} action
 * @param {Number} [cid] Connection ID
 * @return {Juxta}
 */
Juxta.prototype.redirect = function(action, cid) {
	//
	this._state = null;

	window.document.location.hash = '#/' + (typeof cid !== 'undefined' ? cid + '/' : '') + action;

	return this;
};

/**
 * @param {Number} cid
 */
Juxta.prototype._changeConnectionCallback = function(cid) {
	//
	if (cid === undefined) {
		return;
	}

	var text = this._connection.get('name'),
		hide = this.hide,
		connectionsList = $('.header-connections');

	if (!text) {
		text = this._connection.get('user') + '@' + this._connection.get('host');

		if (Number(this._connection.get('port')) !== Juxta.DEFAULT_PORT) {
			text += ':' + this._connection.get('port');
		}
	}

	$('.header-change-connection').text(text);

	this._updateWindowTitle(this._connection.get())
		._repairHeaderLinks(this._connection.get());

	connectionsList.empty();

	this._request.send({action: {get: 'connections'}, context: this, success: function(response) {
		$.each(response, $.proxy(function(key, connection) {
			//
			var li = $('<li>').addClass('header-connection'),
				a = $('<a>');

			if (connection.cid === undefined) {
				a.attr('href', '#/login?id=' + key);

			} else if (!this._connection.isCurrent(connection.cid)) {
				li.addClass('established');
				a.attr('href', '#/' + connection.cid + '/');

			} else {
				li.addClass('current');
			}

			connection.name = connection.user + '@' + connection.host;

			if (!connection.port) {
				connection.port = Juxta.DEFAULT_PORT;
			}

			if (connection.port !== Juxta.DEFAULT_PORT) {
				connection.name += ':' + connection.port;
			}

			if (a.attr('href')) {
				a.on('click', function() { hide(); } );
			}

			connectionsList.append(li.append(a.text(connection.name)));

		}, this));
	}});
};
<commit_msg>Fix oppening SQL editor<commit_after>/*global document, window, setInterval */

/**
 * Juxta 0.0.1
 *
 * Copyright (c) 2010-2011 Alexey Golovnya
 * Licensed under the MIT license
 * http://juxta.ru
 */

/**
 * @class Juxta
 */
var Juxta = function() {

	/**
	 * @type {String}
	 */
	this._state = null;

	/**
	 * @type {Juxta.Cache}
	 */
	this._cache = new Juxta.Cache();

	/**
	 * @type {Juxta.Connection}
	 */
	this._connection = new Juxta.Connection();

	/**
	 * @type {Juxta.Sidebar}
	 */
	this._sidebar = new Juxta.Sidebar('#sidebar', this._connection);

	/**
	 * Request/response
	 *
	 * @type Juxta.Request
	 */
	this._request = new Juxta.Request(this._connection, this._cache, {
		request: {
			beforeSend: this.loading.bind(this, null),
			complete: this.loading.bind(this, false),
			error: (function(xhr, status) {
				if (status == 'parsererror') {
					this.error('Parse error');
				} else {
					this.error(xhr.status + ' ' + xhr.statusText);
				}
			}).bind(this)
		},
		response: {
			connectionError: (function(response) { this.error(response.errormsg); this._auth.show(); }).bind(this),
			sessionNotFound: this.redirect.bind(this, 'login', undefined),
			queryError: (function(response) { this.error(response.errormsg); }).bind(this),
			error: this.error.bind(this, 'An error has occured')
		}
	});

	/**
	 * Notification messages
	 *
	 * @type {Juxta.Notification}
	 */
	this._notification = new Juxta.Notification($('.notifications').eq(0));

	/**
	 * @type {Juxta.Explorer}
	 */
	this._explorer = new Juxta.Explorer('.application.explorer', this._request);

	/**
	 * Table data browser
	 *
	 * @type {Juxta.Browser}
	 */
	this.browser = new Juxta.Browser('#data-browser', this._request);

	/**
	 * Table editor
	 *
	 * @type {Juxta.Table}
	 */
	this.table = new Juxta.Table('#table', this._request);

	/**
	 * Server information
	 *
	 * @type {Juxta.Server}
	 */
	this._server = new Juxta.Server('#server-info', this._request);

	/**
	 * Connect to server form
	 *
	 * @type {Juxta.Auth}
	 */
	this._auth = new Juxta.Auth('#login', this._request);

	/**
	 * Modal window for dialogs
	 *
	 * @type {Juxta.Modal}
	 */
	this.messageBox = new Juxta.Modal('#message');

	// Show Juxta when application ready
	$.each([this._explorer, this._server, this.browser, this.table], (function(i, application) {
		application.on('ready', this.show.bind(this))
			.on('maximize', function() { $('#sidebar').addClass('_hidden'); })
			.on('restore', function() {
				$('#sidebar').removeClass('_hidden');
				if ($('#applications').is(':visible')) {
					$('#sidebar').show();
				}
			});
	}).bind(this));

	this._explorer.on('alert', this.message.bind(this))
		.on('modal-hide', this._notification.hide.bind(this._notification));

	//
	this._connection.on('change', this._changeConnectionCallback.bind(this));

	//
	this._auth
		.on('before-show', (function() { this.hide()._updateWindowTitle(); this._connection.reset(); }).bind(this))
		.on('login', (function(connection) {
			this._connection.set(connection.cid, connection);
			this.redirect('databases', connection.cid);
		}).bind(this))
		.on('logout', (function() { this._cache.flush(); this._updateWindowTitle().redirect('login'); }).bind(this))
		.on('change', (function(cid) { this.redirect('', cid); }).bind(this));

	this._auth.on('notify', (function(message, type, options) {
		if (type === 'error') {
			this.error(message, options);
		} else if (type === 'loading') {
			this.loading(message, options);
		} else {
			this.notify(message, options);
		}
	}).bind(this));

	// Header links

	$('#header a[name=about]').on('click', (function() { this.message($('#about').html(), {title: ''}); return false; }).bind(this));

	$('#header .sql a').on('click', (function() {
		//
		if (this.browser.is(':visible') && this.browser.mode == 'browse') {
			this.browser.toggleEditor();
			return false;
		}
	}).bind(this));

	$('.header-change-connection').on('click', function() {
		//
		var container = $('.header-connections-container'),
			list = container.find('.header-connections');

		container.css({right: ''}).toggle();

		if (container.is(':visible') && $('body').width() - container.offset().left < container.width()) {
			container.css({right: 7});
		}

		list.toggleClass('scroll', list.prop('scrollHeight') > list.prop('offsetHeight'));

		return false;
	});

	$('#header a[name=logout]').on('click', (function() { this._auth.logout(); return false; }).bind(this));

	// @todo Remove this
	$(document.body).on('click', function() {
		$('.context:visible').trigger('hide').hide();
	});

	//

	this.run();

};

/**
 * Default MySQL port
 *
 * @constant {Number}
 */
Juxta.DEFAULT_PORT = 3306;

/**
 * Run application
 *
 * @return {Juxta}
 */
Juxta.prototype.run = function() {
	//
	setInterval($.proxy(this.route, this), 200);

	return this;
};

/**
 *
 */
Juxta.prototype.route = function() {
	//
	var hash = window.location.hash.replace(/#\/?/g, '').split('?'),
		query = hash[0].split('/'),
		paramsString = hash[1],
		params = [],
		pathParams = [],
		cid,
		action;

	function parseParamsString(str) {
		//
		var ret = {},
			seg = str.replace(/^\?/,'').split('&'),
			len = seg.length, i = 0, s;

		for (; i<len; i++) {
			if (!seg[i]) {
				continue;
			}
			s = seg[i].split('=');
			ret[decodeURIComponent(s[0])] = decodeURIComponent(s[1]);
		}

		return ret;
	}

	if (paramsString) {
		params = parseParamsString(paramsString);
	}

	if (/^\d+$/.test(query[0])) {
		cid = Number(query.shift());
	}

	if (query.length > 0) {
		action = query.pop();
		pathParams = query;
	}

	if (cid === undefined && action !== 'login') {
		this.redirect('login');
		return;
	}

	if (hash[0] != this._state) {
		switch (action) {
			case 'databases':
			case 'processlist':
			case 'users':
				this.explore({cid: cid, show: action});
				break;
			case 'status':
			case 'variables':
			case 'charsets':
			case 'engines':
				this._sidebar.highlight('status');
				this._server.info({cid: cid, show: action});
				break;
			case 'login':
				this._auth.show(params.id);
				break;
			//
			case 'tables':
			case 'views':
			case 'triggers':
			case 'routines':
				this.explore({cid: cid, show: action, from: pathParams[0]});
				break;
			//
			case 'browse':
				this.browser.browse({cid: cid, browse: pathParams[1], from: pathParams[0]});
				break;
			case 'sql':
				this.browser.sql({cid: cid, db: pathParams[0]});
				break;
			case 'columns':
				this._sidebar.highlight('columns', {'database': pathParams[0], 'table': pathParams[1]});
				this.table.edit({cid: cid, table: pathParams[1], from: pathParams[0]});
				break;
			case 'flush':
				this._cache.flush();
				this.redirect('databases', cid);
				return;
			default:
				this.redirect('databases', cid);
				return;
		}

		this._state = hash[0];
	}
};

/**
 * Change window title
 *
 * @param {Object} connection
 * @return {Juxta}
 */
Juxta.prototype._updateWindowTitle = function(connection) {
	//
	var title = '';

	if (connection) {
		//
		title = this._connection.get('name');

		if (!title) {
			title = connection.user + '@' +  connection.host;

			if (Number(connection.port) != Juxta.DEFAULT_PORT) {
				title += ':' + connection.port;
			}
		}
	}

	window.document.title = (title ? title + ' - '  : '')  + 'Juxta';

	return this;
};

/**
 * Fix header links href attr
 *
 * @param {Object} connection
 * @return {Juxta}
 */
Juxta.prototype._repairHeaderLinks = function(connection) {
	//
	$('.header a[name]').each(function(i, link) {
		$(link).attr('href', '#/' + connection.cid + '/' + $(link).attr('name'));
	});

	return this;
};

/**
 * Show the appliaction
 *
 * @return {Juxta}
 */
Juxta.prototype.show = function() {
	$('#sidebar:not(._hidden)').slideDown(250);
	$('.modal').hide();
	if ($('#applications').not(':visible')) {
		$('#applications').fadeIn(250);
		$('#header h1, #header .header-links').fadeIn(250);
	}

	return this;
};

/**
 * Hide
 *
 * @return {Juxta}
 */
Juxta.prototype.hide = function() {
	//
	$('#header h1, #header .header-links, #sidebar, #applications, .modal, .context').hide();

	return this;
};

/**
 * @param {Object} params
 * @return {jqXHR}
 */
Juxta.prototype.explore = function(params) {
	//
	if (params.from) {
		this._sidebar.highlight(params.show, {'database': params.from});
		return this._explorer.explore(params);

	} else {
		this._sidebar.highlight(params.show);
		return this._explorer.explore(params);
	}
};

/**
 * Notifications shortcuts
 */
Juxta.prototype.notify = function(message, options) {
	return this._notification.show(message, options);
};

/**
 * Show the notification on loading
 *
 * @param {String} message
 * @param {Object} options
 */
Juxta.prototype.loading = function(message, options) {
	return this._notification.loading(message, options);
};

/**
 * Show error notification
 *
 * @param {String} message
 * @param {Object} options
 * @return {jQuery}
 */
Juxta.prototype.error = function(message, options) {
	return this._notification.show(message, $.extend({}, {type: 'error', hide: false, fast: true}, options));
};

/**
 * Show dialog box with message
 *
 * @param {String} message
 * @param {Object} options
 * @return {Juxta.Modal}
 */
Juxta.prototype.message = function(message, options) {
	return this.messageBox.show(options, message);
};

/**
 * Redirect
 *
 * @param {String} action
 * @param {Number} [cid] Connection ID
 * @return {Juxta}
 */
Juxta.prototype.redirect = function(action, cid) {
	//
	this._state = null;

	window.document.location.hash = '#/' + (typeof cid !== 'undefined' ? cid + '/' : '') + action;

	return this;
};

/**
 * @param {Number} cid
 */
Juxta.prototype._changeConnectionCallback = function(cid) {
	//
	if (cid === undefined) {
		return;
	}

	var text = this._connection.get('name'),
		hide = this.hide,
		connectionsList = $('.header-connections');

	if (!text) {
		text = this._connection.get('user') + '@' + this._connection.get('host');

		if (Number(this._connection.get('port')) !== Juxta.DEFAULT_PORT) {
			text += ':' + this._connection.get('port');
		}
	}

	$('.header-change-connection').text(text);

	this._updateWindowTitle(this._connection.get())
		._repairHeaderLinks(this._connection.get());

	connectionsList.empty();

	this._request.send({action: {get: 'connections'}, context: this, success: function(response) {
		$.each(response, $.proxy(function(key, connection) {
			//
			var li = $('<li>').addClass('header-connection'),
				a = $('<a>');

			if (connection.cid === undefined) {
				a.attr('href', '#/login?id=' + key);

			} else if (!this._connection.isCurrent(connection.cid)) {
				li.addClass('established');
				a.attr('href', '#/' + connection.cid + '/');

			} else {
				li.addClass('current');
			}

			connection.name = connection.user + '@' + connection.host;

			if (!connection.port) {
				connection.port = Juxta.DEFAULT_PORT;
			}

			if (connection.port !== Juxta.DEFAULT_PORT) {
				connection.name += ':' + connection.port;
			}

			if (a.attr('href')) {
				a.on('click', function() { hide(); } );
			}

			connectionsList.append(li.append(a.text(connection.name)));

		}, this));
	}});
};
<|endoftext|>


<commit_before>/**
 * @ngdoc object
 * @name pascalprecht.translate.$translateDefaultInterpolation
 * @requires $interpolate
 *
 * @description
 * Uses angular's `$interpolate` services to interpolate strings against some values.
 *
 * Be aware to configure a proper sanitization strategy.
 *
 * See also:
 * * {@link pascalprecht.translate.$translateSanitization}
 *
 * @return {object} $translateDefaultInterpolation Interpolator service
 */
angular.module('pascalprecht.translate').factory('$translateDefaultInterpolation', $translateDefaultInterpolation);

function $translateDefaultInterpolation ($interpolate, $translateSanitization) {

  'use strict';

  var $translateInterpolator = {},
      $locale,
      $identifier = 'default';

  /**
   * @ngdoc function
   * @name pascalprecht.translate.$translateDefaultInterpolation#setLocale
   * @methodOf pascalprecht.translate.$translateDefaultInterpolation
   *
   * @description
   * Sets current locale (this is currently not use in this interpolation).
   *
   * @param {string} locale Language key or locale.
   */
  $translateInterpolator.setLocale = function (locale) {
    $locale = locale;
  };

  /**
   * @ngdoc function
   * @name pascalprecht.translate.$translateDefaultInterpolation#getInterpolationIdentifier
   * @methodOf pascalprecht.translate.$translateDefaultInterpolation
   *
   * @description
   * Returns an identifier for this interpolation service.
   *
   * @returns {string} $identifier
   */
  $translateInterpolator.getInterpolationIdentifier = function () {
    return $identifier;
  };

  /**
   * @deprecated will be removed in 3.0
   * @see {@link pascalprecht.translate.$translateSanitization}
   */
  $translateInterpolator.useSanitizeValueStrategy = function (value) {
    $translateSanitization.useStrategy(value);
    return this;
  };

  /**
   * @ngdoc function
   * @name pascalprecht.translate.$translateDefaultInterpolation#interpolate
   * @methodOf pascalprecht.translate.$translateDefaultInterpolation
   *
   * @description
   * Interpolates given value agains given interpolate params using angulars
   * `$interpolate` service.
   *
   * Since AngularJS 1.5, `value` must not be a string but can be anything input.
   *
   * @param value translation
   * @param interpolationParams interpolation params
   * @param context current context (filter, directive, service)
   * @param sanitizeStrategy sanitize strategy
   * @param translationId current translationId
   *
   * @returns {string} interpolated string
   */
  $translateInterpolator.interpolate = function (value, interpolationParams, context, sanitizeStrategy, translationId) {
    interpolationParams = interpolationParams || {};
    interpolationParams = $translateSanitization.sanitize(interpolationParams, 'params', sanitizeStrategy, context);

    var interpolatedText;
    if (angular.isNumber(value)) {
      // numbers are safe
      interpolatedText = '' + value;
    } else if (angular.isString(value)) {
      // strings must be interpolated (that's the job here)
      interpolatedText = $interpolate(value)(interpolationParams);
      interpolatedText = $translateSanitization.sanitize(interpolatedText, 'text', sanitizeStrategy, context);
    } else {
      // neither a number or a string, cant interpolate => empty string
      interpolatedText = '';
    }

    return interpolatedText;
  };

  return $translateInterpolator;
}

$translateDefaultInterpolation.displayName = '$translateDefaultInterpolation';
<commit_msg>chore(): fix lint issue<commit_after>/**
 * @ngdoc object
 * @name pascalprecht.translate.$translateDefaultInterpolation
 * @requires $interpolate
 *
 * @description
 * Uses angular's `$interpolate` services to interpolate strings against some values.
 *
 * Be aware to configure a proper sanitization strategy.
 *
 * See also:
 * * {@link pascalprecht.translate.$translateSanitization}
 *
 * @return {object} $translateDefaultInterpolation Interpolator service
 */
angular.module('pascalprecht.translate').factory('$translateDefaultInterpolation', $translateDefaultInterpolation);

function $translateDefaultInterpolation ($interpolate, $translateSanitization) {

  'use strict';

  var $translateInterpolator = {},
      $locale,
      $identifier = 'default';

  /**
   * @ngdoc function
   * @name pascalprecht.translate.$translateDefaultInterpolation#setLocale
   * @methodOf pascalprecht.translate.$translateDefaultInterpolation
   *
   * @description
   * Sets current locale (this is currently not use in this interpolation).
   *
   * @param {string} locale Language key or locale.
   */
  $translateInterpolator.setLocale = function (locale) {
    $locale = locale;
  };

  /**
   * @ngdoc function
   * @name pascalprecht.translate.$translateDefaultInterpolation#getInterpolationIdentifier
   * @methodOf pascalprecht.translate.$translateDefaultInterpolation
   *
   * @description
   * Returns an identifier for this interpolation service.
   *
   * @returns {string} $identifier
   */
  $translateInterpolator.getInterpolationIdentifier = function () {
    return $identifier;
  };

  /**
   * @deprecated will be removed in 3.0
   * @see {@link pascalprecht.translate.$translateSanitization}
   */
  $translateInterpolator.useSanitizeValueStrategy = function (value) {
    $translateSanitization.useStrategy(value);
    return this;
  };

  /**
   * @ngdoc function
   * @name pascalprecht.translate.$translateDefaultInterpolation#interpolate
   * @methodOf pascalprecht.translate.$translateDefaultInterpolation
   *
   * @description
   * Interpolates given value agains given interpolate params using angulars
   * `$interpolate` service.
   *
   * Since AngularJS 1.5, `value` must not be a string but can be anything input.
   *
   * @param value translation
   * @param interpolationParams interpolation params
   * @param context current context (filter, directive, service)
   * @param sanitizeStrategy sanitize strategy
   * @param translationId current translationId
   *
   * @returns {string} interpolated string
   */
  $translateInterpolator.interpolate = function (value, interpolationParams, context, sanitizeStrategy/*, translationId*/) {
    interpolationParams = interpolationParams || {};
    interpolationParams = $translateSanitization.sanitize(interpolationParams, 'params', sanitizeStrategy, context);

    var interpolatedText;
    if (angular.isNumber(value)) {
      // numbers are safe
      interpolatedText = '' + value;
    } else if (angular.isString(value)) {
      // strings must be interpolated (that's the job here)
      interpolatedText = $interpolate(value)(interpolationParams);
      interpolatedText = $translateSanitization.sanitize(interpolatedText, 'text', sanitizeStrategy, context);
    } else {
      // neither a number or a string, cant interpolate => empty string
      interpolatedText = '';
    }

    return interpolatedText;
  };

  return $translateInterpolator;
}

$translateDefaultInterpolation.displayName = '$translateDefaultInterpolation';
<|endoftext|>


<commit_before>dojo.require("dojo.io.script");
dojo.require("dojox.dtl.dom");

dojo.require("dojox.dtl.tag.loader");
dojo.require("dojox.dtl.tag.logic");
dojo.require("dojox.dtl.tag.loop");
dojo.require("dojox.dtl.filter.lists");
dojo.require("dojox.dtl.tag.logic");
dojo.require("dojox.dtl.filter.dates");
dojo.require("dojox.dtl.utils.date");
dojo.require("dojox.dtl.filter.strings");
dojo.require("dojox.dtl.filter.htmlstrings");

dojo.require("dijit._Widget");
dojo.require("dijit._Templated");

// Twitter date filter
dojo.provide("uxebu.dtl.filter");
dojo.require("dojo.date.locale");

uxebu.dtl.filter = {
	ago: function(value, arg){
		// summary:
		//		Simple filter for twitter style display of timestamp

		var	postDate = new Date(value),
			today = new Date(),
			yesterday = dojo.date.add(today, "day", -1),
			postStr;

		yesterday.setHours(23);
		yesterday.setMinutes(59);
		yesterday.setSeconds(59);
		if (postDate <= yesterday){
			postStr = dojo.date.locale.format(postDate);
		}else{
			var diff = dojo.date.difference(postDate, today, "minute"),
				diffObj;

			if (diff > 59){
				diff = Math.round(diff/60);
				diffObj = {
					diff: "about " + diff,
					unit: diff > 1 ? "hours" : "hour"
				};
			}else if (diff > 0){
				diffObj = {
					diff: diff,
					unit: diff > 1 ? "minutes" : "minute"
				};
			}else{
				diffObj = {
					diff: "",
					unit: "just a moment"
				};
			}
			postStr = diffObj.diff + " " + diffObj.unit + " ago";
		}
		return postStr;
	}
}

dojo.ready(function(){
	dojox.dtl.register.filters("uxebu.dtl", {"filter": ["ago"]});

	dojo.provide("learn");
	learn = {
		templates: {
			loader: '

',
			noResults: '

No more results, maybe watch some videos on one of the previous pages, they rock.

',
			about: '

Hi there,
learnjs is a simple Q&A tool by uxebu based on twitter and vimeo.
Simply ask a JavaScript question or provide an answer in a one minute, max. five lines of code video.

If you are interested in making it better or using it in your own environment,
clone/fork the repository at github, or send us a message via twitter (@uxebu) or our website
Background image curtesy of ChicagoGeek

<button class="button" onclick="uxebu.widget.popup.hide();">Close</button>

',
			questions: '{% if not questions|length %}

Hey, no js questions? Just ask one by sending a tweet to @learnjs

{% endif %}{% for q in questions %}

{{ q.text|safe }}
{{ q.created_at|ago }} by {{ q.from_user }}

{% endfor %}',
			answers: '{% for a in answers %}

{{ a.video.title }}
{{ a.video.upload_date|ago }} by {{ a.video.user_name }}
{{ a.video.html|safe }}

{% endfor %}',
			questionPostConfirm: '

Thank you, it might take a few seconds (up to a minute in bad twitter times) until your question has reached the wise ninjas of the interpipes.
If the question doesn\'t show up straight away, just press the reload button a few times.

<button class="button" onclick="uxebu.widget.popup.hide(); learn.getQuestions();">Close</button>

',
		},
		config: {
			limit: 5,
			offset: 1
		},
		currentTab: 0,
		init: function(){
			// summary:
			//		Initializes learnjs

			// Setting up page navigation
			dojo.query(".menu > .about").onclick(function(e){
				dojo.stopEvent(e);
				uxebu.widget.popup.show(learn.templates.about);
			});

			// Parse margin and nomargin loader
			var loaderTempl = new dojox.dtl.Template(learn.templates.loader);
			learn.templates.loaderMargin = loaderTempl.render(new dojox.dtl.Context({marginRight: "marginRight"}));
			learn.templates.loaderNoMargin = loaderTempl.render(new dojox.dtl.Context({marginRight: ""}));

			learn.nodeLists = {
				buttonPrev: dojo.query(".button.previous"),
				buttonNext: dojo.query(".button.next"),
				pageNo: dojo.query(".pageNo"),
				tabs: dojo.query(".tab"),
				tabContents: dojo.query(".tabContents")
			}

			// Set up tabs
			learn.nodeLists.tabs.connect("onclick", function(e){
				var node = e.target;
				while (!dojo.hasClass(node, "tab")){
					node = node.parentNode;
				}

				var index = dojo.indexOf(learn.nodeLists.tabs, node);
				if (index != learn.currentTab){
					learn.skip(index);
				}
			});

			// Connect to search box to auto search on enter
			dojo.query(".search").connect("onkeydown", function(e){
				if (e.keyCode == dojo.keys.ENTER){
					learn.getAnswers();
				}
			});

			learn.getQuestions();
			learn.getAnswers();
		},
		skip: function(index){
			// summary:
			//		Handles skipping to a different tab.

			dojo.removeClass(learn.nodeLists.tabs[learn.currentTab], "active");
			dojo.addClass(learn.nodeLists.tabContents[learn.currentTab], "displayNone");
			learn.currentTab = index;
			dojo.removeClass(learn.nodeLists.tabContents[learn.currentTab], "displayNone");
			dojo.addClass(learn.nodeLists.tabs[learn.currentTab], "active");
		},
		getQuestions: function(){
			// summary:
			//		Gets latest tweets.

			dojo.byId("questions").innerHTML = learn.templates.loaderNoMargin;
			dojo.io.script.get({
				url: "http://search.twitter.com/search.json?q=learnjs", // With questionmark +%3F
				jsonp: "callback",
				load: function(data){
					if (data.results){
						learn.renderQuestions(data.results);
					}
				}
			});
		},
		renderQuestions: function(questions){
			// summary:
			//		Renders questions and twitter feed in general.

			var 	tmpl = new dojox.dtl.Template(learn.templates.questions),
				node = dojo.byId("questions");

			node.innerHTML = ""; // FIXME?!!!
			var context = new dojox.dtl.Context({questions: questions});
			node.appendChild(dojo._toDom(tmpl.render(context)));
		},
		getAnswers: function(type, search){
			// summary:
			//		Gets new answers from yql table.

			switch (type){
				case 'next':
					learn.config.offset += learn.config.limit;
					break;
				case 'prev':
					if (learn.config.offset > 1){
						learn.config.offset -= learn.config.limit;
					}
					break;
			}

			// If search input has a value we make a search is provided we make a search, otherwise list all
			var search = dojo.byId("search").value;
			if (search && search.length > 2){
				// Reset counter on first search
				if (!learn.searchReset){
					learn.config.offset = 1;
					learn.config.limit = 5;
					learn.searchReset = true;
				}
				var url = "http://query.yahooapis.com/v1/public/yql?q=use%20%22http%3A%2F%2Flearnjs.org%2Fyql%2Fvideosearch.xml%22%20as%20videos%3B%20select%20*%20from%20videos%20where%20search%3D%22"+search+"%22%20limit%20"+learn.config.limit+"%20offset%20"+learn.config.offset+"&format=json&_maxage=3600&_rnd=20100802";
			}else{
				// Display alert when search term is only 2 characters long
				if (search && search.length <= 2){
					alert("Search phrase needs to be at least three characters long");
				}
				// Reset counter on first blank lookup
				if (learn.searchReset){
					learn.config.offset = 1;
					learn.config.limit = 5;
				}
				learn.searchReset = false;
				var url = "http://query.yahooapis.com/v1/public/yql?q=use%20%22http%3A%2F%2Flearnjs.org%2Fyql%2Fvideos.xml%22%20as%20videos%3B%20select%20*%20from%20videos%20limit%20"+learn.config.limit+"%20offset%20"+learn.config.offset+"&format=json&_maxage=3600&_rnd=20100803";
			}

			dojo.byId("answers").innerHTML = learn.templates.loaderMargin;
			dojo.io.script.get({
				url: url,
				jsonp: "callback",
				load: function(data){
					// YQL has a weird bug where it resurns an object when resultset is one.
					if (data.query.count == 1 && data.query.results.videos.video){
						var video = data.query.results.videos.video;
						data.query.results.videos = [{ video: data.query.results.videos.video }];
					}
					if (data.query.count == 0){
						learn.nodeLists.buttonNext.attr("disabled", true);
						if (learn.config.offset > 1){
							learn.nodeLists.buttonPrev.attr("disabled", false);
						}

						dojo.byId("answers").innerHTML = learn.templates.noResults;
					}else{
						// Disable next button if resultset < limit
						learn.nodeLists.buttonNext.attr("disabled", data.query.count < learn.config.limit);
						learn.nodeLists.buttonPrev.attr("disabled", !(learn.config.offset > 1));

						learn.renderAnswers(data.query.results.videos);
					}

					learn.nodeLists.pageNo.attr("innerHTML", (learn.config.offset+learn.config.limit-1)/learn.config.limit)
				}
			});
		},
		renderAnswers: function(answers){
			// summary:
			//		Renders available video answers from yql table.

			var	tmpl = new dojox.dtl.Template(learn.templates.answers),
				node = dojo.byId("answers");

			node.innerHTML = ""; // FIXME?!!!

			var context = new dojox.dtl.Context({
				answers: answers
			});
			node.appendChild(dojo._toDom(tmpl.render(context)));
		}
	}

	learn.init();
});
<commit_msg>fixed ago dtl filter<commit_after>dojo.require("dojo.io.script");
dojo.require("dojox.dtl.dom");

dojo.require("dojox.dtl.tag.loader");
dojo.require("dojox.dtl.tag.logic");
dojo.require("dojox.dtl.tag.loop");
dojo.require("dojox.dtl.filter.lists");
dojo.require("dojox.dtl.tag.logic");
dojo.require("dojox.dtl.filter.dates");
dojo.require("dojox.dtl.utils.date");
dojo.require("dojox.dtl.filter.strings");
dojo.require("dojox.dtl.filter.htmlstrings");

dojo.require("dijit._Widget");
dojo.require("dijit._Templated");

// Twitter date filter
dojo.provide("uxebu.dtl.filter");
dojo.require("dojo.date.locale");

uxebu.dtl.filter = {
	ago: function(value, arg){
		// summary:
		//		Simple filter for twitter style display of timestamp

		var	postDate = dojo.date.locale.parse(value, {datePattern: 'y-M-d H:m:s', selector: 'date'}),
			today = new Date(),
			yesterday = dojo.date.add(today, "day", -1),
			postStr;

		yesterday.setHours(23);
		yesterday.setMinutes(59);
		yesterday.setSeconds(59);
		if (postDate <= yesterday){
			postStr = dojo.date.locale.format(postDate);
		}else{
			var diff = dojo.date.difference(postDate, today, "minute"),
				diffObj;

			if (diff > 59){
				diff = Math.round(diff/60);
				diffObj = {
					diff: "about " + diff,
					unit: diff > 1 ? "hours" : "hour"
				};
			}else if (diff > 0){
				diffObj = {
					diff: diff,
					unit: diff > 1 ? "minutes" : "minute"
				};
			}else{
				diffObj = {
					diff: "",
					unit: "just a moment"
				};
			}
			postStr = diffObj.diff + " " + diffObj.unit + " ago";
		}
		return postStr;
	}
}

dojo.ready(function(){
	dojox.dtl.register.filters("uxebu.dtl", {"filter": ["ago"]});

	dojo.provide("learn");
	learn = {
		templates: {
			loader: '

',
			noResults: '

No more results, maybe watch some videos on one of the previous pages, they rock.

',
			about: '

Hi there,
learnjs is a simple Q&A tool by uxebu based on twitter and vimeo.
Simply ask a JavaScript question or provide an answer in a one minute, max. five lines of code video.

If you are interested in making it better or using it in your own environment,
clone/fork the repository at github, or send us a message via twitter (@uxebu) or our website
Background image curtesy of ChicagoGeek

<button class="button" onclick="uxebu.widget.popup.hide();">Close</button>

',
			questions: '{% if not questions|length %}

Hey, no js questions? Just ask one by sending a tweet to @learnjs

{% endif %}{% for q in questions %}

{{ q.text|safe }}
{{ q.created_at|ago }} by {{ q.from_user }}

{% endfor %}',
			answers: '{% for a in answers %}

{{ a.video.title }}
{{ a.video.upload_date|ago }} by {{ a.video.user_name }}
{{ a.video.html|safe }}

{% endfor %}',
			questionPostConfirm: '

Thank you, it might take a few seconds (up to a minute in bad twitter times) until your question has reached the wise ninjas of the interpipes.
If the question doesn\'t show up straight away, just press the reload button a few times.

<button class="button" onclick="uxebu.widget.popup.hide(); learn.getQuestions();">Close</button>

',
		},
		config: {
			limit: 5,
			offset: 1
		},
		currentTab: 0,
		init: function(){
			// summary:
			//		Initializes learnjs

			// Setting up page navigation
			dojo.query(".menu > .about").onclick(function(e){
				dojo.stopEvent(e);
				uxebu.widget.popup.show(learn.templates.about);
			});

			// Parse margin and nomargin loader
			var loaderTempl = new dojox.dtl.Template(learn.templates.loader);
			learn.templates.loaderMargin = loaderTempl.render(new dojox.dtl.Context({marginRight: "marginRight"}));
			learn.templates.loaderNoMargin = loaderTempl.render(new dojox.dtl.Context({marginRight: ""}));

			learn.nodeLists = {
				buttonPrev: dojo.query(".button.previous"),
				buttonNext: dojo.query(".button.next"),
				pageNo: dojo.query(".pageNo"),
				tabs: dojo.query(".tab"),
				tabContents: dojo.query(".tabContents")
			}

			// Set up tabs
			learn.nodeLists.tabs.connect("onclick", function(e){
				var node = e.target;
				while (!dojo.hasClass(node, "tab")){
					node = node.parentNode;
				}

				var index = dojo.indexOf(learn.nodeLists.tabs, node);
				if (index != learn.currentTab){
					learn.skip(index);
				}
			});

			// Connect to search box to auto search on enter
			dojo.query(".search").connect("onkeydown", function(e){
				if (e.keyCode == dojo.keys.ENTER){
					learn.getAnswers();
				}
			});

			learn.getQuestions();
			learn.getAnswers();
		},
		skip: function(index){
			// summary:
			//		Handles skipping to a different tab.

			dojo.removeClass(learn.nodeLists.tabs[learn.currentTab], "active");
			dojo.addClass(learn.nodeLists.tabContents[learn.currentTab], "displayNone");
			learn.currentTab = index;
			dojo.removeClass(learn.nodeLists.tabContents[learn.currentTab], "displayNone");
			dojo.addClass(learn.nodeLists.tabs[learn.currentTab], "active");
		},
		getQuestions: function(){
			// summary:
			//		Gets latest tweets.

			dojo.byId("questions").innerHTML = learn.templates.loaderNoMargin;
			dojo.io.script.get({
				url: "http://search.twitter.com/search.json?q=learnjs", // With questionmark +%3F
				jsonp: "callback",
				load: function(data){
					if (data.results){
						learn.renderQuestions(data.results);
					}
				}
			});
		},
		renderQuestions: function(questions){
			// summary:
			//		Renders questions and twitter feed in general.

			var 	tmpl = new dojox.dtl.Template(learn.templates.questions),
				node = dojo.byId("questions");

			node.innerHTML = ""; // FIXME?!!!
			var context = new dojox.dtl.Context({questions: questions});
			node.appendChild(dojo._toDom(tmpl.render(context)));
		},
		getAnswers: function(type, search){
			// summary:
			//		Gets new answers from yql table.

			switch (type){
				case 'next':
					learn.config.offset += learn.config.limit;
					break;
				case 'prev':
					if (learn.config.offset > 1){
						learn.config.offset -= learn.config.limit;
					}
					break;
			}

			// If search input has a value we make a search is provided we make a search, otherwise list all
			var search = dojo.byId("search").value;
			if (search && search.length > 2){
				// Reset counter on first search
				if (!learn.searchReset){
					learn.config.offset = 1;
					learn.config.limit = 5;
					learn.searchReset = true;
				}
				var url = "http://query.yahooapis.com/v1/public/yql?q=use%20%22http%3A%2F%2Flearnjs.org%2Fyql%2Fvideosearch.xml%22%20as%20videos%3B%20select%20*%20from%20videos%20where%20search%3D%22"+search+"%22%20limit%20"+learn.config.limit+"%20offset%20"+learn.config.offset+"&format=json&_maxage=3600&_rnd=20100802";
			}else{
				// Display alert when search term is only 2 characters long
				if (search && search.length <= 2){
					alert("Search phrase needs to be at least three characters long");
				}
				// Reset counter on first blank lookup
				if (learn.searchReset){
					learn.config.offset = 1;
					learn.config.limit = 5;
				}
				learn.searchReset = false;
				var url = "http://query.yahooapis.com/v1/public/yql?q=use%20%22http%3A%2F%2Flearnjs.org%2Fyql%2Fvideos.xml%22%20as%20videos%3B%20select%20*%20from%20videos%20limit%20"+learn.config.limit+"%20offset%20"+learn.config.offset+"&format=json&_maxage=3600&_rnd=20100803";
			}

			dojo.byId("answers").innerHTML = learn.templates.loaderMargin;
			dojo.io.script.get({
				url: url,
				jsonp: "callback",
				load: function(data){
					// YQL has a weird bug where it resurns an object when resultset is one.
					if (data.query.count == 1 && data.query.results.videos.video){
						var video = data.query.results.videos.video;
						data.query.results.videos = [{ video: data.query.results.videos.video }];
					}
					if (data.query.count == 0){
						learn.nodeLists.buttonNext.attr("disabled", true);
						if (learn.config.offset > 1){
							learn.nodeLists.buttonPrev.attr("disabled", false);
						}

						dojo.byId("answers").innerHTML = learn.templates.noResults;
					}else{
						// Disable next button if resultset < limit
						learn.nodeLists.buttonNext.attr("disabled", data.query.count < learn.config.limit);
						learn.nodeLists.buttonPrev.attr("disabled", !(learn.config.offset > 1));

						learn.renderAnswers(data.query.results.videos);
					}

					learn.nodeLists.pageNo.attr("innerHTML", (learn.config.offset+learn.config.limit-1)/learn.config.limit)
				}
			});
		},
		renderAnswers: function(answers){
			// summary:
			//		Renders available video answers from yql table.

			var	tmpl = new dojox.dtl.Template(learn.templates.answers),
				node = dojo.byId("answers");

			node.innerHTML = ""; // FIXME?!!!

			var context = new dojox.dtl.Context({
				answers: answers
			});
			node.appendChild(dojo._toDom(tmpl.render(context)));
		}
	}

	learn.init();
});
<|endoftext|>


<commit_before>'use strict';

const globalHooks = require('../../../hooks');
const hooks = require('feathers-hooks');
const auth = require('feathers-authentication');
const restrictToCurrentSchool = globalHooks.ifNotLocal(globalHooks.restrictToCurrentSchool);

function createInfoText(user, data){
	return "Ein neues Problem wurde gemeldet." + "\n"
	+ "User: " + user + "\n"
	+ "Kategorie: "+ data.category + "\n"
	+ "Betreff: " + data.subject + "\n"
	+ "Schaue für weitere Details und zur Bearbeitung bitte in den Helpdesk-Bereich der "+ data.cloud +".\n\n"
	+ "Mit freundlichen Grüßen\n"
	+ "Deine " + data.cloud;
}

function createFeedbackText(user, data){
	let text = "User: " + user + "\n"
	+ "Schule: " + data.schoolName + "\n"
	+ "Bereich ausgewählt: " + data.category + "\n";
	if (data.desire && data.desire != ""){
		text = text + "User schrieb folgendes: \n"
		+ "Als " + data.role + "\n"
        + "möchte ich " + data.desire + ",\n"
		+ "um " + data.benefit + ".\n"
		+ "Akzeptanzkriterien: " + data.acceptanceCriteria;
	} else {
		text = text + "User meldet folgendes: \n"
		+ "Problem Kurzbeschreibung: " + data.subject + "\n"
		+ "IST-Zustand: " + data.currentState + "\n"
		+ "SOLL-Zustand: " + data.targetState;
		if(data.notes) text = text + "\n Anmerkungen: " + data.notes;
	}
	return text;
}

const denyDbWriteOnType = hook => {
	if (hook.data.type === "contactHPI"){
		hook.result = {}; //interrupts db interaction
	}
	return hook;
};

exports.before = {
	all: [auth.hooks.authenticate('jwt')],
	find: [globalHooks.hasPermission('HELPDESK_VIEW')],
	get: [globalHooks.hasPermission('HELPDESK_VIEW')],
	create: [globalHooks.hasPermission('HELPDESK_CREATE'), restrictToCurrentSchool, denyDbWriteOnType],
	update: [globalHooks.hasPermission('HELPDESK_EDIT'), restrictToCurrentSchool],
	patch: [globalHooks.hasPermission('HELPDESK_EDIT'),globalHooks.permitGroupOperation, restrictToCurrentSchool],
	remove: [globalHooks.hasPermission('HELPDESK_CREATE'),globalHooks.permitGroupOperation, globalHooks.ifNotLocal(globalHooks.checkSchoolOwnership)]
};

const feedback = () => {
	return hook=>{
		const data=hook.data||{};
		if (data.type === "contactAdmin"){
			globalHooks.sendEmail(hook, {
				"subject": "Ein Problem wurde gemeldet.",
				"roles": ["helpdesk", "administrator"],
				"content": {
					"text": createInfoText(
						(hook.params.account||{}).username||"nouser",
						data)
				}
			});
			//TODO: NOTIFICATION SERVICE
		} else {
			globalHooks.sendEmail(hook, {
				"subject": data.subject||"nosubject",
				"emails": ["ticketsystem@schul-cloud.org"],
				"content": {
					"text": createFeedbackText(
						(hook.params.account||{}).username||"nouser",
						data
					)
				}
			});
		}
		return Promise.resolve(hook);
	};
 };

exports.after = {
	all: [],
	find: [],
	get: [],
	create: [feedback()],
	update: [],
	patch: [],
	remove: []
};
<commit_msg>added the instance (#402)<commit_after>'use strict';

const globalHooks = require('../../../hooks');
const hooks = require('feathers-hooks');
const auth = require('feathers-authentication');
const restrictToCurrentSchool = globalHooks.ifNotLocal(globalHooks.restrictToCurrentSchool);

function createInfoText(user, data){
	return "Ein neues Problem wurde gemeldet." + "\n"
	+ "User: " + user + "\n"
	+ "Kategorie: "+ data.category + "\n"
	+ "Betreff: " + data.subject + "\n"
	+ "Schaue für weitere Details und zur Bearbeitung bitte in den Helpdesk-Bereich der "+ data.cloud +".\n\n"
	+ "Mit freundlichen Grüßen\n"
	+ "Deine " + data.cloud;
}

function createFeedbackText(user, data){
	let text = "User: " + user + "\n"
	+ "Schule: " + data.schoolName + "\n"
	+ "Instanz: " + data.cloud + "\n"
	+ "Bereich ausgewählt: " + data.category + "\n";
	if (data.desire && data.desire != ""){
		text = text + "User schrieb folgendes: \n"
		+ "Als " + data.role + "\n"
        + "möchte ich " + data.desire + ",\n"
		+ "um " + data.benefit + ".\n"
		+ "Akzeptanzkriterien: " + data.acceptanceCriteria;
	} else {
		text = text + "User meldet folgendes: \n"
		+ "Problem Kurzbeschreibung: " + data.subject + "\n"
		+ "IST-Zustand: " + data.currentState + "\n"
		+ "SOLL-Zustand: " + data.targetState;
		if(data.notes) text = text + "\n Anmerkungen: " + data.notes;
	}
	return text;
}

const denyDbWriteOnType = hook => {
	if (hook.data.type === "contactHPI"){
		hook.result = {}; //interrupts db interaction
	}
	return hook;
};

exports.before = {
	all: [auth.hooks.authenticate('jwt')],
	find: [globalHooks.hasPermission('HELPDESK_VIEW')],
	get: [globalHooks.hasPermission('HELPDESK_VIEW')],
	create: [globalHooks.hasPermission('HELPDESK_CREATE'), restrictToCurrentSchool, denyDbWriteOnType],
	update: [globalHooks.hasPermission('HELPDESK_EDIT'), restrictToCurrentSchool],
	patch: [globalHooks.hasPermission('HELPDESK_EDIT'),globalHooks.permitGroupOperation, restrictToCurrentSchool],
	remove: [globalHooks.hasPermission('HELPDESK_CREATE'),globalHooks.permitGroupOperation, globalHooks.ifNotLocal(globalHooks.checkSchoolOwnership)]
};

const feedback = () => {
	return hook=>{
		const data=hook.data||{};
		if (data.type === "contactAdmin"){
			globalHooks.sendEmail(hook, {
				"subject": "Ein Problem wurde gemeldet.",
				"roles": ["helpdesk", "administrator"],
				"content": {
					"text": createInfoText(
						(hook.params.account||{}).username||"nouser",
						data)
				}
			});
			//TODO: NOTIFICATION SERVICE
		} else {
			globalHooks.sendEmail(hook, {
				"subject": data.subject||"nosubject",
				"emails": ["ticketsystem@schul-cloud.org"],
				"content": {
					"text": createFeedbackText(
						(hook.params.account||{}).username||"nouser",
						data
					)
				}
			});
		}
		return Promise.resolve(hook);
	};
 };

exports.after = {
	all: [],
	find: [],
	get: [],
	create: [feedback()],
	update: [],
	patch: [],
	remove: []
};
<|endoftext|>


<commit_before>window.onload = function(){
    var accessToken = "pk.eyJ1IjoiaXNoaWp1IiwiYSI6ImNpaGRpNXh3MTAwMm11OW00Mmd5NHE1bXkifQ.5VJtYHibmT3X-aEQSKz1Ag";
    var map = L.map('map').setView([48.852966, 2.349902], 14);
    L.tileLayer('https://api.mapbox.com/v4/mapbox.streets/{z}/{x}/{y}.png?access_token='+accessToken).addTo(map);
    L.marker([48.810718, 2.384341]).addTo(map) .bindPopup("Thiery ici");
    L.marker([48.831366, 2.355818]).addTo(map) .bindPopup("Henri ici");
    L.marker([48.831405, 2.355545]).addTo(map) .bindPopup("Henri ici");
    L.marker([48.834115, 2.354413]).addTo(map) .bindPopup("Henri ici");
    L.marker([48.889579, 2.320540]).addTo(map) .bindPopup("Henri ici");
    L.marker([48.874001, 2.292688]).addTo(map) .bindPopup("Henri ici");
    L.marker([48.865871, 2.416285]).addTo(map) .bindPopup("Henri ici");
    L.marker([48.892965, 2.320154]).addTo(map) .bindPopup("Henri ici");
    L.marker([48.715685, 2.041376]).addTo(map) .bindPopup("Henri ici");
}
<commit_msg>tentative d'ajout d'image sur la map<commit_after>window.onload = function(){
    var accessToken = "pk.eyJ1IjoiaXNoaWp1IiwiYSI6ImNpaGRpNXh3MTAwMm11OW00Mmd5NHE1bXkifQ.5VJtYHibmT3X-aEQSKz1Ag";
    var map = L.map('map').setView([48.852966, 2.349902], 14);
    L.tileLayer('https://api.mapbox.com/v4/mapbox.streets/{z}/{x}/{y}.png?access_token='+accessToken).addTo(map);
    var LeafIcon = L.Icon.extend({
    options: {
        shadowUrl: 'http://wikipics.net/photos/20150125142221651988185.jpg',
        iconSize:     [38, 95],
        shadowSize:   [50, 64],
        iconAnchor:   [22, 94],
        shadowAnchor: [4, 62],
        popupAnchor:  [-3, -76]
    }
});
    var greenIcon = new LeafIcon({iconUrl: 'http://wikipics.net/photos/20150125142221651988185.jpg'});
    L.marker([48.889579, 2.320540], {icon: greenIcon}).addTo(map).bindPopup("I am a green leaf.");

    L.marker([48.810718, 2.384341]).addTo(map) .bindPopup("Thiery ici");
    L.marker([48.831366, 2.355818]).addTo(map) .bindPopup("Henri ici");
    L.marker([48.831405, 2.355545]).addTo(map) .bindPopup("Henri ici");
    L.marker([48.834115, 2.354413]).addTo(map) .bindPopup("Henri ici");
    L.marker([48.889579, 2.320540]).addTo(map) .bindPopup("Henri ici");
    L.marker([48.874001, 2.292688]).addTo(map) .bindPopup("Henri ici");
    L.marker([48.865871, 2.416285]).addTo(map) .bindPopup("Henri ici");
    L.marker([48.892965, 2.320154]).addTo(map) .bindPopup("Henri ici");
    L.marker([48.715685, 2.041376]).addTo(map) .bindPopup("Henri ici");
}

<|endoftext|>


<commit_before>/*$('#myModal').on('hidden.bs.modal', function () {
  $(this).removeData('bs.modal');
});

$('#myModal').on('show.bs.modal', function () {
       $(this).find('.modal-body').css({
              width:'auto', //probably not needed
              height:'auto', //probably not needed
              'max-height':'100%'
       });
});*/
var $modal = $('.modal');

// Show loader & then get content when modal is shown
$modal.on('hidden.bs.modal', function(e) {
  var paragraphs = $(e.relatedTarget).data('paragraphs');

  $(this)
    //.addClass('modal-scrollfix')
    .find('.modal-body')
    .html('loading...')
    .load('https://neuroimagem-pucrs.github.io/team/' + paragraphs, function() {
      // Use Bootstrap's built-in function to fix scrolling (to no avail)
      //$modal
        //.removeClass('modal-scrollfix')
        //.modal('handleUpdate');
    });
});
<commit_msg>Update modal.js<commit_after>/*$('#myModal').on('hidden.bs.modal', function () {
  $(this).removeData('bs.modal');
});

$('#myModal').on('show.bs.modal', function () {
       $(this).find('.modal-body').css({
              width:'auto', //probably not needed
              height:'auto', //probably not needed
              'max-height':'100%'
       });
});*/
var $modal = $('.modal');

// Show loader & then get content when modal is shown
$modal.on('show.bs.modal', function(e) {
  var paragraphs = $(e.relatedTarget).data('paragraphs');

  $(this)
    //.addClass('modal-scrollfix')
    .find('.modal-body')
    .html('loading...')
    .load('https://neuroimagem-pucrs.github.io/team/' + paragraphs, function() {
      // Use Bootstrap's built-in function to fix scrolling (to no avail)
      //$modal
        //.removeClass('modal-scrollfix')
        //.modal('handleUpdate');
    });
});
<|endoftext|>


<commit_before>$('a.modalButton').on('click', function(e) {
    var src = $(this).attr('data-src');
    var height = $(this).attr('data-height') || 300;
    var width = $(this).attr('data-width') || 400;

    $("#myModal iframe").attr({'src':src,
                        'height': height,
                        'width': width});
});
<commit_msg>Update modal.js<commit_after>$(document).ready(function() {

// Support for AJAX loaded modal window.
// Focuses on first input textbox after it loads the window.
$('[data-toggle="modal"]').click(function(e) {
	e.preventDefault();
	var url = $(this).attr('href');
	if (url.indexOf('#') == 0) {
		$(url).modal('open');
	} else {
		$.get(url, function(data) {
			$('
' + data + '
').modal();
		}).success(function() { $('input:text:visible:first').focus(); });
	}
});

});
<|endoftext|>


<commit_before><commit_msg>Input type submit<commit_after><|endoftext|>


<commit_before>var Wave = function(game, x, y) {
	this.game = game;
	Phaser.Sprite.call(this, this.game, x, y, 'wave');

	this.initialPos = { x: x, y: y }; // looks ugly, should be es6 already!
}

Wave.prototype = Object.create(Phaser.Sprite.prototype);
Wave.prototype.constructor = Wave;

Wave.update = function() {
	var time = this.game.time.time / 1000;
	this.y = this.initialPos.y + Math.sin(time) * 100;
}

var Ocean = function(game) {
	this.game = game;
	Phaser.Group.call(this, this.game);

	this.waves = [];

	for(var y = 0; y < 10; y++) {
		for(var x = 0; x < 10; x++) {
			/*var wave = game.add.image(x*100-100, y*75-100, 'wave');
			this.add(wave);

			this.waves.push(wave);*/

			var wave = new Wave(this.game, x * 100 - 100, y * 75 - 100);
			this.add(wave);

			this.waves.push(wave);
		}
	}
}

Ocean.prototype = Object.create(Phaser.Group.prototype);
Ocean.prototype.constructor = Ocean;

Ocean.prototype.update = function() {

}
<commit_msg>Edit ocean.js<commit_after>var Wave = function(game, x, y) {
	this.game = game;
	Phaser.Image.call(this, this.game, x, y, 'wave');

	this.initialPos = { x: x, y: y }; // looks ugly, should be es6 already!

}

Wave.prototype = Object.create(Phaser.Image.prototype);
Wave.prototype.constructor = Wave;

Wave.prototype.update = function() {
	console.log('test');
	var time = this.game.time.time / 1000;
	this.y = this.initialPos.y + Math.sin(time) * 100;
}

var Ocean = function(game) {
	this.game = game;
	Phaser.Group.call(this, this.game);

	this.waves = [];

	for(var y = 0; y < 10; y++) {
		for(var x = 0; x < 10; x++) {
			/*var wave = game.add.image(x*100-100, y*75-100, 'wave');
			this.add(wave);

			this.waves.push(wave);*/

			var wave = new Wave(this.game, x * 100 - 100, y * 75 - 100);
			this.add(wave);

			this.waves.push(wave);
		}
	}
}

Ocean.prototype = Object.create(Phaser.Group.prototype);
Ocean.prototype.constructor = Ocean;

Ocean.prototype.update = function() {

}
<|endoftext|>


<commit_before>'use strict';

/* globals FileError */

// get video file via XHR
// store with File API
// read Blob from File API and set as video src using createObjectUrl()
// play video
//

var peer = new Peer('2', {host: 'quotacle.com', port: 9000, path: '/'});
function getVideo(fileEntry) {
  peer.on('connection', function(conn){
    conn.on('data', function(uInt8Array){
      var blob = new Blob([uInt8Array], {
        type: 'video/webm'
      });
      writeToFile(fileEntry, blob);
    });
  });
}

window.MediaSource = window.MediaSource || window.WebKitMediaSource;
if (!!!window.MediaSource) {
      alert('MediaSource API is not available');
}

var mediaSource = new MediaSource();

var video = document.querySelector('video');
video.src = window.URL.createObjectURL( mediaSource );

mediaSource.addEventListener('sourceopen', sourceOpen, false);
mediaSource.addEventListener('webkitsourceopen', sourceOpen, false);

var numChunks = 5;

var i = 0;

function sourceOpen(e) {
    var sourceBuffer = mediaSource.addSourceBuffer( 'video/webm; codecs="vorbis,vp8"' );

    peer.on( 'connection', function( conn ) {
        conn.on( 'data', function(uInt8Array) {
            console.log("receiving chunk " + i);

            if( i < numChunks ) {

                var reader = new FileReader();

                reader.onload = function( idx ) {

                    console.log( "reader onload" );

                    var blob = new Blob( [uInt8Array], {type: 'video/webm'} );

                    sourceBuffer.appendBuffer( uInt8Array );

                    if( video.paused ) {
                        video.play();
                    }

                    if( i === numChunks - 1 ) {
                        mediaSource.endOfStream();
                    }

                }

                i++;
            }

        });
    });
}

function GET(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.responseType = 'arraybuffer';
  xhr.send();

  xhr.onload = function() {
    if (xhr.status !== 200) {

      alert('Unexpected status code ' + xhr.status + ' for ' + url);
      return false;
    }
    callback(new Uint8Array(xhr.response));
  };
}

<commit_msg>on update<commit_after>'use strict';

/* globals FileError */

// get video file via XHR
// store with File API
// read Blob from File API and set as video src using createObjectUrl()
// play video
//

var peer = new Peer('2', {host: 'quotacle.com', port: 9000, path: '/'});
function getVideo(fileEntry) {
  peer.on('connection', function(conn){
    conn.on('data', function(uInt8Array){
      var blob = new Blob([uInt8Array], {
        type: 'video/webm'
      });
      writeToFile(fileEntry, blob);
    });
  });
}

window.MediaSource = window.MediaSource || window.WebKitMediaSource;
if (!!!window.MediaSource) {
      alert('MediaSource API is not available');
}

var mediaSource = new MediaSource();

var video = document.querySelector('video');
video.src = window.URL.createObjectURL( mediaSource );

mediaSource.addEventListener('sourceopen', sourceOpen, false);
mediaSource.addEventListener('webkitsourceopen', sourceOpen, false);

var numChunks = 5;

var i = 0;

function sourceOpen(e) {
    var sourceBuffer = mediaSource.addSourceBuffer( 'video/webm; codecs="vorbis,vp8"' );

    peer.on( 'connection', function( conn ) {
        conn.on( 'data', function(uInt8Array) {
            console.log("receiving chunk " + i);

            if( i < numChunks ) {

                //var reader = new FileReader();

                sourceBuffer.on( 'update' ) {

                    console.log( "reader onload" );

                    var blob = new Blob( [uInt8Array], {type: 'video/webm'} );

                    sourceBuffer.appendBuffer( uInt8Array );

                    if( video.paused ) {
                        video.play();
                    }

                    if( i === numChunks - 1 ) {
                        mediaSource.endOfStream();
                    }

                }

                i++;
            }

        });
    });
}

function GET(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.responseType = 'arraybuffer';
  xhr.send();

  xhr.onload = function() {
    if (xhr.status !== 200) {

      alert('Unexpected status code ' + xhr.status + ' for ' + url);
      return false;
    }
    callback(new Uint8Array(xhr.response));
  };
}

<|endoftext|>