<commit_before>var moment    = require('moment');
var React     = require('react/addons');
var PropTypes = React.PropTypes;
var _         = require('underscore');

var DEFAULT_ITEM = {
  name     : '',
  classes  : '',
  cellRefs : []
};

var HvReactAgenda = React.createClass({

  propTypes: {
    locale          : PropTypes.string.isRequired,
    startDate       : PropTypes.instanceOf(Date),
    startAtTime     : PropTypes.number.isRequired,
    rowsPerHour     : PropTypes.oneOf([1,2,3,4]).isRequired,
    numberOfDays    : PropTypes.oneOf([1,2,3,4,5,6,7]).isRequired,
    items           : PropTypes.arrayOf(PropTypes.shape({
      name          : PropTypes.string,
      startDateTime : PropTypes.instanceOf(Date).isRequired,
      endDateTime   : PropTypes.instanceOf(Date).isRequired,
      classes       : PropTypes.string
    })),
    onItemSelect    : PropTypes.func
  },

  getDefaultProps: function() {
    return {
      locale       : 'en',
      startAtTime  : 8,
      rowsPerHour  : 4,
      numberOfDays : 5
    }
  },

  getInitialState: function() {
    return {
      date              : moment(),
      items             : {},
      itemOverlayStyles : {},
      highlightedCells  : [],
      focusedCell       : null
    }
  },

  componentWillMount: function() {
    if (this.props.startDate) {
      this.setState({date: moment(this.props.startDate)});
    }

    if (this.props.items) {
      this.setState({items: this.mapItems(this.props.items)});
    }
  },

  componentDidMount: function() {
    // move to start time (this only happens once)
    var scrollContainer = this.refs.agendaScrollContainer.getDOMNode();
    var rowToScrollTo   = this.refs["hour-" + this.props.startAtTime].getDOMNode();
    scrollContainer.scrollTop = rowToScrollTo.offsetTop;
  },

  componentWillReceiveProps: function() {
    if (this.props.items) {
      this.setState({items: this.mapItems(this.props.items)});
    }

    if (this.props.startDate) {
      this.setState({date: this.props.startDate});
    }
  },

  nextRange: function() {
    this.setState({date: this.state.date.add(this.props.numberOfDays, 'days')});
  },

  prevRange: function() {
    this.setState({date: this.state.date.subtract(this.props.numberOfDays, 'days')});
  },

  mapItems: function(itemsArray) {
    var itemsMap = {};
    itemsArray.forEach(function(item) {
      var interval      = (60/this.props.rowsPerHour);
      var offsetMinutes = item.startDateTime.getMinutes() % interval;
      var start         = moment(item.startDateTime).subtract(offsetMinutes, "minutes").toDate();
      var end           = item.endDateTime;
      var duration      = moment.duration(moment(end).diff(moment(start)));
      var rows          = Math.ceil(duration.asHours()/(interval/60));

      var cellRefs = [];
      for (var i = 0; i < rows; i++) {
        var ref = moment(start).add(i*interval, 'minutes').format('YYYY-MM-DDTHH:mm:ss');
        cellRefs.push(ref);
      }

      cellRefs.forEach(function(ref) {
        var newItem = _.omit(item, 'classes');
        newItem.classes  = (itemsMap[ref]) ? (itemsMap[ref].classes + ' ' + item.classes) : (item.classes || '');
        newItem.cellRefs = cellRefs;
        itemsMap[ref] = newItem;
      });
    }, this);

    return itemsMap;
  },

  getHeaderColumns: function() {
    var cols = [];
    for (var i = 0; i < this.props.numberOfDays; i++) {
      cols.push(moment(this.state.date).add(i, 'days').toDate());
    }
    return cols;
  },

  getBodyRows: function() {
    var rows = [];
    var interval = (60/this.props.rowsPerHour);
    for (var i = 0; i < 24*this.props.rowsPerHour; i++) {
      rows.push(moment(this.state.date).startOf('day').add(Math.floor(i*interval), 'minutes'));
    }
    return rows;
  },

  getMinuteCells: function(rowMoment) {
    var cells = [];
    for (var i = 0; i < this.props.numberOfDays; i++) {
      var cellRef = moment(rowMoment).add(i, 'days').format('YYYY-MM-DDTHH:mm:ss');
      cells.push({
        cellRef: cellRef,
        item: this.state.items[cellRef] || DEFAULT_ITEM
      });
    }
    return cells;
  },

  getItemOverlayStyle: function(cellRef) {
    if (this.state.focusedCell === cellRef && _.contains(this.state.highlightedCells, cellRef)) {
      var firstCell   = this.refs[_.first(this.state.highlightedCells)].getDOMNode();
      var lastCell    = this.refs[_.last(this.state.highlightedCells)].getDOMNode();

      var firstCellY  = firstCell.offsetTop - firstCell.scrollTop + firstCell.clientTop;
      var lastCellY   = lastCell.offsetTop - lastCell.scrollTop + lastCell.clientTop;

      return {
        display: 'block',
        zIndex: 1,
        position: 'absolute',
        width: firstCell.offsetWidth,
        textAlign: 'center',
        top: firstCell.offsetTop + ((lastCellY-firstCellY)/2)
      };
    } else {
      return {
        display: 'none'
      };
    }
  },

  handleMouseEnter: function(cell) {
    if (cell.item) {
      this.setState({focusedCell: cell.cellRef});
      this.setState({highlightedCells: cell.item.cellRefs});
    }
  },

  handleMouseLeave: function(cell) {
    this.setState({focusedCell: null});
    this.setState({highlightedCells: []});
  },

  handleMouseClick: function(cell) {
    if (this.props.onItemSelect && cell.item.startDateTime) {
      this.props.onItemSelect(_.omit(cell.item, 'cellRefs'));
    }
  },

  render: function() {

    var renderHeaderColumns = function(col, i) {
      var headerLabel = moment(col);
      headerLabel.locale(this.props.locale);
      return (

          {headerLabel.format('ddd M\/D')}

      );
    };

    var renderBodyRows = function(row, i) {
      if (i % this.props.rowsPerHour === 0) {
        var ref = "hour-" + Math.floor(i/this.props.rowsPerHour);
        var timeLabel = moment(row);
        timeLabel.locale(this.props.locale);
        return (

            {timeLabel.format('LT')}
            {this.getMinuteCells(row).map(renderMinuteCells, this)}

        );
      } else {
        return (

            {this.getMinuteCells(row).map(renderMinuteCells, this)}

        );
      }
    };

    var renderMinuteCells = function(cell, i) {
      var cellClasses = {
        'agenda__cell'      : true,
        '--hovered'         : _.contains(this.state.highlightedCells, cell.cellRef),
        '--hovered-first'   : _.contains(this.state.highlightedCells, cell.cellRef) && (_.first(this.state.highlightedCells) === cell.cellRef),
        '--hovered-last'    : _.contains(this.state.highlightedCells, cell.cellRef) && (_.last(this.state.highlightedCells)  === cell.cellRef)
      };
      cellClasses[cell.item.classes] = true;

      var classSet = React.addons.classSet(cellClasses);

      return (

              {cell.item.name}

      );
    };

    return (

«

»

                {this.getHeaderColumns().map(renderHeaderColumns, this)}

              {this.getBodyRows().map(renderBodyRows, this)}

    );
  }

});

module.exports = HvReactAgenda;
<commit_msg>Cast startDate as momentjs object.<commit_after>var moment    = require('moment');
var React     = require('react/addons');
var PropTypes = React.PropTypes;
var _         = require('underscore');

var DEFAULT_ITEM = {
  name     : '',
  classes  : '',
  cellRefs : []
};

var HvReactAgenda = React.createClass({

  propTypes: {
    locale          : PropTypes.string.isRequired,
    startDate       : PropTypes.instanceOf(Date),
    startAtTime     : PropTypes.number.isRequired,
    rowsPerHour     : PropTypes.oneOf([1,2,3,4]).isRequired,
    numberOfDays    : PropTypes.oneOf([1,2,3,4,5,6,7]).isRequired,
    items           : PropTypes.arrayOf(PropTypes.shape({
      name          : PropTypes.string,
      startDateTime : PropTypes.instanceOf(Date).isRequired,
      endDateTime   : PropTypes.instanceOf(Date).isRequired,
      classes       : PropTypes.string
    })),
    onItemSelect    : PropTypes.func
  },

  getDefaultProps: function() {
    return {
      locale       : 'en',
      startAtTime  : 8,
      rowsPerHour  : 4,
      numberOfDays : 5
    }
  },

  getInitialState: function() {
    return {
      date              : moment(),
      items             : {},
      itemOverlayStyles : {},
      highlightedCells  : [],
      focusedCell       : null
    }
  },

  componentWillMount: function() {
    if (this.props.startDate) {
      this.setState({date: moment(this.props.startDate)});
    }

    if (this.props.items) {
      this.setState({items: this.mapItems(this.props.items)});
    }
  },

  componentDidMount: function() {
    // move to start time (this only happens once)
    var scrollContainer = this.refs.agendaScrollContainer.getDOMNode();
    var rowToScrollTo   = this.refs["hour-" + this.props.startAtTime].getDOMNode();
    scrollContainer.scrollTop = rowToScrollTo.offsetTop;
  },

  componentWillReceiveProps: function() {
    if (this.props.items) {
      this.setState({items: this.mapItems(this.props.items)});
    }

    if (this.props.startDate) {
      this.setState({date: moment(this.props.startDate)});
    }
  },

  nextRange: function() {
    this.setState({date: this.state.date.add(this.props.numberOfDays, 'days')});
  },

  prevRange: function() {
    this.setState({date: this.state.date.subtract(this.props.numberOfDays, 'days')});
  },

  mapItems: function(itemsArray) {
    var itemsMap = {};
    itemsArray.forEach(function(item) {
      var interval      = (60/this.props.rowsPerHour);
      var offsetMinutes = item.startDateTime.getMinutes() % interval;
      var start         = moment(item.startDateTime).subtract(offsetMinutes, "minutes").toDate();
      var end           = item.endDateTime;
      var duration      = moment.duration(moment(end).diff(moment(start)));
      var rows          = Math.ceil(duration.asHours()/(interval/60));

      var cellRefs = [];
      for (var i = 0; i < rows; i++) {
        var ref = moment(start).add(i*interval, 'minutes').format('YYYY-MM-DDTHH:mm:ss');
        cellRefs.push(ref);
      }

      cellRefs.forEach(function(ref) {
        var newItem = _.omit(item, 'classes');
        newItem.classes  = (itemsMap[ref]) ? (itemsMap[ref].classes + ' ' + item.classes) : (item.classes || '');
        newItem.cellRefs = cellRefs;
        itemsMap[ref] = newItem;
      });
    }, this);

    return itemsMap;
  },

  getHeaderColumns: function() {
    var cols = [];
    for (var i = 0; i < this.props.numberOfDays; i++) {
      cols.push(moment(this.state.date).add(i, 'days').toDate());
    }
    return cols;
  },

  getBodyRows: function() {
    var rows = [];
    var interval = (60/this.props.rowsPerHour);
    for (var i = 0; i < 24*this.props.rowsPerHour; i++) {
      rows.push(moment(this.state.date).startOf('day').add(Math.floor(i*interval), 'minutes'));
    }
    return rows;
  },

  getMinuteCells: function(rowMoment) {
    var cells = [];
    for (var i = 0; i < this.props.numberOfDays; i++) {
      var cellRef = moment(rowMoment).add(i, 'days').format('YYYY-MM-DDTHH:mm:ss');
      cells.push({
        cellRef: cellRef,
        item: this.state.items[cellRef] || DEFAULT_ITEM
      });
    }
    return cells;
  },

  getItemOverlayStyle: function(cellRef) {
    if (this.state.focusedCell === cellRef && _.contains(this.state.highlightedCells, cellRef)) {
      var firstCell   = this.refs[_.first(this.state.highlightedCells)].getDOMNode();
      var lastCell    = this.refs[_.last(this.state.highlightedCells)].getDOMNode();

      var firstCellY  = firstCell.offsetTop - firstCell.scrollTop + firstCell.clientTop;
      var lastCellY   = lastCell.offsetTop - lastCell.scrollTop + lastCell.clientTop;

      return {
        display: 'block',
        zIndex: 1,
        position: 'absolute',
        width: firstCell.offsetWidth,
        textAlign: 'center',
        top: firstCell.offsetTop + ((lastCellY-firstCellY)/2)
      };
    } else {
      return {
        display: 'none'
      };
    }
  },

  handleMouseEnter: function(cell) {
    if (cell.item) {
      this.setState({focusedCell: cell.cellRef});
      this.setState({highlightedCells: cell.item.cellRefs});
    }
  },

  handleMouseLeave: function(cell) {
    this.setState({focusedCell: null});
    this.setState({highlightedCells: []});
  },

  handleMouseClick: function(cell) {
    if (this.props.onItemSelect && cell.item.startDateTime) {
      this.props.onItemSelect(_.omit(cell.item, 'cellRefs'));
    }
  },

  render: function() {

    var renderHeaderColumns = function(col, i) {
      var headerLabel = moment(col);
      headerLabel.locale(this.props.locale);
      return (

          {headerLabel.format('ddd M\/D')}

      );
    };

    var renderBodyRows = function(row, i) {
      if (i % this.props.rowsPerHour === 0) {
        var ref = "hour-" + Math.floor(i/this.props.rowsPerHour);
        var timeLabel = moment(row);
        timeLabel.locale(this.props.locale);
        return (

            {timeLabel.format('LT')}
            {this.getMinuteCells(row).map(renderMinuteCells, this)}

        );
      } else {
        return (

            {this.getMinuteCells(row).map(renderMinuteCells, this)}

        );
      }
    };

    var renderMinuteCells = function(cell, i) {
      var cellClasses = {
        'agenda__cell'      : true,
        '--hovered'         : _.contains(this.state.highlightedCells, cell.cellRef),
        '--hovered-first'   : _.contains(this.state.highlightedCells, cell.cellRef) && (_.first(this.state.highlightedCells) === cell.cellRef),
        '--hovered-last'    : _.contains(this.state.highlightedCells, cell.cellRef) && (_.last(this.state.highlightedCells)  === cell.cellRef)
      };
      cellClasses[cell.item.classes] = true;

      var classSet = React.addons.classSet(cellClasses);

      return (

              {cell.item.name}

      );
    };

    return (

«

»

                {this.getHeaderColumns().map(renderHeaderColumns, this)}

              {this.getBodyRows().map(renderBodyRows, this)}

    );
  }

});

