<commit_before>/*:
 * RS_ScreenShot.js
 * @plugindesc This plugin creates the screenshot file in ScreenShots folder when you press on the specific key.
 *
 * @author biud436
 * @date 2015.12.22
 *
 * @param key
 * @desc Type the keyCode.
 * @default 118
 *
 * @param Screenshot Preview Window
 * @desc
 * @default true
 *
 * @param Play Se
 * @desc Yes - true, No - false
 * @default true
 *
 * @param Se Name
 * @desc Specify a sound file from audio/se folder.
 * @default Save
 * @require 1
 * @dir audio/se/
 * @type file
 *
 * @reference http://stackoverflow.com/questions/32613060/how-to-take-screenshot-with-node-webkit
 *
 * @help
 * - Key Code Link
 * https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
 *
 * - Change Log
 * 2015.12.22 (v1.0.0) - First Release.
 * 2016.03.20 (v1.0.1) - Added parameter called key.
 * 2016.08.13 (v1.0.2) - Added previewWindow.
 * 2016.11.27 (v1.0.3) - Added the code that can delete the texture from the memory.
 * 2016.11.27 (v1.0.4) : Fixed preview window in the html format instead of an image.
 * - Displays the name of the screen shot file in the preview window.
 * - Plays the sound when you are taking a screenshot.
 */
/*:ko
* RS_ScreenShot.js
* @plugindesc 이 플러그인은 스크린샷 파일을 만듭니다.
*
* @author biud436
* @date 2015.12.22
*
* @param key
* @desc 키 코드를 입력하세요
* @default 118
*
* @param Screenshot Preview Window
* @desc 스크린샷을 미리 볼 지 여부를 결정합니다.
* @default true
*
* @param Play Se
* @desc 재생 - true, 재생하지 않음 - false
* @default true
*
* @param Se Name
* @desc audio/se 폴더에 있는 사운드 파일을 지정하세요.
* @default Save
*
* @reference http://stackoverflow.com/questions/32613060/how-to-take-screenshot-with-node-webkit
*
* @help
* - Key Code Link
* https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
*
* - Change Log
* 2015.12.22 (v1.0.0) - First Release.
* 2016.03.20 (v1.0.1) - Added parameter called key.
* 2016.08.13 (v1.0.2) - Added preview window.
* 2016.11.27 (v1.0.3) - Added the code that can delete the texture from the memory.
* 2016.11.27 (v1.0.4) : Fixed preview window in the html format instead of an image.
* - Displays the name of the screen shot file in the preview window.
* - Plays the sound when you are taking a screenshot.
*/

var Imported = Imported || {};
Imported.RS_ScreenShot = true;

var RS = RS || {};
RS.ScreenShot = RS.ScreenShot || {};

(function($) {

  var parameters = PluginManager.parameters('RS_ScreenShot');
  $.KEY = Number(parameters['key'] || 118 );
  $.isPreviewWindow = Boolean(parameters['Screenshot Preview Window'] === 'true');
  $.isPlaySe = Boolean(parameters['Play Se'] === 'true');
  $.seName = parameters['Se Name'] || 'Save';

  $.getPath = function () {
    var path = window.location.pathname.replace(/(\/www|)\/[^\/]*$/, '/ScreenShots/');
    if (path.match(/^\/([A-Z]\:)/)) {
      path = path.slice(1);
    }
    return decodeURIComponent(path);
  };

  $.previewScreenShot = function (fileName) {
    var renderer = Graphics._renderer;
    var renderTexture = PIXI.RenderTexture.create(renderer.width, renderer.height);
    var stage = SceneManager._scene;
    if(stage) {
      renderer.render(stage, renderTexture);
      var canvas = renderer.extract.base64(renderTexture);
      var html = [
        '<!DOCTYPE html>',
        '',
        '  ',
        '    <meta charset="utf-8">',
        '  ',
        '  <title>ScreenShots Preview</title>',
        '  ',
        '
%1.png
'.format(fileName),
        '',
        ''.format(canvas),
        '',
        ''
      ].join('\n');
      var blob = new Blob([html], {type : 'text/html'});
      var url = URL.createObjectURL(blob);
      var win = window.open(url, '_blank');
    }
    if(renderTexture) renderTexture.destroy( { destroyBase: true } );
  };

  $.takeSnapshot = function() {

    if(!StorageManager.isLocalMode()) {
      return;
    }

    var gui = require('nw.gui');
    var win = gui.Window.get();
    var fs = require('fs');
    var filePath;

    var result = win.capturePage(function(buffer) {
      if(!fs.existsSync(this.getPath()) ) {
        fs.mkdirSync(this.getPath());
      }
      var fileName = new Date().toJSON().replace(/[.:]+/g, "-");
      filePath = this.getPath() + '%1.png'.format(fileName);
      fs.writeFile(filePath, buffer, function (err) {
        if (err) throw err;
        if($.isPlaySe) {
          AudioManager.playStaticSe({name: $.seName, pan: 0, pitch: 100, volume: ConfigManager.seVolume});
        }
        if($.isPreviewWindow) $.previewScreenShot(fileName);
      });

    }.bind(this), { format : 'png', datatype : 'buffer'} );

  };

  var alias_SceneManager_onKeyDown = SceneManager.onKeyDown;
  SceneManager.onKeyDown = function(event) {
      alias_SceneManager_onKeyDown.apply(this, arguments);
      if (!event.ctrlKey && !event.altKey) {
        switch (event.keyCode) {
        case $.KEY:   // F7
          $.takeSnapshot();
        break;
        }
      }
  };

})(RS.ScreenShot);
<commit_msg>added the option about exclude unused files in Korean Comment Blocks<commit_after>/*:
 * RS_ScreenShot.js
 * @plugindesc This plugin creates the screenshot file in ScreenShots folder when you press on the specific key.
 *
 * @author biud436
 * @date 2015.12.22
 *
 * @param key
 * @desc Type the keyCode.
 * @default 118
 *
 * @param Screenshot Preview Window
 * @desc
 * @default true
 *
 * @param Play Se
 * @desc Yes - true, No - false
 * @default true
 *
 * @param Se Name
 * @desc Specify a sound file from audio/se folder.
 * @default Save
 * @require 1
 * @dir audio/se/
 * @type file
 *
 * @reference http://stackoverflow.com/questions/32613060/how-to-take-screenshot-with-node-webkit
 *
 * @help
 * - Key Code Link
 * https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
 *
 * - Change Log
 * 2015.12.22 (v1.0.0) - First Release.
 * 2016.03.20 (v1.0.1) - Added parameter called key.
 * 2016.08.13 (v1.0.2) - Added previewWindow.
 * 2016.11.27 (v1.0.3) - Added the code that can delete the texture from the memory.
 * 2016.11.27 (v1.0.4) : Fixed preview window in the html format instead of an image.
 * - Displays the name of the screen shot file in the preview window.
 * - Plays the sound when you are taking a screenshot.
 */
/*:ko
* RS_ScreenShot.js
* @plugindesc 이 플러그인은 스크린샷 파일을 만듭니다.
*
* @author biud436
* @date 2015.12.22
*
* @param key
* @desc 키 코드를 입력하세요
* @default 118
*
* @param Screenshot Preview Window
* @desc 스크린샷을 미리 볼 지 여부를 결정합니다.
* @default true
*
* @param Play Se
* @desc 재생 - true, 재생하지 않음 - false
* @default true
*
* @param Se Name
* @desc audio/se 폴더에 있는 사운드 파일을 지정하세요.
* @default Save
* @require 1
* @dir audio/se/
* @type file
*
* @reference http://stackoverflow.com/questions/32613060/how-to-take-screenshot-with-node-webkit
*
* @help
* - Key Code Link
* https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
*
* - Change Log
* 2015.12.22 (v1.0.0) - First Release.
* 2016.03.20 (v1.0.1) - Added parameter called key.
* 2016.08.13 (v1.0.2) - Added preview window.
* 2016.11.27 (v1.0.3) - Added the code that can delete the texture from the memory.
* 2016.11.27 (v1.0.4) : Fixed preview window in the html format instead of an image.
* - Displays the name of the screen shot file in the preview window.
* - Plays the sound when you are taking a screenshot.
*/

var Imported = Imported || {};
Imported.RS_ScreenShot = true;

var RS = RS || {};
RS.ScreenShot = RS.ScreenShot || {};

(function($) {

  var parameters = PluginManager.parameters('RS_ScreenShot');
  $.KEY = Number(parameters['key'] || 118 );
  $.isPreviewWindow = Boolean(parameters['Screenshot Preview Window'] === 'true');
  $.isPlaySe = Boolean(parameters['Play Se'] === 'true');
  $.seName = parameters['Se Name'] || 'Save';

  $.getPath = function () {
    var path = window.location.pathname.replace(/(\/www|)\/[^\/]*$/, '/ScreenShots/');
    if (path.match(/^\/([A-Z]\:)/)) {
      path = path.slice(1);
    }
    return decodeURIComponent(path);
  };

  $.previewScreenShot = function (fileName) {
    var renderer = Graphics._renderer;
    var renderTexture = PIXI.RenderTexture.create(renderer.width, renderer.height);
    var stage = SceneManager._scene;
    if(stage) {
      renderer.render(stage, renderTexture);
      var canvas = renderer.extract.base64(renderTexture);
      var html = [
        '<!DOCTYPE html>',
        '',
        '  ',
        '    <meta charset="utf-8">',
        '  ',
        '  <title>ScreenShots Preview</title>',
        '  ',
        '
%1.png
'.format(fileName),
        '',
        ''.format(canvas),
        '',
        ''
      ].join('\n');
      var blob = new Blob([html], {type : 'text/html'});
      var url = URL.createObjectURL(blob);
      var win = window.open(url, '_blank');
    }
    if(renderTexture) renderTexture.destroy( { destroyBase: true } );
  };

  $.takeSnapshot = function() {

    if(!StorageManager.isLocalMode()) {
      return;
    }

    var gui = require('nw.gui');
    var win = gui.Window.get();
    var fs = require('fs');
    var filePath;

    var result = win.capturePage(function(buffer) {
      if(!fs.existsSync(this.getPath()) ) {
        fs.mkdirSync(this.getPath());
      }
      var fileName = new Date().toJSON().replace(/[.:]+/g, "-");
      filePath = this.getPath() + '%1.png'.format(fileName);
      fs.writeFile(filePath, buffer, function (err) {
        if (err) throw err;
        if($.isPlaySe) {
          AudioManager.playStaticSe({name: $.seName, pan: 0, pitch: 100, volume: ConfigManager.seVolume});
        }
        if($.isPreviewWindow) $.previewScreenShot(fileName);
      });

    }.bind(this), { format : 'png', datatype : 'buffer'} );

  };

  var alias_SceneManager_onKeyDown = SceneManager.onKeyDown;
  SceneManager.onKeyDown = function(event) {
      alias_SceneManager_onKeyDown.apply(this, arguments);
      if (!event.ctrlKey && !event.altKey) {
        switch (event.keyCode) {
        case $.KEY:   // F7
          $.takeSnapshot();
        break;
        }
      }
  };

})(RS.ScreenShot);
<|endoftext|>


<commit_before>// this sets the background color of the master UIView (when there are no windows/tab groups on it)
Titanium.UI.setBackgroundColor('#000');

//
// create base UI tab and root window
//
var win1 = Titanium.UI.createWindow({
    title:'Tab 1',
    backgroundColor:'#fff'
});

var label1_1 = Titanium.UI.createLabel({
	color:'#999',
	text:'Plaats',
	font:{fontSize:20,fontFamily:'Helvetica Neue'},
	textAlign:'center',
	width:'auto',
	top:10,
	left:20
});

var picker1_1 = Ti.UI.createPicker({
	top:10,
	left:100
});

var data1_1 = [];
data1_1[0]=Ti.UI.createPickerRow({title:'De vest',custom_item:'v'});
data1_1[1]=Ti.UI.createPickerRow({title:'De ham',custom_item:'h'});
data1_1[2]=Ti.UI.createPickerRow({title:'Kruidtuin',custom_item:'k'});

// turn on the selection indicator (off by default)
picker1_1.selectionIndicator = true;

