<commit_before>/*

The following section defines the Constants.h file

*/

// PIN Constants
var HackH = 48;
var HackA = 26;
var HackC = 24;
var HackK = 46;
var MiddleA = 36;
var ColaC = 38;
var ColaO = 28;
var ColaL = 40;
var ColaA = 30;
var RedZero = 44;
var RedOne = 34;
var RedTwo = 50;
var RedThree = 42;
var RedFour = 22;
var RedFive = 32;

// Lights
var Lights = [
    HackH,
    HackA,
    HackC,
    HackK,
    MiddleA,
    ColaC,
    ColaO,
    ColaL,
    ColaA,
    RedZero,
    RedOne,
    RedTwo,
    RedThree,
    RedFour,
    RedFive
];

// Letters
var letters = [
    HackH,
    HackA,
    HackC,
    HackK,
    MiddleA,
    ColaC,
    ColaO,
    ColaL,
    ColaA,
];

// Background
var background = [
    RedZero,
    RedOne,
    RedTwo,
    RedThree,
    RedFour,
    RedFive
];

// Timeouts
none = 0;
blinky = 1000;
minimal = 500;
normal = 800;
ish = 2000;
extended = 4000;

// Constants
var PATTERN_OFF = 0; // HIGH
var PATTERN_ON = 1; // LOW

/*

The following section defines global methods needed

*/

var signDrawer = require('./signDrawer.js');

var lightsState = [ ];

for (var idx in Lights) {
    lightsState[idx] = PATTERN_OFF;
}

var delay = function(time) {
    var entryTime = Date.now();
    while (true) {
        if (Date.now() - entryTime >= time) {
            break;
        }
    }
}

var digitalWrite = function(pin, highOrLow) {
    if (typeof(pin) === 'undefined') {
        throw new Error(`You have an undefined pin being set to: ${highOrLow}`)
    }
     console.log(`digitalWrite light:${Lights.indexOf(pin)} pin:${pin} highOrLow:${highOrLow}`);
     lightsState[Lights.indexOf(pin)] = highOrLow ? PATTERN_ON : PATTERN_OFF;
     signDrawer.drawSign(lightsState);

}

var sizeof = function(value) {
    return value.length;
}

var random = function(min, max) {
    // Min inclusive, max exclusive
    return Math.floor(Math.random() * ((max - 0) - min) + min);
}

var log = function(message, integer) {
    console.log(`${message} ${typeof(integer) !== 'undefined' ? integer : ''}`);
}

/*

The following section attempts, transpile, and run the arduino code

*/

var fs = require('fs');

var pathToArduinoCode = './CocaCola/CocaCola.ino';

console.log(process.argv);
process.argv.forEach(function (value, index, array) {
  pathToArduinoCode = (value == "--file" || value == "-f") && array[index+1] ? array[index+1] : pathToArduinoCode;
});

var arduinoCode = fs.readFileSync(pathToArduinoCode).toString();

console.log(`
Original Code:
######################################
${arduinoCode}
######################################
`);

var arduinoCodeParts = arduinoCode.split("// )'(");