module.exports = HvReactAgenda;
<|endoftext|>


<commit_before>/*! IoradWebWidget 2015-06-18 */
this.JST=this.JST||{},this.JST["templates/freshdeskCategoryList.hbs"]=Handlebars.template({1:function(a,b,c,d){var e,f=b.helperMissing,g="function",h=this.escapeExpression;return'<option value="'+h((e=null!=(e=b.id||(null!=a?a.id:a))?e:f,typeof e===g?e.call(a,{name:"id",hash:{},data:d}):e))+'">'+h((e=null!=(e=b.name||(null!=a?a.name:a))?e:f,typeof e===g?e.call(a,{name:"name",hash:{},data:d}):e))+"</option>\n"},compiler:[6,">= 2.0.0-beta.1"],main:function(a,b,c,d){var e;return null!=(e=b.each.call(a,null!=a?a.categories:a,{name:"each",hash:{},fn:this.program(1,d,0),inverse:this.noop,data:d}))?e:""},useData:!0}),this.JST["templates/freshdeskFolderList.hbs"]=Handlebars.template({1:function(a,b,c,d){var e,f;return'<select id="'+this.escapeExpression((f=null!=(f=b.id||(null!=a?a.id:a))?f:b.helperMissing,"function"==typeof f?f.call(a,{name:"id",hash:{},data:d}):f))+'" class="invisible-options">\n'+(null!=(e=b.each.call(a,null!=a?a.folders:a,{name:"each",hash:{},fn:this.program(2,d,0),inverse:this.noop,data:d}))?e:"")+"</select>\n"},2:function(a,b,c,d){var e,f=b.helperMissing,g="function",h=this.escapeExpression;return'    <option value="'+h((e=null!=(e=b.id||(null!=a?a.id:a))?e:f,typeof e===g?e.call(a,{name:"id",hash:{},data:d}):e))+'">'+h((e=null!=(e=b.name||(null!=a?a.name:a))?e:f,typeof e===g?e.call(a,{name:"name",hash:{},data:d}):e))+"</option> \n"},compiler:[6,">= 2.0.0-beta.1"],main:function(a,b,c,d){var e;return null!=(e=b.each.call(a,null!=a?a.categories:a,{name:"each",hash:{},fn:this.program(1,d,0),inverse:this.noop,data:d}))?e:""},useData:!0}),this.JST["templates/mainLayout.hbs"]=Handlebars.template({compiler:[6,">= 2.0.0-beta.1"],main:function(a,b,c,d){return'
\n
\n

Create a Solution

\n

Categories

<select id="categorySelector"></select>

\n

Solutions

\n
\n            ADD\n
\n
\n
\n\n\n'},useData:!0}),this.JST["templates/modalTemplate.hbs"]=Handlebars.template({compiler:[6,">= 2.0.0-beta.1"],main:function(a,b,c,d){var e,f,g=this.escapeExpression,h=this.lambda;return'
\n

\n
\n
\n            The solution '+g((f=null!=(f=b.articleTitle||(null!=a?a.articleTitle:a))?f:b.helperMissing,"function"==typeof f?f.call(a,{name:"articleTitle",hash:{},data:d}):f))+' has been successfully created.\n
\n

\n        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>VIEW ARTICLE\n
\n
\n'},useData:!0});var ioradWebWidget=function(a,b){return a={freshdesk:{},config:{},util:{},templates:{}}}(ioradWebWidget||{});ioradWebWidget.templates={mainLayout:function(){var a=JST["templates/mainLayout.hbs"];return a()},freshDeskModal:function(a,b){var c=JST["templates/modalTemplate.hbs"];return c({article:a,articleTitle:b})},categoryOptionTemplate:function(a){var b=JST["templates/freshdeskCategoryList.hbs"];return b({categories:a})},folderListTemplate:function(a){var b=JST["templates/freshdeskFolderList.hbs"];return b({categories:a})}},ioradWebWidget.freshdesk=function(a){var b="/solution/categories.json",c="/solution/categories/{category_id}/folders/{folder_id}/articles.json",d=function(){return{dataType:"json",contentType:"application/json"}};return a.listCategories=function(){var a=d();return a.type="GET",a.url=b,a},a.createArticle=function(a,b,e){var f=d();return f.type="POST",f.url=c.replace("{category_id}",a.toString()).replace("{folder_id}",b.toString()),f.data=e,f},a}(ioradWebWidget.freshdesk||{}),function(a,b){var c=a(".c-wrapper");c.html(ioradWebWidget.templates.mainLayout()+c.html());var d=function(){iorad=b.iorad||{};var c=function(){return a.ajax(ioradWebWidget.freshdesk.listCategories())},d=function(b,c,d){return a.ajax(ioradWebWidget.freshdesk.createArticle(b,c,d))},e=function(b){var c=a(b.srcElement);a("#foldersList").children().each(function(b,c){a(c).addClass("invisible-options")}),a("#"+c.val()).removeClass("invisible-options")},f=function(b){var c=[];b.each(function(a){c.push({id:a.category.id,name:a.category.name,folders:a.category.folders})});var d=a("#categorySelector");d.html(ioradWebWidget.templates.categoryOptionTemplate(c)),a("#foldersList").html(ioradWebWidget.templates.folderListTemplate(c)),a("#"+d.val()).removeClass("invisible-options"),d.click(e)};c().then(f,function(a){}),iorad.init({env:"live"},function(){var b=0;a("#newTutorialBtn").click(function(){a("body").addClass("iorad-loading"),iorad.createTutorial(),b=setTimeout(function(){a("body").removeClass("iorad-loading")},5e3),a("#iorad-editor").off().load(function(){a("body").addClass("iorad-open"),clearTimeout(b)})}),iorad.on("editor:close",function(c){a("body").removeClass("iorad-open iorad-loading"),clearTimeout(b);var e=iorad.getEmbeddedPlayerUrl(c.uid,c.tutorialId,c.tutorialTitle),f=a(e);f.attr("src",f.attr("src")+"#viewsteps");var g=a("#categorySelector").val(),h=a("#"+g).val(),i={solution_article:{title:c.tutorialTitle,folder_id:h,description:"
"+f.prop("outerHTML").replace(/\"/g,"'")+"
"}},j=JSON.stringify(i);d(g,h,j).then(function(b){var d={id:b.article.id,categoryId:g,folderId:h};a("#successModal").length>0&&a("#successModal").remove(),a("body").append(ioradWebWidget.templates.freshDeskModal(d,c.tutorialTitle)),a("#successModal").modal("show")},function(a){})})})},e=function(a){var c=10,d=function(){b.iorad?a():b.setTimeout(d,c)};b.setTimeout(d,c)};e(d)}(jQuery,window);<commit_msg>dist update on 2015-06-22 03:36:24<commit_after><|endoftext|>


<commit_before>$(function() {
    refreshPages();
    $('#createPageB').on('click', create_PageBus);
});

function create_PageBus() {
    $('#page_title').css('background', '#FFF');
    var title = $('#page_title').val();
    if(!title) {
        $('#page_title').css('background', '#FAA');
        return;
    }

    $.ajax({
		url:'/api/createPageBus',
		type:'GET',
		dataType:'json',
        data:{title:title},
		success:function(data, status, xhr) {
            $('#page_title').val('');
            populatePages(data.pages);
		},
		error:function(xhr, status, error) {
		alert(xhr.responseText);
		console.error(xhr, status, error);
		}
	});
}

function refreshPages() {
    $.ajax({
		url:'/api/get_pages',
		type:'GET',
		dataType:'json',
		success:function(data, status, xhr) {
            populatePages(data.pages);
		},
		error:function(xhr, status, error) {
		alert(xhr.responseText);
		console.error(xhr, status, error);
		}
	});
}

function populatePages(pages) {
    console.log(pages);
    var Pages_str = '';
    for(var page in pages) {
<<<<<<< HEAD:MyLittleBuisness/web/static/js/userIN.js
        //console.log(pages[page]);
        Pages_str += ''+pages[page].title+''+(pages[page].admin ? '(admin)': '')+'
';
=======
        Pages_str += ''+pages[page].title+''+(pages[page].admin ? '(admin)': '')+'
';
>>>>>>> origin/master:MyLittleBuisness/web/static/js/createPageBus.js
    }
    $('#pages').html(Pages_str);
}

<commit_msg>update<commit_after>$(function() {
    refreshPages();
    $('#createPageB').on('click', create_PageBus);
});

function create_PageBus() {
    $('#page_title').css('background', '#FFF');
    var title = $('#page_title').val();
    if(!title) {
        $('#page_title').css('background', '#FAA');
        return;
    }

    $.ajax({
		url:'/api/createPageBus',
		type:'GET',
		dataType:'json',
        data:{title:title},
		success:function(data, status, xhr) {
            $('#page_title').val('');
            populatePages(data.pages);
		},
		error:function(xhr, status, error) {
		alert(xhr.responseText);
		console.error(xhr, status, error);
		}
	});
}

function refreshPages() {
    $.ajax({
		url:'/api/get_pages',
		type:'GET',
		dataType:'json',
		success:function(data, status, xhr) {
            populatePages(data.pages);
		},
		error:function(xhr, status, error) {
		alert(xhr.responseText);
		console.error(xhr, status, error);
		}
	});
}

function populatePages(pages) {
    console.log(pages);
    var Pages_str = '';
    for(var page in pages) {
        Pages_str += ''+pages[page].title+''+(pages[page].admin ? '(admin)': '')+'
';

    }
    $('#pages').html(Pages_str);
}

<|endoftext|>


<commit_before>/**
 * Uploads latest and versioned copies of schemas to Azure Storage. Reads from the /yaml folder and converts to JSON, rather than reading from the JSON folder directly.
 */

/* eslint-disable
  global-require,
  no-await-in-loop,
  no-console,
*/

// IMPORTS
if (!process.env.AZURE_STORAGE_CONNECTION_STRING) {
  require(`../../credentials/azure-storage-dlx`);
}

const chalk         = require(`chalk`);
const path          = require(`path`);
const { promisify } = require(`util`);
const semverRegExp  = require(`semver-regex`)();
const storage       = require(`azure-storage`).createBlobService();
const yamljs        = require(`yamljs`);

const {
  readdir,
  readFile,
} = require(`fs`).promises;

// PROMISES
const getBlobProperties = promisify(storage.getBlobProperties).bind(storage);
const storeFile         = promisify(storage.createBlockBlobFromText).bind(storage);

// VARIABLES
const jsonMedia = `application/schema+json; charset=utf-8`;
const yamlMedia = `text/yaml; charset=utf-8`;

const schemaNameRegExp = /schemas\/(?<schemaName>.+)-(?<version>.+).json/;
const schemasPath      = path.join(__dirname, `../schemas/yaml`);

// METHODS

/**
 * A Promisifed version of createBlockBlobFromText
 * @param  {String}  blobName                                               The name to upload the file as
 * @param  {String}  schema                                                 The text of the file
 * @param  {String}  [contentType=`application/schema+json; charset=utf-8`] Content type (MIME / media type)
 * @return {Promise}
 */
async function uploadBlob(blobName, schema, contentType = jsonMedia) {

  const hasVersion = semverRegExp.test(blobName);
  let blobProperties;

  // If file is versioned, check whether version already exists and throw a warning if it does
  if (hasVersion) {
    try {
      blobProperties = await getBlobProperties(`schemas`, blobName);
      console.warn(chalk.bgRed(`${blobName} already exists. Upload skipped.`));
    } catch (e) {
      // Don't handle exceptions; allow code to continue executing
    }
  }

  // Upload the file if its versioned form doesn't already exist
  if (!blobProperties) {

    await storeFile(
      `schemas`,
      blobName,
      schema,
      {
        contentSettings: {
          contentLanguage: `en-US`,
          contentType,
        },
      }
    );

    if (hasVersion) console.log(chalk.green(`${blobName} uploaded.`));

  }

}

/**
 * Uploads each of the files associated with a single schema, based on the filename of the schema
 * @param  {String}  filename Filename of the schema (e.g. `Language.yml`)
 * @return {Promise}
 */
async function uploadSchemaFiles(filename) {

  const schemaPath = path.join(schemasPath, filename);
  const yamlSchema = await readFile(schemaPath, `utf8`); // YAML schema
  const schema     = yamljs.parse(yamlSchema);           // JS schema
  const jsonSchema = JSON.stringify(schema, null, 2);    // JSON schema

  const {
    schemaName,
    version,
  } = schemaNameRegExp.exec(schema.$id).groups;

  await Promise.all([
    uploadBlob(schemaName, jsonSchema),                                // plain unversioned
    uploadBlob(`${schemaName}-${version}`, jsonSchema),                // plain versioned
    uploadBlob(`${schemaName}.json`, jsonSchema),                      // JSON unversioned
    uploadBlob(`${schemaName}-${version}.json`, jsonSchema),           // JSON versioned
    uploadBlob(`${schemaName}.yml`, yamlSchema, yamlMedia),            // YAML unversioned
    uploadBlob(`${schemaName}-${version}.yml`, yamlSchema, yamlMedia), // YAML versioned
  ]);

}

// TOP-LEVEL SCRIPT
void async function upload() {

  const filenames = await readdir(schemasPath, `utf8`);

  for (const filename of filenames) {
    await uploadSchemaFiles(filename);
  }

}();
<commit_msg>update upload script<commit_after>/**
 * Uploads latest and versioned copies of schemas to Azure Storage. Reads from the /yaml folder and converts to JSON, rather than reading from the JSON folder directly.
 */

/* eslint-disable
  global-require,
  no-await-in-loop,
  no-console,
*/

// IMPORTS
if (!process.env.AZURE_STORAGE_CONNECTION_STRING) {
  require(`../../credentials/azure-storage-dlx`);
}

const chalk         = require(`chalk`);
const path          = require(`path`);
const { promisify } = require(`util`);
const semverRegExp  = require(`semver-regex`)();
const storage       = require(`azure-storage`).createBlobService(process.env.AZURE_STORAGE_ACCOUNT, process.env.AZURE_STORAGE_ACCESS_KEY);
const yamljs        = require(`yamljs`);

const {
  readdir,
  readFile,
} = require(`fs`).promises;

// PROMISES
const getBlobProperties = promisify(storage.getBlobProperties).bind(storage);
const storeFile         = promisify(storage.createBlockBlobFromText).bind(storage);

// VARIABLES
const jsonMedia = `application/schema+json; charset=utf-8`;
const yamlMedia = `text/yaml; charset=utf-8`;

const schemaNameRegExp = /schemas\/(?<schemaName>.+)-(?<version>.+).json/;
const schemasPath      = path.join(__dirname, `../schemas/yaml`);

// METHODS

/**
 * A Promisifed version of createBlockBlobFromText
 * @param  {String}  blobName                                               The name to upload the file as
 * @param  {String}  schema                                                 The text of the file
 * @param  {String}  [contentType=`application/schema+json; charset=utf-8`] Content type (MIME / media type)
 * @return {Promise}
 */
async function uploadBlob(blobName, schema, contentType = jsonMedia) {

  const hasVersion = semverRegExp.test(blobName);
  let blobProperties;

  // If file is versioned, check whether version already exists and throw a warning if it does
  if (hasVersion) {
    try {
      blobProperties = await getBlobProperties(`schemas`, blobName);
      console.warn(chalk.bgRed(`${blobName} already exists. Upload skipped.`));
    } catch (e) {
      // Don't handle exceptions; allow code to continue executing
    }
  }

  // Upload the file if its versioned form doesn't already exist
  if (!blobProperties) {

    await storeFile(
      `schemas`,
      blobName,
      schema,
      {
        contentSettings: {
          contentLanguage: `en-US`,
          contentType,
        },
      }
    );

    if (hasVersion) console.log(chalk.green(`${blobName} uploaded.`));

  }

}

/**
 * Uploads each of the files associated with a single schema, based on the filename of the schema
 * @param  {String}  filename Filename of the schema (e.g. `Language.yml`)
 * @return {Promise}
 */
async function uploadSchemaFiles(filename) {

  const schemaPath = path.join(schemasPath, filename);
  const yamlSchema = await readFile(schemaPath, `utf8`); // YAML schema
  const schema     = yamljs.parse(yamlSchema);           // JS schema
  const jsonSchema = JSON.stringify(schema, null, 2);    // JSON schema

  const {
    schemaName,
    version,
  } = schemaNameRegExp.exec(schema.$id).groups;

  await Promise.all([
    uploadBlob(schemaName, jsonSchema),                                // plain unversioned
    uploadBlob(`${schemaName}-${version}`, jsonSchema),                // plain versioned
    uploadBlob(`${schemaName}.json`, jsonSchema),                      // JSON unversioned
    uploadBlob(`${schemaName}-${version}.json`, jsonSchema),           // JSON versioned
    uploadBlob(`${schemaName}.yml`, yamlSchema, yamlMedia),            // YAML unversioned
    uploadBlob(`${schemaName}-${version}.yml`, yamlSchema, yamlMedia), // YAML versioned
  ]);

}

// TOP-LEVEL SCRIPT
void async function upload() {

  const filenames = await readdir(schemasPath, `utf8`);

  for (const filename of filenames) {
    await uploadSchemaFiles(filename);
  }

}();
<|endoftext|>


<commit_before>var test = require('tape');
var iteratee = require('./iteratee');

test('amp-iteratee', function (t) {
    t.end();
});<commit_msg>adding tests for iteratee. closes #62<commit_after>var test = require('tape');
var iteratee = require('./iteratee');
var createCallback = require('amp-create-callback');
var matches = require('amp-matches');
var property = require('amp-property');

test('amp-iteratee', function (t) {
    t.equal(iteratee()('hi'), 'hi', 'calling with empty values should return an identity function');
    t.equal(iteratee(null)('hi'), 'hi', 'calling with null should return an identity function');

    var context = {};
    var actualContext;
    var func = function () {
        actualContext = this;
        return 'hi';
    };

    t.equal(iteratee(func).toString(), createCallback(func).toString(), 'fn should return same as createCallback');
    t.equal(iteratee(func, context)(), 'hi', 'fn should return same as createCallback');
    t.equal(context, actualContext, 'should have retained passed context');

    // passing an object
    var matcher = {awesome: true};
    var func1 = iteratee(matcher);
    var func2 = matches(matcher);

    var personToCheck = {name: 'someone', awesome: true};

    t.strictEqual(func1(personToCheck), true, 'should create a matcher that returns true');
    t.equal(func1(personToCheck), func2(personToCheck), 'when given a function, creates callback that works same as createCallback');

    // passing a property name
    var propertyName = 'name';

    func1 = iteratee(propertyName);
    func2 = property(propertyName);

    var personToCheck = {name: 'someone', awesome: true};

    t.equal(func1(personToCheck), 'someone', 'works like property when passed a string');
    t.equal(func1(personToCheck), func2(personToCheck), 'gives sames result as property');

    t.end();
});
<|endoftext|>


<commit_before>/*
 * grunt-deploy-dump
 *
 * Copyright (c) 2014 Matthieu Lassalvy
 * Licensed under the MIT license.
 *
 * https://raw.githubusercontent.com/sequelize/sequelize-auto/master/lib/index.js
 * https://github.com/sequelize/sequelize/wiki/API-Reference-DataTypes
 * https://github.com/sequelize/sequelize/wiki/API-Reference
 * http://sequelizejs.com/docs/1.7.8/installation
 *
 */
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50*/
/*global require, module, console*/
module.exports = function (grunt) {

    'use strict';

    var Q = require('q'),
        Path = require('path'),
        jshint = require('jshint').JSHINT,
        parseString = require('xml2js').parseString,
        format = require('js-beautify').js_beautify;

    var HelperBuilder = require('./../lib/helper-builder'),
        EntityBuilder = require('./../lib/entity-builder'),
        StringUtils = require('./../thirdparty/smile/lib/utils/string-utils');

    /**
     *
     * Build models from Doctrine XML schemas
     *
     */
    grunt.registerMultiTask('build_models', 'Build models from Doctrine XML schemas', function () {

        var requires = this.requiresConfig('build_models', 'build_models.files', 'build_models.files.dest', 'build_models.files.src');
        // Verification de la configuration
        // de la tache Grunt
        if (requires) {

            var str, xml, builder,
                index = 0,
                entries = [],
                done = this.async(),
                options = this.options({
                    rootName: false,
                    extension: 'dcm',
                    helpers: 'helpers/'
                });
            this.files.forEach(function (f) {
                if (f.src.length) {
                    // creation du dossier des helpers
                    if ((grunt.option('helpers') || grunt.option('helpers-reset')) && !grunt.file.exists(options.helpers)) {
                        grunt.file.mkdir(options.helpers);
                    }

                    // creation du dossier des modeles
                    if (!grunt.file.exists(f.dest)) {
                        grunt.file.mkdir(f.dest);
                    }

                    grunt.log.subhead('Start parsing doctrine files');
                    var sources = f.src.filter(function (filepath) {
                        if (grunt.file.isFile(filepath)) {
                            return filepath;
                        } else {
                            return false;
                        }
                    }).map(function (filepath) {
                        if (filepath) {
                            grunt.log.debug('Loading ' + filepath);
                            xml = grunt.file.read(filepath);
                            parseString(xml, {
                                mergeAttrs: true,
                                explicitRoot: (grunt.util.kindOf(options.root) !== 'string')
                            }, function (err, result) {
                                if (err === null) {
                                    grunt.log.debug('Parsing ' + filepath);
                                    // Pyramid of Doom
                                    Q.fcall(function () {
                                        try {
                                            var builder = new EntityBuilder(grunt);
                                            return builder.parse((options.root ? result : result[options.root]));

                                        } catch (e) {
                                            grunt.log.debug('Failed on ' + filepath);
                                            grunt.log.debug(e.stack);
                                            grunt.fail.warn(e);
                                        }
                                    }).then(function (content) {
                                        if (content) {

                                            //if (content && jshint(content)) {
                                            var bs = Path.basename(filepath, Path.extname(filepath));
                                            if (bs.indexOf('.' + options.extension) !== -1) {
                                                bs = Path.basename(bs, Path.extname(bs));
                                            }
                                            var fname = Path.join(Path.normalize(f.dest), bs) + '.js';
                                            var data = format(content, {
                                                indent_size: 4
                                            }); // Format
                                            grunt.log.debug('Creating ' + fname); // Write
                                            var w = grunt.file.write(fname, data);
                                            return (w) ? Path.basename(filepath, Path.extname(filepath)) : false;

                                        } else {
                                            grunt.fail.warn(new Error('Uncorrect file format ' + filepath));

                                        }
                                    }).then(function (name) {
                                        // Creation des helpers
                                        if (grunt.option('helpers') || grunt.option('helpers-reset')) {
                                            var n = name,
                                                funcs = [];
                                            if (n.indexOf('.' + options.extension) !== -1) {
                                                n = n.split('.' + options.extension)[0];
                                            }
                                            n = StringUtils.capitalize(n) + 'Helper';
                                            var hcontent = '',
                                                hbuilder = new HelperBuilder(grunt, n),
                                                hname = Path.join(Path.normalize(options.helpers), n);
                                            if (grunt.option('helpers-reset')) {
                                                if (grunt.file.exists(hname + '.js')) {
                                                    grunt.log.debug('Deleting helper ' + hname + '.js');
                                                    grunt.file.delete(hname + '.js');
                                                }
                                            } else {
                                                grunt.log.debug('Copy ' + hname);
                                                grunt.file.copy('./' + hname + '.js', hname + '.tmp.js');
                                                var m = require('../' + hname + '.tmp');
                                                (Object.keys(m.prototype)).map(function (funcName) {
                                                    if (funcName !== '__super__') {
                                                        var method = m.prototype[funcName].toString();
                                                        method = StringUtils.trimEndLines(method);
                                                        funcs.push(funcName + ': ' + method);
                                                    }
                                                });
                                                grunt.log.debug('delete ' + hname + '.tmp.js');
                                                grunt.file.delete(hname + '.tmp.js');
                                            }
                                            grunt.log.debug('Creating helper ' + hname);
                                            hcontent = hbuilder.create(funcs);
                                            return grunt.file.write(hname + '.js', format(hcontent, {
                                                indent_size: 4
                                            }));
                                        } else {
                                            return true;
                                        }
                                    }).fin(function () {
                                        index++;
                                        if (index >= entries.length) {
                                            done();
                                        }
                                    });
                                    // endof Pyramid of Doom
                                } else {
                                    grunt.fail.warn('Unable to parse file ' + filepath);
                                }
                            });
                        }
                    });
                } else {
                    grunt.log.ok('No files to export');
                    done();
                }
            });
        }
    });
};
<commit_msg>ajout de l'extend des helpers<commit_after>/*
 * grunt-deploy-dump
 *
 * Copyright (c) 2014 Matthieu Lassalvy
 * Licensed under the MIT license.
 *
 * https://raw.githubusercontent.com/sequelize/sequelize-auto/master/lib/index.js
 * https://github.com/sequelize/sequelize/wiki/API-Reference-DataTypes
 * https://github.com/sequelize/sequelize/wiki/API-Reference
 * http://sequelizejs.com/docs/1.7.8/installation
 *
 */
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50*/
/*global require, module, console*/
module.exports = function (grunt) {

    'use strict';

    var Q = require('q'),
        Path = require('path'),
        jshint = require('jshint').JSHINT,
        parseString = require('xml2js').parseString,
        format = require('js-beautify').js_beautify;

    var HelperBuilder = require('./../lib/helper-builder'),
        EntityBuilder = require('./../lib/entity-builder'),
        StringUtils = require('./../thirdparty/smile/lib/utils/string-utils');

    /**
     *
     * Build models from Doctrine XML schemas
     *
     */
    grunt.registerMultiTask('build_models', 'Build models from Doctrine XML schemas', function () {

        var requires = this.requiresConfig('build_models', 'build_models.files', 'build_models.files.dest', 'build_models.files.src');
        // Verification de la configuration
        // de la tache Grunt
        if (requires) {

            var str, xml, builder,
                index = 0,
                entries = [],
                done = this.async(),
                options = this.options({
                    rootName: false,
                    extension: 'dcm',
                    helpers: 'helpers/'
                });
            this.files.forEach(function (f) {
                if (f.src.length) {
                    // creation du dossier des helpers
                    if ((grunt.option('helpers') || grunt.option('helpers-reset')) && !grunt.file.exists(options.helpers)) {
                        grunt.file.mkdir(options.helpers);
                    }

                    // creation du dossier des modeles
                    if (!grunt.file.exists(f.dest)) {
                        grunt.file.mkdir(f.dest);
                    }

                    grunt.log.subhead('Start parsing doctrine files');
                    var sources = f.src.filter(function (filepath) {
                        if (grunt.file.isFile(filepath)) {
                            return filepath;
                        } else {
                            return false;
                        }
                    }).map(function (filepath) {
                        if (filepath) {
                            grunt.log.debug('Loading ' + filepath);
                            xml = grunt.file.read(filepath);
                            parseString(xml, {
                                mergeAttrs: true,
                                explicitRoot: (grunt.util.kindOf(options.root) !== 'string')
                            }, function (err, result) {
                                if (err === null) {
                                    grunt.log.debug('Parsing ' + filepath);
                                    // Pyramid of Doom
                                    Q.fcall(function () {
                                        try {
                                            var builder = new EntityBuilder(grunt);
                                            return builder.parse((options.root ? result : result[options.root]));

                                        } catch (e) {
                                            grunt.log.debug('Failed on ' + filepath);
                                            grunt.log.debug(e.stack);
                                            grunt.fail.warn(e);
                                        }
                                    }).then(function (content) {
                                        if (content) {

                                            //if (content && jshint(content)) {
                                            var bs = Path.basename(filepath, Path.extname(filepath));
                                            if (bs.indexOf('.' + options.extension) !== -1) {
                                                bs = Path.basename(bs, Path.extname(bs));
                                            }
                                            var fname = Path.join(Path.normalize(f.dest), bs) + '.js';
                                            var data = format(content, {
                                                indent_size: 4
                                            }); // Format
                                            grunt.log.debug('Creating ' + fname); // Write
                                            var w = grunt.file.write(fname, data);
                                            return (w) ? Path.basename(filepath, Path.extname(filepath)) : false;

                                        } else {
                                            grunt.fail.warn(new Error('Uncorrect file format ' + filepath));

                                        }
                                    }).then(function (name) {
                                        // Creation des helpers
                                        if (grunt.option('helpers') || grunt.option('helpers-reset')) {
                                            var n = name,
                                                funcs = [];
                                            if (n.indexOf('.' + options.extension) !== -1) {
                                                n = n.split('.' + options.extension)[0];
                                            }
                                            n = StringUtils.capitalize(n) + 'Helper';
                                            var hcontent = '',
                                                hbuilder = new HelperBuilder(grunt, n),
                                                hname = Path.join(Path.normalize(options.helpers), n);
                                            if (grunt.option('helpers-reset')) {
                                                if (grunt.file.exists(hname + '.js')) {
                                                    grunt.log.debug('Deleting helper ' + hname + '.js');
                                                    grunt.file.delete(hname + '.js');
                                                }
                                            } else {
                                                try {
                                                    grunt.log.debug('Copy ' + hname);
                                                    grunt.file.copy(hname + '.js', hname + '.tmp.js');
                                                    var required = Path.join(process.cwd(), hname + '.tmp');
                                                    var m = require(required);
                                                    (Object.keys(m.prototype)).map(function (funcName) {
                                                        if (funcName !== '__super__') {
                                                            var method = m.prototype[funcName].toString();
                                                            method = StringUtils.trimEndLines(method);
                                                            funcs.push(funcName + ': ' + method);
                                                        }
                                                    });
                                                    grunt.log.debug('delete ' + hname + '.tmp.js');
                                                    grunt.file.delete(hname + '.tmp.js');
                                                } catch(e){
                                                    grunt.log.fail(e);
                                                }
                                            }
                                            grunt.log.debug('Creating helper ' + hname);
                                            hcontent = hbuilder.create(funcs);
                                            return grunt.file.write(hname + '.js', format(hcontent, {
                                                indent_size: 4
                                            }));
                                        } else {
                                            return true;
                                        }
                                    }).fin(function () {
                                        index++;
                                        if (index >= entries.length) {
                                            done();
                                        }
                                    });
                                    // endof Pyramid of Doom
                                } else {
                                    grunt.fail.warn('Unable to parse file ' + filepath);
                                }
                            });
                        }
                    });
                } else {
                    grunt.log.ok('No files to export');
                    done();
                }
            });
        }
    });
};
<|endoftext|>


<commit_before>/* Emoticons Plugin
 * This is a chat-plugin for Emoticons
 * You will need a line in parser to actually
 * parse this so that it works. (See command-parser.js)
 * Credits: panpawn, jd
 */

var fs = require('fs');
var path = require('path');
var serialize = require('node-serialize');
var emotes = {};

if (typeof Gold === 'undefined') global.Gold = {};

Gold.emoticons = {
	chatEmotes: {},
	processEmoticons: function(text) {
		var patterns = [],
		metachars = /[[\]{}()*+?.\\|^$\-,&#\s]/g,
		self = this;
		for (var i in this.chatEmotes) {
			if (this.chatEmotes.hasOwnProperty(i)) {
				patterns.push('(' + i.replace(metachars, "\\$&") + ')');
			}
		}
		return text.replace(new RegExp(patterns.join('|'), 'g'), function(match) {
			return typeof self.chatEmotes[match] != 'undefined' ?
				'' :
				match;
		});
	},
	processChatData: function(user, room, connection, message) {
		var match = false;
		for (var i in this.chatEmotes) {
			if (message.indexOf(i) >= 0) {
				match = true;
			}
		}
		switch (Users.ShadowBan.checkBanned(user) && match) {
			case true:
				origmsg = message;
				message = Tools.escapeHTML(message);
				message = this.processEmoticons(message);
				user.sendTo(room, '|html|' +
					user.getIdentity(room).substr(0,1) + '<button class="astext" name="parseCommand" value="/user ' +
					user.name + '">' + '' + Tools.escapeHTML(user.name) + ':</button> ' + message + '
'
				);
				room.update();
				Users.ShadowBan.addMessage(user, "To " + room, origmsg);
				break;
			case false:
				if (!room.emoteStatus && room.type === 'chat' || !room.type === 'battle') {
					kitty = message = this.processEmoticons(message);
					var message = Tools.escapeHTML(kitty);
					return (message);
					return;
				} else if (room.emoteStatus || room.type === 'battle') {
					if (!match || message.charAt(0) === '!') return true;
					message = Tools.escapeHTML(message);
					message = this.processEmoticons(message);
					if (user.hiding) {
						room.addRaw(' <button class="astext" name="parseCommand" value="/user ' +
						user.name + '">' + '' + Tools.escapeHTML(user.name) + ':</button> ' + message + '
');
						room.update();
					}
					room.addRaw(user.getIdentity(room).substr(0,1) + '<button class="astext" name="parseCommand" value="/user ' +
					user.name + '">' + '' + Tools.escapeHTML(user.name) + ':</button> ' + message + '
');
					room.update();
					return false;
				}
				break;
		}
	}
};

//commands

function loadEmotes() {
	try {
		emotes = serialize.unserialize(fs.readFileSync('config/emotes.json', 'utf8'));
		Object.merge(Gold.emoticons.chatEmotes, emotes);
	} catch (e) {}
}
setTimeout(function(){loadEmotes();},1000);

function saveEmotes() {
	try {
		fs.writeFileSync('config/emotes.json',serialize.serialize(emotes));
		Object.merge(Gold.emoticons.chatEmotes, emotes);
	} catch (e) {}
}

exports.commands = {
	emotes: 'ezemote',
	temotes: 'ezemote',
	temote: 'ezemote',
	emote: 'ezemote',
	ec: 'ezemote',
	ezemote: function (target, room, user) {
		if (!target) target = "help";
		var parts = target.split(',');
		for (var u in parts) parts[u] = parts[u].trim();

		try {
			switch (toId(parts[0])) {
				case 'add':
					if (!this.can('ban')) return this.sendReply("Access denied.");
					if (!(parts[2] || parts[3])) return this.sendReply("Usage: /ezemote add, [emote], [link]");
					var emoteName = parts[1];
					if (Gold.emoticons.chatEmotes[emoteName]) return this.sendReply("ERROR - the emote: " + emoteName + " already exists.");
					var link = parts.splice(2, parts.length).join(',');
					var fileTypes = [".gif",".png",".jpg"];
					if (fileTypes.indexOf(link.substr(-4)) < 0) return this.sendReply("ERROR: the emote you are trying to add must be a gif, png, or jpg.");
					emotes[emoteName] = Gold.emoticons.chatEmotes[emoteName] = link;
					saveEmotes();
					this.sendReply("The emote " + emoteName + " has been added.");
					this.logModCommand(user.name + " added the emote " + emoteName);
					Rooms.rooms.staff.add(Tools.escapeHTML(user.name) + " added the emote " + emoteName);
					room.update();
					break;
				case 'rem':
				case 'remove':
				case 'del':
				case 'delete':
					if (!this.can('ban')) return this.sendReply("Access denied.");
					if (!parts[1]) return this.sendReplyBox("/ezemote remove, [emote]");
					var emoteName = parts[1];
					if (!Gold.emoticons.chatEmotes[emoteName]) return this.sendReply("ERROR - the emote: " + emoteName + " does not exist.");
					delete Gold.emoticons.chatEmotes[emoteName];
					delete emotes[emoteName];
					saveEmotes();
					this.sendReply("The emote " + emoteName + " was removed.");
					this.logModCommand("The emote " + emoteName + " was removed by " + user.name);
					Rooms.rooms.staff.add("The emote " + emoteName + " was removed by " + Tools.escapeHTML(user.name));
					room.update();
					break;
				case 'list':
					if (!this.canBroadcast()) return;
					if (this.broadcasting) return this.sendReply("ERROR: this command is too spammy to broadcast.  Use / instead of ! to see it for yourself.");
					var output = "There's a total of " + Object.size(emotes) + " emotes added with this command:
";
					for (var e in emotes) {
						output += e + "
";
					}
					this.sendReplyBox(output);
					break;
				case 'view':
					if (!this.canBroadcast()) return;
					//if (this.broadcasting) return this.sendReply("ERROR: this command is too spammy to broadcast.  Use / instead of ! to see it for yourself.");
					var name = Object.keys(Gold.emoticons.chatEmotes);
					emoticons = [];
					var len = name.length;
					while (len--) {
						emoticons.push((Gold.emoticons.processEmoticons(name[(name.length - 1) - len]) + ' ' + name[(name.length - 1) - len]));
					}
					this.sendReplyBox("List of emoticons (" + Object.size(emotes) + "):

" + emoticons.join(' ').toString());
					break;
				case 'object':
					if (!this.canBroadcast()) return;
					if (this.broadcasting) return this.sendReply("ERROR: this command is too spammy to broadcast.  Use / instead of ! to see it for yourself.");
					this.sendReplyBox("Gold.emoticons.chatEmotes = " + fs.readFileSync('config/emotes.json','utf8'));
					break;
				case 'status':
					if (!this.canBroadcast()) return;
					if (!parts[1]) {
						switch (room.emoteStatus) {
							case true:
								this.sendReply("Chat emotes are currently enabled in this room.");
								break;
							case false:
								this.sendReply("Chat emotes are currently disabled in this room.");
								break;
						}
					} else {
						switch (toId(parts[1])) {
							case 'on':
							case 'enable':
								if (!this.can('declare', null, room)) return this.sendReply("Access denied.");
								if (room.type === 'battle') return this.sendReply("Chat emoticons are already enabled in battle rooms by default and cannot be turned off.");
								if (room.emoteStatus) return this.sendReply("Chat emoticons are already enabled in this room.");
								room.emoteStatus = true;
								room.chatRoomData.emoteStatus = room.emoteStatus;
								Rooms.global.writeChatRoomData();
								//room.add(Tools.escapeHTML(user.name) + ' has enabled chat emoticons in this room.');
								this.add("|raw|
Chat Emoticons have been enabled!
Everyone in this room may use chat emoticons.");
								room.update();
								this.privateModCommand("(" + user.name + " has enabled chat emoticons in this room)");
								break;
							case 'off':
							case 'disable':
								if (!this.can('declare', null, room)) return this.sendReply("Access denied.");
								if (room.type === 'battle') return this.sendReply("Chat emoticons are already enabled in battle rooms by default and cannot be turned off.");
								if (!room.emoteStatus) return this.sendReply("Chat emoticons are already disabled in this room.");
								room.emoteStatus = false;
								room.chatRoomData.emoteStatus = room.emoteStatus;
								Rooms.global.writeChatRoomData();
								//room.add(Tools.escapeHTML(user.name) + " has disabled chat emoticons in this room.");
								this.add("|raw|
Chat Emoticons have been disabled!
No one in this room may use chat emoticons.");
								room.update();
								this.privateModCommand("(" + user.name + " has disabled chat emoticons in this room)");
								break;
							default:
								this.sendReply("Usage: /ezemote status, [on / off] - Enables or disables the current chat emoticon status.  Requires #, &, ~.");
						}
					}
					break;
				case 'help':
				default:
					if (!this.canBroadcast()) return;
					this.sendReplyBox(
						"
" +
							"EZ-Emoticon Commands:
" +
							"(By: panpawn)
" +
							"/ezemote add, [emote], [link] - Adds a chat emoticon. Requires @, &, ~.
" +
							"/ezemote remove, [emote] - Removes a chat emoticon. Requires @, &, ~.
" +
							"/ezemote status, [on / off] - Enables or disables the status of chat emoticons in the respected room. Requires #, &, ~.
" +
							"/ezemote status - Views the current status of chat emoticons.
" +
							"/ezemote list - Shows the chat emoticons in a list form.
" +
							"/ezemote view - Shows all of the current chat emoticons with the respected image.
" +
							"/ezemote object - Shows the object of Gold.emoticons.chatEmotes. (Mostly for development usage)
" +
							"/ezemote help - Shows this help command.
" +
						"
"
					);
			}
		} catch (e) {
			try {
				Rooms.rooms.development.add(e.stack);
			} catch (e) {
				console.log("ERROR!  The EZ-Emote script has crashed!\n" + e.stack);
			}
		}
	}
};<commit_msg>General updates<commit_after>/* Emoticons Plugin
 * This is a chat-plugin for Emoticons
 * You will need a line in parser to actually
 * parse this so that it works. (See command-parser.js)
 * Credits: panpawn, jd
 */

var fs = require('fs');
var path = require('path');
var serialize = require('node-serialize');
var emotes = {};

if (typeof Gold === 'undefined') global.Gold = {};

Gold.emoticons = {
	chatEmotes: {},
	processEmoticons: function(text) {
		var patterns = [],
		metachars = /[[\]{}()*+?.\\|^$\-,&#\s]/g,
		self = this;
		for (var i in this.chatEmotes) {
			if (this.chatEmotes.hasOwnProperty(i)) {
				patterns.push('(' + i.replace(metachars, "\\$&") + ')');
			}
		}
		return text.replace(new RegExp(patterns.join('|'), 'g'), function(match) {
			return typeof self.chatEmotes[match] != 'undefined' ?
				'' :
				match;
		});
	},
	processChatData: function(user, room, connection, message) {
		var match = false;
		for (var i in this.chatEmotes) {
			if (message.indexOf(i) >= 0) {
				match = true;
			}
		}
		switch (Users.ShadowBan.checkBanned(user) && match) {
			case true:
				origmsg = message;
				message = Tools.escapeHTML(message);
				message = this.processEmoticons(message);
				user.sendTo(room, '|html|' +
					user.getIdentity(room).substr(0,1) + '<button class="astext" name="parseCommand" value="/user ' +
					user.name + '">' + '' + Tools.escapeHTML(user.name) + ':</button> ' + message + '
'
				);
				room.update();
				Users.ShadowBan.addMessage(user, "To " + room, origmsg);
				break;
			case false:
				if (!room.emoteStatus && room.type === 'chat' || !room.type === 'battle') {
					kitty = message = this.processEmoticons(message);
					var message = Tools.escapeHTML(kitty);
					return (message);
					return;
				} else if (room.emoteStatus || room.type === 'battle') {
					if (!match || message.charAt(0) === '!') return true;
					message = Tools.escapeHTML(message);
					message = this.processEmoticons(message);
					if (user.hiding) {
						room.addRaw(' <button class="astext" name="parseCommand" value="/user ' +
						user.name + '">' + '' + Tools.escapeHTML(user.name) + ':</button> ' + message + '
');
						room.update();
					}
					room.addRaw(user.getIdentity(room).substr(0,1) + '<button class="astext" name="parseCommand" value="/user ' +
					user.name + '">' + '' + Tools.escapeHTML(user.name) + ':</button> ' + message + '
');
					room.update();
					return false;
				}
				break;
		}
	}
};

//commands

function loadEmotes() {
	try {
		emotes = serialize.unserialize(fs.readFileSync('config/emotes.json', 'utf8'));
		Object.merge(Gold.emoticons.chatEmotes, emotes);
	} catch (e) {}
}
setTimeout(function(){loadEmotes();},1000);

function saveEmotes() {
	try {
		fs.writeFileSync('config/emotes.json',serialize.serialize(emotes));
		Object.merge(Gold.emoticons.chatEmotes, emotes);
	} catch (e) {}
}

exports.commands = {
	emotes: 'ezemote',
	temotes: 'ezemote',
	temote: 'ezemote',
	emote: 'ezemote',
	ec: 'ezemote',
	ezemote: function (target, room, user) {
		if (!target) target = "help";
		var parts = target.split(',');
		for (var u in parts) parts[u] = parts[u].trim();

		try {
			switch (toId(parts[0])) {
				case 'add':
					if (!this.can('ban')) return this.sendReply("Access denied.");
					if (!(parts[2] || parts[3])) return this.sendReply("Usage: /ezemote add, [emote], [link]");
					var emoteName = parts[1];
					if (Gold.emoticons.chatEmotes[emoteName]) return this.sendReply("ERROR - the emote: " + emoteName + " already exists.");
					var link = parts.splice(2, parts.length).join(',');
					var fileTypes = [".gif",".png",".jpg"];
					if (fileTypes.indexOf(link.substr(-4)) < 0) return this.sendReply("ERROR: the emote you are trying to add must be a gif, png, or jpg.");
					emotes[emoteName] = Gold.emoticons.chatEmotes[emoteName] = link;
					saveEmotes();
					this.sendReply("The emote " + emoteName + " has been added.");
					this.logModCommand(user.name + " added the emote " + emoteName);
					Rooms.rooms.staff.add(Tools.escapeHTML(user.name) + " added the emote " + emoteName);
					room.update();
					break;
				case 'rem':
				case 'remove':
				case 'del':
				case 'delete':
					if (!this.can('ban')) return this.sendReply("Access denied.");
					if (!parts[1]) return this.sendReplyBox("/ezemote remove, [emote]");
					var emoteName = parts[1];
					if (!Gold.emoticons.chatEmotes[emoteName]) return this.sendReply("ERROR - the emote: " + emoteName + " does not exist.");
					delete Gold.emoticons.chatEmotes[emoteName];
					delete emotes[emoteName];
					saveEmotes();
					this.sendReply("The emoticon " + emoteName + " was removed.");
					this.logModCommand("The emoticon " + emoteName + " was removed by " + user.name);
					Rooms.rooms.staff.add("The emoticon " + emoteName + " was removed by " + Tools.escapeHTML(user.name));
					room.update();
					break;
				case 'list':
					if (!this.canBroadcast()) return;
					if (this.broadcasting) return this.sendReply("ERROR: this command is too spammy to broadcast.  Use / instead of ! to see it for yourself.");
					var output = "There's a total of " + Object.size(emotes) + " emoticons added with this command:
";
					for (var e in emotes) {
						output += e + "
";
					}
					this.sendReplyBox(output);
					break;
				case 'view':
					if (!this.canBroadcast()) return;
					//if (this.broadcasting) return this.sendReply("ERROR: this command is too spammy to broadcast.  Use / instead of ! to see it for yourself.");
					var name = Object.keys(Gold.emoticons.chatEmotes);
					emoticons = [];
					var len = name.length;
					while (len--) {
						emoticons.push((Gold.emoticons.processEmoticons(name[(name.length - 1) - len]) + ' ' + name[(name.length - 1) - len]));
					}
					this.sendReplyBox("List of emoticons (" + Object.size(emotes) + "):

" + emoticons.join(' ').toString());
					break;
				case 'object':
					if (!this.canBroadcast()) return;
					if (this.broadcasting) return this.sendReply("ERROR: this command is too spammy to broadcast.  Use / instead of ! to see it for yourself.");
					this.sendReplyBox("Gold.emoticons.chatEmotes = " + fs.readFileSync('config/emotes.json','utf8'));
					break;
				case 'status':
					if (!this.canBroadcast()) return;
					if (!parts[1]) {
						switch (room.emoteStatus) {
							case true:
								this.sendReply("Chat emoticons are currently enabled in this room.");
								break;
							case false:
								this.sendReply("Chat emoticons are currently disabled in this room.");
								break;
						}
					} else {
						switch (toId(parts[1])) {
							case 'on':
							case 'enable':
								if (!this.can('declare', null, room)) return this.sendReply("Access denied.");
								if (room.type === 'battle') return this.sendReply("Chat emoticons are already enabled in battle rooms by default and cannot be turned off.");
								if (room.emoteStatus) return this.sendReply("Chat emoticons are already enabled in this room.");
								room.emoteStatus = true;
								room.chatRoomData.emoteStatus = room.emoteStatus;
								Rooms.global.writeChatRoomData();
								//room.add(Tools.escapeHTML(user.name) + ' has enabled chat emoticons in this room.');
								this.add("|raw|
Chat Emoticons have been enabled!
Everyone in this room may use chat emoticons.");
								room.update();
								this.privateModCommand("(" + user.name + " has enabled chat emoticons in this room)");
								break;
							case 'off':
							case 'disable':
								if (!this.can('declare', null, room)) return this.sendReply("Access denied.");
								if (room.type === 'battle') return this.sendReply("Chat emoticons are already enabled in battle rooms by default and cannot be turned off.");
								if (!room.emoteStatus) return this.sendReply("Chat emoticons are already disabled in this room.");
								room.emoteStatus = false;
								room.chatRoomData.emoteStatus = room.emoteStatus;
								Rooms.global.writeChatRoomData();
								//room.add(Tools.escapeHTML(user.name) + " has disabled chat emoticons in this room.");
								this.add("|raw|
Chat Emoticons have been disabled!
No one in this room may use chat emoticons.");
								room.update();
								this.privateModCommand("(" + user.name + " has disabled chat emoticons in this room)");
								break;
							default:
								this.sendReply("Usage: /ezemote status, [on / off] - Enables or disables the current chat emoticon status.  Requires #, &, ~.");
						}
					}
					break;
				case 'help':
				default:
					if (!this.canBroadcast()) return;
					this.sendReplyBox(
						"
" +
							"EZ-Emoticon Commands:
" +
							"(By: panpawn)
" +
							"/ezemote add, [emote], [link] - Adds a chat emoticon. Requires @, &, ~.
" +
							"/ezemote remove, [emote] - Removes a chat emoticon. Requires @, &, ~.
" +
							"/ezemote status, [on / off] - Enables or disables the status of chat emoticons in the respected room. Requires #, &, ~.
" +
							"/ezemote status - Views the current status of chat emoticons.
" +
							"/ezemote list - Shows the chat emoticons in a list form.
" +
							"/ezemote view - Shows all of the current chat emoticons with the respected image.
" +
							"/ezemote object - Shows the object of Gold.emoticons.chatEmotes. (Mostly for development usage)
" +
							"/ezemote help - Shows this help command.
" +
						"
"
					);
			}
		} catch (e) {
			try {
				Rooms.rooms.development.add(e.stack);
			} catch (e) {
				console.log("ERROR!  The EZ-Emote script has crashed!\n" + e.stack);
			}
		}
	}
};<|endoftext|>


<commit_before>/* Room shop system (economy)
 * This plugin gives each room that is allowed,
 * a custom shop for their room.  Room founders
 * can customize what items they want to be in
 * their shops.  Only certain rooms can have
 * their own shops.
 * by: panpawn and Siiilver
 */

// OBJECT STRUCTURE:
// { 'roomid': { 'item1id': ['item1name', 'item1desc', 'item1price'], 'item2id': ['item2name', 'item2desc', 'item2price'] } }

var fs = require('fs');

const ITEM_CAP = 8; // maximum items a room shop can have
var PATH = 'config/roomshops.json';
var RoomShop = require('../' + PATH);

function saveShop() {
	fs.writeFileSync(PATH, JSON.stringify(RoomShop));
}

function getName(user) {
	return '' + Tools.escapeHTML(user) + '';
}

function getRoomShop (room) {
	var output = "" + room.title + " Room Shop
" +
	    '
' +
	    '
Item	Description	Price
';
	for (var i in RoomShop[room.id]) {
	    var item = RoomShop[room.id][i];
	    var name = item[0], desc = item[1], price = item[2];
		output += '
<button name="send" value="/roomshop buy, ' + name + '">' + name + '</button>	' + desc + '	' + price + '
';
	}
	return output + '
Note: As per server rules, global staff are not responsible for scams via a room shop.  However, if severe enough, report it to a global staff and if there was a rule broken, action will be taken.';
}

exports.commands = {
	roomshop: function(target, room, user) {
		if (!room.founder) return this.errorReply("This room is not designed to have a room shop.");

		target = target.split(',');
		for (var u in target) target[u] = target[u].trim();
		if (!RoomShop[room.id]) RoomShop[room.id] = {};
		var RS = RoomShop[room.id];
		switch (target[0]) {
			case 'add':
				if (user.userid !== room.founder && (!room.isOfficial || user.group === ' ')) return this.errorReply("This room does not qualify to have a roomshop at this time.");
				if (RS.length > ITEM_CAP) return this.errorReply("You cannot add any more items.");
				var item = target[1], desc = target[2], price = target[3];
				if (item.lenth > 15) return this.errorReply("Item names cannot exceed 15 characters.");
				if (desc.length > 200) return this.errorReply("Item descriptions cannot exceed 200 characters.");
				if (isNaN(Number(price)) || price < 1 || ~price.indexOf('.') || price > 1000) return this.errorReply("The price must be a positive integer.");
				if (!item || !desc || !price) return this.errorReply("Usage: /roomshop add, [item], [description], [price] - Adds an item to the roomshop.");
				RS[toId(item)] = [item, desc, Number(price)];
				saveShop();
				return this.sendReply("You have successfully added the item '" + item + "' to your room shop.");
				break;
			case 'remove':
				if (user.userid !== room.founder && (!room.isOfficial || user.group === ' ')) return this.errorReply("This room does not qualify to have a roomshop at this time.");
				var item = toId(target[1]);
				if (!RS[item]) return this.errorReply("This item is not in the room's shop. Check spelling?");
				var itemName = RS[item][0];
				delete RoomShop[room.id][item];
				saveShop();
				return this.sendReply("You have successfully removed the item '" + itemName + "' from the room's shop");
				break;
			case 'buy':
				var item = toId(target[1]), price = RS[item][2];
				if (!item) return this.errorReply("Usage: /roomshop buy, [item] - Buys an item from the room's room shop.");
				if (!RS[item]) return this.errorReply("This item is not in the room shop. Check spelling?");
				item = RS[item][0];
				if (economy.readMoney(user.userid) < price) return this.errorReply("You do not have enough bucks to do buy " + item + ". You need " + (price - economy.readMoney(user.userid)) + " more bucks to buy this item.");
				this.parse('/tb ' + room.founder + ', ' + price);
				room.add("|raw|Room Shop: " + getName(user.name) + " has bought a(n) " + Tools.escapeHTML(item) + " from the room shop for " + price + " buck" + (price > 1 ? "s" : "") + ".").update();
				this.privateModCommand("(" + user.name + " has bought a(n) " + item + " from the room shop.)");
				break;
			case 'help':
				this.parse('/help roomshop');
				break;
			default:
				if (!RoomShop[room.id] || Object.keys(RoomShop[room.id]).length < 1) return this.errorReply("This room does not have any items in it's room shop at this time.");
				if (!this.canBroadcast()) return;
				return this.sendReplyBox(getRoomShop(room));
		}
	},
	roomshophelp: ["This plugin allows certain rooms to have their own room shop.  Commands include...",
		"/roomshop add, [item], [description], [price] - Adds an item to the roomshop.  Requires Room Founder.",
		"/roomshop remove, [item] - Removes an item from the roomshop. Requires Room Founder.",
		"/roomshop buy, [item] - Buys an item from the shop.",
		"/roomshop - Displays a room's room shop."],
};
<commit_msg>Lazy way of fixing crash in /roomshop buy<commit_after>/* Room shop system (economy)
 * This plugin gives each room that is allowed,
 * a custom shop for their room.  Room founders
 * can customize what items they want to be in
 * their shops.  Only certain rooms can have
 * their own shops.
 * by: panpawn and Siiilver
 */

// OBJECT STRUCTURE:
// { 'roomid': { 'item1id': ['item1name', 'item1desc', 'item1price'], 'item2id': ['item2name', 'item2desc', 'item2price'] } }

var fs = require('fs');

const ITEM_CAP = 8; // maximum items a room shop can have
var PATH = 'config/roomshops.json';
var RoomShop = require('../' + PATH);

function saveShop() {
	fs.writeFileSync(PATH, JSON.stringify(RoomShop));
}

function getName(user) {
	return '' + Tools.escapeHTML(user) + '';
}

function getRoomShop (room) {
	var output = "" + room.title + " Room Shop
" +
	    '
' +
	    '
Item	Description	Price
';
	for (var i in RoomShop[room.id]) {
	    var item = RoomShop[room.id][i];
	    var name = item[0], desc = item[1], price = item[2];
		output += '
<button name="send" value="/roomshop buy, ' + name + '">' + name + '</button>	' + desc + '	' + price + '
';
	}
	return output + '
Note: As per server rules, global staff are not responsible for scams via a room shop.  However, if severe enough, report it to a global staff and if there was a rule broken, action will be taken.';
}

exports.commands = {
	roomshop: function(target, room, user) {
		if (!room.founder) return this.errorReply("This room is not designed to have a room shop.");

		target = target.split(',');
		for (var u in target) target[u] = target[u].trim();
		if (!RoomShop[room.id]) RoomShop[room.id] = {};
		var RS = RoomShop[room.id];
		switch (target[0]) {
			case 'add':
				if (user.userid !== room.founder && (!room.isOfficial || user.group === ' ')) return this.errorReply("This room does not qualify to have a roomshop at this time.");
				if (RS.length > ITEM_CAP) return this.errorReply("You cannot add any more items.");
				var item = target[1], desc = target[2], price = target[3];
				if (item.lenth > 15) return this.errorReply("Item names cannot exceed 15 characters.");
				if (desc.length > 200) return this.errorReply("Item descriptions cannot exceed 200 characters.");
				if (isNaN(Number(price)) || price < 1 || ~price.indexOf('.') || price > 1000) return this.errorReply("The price must be a positive integer.");
				if (!item || !desc || !price) return this.errorReply("Usage: /roomshop add, [item], [description], [price] - Adds an item to the roomshop.");
				RS[toId(item)] = [item, desc, Number(price)];
				saveShop();
				return this.sendReply("You have successfully added the item '" + item + "' to your room shop.");
				break;
			case 'remove':
				if (user.userid !== room.founder && (!room.isOfficial || user.group === ' ')) return this.errorReply("This room does not qualify to have a roomshop at this time.");
				var item = toId(target[1]);
				if (!RS[item]) return this.errorReply("This item is not in the room's shop. Check spelling?");
				var itemName = RS[item][0];
				delete RoomShop[room.id][item];
				saveShop();
				return this.sendReply("You have successfully removed the item '" + itemName + "' from the room's shop");
				break;
			case 'buy':
				try {
					var item = toId(target[1]), price = RS[item][2];
					if (!item) return this.errorReply("Usage: /roomshop buy, [item] - Buys an item from the room's room shop.");
					if (!RS[item]) return this.errorReply("This item is not in the room shop. Check spelling?");
					item = RS[item][0];
					if (economy.readMoney(user.userid) < price) return this.errorReply("You do not have enough bucks to do buy " + item + ". You need " + (price - economy.readMoney(user.userid)) + " more bucks to buy this item.");
					this.parse('/tb ' + room.founder + ', ' + price);
					room.add("|raw|Room Shop: " + getName(user.name) + " has bought a(n) " + Tools.escapeHTML(item) + " from the room shop for " + price + " buck" + (price > 1 ? "s" : "") + ".").update();
					this.privateModCommand("(" + user.name + " has bought a(n) " + item + " from the room shop.)");
				} catch (e) {
					this.errorReply("This item is not in the roomshop.");
				}
				break;
			case 'help':
				this.parse('/help roomshop');
				break;
			default:
				if (!RoomShop[room.id] || Object.keys(RoomShop[room.id]).length < 1) return this.errorReply("This room does not have any items in it's room shop at this time.");
				if (!this.canBroadcast()) return;
				return this.sendReplyBox(getRoomShop(room));
		}
	},
	roomshophelp: ["This plugin allows certain rooms to have their own room shop.  Commands include...",
		"/roomshop add, [item], [description], [price] - Adds an item to the roomshop.  Requires Room Founder.",
		"/roomshop remove, [item] - Removes an item from the roomshop. Requires Room Founder.",
		"/roomshop buy, [item] - Buys an item from the shop.",
		"/roomshop - Displays a room's room shop."],
};
<|endoftext|>


<commit_before>kWidget.addReadyCallback( function( playerId ){
	var kdp = document.getElementById(playerId);
	// Shortcut to get config:
	var gc = function( attr ){
		return kdp.evaluate('{descriptionBox.' + attr + '}' );
	}
	//var $ = kWidget.getJQuery();
	kdp.kBind( "mediaReady", function(){
		var descriptionTitle	= gc( 'descriptionLabel') || kdp.evaluate('{mediaProxy.entry.name}');
		// check for target:
		var boxTargetID= gc( 'boxTargetId' ) || 'descriptionBox_' + playerId;

		// if no box target ( remove )
		if( ! gc( 'boxTargetId' ) ){
			$( '#' + boxTargetID ).remove();
		}
		// Add box target if missing from page:
		if( !$('#' + boxTargetID ).length ){
			var $descBox = $("<div>")
				.attr("id", boxTargetID )
				.css({
					"height" : gc( 'boxHeight' ),
					'width' : gc( 'boxWidth' ) || '100%'
				})
				// for easy per site theme add kWidget class:
				.addClass('kWidget-descriptionBox');
			// check for where it should be appended:
			switch( gc('boxLocation') ){
				case 'before':
					$(kdp).before( $descBox );
				break;
				case 'left':
					$descBox.css('float', 'left').insertBefore(kdp);
					$(kdp).css('float', 'left');
				break;
				case 'right':
					$descBox.css('float', 'left').insertAfter( kdp );
					$(kdp).css('float', 'left' );
				break;
				case 'after':
				default:
					$(kdp).after( $descBox );
				break;
			};
		}
		// Empty any old description box
		$( '#' + boxTargetID )
			.empty()
			.append(
				$( "<h2>" ).text( descriptionTitle ),
				$( "<p>" ).html( kdp.evaluate('{mediaProxy.entry.description}') )
			)
	});
});<commit_msg>some float layout tweaks <commit_after>kWidget.addReadyCallback( function( playerId ){
	var kdp = document.getElementById(playerId);
	// Shortcut to get config:
	var gc = function( attr ){
		return kdp.evaluate('{descriptionBox.' + attr + '}' );
	}
	//var $ = kWidget.getJQuery();
	kdp.kBind( "mediaReady", function(){
		var descriptionTitle	= gc( 'descriptionLabel') || kdp.evaluate('{mediaProxy.entry.name}');
		// check for target:
		var boxTargetID= gc( 'boxTargetId' ) || 'descriptionBox_' + playerId;

		// if no box target ( remove )
		if( ! gc( 'boxTargetId' ) ){
			$( '#' + boxTargetID ).remove();
		}
		// Add box target if missing from page:
		if( !$('#' + boxTargetID ).length ){
			var $descBox = $("<div>")
				.attr("id", boxTargetID )
				.css({
					"height" : gc( 'boxHeight' ),
					'width' : gc( 'boxWidth' ) || null
				})
				// for easy per site theme add kWidget class:
				.addClass('kWidget-descriptionBox');
			// check for where it should be appended:
			switch( gc('boxLocation') ){
				case 'before':
					$(kdp)
						.css( 'float', 'none')
						.before( $descBox );
				break;
				case 'left':
					$descBox.css('float', 'left').insertBefore(kdp);
					$(kdp).css('float', 'left');
				break;
				case 'right':
					$descBox.css('float', 'left').insertAfter( kdp );
					$(kdp).css('float', 'left' );
				break;
				case 'after':
				default:
					$(kdp)
						.css( 'float', 'none')
						.after( $descBox );
				break;
			};
		}
		// Empty any old description box
		$( '#' + boxTargetID )
			.empty()
			.append(
				$( "<h2>" ).text( descriptionTitle ),
				$( "<p>" ).html( kdp.evaluate('{mediaProxy.entry.description}') )
			)
	});
});<|endoftext|>


<commit_before>(function () {
    'use strict';
var app = angular.module('vitebizFMS');
//Add Category

app.controller('AddCategory', function ($scope, $http,$location,$ionicLoading,ionicToast) {

	var path=window.localStorage['path'];
	var nUserId=window.localStorage['UserId'];

	$scope.AddCategory={};
	//Select Category
	 var Categoryurl = path+"Category.asmx/SelectAllCategory?UserId=" + nUserId;

		$http.get(Categoryurl).then(function (resp) {

			$scope.List = resp.data;
			//window.localStorage['ProductSubCategory'] = JSON.stringify(resp.data);
			$ionicLoading.hide();

		}, function (err) {
			console.error('ERR', err);
    })

	// for Save category

	$scope.Parent=function()
	{

	}

	$scope.AddCategory=function()
	{

		var cCategoryName=$scope.AddCategory.Name;
		var Description=$scope.AddCategory.Description;
		var IsParent=$scope.AddCategory.IsParent;

		//console.log(IsParent);
		//alert(IsParent);
		 if(IsParent==undefined)
		 {
			 var IsParentId=false;
		 }
		 else
		 {
			 var IsParentId=true;
		 }
		if(Description==undefined)
		{
			var cCategoryDesc='';
		}
		else
		{
			var cCategoryDesc=$scope.AddCategory.Description;
		}

		var cCategoryImage='';
		var cCategoryIcon='';
		var cURLKey='';
		var nLanguageId=1;
		var IsActive=true;
		var IsDisable=false;

		if(IsParent=="Yes")
		{

			var intCategoryId = $scope.AddCategory.Category.intCategoryId;
			var nParentId=intCategoryId;

				if(cCategoryName!=undefined)
		            {
						  $http({
                                    method: 'POST',
                                    url: path+'Category.asmx/AddCategory',
                                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                                    transformRequest: function (obj) {
                                        var str = [];
                                        for (var p in obj)
                                            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                                        return str.join("&");
                                    },
                                    data: { cCategoryName: cCategoryName,
									cCategoryDesc: cCategoryDesc,
									cCategoryImage:cCategoryImage,
									cCategoryIcon: cCategoryIcon,
                                    cURLKey: cURLKey,
									IsParent: IsParentId,
                                    nParentId: nParentId,
                                    nUserId: nUserId,
                                    nLanguageId: nLanguageId,
                                    IsActive: IsActive,
                                    IsDisable: IsDisable

                                     }
                                }).success(function (response) {

										var msg=response.Message;
										if(msg=='Category already exists')
										{
											ionicToast.show('Category already exists', 'middle', false, 2500);
						                     $ionicLoading.hide();
										}
										else
										{
											ionicToast.show('Category Add Successfully', 'middle', false, 2500);
						                     $ionicLoading.hide();
											 window.location = "#/app/ShowCategory";
										}

								})
					}
					else
					{
						ionicToast.show('Enter Category Name', 'middle', false, 2500);
						 $ionicLoading.hide();
					}

		}
		else
		{
			var nParentId=0;

				if(cCategoryName!=undefined)
		            {
						  $http({
                                    method: 'POST',
                                    url: path+'Category.asmx/AddCategory',
                                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                                    transformRequest: function (obj) {
                                        var str = [];
                                        for (var p in obj)
                                            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                                        return str.join("&");
                                    },
                                    data: { cCategoryName: cCategoryName,
									cCategoryDesc: cCategoryDesc,
									cCategoryImage:cCategoryImage,
									cCategoryIcon: cCategoryIcon,
                                    cURLKey: cURLKey,
									IsParent: IsParentId,
                                    nParentId: nParentId,
                                    nUserId: nUserId,
                                    nLanguageId: nLanguageId,
                                    IsActive: IsActive,
                                    IsDisable: IsDisable

                                     }
                                }).success(function (response) {

										var msg=response.Message;
										if(msg=='Category already exists')
										{
											ionicToast.show('Category already exists', 'middle', false, 2500);
						                     $ionicLoading.hide();
										}
										else
										{
											ionicToast.show('Category Add Successfully', 'middle', false, 2500);
						                     $ionicLoading.hide();
											  window.location = "#/app/ShowCategory";
										}

								})
					}
					else
					{
						ionicToast.show('Enter Category Name', 'middle', false, 2500);
						 $ionicLoading.hide();
					}

			}

	}

})
// For Display Category

.controller('ShowCategory', function ($scope, $http,$location) {

		var path = window.localStorage['path'];
		var nUserId = window.localStorage['UserId'];

		  var SelectAllCategoryurl = path+"Category.asmx/SelectAll?UserId=" + nUserId;

	     $http.get(SelectAllCategoryurl).then(function (respAllOrderStatus) {

		 $scope.CategoryList = respAllOrderStatus.data;

	}, function (err) {
		console.error('ERR', err);
	})

	$scope.AddCategory=function()
	{
		window.location = "#/app/AddCategory";

	}

	$scope.EditProduct=function(intCategoryId)
	{
	  window.location = "#/app/EditCategory?intCategoryId="+intCategoryId;
	}

})

//End
//edit Category

.controller('EditCategory', function ($scope, $http, $location,$ionicLoading,ionicToast) {

		$scope.EditCategory={};
		var path = window.localStorage['path'];
		var nUserId = window.localStorage['UserId'];

		var nCategoryId = $location.search().intCategoryId;

		var path=window.localStorage['path'];
	var nUserId=window.localStorage['UserId'];

	//$scope.AddCategory={};
	//Select Category

		 var SelectCategoryDataurl = path+"Category.asmx/SelectRowForCategory?nCategoryId=" + nCategoryId+"&nUserId="+nUserId;

	     $http.get(SelectCategoryDataurl).then(function (resp) {

		 $scope.CategoryRowData = resp.data;
		 console.log();
		 $scope.strCategoryName=resp.data[0].strCategoryName;
		  $scope.strCategoryDesc=resp.data[0].strCategoryDesc;
		   $scope.IsParent=resp.data[0].IsParent;
		  $scope.intParentId=resp.data[0].intParentId;
		    $scope.strCategoryImage=resp.data[0].strCategoryImage;
		  $scope.strCategoryIcon=resp.data[0].strCategoryIcon;

		  $scope.EditCategory.Name= $scope.strCategoryName;
		  $scope.EditCategory.Description= $scope.strCategoryDesc;
		  var IsParent=  $scope.IsParent;
		  var intParentId= $scope.intParentId;

		  console.log(IsParent);

		  if(IsParent==true)
		  {
			  $scope.EditCategory.IsParent='Yes';
			   $scope.EditCategory.Category=intParentId;
		  }
		  else
		  {
			   $scope.EditCategory.IsParent='No';
		  }

		  // For Select Category

		   var Categoryurl = path+"Category.asmx/SelectAllCategory?UserId=" + nUserId;

		   $http.get(Categoryurl).then(function (resp) {

				$scope.CategoryListData = resp.data;

				for(var i=0; i < resp.data.length; i++){

					//console.log(resp.data[i].intCategoryId);
					if(intParentId==resp.data[i].intCategoryId)
					{
						console.log(intParentId,resp.data[i].intCategoryId);
						 $scope.EditCategory.intCategoryId =intParentId;
						 // console.log($scope.EditCategory.intCategoryId);
					}

				}
				//window.localStorage['ProductSubCategory'] = JSON.stringify(resp.data);
				$ionicLoading.hide();

			}, function (err) {
				console.error('ERR', err);
            })

			//End Display Category

			//For Edit Category

			$scope.Edit=function()
			{

				  var cCategoryName=$scope.EditCategory.Name;

					var Description=$scope.EditCategory.Description;
					var IsParent=$scope.EditCategory.IsParent;

					if(IsParent=="No")
					{
						var IsParentId=false;
					}
					else
					{
						var IsParentId=true;
					}

					if(Description==undefined)
					{
						var cCategoryDesc='';
					}
					else
					{
						var cCategoryDesc=$scope.EditCategory.Description;
					}

					var cCategoryImage='';
					var cCategoryIcon='';
					var cURLKey='';
					var nLanguageId=1;
					var IsActive=true;
					var IsDisable=false;

							if(IsParent=="Yes")
							{

							   var intCategoryId = $scope.EditCategory.intCategoryId;
								var nParentId=intCategoryId;

									if(cCategoryName!='')
										{
											  $http({
														method: 'POST',
														url: path+'Category.asmx/UpdateCategory',
														headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
														transformRequest: function (obj) {
															var str = [];
															for (var p in obj)
																str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
															return str.join("&");
														},
														data: { nCategoryId:nCategoryId,
														cCategoryName: cCategoryName,
														cCategoryDesc: cCategoryDesc,
														cCategoryImage:cCategoryImage,
														cCategoryIcon: cCategoryIcon,
														cURLKey: cURLKey,
														IsParent: IsParentId,
														nParentId: nParentId,
														nUserId: nUserId,
														nLanguageId: nLanguageId,
														IsActive: IsActive,
														IsDisable: IsDisable

														 }
													}).success(function (response) {

															var msg=response.Message;
															if(msg=='Category already exists')
															{
																ionicToast.show('Category already exists', 'middle', false, 2500);
																 $ionicLoading.hide();
															}
															else
															{
																ionicToast.show('Category Update Successfully', 'middle', false, 2500);
																 $ionicLoading.hide();
																 window.location = "#/app/ShowCategory";
															}

													})
										}
										else
										{
											ionicToast.show('Enter Category Name', 'middle', false, 2500);
											 $ionicLoading.hide();
										}

							}
							else
							{

									 var intCategoryId = $scope.EditCategory.intCategoryId;
								     var nParentId=0;

									if(cCategoryName!='')
										{
											  $http({
														method: 'POST',
														url: path+'Category.asmx/UpdateCategory',
														headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
														transformRequest: function (obj) {
															var str = [];
															for (var p in obj)
																str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
															return str.join("&");
														},
														data: { nCategoryId:nCategoryId,
														cCategoryName: cCategoryName,
														cCategoryDesc: cCategoryDesc,
														cCategoryImage:cCategoryImage,
														cCategoryIcon: cCategoryIcon,
														cURLKey: cURLKey,
														IsParent: IsParentId,
														nParentId: nParentId,
														nUserId: nUserId,
														nLanguageId: nLanguageId,
														IsActive: IsActive,
														IsDisable: IsDisable

														 }
													}).success(function (response) {

															var msg=response.Message;
															if(msg=='Category already exists')
															{
																ionicToast.show('Category already exists', 'middle', false, 2500);
																 $ionicLoading.hide();
															}
															else
															{
																ionicToast.show('Category Update Successfully', 'middle', false, 2500);
																 $ionicLoading.hide();
																 window.location = "#/app/ShowCategory";
															}

													})
										}
										else
										{
											ionicToast.show('Enter Category Name', 'middle', false, 2500);
											 $ionicLoading.hide();
										}

							}

			}

	}, function (err) {
		console.error('ERR', err);
	})

})

}());<commit_msg>Delete category.controller.js<commit_after><|endoftext|>