picker1_1.add(data1_1);

picker1_1.setSelectedRow(0,0,true);

var label1_2 = Titanium.UI.createLabel({
	color:'#999',
	text:'Gebouw',
	font:{fontSize:20,fontFamily:'Helvetica Neue'},
	textAlign:'center',
	width:'auto',
	top:60,
	left:20
});

var picker1_2 = Ti.UI.createPicker({
	top:60,
	left:100
});

var data1_2 = [];
data1_2[0]=Ti.UI.createPickerRow({title:'Verdiep 1',custom_item:'v1'});
data1_2[1]=Ti.UI.createPickerRow({title:'Verdiep 2',custom_item:'v2'});
data1_2[2]=Ti.UI.createPickerRow({title:'Verdiep 3',custom_item:'v3'});

// turn on the selection indicator (off by default)
picker1_2.selectionIndicator = true;

picker1_2.add(data1_2);

picker1_2.setSelectedRow(0,0,true);

var label1_3 = Titanium.UI.createLabel({
	color:'#999',
	text:'Verdiep',
	font:{fontSize:20,fontFamily:'Helvetica Neue'},
	textAlign:'center',
	width:'auto',
	top:110,
	left:20
});

var picker1_3 = Ti.UI.createPicker({
	top:110,
	left:100
});

var data1_3 = [];
data1_3[0]=Ti.UI.createPickerRow({title:'Lokaal 1',custom_item:'l1'});
data1_3[1]=Ti.UI.createPickerRow({title:'Lokaal 2',custom_item:'l2'});
data1_3[2]=Ti.UI.createPickerRow({title:'Lokaal 3',custom_item:'l3'});

// turn on the selection indicator (off by default)
picker1_3.selectionIndicator = true;

picker1_3.add(data1_3);

picker1_3.setSelectedRow(0,0,true);

win1.add(label1_1);
win1.add(picker1_1);
win1.add(label1_2);
win1.add(picker1_2);
win1.add(label1_3);
win1.add(picker1_3);

//lijst binnen halen met problemen op die locatie

var label1_4 = Titanium.UI.createLabel({
	color:'#999',
	text:'Problemen',
	font:{fontSize:20,fontFamily:'Helvetica Neue'},
	textAlign:'center',
	width:'auto',
	top:160,
	left:20
});

var nodeTable = Ti.UI.createTableView({
  	height: '100%',
  	width: '100%',
  	top:190
});
win1.add(label1_4);
win1.add(nodeTable);

var xhr = Titanium.Network.createHTTPClient();

var nodes = [];

  xhr.onload = function()
  {
    //Just log the responseText for fun
    Ti.API.info(this.responseText);

    //We translate the json string into a neat object
    var response = JSON.parse(this.responseText);

    for (var i in response) {
      node = response[i];
      var row = Ti.UI.createTableViewRow({
        title : node.title,
      });
      nodes.push(row);
    }
    nodeTable.data = nodes;
  };

  xhr.onerror = function ()
  {
    Ti.API.info('Unable to fetch nodes from Drupal');
    nodeTable.data = nodes;
  };
// open the client
xhr.open('GET','http://www.vandenboschan2011.dreamhosters.com/drupal-7.10/api/node');

// send the data
xhr.send();

//knop volgende window
var button = Titanium.UI.createButton({
	title:'Volgende stap',
	top:350,
	right:10
});

button.addEventListener('click',function(e)
{
	Ti.API.info('open window');
	//window openen
	win1.close();
	win2.open();
});

win1.add(button);

win1.open();

//
// create controls tab and root window
//
var win2 = Titanium.UI.createWindow({
    title:'Tab 2',
    backgroundColor:'#fff',
    url:'probleem.js'
});<commit_msg>eerste window layout<commit_after>// this sets the background color of the master UIView (when there are no windows/tab groups on it)
Titanium.UI.setBackgroundColor('#000');

//
// create base UI tab and root window
//
var winmain = Titanium.UI.createWindow({
    title:'Less Rooster Home',
    backgroundColor:'#fff'
});

var labelPlaats = Titanium.UI.createLabel({
	color:'#999',
	text:'Plaats',
	font:{fontSize:30,fontFamily:'Helvetica Neue'},
	textAlign:'center',
	width:'auto',
	top:15,
	left:20
});

var picker1_1 = Ti.UI.createPicker({
	top:10,
	left:200
});

var data1_1 = [];
data1_1[0]=Ti.UI.createPickerRow({title:'De vest',custom_item:'v'});
data1_1[1]=Ti.UI.createPickerRow({title:'De ham',custom_item:'h'});
data1_1[2]=Ti.UI.createPickerRow({title:'Kruidtuin',custom_item:'k'});

// turn on the selection indicator (off by default)
picker1_1.selectionIndicator = true;

picker1_1.add(data1_1);

picker1_1.setSelectedRow(0,0,true);

var labelGebouw = Titanium.UI.createLabel({
	color:'#999',
	text:'Gebouw',
	font:{fontSize:30,fontFamily:'Helvetica Neue'},
	textAlign:'center',
	width:'auto',
	top:85,
	left:20
});

var picker1_2 = Ti.UI.createPicker({
	top:80,
	left:200
});

var data1_2 = [];
data1_2[0]=Ti.UI.createPickerRow({title:'Verdiep 1',custom_item:'v1'});
data1_2[1]=Ti.UI.createPickerRow({title:'Verdiep 2',custom_item:'v2'});
data1_2[2]=Ti.UI.createPickerRow({title:'Verdiep 3',custom_item:'v3'});

// turn on the selection indicator (off by default)
picker1_2.selectionIndicator = true;

picker1_2.add(data1_2);

picker1_2.setSelectedRow(0,0,true);

var labelVerdiep = Titanium.UI.createLabel({
	color:'#999',
	text:'Verdiep',
	font:{fontSize:30,fontFamily:'Helvetica Neue'},
	textAlign:'center',
	width:'auto',
	top:155,
	left:20
});

var picker1_3 = Ti.UI.createPicker({
	top:150,
	left:200
});

var data1_3 = [];
data1_3[0]=Ti.UI.createPickerRow({title:'Lokaal 1',custom_item:'l1'});
data1_3[1]=Ti.UI.createPickerRow({title:'Lokaal 2',custom_item:'l2'});
data1_3[2]=Ti.UI.createPickerRow({title:'Lokaal 3',custom_item:'l3'});

// turn on the selection indicator (off by default)
picker1_3.selectionIndicator = true;

picker1_3.add(data1_3);

picker1_3.setSelectedRow(0,0,true);

winmain.add(labelPlaats);
winmain.add(picker1_1);
winmain.add(labelGebouw);
winmain.add(picker1_2);
winmain.add(labelVerdiep);
winmain.add(picker1_3);

//lijst binnen halen met problemen op die locatie

var label1_4 = Titanium.UI.createLabel({
	text:'Bestaande Problemen',
	color: 'black',
	backgroundColor: 'grey',
	font:{fontSize:30,fontFamily:'Helvetica Neue'},
	textAlign:'center',
	width:'auto',
	top:235,
	left:20
});

var nodeTable = Ti.UI.createTableView({
  	height: '80%',
  	width: '80%',
  	align: 'center',
  	top:270

});

winmain.add(label1_4);
winmain.add(nodeTable);

var xhr = Titanium.Network.createHTTPClient();

var nodes = [];

  xhr.onload = function()
  {
    //Just log the responseText for fun
    Ti.API.info(this.responseText);

    //We translate the json string into a neat object
    var response = JSON.parse(this.responseText);

    for (var i in response) {
      node = response[i];
      var row = Ti.UI.createTableViewRow({
        title : node.title,
      });
      nodes.push(row);
    }
    nodeTable.data = nodes;
  };

  xhr.onerror = function ()
  {
    Ti.API.info('Unable to fetch nodes from Drupal');
    nodeTable.data = nodes;
  };
// open the client
xhr.open('GET','http://www.vandenboschan2011.dreamhosters.com/drupal-7.10/api/node');

// send the data
xhr.send();

//knop nieuw probleem
var button = Titanium.UI.createButton({
	title:'Nieuw Probleem',
	color: '#A90329',
	align: 'center',
	top:650,
});

button.addEventListener('click',function(e)
{
	Ti.API.info('open window');
	//window openen
	winmain.close();
	win2.open();
});

winmain.add(button);

winmain.open();

//
// create 2nd window
//
var win2 = Titanium.UI.createWindow({
    title:'Tab 2',
    backgroundColor:'#fff',
    url:'probleem.js'
});<|endoftext|>


<commit_before>// this sets the background color of the master UIView (when there are no windows/tab groups on it)
Titanium.include('initializers/init.js');
try { App.run(); } catch(E) { alert("Failed with "+E); }
require('support/date');

App.setHost("http://quiet-waterfall-1228.herokuapp.com/api");

Layouts.application();
<commit_msg>speakers<commit_after>// this sets the background color of the master UIView (when there are no windows/tab groups on it)
Titanium.include('initializers/init.js');
try { App.run(); } catch(E) { alert("Failed with "+E); }
require('support/date');

App.setHost("http://quiet-waterfall-1228.herokuapp.com/api");

// Layouts.application();
<|endoftext|>


<commit_before>// GLOBAL VARS
var globals = require('lib/globals');
var HTTPClientWithCache = require('lib/HTTPClientWithCache').HTTPClientWithCache;
if (globals.osname === 'iphone') {
  var Flurry = require('ti.flurry');
  Flurry.initialize("4FIT53J4GC77BQB84HX2");
}
var MainTabView;
if (globals.osname === 'iphone' || globals.osname === 'android') {
  MainTabView = require('/ui/common/mainTabView').mainTabView;
}
else {
  MainTabView = require('/ui/common/mainTabView').mainTabView;
  // Commented out iPad interface for now :)
  //MainTabView = require('/ui/ipad/mainSplitView').mainSplitView;
}
if (globals.osname != 'android') {
  new MainTabView().open({transition:Ti.UI.iPhone.AnimationStyle.FLIP_FROM_LEFT});
}
new MainTabView().open();

// Global Event Listeners
Ti.App.addEventListener('events.update', function(args){
  if (Ti.Network.online) {
    var events_xhr = new HTTPClientWithCache({
      baseUrl: globals.baseUrl,
      retryCount: 2,
      cacheSeconds: 300,
      onload: function(response) {
        //Ti.API.info("Response Data: "+ response.responseText);
        //Ti.API.info("Is this cached data?: " + response.cached);
        globals.slcdbSaveEvents(response.responseText);
        if (typeof args.callback === 'function') {
          args.callback;
        }
      }
    });
    if (args.prune) {
      events_xhr.prune_cache(0);
    }
    events_xhr.post({url: globals.eventsUrl});
  } else {
    // Maybe this should fail silently with just a log message
    var dialog = Ti.UI.createAlertDialog({
      message: 'You must be online to refresh the schedule data.',
      ok: 'Okay',
      title: 'Oh noes!'
    }).show();
  }
});
// If there are no sessions, populate the database
var result = globals.dbGetEvents();
if (result.length == 0) {
  Ti.App.fireEvent('events.update', {prune: true});
}

Ti.App.addEventListener('speakers.update', function(args){
  if (Ti.Network.online) {
    var speakers_xhr = new HTTPClientWithCache({
      baseUrl: globals.baseUrl,
      retryCount: 2,
      cacheSeconds: 300,
      onload: function(response) {
        //Ti.API.info("Response Data: "+ response.responseText);
        //Ti.API.info("Is this cached data?: " + response.cached);
        globals.setSpeakerData(response.responseText);
        Ti.App.fireEvent('speakers.updateTableView');
        if (typeof args.callback === 'function') {
          args.callback;
        }
      }
    });
    if (args.prune) {
      speakers_xhr.prune_cache(0);
    }
    speakers_xhr.post({url: globals.speakersUrl});
  } else {
    // Maybe this should fail silently with just a log message
    var dialog = Ti.UI.createAlertDialog({
      message: 'You must be online to refresh the speakers data.',
      ok: 'Okay',
      title: 'Oh noes!'
    }).show();
  }
});

