<commit_before>/**
 * Handle PMtables Data
 * @author Erik A. O. <erik@colosa.com>
 */

var newButton;
var editButton;
var deleteButton;
var importButton;
var backButton;

var store;
var cmodel;
var smodel;
var infoGrid;
var _fields;

Ext.onReady(function(){

  pageSize = 20; //parseInt(CONFIG.pageSize);

  newButton = new Ext.Action({
    text: _('ID_ADD_ROW'),
    iconCls: 'button_menu_ext ss_sprite ss_add',
    handler: NewPMTableRow
  });

  editButton = new Ext.Action({
    text: _('ID_EDIT'),
    iconCls: 'button_menu_ext ss_sprite  ss_pencil',
    handler: EditPMTableRow,
    disabled: true
  });

  deleteButton = new Ext.Action({
    text: _('ID_DELETE'),
    iconCls: 'button_menu_ext ss_sprite  ss_delete',
    handler: DeletePMTableRow,
    disabled: true
  });

  importButton = new Ext.Action({
    text: _('ID_IMPORT'),
    iconCls: 'silk-add',
    icon: '/images/import.gif',
    handler: ImportPMTableCSV
  });

  backButton = new Ext.Action({
    text: _('ID_BACK'),
    icon: '/images/back-icon.png',
    handler: BackPMList
  });

  contextMenu = new Ext.menu.Menu({
      items: [editButton, deleteButton]
  });

  //This loop loads columns and fields to store and column model
  _columns = new Array();
  _fields  = new Array();
  _idProperty = '__index__';

 //default generated id
  _columns.push({
    id: _idProperty,
    hidden: true
  });

  _fields.push({name: _idProperty});

  if (tableDef.FIELDS.length !== 0) {
    for (i in tableDef.FIELDS) {
      _columns.push({
        id: tableDef.FIELDS[i].FLD_NAME,
        header: tableDef.FIELDS[i].FLD_DESCRIPTION,
        dataIndex: tableDef.FIELDS[i].FLD_NAME,
        width: 40,
        editor:{
          xtype: 'textfield',
          allowBlank: true
        }
      });

      _fields.push({name: tableDef.FIELDS[i].FLD_NAME});

      if(_idProperty == '' && tableDef.FIELDS[i].FLD_KEY) {
        _idProperty = tableDef.FIELDS[i].FLD_NAME;
      }
    }
  }

 smodel = new Ext.grid.CheckboxSelectionModel({
     listeners:{
       selectionchange: function(sm){
         var count_rows = sm.getCount();
         switch(count_rows){
         case 0:
           editButton.disable();
           deleteButton.disable();
           break;
         case 1:
           editButton.enable();
           deleteButton.enable();
           break;
         default:
           editButton.disable();
           //deleteButton.disable();
           break;
         }
       }
     }
   });

   //row editor for table columns grid
  editor = new Ext.ux.grid.RowEditor({
      saveText: _("ID_UPDATE"),
      listeners: {
	    afteredit: {
	      fn:function(rowEditor, obj, data, rowIndex ){
		    if (data.phantom === true) {
			  store.reload(); // only if it is an insert
	    	}
	      }
	    }
      }
  });

  var proxy = new Ext.data.HttpProxy({
    //url: '../pmTablesProxy/getData?id=' + tableDef.ADD_TAB_UID
    api: {
      read   : '../pmTablesProxy/dataView?id=' + tableDef.ADD_TAB_UID,
      create : '../pmTablesProxy/dataCreate?id=' + tableDef.ADD_TAB_UID,
      update : '../pmTablesProxy/dataUpdate?id=' + tableDef.ADD_TAB_UID,
      destroy: '../pmTablesProxy/dataDestroy?id=' + tableDef.ADD_TAB_UID
    },
    baseParams : {id: tableDef.ADD_TAB_UID},
  })

  // The new DataWriter component.
  var writer = new Ext.data.JsonWriter({
      encode: true,
      writeAllFields: false
  });

  var reader = new Ext.data.JsonReader({
    root       : 'rows',
    idProperty : 'id',
    fields     : _fields,
    idProperty : _idProperty,
    totalProperty: 'count'
  })

  store = new Ext.data.Store({
    proxy : proxy,
    reader : reader,
    writer : writer, // <-- plug a DataWriter into the store just as you would a Reader
    autoSave: true // <-- false would delay executing create, update, destroy requests until specifically told to do so with some [save] buton.
  });

  /*Ext.data.DataProxy.addListener('write', function(proxy, action, result, res, rs) {
    PMExt.notify('UPDATE', 'the record was updated successfully.');
  });*/

  // load the store immeditately
  //store.load();

  //store.on('update', store._update, store);

  cmodel = new Ext.grid.ColumnModel({
    defaults: {
        width: 50,
        sortable: true
    },
    columns: _columns
  });

  storePageSize = new Ext.data.SimpleStore({
    fields: ['size'],
     data: [['20'],['30'],['40'],['50'],['100']],
     autoLoad: true
  });

  comboPageSize = new Ext.form.ComboBox({
    typeAhead     : false,
    mode          : 'local',
    triggerAction : 'all',
    store: storePageSize,
    valueField: 'size',
    displayField: 'size',
    width: 50,
    editable: false,
    listeners:{
      select: function(c,d,i){
        UpdatePageConfig(d.data['size']);
        bbarpaging.pageSize = parseInt(d.data['size']);
        bbarpaging.moveFirst();
      }
    }
  });

  comboPageSize.setValue(pageSize);

  bbarpaging = new Ext.PagingToolbar({
    pageSize: pageSize,
    store: store,
    displayInfo: true,
    displayMsg: _('ID_GRID_PAGE_DISPLAYING_ROWS_MESSAGE') + '    ',
    emptyMsg: _('ID_GRID_PAGE_NO_ROWS_MESSAGE'),
    items: ['-',_('ID_PAGE_SIZE')+':',comboPageSize]
  });

  infoGrid = new Ext.grid.GridPanel({
    region: 'center',
    layout: 'fit',
    id: 'infoGrid',
    height:1000,
    autoWidth : true,
    title : _('ID_PM_TABLE') + " : " + tableDef.ADD_TAB_NAME,
    stateful : true,
    stateId : 'grid',
    enableColumnResize: true,
    enableHdMenu: true,
    frame:false,
    columnLines: false,
    viewConfig: {
      forceFit:true
    },
    store: store,
    cm: cmodel,
    plugins: [editor],
    sm: smodel,
    tbar:[newButton,'-',editButton, deleteButton,'-',importButton,{xtype: 'tbfill' }, backButton],
    bbar: bbarpaging,
    /*listeners: {
      //rowdblclick: EditPMTableRow,
      render: function(){
          this.loadMask = new Ext.LoadMask(this.body, {msg:_('ID_LOADING_GRID')});
      }
    },*/
  });

  infoGrid.on('rowcontextmenu',
        function (grid, rowIndex, evt) {
            var sm = grid.getSelectionModel();
            sm.selectRow(rowIndex, sm.isSelected(rowIndex));
        },
        this
  );

  infoGrid.on('contextmenu', function(evt){evt.preventDefault();}, this);
  infoGrid.addListener('rowcontextmenu',onMessageContextMenu, this);

  infoGrid.store.load();

  viewport = new Ext.Viewport({
    layout: 'fit',
    autoScroll: false,
    items: [infoGrid]
  });
});

//Funtion Handles Context Menu Opening
onMessageContextMenu = function (grid, rowIndex, e) {
    e.stopEvent();
    var coords = e.getXY();
    contextMenu.showAt([coords[0], coords[1]]);
};

/////JS FUNCTIONS

//Capitalize String Function
capitalize = function(s){
  s = s.toLowerCase();
  return s.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
};

//Do Nothing Function
DoNothing = function(){};

//Load New PM Table Row Forms
var props = function(){};

NewPMTableRow = function(){
  var PMRow = infoGrid.getStore().recordType;
  //var meta = mapPMFieldType(records[i].data['FIELD_UID']);

  for(i=0; i<_fields.length; i++) {
    props.prototype[_fields[i].name] = '';
  }

  var row = new PMRow(new props);
  length = infoGrid.getStore().data.length;

  editor.stopEditing();
  store.insert(length, row);
  infoGrid.getView().refresh();
  infoGrid.getSelectionModel().selectRow(length);
  editor.startEditing(length);
};

//Load PM Table Edition Row Form
EditPMTableRow = function(){
  iGrid = Ext.getCmp('infoGrid');
  rowsSelected = iGrid.getSelectionModel().getSelections();
  var aRowsSeleted = (RetrieveRowsID(rowsSelected)).split(",") ;
  var aTablesPKF   = (TABLES.PKF).split(","); ;
  var sParam = '';
  for(var i=0;i<aTablesPKF.length; i++){
    sParam += '&' + aTablesPKF[i] + '=' + aRowsSeleted[i];
  }
  location.href = 'additionalTablesDataEdit?sUID='+TABLES.UID+sParam;
};

//Confirm PM Table Row Deletion Tasks
DeletePMTableRow = function(){

  PMExt.confirm(_('ID_CONFIRM'), _('ID_CONFIRM_REMOVE_FIELD'), function(){
    var records = Ext.getCmp('infoGrid').getSelectionModel().getSelections();
    Ext.each(records, Ext.getCmp('infoGrid').store.remove, Ext.getCmp('infoGrid').store);
  });

};

//Load Import PM Table From CSV Source
ImportPMTableCSV = function(){
  location.href = 'additionalTablesDataImportForm?sUID=' + TABLES.UID;
};

//Load PM Table List
BackPMList = function(){
  //location.href = 'additionalTablesList';
  history.back();
};

//Gets UIDs from a array of rows
RetrieveRowsID = function(rows){
  var arrAux = new Array();
  var arrPKF = new Array();
  arrPKF = TABLES.PKF.split(',');
  if(rows.length>0){
    var c = 0;
    for(var i=0; i<arrPKF.length; i++){
      arrAux[i] = rows[c].get(arrPKF[i]);
    }
  }
  return arrAux.join(',');
};

//Update Page Size Configuration
UpdatePageConfig = function(pageSize){
  Ext.Ajax.request({
  url: 'additionalTablesAjax',
  params: {action:'updatePageSizeData', size: pageSize}
  });
};<commit_msg>BUG 0000 PM tables - disabled data editing for Report tables<commit_after>/**
 * Handle PMtables Data
 * @author Erik A. O. <erik@colosa.com>
 */

var newButton;
var editButton;
var deleteButton;
var importButton;
var backButton;

var store;
var cmodel;
var smodel;
var infoGrid;
var _fields;
var isReport;