var runableCode = arduinoCodeParts[1]
    .replace(/int ([A-Za-z]*) =/g, ' var $1 =') // Replace any instance of "int variable = n"
    .replace(/int /g, '') // Remove "int" from any instance of "int variable"
    .replace(/void loop\(\) {/, 'while (true) {') // Turn our main method into a while loop
    .replace(/void ([A-Za-z]*)/g, ' var $1 = function'); // Replace any "void function" with a javascript function definition

console.log(`
Runable Code:
######################################
${runableCode}
######################################
`);

console.log(`
Running code:
######################################
`);

eval(runableCode);
<commit_msg>Adjust logging<commit_after>/*

The following section defines the Constants.h file

*/

// PIN Constants
var HackH = 48;
var HackA = 26;
var HackC = 24;
var HackK = 46;
var MiddleA = 36;
var ColaC = 38;
var ColaO = 28;
var ColaL = 40;
var ColaA = 30;
var RedZero = 44;
var RedOne = 34;
var RedTwo = 50;
var RedThree = 42;
var RedFour = 22;
var RedFive = 32;

// Lights
var Lights = [
    HackH,
    HackA,
    HackC,
    HackK,
    MiddleA,
    ColaC,
    ColaO,
    ColaL,
    ColaA,
    RedZero,
    RedOne,
    RedTwo,
    RedThree,
    RedFour,
    RedFive
];

// Letters
var letters = [
    HackH,
    HackA,
    HackC,
    HackK,
    MiddleA,
    ColaC,
    ColaO,
    ColaL,
    ColaA,
];

// Background
var background = [
    RedZero,
    RedOne,
    RedTwo,
    RedThree,
    RedFour,
    RedFive
];

// Timeouts
none = 0;
blinky = 1000;
minimal = 500;
normal = 800;
ish = 2000;
extended = 4000;

// Constants
var PATTERN_OFF = 0; // HIGH
var PATTERN_ON = 1; // LOW

/*

The following section defines global methods needed

*/

var signDrawer = require('./signDrawer.js');

var lightsState = [ ];

for (var idx in Lights) {
    lightsState[idx] = PATTERN_OFF;
}

var delay = function(time) {
    var entryTime = Date.now();
    while (true) {
        if (Date.now() - entryTime >= time) {
            break;
        }
    }
}

var digitalWrite = function(pin, highOrLow) {
    if (typeof(pin) === 'undefined') {
        throw new Error(`You have an undefined pin being set to: ${highOrLow}`)
    }
     console.log(`digitalWrite light:${Lights.indexOf(pin)} pin:${pin} highOrLow:${highOrLow}`);
     lightsState[Lights.indexOf(pin)] = highOrLow ? PATTERN_ON : PATTERN_OFF;
     signDrawer.drawSign(lightsState);

}

var sizeof = function(value) {
    return value.length;
}

var random = function(min, max) {
    // Min inclusive, max exclusive
    return Math.floor(Math.random() * ((max - 0) - min) + min);
}

var log = function(message, integer) {
    console.log(`${message} ${typeof(integer) !== 'undefined' ? integer : ''}`);
}

/*

The following section attempts, transpile, and run the arduino code

*/

var fs = require('fs');

var pathToArduinoCode = './CocaCola/CocaCola.ino';

process.argv.forEach(function (value, index, array) {
  pathToArduinoCode = (value == "--file" || value == "-f") && array[index+1] ? array[index+1] : pathToArduinoCode;
});

console.log(`Loading: ${pathToArduinoCode}`);

var arduinoCode = fs.readFileSync(pathToArduinoCode).toString();

console.log(`
Original Code:
######################################
${arduinoCode}
######################################
`);

var arduinoCodeParts = arduinoCode.split("// )'(");

var runableCode = arduinoCodeParts[1]
    .replace(/int ([A-Za-z]*) =/g, ' var $1 =') // Replace any instance of "int variable = n"
    .replace(/int /g, '') // Remove "int" from any instance of "int variable"
    .replace(/void loop\(\) {/, 'while (true) {') // Turn our main method into a while loop
    .replace(/void ([A-Za-z]*)/g, ' var $1 = function'); // Replace any "void function" with a javascript function definition

console.log(`
Runable Code:
######################################
${runableCode}
######################################
`);

console.log(`
Running code:
######################################
`);

eval(runableCode);
<|endoftext|>


<commit_before>var endTimestamp = [
	[new Date(1504612800000), "It begins..."],
	[new Date(1513969500000), "Have a break."],
	[new Date(1514091600000), "On Chistmas Eve..."],
	[new Date(1514178000000), "Oh Christmas tree,
oh Christmas tree..."],
	[new Date(1514782800000), "\'Ere come 2018..."],
	[new Date(1516971600000), "Your examination is ready."],
	[new Date(1520622070000), "Wait for the break."],
	[new Date(1520658000000), "Have another break."],
	[new Date(1529668800000), "Your other examination
is ready."],
	[new Date(1530209100000), "It is finished."],
];

var daysInMs = 1000 * 60 * 60 * 24;
var hoursInMs = 1000 * 60 * 60;
var minutesInMs = 1000 * 60;

var timerIndex = 0;

function updateTime() {
	var timeUntil = endTimestamp[timerIndex][0].getTime() - new Date().getTime();
	var until = document.getElementById("until");

	if(timeUntil <= 0) {
		until.innerHTML = 'Since '+endTimestamp[timerIndex][0].toLocaleString()+'
'+endTimestamp[timerIndex][1];
		timeUntil = new Date().getTime() - endTimestamp[timerIndex][0].getTime();
	}
	else {
		until.innerHTML = 'Until '+endTimestamp[timerIndex][0].toLocaleString()+'
'+endTimestamp[timerIndex][1];
	}

	var days = document.getElementById("days");
	var hours = document.getElementById("hours");
	var minutes = document.getElementById("minutes");
	var seconds = document.getElementById("seconds");
	var millis = document.getElementById("millis");

	var daysUntil = timeUntil / daysInMs;
	var hoursUntil = (timeUntil / hoursInMs) % 24;
	var minutesUntil = (timeUntil / minutesInMs) % 60;
	var secondsUntil = (timeUntil / 1000) % 60;
	var millisUntil = timeUntil % 1000;

	days.textContent = Math.floor(daysUntil) + ' day';
	hours.textContent = Math.floor(hoursUntil) + ' hour';
	minutes.textContent = Math.floor(minutesUntil) + ' minute';
	seconds.textContent = Math.floor(secondsUntil) + ' second';
	millis.textContent = 'and ' + Math.floor(millisUntil) + ' millisecond';

	if(Math.floor(daysUntil) != 1) days.textContent = days.textContent + 's';
	if(Math.floor(hoursUntil) != 1) hours.textContent = hours.textContent + 's';
	if(Math.floor(minutesUntil) != 1) minutes.textContent = minutes.textContent + 's';
	if(Math.floor(secondsUntil) != 1) seconds.textContent = seconds.textContent + 's';
	if(Math.floor(millisUntil) != 1) millis.textContent = millis.textContent + 's';
}

function changeTimerSelect(change) {
	timerIndex += change;

	if(timerIndex < 0) timerIndex = endTimestamp.length - 1;
	else if(timerIndex >= endTimestamp.length) timerIndex = 0;

	var timerCount = document.getElementById("timerCount");
	if(timerCount != null)
	timerCount.innerText = "Timer {0}/{1}".replace("{0}", (timerIndex+1).toString()).replace("{1}", endTimestamp.length.toString());
}

window.setInterval(updateTime, 1);
<commit_msg>Update time stamps for countdown<commit_after>var endTimestamp = [
	[new Date(1545627600000), "On Chistmas Eve..."],
	[new Date(1545714000000), "Oh Christmas tree,
oh Christmas tree..."],
	[new Date(1546318799000), "\'Ere come 2019..."],
	[new Date(1546318800000), "A New Year is dawni g, arise from your sleep."],
];

var daysInMs = 1000 * 60 * 60 * 24;
var hoursInMs = 1000 * 60 * 60;
var minutesInMs = 1000 * 60;

var timerIndex = 0;

function updateTime() {
	var timeUntil = endTimestamp[timerIndex][0].getTime() - new Date().getTime();
	var until = document.getElementById("until");

	if(timeUntil <= 0) {
		until.innerHTML = 'Since '+endTimestamp[timerIndex][0].toLocaleString()+'
'+endTimestamp[timerIndex][1];
		timeUntil = new Date().getTime() - endTimestamp[timerIndex][0].getTime();
	}
	else {
		until.innerHTML = 'Until '+endTimestamp[timerIndex][0].toLocaleString()+'
'+endTimestamp[timerIndex][1];
	}

	var days = document.getElementById("days");
	var hours = document.getElementById("hours");
	var minutes = document.getElementById("minutes");
	var seconds = document.getElementById("seconds");
	var millis = document.getElementById("millis");

	var daysUntil = timeUntil / daysInMs;
	var hoursUntil = (timeUntil / hoursInMs) % 24;
	var minutesUntil = (timeUntil / minutesInMs) % 60;
	var secondsUntil = (timeUntil / 1000) % 60;
	var millisUntil = timeUntil % 1000;

	days.textContent = Math.floor(daysUntil) + ' day';
	hours.textContent = Math.floor(hoursUntil) + ' hour';
	minutes.textContent = Math.floor(minutesUntil) + ' minute';
	seconds.textContent = Math.floor(secondsUntil) + ' second';
	millis.textContent = 'and ' + Math.floor(millisUntil) + ' millisecond';

	if(Math.floor(daysUntil) != 1) days.textContent = days.textContent + 's';
	if(Math.floor(hoursUntil) != 1) hours.textContent = hours.textContent + 's';
	if(Math.floor(minutesUntil) != 1) minutes.textContent = minutes.textContent + 's';
	if(Math.floor(secondsUntil) != 1) seconds.textContent = seconds.textContent + 's';
	if(Math.floor(millisUntil) != 1) millis.textContent = millis.textContent + 's';
}

function changeTimerSelect(change) {
	timerIndex += change;

	if(timerIndex < 0) timerIndex = endTimestamp.length - 1;
	else if(timerIndex >= endTimestamp.length) timerIndex = 0;

	var timerCount = document.getElementById("timerCount");
	if(timerCount != null)
	timerCount.innerText = "Timer {0}/{1}".replace("{0}", (timerIndex+1).toString()).replace("{1}", endTimestamp.length.toString());
}

window.setInterval(updateTime, 1);
<|endoftext|>


<commit_before>/**
 * Copyright (C) 2013 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Tic Tac Toe Gameplay with Chromecast
 * This file exposes cast.TicTacToe as an object containing a ChannelHandler
 * and capable of receiving and sending messages to the sender application.
 */

// External namespace for cast specific javascript library
var cast = window.cast || {};

// Anonymous namespace
(function() {
  'use strict';

  TicTacToe.PROTOCOL = 'com.google.chromecast.demo.tictactoe';

  TicTacToe.PLAYER = {
    O: 'O',
    X: 'X'
  };

  /**
   * Creates a TicTacToe object with an optional board and attaches a
   * cast.receiver.ChannelHandler, which receives messages from the
   * channel between the sender and receiver.
   * @param {board} opt_board an optional game board.
   * @constructor
   */
  function TicTacToe(opt_board) {
    this.mBoard = opt_board;
    this.mPlayer1 = -1;
    this.mPlayer2 = -1;
    this.mCurrentPlayer;

    this.mChannelHandler =
        new cast.receiver.ChannelHandler('TicTacToeDebug');
    this.mChannelHandler.addEventListener(
        cast.receiver.Channel.EventType.MESSAGE,
        this.onMessage.bind(this));
    this.mChannelHandler.addEventListener(
        cast.receiver.Channel.EventType.OPEN,
        this.onChannelOpened.bind(this));
    this.mChannelHandler.addEventListener(
        cast.receiver.Channel.EventType.CLOSED,
        this.onChannelClosed.bind(this));
  }

  // Adds event listening functions to TicTacToe.prototype.
  TicTacToe.prototype = {

    /**
     * Channel opened event; checks number of open channels.
     * @param {event} event the channel open event.
     */
    onChannelOpened: function(event) {
      console.log('onChannelOpened. Total number of channels: ' +
          this.mChannelHandler.getChannels().length);
    },

    /**
     * Channel closed event; if all devices are disconnected,
     * closes the application.
     * @param {event} event the channel close event.
     */
    onChannelClosed: function(event) {
      console.log('onChannelClosed. Total number of channels: ' +
          this.mChannelHandler.getChannels().length);

      if (this.mChannelHandler.getChannels().length == 0) {
        window.close();
      }
    },

    /**
     * Message received event; determines event message and command, and
     * choose function to call based on them.
     * @param {event} event the event to be processed.
     */
    onMessage: function(event) {
      var message = event.message;
      var channel = event.target;
      console.log('********onMessage********' + JSON.stringify(message));
      console.log('mPlayer1: ' + this.mPlayer1);
      console.log('mPlayer2: ' + this.mPlayer2);

      if (message.command == 'join') {
        this.onJoin(channel, message);
      } else if (message.command == 'leave') {
        this.onLeave(channel);
      } else if (message.command == 'move') {
        this.onMove(channel, message);
      } else if (message.command == 'board_layout_request') {
        this.onBoardLayoutRequest(channel);
      } else {
        cast.log.error('Invalid message command: ' + message.command);
      }
    },

    /**
     * Player joined event: registers a new player who joined the game, or
     * prevents player from joining if invalid.
     * @param {cast.receiver.channel} channel the channel the message came from.
     * @param {Object|string} message the name of the player who just joined.
     */
    onJoin: function(channel, message) {
      console.log('****onJoin: ' + JSON.stringify(message));

      if ((this.mPlayer1 != -1) &&
          (this.mPlayer1.channel == channel)) {
        this.sendError(channel, 'You are already ' +
                       this.mPlayer1.player +
                       ' You aren\'t allowed to play against yourself.');
        return;
      }
      if ((this.mPlayer2 != -1) &&
          (this.mPlayer2.channel == channel)) {
        this.sendError(channel, 'You are already ' +
                       this.mPlayer2.player +
                       ' You aren\'t allowed to play against yourself.');
        return;
      }

      if (this.mPlayer1 == -1) {
        this.mPlayer1 = new Object();
        this.mPlayer1.name = message.name;
        this.mPlayer1.channel = channel;
      } else if (this.mPlayer2 == -1) {
        this.mPlayer2 = new Object();
        this.mPlayer2.name = message.name;
        this.mPlayer2.channel = channel;
      } else {
        console.log('Unable to join a full game.');
        this.sendError(channel, 'Game is full.');
        return;
      }

      console.log('mPlayer1: ' + this.mPlayer1);
      console.log('mPlayer2: ' + this.mPlayer2);

      if (this.mPlayer1 != -1 && this.mPlayer2 != -1) {
        this.mBoard.reset();
        this.startGame_();
      }
    },

    /**
     * Player leave event: determines which player left and unregisters that
     * player, and ends the game if all players are absent.
     * @param {cast.receiver.channel} channel the channel of the leaving player.
     */
    onLeave: function(channel) {
      console.log('****OnLeave');

      if (this.mPlayer1 != -1 && this.mPlayer1.channel == channel) {
        this.mPlayer1 = -1;
      } else if (this.mPlayer2 != -1 && this.mPlayer2.channel == channel) {
        this.mPlayer2 = -1;
      } else {
        console.log('Neither player left the game');
        return;
      }
      console.log('mBoard.GameResult: ' + this.mBoard.getGameResult());
      if (this.mBoard.getGameResult() == -1) {
        this.mBoard.setGameAbandoned();
        this.broadcastEndGame(this.mBoard.getGameResult());
      }
    },

    /**
     * Move event: checks whether a valid move was made and updates the board
     * as necessary.
     * @param {cast.receiver.channel} channel the source of the move, which
     *     determines the player.
     * @param {Object|string} message contains the row and column of the move.
     */
    onMove: function(channel, message) {
      console.log('****onMove: ' + JSON.stringify(message));
      var isMoveValid;

      if ((this.mPlayer1 == -1) || (this.mPlayer2 == -1)) {
        console.log('Looks like one of the players is not there');
        console.log('mPlayer1: ' + this.mPlayer1);
        console.log('mPlayer2: ' + this.mPlayer2);
        return;
      }

      if (this.mPlayer1.channel == channel) {
        if (this.mPlayer1.player == this.mCurrentPlayer) {
          if (this.mPlayer1.player == TicTacToe.PLAYER.X) {
            isMoveValid = this.mBoard.drawCross(message.row, message.column);
          } else {
            isMoveValid = this.mBoard.drawNaught(message.row, message.column);
          }
        } else {
          console.log('Ignoring the move. It\'s not your turn.');
          this.sendError(channel, 'It\'s not your turn.');
          return;
        }
      } else if (this.mPlayer2.channel == channel) {
        if (this.mPlayer2.player == this.mCurrentPlayer) {
          if (this.mPlayer2.player == TicTacToe.PLAYER.X) {
            isMoveValid = this.mBoard.drawCross(message.row, message.column);
          } else {
            isMoveValid = this.mBoard.drawNaught(message.row, message.column);
          }
        } else {
          console.log('Ignoring the move. It\'s not your turn.');
          this.sendError(channel, 'It\'s not your turn.');
          return;
        }
      } else {
        console.log('Ignorning message. Someone other than the current' +
            'players sent a move.');
        this.sendError(channel, 'You are not playing the game');
        return;
      }

      if (isMoveValid === false) {
        this.sendError(channel, 'Your last move was invalid');
        return;
      }

      var isGameOver = this.mBoard.isGameOver();
      this.broadcast({ event: 'moved',
                       player: this.mCurrentPlayer,
                       row: message.row,
                       column: message.column,
                       game_over: isGameOver });

      console.log('isGameOver: ' + isGameOver);
      console.log('winningLoc: ' + this.mBoard.getWinningLocation());

      // When the game should end
      if (isGameOver == true) {
        this.broadcastEndGame(this.mBoard.getGameResult(),
            this.mBoard.getWinningLocation());
      }
      // Switch current player
      this.mCurrentPlayer = (this.mCurrentPlayer == TicTacToe.PLAYER.X) ?
          TicTacToe.PLAYER.O : TicTacToe.PLAYER.X;
    },

    /**
     * Request event for the board layout: sends the current layout of pieces
     * on the board through the channel.
     * @param {cast.receiver.channel} channel the channel the event came from.
     */
    onBoardLayoutRequest: function(channel) {
      console.log('****onBoardLayoutRequest');
      var boardLayout = [];
      for (var i = 0; i < 3; i++) {
        for (var j = 0; j < 3; j++) {
          boardLayout[i * 3 + j] = this.mBoard.mBoard[i][j];
        }
      }
      channel.send({ 'event': 'board_layout_response',
                     'board': boardLayout });
    },

    sendError: function(channel, errorMessage) {
      channel.send({ event: 'error',
                     message: errorMessage });
    },

    broadcastEndGame: function(endState, winningLocation) {
      console.log('****endGame');
      this.mPlayer1 = -1;
      this.mPlayer2 = -1;
      this.broadcast({ event: 'endgame',
                       end_state: endState,
                       winning_location: winningLocation });
    },

    /**
     * @private
     */
    startGame_: function() {
      console.log('****startGame');
      var firstPlayer = Math.floor((Math.random() * 10) % 2);
      this.mPlayer1.player = (firstPlayer === 0) ?
          TicTacToe.PLAYER.X : TicTacToe.PLAYER.O;
      this.mPlayer2.player = (firstPlayer === 0) ?
          TicTacToe.PLAYER.O : TicTacToe.PLAYER.X;
      this.mCurrentPlayer = TicTacToe.PLAYER.X;

      this.mPlayer1.channel.send({ event: 'joined',
                                   player: this.mPlayer1.player,
                                   opponent: this.mPlayer2.name });
      this.mPlayer2.channel.send({ event: 'joined',
                                   player: this.mPlayer2.player,
                                   opponent: this.mPlayer1.name });
    },

    /**
     * Broadcasts a message to all of this object's known channels.
     * @param {Object|string} message the message to broadcast.
     */
    broadcast: function(message) {
      this.mChannelHandler.getChannels().forEach(
        function(channel) {
          channel.send(message);
        });
    }

  };

  // Exposes public functions and APIs
  cast.TicTacToe = TicTacToe;
})();
<commit_msg>remove unneeded tictactoe example<commit_after><|endoftext|>


<commit_before>// convert mongo db object style to middle style used by plist.js
var when = require('when');
var request = require('request');

var server_url = "http://ubicall.com/design/plist/";
var ws_server_url = "http://ws.ubicall.com/webservice/check_ivr_version.php?url="
//var ws_server_url = "http://10.0.0.161/webservice/check_ivr_version.php?url=";

var g_flow;
var plistMapper = {
    "choicesscreen": {name: "Choice", type: "String"},
    "gridscreen": {name: "Grid", type: "String"},
    "InfoScreen": {name: "Info", type: "String"},
    "formscreen": {name: "Form", type: "String"},
    "type": {name: "ScreenType", type: "String"},
    "choices": {name: "choices", type: "Array"},
    "t": {name: "ChoiceText", type: "String"},
    "wi": {name: "ScreenName", type: "String"},
    "wt": {name: "ChoiceType", type: "String"},
    "form_screen_name": {name: "ScreenTitle", type: "String"},
    "form_screen_title": {name: "FormTitle", type: "String"},
    "form_screen_items": {name: "FormFields", type: "Array"},
    "fieldLabel": {name: "FieldLabel", type: "String"},
    "fieldType": {name: "FieldType", type: "String"},
    "isMandatory": {name: "isMandatory", type: "String"},
    "keyboard": {name: "Keyboard", type: "String"},
    "placeholder": {name: "Placeholder", type: "String"},
    "Values": {name: "Values", type: "String"},
    "screen_name": {name: "ScreenTitle", type: "String"},
    "screen_content": {name: "ContentText", type: "String"},
    "url": {name: "URL", type: "String"},
    "grid_url": {name: "UrlImage", type: "String"},
    "url_title": {name: "ChoiceText", type: "String"},
    "call": {name: "Call", type: "String"},
    "title": {name: "ChoiceText", type: "String"},
    "queue": {name: "QueueDestination", type: "String"}
};

function getNodeWithId(_id) {//get first one , id attribute doesn't duplicate
    return g_flow.Nodes.filter(function (node) {
        return (_id && node.hasOwnProperty('id') && node.id == _id);
    })[0];
}

function isNodeValid(Node) {
    if (Node && Node.hasOwnProperty('type')) {
        return true;
    }
    return false;
}

function mapElement(that) {
    var rObj = {};
    for (var k in that) {
        if (that.hasOwnProperty(k) && plistMapper.hasOwnProperty(k)) {
            if (plistMapper[k].name == 'choices') {
                rObj[plistMapper[k].name] = that.choices.map(mapElement);
                rObj[plistMapper[k].name].forEach(function (choice, index) {
                    var Node = getNodeWithId(that.wires[index][0]);
                    choice.ChoiceType = plistMapper[Node.type].name;
                    if (Node.type == 'url') {
                        choice.url = Node.url;
                        delete choice.ScreenName;
                    } else if (Node.type == 'call') {
                        choice.QueueDestination = Node.queue.id;
                        delete choice.ScreenName;
                    } else {
                        choice.ScreenName = that.wires[index][0];
                    }
                });
            } else if (plistMapper[k].name == 'FormFields') {
                rObj[plistMapper[k].name] = that.form_screen_items.map(mapElement);
            } else {
                rObj[plistMapper[k].name] = k == 'type' ? plistMapper[that[k]].name : that[k];
            }
        }
    }
    return rObj;
}

module.exports = {
    extractFlow: function (flow) {
        return when.promise(function (resolve) {
            var __flow = {};
            try {
                //remove unnecessary parts from mongo db object
                var _flow = JSON.parse(JSON.stringify(flow, function (key, value) {
                    return key !== '_id' && key !== '__v' && key !== 'created' && key !== 'deploy' ? value : undefined;
                }));

                g_flow = _flow;
                __flow.key = _flow.key;
                __flow.Version = _flow.version;

                var startId = _flow.Nodes.filter(function (node) {
                    // TODO : if it has no start point through exception
                    return (node.hasOwnProperty('type') && node.type == 'start');
                })[0].wires[0][0];
                var initial = getNodeWithId(startId);
                var rest_of_flow = _flow.Nodes.filter(function (node) {
                    return (node.type != 'start' && node.type != 'tab');
                });
                __flow.Initial = plistMapper[initial.type].name;
                __flow.MainScreen = [initial].map(mapElement)[0];
                rest_of_flow.forEach(function (node) {
                    __flow[node.id] = mapElement(node);
                });
            } catch (ex) {
                resolve([]);
            }
            resolve(__flow);
        });
    },
    deployFlowOnline: function (licence, version) {
        return when.promise(function (resolve, reject) {
            console.log("deploy URL " + ws_server_url + server_url + licence + "/" + version);
            request(ws_server_url + server_url + licence + "/" + version,
                function (error, response, body) {
                    if (!error && response.statusCode == 200) {
                        return resolve(body);
                    } else {
                        return resolve(null);
                    }
                })
        });
    }
}<commit_msg>hard coded i know<commit_after>// convert mongo db object style to middle style used by plist.js
var when = require('when');
var request = require('request');

var server_url = "https://ivr.ubicall.com/plist/";
var ws_server_url = "http://ws.ubicall.com/webservice/check_ivr_version.php?url="
//var ws_server_url = "http://10.0.0.161/webservice/check_ivr_version.php?url=";

var g_flow;
var plistMapper = {
    "choicesscreen": {name: "Choice", type: "String"},
    "gridscreen": {name: "Grid", type: "String"},
    "InfoScreen": {name: "Info", type: "String"},
    "formscreen": {name: "Form", type: "String"},
    "type": {name: "ScreenType", type: "String"},
    "choices": {name: "choices", type: "Array"},
    "t": {name: "ChoiceText", type: "String"},
    "wi": {name: "ScreenName", type: "String"},
    "wt": {name: "ChoiceType", type: "String"},
    "form_screen_name": {name: "ScreenTitle", type: "String"},
    "form_screen_title": {name: "FormTitle", type: "String"},
    "form_screen_items": {name: "FormFields", type: "Array"},
    "fieldLabel": {name: "FieldLabel", type: "String"},
    "fieldType": {name: "FieldType", type: "String"},
    "isMandatory": {name: "isMandatory", type: "String"},
    "keyboard": {name: "Keyboard", type: "String"},
    "placeholder": {name: "Placeholder", type: "String"},
    "Values": {name: "Values", type: "String"},
    "screen_name": {name: "ScreenTitle", type: "String"},
    "screen_content": {name: "ContentText", type: "String"},
    "url": {name: "URL", type: "String"},
    "grid_url": {name: "UrlImage", type: "String"},
    "url_title": {name: "ChoiceText", type: "String"},
    "call": {name: "Call", type: "String"},
    "title": {name: "ChoiceText", type: "String"},
    "queue": {name: "QueueDestination", type: "String"}
};

function getNodeWithId(_id) {//get first one , id attribute doesn't duplicate
    return g_flow.Nodes.filter(function (node) {
        return (_id && node.hasOwnProperty('id') && node.id == _id);
    })[0];
}

function isNodeValid(Node) {
    if (Node && Node.hasOwnProperty('type')) {
        return true;
    }
    return false;
}

function mapElement(that) {
    var rObj = {};
    for (var k in that) {
        if (that.hasOwnProperty(k) && plistMapper.hasOwnProperty(k)) {
            if (plistMapper[k].name == 'choices') {
                rObj[plistMapper[k].name] = that.choices.map(mapElement);
                rObj[plistMapper[k].name].forEach(function (choice, index) {
                    var Node = getNodeWithId(that.wires[index][0]);
                    choice.ChoiceType = plistMapper[Node.type].name;
                    if (Node.type == 'url') {
                        choice.url = Node.url;
                        delete choice.ScreenName;
                    } else if (Node.type == 'call') {
                        choice.QueueDestination = Node.queue.id;
                        delete choice.ScreenName;
                    } else {
                        choice.ScreenName = that.wires[index][0];
                    }
                });
            } else if (plistMapper[k].name == 'FormFields') {
                rObj[plistMapper[k].name] = that.form_screen_items.map(mapElement);
            } else {
                rObj[plistMapper[k].name] = k == 'type' ? plistMapper[that[k]].name : that[k];
            }
        }
    }
    return rObj;
}

module.exports = {
    extractFlow: function (flow) {
        return when.promise(function (resolve) {
            var __flow = {};
            try {
                //remove unnecessary parts from mongo db object
                var _flow = JSON.parse(JSON.stringify(flow, function (key, value) {
                    return key !== '_id' && key !== '__v' && key !== 'created' && key !== 'deploy' ? value : undefined;
                }));

                g_flow = _flow;
                __flow.key = _flow.key;
                __flow.Version = _flow.version;

                var startId = _flow.Nodes.filter(function (node) {
                    // TODO : if it has no start point through exception
                    return (node.hasOwnProperty('type') && node.type == 'start');
                })[0].wires[0][0];
                var initial = getNodeWithId(startId);
                var rest_of_flow = _flow.Nodes.filter(function (node) {
                    return (node.type != 'start' && node.type != 'tab');
                });
                __flow.Initial = plistMapper[initial.type].name;
                __flow.MainScreen = [initial].map(mapElement)[0];
                rest_of_flow.forEach(function (node) {
                    __flow[node.id] = mapElement(node);
                });
            } catch (ex) {
                resolve([]);
            }
            resolve(__flow);
        });
    },
    deployFlowOnline: function (licence, version) {
        return when.promise(function (resolve, reject) {
            console.log("deploy URL " + ws_server_url + server_url + licence + "/" + version);
            request(ws_server_url + server_url + licence + "/" + version,
                function (error, response, body) {
                    if (!error && response.statusCode == 200) {
                        return resolve(body);
                    } else {
                        return resolve(null);
                    }
                })
        });
    }
}<|endoftext|>


<commit_before>/*
   Table sorting script  by Joost de Valk, check it out at http://www.joostdevalk.nl/code/sortable-table/.
   Based on a script from http://www.kryogenix.org/code/browser/sorttable/.
   Distributed under the MIT license: http://www.kryogenix.org/code/browser/licence.html .

   Copyright (c) 1997-2007 Stuart Langridge, Joost de Valk.

   Version 1.5.7
   */

/* You can change these values */
var image_down = " &#x25BE";
var image_up   = " &#x25B4";

/* Don't change anything below this unless you know what you're doing */
addEvent(window, "load", sortables_init);

var SORT_COLUMN_INDEX;
var thead = false;

function sortables_init() {
	// Find all tables with class sortable and make them sortable
	if (!document.getElementsByTagName) return;
	tbls = document.getElementsByTagName("table");
	for (ti=0;ti<tbls.length;ti++) {
		thisTbl = tbls[ti];
		if (((' '+thisTbl.className+' ').indexOf("sortable") != -1) && (thisTbl.id)) {
			ts_makeSortable(thisTbl);
		}
	}
}

function ts_makeSortable(t) {
	if (t.rows.length > 0) {
		if (t.tHead && t.tHead.rows.length > 0) {
			var firstRow = t.tHead.rows[t.tHead.rows.length-1];
			thead = true;
		} else {
			var firstRow = t.rows[0];
		}
	}
	if (!firstRow) return;

	// We have a first row: assume it's the header, and make its contents clickable links
	for (var i=0;i<firstRow.cells.length;i++) {
		var cell = firstRow.cells[i];
		var txt = ts_getInnerText(cell);
		if (cell.className != "unsortable" && cell.className.indexOf("unsortable") == -1) {
			cell.innerHTML = ''+txt+'';
		}
	}
	alternate(t);
}

function ts_getInnerText(el) {
	if (typeof el == "string") return el;
	if (typeof el == "undefined") { return el };
	if (el.innerText) return el.innerText;	//Not needed but it is faster
	var str = "";
	var cs = el.childNodes;
	for (var i = 0; i < cs.length; i++) {
		switch (cs[i].nodeType) {
		case 1: //ELEMENT_NODE
			str += ts_getInnerText(cs[i]);
			break;
		case 3:	//TEXT_NODE
			str += cs[i].nodeValue;
			break;
		}
	}
	return str;
}

function ts_resortTable(lnk) {
	var span;
	for (var ci=0;ci<lnk.childNodes.length;ci++) {
		if (lnk.childNodes[ci].tagName && lnk.childNodes[ci].tagName.toLowerCase() == 'span')
			span = lnk.childNodes[ci];
	}
	var spantext = ts_getInnerText(span);
	var td = lnk.parentNode;
	var column = td.cellIndex;
	var t = getParent(td,'TABLE');
	// Work out a type for the column
	if (t.rows.length <= 1) return;
	var itm = "";
	var i = 1;
	while (itm == "" && i < t.tBodies[0].rows.length) {
		var itm = ts_getInnerText(t.tBodies[0].rows[i].cells[column]);
		itm = trim(itm);
		if (itm.substr(0,4) == "


<commit_before>var notify  = require('gulp-notify');
var plumber = require('gulp-plumber');

module.exports = function () {
  return plumber(function () {
    // Send error to notification center with gulp-notify
    notify.onError({
      title: 'Compile Error',
      message: '<' + '%= error.message %' + '>'
    }).apply(this, arguments);

    // Keep gulp from hanging on this task
    this.emit('end');
  });
};
<commit_msg>Provide better error messages on notifications<commit_after>// This code was borrowed from the project `gulp-starter`, by Daniel Tello,
// licensed under the MIT License.
//
// Find out more in <https://github.com/greypants/gulp-starter/>

var notify  = require('gulp-notify');
var plumber = require('gulp-plumber');

module.exports = function () {
  return plumber(function () {
    // Send error to notification center with gulp-notify
    notify.onError({
      title: 'Compile Error',
      message: '<' + '%= error %' + '>'
    }).apply(this, arguments);

    // Keep gulp from hanging on this task
    this.emit('end');
  });
};
<|endoftext|>


<commit_before>import passport from 'passport';

function configureApp(app, loginRoute, logoutRoute, userDetailsExtractor, loadInitialData) {
  app.use(passport.initialize());
  app.use(passport.session());

  app.post(loginRoute, (req, res, next) => {
    passport.authenticate('local', (err, user, params) => {
      if (err) return next(err);
      if (!user) return res.status(401).json({error: params ? params.message : 'Invalid login'});
        req.login(user, {}, error => {
        if (error) return res.status(500).json({error});
        const initialData = loadInitialData(user);
        return res.json({
          ...initialData,
          user: userDetailsExtractor(user),
          returnTo: (req.session && req.session.returnTo) ? req.session.returnTo : '/'
        });
      });
    })(req, res, next);
  });

  app.get(logoutRoute, (req, res) => {
    req.logout();
    res.end();
  })
}

export default configureApp;
<commit_msg>loadInitialData expects promise returned also pass in req<commit_after>import passport from 'passport';

function configureApp(app, loginRoute, logoutRoute, userDetailsExtractor, loadInitialData) {
  app.use(passport.initialize());
  app.use(passport.session());

  app.post(loginRoute, (req, res, next) => {
    passport.authenticate('local', (err, user, params) => {
      if (err) return next(err);
      if (!user) return res.status(401).json({error: params ? params.message : 'Invalid login'});
        req.login(user, {}, error => {
        if (error) return res.status(500).json({error});
        loadInitialData(user, req).then(initialData => {
          res.json({
            ...initialData,
            user: userDetailsExtractor(user),
            returnTo: (req.session && req.session.returnTo) ? req.session.returnTo : '/'
          });
        });
      });
    })(req, res, next);
  });

  app.get(logoutRoute, (req, res) => {
    req.logout();
    res.end();
  })
}

export default configureApp;
<|endoftext|>


<commit_before>/*
---

name: View

description: Provides the base class for every objects that are displayed
             through an element.

license: MIT-style license.

authors:
	- Jean-Philippe Dery (jeanphilippe.dery@gmail.com)

requires:
	- Entity

provides:
	- View

...
*/

Moobile.View = new Class({

	Extends: Moobile.Entity,

	content: null,

	options: {
		className: 'view'
	},

	teardown: function() {
		this.parent();
		this.content = null;
	},

	attachEvents: function() {
		this.parent();
		this.element.addEvent('swipe', this.bound('onSwipe'));
	},

	detachEvents: function() {
		this.parent();
		this.element.removeEvent('swipe', this.bound('onSwipe'));
	},

	enable: function() {
		this.element.removeClass('disable').addClass('enable');
		return this;
	},

	disable: function() {
		this.element.removeClass('enable').addClass('disable');
		return this;
	},

	addChild: function(entity, where, context) {

		if (entity instanceof Moobile.ViewContent) {
			return this.parent(entity, where, context);
		}

		switch (where) {
			case 'header': return this.parent(entity, 'top');
			case 'footer': return this.parent(entity, 'bottom');
		}

		if (this.content && this.content.hasOwner()) {

			if (this.hasChild(entity)) {
				return false;
			}

			if (this.hasElement(entity) && !this.content.hasElement(entity) ||
				this.hasElement(context) && !this.content.hasElement(context)) {
				return this.parent(entity, where, context);
			}

			return this.content.addChild(entity, where, context);
		}

		return this.parent(entity, where, context);
	},

	getChildren: function() {
		return [].concat(this.content.getChildren(), this.getChildren());
	},

	getChild: function(name) {
		return this.content && this.content.hasOwner()
			 ? this.content.getChild(name) || this.parent(name)
			 : this.parent(name);
	},

	hasChild: function(entity) {
		return this.content && this.content.hasOwner()
		     ? this.content.hasChild(entity) || this.parent(entity)
		     : this.parent(entity);
	},

	replaceChild: function(replace, entity) {
		return this.content && this.content.hasOwner()
		     ? this.content.replaceChild(replace, entity) || this.parent(replace, entity)
		     : this.parent(replace, entity);
	},

	removeChild: function(entity) {
		return this.content && this.content.hasOwner()
		     ? this.content.removeChild(entity) || this.parent(entity)
		     : this.parent(entity);
	},

	getOwnerView: function() {

		var owner = this.owner;
		while (owner) {

			if (owner instanceof Moobile.View) {
				return owner;
			}

			owner = owner.getOwner();
		}

		return null;
	},

	getContent: function() {
		return this.content;
	},

	rolesWillLoad: function() {

		this.parent();

		var content = this.getRoleElement('content');
		if (content == null) {
			content = new Element('div');
			content.ingest(this.element);
			content.inject(this.element);
		}

		this.setRole('content', content);
	},

	onSwipe: function(e) {
		e.target = this;
		this.fireEvent('swipe', e);
	}

});

Moobile.View.elementAtPath = function(path) {
	return new Moobile.Request.ViewElement().load(path);
};

Moobile.View.atPath = function(path) {

	var element = Moobile.View.elementAtPath(path);
	if (element) {
		return Class.instantiate(element.get('data-view') || 'Moobile.View', element, null, element.get('data-name'));
	}

	return null;
};

//------------------------------------------------------------------------------
// Child Roles
//------------------------------------------------------------------------------

Moobile.Entity.defineRole('content', Moobile.View, function(element, options, name) {

	var instance = Class.instantiate(element.get('data-content') || Moobile.ViewContent, element, options, name);
	if (instance instanceof Moobile.ViewContent) {
		this.addChild(instance);
		this.content = instance;
	}

	return instance;
});
<commit_msg>Fixed a maximum call stack exceeded error<commit_after>/*
---

name: View

description: Provides the base class for every objects that are displayed
             through an element.

license: MIT-style license.

authors:
	- Jean-Philippe Dery (jeanphilippe.dery@gmail.com)

requires:
	- Entity

provides:
	- View

...
*/

Moobile.View = new Class({

	Extends: Moobile.Entity,

	content: null,

	options: {
		className: 'view'
	},

	teardown: function() {
		this.parent();
		this.content = null;
	},

	attachEvents: function() {
		this.parent();
		this.element.addEvent('swipe', this.bound('onSwipe'));
	},

	detachEvents: function() {
		this.parent();
		this.element.removeEvent('swipe', this.bound('onSwipe'));
	},

	enable: function() {
		this.element.removeClass('disable').addClass('enable');
		return this;
	},

	disable: function() {
		this.element.removeClass('enable').addClass('disable');
		return this;
	},

	addChild: function(entity, where, context) {

		if (entity instanceof Moobile.ViewContent) {
			return this.parent(entity, where, context);
		}

		switch (where) {
			case 'header': return this.parent(entity, 'top');
			case 'footer': return this.parent(entity, 'bottom');
		}

		if (this.content && this.content.hasOwner()) {

			if (this.hasChild(entity)) {
				return false;
			}

			if (this.hasElement(entity) && !this.content.hasElement(entity) ||
				this.hasElement(context) && !this.content.hasElement(context)) {
				return this.parent(entity, where, context);
			}

			return this.content.addChild(entity, where, context);
		}

		return this.parent(entity, where, context);
	},

	getChildren: function() {
		return [].concat(this.content.getChildren(), this.parent());
	},

	getChild: function(name) {
		return this.content && this.content.hasOwner()
			 ? this.content.getChild(name) || this.parent(name)
			 : this.parent(name);
	},

	hasChild: function(entity) {
		return this.content && this.content.hasOwner()
		     ? this.content.hasChild(entity) || this.parent(entity)
		     : this.parent(entity);
	},

	replaceChild: function(replace, entity) {
		return this.content && this.content.hasOwner()
		     ? this.content.replaceChild(replace, entity) || this.parent(replace, entity)
		     : this.parent(replace, entity);
	},

	removeChild: function(entity) {
		return this.content && this.content.hasOwner()
		     ? this.content.removeChild(entity) || this.parent(entity)
		     : this.parent(entity);
	},

	getOwnerView: function() {

		var owner = this.owner;
		while (owner) {

			if (owner instanceof Moobile.View) {
				return owner;
			}

			owner = owner.getOwner();
		}

		return null;
	},

	getContent: function() {
		return this.content;
	},

	rolesWillLoad: function() {

		this.parent();

		var content = this.getRoleElement('content');
		if (content == null) {
			content = new Element('div');
			content.ingest(this.element);
			content.inject(this.element);
		}

		this.setRole('content', content);
	},

	onSwipe: function(e) {
		e.target = this;
		this.fireEvent('swipe', e);
	}

});

Moobile.View.elementAtPath = function(path) {
	return new Moobile.Request.ViewElement().load(path);
};

Moobile.View.atPath = function(path) {

	var element = Moobile.View.elementAtPath(path);
	if (element) {
		return Class.instantiate(element.get('data-view') || 'Moobile.View', element, null, element.get('data-name'));
	}

	return null;
};

//------------------------------------------------------------------------------
// Child Roles
//------------------------------------------------------------------------------

Moobile.Entity.defineRole('content', Moobile.View, function(element, options, name) {

	var instance = Class.instantiate(element.get('data-content') || Moobile.ViewContent, element, options, name);
	if (instance instanceof Moobile.ViewContent) {
		this.addChild(instance);
		this.content = instance;
	}

	return instance;
});
<|endoftext|>


<commit_before>openerp.web_calendar_repeat_form = function (session) {

    session.web_calendar.CalendarView.include({
        view_loading: function(fv) {
            this.prev_data = {};
            this.repeat_form = false;
            var res =  this._super(fv);
            if (this.quick_create_instance == 'instance.web_calendar_repeat_form.QuickCreateRepeated') {
                this.repeat_form = true;
            }
            return res
        },
        slow_created: function (data) {
            this._super();
            if (this.repeat_form) {
                this.prev_data = data;
            }
        },
        open_quick_create: function(data_template) {
            if (this.repeat_form) {
                data_template = $.extend({}, this.prev_data, data_template);
            }
            this._super(data_template);
        }
    });

    session.web_calendar_repeat_form.QuickCreateRepeated = session.web_calendar.QuickCreate.extend({
        // build_pop: function() {

        // }
        slow_create: function(data) {
            this.prev_data = {};
            var self = this;
            var def = $.Deferred();
            var defaults = {};
            var created = false;

            _.each($.extend({}, this.data_template, data), function(val, field_name) {
                defaults['default_' + field_name] = val;
            });

            var pop_infos = self.get_form_popup_infos();
            this.pop = new session.web.form.FormOpenPopup(this);
            var context = new session.web.CompoundContext(this.dataset.context, defaults);
            this.pop.show_element(this.dataset.model, null, this.dataset.get_context(defaults), {
                title: this.get_title(),
                disable_multiple_selection: true,
                view_id: pop_infos.view_id,
                create_function: function(data, options) {
                    self.prev_data = data;
                    return self.dataset.create(data, options).done(function(r) {
                    }).fail(function (r, event) {
                       if (!r.data.message) { //else manage by openerp
                            throw new Error(r);
                       }
                    });
                },
                read_function: function(id, fields, options) {
                    return self.dataset.read_ids.apply(self.dataset, arguments).done(function() {
                    }).fail(function (r, event) {
                        if (!r.data.message) { //else manage by openerp
                            throw new Error(r);
                        }
                    });
                },
            });
            this.pop.on('closed', self, function() {
                if (def.state() === "pending") {
                    def.resolve();
                }
            });
            this.pop.on('create_completed', self, function(id) {
                created = true;
                self.trigger('slowadded', self.prev_data);
            });
            def.then(function() {
                if (created) {
                    var parent = self.getParent();
                    parent.$calendar.fullCalendar('refetchEvents');
                }
                self.trigger('close');
            });
            return def;
        }
    });

}<commit_msg>Code clean up<commit_after>openerp.web_calendar_repeat_form = function (session) {

    session.web_calendar.CalendarView.include({
        view_loading: function(fv) {
            this.prev_data = {};
            this.repeat_form = false;
            var res =  this._super(fv);
            if (this.quick_create_instance == 'instance.web_calendar_repeat_form.QuickCreateRepeated') {
                this.repeat_form = true;
            }
            return res
        },
        slow_created: function (data) {
            this._super();
            if (this.repeat_form) {
                this.prev_data = data;
            }
        },
        open_quick_create: function(data_template) {
            if (this.repeat_form) {
                data_template = $.extend({}, this.prev_data, data_template);
            }
            this._super(data_template);
        }
    });

    session.web_calendar_repeat_form.QuickCreateRepeated = session.web_calendar.QuickCreate.extend({
        slow_create: function(data) {
            this.prev_data = {};
            var self = this;
            var def = $.Deferred();
            var defaults = {};
            var created = false;

            _.each($.extend({}, this.data_template, data), function(val, field_name) {
                defaults['default_' + field_name] = val;
            });

            var pop_infos = self.get_form_popup_infos();
            this.pop = new session.web.form.FormOpenPopup(this);
            var context = new session.web.CompoundContext(this.dataset.context, defaults);
            this.pop.show_element(this.dataset.model, null, this.dataset.get_context(defaults), {
                title: this.get_title(),
                disable_multiple_selection: true,
                view_id: pop_infos.view_id,
                create_function: function(data, options) {
                    self.prev_data = data;
                    return self.dataset.create(data, options).done(function(r) {
                    }).fail(function (r, event) {
                       if (!r.data.message) { //else manage by openerp
                            throw new Error(r);
                       }
                    });
                },
                read_function: function(id, fields, options) {
                    return self.dataset.read_ids.apply(self.dataset, arguments).done(function() {
                    }).fail(function (r, event) {
                        if (!r.data.message) { //else manage by openerp
                            throw new Error(r);
                        }
                    });
                },
            });
            this.pop.on('closed', self, function() {
                if (def.state() === "pending") {
                    def.resolve();
                }
            });
            this.pop.on('create_completed', self, function(id) {
                created = true;
                self.trigger('slowadded', self.prev_data);
            });
            def.then(function() {
                if (created) {
                    var parent = self.getParent();
                    parent.$calendar.fullCalendar('refetchEvents');
                }
                self.trigger('close');
            });
            return def;
        }
    });

}<|endoftext|>


<commit_before>angular.module('issueTrackingSystem.issuesModule', [])

    .config(['$stateProvider', function ($stateProvider) {
        $stateProvider
            .state('authenticated.single_issue', {
                url:         "/issues/:id",
                controller:  'SingleIssueCtrl',
                templateUrl: "modules/issues/single_issue.html",
                resolve:     {
                    issueData: ['$stateParams', 'httpRequests', function ($stateParams, httpRequests) {
                        return httpRequests.get('single_issue', {
                            id: $stateParams.id
                        });
                    }],

                    commentsData: ['$stateParams', 'httpRequests', function ($stateParams, httpRequests) {
                        return httpRequests.get('single_issue_comments', {
                            id: $stateParams.id
                        });
                    }]
                }
            })

            .state('authenticated.single_project_add_issue', {
                url:         "/projects/:id/add-issue",
                controller:  'AddIssueCtrl',
                templateUrl: "modules/issues/form.html",
                resolve:     {
                    projectData: ['$stateParams', 'httpRequests', function ($stateParams, httpRequests) {
                        return httpRequests.get('single_project', {
                            id: $stateParams.id
                        });
                    }],

                    allUsers: ['httpRequests', function (httpRequests) {
                        return httpRequests.get('users');
                    }],

                    allProjects: ['httpRequests', function (httpRequests) {
                        return httpRequests.get('projects');
                    }]
                }
            })

            .state('authenticated.single_project_edit_issue', {
                url:         "/issues/:id/edit",
                controller:  'EditIssueCtrl',
                templateUrl: "modules/issues/form.html",
                resolve:     {
                    issueData: ['$stateParams', 'httpRequests', function ($stateParams, httpRequests) {
                        return httpRequests.get('single_issue', {
                            id: $stateParams.id
                        });
                    }],

                    projectData: ['issueData', 'httpRequests', function (issueData, httpRequests) {
                        return httpRequests.get('single_project', {
                            id: issueData.Project.Id
                        });
                    }],

                    allUsers: ['httpRequests', function (httpRequests) {
                        return httpRequests.get('users');
                    }],

                    allProjects: ['httpRequests', function (httpRequests) {
                        return httpRequests.get('projects');
                    }]
                }
            });
    }])

    .controller('SingleIssueCtrl', ['$scope', '$state', 'httpRequests', 'errorsHandler', 'SweetAlert', 'user', 'issueData', 'commentsData', function ($scope, $state, httpRequests, errorsHandler, SweetAlert, user, issueData, commentsData) {

        $scope.isCurrentUserAuthor   = (user.getLoggedUserData().Id === issueData.Author.Id);
        $scope.isCurrentUserAssigned = (user.getLoggedUserData().Id === issueData.Assignee.Id);
        $scope.issueData             = issueData;

        $scope.changeIssueStatus = function (status) {
            if (!$scope.isCurrentUserAssigned) {
                SweetAlert.error('You need to be author or assigned to this issue!');
                return false;
            }

            httpRequests.put('single_issue_change_status', {}, {
                    id:       issueData.Id,
                    statusId: status.Id
                })
                .then(function (response) {
                    $scope.issueData.Status = status;
                    $scope.issueData.AvailableStatuses = response;
                }, function (err) {
                    errorsHandler.handle(err);
                });
        };

        /**
         * Comments
         */
        $scope.commentsData = commentsData;
        $scope.newCommentText = null;

        $scope.addComment = function () {
            if (!($scope.isCurrentUserAuthor || $scope.isCurrentUserAssigned)) {
                SweetAlert.error('You need to be author or assigned to this issue!');
                return false;
            }

            httpRequests.post('single_issue_comments', {
                    Text: $scope.newCommentText
                }, {
                    id: issueData.Id
                })
                .then(function (response) {
                    $scope.newCommentText = null;
                    $scope.commentsData   = response;

                    // clear form data
                    $scope.chatForm.$setPristine();
                }, function (err) {
                    errorsHandler.handle(err);
                });
        };

    }])

    .controller('AddIssueCtrl', ['$scope', '$state', '$stateParams', 'httpRequests', 'errorsHandler', 'user', 'issueService', 'projectData', 'allUsers', 'allProjects', function ($scope, $state, $stateParams, httpRequests, errorsHandler, user, issueService, projectData, allUsers, allProjects) {

        // check user permissions
        if (!user.getLoggedUserData().isAdmin && user.getLoggedUserData().Id !== projectData.Lead.Id) {
            $state.go('authenticated.single_project', {
                id: $stateParams.id
            });

            return false;
        }

        $scope.title               = "Add Issue";
        $scope.isSubmitBtnDisabled = false;

        $scope.projectId   = $stateParams.id;
        $scope.projectData = projectData;

        $scope.allUsers    = allUsers;
        $scope.allProjects = allProjects;
        $scope.priorities  = projectData.Priorities;

        $scope.issue = {
            Title:       null,
            Description: null,
            DueDate:     null,
            ProjectId:   $scope.projectId,
            AssigneeId:  projectData.Lead.Id,
            PriorityId:  null,
            Labels:      _.pluck(projectData.Labels, 'Name')
        };

        $scope.labelsSelectConfig = {
            create:      true,
            valueField:  'Name',
            labelField:  'Name',
            delimiter:   ',',
            placeholder: 'Pick some labels'
        };

        $scope.doIssue = function () {
            $scope.isSubmitBtnDisabled = true;

            issueService.saveIssue($scope.issue, 'issues', 'POST')
                .then(function (response) {
                    $state.go('authenticated.single_project', {
                        id: $scope.projectId
                    });

                }, function (err) {
                    $scope.isSubmitBtnDisabled = false;
                    errorsHandler.handle(err);
                });
        };
    }])

    .controller('EditIssueCtrl', ['$scope', '$stateParams', '$state', 'httpRequests', 'errorsHandler', 'user', 'issueService', 'SweetAlert', 'issueData', 'projectData', 'allUsers', 'allProjects', function ($scope, $stateParams, $state, httpRequests, errorsHandler, user, issueService, SweetAlert, issueData, projectData, allUsers, allProjects) {

        // check user permissions
        if (!user.getLoggedUserData().isAdmin && user.getLoggedUserData().Id !== projectData.Lead.Id && user.getLoggedUserData().Id !== issueData.Author.Id) {
            $state.go('authenticated.single_issue', {
                id: $stateParams.id
            });

            return false;
        }

        $scope.title               = "Edit Issue";
        $scope.isSubmitBtnDisabled = false;

        $scope.projectId   = issueData.Project.Id;
        $scope.allUsers  = allUsers;
        $scope.allProjects = allProjects;

        $scope.projectData = projectData;
        $scope.priorities  = projectData.Priorities;

        $scope.issue = {
            Title:       issueData.Title,
            Description: issueData.Description,
            DueDate:     new Date(issueData.DueDate),
            ProjectId:   issueData.Project.Id.toString(),
            AssigneeId:  {
                Id: issueData.Assignee.Id
            },
            PriorityId:  issueData.Priority.Id.toString(),
            Labels:      _.pluck(issueData.Labels, 'Name')
        };

        $scope.labelsSelectConfig = {
            create:      true,
            valueField:  'Name',
            labelField:  'Name',
            delimiter:   ',',
            placeholder: 'Pick some labels'
        };

        // make update
        $scope.doIssue = function () {
            $scope.isSubmitBtnDisabled = true;

            var updatedIssueData = {
                Title:       $scope.issue.Title,
                Description: $scope.issue.Description,
                DueDate:     $scope.issue.DueDate,
                ProjectId:   $scope.issue.ProjectId,
                AssigneeId:  $scope.issue.AssigneeId.Id,
                PriorityId:  $scope.issue.PriorityId,
                Labels:      $scope.issue.Labels
            };

            issueService.saveIssue(updatedIssueData, 'single_issue', 'PUT', {
                    id: issueData.Id
                })
                .then(function (response) {
                    $scope.isSubmitBtnDisabled = false;
                    SweetAlert.success('Issue data was successfully edited!');

                }, function (err) {
                    $scope.isSubmitBtnDisabled = false;
                    errorsHandler.handle(err);
                });
        };

    }])
;<commit_msg>Fix Assigned user id<commit_after>angular.module('issueTrackingSystem.issuesModule', [])

    .config(['$stateProvider', function ($stateProvider) {
        $stateProvider
            .state('authenticated.single_issue', {
                url:         "/issues/:id",
                controller:  'SingleIssueCtrl',
                templateUrl: "modules/issues/single_issue.html",
                resolve:     {
                    issueData: ['$stateParams', 'httpRequests', function ($stateParams, httpRequests) {
                        return httpRequests.get('single_issue', {
                            id: $stateParams.id
                        });
                    }],

                    commentsData: ['$stateParams', 'httpRequests', function ($stateParams, httpRequests) {
                        return httpRequests.get('single_issue_comments', {
                            id: $stateParams.id
                        });
                    }]
                }
            })

            .state('authenticated.single_project_add_issue', {
                url:         "/projects/:id/add-issue",
                controller:  'AddIssueCtrl',
                templateUrl: "modules/issues/form.html",
                resolve:     {
                    projectData: ['$stateParams', 'httpRequests', function ($stateParams, httpRequests) {
                        return httpRequests.get('single_project', {
                            id: $stateParams.id
                        });
                    }],

                    allUsers: ['httpRequests', function (httpRequests) {
                        return httpRequests.get('users');
                    }],

                    allProjects: ['httpRequests', function (httpRequests) {
                        return httpRequests.get('projects');
                    }]
                }
            })

            .state('authenticated.single_project_edit_issue', {
                url:         "/issues/:id/edit",
                controller:  'EditIssueCtrl',
                templateUrl: "modules/issues/form.html",
                resolve:     {
                    issueData: ['$stateParams', 'httpRequests', function ($stateParams, httpRequests) {
                        return httpRequests.get('single_issue', {
                            id: $stateParams.id
                        });
                    }],

                    projectData: ['issueData', 'httpRequests', function (issueData, httpRequests) {
                        return httpRequests.get('single_project', {
                            id: issueData.Project.Id
                        });
                    }],

                    allUsers: ['httpRequests', function (httpRequests) {
                        return httpRequests.get('users');
                    }],

                    allProjects: ['httpRequests', function (httpRequests) {
                        return httpRequests.get('projects');
                    }]
                }
            });
    }])

    .controller('SingleIssueCtrl', ['$scope', '$state', 'httpRequests', 'errorsHandler', 'SweetAlert', 'user', 'issueData', 'commentsData', function ($scope, $state, httpRequests, errorsHandler, SweetAlert, user, issueData, commentsData) {

        $scope.isCurrentUserAuthor   = (user.getLoggedUserData().Id === issueData.Author.Id);
        $scope.isCurrentUserAssigned = (user.getLoggedUserData().Id === issueData.Assignee.Id);
        $scope.issueData             = issueData;

        $scope.changeIssueStatus = function (status) {
            if (!$scope.isCurrentUserAssigned) {
                SweetAlert.error('You need to be author or assigned to this issue!');
                return false;
            }

            httpRequests.put('single_issue_change_status', {}, {
                    id:       issueData.Id,
                    statusId: status.Id
                })
                .then(function (response) {
                    $scope.issueData.Status = status;
                    $scope.issueData.AvailableStatuses = response;
                }, function (err) {
                    errorsHandler.handle(err);
                });
        };

        /**
         * Comments
         */
        $scope.commentsData = commentsData;
        $scope.newCommentText = null;

        $scope.addComment = function () {
            if (!($scope.isCurrentUserAuthor || $scope.isCurrentUserAssigned)) {
                SweetAlert.error('You need to be author or assigned to this issue!');
                return false;
            }

            httpRequests.post('single_issue_comments', {
                    Text: $scope.newCommentText
                }, {
                    id: issueData.Id
                })
                .then(function (response) {
                    $scope.newCommentText = null;
                    $scope.commentsData   = response;

                    // clear form data
                    $scope.chatForm.$setPristine();
                }, function (err) {
                    errorsHandler.handle(err);
                });
        };

    }])

    .controller('AddIssueCtrl', ['$scope', '$state', '$stateParams', 'httpRequests', 'errorsHandler', 'user', 'issueService', 'projectData', 'allUsers', 'allProjects', function ($scope, $state, $stateParams, httpRequests, errorsHandler, user, issueService, projectData, allUsers, allProjects) {

        // check user permissions
        if (!user.getLoggedUserData().isAdmin && user.getLoggedUserData().Id !== projectData.Lead.Id) {
            $state.go('authenticated.single_project', {
                id: $stateParams.id
            });

            return false;
        }

        $scope.title               = "Add Issue";
        $scope.isSubmitBtnDisabled = false;

        $scope.projectId   = $stateParams.id;
        $scope.projectData = projectData;

        $scope.allUsers    = allUsers;
        $scope.allProjects = allProjects;
        $scope.priorities  = projectData.Priorities;

        $scope.issue = {
            Title:       null,
            Description: null,
            DueDate:     null,
            ProjectId:   $scope.projectId,
            AssigneeId:  projectData.Lead.Id,
            PriorityId:  null,
            Labels:      _.pluck(projectData.Labels, 'Name')
        };

        $scope.labelsSelectConfig = {
            create:      true,
            valueField:  'Name',
            labelField:  'Name',
            delimiter:   ',',
            placeholder: 'Pick some labels'
        };

        $scope.doIssue = function () {
            $scope.isSubmitBtnDisabled = true;

            issueService.saveIssue({
                    Title:       $scope.issue.Title,
                    Description: $scope.issue.Description,
                    DueDate:     $scope.issue.DueDate,
                    ProjectId:   $scope.projectId,
                    AssigneeId:  $scope.issue.AssigneeId.Id,
                    PriorityId:  $scope.issue.PriorityId,
                    Labels:      $scope.issue.Labels
                }, 'issues', 'POST')
                .then(function (response) {
                    $state.go('authenticated.single_project', {
                        id: $scope.projectId
                    });

                }, function (err) {
                    $scope.isSubmitBtnDisabled = false;
                    errorsHandler.handle(err);
                });
        };
    }])

    .controller('EditIssueCtrl', ['$scope', '$stateParams', '$state', 'httpRequests', 'errorsHandler', 'user', 'issueService', 'SweetAlert', 'issueData', 'projectData', 'allUsers', 'allProjects', function ($scope, $stateParams, $state, httpRequests, errorsHandler, user, issueService, SweetAlert, issueData, projectData, allUsers, allProjects) {

        // check user permissions
        if (!user.getLoggedUserData().isAdmin && user.getLoggedUserData().Id !== projectData.Lead.Id && user.getLoggedUserData().Id !== issueData.Author.Id) {
            $state.go('authenticated.single_issue', {
                id: $stateParams.id
            });

            return false;
        }

        $scope.title               = "Edit Issue";
        $scope.isSubmitBtnDisabled = false;

        $scope.projectId   = issueData.Project.Id;
        $scope.allUsers  = allUsers;
        $scope.allProjects = allProjects;

        $scope.projectData = projectData;
        $scope.priorities  = projectData.Priorities;

        $scope.issue = {
            Title:       issueData.Title,
            Description: issueData.Description,
            DueDate:     new Date(issueData.DueDate),
            ProjectId:   issueData.Project.Id.toString(),
            AssigneeId:  {
                Id: issueData.Assignee.Id
            },
            PriorityId:  issueData.Priority.Id.toString(),
            Labels:      _.pluck(issueData.Labels, 'Name')
        };

        $scope.labelsSelectConfig = {
            create:      true,
            valueField:  'Name',
            labelField:  'Name',
            delimiter:   ',',
            placeholder: 'Pick some labels'
        };

        // make update
        $scope.doIssue = function () {
            $scope.isSubmitBtnDisabled = true;

            var updatedIssueData = {
                Title:       $scope.issue.Title,
                Description: $scope.issue.Description,
                DueDate:     $scope.issue.DueDate,
                ProjectId:   $scope.issue.ProjectId,
                AssigneeId:  $scope.issue.AssigneeId.Id,
                PriorityId:  $scope.issue.PriorityId,
                Labels:      $scope.issue.Labels
            };

            issueService.saveIssue(updatedIssueData, 'single_issue', 'PUT', {
                    id: issueData.Id
                })
                .then(function (response) {
                    $scope.isSubmitBtnDisabled = false;
                    SweetAlert.success('Issue data was successfully edited!');

                }, function (err) {
                    $scope.isSubmitBtnDisabled = false;
                    errorsHandler.handle(err);
                });
        };

    }])
;<|endoftext|>


<commit_before>/*
---

name: View

description: Provides the base class for every objects that are displayed
             through an element.

license: MIT-style license.

authors:
	- Jean-Philippe Dery (jeanphilippe.dery@gmail.com)

requires:
	- Core/Class
	- Core/Class.Extras
	- Core/Array
	- Core/String
	- Core/Number
	- Core/Function
	- Core/Object
	- Core/Event
	- Core/DOMReady
	- Core/Element
	- Core/Element.Style
	- Core/Element.Event
	- Core/Element.Dimensions
	- More/Element.Shortcuts
	- Class-Extras/Class.Binds
	- Class-Extras/Class.Singleton
	- Event.ViewLoad
	- Event.ViewReady
	- Object.Extras
	- Element.Properties.Name
	- Element.Properties.Role
	- Element.Properties.Options
	- Element.Ingest
	- Element.Styles
	- String.Extras
	- Array.Extras
	- Class.Instanciate

provides:
	- View

...
*/

if (!window.Moobile) window.Moobile = {};

Moobile.View = new Class({

	Implements: [
		Events,
		Options,
		Class.Binds
	],

	window: null,

	name: null,

	ready: null,

	element: null,

	content: null,

	childViews: [],

	parentView: null,

	options: {
		className: 'view'
	},

	initialize: function(element, options, name) {

		this.setOptions(options);

		this.name = name || null;

		this.build(element);

		return this;
	},

	build: function(element) {

		this.element = document.id(element) || new Element('div');

		this.element.set('role', 'view');

		var content = this.getElement('[data-role=content]');
		if (content == null) {
			content = new Element('div[data-role=content]');
			content.ingest(this.element);
			content.inject(this.element);
		}

		this.content = content;

		var className = this.options.className;
		if (className) {
			this.element.addClass(className);
			this.content.addClass(className + '-content');
		}

		return this;
	},

	startup: function() {

		if (this.ready == true)
			return this;

		this.ready = true;

		this.attachRoleElements();
		this.setup();
		this.attachEvents();

		return this;
	},

	destroy: function() {

		if (this.ready == false)
			return this;

		this.detachRoleElements();
		this.detachEvents();
		this.destroyChildViews();
		this.teardown();

		this.removeFromParentView();

		this.element.destroy();
		this.element = null;
		this.content = null;
		this.window = null;

		this.ready = false;

		return this;
	},

	setup: function() {
		return this;
	},

	teardown: function() {
		return this;
	},

	attachEvents: function() {
		this.element.addEvent('swipe', this.bound('onViewSwipe'));
		this.element.addEvent('click', this.bound('onViewClick'));
		this.element.addEvent('mouseup', this.bound('onViewMouseUp'))
		this.element.addEvent('mousedown', this.bound('onViewMouseDown'));
		return this;
	},

	detachEvents: function() {
		this.element.removeEvent('swipe', this.bound('onViewSwipe'));
		this.element.removeEvent('click', this.bound('onViewClick'));
		this.element.removeEvent('mouseup', this.bound('onViewMouseUp'));
		this.element.removeEvent('mousedown', this.bound('onViewMouseDown'));
		return this;
	},

	attachRoleElements: function() {
		this.getElements('[data-role]').each(this.bound('attachRoleElement'));
		return this;
	},

	attachRoleElement: function(element) {
		var role = element.get('role');
		if (role) {

			var instance = this.getRoleInstance(element);
			if (instance instanceof Moobile.View) {
				this.addChildView(instance);
			}

			if (role.onAttach) {
				role.onAttach.call(element);
			}
		}
		return this;
	},

	detachRoleElements: function() {
		this.getElements('[data-role]').each(this.bound('detachRoleElement'));
		return this;
	},

	detachRoleElement: function(element) {
		var role = element.get('role');
		if (role) {
			if (role.onDetach) {
				role.onDetach.call(element);
			}
		}
		return this;
	},

	getRoleInstance: function(element) {

		var role = element.get('role');
		if (role) {
			var instance = element.retrieve('moobile:role-instance');
			if (instance == null) {
				if (role.apply) {
					instance = role.apply.call(element);
					element.store('moobile:role-instance', instance);
				}
			}
			return instance;
		}

		return null;
	},

	addChildView: function(view, where, context) {

		var exists = this.childViews.contains(view);
		if (exists == true)
			return this;

		var element = view.getElement();

		this.willAddChildView(view);
		view.parentViewWillChange(this);
		view.setParentView(this);
		view.setWindow(this.window);
		this.childViews.push(view);

		var contains = this.element.contains(element);
		if (contains == false) {
			if (context) {
				element.inject(context, where);
			} else {
				switch (where) {
					case 'header': this.element.grab(element, 'top');    break;
					case 'footer': this.element.grab(element, 'bottom'); break;
					default:	   this.content.grab(element, where);	 break;
				}
			}
		}

		view.parentViewDidChange(this);
		view.startup();
		this.didAddChildView(view);

		Object.defineMember(this, view, view.name);

		return this;
	},

	getChildView: function(name) {
		return this.childViews.find(function(childView) {
			return childView.getName() == name;
		});
	},

	getChildViewAt: function(index) {
		return this.childViews[index] || null;
	},

	replaceChildView: function(replace, view) {
		return this.addChildView(view, 'before', replace).removeChildView(replace);
	},

	removeChildView: function(view) {

		var exists = this.childViews.contains(view);
		if (exists == false)
			return this;

		var element = view.getElement();

		this.willRemoveChildView(view);
		view.parentViewWillChange(null);
		view.setParentView(null);
		view.setWindow(null);
		view.parentViewDidChange(null);
		element.dispose();
		this.childViews.erase(view);
		this.didRemoveChildView(view);

		return this;
	},

	removeFromParentView: function() {
		var parent = this.parentView || this.window;
		if (parent) parent.removeChildView(this);
		return this;
	},

	destroyChildViews: function() {
		this.childViews.each(this.bound('destroyChildView'));
		this.childViews.empty();
		return this;
	},

	destroyChildView: function(view) {
		view.destroy();
		view = null;
		return this;
	},

	show: function() {
		this.willShow();
		this.element.show();
		this.didShow();
		return this;
	},

	hide: function() {
		this.willHide();
		this.element.hide();
		this.didHide();
		return this;
	},

	setWindow: function(window) {
		this.window = window;
		return this;
	},

	getWindow: function(window) {
		return this.window;
	},

	getName: function() {
		return this.name;
	},

	isReady: function() {
		return this.ready;
	},

	getElement: function(selector) {
		return selector ? this.element.getElements(selector)[0] || null : this.element;
	},

	getElements: function(selector) {
		return this.element.getElements(selector).filter(this.bound('filterElement'));
	},

	filterElement: function(element) {

		var roles = [];

		var keys = Moobile.View.Roles;
		for (var key in keys) {
			if (keys[key].stop) roles.push(key);
		}

		var parent = element.getParent('[data-role]');
		while (true) {

			if (parent == null) {
				return true
			}

			var role = parent.get('role');
			if (role && role.stop) {
				if (roles.contains(role.name)) {
					return parent === this.element;
				}
			}

			parent = parent.getParent('[data-role]');
		}

		return false;
	},

	getContent: function() {
		return this.content;
	},

	setParentView: function(parentView) {
		this.parentView = parentView;
		return this;
	},

	getParentView: function() {
		return this.parentView;
	},

	getChildViews: function() {
		return this.childViews;
	},

	get: function(name) {

		switch (name) {
			case 'html':
			case 'text':
				return this.content.get(name);
			default:
				return this.element.get(name);
		}

		return t;
	},

	set: function(name, value) {

		switch (name) {
			case 'html':
			case 'text':
				this.content.set(name, value);
				break;
			default:
				this.element.set(name, value);
				break;
		}

		return this;
	},

	addClass: function(name) {
		this.element.addClass(name);
		return this;
	},

	removeClass: function(name) {
		this.element.removeClass(name);
		return this;
	},

	toggleClass: function(name) {
		this.element.toggleClass(name);
		return this;
	},

	setStyle: function(style, value) {
		this.element.setStyle(style, value);
		return this;
	},

	setStyles: function(styles) {
		this.element.setStyles(styles);
		return this;
	},

	getStyle: function(style) {
		return this.element.getStyle(style);
	},

	getStyles: function(styles) {
		return this.element.getStyles(styles);
	},

	removeStyle: function(style) {
		this.element.removeStyle(style);
		return this;
	},

	removeStyles: function(styles) {
		this.element.removeStyles(styles);
		return this;
	},

	getSize: function() {
		return this.element.getSize();
	},

	parentViewWillChange: function(parentView) {
		return this;
	},

	parentViewDidChange: function(parentView) {
		return this;
	},

	willAddChildView: function(childView) {
		return this;
	},

	didAddChildView: function(childView) {
		return this;
	},

	willRemoveChildView: function(childView) {
		return this;
	},

	didRemoveChildView: function(childView) {
		return this;
	},

	willAddChildElement: function(childElement) {
		return this;
	},

	didAddChildElement: function(childElement) {
		return this;
	},

	willRemoveChildElement: function(childElement) {
		return this;
	},

	didRemoveChildElement: function(childElement) {
		return this;
	},

	willShow: function() {
		return this;
	},

	didShow: function() {
		return this;
	},

	willHide: function() {
		return this;
	},

	didHide: function() {
		return this;
	},

	onViewSwipe: function(e) {
		e.target = this;
		this.fireEvent('swipe', e);
		return this;
	},

	onViewClick: function(e) {
		e.target = this;
		this.fireEvent('click', e);
		return this;
	},

	onViewMouseUp: function(e) {
		e.target = this;
		this.fireEvent('mouseup', e);
		return this;
	},

	onViewMouseDown: function(e) {
		e.target = this;
		this.fireEvent('mousedown', e);
		return this;
	},

	toElement: function() {
		return this.element;
	}

});<commit_msg>Fixed a bug that have yet to be discovered<commit_after>/*
---

name: View

description: Provides the base class for every objects that are displayed
             through an element.

license: MIT-style license.

authors:
	- Jean-Philippe Dery (jeanphilippe.dery@gmail.com)

requires:
	- Core/Class
	- Core/Class.Extras
	- Core/Array
	- Core/String
	- Core/Number
	- Core/Function
	- Core/Object
	- Core/Event
	- Core/DOMReady
	- Core/Element
	- Core/Element.Style
	- Core/Element.Event
	- Core/Element.Dimensions
	- More/Element.Shortcuts
	- Class-Extras/Class.Binds
	- Class-Extras/Class.Singleton
	- Event.ViewLoad
	- Event.ViewReady
	- Object.Extras
	- Element.Properties.Name
	- Element.Properties.Role
	- Element.Properties.Options
	- Element.Ingest
	- Element.Styles
	- String.Extras
	- Array.Extras
	- Class.Instanciate

provides:
	- View

...
*/

if (!window.Moobile) window.Moobile = {};

Moobile.View = new Class({

	Implements: [
		Events,
		Options,
		Class.Binds
	],

	window: null,

	name: null,

	ready: null,

	element: null,

	content: null,

	childViews: [],

	parentView: null,

	options: {
		className: 'view'
	},

	initialize: function(element, options, name) {

		this.setOptions(options);

		this.name = name || null;

		this.build(element);

		return this;
	},

	build: function(element) {

		this.element = document.id(element) || new Element('div');

		this.element.set('role', 'view');

		var content = this.getElement('[data-role=content]');
		if (content == null) {
			content = new Element('div[data-role=content]');
			content.ingest(this.element);
			content.inject(this.element);
		}

		this.content = content;

		var className = this.options.className;
		if (className) {
			this.element.addClass(className);
			this.content.addClass(className + '-content');
		}

		return this;
	},

	startup: function() {

		if (this.ready == true)
			return this;

		this.ready = true;

		this.attachRoleElements();
		this.setup();
		this.attachEvents();

		return this;
	},

	destroy: function() {

		if (this.ready == false)
			return this;

		this.detachRoleElements();
		this.detachEvents();
		this.destroyChildViews();
		this.teardown();

		this.removeFromParentView();

		this.element.destroy();
		this.element = null;
		this.content = null;
		this.window = null;

		this.ready = false;

		return this;
	},

	setup: function() {
		return this;
	},

	teardown: function() {
		return this;
	},

	attachEvents: function() {
		this.element.addEvent('swipe', this.bound('onViewSwipe'));
		this.element.addEvent('click', this.bound('onViewClick'));
		this.element.addEvent('mouseup', this.bound('onViewMouseUp'))
		this.element.addEvent('mousedown', this.bound('onViewMouseDown'));
		return this;
	},

	detachEvents: function() {
		this.element.removeEvent('swipe', this.bound('onViewSwipe'));
		this.element.removeEvent('click', this.bound('onViewClick'));
		this.element.removeEvent('mouseup', this.bound('onViewMouseUp'));
		this.element.removeEvent('mousedown', this.bound('onViewMouseDown'));
		return this;
	},

	attachRoleElements: function() {
		this.getElements('[data-role]').each(this.bound('attachRoleElement'));
		return this;
	},

	attachRoleElement: function(element) {
		var role = element.get('role');
		if (role) {

			var instance = this.getRoleInstance(element);
			if (instance instanceof Moobile.View) {
				this.addChildView(instance);
			}

			if (role.onAttach) {
				role.onAttach.call(element);
			}
		}
		return this;
	},

	detachRoleElements: function() {
		this.getElements('[data-role]').each(this.bound('detachRoleElement'));
		return this;
	},

	detachRoleElement: function(element) {
		var role = element.get('role');
		if (role) {
			if (role.onDetach) {
				role.onDetach.call(element);
			}
		}
		return this;
	},

	getRoleInstance: function(element) {

		var role = element.get('role');
		if (role) {
			var instance = element.retrieve('moobile:role-instance');
			if (instance == null) {
				if (role.apply) {
					instance = role.apply.call(element);
					element.store('moobile:role-instance', instance);
				}
			}
			return instance;
		}

		return null;
	},

	addChildView: function(view, where, context) {

		var exists = this.childViews.contains(view);
		if (exists == true)
			return this;

		var element = view.getElement();

		this.willAddChildView(view);
		view.parentViewWillChange(this);
		view.setParentView(this);
		view.setWindow(this.window);
		this.childViews.push(view);

		var contains = this.element.contains(element);
		if (contains == false) {
			if (context) {
				element.inject(context, where);
			} else {
				switch (where) {
					case 'header': this.element.grab(element, 'top');    break;
					case 'footer': this.element.grab(element, 'bottom'); break;
					default:	   this.content.grab(element, where);	 break;
				}
			}
		}

		view.parentViewDidChange(this);
		view.startup();
		this.didAddChildView(view);

		Object.defineMember(this, view, view.name);

		return this;
	},

	getChildView: function(name) {
		return this.childViews.find(function(childView) {
			return childView.getName() == name;
		});
	},

	getChildViewAt: function(index) {
		return this.childViews[index] || null;
	},

	replaceChildView: function(replace, view) {
		return this.addChildView(view, 'before', replace).removeChildView(replace);
	},

	removeChildView: function(view) {

		var exists = this.childViews.contains(view);
		if (exists == false)
			return this;

		var element = view.getElement();

		this.willRemoveChildView(view);
		view.parentViewWillChange(null);
		view.setParentView(null);
		view.setWindow(null);
		view.parentViewDidChange(null);
		element.dispose();
		this.childViews.erase(view);
		this.didRemoveChildView(view);

		return this;
	},

	removeFromParentView: function() {
		var parent = this.parentView || this.window;
		if (parent) parent.removeChildView(this);
		return this;
	},

	destroyChildViews: function() {
		this.childViews.each(this.bound('destroyChildView'));
		this.childViews.empty();
		return this;
	},

	destroyChildView: function(view) {
		view.destroy();
		view = null;
		return this;
	},

	show: function() {
		this.willShow();
		this.element.show();
		this.didShow();
		return this;
	},

	hide: function() {
		this.willHide();
		this.element.hide();
		this.didHide();
		return this;
	},

	setWindow: function(window) {
		this.window = window;
		return this;
	},

	getWindow: function(window) {
		return this.window;
	},

	getName: function() {
		return this.name;
	},

	isReady: function() {
		return this.ready;
	},

	getElement: function(selector) {
		return selector ? this.getElements(selector)[0] || null : this.element;
	},

	getElements: function(selector) {
		return this.element.getElements(selector).filter(this.bound('filterElement'));
	},

	filterElement: function(element) {

		var roles = [];

		var keys = Moobile.View.Roles;
		for (var key in keys) {
			if (keys[key].stop) roles.push(key);
		}

		var parent = element.getParent('[data-role]');
		while (true) {

			if (parent == null) {
				return true
			}

			var role = parent.get('role');
			if (role && role.stop) {
				if (roles.contains(role.name)) {
					return parent === this.element;
				}
			}

			parent = parent.getParent('[data-role]');
		}

		return false;
	},

	getContent: function() {
		return this.content;
	},

	setParentView: function(parentView) {
		this.parentView = parentView;
		return this;
	},

	getParentView: function() {
		return this.parentView;
	},

	getChildViews: function() {
		return this.childViews;
	},

	get: function(name) {

		switch (name) {
			case 'html':
			case 'text':
				return this.content.get(name);
			default:
				return this.element.get(name);
		}

		return t;
	},

	set: function(name, value) {

		switch (name) {
			case 'html':
			case 'text':
				this.content.set(name, value);
				break;
			default:
				this.element.set(name, value);
				break;
		}

		return this;
	},

	addClass: function(name) {
		this.element.addClass(name);
		return this;
	},

	removeClass: function(name) {
		this.element.removeClass(name);
		return this;
	},

	toggleClass: function(name) {
		this.element.toggleClass(name);
		return this;
	},

	setStyle: function(style, value) {
		this.element.setStyle(style, value);
		return this;
	},

	setStyles: function(styles) {
		this.element.setStyles(styles);
		return this;
	},

	getStyle: function(style) {
		return this.element.getStyle(style);
	},

	getStyles: function(styles) {
		return this.element.getStyles(styles);
	},

	removeStyle: function(style) {
		this.element.removeStyle(style);
		return this;
	},

	removeStyles: function(styles) {
		this.element.removeStyles(styles);
		return this;
	},

	getSize: function() {
		return this.element.getSize();
	},

	parentViewWillChange: function(parentView) {
		return this;
	},

	parentViewDidChange: function(parentView) {
		return this;
	},

	willAddChildView: function(childView) {
		return this;
	},

	didAddChildView: function(childView) {
		return this;
	},

	willRemoveChildView: function(childView) {
		return this;
	},

	didRemoveChildView: function(childView) {
		return this;
	},

	willAddChildElement: function(childElement) {
		return this;
	},

	didAddChildElement: function(childElement) {
		return this;
	},

	willRemoveChildElement: function(childElement) {
		return this;
	},

	didRemoveChildElement: function(childElement) {
		return this;
	},

	willShow: function() {
		return this;
	},

	didShow: function() {
		return this;
	},

	willHide: function() {
		return this;
	},

	didHide: function() {
		return this;
	},

	onViewSwipe: function(e) {
		e.target = this;
		this.fireEvent('swipe', e);
		return this;
	},

	onViewClick: function(e) {
		e.target = this;
		this.fireEvent('click', e);
		return this;
	},

	onViewMouseUp: function(e) {
		e.target = this;
		this.fireEvent('mouseup', e);
		return this;
	},

	onViewMouseDown: function(e) {
		e.target = this;
		this.fireEvent('mousedown', e);
		return this;
	},

	toElement: function() {
		return this.element;
	}

});<|endoftext|>


<commit_before>(function () { /* Begin of privacy scope */
    "use strict";

    gpf.encoding = {};

    /**
     * encode (string input) : byte[]
     *
     * decode (byte[] input, byte[] unprocessed) : string
     */

    //region UTF-8
    // UTF-8 encode/decode based on  http://www.webtoolkit.info/

    var
        utf8 = {

            encode: function (input) {
                var
                    result = [],
                    len = input.length,
                    idx,
                    charCode;
                for (idx = 0; idx < len; ++idx) {
                    charCode = input.charCodeAt(idx);
                    if (charCode < 128) {
                        result.push(charCode);
                    } else if(charCode > 127 && charCode < 2048) {
                        result.push((charCode >> 6) | 192);
                        result.push((charCode & 63) | 128);
                    } else {
                        result.push((charCode >> 12) | 224);
                        result.push(((charCode >> 6) & 63) | 128);
                        result.push((charCode & 63) | 128);
                    }
                }
                return result;
            },

            decode: function (input, unprocessed) {
                var
                    result = [],
                    len = input.length,
                    idx,
                    byte,
                    byte2,
                    byte3;
                while (idx < len) {
                    byte = input[idx];
                    if (byte < 128) {
                        result.push(String.fromCharCode(byte));
                    } else if(byte > 191 && byte < 224) {
                        if (idx + 1 === len) {
                            break;
                        }
                        byte2 = input[++idx];
                        result.push(String.fromCharCode(((byte & 31) << 6)
                            | (byte2 & 63)));
                    }
                    else {
                        if (idx + 2 >= len) {
                            break;
                        }
                        byte2 = input[++idx];
                        byte3 = input[++idx];
                        result.push(String.fromCharCode(((byte & 15) << 12)
                            | ((byte2 & 63) << 6) | (byte3 & 63)));
                    }
                    ++idx;
                }
                while (idx < len) {
                    unprocessed.push(input[idx++]);
                }
                return result.join("");
            }

        };

    //endregion

}()); /* End of privacy scope */
<commit_msg>Encoding WIP<commit_after>(function () { /* Begin of privacy scope */
    "use strict";

    var
        gpfI = gpf.interfaces,

        //region UTF-8
        // UTF-8 encode/decode based on  http://www.webtoolkit.info/

        _utf8Encode = function (input) {
            var
                result = [],
                len = input.length,
                idx,
                charCode;
            for (idx = 0; idx < len; ++idx) {
                charCode = input.charCodeAt(idx);
                if (charCode < 128) {
                    result.push(charCode);
                } else if(charCode > 127 && charCode < 2048) {
                    result.push((charCode >> 6) | 192);
                    result.push((charCode & 63) | 128);
                } else {
                    result.push((charCode >> 12) | 224);
                    result.push(((charCode >> 6) & 63) | 128);
                    result.push((charCode & 63) | 128);
                }
            }
            return result;
        },

        _utf8Decode = function (input, unprocessed) {
            var
                result = [],
                len = input.length,
                idx,
                byte,
                byte2,
                byte3;
            while (idx < len) {
                byte = input[idx];
                if (byte < 128) {
                    result.push(String.fromCharCode(byte));
                } else if(byte > 191 && byte < 224) {
                    if (idx + 1 === len) {
                        break;
                    }
                    byte2 = input[++idx];
                    result.push(String.fromCharCode(((byte & 31) << 6)
                        | (byte2 & 63)));
                }
                else {
                    if (idx + 2 >= len) {
                        break;
                    }
                    byte2 = input[++idx];
                    byte3 = input[++idx];
                    result.push(String.fromCharCode(((byte & 15) << 12)
                        | ((byte2 & 63) << 6) | (byte3 & 63)));
                }
                ++idx;
            }
            while (idx < len) {
                unprocessed.push(input[idx++]);
            }
            return result.join("");
        },

        //endregion

        /**
         * Map that relates encoding to the appropriate encoder/decoder
         *
         * encode (string input) : byte[]
         * decode (byte[] input, byte[] unprocessed) : string
         *
         * @type {Object}
         * @private
         */
        _encodings = {
            "utf-8": [_utf8Encode, _utf8Decode]
        };

    gpf.encoding = {

        /**
         * Create a encoder to convert an input text stream into an output
         * binary buffer.
         *
         * @param {gpf.interfaces.IReadableStream} input
         * @param {String} encoding
         * @return {gpf.interfaces.IReadableStream}
         */
        createEncoder: function (input, encoding) {
            var iStream = gpfI.query(input, gpfI.IReadableStream, true),
                module = _encodings[encoding];
            if (undefined === module) {

            }

        },

        createDecoder: function (input, encoding) {

        }
    };

}()); /* End of privacy scope */
<|endoftext|>