Ti.App.addEventListener('schedule.click', function(opts) {
  var winClass = require('ui/common/workshopWindow').workshopWindow;
  var nodeData = globals.dbGetWorkshopEvents(opts.nid);
  var workshop = globals.dbGetSingleEvent(opts.nid);
  var args = {
    workshop: workshop,
    nodes: nodeData
  };
  var scheduleFirstWin = new winClass(args);
  Ti.API._activeTab.open(scheduleFirstWin, {animated: true});
  // Run user supplied callback
  if (typeof opts.callback === 'function') {
    callback();
  }
});

Ti.App.addEventListener('session.click', function(opts) {
  var winClass = require('ui/common/audioPlayer').window;
  var nodeData = globals.dbGetSingleEvent(opts.nid);
  var args = {node: nodeData};
  var audioPlayerWin = new winClass(args);
  Ti.API._activeTab.open(audioPlayerWin, {animated: true});
  // Run user supplied callback
  if (typeof opts.callback === 'function') {
    callback();
  }
});

// TODO: Remove this code, no longer needed.
Ti.App.addEventListener('day.click', function(opts){
  var winClass = require('ui/common/workshopWindow').workshopWindow;
  var workshopWin = new winClass(opts);
  Ti.API._activeTab.open(workshopWin, {animated: true});
  // Run user supplied callback
  if (typeof opts.callback === 'function') {
    callback();
  }
});

Ti.App.addEventListener('map.click', function(opts) {
  var winClass = require('ui/common/staticPageWindow').staticPageWindow;
  var mapDetailWindow = new winClass(opts);
  /**
  if (globals.osname === "ipad") {
    Ti.App.fireEvent('detailView.change', {
      requirejs: 'ui/common/staticPageWindow',
      classname: 'staticPageWindow',
      args: opts
    });
  } else {
    Ti.API._activeTab.open(mapDetailWindow, {animated: true});
  }
  */
  Ti.API._activeTab.open(mapDetailWindow, {animated: true});
  // Run user supplied callback
  if (typeof opts.callback === 'function') {
    callback();
  }
});

Ti.App.addEventListener('speakers.click', function(opts) {
  var winClass = require('ui/common/speakerDetailWindow').speakerDetailWindow;
  var speakerDetailWindow = new winClass(opts);
  Ti.API._activeTab.open(speakerDetailWindow, {animated: true});
  // Run user supplied callback
  if (typeof opts.callback === 'function') {
    callback();
  }
});

Ti.App.addEventListener('live.click', function() {
  if (Ti.Network.online) {
    var winClass = require('ui/iphon/livePlayerWindow').livePlayerWindow;
    var livePlayerWindow = new winClass();
    Ti.API._activeTab.open(livePlayerWindow, {animated: true});
  } else {
    var dialog = Ti.UI.createAlertDialog({
      title: 'Oh noes!',
      message: 'You must be online in order to access our live stream events.',
      ok: 'Okay'
    }).show();
  }
});
Ti.App.addEventListener('live.update', function(args) {
  if (Ti.Network.online) {
    var live_xhr = new HTTPClientWithCache({
      baseUrl: globals.baseUrl,
      retryCount: 2,
      cacheSeconds: 300,
      onload: function(response) {
        //Ti.API.info("Response Data: "+ response.responseText);
        //Ti.API.info("Is this cached data?: " + response.cached);
        globals.setLiveData(response.responseText);
        Ti.App.fireEvent('live.updateTableView');
        if (typeof args.callback === 'function') {
          args.callback;
        }
      }
    });
    if (args.prune) {
      live_xhr.prune_cache(0);
    }
    live_xhr.post({url: globals.liveUrl});
  } else {
    var dialog = Ti.UI.createAlertDialog({
      title: 'Oh noes!',
      message: 'You must be online in order to update the live stream event feed.',
      ok: 'Okay'
    }).show();
  }
});

Ti.App.addEventListener('photos.click', function(opts) {
  var winClass = require('ui/common/photosDetailWindow').photosDetailWindow;
  var photoDetailWindow = new winClass(opts);
  if (globals.osname != 'android') photoDetailWindow.hideTabBar();
  Ti.API._activeTab.open(photoDetailWindow, {animated: true});
  if (typeof opts.callback === 'function') {
    callback();
  }
});
<commit_msg>fixes for sessionWindow<commit_after>// GLOBAL VARS
var globals = require('lib/globals');
var HTTPClientWithCache = require('lib/HTTPClientWithCache').HTTPClientWithCache;
if (globals.osname === 'iphone') {
  var Flurry = require('ti.flurry');
  Flurry.initialize("4FIT53J4GC77BQB84HX2");
}
var MainTabView;
if (globals.osname === 'iphone' || globals.osname === 'android') {
  MainTabView = require('/ui/common/mainTabView').mainTabView;
}
else {
  MainTabView = require('/ui/common/mainTabView').mainTabView;
  // Commented out iPad interface for now :)
  //MainTabView = require('/ui/ipad/mainSplitView').mainSplitView;
}
if (globals.osname != 'android') {
  new MainTabView().open({transition:Ti.UI.iPhone.AnimationStyle.FLIP_FROM_LEFT});
}
new MainTabView().open();

// Global Event Listeners
Ti.App.addEventListener('events.update', function(args){
  if (Ti.Network.online) {
    var events_xhr = new HTTPClientWithCache({
      baseUrl: globals.baseUrl,
      retryCount: 2,
      cacheSeconds: 300,
      onload: function(response) {
        //Ti.API.info("Response Data: "+ response.responseText);
        //Ti.API.info("Is this cached data?: " + response.cached);
        globals.slcdbSaveEvents(response.responseText);
        if (typeof args.callback === 'function') {
          args.callback;
        }
      }
    });
    if (args.prune) {
      events_xhr.prune_cache(0);
    }
    events_xhr.post({url: globals.eventsUrl});
  } else {
    // Maybe this should fail silently with just a log message
    var dialog = Ti.UI.createAlertDialog({
      message: 'You must be online to refresh the schedule data.',
      ok: 'Okay',
      title: 'Oh noes!'
    }).show();
  }
});
// If there are no sessions, populate the database
var result = globals.dbGetEvents();
if (result.length == 0) {
  Ti.App.fireEvent('events.update', {prune: true});
}

Ti.App.addEventListener('speakers.update', function(args){
  if (Ti.Network.online) {
    var speakers_xhr = new HTTPClientWithCache({
      baseUrl: globals.baseUrl,
      retryCount: 2,
      cacheSeconds: 300,
      onload: function(response) {
        //Ti.API.info("Response Data: "+ response.responseText);
        //Ti.API.info("Is this cached data?: " + response.cached);
        globals.setSpeakerData(response.responseText);
        Ti.App.fireEvent('speakers.updateTableView');
        if (typeof args.callback === 'function') {
          args.callback;
        }
      }
    });
    if (args.prune) {
      speakers_xhr.prune_cache(0);
    }
    speakers_xhr.post({url: globals.speakersUrl});
  } else {
    // Maybe this should fail silently with just a log message
    var dialog = Ti.UI.createAlertDialog({
      message: 'You must be online to refresh the speakers data.',
      ok: 'Okay',
      title: 'Oh noes!'
    }).show();
  }
});

Ti.App.addEventListener('schedule.click', function(opts) {
  var winClass = require('ui/common/workshopWindow').workshopWindow;
  var nodeData = globals.dbGetWorkshopEvents(opts.nid);
  var workshop = globals.dbGetSingleEvent(opts.nid);
  var args = {
    workshop: workshop,
    nodes: nodeData
  };
  var scheduleFirstWin = new winClass(args);
  Ti.API._activeTab.open(scheduleFirstWin, {animated: true});
  // Run user supplied callback
  if (typeof opts.callback === 'function') {
    callback();
  }
});

Ti.App.addEventListener('session.click', function(opts) {
  var winClass = require('ui/common/audioPlayer').window;
  var nodeData = globals.dbGetSingleEvent(opts.nid);
  var args = {node: nodeData[0]};
  var audioPlayerWin = new winClass(args);
  Ti.API._activeTab.open(audioPlayerWin, {animated: true});
  // Run user supplied callback
  if (typeof opts.callback === 'function') {
    opts.callback();
  }
});

// TODO: Remove this code, no longer needed.
Ti.App.addEventListener('day.click', function(opts){
  var winClass = require('ui/common/workshopWindow').workshopWindow;
  var workshopWin = new winClass(opts);
  Ti.API._activeTab.open(workshopWin, {animated: true});
  // Run user supplied callback
  if (typeof opts.callback === 'function') {
    callback();
  }
});

Ti.App.addEventListener('map.click', function(opts) {
  var winClass = require('ui/common/staticPageWindow').staticPageWindow;
  var mapDetailWindow = new winClass(opts);
  /**
  if (globals.osname === "ipad") {
    Ti.App.fireEvent('detailView.change', {
      requirejs: 'ui/common/staticPageWindow',
      classname: 'staticPageWindow',
      args: opts
    });
  } else {
    Ti.API._activeTab.open(mapDetailWindow, {animated: true});
  }
  */
  Ti.API._activeTab.open(mapDetailWindow, {animated: true});
  // Run user supplied callback
  if (typeof opts.callback === 'function') {
    callback();
  }
});

Ti.App.addEventListener('speakers.click', function(opts) {
  var winClass = require('ui/common/speakerDetailWindow').speakerDetailWindow;
  var speakerDetailWindow = new winClass(opts);
  Ti.API._activeTab.open(speakerDetailWindow, {animated: true});
  // Run user supplied callback
  if (typeof opts.callback === 'function') {
    callback();
  }
});

Ti.App.addEventListener('live.click', function() {
  if (Ti.Network.online) {
    var winClass = require('ui/iphon/livePlayerWindow').livePlayerWindow;
    var livePlayerWindow = new winClass();
    Ti.API._activeTab.open(livePlayerWindow, {animated: true});
  } else {
    var dialog = Ti.UI.createAlertDialog({
      title: 'Oh noes!',
      message: 'You must be online in order to access our live stream events.',
      ok: 'Okay'
    }).show();
  }
});
Ti.App.addEventListener('live.update', function(args) {
  if (Ti.Network.online) {
    var live_xhr = new HTTPClientWithCache({
      baseUrl: globals.baseUrl,
      retryCount: 2,
      cacheSeconds: 300,
      onload: function(response) {
        //Ti.API.info("Response Data: "+ response.responseText);
        //Ti.API.info("Is this cached data?: " + response.cached);
        globals.setLiveData(response.responseText);
        Ti.App.fireEvent('live.updateTableView');
        if (typeof args.callback === 'function') {
          args.callback;
        }
      }
    });
    if (args.prune) {
      live_xhr.prune_cache(0);
    }
    live_xhr.post({url: globals.liveUrl});
  } else {
    var dialog = Ti.UI.createAlertDialog({
      title: 'Oh noes!',
      message: 'You must be online in order to update the live stream event feed.',
      ok: 'Okay'
    }).show();
  }
});

Ti.App.addEventListener('photos.click', function(opts) {
  var winClass = require('ui/common/photosDetailWindow').photosDetailWindow;
  var photoDetailWindow = new winClass(opts);
  if (globals.osname != 'android') photoDetailWindow.hideTabBar();
  Ti.API._activeTab.open(photoDetailWindow, {animated: true});
  if (typeof opts.callback === 'function') {
    callback();
  }
});
<|endoftext|>


<commit_before>// this sets the background color of the master UIView (when there are no windows/tab groups on it)
Titanium.UI.setBackgroundColor('#FD9627');

var Cloud = require('ti.cloud');
Cloud.debug = true;

/* MAIN WINDOW */

var mainWindow = Ti.UI.createWindow({
	title: 'Pati Dostlari'
});

var MapModule = require('ti.map');

var rc = MapModule.isGooglePlayServicesAvailable();
switch (rc) {
    case MapModule.SUCCESS:
        Ti.API.info('Google Play services is installed.');
        break;
    case MapModule.SERVICE_MISSING:
        alert('Google Play services is missing. Please install Google Play services from the Google Play store.');
        break;
    case MapModule.SERVICE_VERSION_UPDATE_REQUIRED:
        alert('Google Play services is out of date. Please update Google Play services.');
        break;
    case MapModule.SERVICE_DISABLED:
        alert('Google Play services is disabled. Please enable Google Play services.');
        break;
    case MapModule.SERVICE_INVALID:
        alert('Google Play services cannot be authenticated. Reinstall Google Play services.');
        break;
    default:
        alert('Unknown error.');
        break;
}