Ext.onReady(function(){

  pageSize = 20; //parseInt(CONFIG.pageSize);

  isReport = tableDef.PRO_UID ? true : false;

  newButton = new Ext.Action({
    text: _('ID_ADD_ROW'),
    iconCls: 'button_menu_ext ss_sprite ss_add',
    handler: NewPMTableRow
  });

  editButton = new Ext.Action({
    text: _('ID_EDIT'),
    iconCls: 'button_menu_ext ss_sprite  ss_pencil',
    handler: EditPMTableRow,
    disabled: true
  });

  deleteButton = new Ext.Action({
    text: _('ID_DELETE'),
    iconCls: 'button_menu_ext ss_sprite  ss_delete',
    handler: DeletePMTableRow,
    disabled: true
  });

  importButton = new Ext.Action({
    text: _('ID_IMPORT'),
    iconCls: 'silk-add',
    icon: '/images/import.gif',
    handler: ImportPMTableCSV
  });

  backButton = new Ext.Action({
    text: _('ID_BACK'),
    icon: '/images/back-icon.png',
    handler: BackPMList
  });

  contextMenu = new Ext.menu.Menu({
      items: [editButton, deleteButton]
  });

  //This loop loads columns and fields to store and column model
  _columns = new Array();
  _fields  = new Array();
  _idProperty = '__index__';

 //default generated id
  _columns.push({
    id: _idProperty,
    hidden: true
  });

  _fields.push({name: _idProperty});

  if (tableDef.FIELDS.length !== 0) {
    for (i in tableDef.FIELDS) {
      _columns.push({
        id: tableDef.FIELDS[i].FLD_NAME,
        header: tableDef.FIELDS[i].FLD_DESCRIPTION,
        dataIndex: tableDef.FIELDS[i].FLD_NAME,
        width: 40,
        editor:{
          xtype: 'textfield',
          allowBlank: true
        }
      });

      _fields.push({name: tableDef.FIELDS[i].FLD_NAME});

      if(_idProperty == '' && tableDef.FIELDS[i].FLD_KEY) {
        _idProperty = tableDef.FIELDS[i].FLD_NAME;
      }
    }
  }

 smodel = new Ext.grid.CheckboxSelectionModel({
     listeners:{
       selectionchange: function(sm){
         var count_rows = sm.getCount();
         switch(count_rows){
         case 0:
           editButton.disable();
           deleteButton.disable();
           break;
         case 1:
           if (!isReport) {
             editButton.enable();
           }
           deleteButton.enable();
           break;
         default:
           editButton.disable();
           //deleteButton.disable();
           break;
         }
       }
     }
   });

  //row editor for table columns grid
  if (!isReport) {
    editor = new Ext.ux.grid.RowEditor({
      saveText: _("ID_UPDATE"),
      listeners: {
  	    afteredit: {
  	      fn:function(rowEditor, obj, data, rowIndex ){
    		    if (data.phantom === true) {
    			  store.reload(); // only if it is an insert
    	    	}
  	      }
  	    }
      }
    });
  }

  var proxy = new Ext.data.HttpProxy({
    //url: '../pmTablesProxy/getData?id=' + tableDef.ADD_TAB_UID
    api: {
      read   : '../pmTablesProxy/dataView?id=' + tableDef.ADD_TAB_UID,
      create : '../pmTablesProxy/dataCreate?id=' + tableDef.ADD_TAB_UID,
      update : '../pmTablesProxy/dataUpdate?id=' + tableDef.ADD_TAB_UID,
      destroy: '../pmTablesProxy/dataDestroy?id=' + tableDef.ADD_TAB_UID
    },
    baseParams : {id: tableDef.ADD_TAB_UID},
  })

  // The new DataWriter component.
  var writer = new Ext.data.JsonWriter({
      encode: true,
      writeAllFields: false
  });

  var reader = new Ext.data.JsonReader({
    root       : 'rows',
    idProperty : 'id',
    fields     : _fields,
    idProperty : _idProperty,
    totalProperty: 'count'
  })

  store = new Ext.data.Store({
    proxy : proxy,
    reader : reader,
    writer : writer, // <-- plug a DataWriter into the store just as you would a Reader
    autoSave: true // <-- false would delay executing create, update, destroy requests until specifically told to do so with some [save] buton.
  });

  cmodel = new Ext.grid.ColumnModel({
    defaults: {
        width: 50,
        sortable: true
    },
    columns: _columns
  });

  storePageSize = new Ext.data.SimpleStore({
    fields: ['size'],
     data: [['20'],['30'],['40'],['50'],['100']],
     autoLoad: true
  });

  comboPageSize = new Ext.form.ComboBox({
    typeAhead     : false,
    mode          : 'local',
    triggerAction : 'all',
    store: storePageSize,
    valueField: 'size',
    displayField: 'size',
    width: 50,
    editable: false,
    listeners:{
      select: function(c,d,i){
        UpdatePageConfig(d.data['size']);
        bbarpaging.pageSize = parseInt(d.data['size']);
        bbarpaging.moveFirst();
      }
    }
  });

  comboPageSize.setValue(pageSize);

  bbarpaging = new Ext.PagingToolbar({
    pageSize: pageSize,
    store: store,
    displayInfo: true,
    displayMsg: _('ID_GRID_PAGE_DISPLAYING_ROWS_MESSAGE') + '    ',
    emptyMsg: _('ID_GRID_PAGE_NO_ROWS_MESSAGE'),
    items: ['-',_('ID_PAGE_SIZE')+':',comboPageSize]
  });

  infoGridConfig = {
    region: 'center',
    layout: 'fit',
    id: 'infoGrid',
    height:1000,
    autoWidth : true,
    title : _('ID_PM_TABLE') + " : " + tableDef.ADD_TAB_NAME,
    stateful : true,
    stateId : 'grid',
    enableColumnResize: true,
    enableHdMenu: true,
    frame:false,
    columnLines: false,
    viewConfig: {
      forceFit:true
    },
    store: store,
    cm: cmodel,
    sm: smodel,
    tbar:[newButton,'-',editButton, deleteButton,'-',importButton,{xtype: 'tbfill' }, backButton],
    bbar: bbarpaging
  }

  if (!isReport) {
    infoGridConfig.plugins = new Array();
    infoGridConfig.plugins.push(editor);
  }

  infoGrid = new Ext.grid.GridPanel(infoGridConfig);

  infoGrid.on('rowcontextmenu',
        function (grid, rowIndex, evt) {
            var sm = grid.getSelectionModel();
            sm.selectRow(rowIndex, sm.isSelected(rowIndex));
        },
        this
  );

  infoGrid.on('contextmenu', function(evt){evt.preventDefault();}, this);
  infoGrid.addListener('rowcontextmenu',onMessageContextMenu, this);

  infoGrid.store.load();

  viewport = new Ext.Viewport({
    layout: 'fit',
    autoScroll: false,
    items: [infoGrid]
  });
});

//Funtion Handles Context Menu Opening
onMessageContextMenu = function (grid, rowIndex, e) {
    e.stopEvent();
    var coords = e.getXY();
    contextMenu.showAt([coords[0], coords[1]]);
};

/////JS FUNCTIONS

//Capitalize String Function
capitalize = function(s){
  s = s.toLowerCase();
  return s.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
};

//Do Nothing Function
DoNothing = function(){};

//Load New PM Table Row Forms
var props = function(){};

NewPMTableRow = function(){
  var PMRow = infoGrid.getStore().recordType;
  //var meta = mapPMFieldType(records[i].data['FIELD_UID']);

  for(i=0; i<_fields.length; i++) {
    props.prototype[_fields[i].name] = '';
  }

  var row = new PMRow(new props);
  length = infoGrid.getStore().data.length;

  editor.stopEditing();
  store.insert(length, row);
  infoGrid.getView().refresh();
  infoGrid.getSelectionModel().selectRow(length);
  editor.startEditing(length);
};

//Load PM Table Edition Row Form
EditPMTableRow = function(){
  iGrid = Ext.getCmp('infoGrid');
  rowsSelected = iGrid.getSelectionModel().getSelections();
  var aRowsSeleted = (RetrieveRowsID(rowsSelected)).split(",") ;
  var aTablesPKF   = (TABLES.PKF).split(","); ;
  var sParam = '';
  for(var i=0;i<aTablesPKF.length; i++){
    sParam += '&' + aTablesPKF[i] + '=' + aRowsSeleted[i];
  }
  location.href = 'additionalTablesDataEdit?sUID='+TABLES.UID+sParam;
};

//Confirm PM Table Row Deletion Tasks
DeletePMTableRow = function(){

  PMExt.confirm(_('ID_CONFIRM'), _('ID_CONFIRM_REMOVE_FIELD'), function(){
    var records = Ext.getCmp('infoGrid').getSelectionModel().getSelections();
    Ext.each(records, Ext.getCmp('infoGrid').store.remove, Ext.getCmp('infoGrid').store);
  });

};

//Load Import PM Table From CSV Source
ImportPMTableCSV = function(){
  location.href = 'additionalTablesDataImportForm?sUID=' + TABLES.UID;
};

//Load PM Table List
BackPMList = function(){
  //location.href = 'additionalTablesList';
  history.back();
};

//Gets UIDs from a array of rows
RetrieveRowsID = function(rows){
  var arrAux = new Array();
  var arrPKF = new Array();
  arrPKF = TABLES.PKF.split(',');
  if(rows.length>0){
    var c = 0;
    for(var i=0; i<arrPKF.length; i++){
      arrAux[i] = rows[c].get(arrPKF[i]);
    }
  }
  return arrAux.join(',');
};

//Update Page Size Configuration
UpdatePageConfig = function(pageSize){
  Ext.Ajax.request({
  url: 'additionalTablesAjax',
  params: {action:'updatePageSizeData', size: pageSize}
  });
};<|endoftext|>


<commit_before>import './editable_node_selector.html';
import { Blaze } from 'meteor/blaze';
import { Template } from 'meteor/templating';
import './x_editable_node_selector.js';
import './x_editable_node_selector.css';

/**
 * Template Helpers
 */
Template.EditableNodeSelector.helpers({});

/**
 * Template Event Handlers
 */
Template.EditableNodeSelector.events({});

/**
 * Template Created
 */
Template.EditableNodeSelector.created = function () {

};

/**
 * Template Rendered
 */
Template.EditableNodeSelector.rendered = function () {
  var instance = Template.instance();

  console.log("EditableNodeSelector context:", instance.data);

  // Make sure there's a project version id
  if(!instance.data.projectVersionId){
    throw new Meteor.Error('Null project version id:', instance.data);
  }

  instance.$(".editable").editable({
    type            : "nodeSelector",
    mode            : instance.data.mode || "popup",
    placement       : instance.data.placement || "auto",
    value           : instance.data.value,
    projectVersionId: instance.data.projectVersionId,
    parentInstance  : instance,
    highlight       : false,
    display() {
    },
    success(response, newValue) {
      console.log("EditableNodeSelector edited: ", newValue);
      var editedElement = this;
      $(editedElement).trigger("edited", [ newValue ]);
      setTimeout(function () {
        $(editedElement).removeClass('editable-unsaved');
      }, 10);
    }
  });

  // this event listener needs to be registered directly
  instance.$(".editable").on("hidden", function () {
    console.log("EditableNodeSelector .editable hidden: ", instance.searchView);
    if (instance.searchView) {
      setTimeout(function () {
        Blaze.remove(instance.searchView);
      }, 100);
    }
  });

  instance.autorun(function () {
    var data = Template.currentData();
    console.log("EditableNodeSelector autorun setting value: ", data.value);
    instance.$(".editable").editable("setValue", data.value);
  });
};

/**
 * Template Destroyed
 */
Template.EditableNodeSelector.destroyed = function () {

};
<commit_msg>Removed verbose logging<commit_after>import './editable_node_selector.html';
import { Blaze } from 'meteor/blaze';
import { Template } from 'meteor/templating';
import './x_editable_node_selector.js';
import './x_editable_node_selector.css';

/**
 * Template Helpers
 */
Template.EditableNodeSelector.helpers({});

/**
 * Template Event Handlers
 */
Template.EditableNodeSelector.events({});

/**
 * Template Created
 */
Template.EditableNodeSelector.created = function () {

};

/**
 * Template Rendered
 */
Template.EditableNodeSelector.rendered = function () {
  var instance = Template.instance();

  //console.log("EditableNodeSelector context:", instance.data);

  // Make sure there's a project version id
  if(!instance.data.projectVersionId){
    throw new Meteor.Error('Null project version id:', instance.data);
  }

  instance.$(".editable").editable({
    type            : "nodeSelector",
    mode            : instance.data.mode || "popup",
    placement       : instance.data.placement || "auto",
    value           : instance.data.value,
    projectVersionId: instance.data.projectVersionId,
    parentInstance  : instance,
    highlight       : false,
    display() {
    },
    success(response, newValue) {
      console.log("EditableNodeSelector edited: ", newValue);
      var editedElement = this;
      $(editedElement).trigger("edited", [ newValue ]);
      setTimeout(function () {
        $(editedElement).removeClass('editable-unsaved');
      }, 10);
    }
  });

  // this event listener needs to be registered directly
  instance.$(".editable").on("hidden", function () {
    console.log("EditableNodeSelector .editable hidden: ", instance.searchView);
    if (instance.searchView) {
      setTimeout(function () {
        Blaze.remove(instance.searchView);
      }, 100);
    }
  });

  instance.autorun(function () {
    var data = Template.currentData();
    console.log("EditableNodeSelector autorun setting value: ", data.value);
    instance.$(".editable").editable("setValue", data.value);
  });
};