var calculateLatLngfromPixels = function(mapview, xPixels, yPixels) {

    var region = mapview.actualRegion || mapview.region;
    var widthInPixels = mapview.rect.width;
    var heightInPixels = mapview.rect.height;

    // should invert because of the pixel reference frame
    heightDegPerPixel = -region.latitudeDelta / heightInPixels;
    widthDegPerPixel = region.longitudeDelta / widthInPixels;

    return {
        lat : (yPixels - heightInPixels / 2) * heightDegPerPixel + region.latitude,
        lon : (xPixels - widthInPixels / 2) * widthDegPerPixel + region.longitude

    };
};

Titanium.Geolocation.getCurrentPosition(function(e)
{
    if (e.error)
    {
        alert('HFL cannot get your current location');
        return;
    }

    var longitude = e.coords.longitude;
    var latitude = e.coords.latitude;
    var altitude = e.coords.altitude;
    var heading = e.coords.heading;
    var accuracy = e.coords.accuracy;
    var speed = e.coords.speed;
    var timestamp = e.coords.timestamp;
    var altitudeAccuracy = e.coords.altitudeAccuracy;

    var mapview = MapModule.createView({
		mapType: MapModule.NORMAL_TYPE,
		userLocation: true,
		animate: true,
		width: '100%',
		height: '100%',
		region: {latitude: latitude, longitude: longitude, latitudeDelta: 0.1, longitudeDelta: 0.1 }
	});

	mapview.addEventListener('click', function(evt)
    {
        // get event properties
        var annotation = evt.annotation; //get the Myid from annotation

        Ti.API.info("LAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA: " + annotation);

        /*var clicksource = evt.clicksource;

        if (clicksource='leftButton'){  //leftButton event
            alert("leftButton of " + annotation + " has been clicked.");
        }
        if (clicksource='title'){   //title event
            alert("title of " + annotation + " has been clicked.");
        }*/
       if (clicksource='title'){
	       var eventid = annotation.myid;

	       Cloud.Objects.show({
			    classname: 'Location',
			    id: eventid
			}, function (e) {
			    if (e.success) {

			        var locat = e.Location[0];

			        var locationWindow = Ti.UI.createWindow({
						backgroundColor:'#FD9627',
						title: 'Location'
					});

					var annot = MapModule.createAnnotation({
					    latitude:locat.latitude,
					    longitude:locat.longitude,
					    title:locat.name,
					    pincolor:MapModule.ANNOTATION_ORANGE
					});

					var annots = [];
					annots.push(annot);

					var locmap = MapModule.createView({
						top: 0,
						left: 0,
						height: '35%',
						width: '100%',

						mapType: MapModule.NORMAL_TYPE,
						userLocation: true,
						animate: true,

						region: {latitude: locat.latitude, longitude: locat.longitude, latitudeDelta: 0.1, longitudeDelta: 0.1 },
						annotations: annots
					});

					var loclabel0=Ti.UI.createLabel({

						textAlign:'center',
						backgroundColor: 'white',
						width:'350px',
						text: locat.name,
						color:'#FD9627',
						height:'70px',
						font:{fontSize:15,fontFamily:'Helvetica Neue'},
						top:'40%',
						borderRadius:15,
						borderWidth:5
					});

					var bg = '#7D736C';
					var text = "Empty (Click to fill)";

					if (locat.block0.length > 0)
					{
						bg = '#FD9627';
						text = locat.block0;
					}

					var locview1= Ti.UI.createView({

						backgroundColor: bg,
						borderRadius:15,
						borderWidth:5,
						width:'500px',
						top:'50%',
						//text: '09.00-12.00',
						height:'250px'

					});

					var loclabel11=Ti.UI.createLabel({

						textAlign:'center',
						backgroundColor: 'transparent',
						width:'500px',
						text: '09.00-12.00',
						color:'white',
						height:'100px',
						font:{fontSize:25,fontFamily:'Helvetica Neue'},
						top:'25px'
					});

					var loclabel12=Ti.UI.createLabel({

						textAlign:'center',
						backgroundColor: 'transparent',
						width:'500px',
						text: text,
						color:'white',
						height:'100px',
						font:{fontSize:25,fontFamily:'Helvetica Neue'},
						bottom:'25px'
					});

					bg = '#7D736C';
					text = "Empty (Click to fill)";

					if (locat.block1.length > 0)
					{
						bg = '#FD9627';
						text = locat.block1;
					}

					var locview2= Ti.UI.createView({

						backgroundColor: bg,
						borderRadius:15,
						borderWidth:5,
						width:'500px',
						top:'75%',
						height:'250px'

					});

					var loclabel21=Ti.UI.createLabel({

						textAlign:'center',
						backgroundColor: 'transparent',
						width:'500px',
						text: '15.00-18.00',
						color:'white',
						height:'100px',
						font:{fontSize:25,fontFamily:'Helvetica Neue'},
						top:'25px'
					});

					var loclabel22=Ti.UI.createLabel({

						textAlign:'center',
						backgroundColor: 'transparent',
						width:'500px',
						text: text,
						color:'white',
						height:'100px',
						font:{fontSize:25,fontFamily:'Helvetica Neue'},
						bottom:'25px'
					});
					////////////////////////////////
					locview1.add(loclabel11);
					locview1.add(loclabel12);

					locview2.add(loclabel21);
					locview2.add(loclabel22);
					locationWindow.add(locmap);
					locationWindow.add(loclabel0);
					locationWindow.add(locview1);
					locationWindow.add(locview2);
					locationWindow.open();

			    } else {
			        alert('Error:\n' +
			            ((e.error && e.message) || JSON.stringify(e)));
			    }
			});

        }

	});

	var llatitude = 0;
	var llongitude = 0;

	mapview.addEventListener('regionchanged',function(evt){
	    llatitude = evt.latitude.toPrecision(10);
	    llongitude = evt.longitude.toPrecision(10);
	});

    mainWindow.add(mapview);

    mainWindow.addEventListener('open', function(e){
		Cloud.Objects.query({
		    classname: 'Location'
		}, function (e) {
		    if (e.success) {
		        /*alert('Success:\n' +
		            'Count: ' + e.Location.length);*/
		        for (var i = 0; i < e.Location.length; i++) {
		            var loc = e.Location[i];
		            /*alert('id: ' + cars.id + '\n' +
		                'make: ' + car.make + '\n' +
		                'color: ' + car.color + '\n' +
		                'year: ' + car.year + '\n' +
		                'created_at: ' + car.created_at);*/
		            var temp = MapModule.createAnnotation({
					    latitude:loc.latitude,
					    longitude:loc.longitude,
					    title:loc.name,
					    pincolor:MapModule.ANNOTATION_ORANGE,
					    myid:loc.id // Custom property to uniquely identify this annotation.
					});
					mapview.addAnnotation(temp);
		        }
		    } else {
		        alert('Error:\n' +
		            ((e.error && e.message) || JSON.stringify(e)));
		    }
		});
	});

    var addButton = Ti.UI.createButton({
    	width: '120px',
    	height: '120px',
    	borderRadius: '60px',
    	title: '+',
    	bottom: '30px',
    	backgroundColor: '#FD9627',
    	font:{fontSize:40,fontFamily:'Helvetica Neue'},
    });
    addButton.addEventListener('click',function(){

	   	addButton.bottom = -200 + 'px';

	   	var locationNameField = Ti.UI.createTextField({
	   		top: '10px',
	   		height: '100px',
	   		width: '90%',
	   		color: '#000',
	   		backgroundColor: 'white',
	   		borderColor: '#FD9627',
	   		borderRadius: 15,
	   		borderWidth: 5,
	   		hintText: 'Enter a name for location...'
	   	});

	   	var okButton = Ti.UI.createButton({
	   		top: '120px',
	   		width: '250px',
	   		height: '100px',
	   		color: 'white',
	   		borderRadius: 15,
	   		borderWidth: 5,
	   		backgroundColor: '#FD9627',
	   		font:{fontSize:20,fontFamily:'Helvetica Neue'},
	   		title: 'OK'
	   	});

	   	okButton.addEventListener('click',function(){

		   	var lname = locationNameField.value;

		   	locationNameField.hide();
		   	okButton.hide();

		   	//var coordinate = calculateLatLngfromPixels(mapview, e.x, e.y);
		    //var llongitude = coordinate.lat;
		    //var llatitude = coordinate.lat;

		    alert(llatitude + " + " + llongitude);

		    //var Cloud = require('ti.cloud');
			//Cloud.debug = true;

		    Cloud.Objects.create({
			    classname: 'Location',
			    fields: {
			        latitude: llatitude,
			        longitude: llongitude,
			        name: lname
			    }
			}, function (e) {
			    if (e.success) {
			        //var car = e.cars[0];
			        alert('Success!');
			    } else {
			        alert('Error:\n' +
			            ((e.error && e.message) || JSON.stringify(e)));
			    }
			});

		});
		mainWindow.add(locationNameField);
		mainWindow.add(okButton);

	});
    mainWindow.add(addButton);
});

//Ti.include('main.js');

if (Ti.App.Properties.hasProperty('isLogged') && Ti.App.Properties.getBool('isLogged'))
{
	mainWindow.open();
}
else
{
	Ti.include('login.js');
}

//Ti.include('location.js');

<commit_msg>click buttonu yapilacak<commit_after>// this sets the background color of the master UIView (when there are no windows/tab groups on it)
Titanium.UI.setBackgroundColor('#FD9627');

var Cloud = require('ti.cloud');
Cloud.debug = true;

/* MAIN WINDOW */

var mainWindow = Ti.UI.createWindow({
	title: 'Pati Dostlari'
});

var MapModule = require('ti.map');

var rc = MapModule.isGooglePlayServicesAvailable();
switch (rc) {
    case MapModule.SUCCESS:
        Ti.API.info('Google Play services is installed.');
        break;
    case MapModule.SERVICE_MISSING:
        alert('Google Play services is missing. Please install Google Play services from the Google Play store.');
        break;
    case MapModule.SERVICE_VERSION_UPDATE_REQUIRED:
        alert('Google Play services is out of date. Please update Google Play services.');
        break;
    case MapModule.SERVICE_DISABLED:
        alert('Google Play services is disabled. Please enable Google Play services.');
        break;
    case MapModule.SERVICE_INVALID:
        alert('Google Play services cannot be authenticated. Reinstall Google Play services.');
        break;
    default:
        alert('Unknown error.');
        break;
}

var calculateLatLngfromPixels = function(mapview, xPixels, yPixels) {

    var region = mapview.actualRegion || mapview.region;
    var widthInPixels = mapview.rect.width;
    var heightInPixels = mapview.rect.height;

    // should invert because of the pixel reference frame
    heightDegPerPixel = -region.latitudeDelta / heightInPixels;
    widthDegPerPixel = region.longitudeDelta / widthInPixels;

    return {
        lat : (yPixels - heightInPixels / 2) * heightDegPerPixel + region.latitude,
        lon : (xPixels - widthInPixels / 2) * widthDegPerPixel + region.longitude

    };
};

Titanium.Geolocation.getCurrentPosition(function(e)
{
    if (e.error)
    {
        alert('HFL cannot get your current location');
        return;
    }

    var longitude = e.coords.longitude;
    var latitude = e.coords.latitude;
    var altitude = e.coords.altitude;
    var heading = e.coords.heading;
    var accuracy = e.coords.accuracy;
    var speed = e.coords.speed;
    var timestamp = e.coords.timestamp;
    var altitudeAccuracy = e.coords.altitudeAccuracy;

    var mapview = MapModule.createView({
		mapType: MapModule.NORMAL_TYPE,
		userLocation: true,
		animate: true,
		width: '100%',
		height: '100%',
		region: {latitude: latitude, longitude: longitude, latitudeDelta: 0.1, longitudeDelta: 0.1 }
	});

	mapview.addEventListener('click', function(evt)
    {
        // get event properties
        var annotation = evt.annotation; //get the Myid from annotation

        Ti.API.info("LAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA: " + annotation);

        /*var clicksource = evt.clicksource;

        if (clicksource='leftButton'){  //leftButton event
            alert("leftButton of " + annotation + " has been clicked.");
        }
        if (clicksource='title'){   //title event
            alert("title of " + annotation + " has been clicked.");
        }*/
       if (clicksource='title'){
	       var eventid = annotation.myid;

	       Cloud.Objects.show({
			    classname: 'Location',
			    id: eventid
			}, function (e) {
			    if (e.success) {

			        var locat = e.Location[0];

			        var locationWindow = Ti.UI.createWindow({
						backgroundColor:'#FD9627',
						title: 'Location'
					});

					var annot = MapModule.createAnnotation({
					    latitude:locat.latitude,
					    longitude:locat.longitude,
					    title:locat.name,
					    pincolor:MapModule.ANNOTATION_ORANGE
					});

					var annots = [];
					annots.push(annot);

					var locmap = MapModule.createView({
						top: 0,
						left: 0,
						height: '35%',
						width: '100%',

						mapType: MapModule.NORMAL_TYPE,
						userLocation: true,
						animate: true,

						region: {latitude: locat.latitude, longitude: locat.longitude, latitudeDelta: 0.1, longitudeDelta: 0.1 },
						annotations: annots
					});

					var loclabel0=Ti.UI.createLabel({

						textAlign:'center',
						backgroundColor: 'white',
						width:'350px',
						text: locat.name,
						color:'#FD9627',
						height:'70px',
						font:{fontSize:15,fontFamily:'Helvetica Neue'},
						top:'40%',
						borderRadius:15,
						borderWidth:5
					});

					var bg = 'white';
					var text = "Empty (Click to fill)";
					var textcolor= '#FD9627';

					if (locat.block0.length > 0)
					{
						bg = '#FD9627';
						text = locat.block0;
						textcolor= 'white';
					}

					var locview1= Ti.UI.createView({

						backgroundColor: bg,
						borderRadius:15,
						borderWidth:5,
						borderColor:'white',
						width:'500px',
						top:'50%',
						//text: '09.00-12.00',
						height:'250px'

					});

					var loclabel11=Ti.UI.createLabel({

						textAlign:'center',
						backgroundColor: 'transparent',
						width:'500px',
						text: '09.00-12.00',
						color: textcolor,
						height:'100px',
						font:{fontSize:25,fontFamily:'Helvetica Neue'},
						top:'25px'
					});

					var loclabel12=Ti.UI.createLabel({

						textAlign:'center',
						backgroundColor: 'transparent',
						width:'500px',
						text: text,
						color: textcolor,
						height:'100px',
						font:{fontSize:25,fontFamily:'Helvetica Neue'},
						bottom:'25px'
					});

					bg = 'white';
					text = "Empty (Click to fill)";
					textcolor= '#FD9627';

					if (locat.block1.length > 0)
					{
						bg = '#FD9627';
						text = locat.block1;
						textcolor= 'white';
					}

					var locview2= Ti.UI.createView({

						backgroundColor: bg,
						borderRadius:15,
						borderWidth:5,
						borderColor:'white',
						width:'500px',
						top:'75%',
						height:'250px'

					});

					var loclabel21=Ti.UI.createLabel({

						textAlign:'center',
						backgroundColor: 'transparent',
						width:'500px',
						text: '15.00-18.00',
						color: textcolor,
						height:'100px',
						font:{fontSize:25,fontFamily:'Helvetica Neue'},
						top:'25px'
					});

					var loclabel22=Ti.UI.createLabel({

						textAlign:'center',
						backgroundColor: 'transparent',
						width:'500px',
						text: text,
						color: textcolor,
						height:'100px',
						font:{fontSize:25,fontFamily:'Helvetica Neue'},
						bottom:'25px'
					});
					////////////////////////////////
					locview1.add(loclabel11);
					locview1.add(loclabel12);

					locview2.add(loclabel21);
					locview2.add(loclabel22);
					locationWindow.add(locmap);
					locationWindow.add(loclabel0);
					locationWindow.add(locview1);
					locationWindow.add(locview2);
					locationWindow.open();

			    } else {
			        alert('Error:\n' +
			            ((e.error && e.message) || JSON.stringify(e)));
			    }
			});

        }

	});

	var llatitude = 0;
	var llongitude = 0;

	mapview.addEventListener('regionchanged',function(evt){
	    llatitude = evt.latitude.toPrecision(10);
	    llongitude = evt.longitude.toPrecision(10);
	});

    mainWindow.add(mapview);

    mainWindow.addEventListener('open', function(e){
		Cloud.Objects.query({
		    classname: 'Location'
		}, function (e) {
		    if (e.success) {
		        /*alert('Success:\n' +
		            'Count: ' + e.Location.length);*/
		        for (var i = 0; i < e.Location.length; i++) {
		            var loc = e.Location[i];
		            /*alert('id: ' + cars.id + '\n' +
		                'make: ' + car.make + '\n' +
		                'color: ' + car.color + '\n' +
		                'year: ' + car.year + '\n' +
		                'created_at: ' + car.created_at);*/
		            var temp = MapModule.createAnnotation({
					    latitude:loc.latitude,
					    longitude:loc.longitude,
					    title:loc.name,
					    pincolor:MapModule.ANNOTATION_ORANGE,
					    myid:loc.id // Custom property to uniquely identify this annotation.
					});
					mapview.addAnnotation(temp);
		        }
		    } else {
		        alert('Error:\n' +
		            ((e.error && e.message) || JSON.stringify(e)));
		    }
		});
	});

    var addButton = Ti.UI.createButton({
    	width: '120px',
    	height: '120px',
    	borderRadius: '60px',
    	title: '+',
    	bottom: '30px',
    	backgroundColor: '#FD9627',
    	font:{fontSize:40,fontFamily:'Helvetica Neue'},
    });
    addButton.addEventListener('click',function(){

	   	addButton.bottom = -200 + 'px';

	   	var locationNameField = Ti.UI.createTextField({
	   		top: '10px',
	   		height: '100px',
	   		width: '90%',
	   		color: '#000',
	   		backgroundColor: 'white',
	   		borderColor: '#FD9627',
	   		borderRadius: 15,
	   		borderWidth: 5,
	   		hintText: 'Enter a name for location...'
	   	});

	   	var okButton = Ti.UI.createButton({
	   		top: '120px',
	   		width: '250px',
	   		height: '100px',
	   		color: 'white',
	   		borderRadius: 15,
	   		borderWidth: 5,
	   		backgroundColor: '#FD9627',
	   		font:{fontSize:20,fontFamily:'Helvetica Neue'},
	   		title: 'OK'
	   	});

	   	okButton.addEventListener('click',function(){

		   	var lname = locationNameField.value;

		   	locationNameField.hide();
		   	okButton.hide();

		   	//var coordinate = calculateLatLngfromPixels(mapview, e.x, e.y);
		    //var llongitude = coordinate.lat;
		    //var llatitude = coordinate.lat;

		    alert(llatitude + " + " + llongitude);

		    //var Cloud = require('ti.cloud');
			//Cloud.debug = true;

		    Cloud.Objects.create({
			    classname: 'Location',
			    fields: {
			        latitude: llatitude,
			        longitude: llongitude,
			        name: lname
			    }
			}, function (e) {
			    if (e.success) {
			        //var car = e.cars[0];
			        alert('Success!');
			    } else {
			        alert('Error:\n' +
			            ((e.error && e.message) || JSON.stringify(e)));
			    }
			});

		});
		mainWindow.add(locationNameField);
		mainWindow.add(okButton);

	});
    mainWindow.add(addButton);
});

//Ti.include('main.js');

if (Ti.App.Properties.hasProperty('isLogged') && Ti.App.Properties.getBool('isLogged'))
{
	mainWindow.open();
}
else
{
	Ti.include('login.js');
}

//Ti.include('location.js');

<|endoftext|>


<commit_before>// this sets the background color of the master UIView (when there are no windows/tab groups on it)
Titanium.UI.setBackgroundColor('#000');

// create tab group
var tabGroup = Titanium.UI.createTabGroup();

//
// create base UI tab and root window
//
var win1 = Titanium.UI.createWindow({
    title:'Tab 1',
    backgroundColor:'#fff'
});
var tab1 = Titanium.UI.createTab({
    icon:'KS_nav_views.png',
    title:'Tab 1',
    window:win1
});

var label1 = Titanium.UI.createLabel({
	color:'#999',
	text:'I am Window 1',
	font:{fontSize:20,fontFamily:'Helvetica Neue'},
	textAlign:'center',
	width:'auto'
});

win1.add(label1);

label1.addEventListener('click',function(){

	Ti.Platform.openURL('tel:9823724887');

});

//
// create controls tab and root window
//
var win2 = Titanium.UI.createWindow({
    title:'Tab 2',
    backgroundColor:'#fff'
});
var tab2 = Titanium.UI.createTab({
    icon:'KS_nav_ui.png',
    title:'Tab 2',
    window:win2
});

var label2 = Titanium.UI.createLabel({
	color:'#999',
	text:'I am Window 2',
	font:{fontSize:20,fontFamily:'Helvetica Neue'},
	textAlign:'center',
	width:'auto'
});

win2.add(label2);

//
//  add tabs
//
tabGroup.addTab(tab1);
tabGroup.addTab(tab2);

// open tab group
tabGroup.open();
<commit_msg>Master Change<commit_after>// this sets the background color of the master UIView (when there are no windows/tab groups on it)
Titanium.UI.setBackgroundColor('#000');

//THIS IS MASTER CHANGE

// create tab group
var tabGroup = Titanium.UI.createTabGroup();

//
// create base UI tab and root window
//
var win1 = Titanium.UI.createWindow({
    title:'Tab 1',
    backgroundColor:'#fff'
});
var tab1 = Titanium.UI.createTab({
    icon:'KS_nav_views.png',
    title:'Tab 1',
    window:win1
});

var label1 = Titanium.UI.createLabel({
	color:'#999',
	text:'I am Window 1',
	font:{fontSize:20,fontFamily:'Helvetica Neue'},
	textAlign:'center',
	width:'auto'
});

win1.add(label1);

label1.addEventListener('click',function(){

	Ti.Platform.openURL('tel:9823724887');

});

//
// create controls tab and root window
//
var win2 = Titanium.UI.createWindow({
    title:'Tab 2',
    backgroundColor:'#fff'
});
var tab2 = Titanium.UI.createTab({
    icon:'KS_nav_ui.png',
    title:'Tab 2',
    window:win2
});

var label2 = Titanium.UI.createLabel({
	color:'#999',
	text:'I am Window 2',
	font:{fontSize:20,fontFamily:'Helvetica Neue'},
	textAlign:'center',
	width:'auto'
});

win2.add(label2);

//
//  add tabs
//
tabGroup.addTab(tab1);
tabGroup.addTab(tab2);

// open tab group
tabGroup.open();
<|endoftext|>


<commit_before>//node modules
var events = require('events');
var util = require('util');

function RoundsEmitter(maxRounds){
  this._rounds = 0;
  this._turns = 0;
  this._roundsRemaining = maxRounds || 1;
  this._next = this.setup;

  events.EventEmitter.call(this);
}

util.inherits(RoundsEmitter, events.EventEmitter);

RoundsEmitter.prototype.next = function next(){
  if (this._roundsRemaining == 0){
    this.emit('gameOver');
  }else{
    this._next(arguments);
  }
}

RoundsEmitter.prototype.setup = function setup(){
  this._next = this.roundStart;
  this.emit('setup');
}

RoundsEmitter.prototype.roundStart = function roundStart(){
  this._rounds++;
  this._next = this.turnStart;
  this.emit('roundStart', this._rounds, arguments);
}

RoundsEmitter.prototype.roundEnd = function roundEnd(){
  this._roundsRemaining--;
  this._next = this.roundStart;
  this.emit('roundEnd', this._rounds, arguments);
}

RoundsEmitter.prototype.turnStart = function turnStart(){
  this._turns++;
  this._next = this.turnEnd;
  this.emit('turnStart', this._rounds, this._turns, arguments);
}