/**
 * Template Destroyed
 */
Template.EditableNodeSelector.destroyed = function () {

};
<|endoftext|>


<commit_before>function leaflet_alert() {
    alert("By clicking OK the user takes full responsibility of using this map and absolves the map developper of any responsibility.");
}

function leaflet_confirm() {
  var txt;
  var r = confirm("By clicking OK the user takes full responsibility of using this map and absolves the map developper of any responsibility.");
  if (r != true) {
      window.location = 'https://edrap.github.io/abruzzomap';
  }
}
<commit_msg>Update custom_funct.js<commit_after>function leaflet_alert() {
    alert("By clicking OK the user takes full responsibility of using this map and absolves the map developper of any responsibility.");
    keyPress (e);
}

function leaflet_confirm() {
  var txt;
  var r = confirm("By clicking OK the user takes full responsibility of using this map and absolves the map developper of any responsibility.");
  if (r != true) {
      window.location = 'https://edrap.github.io/abruzzomap';
  }
}

function keyPress (e) {
    if(e.key === "Escape") {
        // write your logic here.
    }
}
<|endoftext|>


<commit_before>function displayStockList(stockCode) {

	var containerName = 'container'+stockCode;
	appendContainer(containerName);

	var analysisData = [];
	$.getJSON('getAnalysisData.do?stockCode=' + stockCode, function(data) {
		for ( var i = 0; i < data.length; i++) {

			var price = data[i]['price'];
			var obj = {
				x :  parseToDateTime(data[i]['date']),
				title : price < 0 ? '買' : '賣',
				text : price < 0 ? '買進點: '+(-1*price) : '賣出點: '+price,
				color : price < 0 ? '#FF5050' : '#50FF50'
			};
			analysisData.push(obj);
		}
	});

	$.getJSON('getData.do?stockCode=' + stockCode, function(data) {

		// split the data set into ohlc and volume
		var ohlc = [], volume = [], dataLength = data.length;

		for ( var i = 0; i < dataLength; i++) {
			var datetime = parseToDateTime(data[i]['date']);
			ohlc.push([ datetime, // the date
			data[i]['open'], // open
			data[i]['high'], // high
			data[i]['low'], // low
			data[i]['close'] // close
			]);

			volume.push([ datetime, // the date
			data[i]['volumn'] // the volume
			]);
		}

		// create the chart
		$('#'+containerName).highcharts('StockChart', {

			rangeSelector : {
				selected : 1
			},
			title : {
				text : stockCode + ' 歷史資料'
			},
			yAxis : [ {
				title : {
					text : 'K線'
				},
				height : 200,
				lineWidth : 2
			}, {
				title : {
					text : '成交量'
				},
				top : 300,
				height : 100,
				offset : 0,
				lineWidth : 2
			} ],

			tooltip : {
				xDateFormat : '%Y-%m-%d',
				shared : true
			},

			plotOptions: {
				candlestick:{
				color: '#6adc3a',
				upColor: '#f40117'

			}},

			series : [ {
				type : 'candlestick',
				name : stockCode,
				data : ohlc,
				id : 'flags',
				dataGrouping:{enabled:false}
			}, {
				type : 'column',
				name : 'Volume',
				data : volume,
				yAxis : 1,
				dataGrouping:{enabled:false}
			}, {
				type : 'flags',
				data : analysisData,
				onSeries : 'flags',
				shape : 'circlepin',
				width : 16
			}, {
				type : 'flags',
				data : [],
				width : 15,
				shape : 'squarepin'

			}, {
				type : 'flags',
				data : [],
				width : 5,
				onSeries : '',
				shape : 'circlepin'

			} ]
		});
	});
}

function parseToDateTime(str){
	var yyyy = str.substring(0, 4) - 0;
	var MM = str.substring(4, 6) - 1;
	var dd = str.substring(6, 8) - 0;
	return Date.UTC(yyyy, MM, dd);
}