RoundsEmitter.prototype.turnEnd = function turnEnd(){
  this._next = this.roundEnd;
  this.emit('turnEnd', this._rounds, this._turns, arguments);
}

RoundsEmitter.prototype.gameOver = function gameOver(){
  this._next = gameOver;
  this.emit('gameOver');
}

RoundsEmitter.prototype.getTurns = function getTurns(){
  return this._turns;
}

RoundsEmitter.prototype.getRoundsRemaining = function getRoundsRemaining(){
  return this._roundsRemaining;
}

RoundsEmitter.prototype.getRoundsPlayed = function getRoundsPlayed(){
  return this._rounds;
}

RoundsEmitter.prototype.setMaxRounds = function setMaxRounds(maxRounds){
  this._roundsRemaining = maxRounds;
}

RoundsEmitter.prototype.setNext = function setNext(fn){
  if (fn === 'roundStart'){ this._next = this.roundStart; }
  else if (fn === 'roundEnd'){ this._next = this.roundEnd; }
  else if (fn === 'turnStart'){ this._next = this.turnStart; }
  else if (fn === 'turnEnd'){ this._next = this.turnEnd; }
  else if (fn === 'gameOver'){ this._next = this.gameOver; }
  else{
    this._next = fn;
  }
}

module.exports = RoundsEmitter;<commit_msg>simpler transmission of arguments through events<commit_after>//node modules
var events = require('events');
var util = require('util');

function RoundsEmitter(maxRounds){
  this._rounds = 0;
  this._turns = 0;
  this._roundsRemaining = maxRounds || 1;
  this._next = this.setup;

  events.EventEmitter.call(this);
}

util.inherits(RoundsEmitter, events.EventEmitter);

RoundsEmitter.prototype.next = function next(){
  if (this._roundsRemaining == 0){
    this.emit('gameOver');
  }else{
    var args = Array.prototype.slice.call(arguments);
    this._next(args);
  }
}

RoundsEmitter.prototype.setup = function setup(){
  this._next = this.roundStart;
  this.emit('setup');
}

RoundsEmitter.prototype.roundStart = function roundStart(args){
  this._rounds++;
  this._next = this.turnStart;
  this.emit('roundStart', this._rounds, args);
}

RoundsEmitter.prototype.roundEnd = function roundEnd(args){
  this._roundsRemaining--;
  this._next = this.roundStart;
  this.emit('roundEnd', this._rounds, args);
}

RoundsEmitter.prototype.turnStart = function turnStart(args){
  this._turns++;
  this._next = this.turnEnd;
  this.emit('turnStart', this._rounds, this._turns, args);
}

RoundsEmitter.prototype.turnEnd = function turnEnd(args){
  this._next = this.roundEnd;
  this.emit('turnEnd', this._rounds, this._turns, args);
}

RoundsEmitter.prototype.gameOver = function gameOver(){
  this._next = gameOver;
  this.emit('gameOver');
}

RoundsEmitter.prototype.getTurns = function getTurns(){
  return this._turns;
}

RoundsEmitter.prototype.getRoundsRemaining = function getRoundsRemaining(){
  return this._roundsRemaining;
}

RoundsEmitter.prototype.getRoundsPlayed = function getRoundsPlayed(){
  return this._rounds;
}

RoundsEmitter.prototype.setMaxRounds = function setMaxRounds(maxRounds){
  this._roundsRemaining = maxRounds;
}

RoundsEmitter.prototype.setNext = function setNext(fn){
  if (fn === 'roundStart'){ this._next = this.roundStart; }
  else if (fn === 'roundEnd'){ this._next = this.roundEnd; }
  else if (fn === 'turnStart'){ this._next = this.turnStart; }
  else if (fn === 'turnEnd'){ this._next = this.turnEnd; }
  else if (fn === 'gameOver'){ this._next = this.gameOver; }
  else{
    this._next = fn;
  }
}

module.exports = RoundsEmitter;<|endoftext|>


<commit_before>var express = require('express');
var weatherApp = express();
var weatherService = require('./lib/weatherService');
var config = require('./config');

weatherApp.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

weatherApp.get('/byZip/:zipCode',(req,res)=>{

    var service = new weatherService(config);

    if (isValidUSZip(req.params.zipCode)){
        //fetch weather data using provided zipcode
        var currentWeather = service.getCurrentConditionsForZipCode(req.params.zipCode)
            .then(conditionsResult=>res.json(conditionsResult))
            .catch(err=>res.sendStatus(404).json(err));
    }
    else{
        res.status(404).json({errorCode: 1, message:"Invalid zipcode provided."});
    }

});

function isValidUSZip(zipCode) {
   return /^\d{5}(-\d{4})?$/.test(zipCode);
}

weatherApp.listen(3000, function () {
  console.log('Weather app listening on port 3000!')
})<commit_msg>send json errors from promise reject op<commit_after>var express = require('express');
var weatherApp = express();
var weatherService = require('./lib/weatherService');
var config = require('./config');

weatherApp.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

weatherApp.get('/byZip/:zipCode',(req,res)=>{

    var service = new weatherService(config);

    if (isValidUSZip(req.params.zipCode)){
        //fetch weather data using provided zipcode
        var currentWeather = service.getCurrentConditionsForZipCode(req.params.zipCode)
            .then(
                conditionsResult=>res.json(conditionsResult),
                err=>res.status(404).json(err)
            )
            .catch(err=>res.status(404).json(err));
    }
    else{
        res.status(404).json({errorCode: 1, message:"Invalid zipcode provided."});
    }

});

function isValidUSZip(zipCode) {
   return /^\d{5}(-\d{4})?$/.test(zipCode);
}

weatherApp.listen(3000, function () {
  console.log('Weather app listening on port 3000!')
})<|endoftext|>


<commit_before>"use strict"
let NodeStream = require('stream')
let Path = require('path')
let FS = require('fs')
class Plugin{
  static Initialize(){
    this.Tags = new Map()
    this.Tags.set('Compiler-Output', function(Name, Value, Buffer, Options){
      Options.Output = Path.resolve(Path.dirname(Options.File.Path), Value)
    })
    this.Tags.set('Compiler-Include', function(Name, Value, Buffer, Options){
      return new Promise(function(Resolve){
        FS.readFile(Path.resolve(Path.dirname(Options.File.Path), Value), function(_, Contents){
          Resolve(Contents || ' ')
        })
      })
    })
    this.Info = {
      Name: "Plugin",
      Priority: 1,
      Extensions: []
    }
  }
  static Stream(Options){
    let Me = this
    var Stream = new NodeStream.Transform({
      objectMode: true,
      transform: function (Buffer, Encoding, Callback) {
        new Promise(function (Resolve) {
          Resolve(Me.Process(Buffer.toString("utf8"), Options))
        }).then(function(Contents){
            Stream.push(Contents)
            Callback()
          }, function(e){
            Stream.emit('error', e)
          })
      }
    })
    return Stream
  }
  static ProcessTags(CommentToken, Buffer, Options){
    let Regex = new RegExp(' *' + CommentToken.replace('//', '\\/\\/') + ' @([\\w-]+) "(.+)"', 'g')
    let Results = []
    let Sequence = Promise.resolve()
    for(let Result; (Result = Regex.exec(Buffer)) !== null;){
      let Value
      if(this.Tags.has(Result[1])){
        Value = this.Tags.get(Result[1])(Result[1], Result[2], Buffer, Options) || ''
      } else Value = Result[0]
      Sequence = Sequence.then(function(){
        if(Value && Value.constructor.name === 'Promise'){
          return Value.then(function(Value){
            Results.push(Value)
          })
        } else Results.push(Value)
      })
    }
    return Sequence.then(function(){
      let Regex = new RegExp(' *' + CommentToken.replace('//', '\\/\\/') + ' @([\\w-]+) "(.+)"', 'g')
      return Buffer.replace(Regex, function(){
        return Results.shift()
      })
    })
  }
  static Validate(Options){
    return this.Info.Extensions.indexOf(Options.File.Extension) !== -1
  }
  static Register(UCompiler){
    UCompiler.Plugins.add(this)
  }
}

module.exports = Plugin<commit_msg>:art: Run all tags in parallel<commit_after>"use strict"
let NodeStream = require('stream')
let Path = require('path')
let FS = require('fs')
class Plugin{
  static Initialize(){
    this.Tags = new Map()
    this.Tags.set('Compiler-Output', function(Name, Value, Buffer, Options){
      Options.Output = Path.resolve(Path.dirname(Options.File.Path), Value)
    })
    this.Tags.set('Compiler-Include', function(Name, Value, Buffer, Options){
      return new Promise(function(Resolve){
        FS.readFile(Path.resolve(Path.dirname(Options.File.Path), Value), function(_, Contents){
          Resolve(Contents || ' ')
        })
      })
    })
    this.Info = {
      Name: "Plugin",
      Priority: 1,
      Extensions: []
    }
  }
  static Stream(Options){
    let Me = this
    var Stream = new NodeStream.Transform({
      objectMode: true,
      transform: function (Buffer, Encoding, Callback) {
        new Promise(function (Resolve) {
          Resolve(Me.Process(Buffer.toString("utf8"), Options))
        }).then(function(Contents){
            Stream.push(Contents)
            Callback()
          }, function(e){
            Stream.emit('error', e)
          })
      }
    })
    return Stream
  }
  static ProcessTags(CommentToken, Buffer, Options){
    let Regex = new RegExp(' *' + CommentToken.replace('//', '\\/\\/') + ' @([\\w-]+) "(.+)"', 'g')
    let Promises = []
    for(let Result; (Result = Regex.exec(Buffer)) !== null;){
      let Value
      if(this.Tags.has(Result[1])){
        Value = this.Tags.get(Result[1])(Result[1], Result[2], Buffer, Options) || ''
      } else Value = Result[0]
      Promises.push(Value)
    }
    return Promise.all(Promises).then(function(Results){
      let Regex = new RegExp(' *' + CommentToken.replace('//', '\\/\\/') + ' @([\\w-]+) "(.+)"', 'g')
      return Buffer.replace(Regex, function(){
        return Results.shift()
      })
    })
  }
  static Validate(Options){
    return this.Info.Extensions.indexOf(Options.File.Extension) !== -1
  }
  static Register(UCompiler){
    UCompiler.Plugins.add(this)
  }
}

module.exports = Plugin<|endoftext|>


<commit_before>'use strict';

var SAF = SAF || {};

SAF.StringBuilder = function () {
    var items = [];

    this.append = function (value) {
        if (value || value === 0) {
            items.push(value);
        }
        return this;
    };

    this.appendLine = function (value) {
        if (value || value === 0) {
            items.push(value + '\n');
        }
        return this;
    };

    this.appendFormat = function () {
        var value = arguments[0];

        for (var i = 0; i < arguments.length; i++) {
            if (value || value === 0) {
                value = value.replace('{' + (i - 1) + '}', arguments[i]);
            }
        }

        items.push(value);

        return this;
    };

    this.remove = function (value) {
        if (value || value === 0) {
            var args = arguments;
            var ax;

            while ((ax = items.indexOf(value)) !== -1) {
                items.splice(ax, 1);
            }
        }

        return this;
    };

    this.removeLine = function (value) {
        if (value || value === 0) {
            var ax;
            var target = value + '\n';

            while ((ax = items.indexOf(target)) !== -1) {
                items.splice(ax, 1);
            }
        }

        return this;
    };

    this.clear = function () {
        while (items.length > 0) {
            items.pop();
        }
        //items.splice(0, items.length);
        return this;
    };

    /**
     * @return {string}
     */
    this.toString = function () {
        if (items.length > 0) {
            return items.join('');
        }
        return '';
    };

    /**
     * @return {string}
     */
    this.toString2 = function () {
        var result = '';

        for (i = 0; i < items.length; i++) {
            result += items[i];
        }

        return result;
    };
};

/**
 * @return {string}
 */
SAF.StringBuilder.prototype.version = function () {
    return '1.0';
};
<commit_msg>minor tweaks<commit_after>var SAF = SAF || {};

SAF.StringBuilder = function () {
    'use strict';

    var items = [];

    this.append = function (value) {
        if (value || value === 0) {
            items.push(value);
        }
        return this;
    };

    this.appendLine = function (value) {
        if (value || value === 0) {
            items.push(value + '\n');
        }
        return this;
    };

    this.appendFormat = function () {
        var value = arguments[0];

        for (var i = 0; i < arguments.length; i++) {
            if (value || value === 0) {
                value = value.replace('{' + (i - 1) + '}', arguments[i]);
            }
        }

        items.push(value);

        return this;
    };

    this.remove = function (value) {
        if (value || value === 0) {
            var args = arguments;
            var ax;

            while ((ax = items.indexOf(value)) !== -1) {
                items.splice(ax, 1);
            }
        }

        return this;
    };

    this.removeLine = function (value) {
        if (value || value === 0) {
            var ax;
            var target = value + '\n';

            while ((ax = items.indexOf(target)) !== -1) {
                items.splice(ax, 1);
            }
        }

        return this;
    };

    this.clear = function () {
        while (items.length > 0) {
            items.pop();
        }
        //items.splice(0, items.length);
        return this;
    };

    /**
     * @return {string}
     */
    this.toString = function () {
        if (items.length > 0) {
            return items.join('');
        }
        return '';
    };

    /**
     * @return {string}
     */
    this.toString2 = function () {
        var result = '';

        for (var i = 0; i < items.length; i++) {
            result += items[i];
        }

        return result;
    };
};

/**
 * @return {string}
 */
SAF.StringBuilder.prototype.version = function () {
    'use strict';
    return '1.0';
};
<|endoftext|>


<commit_before>const path = require('path');
const Discord = require('discord.js');
const Settings = require('./settings.json');
const Tokens = require('./tokens.json');

class TheAwesomeBot {
  constructor(token, discordOpt) {
    this.token = token;
    this.client = new Discord.Client(discordOpt || { autoReconnect: true });
    this.settings = Settings;
    this.settings.tokens = Tokens; // insert tokens into our settings obj
    this.commands = {};
    this.usageList = '';

    // store the RE as they're expensive to create
    this.cmd_re = new RegExp(`^${this.settings.bot_cmd}\\s+([^\\s]+)\\s*([^]*)\\s*`, 'i');
  }

  onMessage() {
    return (message) => {
      // don't respond to own messages
      if (this.client.user.username === message.author.username) {
        return;
      }

      // check if message is a command
      const cmdMatch = message.cleanContent.match(this.cmd_re);

      // not a known command
      if (!cmdMatch || Object.keys(this.commands).indexOf(cmdMatch[1]) === -1) {
        if (message.content.match(new RegExp(`^${this.settings.bot_cmd}[\\s]*( .*)?$`, 'i'))) {
          let helpText = 'maybe try these valid commands? *kthnxbye!*\n\n```';
          helpText += this.usageList;
          helpText += '```';
          message.channel.sendMessage(helpText);
        }
        return;
      }

      // process commands
      const cmd = cmdMatch[1];
      const cmdArgs = cmdMatch[2].trim();

      let showUsage;

      try {
        showUsage = this.commands[cmd].run(this, message, cmdArgs);
      } catch (err) {
        message.channel.sendMessage('There was an error running the command:\n' +
          '```\n' + err.toString() + '\n```');
        console.error(err);
        console.error(err.stack);
      }

      if (showUsage === true) {
        let usage = this.commands[cmd].usage;
        if (typeof usage !== 'string') {
          usage = usage.join('\n');
        }
        message.channel.sendMessage('```\n' + usage + '\n```');
      }
    };
  }

  onReady() {
    return (() => {
      console.log('\nConnected to discord server!');
      console.log('Running initializations...');
      Object.keys(this.commands).filter(cmd =>
        typeof this.commands[cmd].init === 'function')
      .forEach(cmd => this.commands[cmd].init(this));
    });
  }

  serverNewMember() {
    return ((server, user) => this.client.sendMessage(user, this.usageList));
  }

  static onDisconnected() {
    return () =>
      console.warn('Bot has been disconnected from server...');
  }

  static onError() {
    return ((err) => {
      console.error('error: ', err);
      console.error(err.trace);
    });
  }

  loadCommands(cmdList) {
    this.usageList = '';
    cmdList.forEach((cmd) => {
      const fullpath = path.join(__dirname, 'commands', cmd, `${cmd}.js`);
      const script = require(fullpath); // eslint-disable-line global-require, import/no-dynamic-require
      this.commands[cmd] = script;

      const usageObj = script.usage;
      if (usageObj) {
        const usageStrs = [];
        if (Array.isArray(usageObj)) {
          usageObj.forEach(u => usageStrs.push(u));
        } else {
          usageStrs.push(usageObj.toString());
        }

        usageStrs.forEach(u => (this.usageList += `\n- ${this.settings.bot_cmd} ${u}`));
      }
    });
  }

  init() {
    // load commands
    console.log('Loading commands...');
    this.loadCommands(this.settings.commands);

    // setup events
    console.log('Setting up event bindings...');
    this.client
      .on('ready', this.onReady())
      .on('serverNewMember', this.serverNewMember())
      .on('message', this.onMessage())
      .on('error', this.onError());

    console.log('Connecting...');
    this.client.login(this.token);
  }

  isAdminOrMod(member) {
    const immuneRoles = new Set(this.settings.voting.immuneRoles);
    const userRoles = new Set(member.roles.array().map(r => r.name));
    const setIntersection = [...userRoles].filter(r => immuneRoles.has(r));
    return setIntersection.length > 0;
  }
}

module.exports = TheAwesomeBot;

<commit_msg>Fix this.onDisconnected and this.onError<commit_after>/* eslint-disable class-methods-use-this */
const path = require('path');
const Discord = require('discord.js');
const Settings = require('./settings.json');
const Tokens = require('./tokens.json');

class TheAwesomeBot {
  constructor(token, discordOpt) {
    this.token = token;
    this.client = new Discord.Client(discordOpt || { autoReconnect: true });
    this.settings = Settings;
    this.settings.tokens = Tokens; // insert tokens into our settings obj
    this.commands = {};
    this.usageList = '';

    // store the RE as they're expensive to create
    this.cmd_re = new RegExp(`^${this.settings.bot_cmd}\\s+([^\\s]+)\\s*([^]*)\\s*`, 'i');
  }

  onMessage() {
    return (message) => {
      // don't respond to own messages
      if (this.client.user.username === message.author.username) {
        return;
      }

      // check if message is a command
      const cmdMatch = message.cleanContent.match(this.cmd_re);

      // not a known command
      if (!cmdMatch || Object.keys(this.commands).indexOf(cmdMatch[1]) === -1) {
        if (message.content.match(new RegExp(`^${this.settings.bot_cmd}[\\s]*( .*)?$`, 'i'))) {
          let helpText = 'maybe try these valid commands? *kthnxbye!*\n\n```';
          helpText += this.usageList;
          helpText += '```';
          message.channel.sendMessage(helpText);
        }
        return;
      }

      // process commands
      const cmd = cmdMatch[1];
      const cmdArgs = cmdMatch[2].trim();

      let showUsage;

      try {
        showUsage = this.commands[cmd].run(this, message, cmdArgs);
      } catch (err) {
        message.channel.sendMessage('There was an error running the command:\n' +
          '```\n' + err.toString() + '\n```');
        console.error(err);
        console.error(err.stack);
      }

      if (showUsage === true) {
        let usage = this.commands[cmd].usage;
        if (typeof usage !== 'string') {
          usage = usage.join('\n');
        }
        message.channel.sendMessage('```\n' + usage + '\n```');
      }
    };
  }

  onReady() {
    return (() => {
      console.log('\nConnected to discord server!');
      console.log('Running initializations...');
      Object.keys(this.commands).filter(cmd =>
        typeof this.commands[cmd].init === 'function')
      .forEach(cmd => this.commands[cmd].init(this));
    });
  }

  serverNewMember() {
    return ((server, user) => this.client.sendMessage(user, this.usageList));
  }

  onDisconnected() {
    return () =>
      console.warn('Bot has been disconnected from server...');
  }

  onError() {
    return ((err) => {
      console.error('error: ', err);
      console.error(err.trace);
    });
  }

  loadCommands(cmdList) {
    this.usageList = '';
    cmdList.forEach((cmd) => {
      const fullpath = path.join(__dirname, 'commands', cmd, `${cmd}.js`);
      const script = require(fullpath); // eslint-disable-line global-require, import/no-dynamic-require
      this.commands[cmd] = script;

      const usageObj = script.usage;
      if (usageObj) {
        const usageStrs = [];
        if (Array.isArray(usageObj)) {
          usageObj.forEach(u => usageStrs.push(u));
        } else {
          usageStrs.push(usageObj.toString());
        }

        usageStrs.forEach(u => (this.usageList += `\n- ${this.settings.bot_cmd} ${u}`));
      }
    });
  }

  init() {
    // load commands
    console.log('Loading commands...');
    this.loadCommands(this.settings.commands);

    // setup events
    console.log('Setting up event bindings...');
    this.client
      .on('ready', this.onReady())
      .on('serverNewMember', this.serverNewMember())
      .on('message', this.onMessage())
      .on('error', this.onError());

    console.log('Connecting...');
    this.client.login(this.token);
  }

  isAdminOrMod(member) {
    const immuneRoles = new Set(this.settings.voting.immuneRoles);
    const userRoles = new Set(member.roles.array().map(r => r.name));
    const setIntersection = [...userRoles].filter(r => immuneRoles.has(r));
    return setIntersection.length > 0;
  }
}

module.exports = TheAwesomeBot;

<|endoftext|>


<commit_before>$(document).ready(function() {
  // nav
  // nav clase
  $(".nav a").on("click", function(){
   $(".nav").find(".active").removeClass("active");
   $(this).parent().addClass("active");
});
  // new
  $('.navbar-collapse a').click(function(){
    $(".navbar-collapse").collapse('hide');
});
  // end new
    $('nav').affix({
      offset: {
        top: function() { return  $('#imagen-inicial').height(); }
      }
     });

  $('a[href*="#"]:not([href="#"])').click(function(event) {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      if (this.hash !== "") {

          // Prevent default anchor click behavior
          event.preventDefault();

          // Store hash
          var hash = this.hash;

          // Using jQuery's animate() method to add smooth page scroll
          // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
          $('html, body').animate({
            scrollTop: $(hash).offset().top - 51
          }, 800, function(){

          // Add hash (#) to URL when done scrolling (default click behavior)
            window.location.hash = hash;
          });

        } // End if

      /*
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html, body').animate({
          scrollTop: target.offset().top - 51
        }, 300);
        return false;
      }
      */
    }
  });

  // Animación
  var $window           = $(window),
      win_height_padded = $window.height() * 1.1,
      isTouch           = Modernizr.touch;

  if (isTouch) { $('.revealOnScroll').addClass('animated'); }

  $window.on('scroll', revealOnScroll);

  function revealOnScroll() {
    var scrolled = $window.scrollTop(),
        win_height_padded = $window.height() * 1.1;

    // Showed...
    $(".revealOnScroll:not(.animated)").each(function () {
      var $this     = $(this),
          offsetTop = $this.offset().top;

      if (scrolled + win_height_padded > offsetTop) {
        if ($this.data('timeout')) {
          window.setTimeout(function(){
            $this.addClass('animated ' + $this.data('animation'));
          }, parseInt($this.data('timeout'),10));
        } else {
          $this.addClass('animated ' + $this.data('animation'));
        }
      }
    });
    // Hidden...
   $(".revealOnScroll.animated").each(function (index) {
      var $this     = $(this),
          offsetTop = $this.offset().top;
      if (scrolled + win_height_padded < offsetTop) {
        $(this).removeClass('animated fadeInUp flipInX lightSpeedIn')
      }
    });
  }

  revealOnScroll();

});
<commit_msg>Update script.js<commit_after>$(document).ready(function() {
  // nav
  // nav clase
  $(".nav a").on("click", function(){
   $(".nav").find(".active").removeClass("active");
   $(this).parent().addClass("active");
});
  // new
  $('.navbar-collapse a').click(function(){
    $(".navbar-collapse").collapse('hide');
});
  // end new
    $('nav').affix({
      offset: {
        top: function() { return  $('#imagen-inicial').height(); }
      }
     });

  $('a[href*="#"]:not([href="#"])').click(function(event) {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      if (this.hash !== "") {

          // Prevent default anchor click behavior
          event.preventDefault();

          // Store hash
          var hash = this.hash;

          // Using jQuery's animate() method to add smooth page scroll
          // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
        if ( $("nav").hasClass("affix")) {
          $('html, body').animate({
            scrollTop: $(hash).offset().top - 51
          }, 800, function(){

          // Add hash (#) to URL when done scrolling (default click behavior)
            window.location.hash = hash;
          });
      } else {
          $('html, body').animate({
            scrollTop: $(hash).offset().top - 120
          }, 800, function(){

          // Add hash (#) to URL when done scrolling (default click behavior)
            window.location.hash = hash;
          });
      }

        } // End if

      /*
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html, body').animate({
          scrollTop: target.offset().top - 51
        }, 300);
        return false;
      }
      */
    }
  });

  // Animación
  var $window           = $(window),
      win_height_padded = $window.height() * 1.1,
      isTouch           = Modernizr.touch;

  if (isTouch) { $('.revealOnScroll').addClass('animated'); }

  $window.on('scroll', revealOnScroll);

  function revealOnScroll() {
    var scrolled = $window.scrollTop(),
        win_height_padded = $window.height() * 1.1;

    // Showed...
    $(".revealOnScroll:not(.animated)").each(function () {
      var $this     = $(this),
          offsetTop = $this.offset().top;

      if (scrolled + win_height_padded > offsetTop) {
        if ($this.data('timeout')) {
          window.setTimeout(function(){
            $this.addClass('animated ' + $this.data('animation'));
          }, parseInt($this.data('timeout'),10));
        } else {
          $this.addClass('animated ' + $this.data('animation'));
        }
      }
    });
    // Hidden...
   $(".revealOnScroll.animated").each(function (index) {
      var $this     = $(this),
          offsetTop = $this.offset().top;
      if (scrolled + win_height_padded < offsetTop) {
        $(this).removeClass('animated fadeInUp flipInX lightSpeedIn')
      }
    });
  }

  revealOnScroll();

});
<|endoftext|>