function appendContainer(containerName){
	if($('#'+containerName).length == 0){
		$('#content').append('

');
	}
}

$(function() {
	$.getJSON('getAllStockOrderByEarnMoney.do', function(data) {
		for ( var i = 0; i < data.length; i++) {
			var code = $.trim(data[i]['code']);
			var html = '<input type="button" onclick="displayStockList('+code+')" value="股票代號('+code+'), 賺錢:'+data[i]['earnMoney']+'">';
			$('#content').append(html);
			appendContainer('container'+code);
		}
	});
});<commit_msg>修正 股票代號 含有英文問題<commit_after>function displayStockList(stockCode) {

	var containerName = 'container'+stockCode;
	appendContainer(containerName);

	var analysisData = [];
	$.getJSON('getAnalysisData.do?stockCode=' + stockCode, function(data) {
		for ( var i = 0; i < data.length; i++) {

			var price = data[i]['price'];
			var obj = {
				x :  parseToDateTime(data[i]['date']),
				title : price < 0 ? '買' : '賣',
				text : price < 0 ? '買進點: '+(-1*price) : '賣出點: '+price,
				color : price < 0 ? '#FF5050' : '#50FF50'
			};
			analysisData.push(obj);
		}

		$.getJSON('getData.do?stockCode=' + stockCode, function(data) {

			// split the data set into ohlc and volume
			var ohlc = [], volume = [], dataLength = data.length;

			for ( var i = 0; i < dataLength; i++) {
				var datetime = parseToDateTime(data[i]['date']);
				ohlc.push([ datetime, // the date
				data[i]['open'], // open
				data[i]['high'], // high
				data[i]['low'], // low
				data[i]['close'] // close
				]);

				volume.push([ datetime, // the date
				data[i]['volumn'] // the volume
				]);
			}

			// create the chart
			$('#'+containerName).highcharts('StockChart', {

				rangeSelector : {
					selected : 1
				},
				title : {
					text : stockCode + ' 歷史資料'
				},
				yAxis : [ {
					title : {
						text : 'K線'
					},
					height : 200,
					lineWidth : 2
				}, {
					title : {
						text : '成交量'
					},
					top : 300,
					height : 100,
					offset : 0,
					lineWidth : 2
				} ],

				tooltip : {
					xDateFormat : '%Y-%m-%d',
					shared : true
				},

				plotOptions: {
					candlestick:{
					color: '#6adc3a',
					upColor: '#f40117'

				}},

				series : [ {
					type : 'candlestick',
					name : stockCode,
					data : ohlc,
					id : 'flags',
					dataGrouping:{enabled:false}
				}, {
					type : 'column',
					name : 'Volume',
					data : volume,
					yAxis : 1,
					dataGrouping:{enabled:false}
				}, {
					type : 'flags',
					data : analysisData,
					onSeries : 'flags',
					shape : 'circlepin',
					width : 16
				}, {
					type : 'flags',
					data : [],
					width : 15,
					shape : 'squarepin'

				}, {
					type : 'flags',
					data : [],
					width : 5,
					onSeries : '',
					shape : 'circlepin'

				} ]
			});
		});
	});

}

function parseToDateTime(str){
	var yyyy = str.substring(0, 4) - 0;
	var MM = str.substring(4, 6) - 1;
	var dd = str.substring(6, 8) - 0;
	return Date.UTC(yyyy, MM, dd);
}

function appendContainer(containerName){
	if($('#'+containerName).length == 0){
		$('#content').append('

');
	}
}

$(function() {
	$.getJSON('getAllStockOrderByEarnMoney.do', function(data) {
		for ( var i = 0; i < data.length; i++) {
			var code = $.trim(data[i]['code']);
			var html = '<input type="button" onclick="displayStockList(\''+code+'\')" value="股票代號('+code+'), 賺錢:'+data[i]['earnMoney']+'">';
			$('#content').append(html);
			appendContainer('container'+code);
		}
	});
});<|endoftext|>


<commit_before>//we are using bundlers so there is no need to create a singleton in the form of java

//File: EventsManager.js
//a super simplistic event listener implementation
class EventsManager {
  constructor() {
    this.index = 0;
    this.events = {};

    //binding
    this.on = this.on.bind(this);
    this.dispatch = this.dispatch.bind(this);
    this.remove = this.remove.bind(this);
  }

  on(event, callback) {
    if(!this.events[event]) this.events[event] = []; //initialize
    this.index++;
    this.events[event].push({index: this.index, callback: callback});
    return this.index++; //return listener id
  }

  dispatch(event, data) {
    if(!this.events[event]) return; //validation
    for(let e of this.events[event]) {
      e.callback(data); //call all listeners
    }
  }

  remove(event, index) {
    if(!this.events[event]) return; //validation
    this.events[event] = this.events[event].filter(e => e.index !== index);
  }

}

let eventManager = new EventManager(); //creating an instance
export default eventManager; //exporting a singleton
<commit_msg>Update singleton.js<commit_after>//we are using bundlers so there is no need to create a singleton in the form of java

//File: EventsManager.js
//a super simplistic event listener implementation
class EventsManager {
  constructor() {
    this.index = 0;
    this.events = {};

    //binding
    this.on = this.on.bind(this);
    this.dispatch = this.dispatch.bind(this);
    this.remove = this.remove.bind(this);
  }

  on(event, callback) {
    if(!this.events[event]) this.events[event] = []; //initialize
    this.index++;
    this.events[event].push({index: this.index, callback: callback});
    return this.index++; //return listener id
  }

  dispatch(event, data) {
    if(!this.events[event]) return; //validation
    for(let e of this.events[event]) {
      e.callback(data); //call all listeners
    }
  }

  remove(event, index) {
    if(!this.events[event]) return; //validation
    this.events[event] = this.events[event].filter(e => e.index !== index);
  }

}

const eventManager = new EventManager(); //creating an instance
export default eventManager; //exporting a singleton
<|endoftext|>


<commit_before>// check for Geolocation support
if (navigator.geolocation)
{

    console.log('Geolocation is supported!');
}
else
{
    alert('Geolocation is not supported for this Browser/OS version yet.');
}

// our current position
var worldAdjustRotation = null;
var ajusteRot = null;
var positionHng;
var defaultOrientation;
var positionCurrent = {
    lat: null,
    lng: null,
    hng: null
};

function adjustRotationScene()
{
    console.log('adjustRotationScene');
    console.log('ajusteRot '+ajusteRot);
    console.log('positionCurrent ',positionCurrent);
    if(ajusteRot == null )
    {
        ajusteRot = 90 - positionCurrent.hng;
        console.log('Ajuste rotación: '+ajusteRot);
        $('.orientation').html('
AJUSTE ROT: '+ajusteRot+'
')
    }
}

function getBrowserOrientation() {
    var orientation;
    if (screen.orientation && screen.orientation.type) {
        orientation = screen.orientation.type;
    } else {
        orientation = screen.orientation ||
            screen.mozOrientation ||
            screen.msOrientation;
    }

    /*
     'portait-primary':      for (screen width < screen height, e.g. phone, phablet, small tablet)
     device is in 'normal' orientation
     for (screen width > screen height, e.g. large tablet, laptop)
     device has been turned 90deg clockwise from normal

     'portait-secondary':    for (screen width < screen height)
     device has been turned 180deg from normal
     for (screen width > screen height)
     device has been turned 90deg anti-clockwise (or 270deg clockwise) from normal

     'landscape-primary':    for (screen width < screen height)
     device has been turned 90deg clockwise from normal
     for (screen width > screen height)
     device is in 'normal' orientation

     'landscape-secondary':  for (screen width < screen height)
     device has been turned 90deg anti-clockwise (or 270deg clockwise) from normal
     for (screen width > screen height)
     device has been turned 180deg from normal
     */

    return orientation;
}

function onHeadingChange(event) {
    var heading = event.alpha;

    if (typeof event.webkitCompassHeading !== "undefined") {
        heading = event.webkitCompassHeading; //iOS non-standard
    }

    var orientation = getBrowserOrientation();

    if (typeof heading !== "undefined" && heading !== null)
    {
        // && typeof orientation !== "undefined") {
        // we have a browser that reports device heading and orientation

        // what adjustment we have to add to rotation to allow for current device orientation
        var adjustment = 0;
        if (defaultOrientation === "landscape") {
            adjustment -= 90;
        }

        if (typeof orientation !== "undefined") {
            var currentOrientation = orientation.split("-");

            if (defaultOrientation !== currentOrientation[0])
            {
                if (defaultOrientation === "landscape")
                {
                    adjustment -= 270;
                }
                else
                {
                    adjustment -= 90;
                }
            }

            if (currentOrientation[1] === "secondary")
            {
                adjustment -= 180;
            }
        }

        positionCurrent.hng = heading + adjustment;

        var phase = positionCurrent.hng < 0 ? 360 + positionCurrent.hng : positionCurrent.hng;
        //positionHng.textContent = (360 - phase | 0) + "°";

        //console.log('positionCurrent.hng ',positionCurrent.hng,positionCurrent);
        //console.log( (360 - phase | 0) + "°");

        adjustRotationScene();

        $('.brujula').html(parseFloat(positionCurrent.hng).toFixed(2)+ "°")

        /*
        // apply rotation to compass rose
        if (typeof rose.style.transform !== "undefined") {
            rose.style.transform = "rotateZ(" + positionCurrent.hng + "deg)";
        } else if (typeof rose.style.webkitTransform !== "undefined") {
            rose.style.webkitTransform = "rotateZ(" + positionCurrent.hng + "deg)";
        }
        */
    }
    else
    {
        // device can't show heading

        positionHng  = "n/a";
        console.log('brujula no disponible');
    }
}

if (window.DeviceOrientationEvent) {

    if (screen.width > screen.height)
    {
        defaultOrientation = "landscape";
    }
    else
    {
        defaultOrientation = "portrait";
    }

    window.addEventListener("deviceorientation", onHeadingChange);

} else {
    alert("Sorry, your browser doesn't support Device Orientation");
}

MAP_WIDTH           = 100000;
MAP_HEIGHT          = 100000;
var store_current   = null;

function convert(lat, lon){
    var y = ((-1 * lat) + 90) * (MAP_HEIGHT / 180);
    var x = (lon + 180) * (MAP_WIDTH / 360);
    return {x:x,y:y};
}

window.onload = function()
{
    var startPos;
    var stores =
    [
        {
            lat: 19.4375921,
            lng: -99.2099433,
            info:{
                title: 'Superama Los Morales',
                horario: 'horario',
                promo: 'promo',
                info: 'info',
                desc: 'desc',
                dist: 'dist',
                type: 'superama'
            }
        },
        {
            lat: 19.4477107,
            lng: -99.2171927,
            info:{
                title: 'Sam\'s Club Toreo',
                horario: 'horario',
                promo: 'promo',
                info: 'info',
                desc: 'desc',
                dist: 'dist',
                type: 'sams'
            }
        },
        {
            lat: 19.4373714,
            lng: -99.2056145,
            info:{
                title: 'Superama Polanco',
                horario: 'horario',
                promo: 'promo',
                info: 'info',
                desc: 'desc',
                dist: 'dist',
                type: 'superama'
            }
        },
        {
            lat: 19.2973321,
            lng: -99.1065446,
            info:{
                title: 'Walmart Pabellón Cuemanco',
                horario: 'horario',
                promo: 'promo',
                info: 'info',
                desc: 'desc',
                dist: 'dist',
                type: 'supercenter'
            }
        },
        {
            lat: 19.2989663,
            lng: -99.1059896,
            info:{
                title: 'Bodega Aurrera Hueso',
                horario: 'horario',
                promo: 'promo',
                info: 'info',
                desc: 'desc',
                dist: 'dist',
                type: 'ba'
            }
        },
        {
            lat: 19.2982219,
            lng: -99.1143161,
            info:{
                title: 'Audi Coapa',
                horario: 'horario',
                promo: 'promo',
                info: 'info',
                desc: 'desc',
                dist: 'dist',
                type: 'ba'
            }
        },
        {
            lat:19.2969037,
            lng: -99.1119386,
            info:{
                title: 'IIM',
                horario: 'horario',
                promo: 'promo',
                info: 'info',
                desc: 'desc',
                dist: 'dist',
                type: 'ba'
            }
        },

    ];

    $('.cerrar').click(function()
    {
        $('.info').hide();
    });

    $('.debug').click(function()
    {
        if($('#tripmeter').is(':visible'))
        {
            $('#tripmeter').hide();
        }
        else
        {
            $('#tripmeter').show();
        }
    });

    //ajuste inical mundo, mandar el norte arriba
    $('#pointers').attr('rotation','0 -90 0');

    //ajuste por la posicion inicial del teléfono con respecto al norte, prueba
   // $('#pointers').attr('rotation','0 146 0');

    navigator.geolocation.getCurrentPosition(
        function(position)
        {
            startPos = position;
            document.getElementById('startLat').innerHTML = startPos.coords.latitude;
            document.getElementById('startLon').innerHTML = startPos.coords.longitude;

            //console.log('startPos ', startPos);
            //console.log('camera '  , $('#camera').attr('position'));

            var convStart   = convert(startPos.coords.latitude,startPos.coords.longitude);
            var conv        = convert(stores[0].lat,stores[0].lng);
            var dif         =
            {
                x: convStart.x - conv.x,
                y: convStart.y - conv.y
            }

            $('#superama').attr('position',dif.x+' 0.5 '+dif.y);

            var convSams    = convert(stores[1].lat,stores[1].lng);
            var difSams     =
            {
                x: convStart.x - convSams.x,
                y: convStart.y - convSams.y
            }

            $('#sams').attr('position',difSams.x+' 0.5 '+difSams.y);
            $('#sams').attr('show-info', JSON.stringify(stores[1].info));

            var convSup    = convert(stores[2].lat,stores[2].lng);
            var difSup     =
            {
                x: convStart.x - convSup.x,
                y: convStart.y - convSup.y
            }
            $('#supPol').attr('position',difSup.x+' 0.5 '+difSup.y);

            var offset = 10000;
            var difCoordenads = {
                x: (startPos.coords.latitude     - stores[0].lat)*offset,
                y: (startPos.coords.longitude    - stores[0].lng)*offset
            }

            $('#sams').attr('position',difCoordenads.x+' 0.5 '+difCoordenads.y);
            //console.log(dif,difCoordenads)

            generatePin(startPos)

        },
        function(error)
        {
            alert('Error occurred. Error code: ' + error.code);
            // error.code can be:
            //   0: unknown error
            //   1: permission denied
            //   2: position unavailable (error response from locaton provider)
            //   3: timed out
        });

    navigator.geolocation.watchPosition(
        function(position)
        {
            console.log('store_current ',store_current);
            document.getElementById('currentLat').innerHTML = position.coords.latitude;
            document.getElementById('currentLon').innerHTML = position.coords.longitude;

            $('.stores').html('');
            for(var s in stores)
            {
                $('.stores').append('
Distance to '+stores[s].info.title+':
 '+calculateDistance(stores[s].lat, stores[s].lng,position.coords.latitude, position.coords.longitude)+' m
')
            }

            if(store_current!=null)
            {
                $('.txt.dist').show();
                $('.txt.dist').html(this.calculateDistance(store_current.lat, store_current.lng,position.coords.latitude, position.coords.longitude)+'m');
            }

        });

    function generatePin(startPos)
    {
        var offset  = 5000;
        var scene   = document.getElementById('pointers');

        for(var s in stores)
        {

            var convStart   = convert(startPos.coords.latitude,startPos.coords.longitude);
            var conv        = convert(stores[s].lat,stores[s].lng);
            var difCoordenads =
            {
                x: convStart.x - conv.x,
                y: convStart.y - conv.y
            }

            difCoordenads =
            {
                x: (startPos.coords.latitude     - stores[s].lat)*offset,
                y: (startPos.coords.longitude    - stores[s].lng)*offset
            }
            //console.log(difCoordenads)

            var color = '#123123';
            if(stores[s].info.title == 'IIM')
            {
                color = '#ff0000';
            }

            if(stores[s].info.title == 'Audi Coapa')
            {
                color = '#00ff00';
            }

           // console.log('X:', startPos.coords.latitude, stores[s].lat , difCoordenads.x , stores[s].info.title);
            //console.log(' ');

            var box	= document.createElement('a-box');
            box.setAttribute("position"	, difCoordenads.x+' 0.5 '+difCoordenads.y);
            //box.setAttribute("position"	, difCoordenads.x+' 0.5 0');
            box.setAttribute("rotation"	, "0 45 0");
            box.setAttribute("show-info", JSON.stringify(stores[s]));
            box.setAttribute("color"    , color);
            //box.setAttribute("look-at"	, "[camera]");

            //console.log('position' , difCoordenads.x+' 0.5 '+difCoordenads.y)

            scene.appendChild(box);
        }

        var norte	= document.createElement('a-entity');
        norte.setAttribute("position"   , '-10 0 0');
        norte.setAttribute("text"       , 'width:10; color:black; value:Norte; align:center;');
        norte.setAttribute("look-at"	, "[camera]");
        scene.appendChild(norte);

        var sur	= document.createElement('a-entity');
        sur.setAttribute("position"     , '10 0 0');
        sur.setAttribute("text"         , 'width:10; color:black; value:Sur; align:center;');
        sur.setAttribute("look-at"	    , "[camera]");
        scene.appendChild(sur);

        var este	= document.createElement('a-entity');
        este.setAttribute("position"     , '0 0 -10');
        este.setAttribute("text"         , 'width:10; color:black; value:Este; align:center;');
        este.setAttribute("look-at"	    , "[camera]");
        scene.appendChild(este);

        var oeste	= document.createElement('a-entity');
        oeste.setAttribute("position"     , '0 0 10');
        oeste.setAttribute("text"         , 'width:10; color:black; value:Oeste; align:center;');
        oeste.setAttribute("look-at"	  , "[camera]");
        scene.appendChild(oeste);

    }
};

function calculateDistance(lat1, lon1, lat2, lon2)
{
    var R = 6371 * 1000; // m
    var dLat = (lat2 - lat1).toRad();
    var dLon = (lon2 - lon1).toRad();
    var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
            Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
            Math.sin(dLon / 2) * Math.sin(dLon / 2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    var d = R * c;
    return d;
}

Number.prototype.toRad = function()
{
    return this * Math.PI / 180;
}
<commit_msg>adjust rotation scene<commit_after>// check for Geolocation support
if (navigator.geolocation)
{

    console.log('Geolocation is supported!');
}
else
{
    alert('Geolocation is not supported for this Browser/OS version yet.');
}

// our current position
var worldAdjustRotation = null;
var ajusteRot = null;
var positionHng;
var defaultOrientation;
var positionCurrent = {
    lat: null,
    lng: null,
    hng: null
};

function adjustRotationScene()
{

    if(ajusteRot == null && positionCurrent.hng!=null)
    {
        console.log('adjustRotationScene');
        console.log('ajusteRot '+ajusteRot);
        console.log('positionCurrent ',positionCurrent);

        ajusteRot = 90 - positionCurrent.hng;
        $('.orientation').html('
AJUSTE ROT: '+ajusteRot+'
')

        console.log('Ajuste rotación: '+ajusteRot);
    }
}

function getBrowserOrientation() {
    var orientation;
    if (screen.orientation && screen.orientation.type) {
        orientation = screen.orientation.type;
    } else {
        orientation = screen.orientation ||
            screen.mozOrientation ||
            screen.msOrientation;
    }

    /*
     'portait-primary':      for (screen width < screen height, e.g. phone, phablet, small tablet)
     device is in 'normal' orientation
     for (screen width > screen height, e.g. large tablet, laptop)
     device has been turned 90deg clockwise from normal

     'portait-secondary':    for (screen width < screen height)
     device has been turned 180deg from normal
     for (screen width > screen height)
     device has been turned 90deg anti-clockwise (or 270deg clockwise) from normal

     'landscape-primary':    for (screen width < screen height)
     device has been turned 90deg clockwise from normal
     for (screen width > screen height)
     device is in 'normal' orientation

     'landscape-secondary':  for (screen width < screen height)
     device has been turned 90deg anti-clockwise (or 270deg clockwise) from normal
     for (screen width > screen height)
     device has been turned 180deg from normal
     */

    return orientation;
}

function onHeadingChange(event) {
    var heading = event.alpha;

    if (typeof event.webkitCompassHeading !== "undefined") {
        heading = event.webkitCompassHeading; //iOS non-standard
    }

    var orientation = getBrowserOrientation();

    if (typeof heading !== "undefined" && heading !== null)
    {
        // && typeof orientation !== "undefined") {
        // we have a browser that reports device heading and orientation

        // what adjustment we have to add to rotation to allow for current device orientation
        var adjustment = 0;
        if (defaultOrientation === "landscape") {
            adjustment -= 90;
        }

        if (typeof orientation !== "undefined") {
            var currentOrientation = orientation.split("-");

            if (defaultOrientation !== currentOrientation[0])
            {
                if (defaultOrientation === "landscape")
                {
                    adjustment -= 270;
                }
                else
                {
                    adjustment -= 90;
                }
            }

            if (currentOrientation[1] === "secondary")
            {
                adjustment -= 180;
            }
        }

        positionCurrent.hng = heading + adjustment;

        var phase = positionCurrent.hng < 0 ? 360 + positionCurrent.hng : positionCurrent.hng;
        //positionHng.textContent = (360 - phase | 0) + "°";

        //console.log('positionCurrent.hng ',positionCurrent.hng,positionCurrent);
        //console.log( (360 - phase | 0) + "°");

        adjustRotationScene();

        $('.brujula').html(parseFloat(positionCurrent.hng).toFixed(2)+ "°")

        /*
        // apply rotation to compass rose
        if (typeof rose.style.transform !== "undefined") {
            rose.style.transform = "rotateZ(" + positionCurrent.hng + "deg)";
        } else if (typeof rose.style.webkitTransform !== "undefined") {
            rose.style.webkitTransform = "rotateZ(" + positionCurrent.hng + "deg)";
        }
        */
    }
    else
    {
        // device can't show heading

        positionHng  = "n/a";
        console.log('brujula no disponible');
    }
}

if (window.DeviceOrientationEvent) {

    if (screen.width > screen.height)
    {
        defaultOrientation = "landscape";
    }
    else
    {
        defaultOrientation = "portrait";
    }

    window.addEventListener("deviceorientation", onHeadingChange);

} else {
    alert("Sorry, your browser doesn't support Device Orientation");
}

MAP_WIDTH           = 100000;
MAP_HEIGHT          = 100000;
var store_current   = null;

function convert(lat, lon){
    var y = ((-1 * lat) + 90) * (MAP_HEIGHT / 180);
    var x = (lon + 180) * (MAP_WIDTH / 360);
    return {x:x,y:y};
}

window.onload = function()
{
    var startPos;
    var stores =
    [
        {
            lat: 19.4375921,
            lng: -99.2099433,
            info:{
                title: 'Superama Los Morales',
                horario: 'horario',
                promo: 'promo',
                info: 'info',
                desc: 'desc',
                dist: 'dist',
                type: 'superama'
            }
        },
        {
            lat: 19.4477107,
            lng: -99.2171927,
            info:{
                title: 'Sam\'s Club Toreo',
                horario: 'horario',
                promo: 'promo',
                info: 'info',
                desc: 'desc',
                dist: 'dist',
                type: 'sams'
            }
        },
        {
            lat: 19.4373714,
            lng: -99.2056145,
            info:{
                title: 'Superama Polanco',
                horario: 'horario',
                promo: 'promo',
                info: 'info',
                desc: 'desc',
                dist: 'dist',
                type: 'superama'
            }
        },
        {
            lat: 19.2973321,
            lng: -99.1065446,
            info:{
                title: 'Walmart Pabellón Cuemanco',
                horario: 'horario',
                promo: 'promo',
                info: 'info',
                desc: 'desc',
                dist: 'dist',
                type: 'supercenter'
            }
        },
        {
            lat: 19.2989663,
            lng: -99.1059896,
            info:{
                title: 'Bodega Aurrera Hueso',
                horario: 'horario',
                promo: 'promo',
                info: 'info',
                desc: 'desc',
                dist: 'dist',
                type: 'ba'
            }
        },
        {
            lat: 19.2982219,
            lng: -99.1143161,
            info:{
                title: 'Audi Coapa',
                horario: 'horario',
                promo: 'promo',
                info: 'info',
                desc: 'desc',
                dist: 'dist',
                type: 'ba'
            }
        },
        {
            lat:19.2969037,
            lng: -99.1119386,
            info:{
                title: 'IIM',
                horario: 'horario',
                promo: 'promo',
                info: 'info',
                desc: 'desc',
                dist: 'dist',
                type: 'ba'
            }
        },

    ];

    $('.cerrar').click(function()
    {
        $('.info').hide();
    });

    $('.debug').click(function()
    {
        if($('#tripmeter').is(':visible'))
        {
            $('#tripmeter').hide();
        }
        else
        {
            $('#tripmeter').show();
        }
    });

    //ajuste inical mundo, mandar el norte arriba
    $('#pointers').attr('rotation','0 -90 0');

    //ajuste por la posicion inicial del teléfono con respecto al norte, prueba
   // $('#pointers').attr('rotation','0 146 0');

    navigator.geolocation.getCurrentPosition(
        function(position)
        {
            startPos = position;
            document.getElementById('startLat').innerHTML = startPos.coords.latitude;
            document.getElementById('startLon').innerHTML = startPos.coords.longitude;

            //console.log('startPos ', startPos);
            //console.log('camera '  , $('#camera').attr('position'));

            var convStart   = convert(startPos.coords.latitude,startPos.coords.longitude);
            var conv        = convert(stores[0].lat,stores[0].lng);
            var dif         =
            {
                x: convStart.x - conv.x,
                y: convStart.y - conv.y
            }

            $('#superama').attr('position',dif.x+' 0.5 '+dif.y);

            var convSams    = convert(stores[1].lat,stores[1].lng);
            var difSams     =
            {
                x: convStart.x - convSams.x,
                y: convStart.y - convSams.y
            }

            $('#sams').attr('position',difSams.x+' 0.5 '+difSams.y);
            $('#sams').attr('show-info', JSON.stringify(stores[1].info));

            var convSup    = convert(stores[2].lat,stores[2].lng);
            var difSup     =
            {
                x: convStart.x - convSup.x,
                y: convStart.y - convSup.y
            }
            $('#supPol').attr('position',difSup.x+' 0.5 '+difSup.y);

            var offset = 10000;
            var difCoordenads = {
                x: (startPos.coords.latitude     - stores[0].lat)*offset,
                y: (startPos.coords.longitude    - stores[0].lng)*offset
            }

            $('#sams').attr('position',difCoordenads.x+' 0.5 '+difCoordenads.y);
            //console.log(dif,difCoordenads)

            generatePin(startPos)

        },
        function(error)
        {
            alert('Error occurred. Error code: ' + error.code);
            // error.code can be:
            //   0: unknown error
            //   1: permission denied
            //   2: position unavailable (error response from locaton provider)
            //   3: timed out
        });

    navigator.geolocation.watchPosition(
        function(position)
        {
            console.log('store_current ',store_current);
            document.getElementById('currentLat').innerHTML = position.coords.latitude;
            document.getElementById('currentLon').innerHTML = position.coords.longitude;

            $('.stores').html('');
            for(var s in stores)
            {
                $('.stores').append('
Distance to '+stores[s].info.title+':
 '+calculateDistance(stores[s].lat, stores[s].lng,position.coords.latitude, position.coords.longitude)+' m
')
            }

            if(store_current!=null)
            {
                $('.txt.dist').show();
                $('.txt.dist').html(this.calculateDistance(store_current.lat, store_current.lng,position.coords.latitude, position.coords.longitude)+'m');
            }

        });

    function generatePin(startPos)
    {
        var offset  = 5000;
        var scene   = document.getElementById('pointers');

        for(var s in stores)
        {

            var convStart   = convert(startPos.coords.latitude,startPos.coords.longitude);
            var conv        = convert(stores[s].lat,stores[s].lng);
            var difCoordenads =
            {
                x: convStart.x - conv.x,
                y: convStart.y - conv.y
            }

            difCoordenads =
            {
                x: (startPos.coords.latitude     - stores[s].lat)*offset,
                y: (startPos.coords.longitude    - stores[s].lng)*offset
            }
            //console.log(difCoordenads)

            var color = '#123123';
            if(stores[s].info.title == 'IIM')
            {
                color = '#ff0000';
            }

            if(stores[s].info.title == 'Audi Coapa')
            {
                color = '#00ff00';
            }

           // console.log('X:', startPos.coords.latitude, stores[s].lat , difCoordenads.x , stores[s].info.title);
            //console.log(' ');

            var box	= document.createElement('a-box');
            box.setAttribute("position"	, difCoordenads.x+' 0.5 '+difCoordenads.y);
            //box.setAttribute("position"	, difCoordenads.x+' 0.5 0');
            box.setAttribute("rotation"	, "0 45 0");
            box.setAttribute("show-info", JSON.stringify(stores[s]));
            box.setAttribute("color"    , color);
            //box.setAttribute("look-at"	, "[camera]");

            //console.log('position' , difCoordenads.x+' 0.5 '+difCoordenads.y)

            scene.appendChild(box);
        }

        var norte	= document.createElement('a-entity');
        norte.setAttribute("position"   , '-10 0 0');
        norte.setAttribute("text"       , 'width:10; color:black; value:Norte; align:center;');
        norte.setAttribute("look-at"	, "[camera]");
        scene.appendChild(norte);

        var sur	= document.createElement('a-entity');
        sur.setAttribute("position"     , '10 0 0');
        sur.setAttribute("text"         , 'width:10; color:black; value:Sur; align:center;');
        sur.setAttribute("look-at"	    , "[camera]");
        scene.appendChild(sur);

        var este	= document.createElement('a-entity');
        este.setAttribute("position"     , '0 0 -10');
        este.setAttribute("text"         , 'width:10; color:black; value:Este; align:center;');
        este.setAttribute("look-at"	    , "[camera]");
        scene.appendChild(este);

        var oeste	= document.createElement('a-entity');
        oeste.setAttribute("position"     , '0 0 10');
        oeste.setAttribute("text"         , 'width:10; color:black; value:Oeste; align:center;');
        oeste.setAttribute("look-at"	  , "[camera]");
        scene.appendChild(oeste);

    }
};

function calculateDistance(lat1, lon1, lat2, lon2)
{
    var R = 6371 * 1000; // m
    var dLat = (lat2 - lat1).toRad();
    var dLon = (lon2 - lon1).toRad();
    var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
            Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
            Math.sin(dLon / 2) * Math.sin(dLon / 2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    var d = R * c;
    return d;
}

Number.prototype.toRad = function()
{
    return this * Math.PI / 180;
}
<|endoftext|>


<commit_before>'use strict';

var test      =  require('tap').test;
var fs        =  require('fs');
var path      =  require('path');
var through   =  require('through');
var convert   =  require('convert-source-map');
var coffee    =  require('coffee-script');
var transform =  require('..');

test('transform adds sourcemap comment and uses cache on second time', function (t) {
    t.plan(2);
    var data = '';
    var compiles = 0;
    var originalCompile = coffee.compile;

    coffee.compile = function () {
      compiles++;
      var args = [].slice.call(arguments);
      return originalCompile.apply(this, args);
    };

    var file = path.join(__dirname, '../example/foo.coffee');
    // first time
    fs.createReadStream(file)
        .pipe(transform(file))
        .pipe(through(write));

    // second time
    fs.createReadStream(file)
        .pipe(transform(file))
        .pipe(through(write, end));

    function write (buf) { data += buf; }
    function end () {
        var sourceMap = convert.fromSource(data).toObject();

        t.deepEqual(
            sourceMap,
            { version: 3,
              file: file,
              sourceRoot: '',
              sources: [ file ],
              names: [],
              mappings: 'AAAA,OAAO,CAAC,GAAR,CAAY,OAAA,CAAQ,UAAR,CAAZ,CAAA,CAAA',
              sourcesContent: [ 'console.log(require \'./bar.js\')\n' ] },
            'adds sourcemap comment including original source'
      );
      t.equal(compiles, 1, 'compiles only the first time');
    }
});
<commit_msg>Override coffeeify's compile for tests<commit_after>'use strict';

var test      =  require('tap').test;
var fs        =  require('fs');
var path      =  require('path');
var through   =  require('through');
var convert   =  require('convert-source-map');
var coffeeify =  require('coffeeify');
var transform =  require('..');

test('transform adds sourcemap comment and uses cache on second time', function (t) {
    t.plan(2);
    var data = '';
    var compiles = 0;
    var originalCompile = coffeeify.compile;

    coffeeify.compile = function () {
      compiles++;
      var args = [].slice.call(arguments);
      return originalCompile.apply(this, args);
    };

    var file = path.join(__dirname, '../example/foo.coffee');
    // first time
    fs.createReadStream(file)
        .pipe(transform(file))
        .pipe(through(write));

    // second time
    fs.createReadStream(file)
        .pipe(transform(file))
        .pipe(through(write, end));

    function write (buf) { data += buf; }
    function end () {
        var sourceMap = convert.fromSource(data).toObject();

        t.deepEqual(
            sourceMap,
            { version: 3,
              file: file,
              sourceRoot: '',
              sources: [ file ],
              names: [],
              mappings: 'AAAA,OAAO,CAAC,GAAR,CAAY,OAAA,CAAQ,UAAR,CAAZ,CAAA,CAAA',
              sourcesContent: [ 'console.log(require \'./bar.js\')\n' ] },
            'adds sourcemap comment including original source'
      );
      t.equal(compiles, 1, 'compiles only the first time');
    }
});
<|endoftext|>


<commit_before>/*jslint node:true */

module.exports = function (grunt) {
  'use strict';

  var http = require('http'),
    chalk = require('chalk'),
    path = require('path'),
    async = require('async'),
    fs = require('fs-extra'),
    pkg = require('../package.json'),
    chrome = require('../lib/launch-chrome');

  function addFiles(files, to, tagFilter) {
    var tags = '';

    files.forEach(function (file) {
      file.src.forEach(function (f) {
        var dest;
        if (file.dest && grunt.file.isDir(file.dest)) {
          dest = f;
        } else {
          dest = file.dest || f;
        }
        if (grunt.file.isFile(f)) {
          if (grunt.file.isMatch(tagFilter, f)) {
            tags += "\n";
          }
          grunt.file.copy(f, to + '/scripts/' + dest);
        }
      });
    });

    return tags;
  }

  function buildSpec(ctx, next) {
    grunt.log.write('Building...');
    grunt.file.mkdir(ctx.outfile);
    var dest = ctx.outfile,
      tags = "";

    // Copy the template
    grunt.file.recurse(ctx.template, function (file, root, dir, filename) {
      grunt.file.copy(file, dest + '/' + filename);
    });
    // Copy Jasmine
    grunt.file.recurse(__dirname + '/../vendor/jasmine-core-' + ctx.version,
      function (file, root, dir, filename) {
        if (!dir) {
          dir = '';
        }
        grunt.file.copy(file, dest + '/jasmine-core/' + dir + '/' + filename);
      });
    // Make a profile directory.
    grunt.file.mkdir(ctx.outfile + '/profile');

    // Copy user files.
    if (!ctx.paths) {
      ctx.paths = grunt.file.expand(ctx.files[0].src);
    }
    tags += addFiles(ctx.files, dest, ctx.paths);

    tags += "";

    // Update the template with found specs.
    tags = grunt.file.read(dest + '/main.html') + tags;
    grunt.file.write(dest + '/main.html', tags);

    grunt.log.writeln(chalk.green('Done.'));
    next();
  }

  function startReporter(ctx, next) {
    ctx.cleanupTimeout = setTimeout(cleanup.bind({}, ctx), ctx.timeout);
    grunt.log.write('Starting Reporter...');

    ctx.messages = [];
    ctx.inprogress = '';
    ctx.web = http.createServer(function (req, res) {
      if (req.url === '/') {
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.end('' +
                'Reporting server for grunt-jasmine-chromeapp.' +
                '');
      } else if (req.url === '/put') {
        req.setEncoding('utf8');
        req.on('data', function (chunk) {
          ctx.inprogress += chunk;
        });
        req.on('end', function () {
          ctx.messages.push(ctx.inprogress);
          ctx.inprogress = '';
          res.setHeader('Access-Control-Allow-Origin', '*');
          res.end(ctx.keepRunner? 'thanks!': 'kill');
          if (ctx.onMessage) {
            ctx.onMessage();
          }
        });
      } else if (req.url === '/ready') {
        grunt.log.writeln(chalk.green('Done.'));
        res.end('Okay.');
        if (ctx.onMessage) {
          ctx.onMessage();
        }
      }
    }).listen(ctx.port);

    grunt.log.writeln(chalk.green('Done.'));
    next();
  }

  function startChrome(ctx, next) {
    grunt.log.write('Starting Chrome...');
    ctx.onMessage = next;

    if (process.platform === "darwin") {
      ctx.flags = ctx.flags.concat("--no-startup-window");
    }

    ctx.chrome = chrome([
        "--no-first-run",
        "--force-app-mode",
        "--apps-keep-chrome-alive-in-tests",
        "--load-and-launch-app=" + ctx.outfile,
        "--user-data-dir=" + ctx.outfile + '/profile'
    ].concat(ctx.flags), ctx.binary);
  }

  function testPoll(ctx, cb) {
    if (ctx.messages.length > 0) {
      cb();
    } else {
      setTimeout(testPoll.bind({}, ctx, cb), 500);
    }
  }

  function runTests(ctx, next) {
    grunt.log.write('Running Tests...');
    clearTimeout(ctx.cleanupTimeout);
    ctx.onMessage = function () {
      grunt.log.writeln(chalk.green('Done.'));
      next();
    };
  }

  function finishTests(ctx, next) {
    grunt.log.write('Reporting on Tests...');
    testPoll(ctx, function (ctx) {
      grunt.log.writeln(chalk.green('Done.'));
      var parse = JSON.parse(ctx.messages[0]),
        spec,
        i = 0;

      ctx.status = {failed: 0};
      for (i = 0; i < parse.length; i += 1) {
        spec = parse[i];
        if (process.stdout.clearLine) {
          process.stdout.clearLine();
          process.stdout.cursorTo(0);
          if (spec.status === 'passed') {
            grunt.log.writeln(chalk.green.bold('✓') + '\t' + spec.fullName);
          } else if (spec.status === 'failed') {
            ctx.status.failed += 1;
            grunt.log.writeln(chalk.red.bold('X') + '\t' + spec.fullName);
          } else {
            grunt.log.writeln(chalk.yellow.bold('*') + '\t' + spec.fullName);
          }
        } else {
          if (spec.status === 'passed') {
            grunt.log.writeln('✓' + spec.fullName);
          } else if (spec.status === 'failed') {
            ctx.status.failed += 1;
            grunt.log.writeln('X' + spec.fullName);
          } else {
            grunt.log.writeln('*' + spec.fullName);
          }
        }
      }
      next();
    }.bind({}, ctx));
  }

  function cleanup(ctx, next) {
    var good = true;
    if (ctx.cleanupTimeout) {
      clearTimeout(ctx.cleanupTimeout);
    }
    if (!next) {
      next = ctx.done;
    }
    if (!ctx.status) {
      grunt.log.error(chalk.red('Timed out'));
      good = false;
    } else if (ctx.status.failed === 0) {
      grunt.log.ok(chalk.green('0 failures'));
    } else {
      grunt.log.error(chalk.red(ctx.status.failed + ' failures'));
      good = false;
    }
    if (ctx.keepRunner) {
      ctx.chrome.on('close', function () {
        grunt.file['delete'](ctx.outfile);
        ctx.web.close();
        next(good || new Error('One or more tests failed.'));
      });
      return;
    }

    ctx.web.close();
    if (ctx.chrome) {
      ctx.chrome.on('close', function () {
        grunt.file['delete'](ctx.outfile);
      });
      ctx.chrome.kill();
    } else {
      grunt.file['delete'](ctx.outfile);
    }

    next(good || new Error('One or more tests failed.'));
  }

  grunt.registerMultiTask('jasmine_chromeapp', pkg.description, function () {
    var done = this.async(),
      name = this.target,
      ctx = this.options({
        template: __dirname + '/../tasks/jasmine-chromeapp',
        version: '2.0.0',
        outfile: '.build',
        paths: undefined,
        binary: undefined,
        keepRunner: false,
        port: 9989,
        timeout : 30000,
        flags: []
      });

    if (grunt.option('debug')) {
      grunt.log.debug(JSON.stringify(ctx));
    }

    ctx.files = this.files;
    ctx.done = done;

    process.on('SIGINT', function () {
      cleanup(ctx);
    });

    async.series([
      async.apply(buildSpec, ctx),
      async.apply(startReporter, ctx),
      async.apply(startChrome, ctx),
      async.apply(runTests, ctx),
      async.apply(finishTests, ctx),
      async.apply(cleanup, ctx)
    ], function (good) {
      ctx.done(good);
    });
  });
};
<commit_msg>process *all* files for default path whitelist<commit_after>/*jslint node:true */

module.exports = function (grunt) {
  'use strict';

  var http = require('http'),
    chalk = require('chalk'),
    path = require('path'),
    async = require('async'),
    fs = require('fs-extra'),
    pkg = require('../package.json'),
    chrome = require('../lib/launch-chrome');

  function addFiles(files, to, tagFilter) {
    var tags = '';

    files.forEach(function (file) {
      file.src.forEach(function (f) {
        var dest;
        if (file.dest && grunt.file.isDir(file.dest)) {
          dest = f;
        } else {
          dest = file.dest || f;
        }
        if (grunt.file.isFile(f)) {
          if (grunt.file.isMatch(tagFilter, f)) {
            tags += "\n";
          }
          grunt.file.copy(f, to + '/scripts/' + dest);
        }
      });
    });

    return tags;
  }

  function buildSpec(ctx, next) {
    grunt.log.write('Building...');
    grunt.file.mkdir(ctx.outfile);
    var dest = ctx.outfile,
      tags = "";

    // Copy the template
    grunt.file.recurse(ctx.template, function (file, root, dir, filename) {
      grunt.file.copy(file, dest + '/' + filename);
    });
    // Copy Jasmine
    grunt.file.recurse(__dirname + '/../vendor/jasmine-core-' + ctx.version,
      function (file, root, dir, filename) {
        if (!dir) {
          dir = '';
        }
        grunt.file.copy(file, dest + '/jasmine-core/' + dir + '/' + filename);
      });
    // Make a profile directory.
    grunt.file.mkdir(ctx.outfile + '/profile');

    // Copy user files.
    if (!ctx.paths) {
      ctx.paths = [];
      ctx.files.forEach(function(file) {
        ctx.paths = ctx.paths.concat(grunt.file.expand(file.src));
      });
    }
    tags += addFiles(ctx.files, dest, ctx.paths);

    tags += "";

    // Update the template with found specs.
    tags = grunt.file.read(dest + '/main.html') + tags;
    grunt.file.write(dest + '/main.html', tags);

    grunt.log.writeln(chalk.green('Done.'));
    next();
  }

  function startReporter(ctx, next) {
    ctx.cleanupTimeout = setTimeout(cleanup.bind({}, ctx), ctx.timeout);
    grunt.log.write('Starting Reporter...');

    ctx.messages = [];
    ctx.inprogress = '';
    ctx.web = http.createServer(function (req, res) {
      if (req.url === '/') {
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.end('' +
                'Reporting server for grunt-jasmine-chromeapp.' +
                '');
      } else if (req.url === '/put') {
        req.setEncoding('utf8');
        req.on('data', function (chunk) {
          ctx.inprogress += chunk;
        });
        req.on('end', function () {
          ctx.messages.push(ctx.inprogress);
          ctx.inprogress = '';
          res.setHeader('Access-Control-Allow-Origin', '*');
          res.end(ctx.keepRunner? 'thanks!': 'kill');
          if (ctx.onMessage) {
            ctx.onMessage();
          }
        });
      } else if (req.url === '/ready') {
        grunt.log.writeln(chalk.green('Done.'));
        res.end('Okay.');
        if (ctx.onMessage) {
          ctx.onMessage();
        }
      }
    }).listen(ctx.port);

    grunt.log.writeln(chalk.green('Done.'));
    next();
  }

  function startChrome(ctx, next) {
    grunt.log.write('Starting Chrome...');
    ctx.onMessage = next;

    if (process.platform === "darwin") {
      ctx.flags = ctx.flags.concat("--no-startup-window");
    }

    ctx.chrome = chrome([
        "--no-first-run",
        "--force-app-mode",
        "--apps-keep-chrome-alive-in-tests",
        "--load-and-launch-app=" + ctx.outfile,
        "--user-data-dir=" + ctx.outfile + '/profile'
    ].concat(ctx.flags), ctx.binary);
  }

  function testPoll(ctx, cb) {
    if (ctx.messages.length > 0) {
      cb();
    } else {
      setTimeout(testPoll.bind({}, ctx, cb), 500);
    }
  }

  function runTests(ctx, next) {
    grunt.log.write('Running Tests...');
    clearTimeout(ctx.cleanupTimeout);
    ctx.onMessage = function () {
      grunt.log.writeln(chalk.green('Done.'));
      next();
    };
  }

  function finishTests(ctx, next) {
    grunt.log.write('Reporting on Tests...');
    testPoll(ctx, function (ctx) {
      grunt.log.writeln(chalk.green('Done.'));
      var parse = JSON.parse(ctx.messages[0]),
        spec,
        i = 0;

      ctx.status = {failed: 0};
      for (i = 0; i < parse.length; i += 1) {
        spec = parse[i];
        if (process.stdout.clearLine) {
          process.stdout.clearLine();
          process.stdout.cursorTo(0);
          if (spec.status === 'passed') {
            grunt.log.writeln(chalk.green.bold('✓') + '\t' + spec.fullName);
          } else if (spec.status === 'failed') {
            ctx.status.failed += 1;
            grunt.log.writeln(chalk.red.bold('X') + '\t' + spec.fullName);
          } else {
            grunt.log.writeln(chalk.yellow.bold('*') + '\t' + spec.fullName);
          }
        } else {
          if (spec.status === 'passed') {
            grunt.log.writeln('✓' + spec.fullName);
          } else if (spec.status === 'failed') {
            ctx.status.failed += 1;
            grunt.log.writeln('X' + spec.fullName);
          } else {
            grunt.log.writeln('*' + spec.fullName);
          }
        }
      }
      next();
    }.bind({}, ctx));
  }

  function cleanup(ctx, next) {
    var good = true;
    if (ctx.cleanupTimeout) {
      clearTimeout(ctx.cleanupTimeout);
    }
    if (!next) {
      next = ctx.done;
    }
    if (!ctx.status) {
      grunt.log.error(chalk.red('Timed out'));
      good = false;
    } else if (ctx.status.failed === 0) {
      grunt.log.ok(chalk.green('0 failures'));
    } else {
      grunt.log.error(chalk.red(ctx.status.failed + ' failures'));
      good = false;
    }
    if (ctx.keepRunner) {
      ctx.chrome.on('close', function () {
        grunt.file['delete'](ctx.outfile);
        ctx.web.close();
        next(good || new Error('One or more tests failed.'));
      });
      return;
    }

    ctx.web.close();
    if (ctx.chrome) {
      ctx.chrome.on('close', function () {
        grunt.file['delete'](ctx.outfile);
      });
      ctx.chrome.kill();
    } else {
      grunt.file['delete'](ctx.outfile);
    }

    next(good || new Error('One or more tests failed.'));
  }

  grunt.registerMultiTask('jasmine_chromeapp', pkg.description, function () {
    var done = this.async(),
      name = this.target,
      ctx = this.options({
        template: __dirname + '/../tasks/jasmine-chromeapp',
        version: '2.0.0',
        outfile: '.build',
        paths: undefined,
        binary: undefined,
        keepRunner: false,
        port: 9989,
        timeout : 30000,
        flags: []
      });

    if (grunt.option('debug')) {
      grunt.log.debug(JSON.stringify(ctx));
    }

    ctx.files = this.files;
    ctx.done = done;

    process.on('SIGINT', function () {
      cleanup(ctx);
    });

    async.series([
      async.apply(buildSpec, ctx),
      async.apply(startReporter, ctx),
      async.apply(startChrome, ctx),
      async.apply(runTests, ctx),
      async.apply(finishTests, ctx),
      async.apply(cleanup, ctx)
    ], function (good) {
      ctx.done(good);
    });
  });
};
<|endoftext|>


<commit_before>describe('The dp-toggle-layer-selection component', function () {
    var $compile,
        $rootScope,
        store,
        ACTIONS;

    beforeEach(function () {
        angular.mock.module(
            'dpMap',
            {
                store: {
                    dispatch: function () {}
                }
            }
        );

        angular.mock.inject(function (_$compile_, _$rootScope_, _store_, _ACTIONS_) {
            $compile = _$compile_;
            $rootScope = _$rootScope_;
            store = _store_;
            ACTIONS = _ACTIONS_;
        });

        spyOn(store, 'dispatch');
    });

    function getComponent (overlays, showLayerSelection) {
        var component,
            element,
            scope;

        element = document.createElement('dp-toggle-layer-selection');
        element.setAttribute('overlays', 'overlays');
        element.setAttribute('show-layer-selection', 'showLayerSelection');

        scope = $rootScope.$new();
        scope.overlays = overlays;
        scope.showLayerSelection = showLayerSelection;

        component = $compile(element)(scope);
        scope.$apply();

        return component;
    }

    it('has a toggle that can trigger both SHOW_LAYER_SELECTION and HIDE_LAYER_SELECTION', function () {
        var component;

        // When showActiveOverlays is false
        component = getComponent([], false);
        component.find('button').click();

        expect(store.dispatch).toHaveBeenCalledTimes(1);
        expect(store.dispatch).toHaveBeenCalledWith({
            type: ACTIONS.SHOW_LAYER_SELECTION
        });

        // When showActiveOverlays is true
        component = getComponent([], true);
        component.find('button').click();

        expect(store.dispatch).toHaveBeenCalledTimes(2);
        expect(store.dispatch).toHaveBeenCalledWith({
            type: ACTIONS.HIDE_LAYER_SELECTION
        });
    });

    it('has different styling depending on showLayerSelection', function () {
        var component;

        // When showActiveOverlays is false
        component = getComponent([], false);
        expect(component.find('.c-toggle-layer-selection').attr('class'))
            .not.toContain('c-toggle-layer-selection--mirrored');

        // When showActiveOverlays is true
        component = getComponent([], true);
        expect(component.find('.c-toggle-layer-selection').attr('class'))
            .toContain('c-toggle-layer-selection--mirrored');
    });

    it('has a different title and alt attribute depending on showLayerSelection', function () {
        var component;

        // When showActiveOverlays is false
        component = getComponent([], false);

        expect(component.find('button').attr('title'))
            .not.toContain('Meer kaartlagen');

        // When showActiveOverlays is true
        component = getComponent([], true);

        expect(component.find('button').attr('title'))
            .toContain('Sluit paneel voor selecteren kaartlagen');
    });
});
<commit_msg>updated unit tests<commit_after>describe('The dp-toggle-layer-selection component', function () {
    var $compile,
        $rootScope,
        store,
        ACTIONS;

    beforeEach(function () {
        angular.mock.module(
            'dpMap',
            {
                store: {
                    dispatch: function () {}
                }
            }
        );

        angular.mock.inject(function (_$compile_, _$rootScope_, _store_, _ACTIONS_) {
            $compile = _$compile_;
            $rootScope = _$rootScope_;
            store = _store_;
            ACTIONS = _ACTIONS_;
        });

        spyOn(store, 'dispatch');
    });

    function getComponent (overlays, showLayerSelection) {
        var component,
            element,
            scope;

        element = document.createElement('dp-toggle-layer-selection');
        element.setAttribute('overlays', 'overlays');
        element.setAttribute('show-layer-selection', 'showLayerSelection');

        scope = $rootScope.$new();
        scope.overlays = overlays;
        scope.showLayerSelection = showLayerSelection;

        component = $compile(element)(scope);
        scope.$apply();

        return component;
    }

    it('has a toggle that can trigger both SHOW_LAYER_SELECTION and HIDE_LAYER_SELECTION', function () {
        var component;

        // When showActiveOverlays is false
        component = getComponent([], false);
        component.find('button').click();

        expect(store.dispatch).toHaveBeenCalledTimes(1);
        expect(store.dispatch).toHaveBeenCalledWith({
            type: ACTIONS.SHOW_LAYER_SELECTION
        });

        // When showActiveOverlays is true
        component = getComponent([], true);
        component.find('button').click();

        expect(store.dispatch).toHaveBeenCalledTimes(2);
        expect(store.dispatch).toHaveBeenCalledWith({
            type: ACTIONS.HIDE_LAYER_SELECTION
        });
    });

    it('has different styling depending on showLayerSelection', function () {
        var component;

        // When showActiveOverlays is false
        component = getComponent([], false);
        expect(component.find('.c-toggle-layer-selection').attr('class'))
            .toContain('c-toggle-layer-selection--closed');

        // When showActiveOverlays is true
        component = getComponent([], true);
        expect(component.find('.c-toggle-layer-selection').attr('class'))
            .toContain('c-toggle-layer-selection--opened');
    });

    it('has a different title and alt attribute depending on showLayerSelection', function () {
        var component;

        // When showActiveOverlays is false
        component = getComponent([], false);

        expect(component.find('button').attr('title'))
            .not.toContain('Meer kaartlagen');

        // When showActiveOverlays is true
        component = getComponent([], true);

        expect(component.find('button').attr('title'))
            .toContain('Sluit paneel voor selecteren kaartlagen');
    });
});
<|endoftext|>


<commit_before>//utils Test
var utils = require('../controllerUtils.js');
var assert = require('assert');

//email tests
//invalid email returns false
var badEmail = "ojh12345@gmail";
var goodEmail = "ojh12345@yahoo.com";
//if(utils.verifyEmail(badEmail)==false){
//    console.log('Test Passed')
//}
//else{
//    console.log('Test failed')
//}
assert.equal(utils.validEmail(badEmail), false, ['invalid email']);
assert.equal(utils.validEmail(goodEmail), true, ['valid email']);

//password test
//invalid password return false, needs to be 8-16 characters
var badPass = "1234";
var goodPass = "1234567890";
assert.equal(utils.validPassword(badPass), false, ['invalid password']);
assert.equal(utils.validPassword(goodPass), true, ['valid password']);

//token test
//invalid token returns false, needs to be 36 characters
var badToken = "1245720983";
var goodToken = "123456789012345678901234567890123456";
assert.equal(utils.validToken(badToken), false, ['invalid token']);
assert.equal(utils.validToken(goodToken), true, ["valid token"]);
<commit_msg>Update utilsTest.js<commit_after>//utils Test
var utils = require('../controllerUtils.js');
var assert = require('assert');

//email tests
//invalid email returns false
var badEmail = "ojh12345@gmail";
var goodEmail = "ojh12345@yahoo.com";
if(utils.validEmail(badEmail)==false){
    console.log('Test Passed')
}
else{
    console.log('Test failed')
}
//assert.equal(utils.validEmail(badEmail), false, ['invalid email']);
//assert.equal(utils.validEmail(goodEmail), true, ['valid email']);

//password test
//invalid password return false, needs to be 8-16 characters
//var badPass = "1234";
//var goodPass = "1234567890";
//assert.equal(utils.validPassword(badPass), false, ['invalid password']);
//assert.equal(utils.validPassword(goodPass), true, ['valid password']);

//token test
//invalid token returns false, needs to be 36 characters
//var badToken = "1245720983";
//var goodToken = "123456789012345678901234567890123456";
//assert.equal(utils.validToken(badToken), false, ['invalid token']);
//assert.equal(utils.validToken(goodToken), true, ["valid token"]);
<|endoftext|>


<commit_before>//META{"name":"ownerTag"}*//

var ownerTag = function () {};

(function () {
    "use strict";

    // This is super hackish, and will likely break as Discord's internal API changes
    // Anything using this or what it returns should be prepared to catch some exceptions
    function getInternalProps(e) {
        try {
            var reactInternal = e[Object.keys(e).filter(k => k.startsWith("__reactInternalInstance"))[0]];
            return reactInternal._currentElement._owner._instance.props;
        } catch (err) {
            return undefined;
        }
    }

    // Get the relevant user ID for an element, or undefined
    function getUserId(e) {
        var props = getInternalProps(e);
        if (props === undefined) {
            return undefined;
        }

        try {
            return props.user.id;
        } catch (err) {
            // Catch TypeError if no user in props
        }

        try {
            return props.message.author.id;
        } catch (err) {
            // Catch TypeError if no message in props
        }

        return undefined;
    }

    // Get the relevant user color for an element, or undefined
    function getUserColor(e) {
        var props = getInternalProps(e);
        if (props === undefined) {
            return undefined;
        }

        try {
            return props.message.colorString;
        } catch (err) {
            // Catch TypeError if no message in props
        }

        // Return colorString or undefined if not present
        return props.colorString;
    }

    // Get the relevant guild owner ID for an element, or undefined
    function getOwnerId(e) {
        var props = getInternalProps(e);
        if (props === undefined) {
            return undefined;
        }

        try {
            return props.guild.ownerId;
        } catch (err) {
            // Catch TypeError if no guild in props
        }

        return undefined;
    }

    function processServer(mutation) {
        var ownerId, usernames, tags;

        // Get the ID of the server's owner
        ownerId = getOwnerId($(".guild.selected")[0]);
        if (ownerId === undefined) {
            // (Probably) not looking at a server
            return;
        }

        // Check if changed servers and need to redo member list tagging
        // React likes to make minimal changes to the DOM, so owner tags
        // will stick around (or not get added) when a user is in both this
        // and the previous server.
        if (ownerId !== prevOwnerId) {
            // Get all visible members
            usernames = $(".member-username-inner");
            // Remove tags that were added
            usernames.siblings(".kawaii-tag").remove();
            usernames.filter(".kawaii-tagged").removeClass("kawaii-tagged");
            // Add the set of message authors affected by this mutation
            usernames = usernames.add(mutationFind(mutation, ".user-name"));
        } else {
            // Get the set of message authors and server members affected by this mutation
            usernames = mutationFind(mutation, ".member-username-inner, .user-name");
        }

        // Process usernames
        usernames.filter((_, e) => getUserId(e) === ownerId).not(".kawaii-tagged").after(function () {
            var color = getUserColor(this);
            var tag = $("<span>", {
                class: "bot-tag kawaii-tag",
            }).text("OWNER");
            if (color !== null) {
                tag.css("background-color", color);
            }
            return tag;
        }).addClass("kawaii-tagged");

        tags = mutationFind(mutation, ".discord-tag");

        tags.filter((_, e) => getUserId(e) === ownerId).not(".kawaii-tagged")
            .append($("<span>", {class: "bot-tag bot-tag-invert kawaii-tag"}).text("OWNER"))
            .addClass("kawaii-tagged");

        prevOwnerId = ownerId;
    }

    function processProfile(mutation) {
        var profile, userId, guilds;

        profile = mutationFind(mutation, "#user-profile-modal");
        userId = getUserId(profile[0]);
        if (userId === undefined) {
            // (Probably) not looking at a profile
            return;
        }

        guilds = profile.find(".guild .avatar-large");

        guilds.filter((_, e) => getOwnerId(e) === userId).parent().not(".kawaii-tagged")
            .append($("<span>", {class: "bot-tag kawaii-tag"}).text("OWNER"))
            .addClass("kawaii-tagged");
    }

    // Helper function for finding all elements matching selector affected by a mutation
    function mutationFind(mutation, selector) {
        var target = $(mutation.target), addedNodes = $(mutation.addedNodes);
        var mutated = target.add(addedNodes).filter(selector);
        var descendants = addedNodes.find(selector);
        var ancestors = target.parents(selector);
        return mutated.add(descendants).add(ancestors);
    }

    var prevOwnerId;

    ownerTag.prototype.start = function () {
        // process entire document
        var mutation = {target: document, addedNodes: [document]};
        processServer(mutation);
        processProfile(mutation);
    };

    ownerTag.prototype.observer = function (mutation) {
        processServer(mutation);
        processProfile(mutation);
    };

    ownerTag.prototype.load = function () {};

    ownerTag.prototype.unload = function () {};

    ownerTag.prototype.stop = function () {
        // Remove tags that were added
        $(".kawaii-tag").remove();
        $(".kawaii-tagged").removeClass("kawaii-tagged");
    };

    ownerTag.prototype.getSettingsPanel = function () {
        return "";
    };

    ownerTag.prototype.getName = function () {
        return "Owner Tags";
    };

    ownerTag.prototype.getDescription = function () {
        return "Show a tag next to a server owner's name";
    };

    ownerTag.prototype.getVersion = function () {
        return "1.2.0";
    };

    ownerTag.prototype.getAuthor = function () {
        return "noodlebox";
    };
})();
<commit_msg>Bump OwnerTag version to 1.2.1<commit_after>//META{"name":"ownerTag"}*//

var ownerTag = function () {};

(function () {
    "use strict";

    // This is super hackish, and will likely break as Discord's internal API changes
    // Anything using this or what it returns should be prepared to catch some exceptions
    function getInternalProps(e) {
        try {
            var reactInternal = e[Object.keys(e).filter(k => k.startsWith("__reactInternalInstance"))[0]];
            return reactInternal._currentElement._owner._instance.props;
        } catch (err) {
            return undefined;
        }
    }

    // Get the relevant user ID for an element, or undefined
    function getUserId(e) {
        var props = getInternalProps(e);
        if (props === undefined) {
            return undefined;
        }

        try {
            return props.user.id;
        } catch (err) {
            // Catch TypeError if no user in props
        }

        try {
            return props.message.author.id;
        } catch (err) {
            // Catch TypeError if no message in props
        }

        return undefined;
    }

    // Get the relevant user color for an element, or undefined
    function getUserColor(e) {
        var props = getInternalProps(e);
        if (props === undefined) {
            return undefined;
        }

        try {
            return props.message.colorString;
        } catch (err) {
            // Catch TypeError if no message in props
        }

        // Return colorString or undefined if not present
        return props.colorString;
    }

    // Get the relevant guild owner ID for an element, or undefined
    function getOwnerId(e) {
        var props = getInternalProps(e);
        if (props === undefined) {
            return undefined;
        }

        try {
            return props.guild.ownerId;
        } catch (err) {
            // Catch TypeError if no guild in props
        }

        return undefined;
    }

    function processServer(mutation) {
        var ownerId, usernames, tags;

        // Get the ID of the server's owner
        ownerId = getOwnerId($(".guild.selected")[0]);
        if (ownerId === undefined) {
            // (Probably) not looking at a server
            return;
        }

        // Check if changed servers and need to redo member list tagging
        // React likes to make minimal changes to the DOM, so owner tags
        // will stick around (or not get added) when a user is in both this
        // and the previous server.
        if (ownerId !== prevOwnerId) {
            // Get all visible members
            usernames = $(".member-username-inner");
            // Remove tags that were added
            usernames.siblings(".kawaii-tag").remove();
            usernames.filter(".kawaii-tagged").removeClass("kawaii-tagged");
            // Add the set of message authors affected by this mutation
            usernames = usernames.add(mutationFind(mutation, ".user-name"));
        } else {
            // Get the set of message authors and server members affected by this mutation
            usernames = mutationFind(mutation, ".member-username-inner, .user-name");
        }

        // Process usernames
        usernames.filter((_, e) => getUserId(e) === ownerId).not(".kawaii-tagged").after(function () {
            var color = getUserColor(this);
            var tag = $("<span>", {
                class: "bot-tag kawaii-tag",
            }).text("OWNER");
            if (color !== null) {
                tag.css("background-color", color);
            }
            return tag;
        }).addClass("kawaii-tagged");

        tags = mutationFind(mutation, ".discord-tag");

        tags.filter((_, e) => getUserId(e) === ownerId).not(".kawaii-tagged")
            .append($("<span>", {class: "bot-tag bot-tag-invert kawaii-tag"}).text("OWNER"))
            .addClass("kawaii-tagged");

        prevOwnerId = ownerId;
    }

    function processProfile(mutation) {
        var profile, userId, guilds;

        profile = mutationFind(mutation, "#user-profile-modal");
        userId = getUserId(profile[0]);
        if (userId === undefined) {
            // (Probably) not looking at a profile
            return;
        }

        guilds = profile.find(".guild .avatar-large");

        guilds.filter((_, e) => getOwnerId(e) === userId).parent().not(".kawaii-tagged")
            .append($("<span>", {class: "bot-tag kawaii-tag"}).text("OWNER"))
            .addClass("kawaii-tagged");
    }

    // Helper function for finding all elements matching selector affected by a mutation
    function mutationFind(mutation, selector) {
        var target = $(mutation.target), addedNodes = $(mutation.addedNodes);
        var mutated = target.add(addedNodes).filter(selector);
        var descendants = addedNodes.find(selector);
        var ancestors = target.parents(selector);
        return mutated.add(descendants).add(ancestors);
    }

    var prevOwnerId;

    ownerTag.prototype.start = function () {
        // process entire document
        var mutation = {target: document, addedNodes: [document]};
        processServer(mutation);
        processProfile(mutation);
    };

    ownerTag.prototype.observer = function (mutation) {
        processServer(mutation);
        processProfile(mutation);
    };

    ownerTag.prototype.load = function () {};

    ownerTag.prototype.unload = function () {};

    ownerTag.prototype.stop = function () {
        // Remove tags that were added
        $(".kawaii-tag").remove();
        $(".kawaii-tagged").removeClass("kawaii-tagged");
    };

    ownerTag.prototype.getSettingsPanel = function () {
        return "";
    };

    ownerTag.prototype.getName = function () {
        return "Owner Tags";
    };

    ownerTag.prototype.getDescription = function () {
        return "Show a tag next to a server owner's name";
    };

    ownerTag.prototype.getVersion = function () {
        return "1.2.1";
    };

    ownerTag.prototype.getAuthor = function () {
        return "noodlebox";
    };
})();
<|endoftext|>