<commit_before>jest.unmock('../lib/bot');

const Bot = require('../lib/bot');

describe('bot', () => {
  it('throws error when no configuration is provided', () => {
    expect(() => new Bot() ).toThrow();
  });

  it('throws error when no client is provided', () => {
    expect(() => new Bot({
      router: () => {}
    }) ).toThrow();
  });

  it('throws error when no router is provided', () => {
    expect(() => new Bot({
      client: {}
    })).toThrow();
  });

  it('starts context store when started', () => {

    var contextStore = {
      start: jest.fn()
    }

    var bot = new Bot({
      contextStore: contextStore,
      client: {},
      router: () => {}
    })

    bot.start()

    expect(contextStore.start).toBeCalled()
  });

  it('starts client when started', () => {

    var client = {
      start: jest.fn()
    }

    var bot = new Bot({
      client: client,
      router: () => {}
    })

    bot.start()

    expect(client.start).toBeCalled()
  });

  it('starts client when started after context store has started', () => {

    var client = {
      start: jest.fn()
    }

    var contextStore = {
      start: function(callback) {
        callback();
      }
    }

    var bot = new Bot({
      contextStore: contextStore,
      client: client,
      router: () => {}
    })

    bot.start()

    expect(client.start).toBeCalled()
  });
});
<commit_msg>Refactors to reduce repetition.<commit_after>jest.unmock('../lib/bot');

const Bot = require('../lib/bot');

const client = {
  start: jest.fn()
}

const router = jest.fn()

const contextStore = {
  start: jest.fn()
}

describe('bot', () => {
  it('throws error when no configuration is provided', () => {
    expect(() => new Bot()).toThrow();
  });

  it('throws error when no client is provided', () => {
    expect(() => new Bot({
      router: router
    })).toThrow();
  });

  it('throws error when no router is provided', () => {
    expect(() => new Bot({
      client: client
    })).toThrow();
  });

  it('starts context store when started', () => {

    var bot = new Bot({
      contextStore: contextStore,
      client: client,
      router: router
    })

    bot.start()

    expect(contextStore.start).toBeCalled()
  });

  it('starts client when started', () => {

    var bot = new Bot({
      client: client,
      router: router
    })

    bot.start()

    expect(client.start).toBeCalled()
  });

  it('starts client when started after context store has started', () => {

    var bot = new Bot({
      contextStore: contextStore,
      client: client,
      router: router
    })

    bot.start()

    expect(client.start).toBeCalled()
  });
});
<|endoftext|>


<commit_before>$(function () {
  console.log("directChat script done");

  // 메뉴 API
  var ajaxParamType = 'noneParam';
  var ajaxParam = '';
  var ajaxURL = '/api/rivalWar/directChat/getPaginatedChildNode.do?c_id=2&pageIndex=1&pageUnit=1&pageSize=10';
  var ajaxType = 'GET';
  var ajaxReturnType = 'json';

  function beforeSendCallback() {
    console.log("beforeSendCallback");
  }

  function successCallback(responseData) {
    directChatAjaxCall(responseData.result);
  }

  function errorCallback() {
    console.log("errorCallback");
  }

  function completeCallback() {
    console.log("completeCallback");
  }

  callAjax(ajaxParamType, ajaxParam, ajaxURL, ajaxType, ajaxReturnType, beforeSendCallback, successCallback, errorCallback, completeCallback);
});

function directChatAjaxCall(jsonData){
  $('#chat-messages').empty(); //패널(div)의 내용 초기화
  var table = "";
  $(jsonData).each(function (chatIndex, chatList){

    table += "
";

    table += "
";
    table += "
" + chatList.writeTime + "
";
    table += "    ";
    table += "      ";
    table += "    ";
    table += "
";
    table += "      ";
    table += "
";
    table += "
";

    table += "
";
    table += "    ";
    table += "
";
    table += "      " + chatList.userId + "";
    table += "
";
    table += "
" + chatList.contentsBody + "
";
    table += "
";
    table += "      " + chatList.hashTags + "";
    table += "
";
    table += "
";
    table += "      <button class='info-box-icon chat-type type-up'>";
    table += "        " + chatList.likeCount;
    table += "      </button>";
    table += "      <button class='info-box-icon chat-type type-down'>";
    table += "        " + chatList.hateCount;
    table += "      </button>";
    table += "      <button class='info-box-icon chat-type type-reply'>";
    table += "        " + "답글";
    table += "      </button>";
    table += "      <button class='info-box-icon chat-type type-reply'>";
    table += "        " + "신고";
    table += "      </button>";
    table += "
";

    replyChatAjaxCall(chatList, table);

    table += "
";
    table += "
";

  });
  $('#chat-messages').append(table); //패널에 추가하기
}

function replyChatAjaxCall(chatList, table){

  console.log("menu script done");

  // 메뉴 API
  var ajaxParamType = 'noneParam';
  var ajaxParam = '';
  var ajaxURL = '/api/rivalWar/directChat/getPaginatedChildNode.do?c_id=' + chatList.c_id + '&pageIndex=1&pageUnit=1&pageSize=100';
  var ajaxType = 'GET';
  var ajaxReturnType = 'json';

  function beforeSendCallback() {
    console.log("beforeSendCallback");
  }

  function successCallback(responseData) {

    table += "
";
    var collection = responseData.result;

    $(collection).each(function (replyIndex, replyList){

      table += "
";
      table += "
";
      table += "
";
      table += "        ";
      table += "          ";
      table += "        ";
      table += "        " + replyList.userId + "";
      table += "        " + replyList.writeTime + "";
      table += "
";
      table += "
" + replyList.contentsBody + "
";
      table += "
";
      table += "        <button class='info-box-icon chat-type type-up'>" + "좋아요" + replyList.likeCount + "</button>";
      table += "        <button class='info-box-icon chat-type type-reply'>" + "답글 달기" + "</button>";
      table += "
";
      table += "
";
      table += "
";

    });

    table += "
";

  }

  function errorCallback() {
    console.log("errorCallback");
  }

  function completeCallback() {
    console.log("completeCallback");
  }

  callAjax(ajaxParamType, ajaxParam, ajaxURL, ajaxType, ajaxReturnType, beforeSendCallback, successCallback, errorCallback, completeCallback);

}
<commit_msg>[BT] SP-488 #close #time 1h #comment 댓글 코드 fix. [RV] +review SR @admin<commit_after>$(function () {
  console.log("directChat script done");

  // 메뉴 API
  var ajaxParamType = 'noneParam';
  var ajaxParam = '';
  var ajaxURL = '/api/rivalWar/directChat/getPaginatedChildNode.do?c_id=2&pageIndex=1&pageUnit=1&pageSize=10';
  var ajaxType = 'GET';
  var ajaxReturnType = 'json';

  function beforeSendCallback() {
    console.log("beforeSendCallback");
  }

  function successCallback(responseData) {
    directChatAjaxCall(responseData.result);
  }

  function errorCallback() {
    console.log("errorCallback");
  }

  function completeCallback() {
    console.log("completeCallback");
  }

  callAjax(ajaxParamType, ajaxParam, ajaxURL, ajaxType, ajaxReturnType, beforeSendCallback, successCallback, errorCallback, completeCallback);
});

function directChatAjaxCall(jsonData){
  $('#chat-messages').empty(); //패널(div)의 내용 초기화
  var table = "";
  $(jsonData).each(function (chatIndex, chatList){

    table += "
";

    table += "
";
    table += "
" + chatList.writeTime + "
";
    table += "    ";
    table += "      ";
    table += "    ";
    table += "
";
    table += "      ";
    table += "
";
    table += "
";

    table += "
";
    table += "    ";
    table += "
";
    table += "      " + chatList.userId + "";
    table += "
";
    table += "
" + chatList.contentsBody + "
";
    table += "
";
    table += "      " + chatList.hashTags + "";
    table += "
";
    table += "
";
    table += "      <button class='info-box-icon chat-type type-up'>";
    table += "        " + chatList.likeCount;
    table += "      </button>";
    table += "      <button class='info-box-icon chat-type type-down'>";
    table += "        " + chatList.hateCount;
    table += "      </button>";
    table += "      <button class='info-box-icon chat-type type-reply'>";
    table += "        " + "답글";
    table += "      </button>";
    table += "      <button class='info-box-icon chat-type type-reply'>";
    table += "        " + "신고";
    table += "      </button>";
    table += "
";

    table += replyChatAjaxCall(chatList, table);

    table += "
";
    table += "
";

  });
  $('#chat-messages').append(table); //패널에 추가하기
}

function replyChatAjaxCall(chatList, table){

  console.log("replyChatAjaxCall script done");

  // 메뉴 API
  var ajaxParamType = 'noneParam';
  var ajaxParam = '';
  var ajaxURL = '/api/rivalWar/directChat/getPaginatedChildNode.do?c_id=' + chatList.c_id + '&pageIndex=1&pageUnit=1&pageSize=100';
  var ajaxType = 'GET';
  var ajaxReturnType = 'json';

  function beforeSendCallback() {
    console.log("beforeSendCallback");
  }

  function successCallback(responseData) {

    var collection = responseData.result;

    table += "
";
    $(collection).each(function (replyIndex, replyList){

      table += "
";
      table += "
";
      table += "
";
      table += "        ";
      table += "          ";
      table += "        ";
      table += "        " + replyList.userId + "";
      table += "        " + replyList.writeTime + "";
      table += "
";
      table += "
" + replyList.contentsBody + "
";
      table += "
";
      table += "        <button class='info-box-icon chat-type type-up'>" + "좋아요" + replyList.likeCount + "</button>";
      table += "        <button class='info-box-icon chat-type type-reply'>" + "답글 달기" + "</button>";
      table += "
";
      table += "
";
      table += "
";

    });
    table += "
";

  }

  function errorCallback() {
    console.log("errorCallback");
  }

  function completeCallback() {
    console.log("completeCallback");
  }

  callAjax(ajaxParamType, ajaxParam, ajaxURL, ajaxType, ajaxReturnType, beforeSendCallback, successCallback, errorCallback, completeCallback);
  return table;
}
<|endoftext|>