<commit_before>/**
 * Created by meathill on 14-9-17.
 */
'use strict';
(function (ns) {
  var timeout;
  var Editor = ns.Editor = tp.view.DataSyncView.extend({
    $context: null,
    form: null,
    events: {
      'hidden.bs.modal': 'hiddenHandler',
      'keydown': 'keydownHandler',
      'mousedown .input-group': 'inputGroup_mouseDownHandler'
    },
    initialize: function (options) {
      this.submit = this.$('.btn-primary');
      this.options = options;
      var type = options.type || 'short-text'
        , template = options.template ? 'page/' + options.template : (tp.path + 'template/popup-' + type);
      $.get(template + '.hbs', _.bind(this.loadCompleteHandler, this), 'html');

      // 补充信息
      var info = $('.editor-info');
      if (info.length) {
        info = Handlebars.compile(info.html());
        this.$('.info').html(info(this.model.toJSON()));
      }
      this.$el.modal(options);
    },
    render: function (template) {
      template = Handlebars.compile(template);
      this.$('.loading').remove();
      this.form = new tp.component.SmartForm({
        tagName: 'form',
        id: 'prop-editor',
        className: 'editor-form model-editor',
        model: this.model
      });
      var html = template(_.extend(this.model.toJSON(), this.options));
      this.form.$el.html(html).insertAfter(this.$('.alert-msg'));
      this.form.on('success', this.form_successHandler, this);
      this.form.on('error', this.form_errorHandler, this);

      html = this.$('script').remove().html();
      if (html) {
        this.template = Handlebars.compile(html);
        this.$('script').empty();
      }

      var dateFields = this.$('[type=datetime]');
      if (dateFields.length) {
        dateFields.each(function () {
          $(this).datetimepicker($(this).data());
        });
      }

      this.submit.prop('disabled', false);
    },
    hide: function (delay) {
      delay = delay === undefined ? 3000 : delay;
      var modal = this.$el;
      timeout = setTimeout(function () {
        modal.modal('hide');
      }, delay);
    },
    form_errorHandler: function (xhr, status, error) {
      this.displayResult(false, error.message, 'frown-o');
      this.trigger('error', xhr, status, error);
    },
    form_successHandler: function (response) {
      this.displayResult(true, response.msg, 'smile-o');
      this.trigger('success', response);
      this.hide();
    },
    inputGroup_mouseDownHandler: function (event) {
      $(event.currentTarget).find('[type=radio]').prop('checked', true);
    },
    keydownHandler: function (event) {
      if (event.keyCode === 13 && event.ctrlKey) {
        this.form.$el.submit();
        event.preventDefault();
      }
    },
    loadCompleteHandler: function (response) {
      this.render(response);
    },
    hiddenHandler: function () {
      this.form.remove();
      if (this.collection && this.collection instanceof Backbone.Collection) {
        this.collection.off(null, null, this);
      }
      clearTimeout(timeout);
      this.$el.remove();
      this.trigger('hidden');
    }
  });

  ns.SearchEditor = Editor.extend({
    fragment: '',
    events: _.extend(Editor.prototype.events, {
      'click .search-button': 'searchButton_clickHandler'
    }),
    initialize: function (options) {
      Editor.prototype.initialize.call(this, options);
      this.collection = tp.model.ListCollection.getInstance();
      this.collection.url = tp.API + options.url;
      this.collection.on('add', this.collection_addHandler, this);
      this.collection.on('sync', this.collection_syncHandler, this);
    },
    remove: function () {
      this.collection.off();
      Backbone.View.prototype.remove.call(this);
    },
    render: function (response) {
      Editor.prototype.render.call(this, response);
    },
    search: function () {
      var keyword = this.$('[type=search]').val();
      if (!keyword) {
        return;
      }
      this.collection.fetch({data: {keyword: keyword}});
      this.$('[type=search]').prop('disabled', true);
      this.$('.search-button').spinner();
    },
    collection_addHandler: function (model) {
      this.fragment += this.template(_.extend(model.toJSON(), this.options));
    },
    collection_syncHandler: function () {
      this.$('.search-result').html(this.fragment + '<hr />');
      this.$('[type=search]').prop('disabled', false);
      this.$('.search-button').spinner(false);
      this.fragment = '';
    },
    searchButton_clickHandler: function () {
      this.search();
    },
    keydownHandler: function (event) {
      Editor.prototype.keydownHandler.call(this, event);
      if (event.keyCode === 13 && event.target.type === 'search' && event.target.value != '') {
        this.search();
        event.preventDefault();
      }
    }
  });

  ns.TagsEditor = Editor.extend({
    events: _.extend(Editor.prototype.events, {
      'click .add-button': 'addButton_clickHandler'
    }),
    initialize: function (options) {
      Editor.prototype.initialize.call(this, options);
      this.collection.on('add', this.collection_addHandler, this);
    },
    render: function (response) {
      Editor.prototype.render.call(this, response);
      if (this.options.tag && this.collection) {
        var prop = this.options.tag;
        this.collection.map(function (model) {
          model.set('tag', model.get(prop));
        });
      }
      this.$('.tags').html(this.template({value: this.collection.toJSON()}));
    },
    add: function () {
      var value = this.$('[name=query]').val().replace(/^\s+|\s+$/, '');
      if (value && !this.collection.find({tag: value})){
        this.$('[name=query], .add-button').prop('disabled', true);
        this.$('.add-button i').addClass('fa-spin fa-spinner');
        this.collection.create({tag: value}, {wait: true});
      }
    },
    addButton_clickHandler: function () {
      this.add();
    },
    collection_addHandler: function (model) {
      var data = model.toJSON();
      data.index = this.collection.length - 1;
      $(this.template({value: [data], append: true})).insertBefore(this.$('hr'));
      this.$('[name=query],.add-button').prop('disabled', false).val('');
      this.$('.add-button i').removeClass('fa-spin fa-spinner');
    },
    keydownHandler: function (event) {
      if (event.keyCode === 13 && event.target.value != '') {
        this.add();
        event.preventDefault();
      }
    }
  });

  ns.SelectEditor = Editor.extend({
    render: function (response) {
      if (this.options.options) {
        if (this.model.options) {
          this.options.options = this.model.options[this.options.options];
        } else if (this.model.collection.options) {
          this.options.options = this.model.collection.options[this.options.options];
        }
      }
      Editor.prototype.render.call(this, response);

      if (this.options.addNew) {
        var collection = new tp.model.ListCollection.getInstance({
            collectionId: this.options.prop,
            url: tp.API + this.options.url
          })
          , select = new tp.component.CollectionSelect({
            el: this.$('select'),
            collection: collection
          });
        collection.reset(this.options.options);
      } else if (this.options.list) {
        this.$('select').html($(this.options.list).html());
      }

      this.$('select').val(this.options.value)
    }
  });

  ns.NumberEditor = Editor.extend({
    initialize: function (options) {
      options.range = options.type === 'range';
      options.type = 'number';
      Editor.prototype.initialize.call(this, options);
    }
  });

  ns.FileEditor = Editor.extend({
    events: _.extend({
      'click [data-dismiss]': 'clickHandler'
    }, Editor.prototype.events),
    initialize: function (options) {
      options.isImage = /image\/\*/.test(options.accept);
      options.API = tp.API;
      if (options.multiple) {
        options.items = _.isArray(options.value) ? options.value : options.value.split(',');
      }
      // 防止误触导致退出窗体
      options.backdrop = 'static';
      options.keyboard = false;
      Editor.prototype.initialize.call(this, options);
    },
    render: function (response) {
      Editor.prototype.render.call(this, response);
      this.form.initUploader();
    },
    clickHandler: function (e) {
      var label = '您有文件正在上传，关闭窗口将导致上传失败。您确认要继续关闭窗口么？';
      if (this.form.$el.hasClass('loading') && !confirm(label)) {
        e.stopPropagation();
      }
    }
  });

  ns.SwitchEditor = Editor.extend({
    initialize: function (options) {
      options.value = this.model.get(options.prop) != options.open;
      Editor.prototype.initialize.call(this, options);
    }
  });

  ns.CheckboxEditor = Editor.extend({
    render: function (response) {
      if (this.options.options) {
        if (this.model.options) {
          this.options.options = this.model.options[this.options.options];
        } else {
          this.options.options = this.model.collection.options[this.options.options];
        }
      }
      Editor.prototype.render.call(this, response);
    }
  });
}(Nervenet.createNameSpace('tp.popup')));<commit_msg>修改没有搜索结果的显示。<commit_after>/**
 * Created by meathill on 14-9-17.
 */
'use strict';
(function (ns) {
  var timeout;
  var Editor = ns.Editor = tp.view.DataSyncView.extend({
    $context: null,
    form: null,
    events: {
      'hidden.bs.modal': 'hiddenHandler',
      'keydown': 'keydownHandler',
      'mousedown .input-group': 'inputGroup_mouseDownHandler'
    },
    initialize: function (options) {
      this.submit = this.$('.btn-primary');
      this.options = options;
      var type = options.type || 'short-text'
        , template = options.template ? 'page/' + options.template : (tp.path + 'template/popup-' + type);
      $.get(template + '.hbs', _.bind(this.loadCompleteHandler, this), 'html');

      // 补充信息
      var info = $('.editor-info');
      if (info.length) {
        info = Handlebars.compile(info.html());
        this.$('.info').html(info(this.model.toJSON()));
      }
      this.$el.modal(options);
    },
    render: function (template) {
      template = Handlebars.compile(template);
      this.$('.loading').remove();
      this.form = new tp.component.SmartForm({
        tagName: 'form',
        id: 'prop-editor',
        className: 'editor-form model-editor',
        model: this.model
      });
      var html = template(_.extend(this.model.toJSON(), this.options));
      this.form.$el.html(html).insertAfter(this.$('.alert-msg'));
      this.form.on('success', this.form_successHandler, this);
      this.form.on('error', this.form_errorHandler, this);

      html = this.$('script').remove().html();
      if (html) {
        this.template = Handlebars.compile(html);
        this.$('script').empty();
      }

      var dateFields = this.$('[type=datetime]');
      if (dateFields.length) {
        dateFields.each(function () {
          $(this).datetimepicker($(this).data());
        });
      }

      this.submit.prop('disabled', false);
    },
    hide: function (delay) {
      delay = delay === undefined ? 3000 : delay;
      var modal = this.$el;
      timeout = setTimeout(function () {
        modal.modal('hide');
      }, delay);
    },
    form_errorHandler: function (xhr, status, error) {
      this.displayResult(false, error.message, 'frown-o');
      this.trigger('error', xhr, status, error);
    },
    form_successHandler: function (response) {
      this.displayResult(true, response.msg, 'smile-o');
      this.trigger('success', response);
      this.hide();
    },
    inputGroup_mouseDownHandler: function (event) {
      $(event.currentTarget).find('[type=radio]').prop('checked', true);
    },
    keydownHandler: function (event) {
      if (event.keyCode === 13 && event.ctrlKey) {
        this.form.$el.submit();
        event.preventDefault();
      }
    },
    loadCompleteHandler: function (response) {
      this.render(response);
    },
    hiddenHandler: function () {
      this.form.remove();
      if (this.collection && this.collection instanceof Backbone.Collection) {
        this.collection.off(null, null, this);
      }
      clearTimeout(timeout);
      this.$el.remove();
      this.trigger('hidden');
    }
  });

  ns.SearchEditor = Editor.extend({
    fragment: '',
    events: _.extend(Editor.prototype.events, {
      'click .search-button': 'searchButton_clickHandler'
    }),
    initialize: function (options) {
      Editor.prototype.initialize.call(this, options);
      this.collection = tp.model.ListCollection.getInstance();
      this.collection.url = tp.API + options.url;
      this.collection.on('add', this.collection_addHandler, this);
      this.collection.on('sync', this.collection_syncHandler, this);
    },
    remove: function () {
      this.collection.off();
      Backbone.View.prototype.remove.call(this);
    },
    render: function (response) {
      Editor.prototype.render.call(this, response);
    },
    search: function () {
      var keyword = this.$('[type=search]').val();
      if (!keyword) {
        return;
      }
      this.collection.fetch({data: {keyword: keyword}});
      this.$('[type=search]').prop('disabled', true);
      this.$('.search-button').spinner();
    },
    collection_addHandler: function (model) {
      this.fragment += this.template(_.extend(model.toJSON(), this.options));
    },
    collection_syncHandler: function () {
      this.fragment = this.fragment || '没有与此关键词接近的结果。';
      this.$('.search-result').html(this.fragment);
      this.$('[type=search]').prop('disabled', false);
      this.$('.search-button').spinner(false);
      this.fragment = '';
    },
    searchButton_clickHandler: function () {
      this.search();
    },
    keydownHandler: function (event) {
      Editor.prototype.keydownHandler.call(this, event);
      if (event.keyCode === 13 && event.target.type === 'search' && event.target.value != '') {
        this.search();
        event.preventDefault();
      }
    }
  });

  ns.TagsEditor = Editor.extend({
    events: _.extend(Editor.prototype.events, {
      'click .add-button': 'addButton_clickHandler'
    }),
    initialize: function (options) {
      Editor.prototype.initialize.call(this, options);
      this.collection.on('add', this.collection_addHandler, this);
    },
    render: function (response) {
      Editor.prototype.render.call(this, response);
      if (this.options.tag && this.collection) {
        var prop = this.options.tag;
        this.collection.map(function (model) {
          model.set('tag', model.get(prop));
        });
      }
      this.$('.tags').html(this.template({value: this.collection.toJSON()}));
    },
    add: function () {
      var value = this.$('[name=query]').val().replace(/^\s+|\s+$/, '');
      if (value && !this.collection.find({tag: value})){
        this.$('[name=query], .add-button').prop('disabled', true);
        this.$('.add-button i').addClass('fa-spin fa-spinner');
        this.collection.create({tag: value}, {wait: true});
      }
    },
    addButton_clickHandler: function () {
      this.add();
    },
    collection_addHandler: function (model) {
      var data = model.toJSON();
      data.index = this.collection.length - 1;
      $(this.template({value: [data], append: true})).insertBefore(this.$('hr'));
      this.$('[name=query],.add-button').prop('disabled', false).val('');
      this.$('.add-button i').removeClass('fa-spin fa-spinner');
    },
    keydownHandler: function (event) {
      if (event.keyCode === 13 && event.target.value != '') {
        this.add();
        event.preventDefault();
      }
    }
  });

  ns.SelectEditor = Editor.extend({
    render: function (response) {
      if (this.options.options) {
        if (this.model.options) {
          this.options.options = this.model.options[this.options.options];
        } else if (this.model.collection.options) {
          this.options.options = this.model.collection.options[this.options.options];
        }
      }
      Editor.prototype.render.call(this, response);

      if (this.options.addNew) {
        var collection = new tp.model.ListCollection.getInstance({
            collectionId: this.options.prop,
            url: tp.API + this.options.url
          })
          , select = new tp.component.CollectionSelect({
            el: this.$('select'),
            collection: collection
          });
        collection.reset(this.options.options);
      } else if (this.options.list) {
        this.$('select').html($(this.options.list).html());
      }

      this.$('select').val(this.options.value)
    }
  });

  ns.NumberEditor = Editor.extend({
    initialize: function (options) {
      options.range = options.type === 'range';
      options.type = 'number';
      Editor.prototype.initialize.call(this, options);
    }
  });

  ns.FileEditor = Editor.extend({
    events: _.extend({
      'click [data-dismiss]': 'clickHandler'
    }, Editor.prototype.events),
    initialize: function (options) {
      options.isImage = /image\/\*/.test(options.accept);
      options.API = tp.API;
      if (options.multiple) {
        options.items = _.isArray(options.value) ? options.value : options.value.split(',');
      }
      // 防止误触导致退出窗体
      options.backdrop = 'static';
      options.keyboard = false;
      Editor.prototype.initialize.call(this, options);
    },
    render: function (response) {
      Editor.prototype.render.call(this, response);
      this.form.initUploader();
    },
    clickHandler: function (e) {
      var label = '您有文件正在上传，关闭窗口将导致上传失败。您确认要继续关闭窗口么？';
      if (this.form.$el.hasClass('loading') && !confirm(label)) {
        e.stopPropagation();
      }
    }
  });

  ns.SwitchEditor = Editor.extend({
    initialize: function (options) {
      options.value = this.model.get(options.prop) != options.open;
      Editor.prototype.initialize.call(this, options);
    }
  });

  ns.CheckboxEditor = Editor.extend({
    render: function (response) {
      if (this.options.options) {
        if (this.model.options) {
          this.options.options = this.model.options[this.options.options];
        } else {
          this.options.options = this.model.collection.options[this.options.options];
        }
      }
      Editor.prototype.render.call(this, response);
    }
  });
}(Nervenet.createNameSpace('tp.popup')));<|endoftext|>


<commit_before>function ProductTour(options){

}<commit_msg>added init property and public addNewTourSteps property<commit_after>function ProductTour(steps, options){

	this.addNewTourStep = (items)=> {
		var itemString = "
";

		for (var i = 0; i<items.length; i++) {
			items[i].element = items[i].element ? items[i].element : 0;
			items[i].title = items[i].title ? items[i].title : 'hey... i worked';
			items[i].content = items[i].content ? items[i].content : '';
			items[i].image = items[i].image ? items[i].image : '';
			items[i].class = items[i].class ? items[i].class : 'bottom';

			var foo = "

<input type='hidden' value=''>Step

"
			var htmlElement = jQuery(foo);
			jQuery('h2', htmlElement).text(items[i].title);
			jQuery('p', htmlElement).text(items[i].content);
			jQuery('.cd-more-info', htmlElement).addClass(items[i].class);
			jQuery('img', htmlElement).text(items[i].content);
			if(items[i].element){
				var widthHalf = jQuery(items[i].element).outerWidth()/2;
				var heightHalf = jQuery(items[i].element).outerHeight()-10;

				var top = jQuery(items[i].element).offset().top + heightHalf;
				var left = jQuery(items[i].element).offset().left + widthHalf;
				jQuery('input', htmlElement).val(items[i].element);
				jQuery('li.cd-single-step', htmlElement).css({top: top, left: left, height: '10px', width: '10px'});
			}
			itemString = itemString.concat(htmlElement.html());
		}

		itemString = itemString.concat("
");
		jQuery('body').append(itemString);
		jQuery('body').append("

");
	};

	function initTour() {
		var tourWrapper = jQuery('.cd-tour-wrapper'), //get the wrapper element
			tourSteps = tourWrapper.children('li'), //get all its children with tag 'li'
			stepsNumber = tourSteps.length, //get the no of elements in this array
			coverLayer = jQuery('.cd-cover-layer'),
			tourStepInfo = jQuery('.cd-more-info'),
			tourTrigger = jQuery('#cd-tour-trigger');
			jQuery('.overlay-tour').css({display: 'block'});
			//jQuery(jQuery(".active .cd-single-step.is-selected input").val()).css({'z-index': 90001});

		//create the navigation for each step of the tour
		createNavigation(tourSteps, stepsNumber);
		console.log(jQuery(".cd-single-step input").val());
		jQuery(jQuery("li.cd-single-step input").val()).css({'z-index': 90001, position: 'relative'});

		tourTrigger.on('click', function(){
			//start tour
			if(!tourWrapper.hasClass('active')) {
				//in that case, the tour has not been started yet
				tourWrapper.addClass('active');
				showStep(tourSteps.eq(0), coverLayer);
			}
		});

		//change visible step
		tourStepInfo.on('click', '.cd-prev', function(event){
			//go to prev step - if available
			( !jQuery(event.target).hasClass('inactive') ) && changeStep(tourSteps, coverLayer, 'prev');
		});
		tourStepInfo.on('click', '.cd-next', function(event){
			//go to next step - if available
			( !jQuery(event.target).hasClass('inactive') ) && changeStep(tourSteps, coverLayer, 'next');
		});

		//close tour
		tourStepInfo.on('click', '.cd-close', function(event){
			closeTour(tourSteps, tourWrapper, coverLayer);
		});

		//detect swipe event on mobile - change visible step
		tourStepInfo.on('swiperight', function(event){
			//go to prev step - if available
			if( !jQuery(this).find('.cd-prev').hasClass('inactive') && viewportSize() == 'mobile' ) changeStep(tourSteps, coverLayer, 'prev');
		});
		tourStepInfo.on('swipeleft', function(event){
			//go to next step - if available
			if( !jQuery(this).find('.cd-next').hasClass('inactive') && viewportSize() == 'mobile' ) changeStep(tourSteps, coverLayer, 'next');
		});

		//keyboard navigation
		jQuery(document).keyup(function(event){
			if( event.which=='37' && !tourSteps.filter('.is-selected').find('.cd-prev').hasClass('inactive') ) {
				changeStep(tourSteps, coverLayer, 'prev');
			} else if( event.which=='39' && !tourSteps.filter('.is-selected').find('.cd-next').hasClass('inactive') ) {
				changeStep(tourSteps, coverLayer, 'next');
			} else if( event.which=='27' ) {
				closeTour(tourSteps, tourWrapper, coverLayer);
			}
		});

		if(!tourWrapper.hasClass('active')) {
				//in that case, the tour has not been started yet
				tourWrapper.addClass('active');
				showStep(tourSteps.eq(0), coverLayer);
		}
	};

}<|endoftext|>


<commit_before>var queryOption = null;

$(document).on('pageinit', '#post-list', function() {
    updateQuery();

    $('#order-by').change(function() {
	updateQuery();
    });

    $('#order').change(function() {
	updateQuery();
    });

    $('#limit').change(function() {
	updateQuery();
    });
});

function updateQuery() {
    var $orderBy = $('#order-by option:selected');
    var $order   = $('#order option:selected');
    var $limit   = $('#limit');

    queryOption = new QueryOptionBuilder()
	.setOrderBy($orderBy.val(), $order.val())
	.setLimit($limit.val())
	.build();;
}<commit_msg>:golf:<commit_after>var queryOption = null;

$(document).on('pageinit', '#post-list', function() {
    updateQuery();

    $('#order-by, #order, #limit').change(function() {
	updateQuery();
    });
});

function updateQuery() {
    var $orderBy = $('#order-by option:selected');
    var $order   = $('#order option:selected');
    var $limit   = $('#limit');

    queryOption = new QueryOptionBuilder()
	.setOrderBy($orderBy.val(), $order.val())
	.setLimit($limit.val())
	.build();;
}<|endoftext|>


<commit_before>var players = [];

function Player(){

    this.playerId = players.length;
    this.x = 1;
    this.y = 1.6;
    this.z = 1;
    this.r_x = 0;
    this.r_y = 0;
    this.r_z = 0;
    this.sizeX = 1;
    this.sizeY = 1;
    this.sizeZ = 1;
    this.speed = 0.2;
    //this.keyState={};
    this.turnSpeed = 0.075;

}

var addPlayer = function(id){

    var player = new Player();
    player.playerId = id;
    players.push( player );

    return player;
};

var removePlayer = function(player){

    var index = players.indexOf(player);

    if (index > -1) {
        players.splice(index, 1);
    }
};

var updatePlayerData = function(data){
    var player = playerForId(data.playerId);
    player.x = data.x;
    player.y = data.y;
    player.z = data.z;
    player.r_x = data.r_x;
    player.r_y = data.r_y;
    player.r_z = data.r_z;
    //player.keyState=data.keyState;

    return player;
};

var playerForId = function(id){

    var player;
    for (var i = 0; i < players.length; i++){
        if (players[i].playerId === id){

            player = players[i];
            break;

        }
    }

    return player;
};

module.exports.players = players;
module.exports.addPlayer = addPlayer;
module.exports.removePlayer = removePlayer;
module.exports.updatePlayerData = updatePlayerData;
module.exports.playerForId = playerForId;<commit_msg>problems hmm<commit_after>var players = [];

function Player(){

    this.playerId = players.length;
    this.x = 1;
    this.y = 1.6;
    this.z = 1;
    this.r_x = 0;
    this.r_y = 0;
    this.r_z = 0;
    this.sizeX = 1;
    this.sizeY = 1;
    this.sizeZ = 1;
    this.speed = 0.2;
    //this.keyState={};
    this.turnSpeed = 0.075;

}

var addPlayer = function(id){

    var player = new Player();
    player.playerId = id;
    players.push( player );

    return player;
};

var removePlayer = function(player){

    var index = players.indexOf(player);

    if (index > -1) {
        players.splice(index, 1);
    }
};

var updatePlayerData = function(data){
    var player = playerForId(data.playerId);
    if(player.x-data.x!==0){
    console.log("change change"+data.playerId);
 }

    player.x = data.x;
    player.y = data.y;
    player.z = data.z;
    player.r_x = data.r_x;
    player.r_y = data.r_y;
    player.r_z = data.r_z;
    //player.keyState=data.keyState;

    return player;
};

var playerForId = function(id){

    var player;
    for (var i = 0; i < players.length; i++){
        if (players[i].playerId === id){

            player = players[i];
            break;

        }
    }

    return player;
};

module.exports.players = players;
module.exports.addPlayer = addPlayer;
module.exports.removePlayer = removePlayer;
module.exports.updatePlayerData = updatePlayerData;
module.exports.playerForId = playerForId;<|endoftext|>


<commit_before>(function(){
	'use strict'
	var selectTreeSelector = ".selectTree",
	get = {
		// selectors tree dom - get.item/all("seletor",fatherDom)
	 	item: function(el, root){
			if(typeof(root)!="undefined") return root.querySelector(el);
			return document.querySelector(el);
	 	},
	 	all: function(el, root){
	 		if(typeof(root)!="undefined") return root.querySelectorAll(el);
	 		return document.querySelectorAll(el);
	 	},
		searchKey: function(arr, key, value){
			for (var i = arr.length; i--;) {
				if(arr[i][key]==value) return i;
			};
			return null;
		}
	},
	selectTree = (function(el){
		var app = {
			active: false,
			disabled: false,
			list: [],
			fathers: [],
			el: {},
			value: null,
			empty: "Sem itens para os pai(s) selecionados", // DEFAULT MESSAGE EMPTY
			beforeOptions: "", //DEFAULT AFTER OPTION
			_getValueFather: function(key){
				var temp = get.item('select[data-shr-id="'+key+'"]'),
				val;
				if(temp===null) {
					throw "SelectTree: Father ("+key+") not found";
				}
				val = temp.value;
				app.fathers.push({'id': key,'value': val,'el': temp});
			},
			_updateValueFather: function(){
				var fathers = app.fathers;
				app.fathers = [];
				for (var i = fathers.length; i--;) {
					app._getValueFather(fathers[i].id);
				}
				app._checkDisabled();
			},
			_checkDisabled: function(){
				var disabled = false;
				for (var i = app.fathers.length; i--;) {
					if(app.fathers[i].value==="choose")
						disabled = true;
				}
				app.disabled = disabled;
				if(app.disabled) return app.el.setAttribute("disabled","on");
				app.el.removeAttribute("disabled");
			},
			_filter: function(option){
				for (var i = app.fathers.length; i--;) {
					if(app.fathers[i].value!="all" && app.fathers[i].value!="choose"){
						if(typeof(option[app.fathers[i].id])==="undefined") return false;
						// CONFERIR LANCE DE COMPRAÇÂO DE STRING COM NUMBER DO INDEX OF
						if(option[app.fathers[i].id].indexOf(app.fathers[i].value)===-1) return false;
					}
				}
				return true;
			},
			_clearSelected: function(){
				for (var i = app.list.length; i--;) {
					if(app.list[i].html.indexOf('selected')) {
						app.list[i].html = app.list[i].html.replace('selected="on"', "");
						app.list[i].html = app.list[i].html.replace("selected", "");
					}
				}
			},
			buildOptions: function(){
				var string = "";
				for (var i = app.list.length; i--;) {
					if(app._filter(app.list[i]))
						string = app.list[i].html + string;
				};
				if(string===""){
					string = '<option disabled="on" value="" selected="on">'+app.empty+'</option>';
				} else {
					string = app.beforeOptions.html + string;
				}
				app.el.innerHTML = string;
			},
			statusSelect: function(){
				var dataset = app.el.dataset;
				if(dataset.shrValue){
					app.value = dataset['shrValue'];
					delete dataset['shrValue'];
				}
				if(dataset.shrEmpty) app.empty = dataset.shrEmpty;
				app._checkDisabled();
			},
			setEvents: function(){
				var flag = true;
				for (var i = app.fathers.length; i--;) {
					app.fathers[i].el.addEventListener('change',function(){
						app._updateValueFather();
						app.buildOptions();
					},false);
					app.fathers[i].el.addEventListener('DOMSubtreeModified',function(){
						//EVENTO @DOMSubtreeModified É DISPARADO DUAS VEZES
						//FLAG e SeTimeout PARA NÃO EXECUTAR DUAS VEZES
						if(flag){
							flag = false;
							setTimeout(function(){
								app._updateValueFather();
								app.buildOptions();
								flag = true;
							},20);
						}
					},false);
				}
				setTimeout(app._clearSelected, 500); //CLEAR SELECTED OF LIST AFTER INIT PROGRAM
			},
			list: function(select){
				var elOptions = get.all("option",select),
				list = [],
				dataset = {},
				valueCheck = [],
				listTemp,
				val = 0,
				keySearch;
				for (var i = 0, lim = elOptions.length; i<lim; i++) {
					val = elOptions[i].value
					listTemp = {'value': val};

					keySearch = null;
					if(valueCheck.indexOf(val)!==-1) {
						keySearch = get.searchKey(list, 'value', val);
					}
					valueCheck.push(elOptions[i].value);
					if(keySearch!==null) listTemp = list[keySearch]

					//PERCORRER OBJETO DATASET
					dataset = elOptions[i].dataset;
					for (var key in dataset) if(dataset.hasOwnProperty(key)) {
						// IF HAVE DATA OF SELECTTREE - @data-cod | @dataCod
						if(key.indexOf("Cod")!=-1){
							if(keySearch!==null && key in listTemp) {
								listTemp[key] = listTemp[key].concat(dataset[key].split(","));
							} else {
								listTemp[key] = dataset[key].split(",");
							}
							delete dataset[key];
							if(!app.active) app.active = true;
							if(get.searchKey(app.fathers,'id',key)===null)
								app._getValueFather(key);
						}
					}

					// SETA VALUE DEFAULT
					if(val==app.value) elOptions[i].setAttribute('selected','on');
					if(elOptions[i].hasAttribute('selected')){
						if(app.value==null) app.value = val;
						if(app.value!=val) elOptions[i].removeAttribute('selected');
					}
					listTemp.html = elOptions[i].outerHTML;

					if(val === "all" || val === "choose" ){
						app.beforeOptions = listTemp;
					} else {
						if(keySearch===null){
							list.push(listTemp);
						} else {
							list[keySearch] = listTemp;
						}
					}
				};
				return list;
			}
		}
		app.el = el;
		app.statusSelect();
		app.list = app.list(el); //FOR CLEAN FUNCTION LIST WITH ARRAY LIST - CLEAN MEMORY
		app.buildOptions();
		if(!app.active) return 0;
		app.setEvents();
		console.dir(app);
	});
	var el = get.all(selectTreeSelector);
	for (var i = el.length - 1; i >= 0; i--) {
		selectTree(el[i]);
	};
}());<commit_msg>Correções de bug no disabled de filhoi vazio.<commit_after>(function(){
	'use strict'
	var selectTreeSelector = ".selectTree",
	get = {
		// selectors tree dom - get.item/all("seletor",fatherDom)
	 	item: function(el, root){
			if(typeof(root)!="undefined") return root.querySelector(el);
			return document.querySelector(el);
	 	},
	 	all: function(el, root){
	 		if(typeof(root)!="undefined") return root.querySelectorAll(el);
	 		return document.querySelectorAll(el);
	 	},
		searchKey: function(arr, key, value){
			for (var i = arr.length; i--;) {
				if(arr[i][key]==value) return i;
			};
			return null;
		}
	},
	selectTree = (function(el){
		var app = {
			active: false,
			disabled: false,
			list: [],
			fathers: [],
			el: {},
			value: null,
			empty: "Sem itens para os pai(s) selecionados", // DEFAULT MESSAGE EMPTY
			beforeOptions: "", //DEFAULT AFTER OPTION
			_getValueFather: function(key){
				var temp = get.item('select[data-shr-id="'+key+'"]'),
				val;
				if(temp===null) {
					throw "SelectTree: Father ("+key+") not found";
				}
				val = temp.value;
				app.fathers.push({'id': key,'value': val,'el': temp});
			},
			_updateValueFather: function(){
				var fathers = app.fathers;
				app.fathers = [];
				for (var i = fathers.length; i--;) {
					app._getValueFather(fathers[i].id);
				}
				app._checkDisabled();
			},
			_checkDisabled: function(){
				var disabled = false;
				for (var i = app.fathers.length; i--;) {
					if(app.fathers[i].value==="choose")
						disabled = true;
				}
				if(disabled) app.disabled = true
				console.log(app.disabled);
				if(app.disabled) return app.el.setAttribute("disabled","on");
				app.el.removeAttribute("disabled");
			},
			_filter: function(option){
				for (var i = app.fathers.length; i--;) {
					if(app.fathers[i].value!="all" && app.fathers[i].value!="choose"){
						if(typeof(option[app.fathers[i].id])==="undefined") return false;
						// CONFERIR LANCE DE COMPRAÇÂO DE STRING COM NUMBER DO INDEX OF
						if(option[app.fathers[i].id].indexOf(app.fathers[i].value)===-1) return false;
					}
				}
				return true;
			},
			_clearSelected: function(){
				for (var i = app.list.length; i--;) {
					if(app.list[i].html.indexOf('selected')) {
						app.list[i].html = app.list[i].html.replace('selected="on"', "");
						app.list[i].html = app.list[i].html.replace("selected", "");
					}
				}
			},
			buildOptions: function(){
				var string = "";
				for (var i = app.list.length; i--;) {
					if(app._filter(app.list[i]))
						string = app.list[i].html + string;
				};
				if(string===""){
					app.disabled = true;
					console.log("entrou")
					string = '<option disabled="on" value="" selected="on">'+app.empty+'</option>';
				} else {
					app.disabled = false;
					string = app.beforeOptions.html + string;
				}
				app.el.innerHTML = string;
				app._checkDisabled();
			},
			statusSelect: function(){
				var dataset = app.el.dataset;
				if(dataset.shrValue){
					app.value = dataset['shrValue'];
					delete dataset['shrValue'];
				}
				if(dataset.shrEmpty) app.empty = dataset.shrEmpty;
				app._checkDisabled();
			},
			setEvents: function(){
				var flag = true;
				for (var i = app.fathers.length; i--;) {
					app.fathers[i].el.addEventListener('change',function(){
						app._updateValueFather();
						app.buildOptions();
					},false);
					app.fathers[i].el.addEventListener('DOMSubtreeModified',function(){
						//EVENTO @DOMSubtreeModified É DISPARADO DUAS VEZES
						//FLAG e SeTimeout PARA NÃO EXECUTAR DUAS VEZES
						if(flag){
							flag = false;
							setTimeout(function(){
								app._updateValueFather();
								app.buildOptions();
								flag = true;
							},20);
						}
					},false);
				}
				setTimeout(app._clearSelected, 500); //CLEAR SELECTED OF LIST AFTER INIT PROGRAM
			},
			list: function(select){
				var elOptions = get.all("option",select),
				list = [],
				dataset = {},
				valueCheck = [],
				listTemp,
				val = 0,
				keySearch;
				for (var i = 0, lim = elOptions.length; i<lim; i++) {
					val = elOptions[i].value
					listTemp = {'value': val};

					keySearch = null;
					if(valueCheck.indexOf(val)!==-1) {
						keySearch = get.searchKey(list, 'value', val);
					}
					valueCheck.push(elOptions[i].value);
					if(keySearch!==null) listTemp = list[keySearch]

					//PERCORRER OBJETO DATASET
					dataset = elOptions[i].dataset;
					for (var key in dataset) if(dataset.hasOwnProperty(key)) {
						// IF HAVE DATA OF SELECTTREE - @data-cod | @dataCod
						if(key.indexOf("Cod")!=-1){
							if(keySearch!==null && key in listTemp) {
								listTemp[key] = listTemp[key].concat(dataset[key].split(","));
							} else {
								listTemp[key] = dataset[key].split(",");
							}
							delete dataset[key];
							if(!app.active) app.active = true;
							if(get.searchKey(app.fathers,'id',key)===null)
								app._getValueFather(key);
						}
					}

					// SETA VALUE DEFAULT
					if(val==app.value) elOptions[i].setAttribute('selected','on');
					if(elOptions[i].hasAttribute('selected')){
						if(app.value==null) app.value = val;
						if(app.value!=val) elOptions[i].removeAttribute('selected');
					}
					listTemp.html = elOptions[i].outerHTML;

					if(val === "all" || val === "choose" ){
						app.beforeOptions = listTemp;
					} else {
						if(keySearch===null){
							list.push(listTemp);
						} else {
							list[keySearch] = listTemp;
						}
					}
				};
				return list;
			}
		}
		app.el = el;
		app.statusSelect();
		app.list = app.list(el); //FOR CLEAN FUNCTION LIST WITH ARRAY LIST - CLEAN MEMORY
		app.buildOptions();
		if(!app.active) return 0;
		app.setEvents();
		console.dir(app);
	});
	var el = get.all(selectTreeSelector);
	for (var i = el.length - 1; i >= 0; i--) {
		selectTree(el[i]);
	};
}());<|endoftext|>


<commit_before>/**
 * SuperBox v2.0.0
 *
 * The lightbox reimagined. Fully responsive HTML5 image galleries.
 *
 * Latest version: https://github.com/toddmotto/superbox
 *
 * Copyright 2013 Todd Motto <http://www.toddmotto.com> / Adam Merrifield <http://seydesign.com>
 *
 * Licensed under the MIT license <http://www.opensource.org/licenses/mit-license.php>
 */
(function(a){a.fn.SuperBox=function(e){var f=a.extend({background:null,border:null,xColor:null,xShadow:"none"},e);var b=a('
'),h=a(''),d=a('×'),c=a('
'),g=this.find(">div");b.append(h).append(d).insertAfter(g);c.appendTo(this);this.addClass("superbox-active");if(f.background!==null){g.next().css({"background-color":f.background})}if(f.border!==null){g.next().find("img.superbox-current-img").css({"border-color":f.border})}if(f.xColor!==null){g.next().find("a.superbox-close").css({color:f.xColor})}if(f.xShadow=="emboss"){g.next().find("a.superbox-close").css({"text-shadow":"0 1px 0 rgba(0,0,0,0.6), 0 -1px 0 rgba(250,250,250,0.2)"})}else{if(f.xShadow=="embed"){g.next().find("a.superbox-close").css({"text-shadow":"0 -1px 0 rgba(0,0,0,0.4), 0 1px 0 rgba(250,250,250,0.5)"})}}g.each(function(){var i=a(this).find("img").data("img");a(this).next().find("img.superbox-current-img").attr("src",i);a(this).on("click",function(){g.next(".superbox-O").removeClass("superbox-O").addClass("superbox-X").find("img.superbox-current-img, div.superbox-close").animate({opacity:0},100).end().slideUp();a(this).next().removeClass("superbox-X").addClass("superbox-O").slideDown(function(){a("html,body").animate({scrollTop:(a(".superbox-O").offset().top)-((a(window).height()-a(".superbox-O").height())/2)},"fast")}).find("img.superbox-current-img, div.superbox-close").animate({opacity:1},1000)})});a(".superbox-close").on("click",function(i){i.preventDefault();a(this).add(a(this).siblings()).animate({opacity:0},100).parent().slideUp()});return this}})(jQuery);<commit_msg>Corrected selector on superbox-close.<commit_after>/**
 * SuperBox v2.0.0
 *
 * The lightbox reimagined. Fully responsive HTML5 image galleries.
 *
 * Latest version: https://github.com/toddmotto/superbox
 *
 * Copyright 2013 Todd Motto <http://www.toddmotto.com> / Adam Merrifield <http://seydesign.com>
 *
 * Licensed under the MIT license <http://www.opensource.org/licenses/mit-license.php>
 */
(function(a){a.fn.SuperBox=function(e){var f=a.extend({background:null,border:null,xColor:null,xShadow:"none"},e);var b=a('
'),h=a(''),d=a('×'),c=a('
'),g=this.find(">div");b.append(h).append(d).insertAfter(g);c.appendTo(this);this.addClass("superbox-active");if(f.background!==null){g.next().css({"background-color":f.background})}if(f.border!==null){g.next().find("img.superbox-current-img").css({"border-color":f.border})}if(f.xColor!==null){g.next().find("a.superbox-close").css({color:f.xColor})}if(f.xShadow=="emboss"){g.next().find("a.superbox-close").css({"text-shadow":"0 1px 0 rgba(0,0,0,0.6), 0 -1px 0 rgba(250,250,250,0.2)"})}else{if(f.xShadow=="embed"){g.next().find("a.superbox-close").css({"text-shadow":"0 -1px 0 rgba(0,0,0,0.4), 0 1px 0 rgba(250,250,250,0.5)"})}}g.each(function(){var i=a(this).find("img").data("img");a(this).next().find("img.superbox-current-img").attr("src",i);a(this).on("click",function(){g.next(".superbox-O").removeClass("superbox-O").addClass("superbox-X").find("img.superbox-current-img, a.superbox-close").animate({opacity:0},100).end().slideUp();a(this).next().removeClass("superbox-X").addClass("superbox-O").slideDown(function(){a("html,body").animate({scrollTop:(a(".superbox-O").offset().top)-((a(window).height()-a(".superbox-O").height())/2)},"fast")}).find("img.superbox-current-img, a.superbox-close").animate({opacity:1},1000)})});a(".superbox-close").on("click",function(i){i.preventDefault();a(this).add(a(this).siblings()).animate({opacity:0},100).parent().slideUp()});return this}})(jQuery);<|endoftext|>


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

/**
 * @fileoverview [MODULE: edit] The toolbar for editing commands.
 * @author kpy@google.com (Ka-Ping Yee)
 */
goog.provide('cm.ToolbarView');

goog.require('cm.MapModel');
goog.require('cm.css');
goog.require('cm.events');
goog.require('cm.ui');
goog.require('goog.dom');
goog.require('goog.format.JsonPrettyPrinter');
goog.require('goog.json');
goog.require('goog.net.XhrIo');
goog.require('goog.string');

/** @desc Label for a link that lets the user rearrange the layer
 *  order and hierarchy.
 */

/** @desc Link text to arrange the layers in the panel. */
var MSG_ARRANGE_LAYERS_LINK = goog.getMsg('Arrange');

/** @desc Link text to arrange the layers in the panel. */
var MSG_SHARE_EMAIL_LINK = goog.getMsg('Share with user');

/** @desc Link text to add a new layer to the map. */
var MSG_ADD_NEW_LAYERS = goog.getMsg('Add layers');

/** @desc Default title for an empty layer. */
var MSG_UNTITLED_LAYER = goog.getMsg('Untitled Layer');

/** @desc Link text to add a new folder to the map. */
var MSG_ADD_NEW_FOLDER = goog.getMsg('Add folder');

/** @desc Link text to return to map list. */
var MSG_BACK_TO_MAP_LIST = goog.getMsg('Back to map list');

/** @desc Link text to documentation on how to use the map editor. */
var MSG_HELP_LINK = goog.getMsg('Help');

/** @desc Default title for an empty folder. */
var MSG_UNTITLED_FOLDER = goog.getMsg('Untitled Folder');

/** @desc Warning message when discarding unsaved changes. */
var MSG_UNSAVED_CHANGES = goog.getMsg(
    'You have unsaved changes that will be lost if you leave' +
    ' the page without clicking the "Save" link.');

/* TODO(rew): This link needs to be updated when the draft document is
   finalized and published in its permanent location. */
/* URL to the help document for editing maps. */
var HELP_LINK_URL = 'https://docs.google.com/document/d/' +
    '1cp9hLYJzGZZtM6IyO2WqIUvolU1WyCadlI_pGGtBGDY/edit#';

/**
 * A command toolbar.  For now, this is just a few links, but in future will
 * contain other editing/drawing functions.
 * @param {Element} parentElem The DOM element in which to render the toolbar.
 * @param {cm.MapModel} mapModel The map model.
 * @param {boolean} enableSave True to enable the "Save" function.
 * @param {boolean} devMode True to enable the "Show JSON" function.
 * @param {string} mapListUrl The URL endpoint for the user's map list.
 * @param {boolean} touch True if the map is being edited on a touch device.
 * @param {string=} opt_diffUrl URL used in devMode to diff the current
 *     maproot against the original maproot.
 * @constructor
 */
cm.ToolbarView = function(parentElem, mapModel, enableSave, devMode, mapListUrl,
    touch, opt_diffUrl) {
  var shareEmailLink = cm.ui.createLink(MSG_SHARE_EMAIL_LINK);
  cm.events.forward(shareEmailLink, 'click',
                    goog.global, cm.events.SHARE_EMAIL);

  // TODO(romano): move the toolbars into the inner panel element, which
  // contains the collapse button, map title, description, and layers.
  var toolbarElem = cm.ui.create('div', {'class': cm.css.TOOLBAR},
      cm.ui.createLink(MSG_BACK_TO_MAP_LIST, mapListUrl),
      cm.ui.SEPARATOR_DOT, shareEmailLink);

  var helpLink = cm.ui.createLink(MSG_HELP_LINK, HELP_LINK_URL, '_blank');
  cm.ui.append(toolbarElem, cm.ui.SEPARATOR_DOT, helpLink);

  // Initially, neither the undo nor the redo operation can be done.
  var undoLink = cm.ui.createLink('Undo');
  var redoLink = cm.ui.createLink('Redo');
  goog.dom.classes.add(undoLink, cm.css.DISABLED);
  goog.dom.classes.add(redoLink, cm.css.DISABLED);

  var undoLinkEventToken = cm.events.forward(undoLink, 'click',
      goog.global, cm.events.UNDO);
  var redoLinkEventToken = cm.events.forward(redoLink, 'click',
      goog.global, cm.events.REDO);

  cm.events.listen(goog.global, cm.events.UNDO_REDO_BUFFER_CHANGED,
    function(e) {
      goog.dom.classes.enable(undoLink, cm.css.DISABLED, !e.undo_possible);
      goog.dom.classes.enable(redoLink, cm.css.DISABLED, !e.redo_possible);
  }, this);

  var editToolbarElem = cm.ui.create('div', {'class': cm.css.EDIT_TOOLBAR},
      undoLink, cm.ui.SEPARATOR_DOT, redoLink);

  if (enableSave) {
    var saveLink = cm.ui.createLink('Saved');
    cm.ui.append(editToolbarElem, cm.ui.SEPARATOR_DOT, saveLink);

    // The "Save" link is initially disabled. Changing the model enables it.
    goog.dom.classes.add(saveLink, cm.css.DISABLED);
    cm.events.listen(goog.global, cm.events.MODEL_CHANGED, function() {
      cm.ui.setText(saveLink, 'Save');
      goog.dom.classes.remove(saveLink, cm.css.DISABLED, cm.css.ERROR);
    }, this);

    // Handle clicks on the "Save" link.
    cm.events.listen(saveLink, 'click', function() {
      if (!goog.dom.classes.has(saveLink, cm.css.DISABLED)) {
        cm.ui.setText(saveLink, 'Saving...');
        goog.dom.classes.remove(saveLink, cm.css.ERROR);
        goog.dom.classes.add(saveLink, cm.css.DISABLED);
        cm.events.emit(goog.global, cm.events.SAVE, {model: mapModel});
      }
    });

    // Handle completion of the Save operation.
    cm.events.listen(goog.global, cm.events.SAVE_DONE, function() {
      cm.ui.setText(saveLink, 'Saved');
    }, this);
    cm.events.listen(goog.global, cm.events.SAVE_FAILED, function() {
      // If the save fails, leave the link enabled so the user can click it
      // to try again.  Not the most elegant solution, but good enough for now.
      goog.dom.classes.remove(saveLink, cm.css.DISABLED);
      goog.dom.classes.add(saveLink, cm.css.ERROR);
      cm.ui.setText(saveLink, 'Save failed');
    }, this);

    // This way works for Chrome, Firefox.
    // cm.events.listen only works in Chrome.
    // In Chrome, this event will not get fired if you navigate to another page
    // within this app via the navigation bar.
    window.onbeforeunload = function() {
      if (!goog.dom.classes.has(saveLink, cm.css.DISABLED)) {
        return MSG_UNSAVED_CHANGES;
      }
    };
  }

  var addNewLayerLink = cm.ui.createLink(MSG_ADD_NEW_LAYERS);
  cm.events.forward(addNewLayerLink, 'click', goog.global,
      cm.events.IMPORT);
  cm.ui.append(editToolbarElem, cm.ui.SEPARATOR_DOT,
               addNewLayerLink, cm.ui.SEPARATOR_DOT);

  // TODO(joeysilva): Use INSPECT event to create new folders by using a type
  // FOLDER argument.
  var addNewFolderLink = cm.ui.createLink(MSG_ADD_NEW_FOLDER);
  cm.events.forward(
      addNewFolderLink, 'click', goog.global, cm.events.ADD_LAYERS, {
        layers: [{title: MSG_UNTITLED_FOLDER, type: cm.LayerModel.Type.FOLDER}]
      });
  cm.ui.append(editToolbarElem, addNewFolderLink, cm.ui.SEPARATOR_DOT);

  if (!touch) {
    var arrangeLink = cm.ui.createLink(MSG_ARRANGE_LAYERS_LINK);
    cm.events.forward(arrangeLink, 'click', goog.global, cm.events.ARRANGE);
    cm.ui.append(editToolbarElem, arrangeLink);
  }

  if (devMode) {
    var diffJsonLink = cm.ui.createLink(opt_diffUrl ? 'Diff' : 'Show JSON');
    cm.events.listen(diffJsonLink, 'click', goog.bind(
        this.handleDiffJsonClick_, this, mapModel, opt_diffUrl));
    cm.ui.append(editToolbarElem, cm.ui.SEPARATOR_DOT, diffJsonLink);
  }

  toolbarElem.appendChild(editToolbarElem);
  parentElem.appendChild(toolbarElem);
};

/**
 * Displays a popup showing diffs between the MapRoot JSON of the most recently
 * saved draft as well as any/all published versions of this map, against the
 * current, unsaved draft. Will simply show the current, unsaved draft if no
 * map ID is provided.
 * @param {cm.MapModel} mapModel The map model.
 * @param {string=} opt_diffUrl URL used to retrieve diffs between the current,
 *     currently saved, and published versions of this map.
 * @private
 */
cm.ToolbarView.prototype.handleDiffJsonClick_ =
    function(mapModel, opt_diffUrl) {
  var popup = cm.ui.create('div', {'class': [cm.css.POPUP, cm.css.DIFF]});
  cm.ui.createCloseButton(
      popup, function() { goog.dom.removeNode(popup); });
  cm.ui.showPopup(popup);

  // Define links and content element used by showJson and showDiff methods.
  var showJsonLink, showDiffLink;
  var contentElem = cm.ui.create('div');

  // Method to show JSON. Used by JSON link, and when diffs cannot be loaded.
  var showJson = function() {
    contentElem.innerHTML = goog.string.htmlEscape(
        new goog.format.JsonPrettyPrinter(
            new goog.format.JsonPrettyPrinter.TextDelimiters()).
            format(mapModel.toMapRoot())).
        replace(/ /g, ' ').replace(/\n/g, '<br>');

    showJsonLink && goog.style.setElementShown(showJsonLink, false);
    showDiffLink && goog.style.setElementShown(showDiffLink, true);
    cm.ui.showPopup(popup);
  };

  if (opt_diffUrl) {
    // Request diffs and show them.
    var loading = cm.ui.create('span', {}, 'Loading diff...');
    cm.ui.append(popup, loading);
    goog.net.XhrIo.send(opt_diffUrl, function(e) {
      cm.ui.remove(loading);
      if (e.target.isSuccess()) {
        // Stored diffs, along with method to show one based on the select
        // element's current selection. Used by select element, as well as
        // diff link.
        var htmlDiffs, diffSelectElem;
        var showDiff = function() {
          // TODO(joeysilva): Fix bug where line numbers are compacted.
          contentElem.innerHTML = htmlDiffs[diffSelectElem.selectedIndex];
          goog.style.setElementShown(showJsonLink, true);
          goog.style.setElementShown(showDiffLink, false);
          cm.ui.showPopup(popup);
        };

        cm.ui.append(popup,
            'Diff against: ', diffSelectElem = cm.ui.create('select', {},
                cm.ui.create('option', {}, 'Saved')),
            cm.ui.SEPARATOR_DASH,
            showJsonLink = cm.ui.createLink('Show JSON'),
            showDiffLink = cm.ui.createLink('Show diff'),
            cm.ui.create('br'), cm.ui.create('br'),
            contentElem);

        var response = e.target.getResponseJson();
        htmlDiffs = [response['saved_diff']];
        goog.array.forEach(response['catalog_diffs'], function(entry) {
          cm.ui.append(diffSelectElem,
              cm.ui.create('option', {}, entry['name']));
          htmlDiffs.push(entry['diff']);
        });

        cm.events.listen(diffSelectElem, 'change', showDiff);
        cm.events.listen(showDiffLink, 'click', showDiff);
        showDiff();
      } else {
        cm.ui.append(popup, 'Failed to load diff',
            cm.ui.SEPARATOR_DASH,
            showJsonLink = cm.ui.createLink('Show JSON'),
            cm.ui.create('br'), cm.ui.create('br'),
            contentElem);
      }
      cm.events.listen(showJsonLink, 'click', showJson);

    }, 'POST', 'new_json=' + encodeURIComponent(
        goog.json.serialize(mapModel.toMapRoot())));
  } else {
    // No map ID; just show the JSON.
    cm.ui.append(popup, contentElem);
    showJson();
  }
};
<commit_msg>Switch to published version of the documentation. ------------- Created by MOE: http://code.google.com/p/moe-java MOE_MIGRATED_REVID=45063422<commit_after>// Copyright 2012 Google Inc.  All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License.  You may obtain a copy
// of the License at: http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distrib-
// uted under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
// OR CONDITIONS OF ANY KIND, either express or implied.  See the License for
// specific language governing permissions and limitations under the License.

/**
 * @fileoverview [MODULE: edit] The toolbar for editing commands.
 * @author kpy@google.com (Ka-Ping Yee)
 */
goog.provide('cm.ToolbarView');

goog.require('cm.MapModel');
goog.require('cm.css');
goog.require('cm.events');
goog.require('cm.ui');
goog.require('goog.dom');
goog.require('goog.format.JsonPrettyPrinter');
goog.require('goog.json');
goog.require('goog.net.XhrIo');
goog.require('goog.string');

/** @desc Label for a link that lets the user rearrange the layer
 *  order and hierarchy.
 */

/** @desc Link text to arrange the layers in the panel. */
var MSG_ARRANGE_LAYERS_LINK = goog.getMsg('Arrange');

/** @desc Link text to arrange the layers in the panel. */
var MSG_SHARE_EMAIL_LINK = goog.getMsg('Share with user');

/** @desc Link text to add a new layer to the map. */
var MSG_ADD_NEW_LAYERS = goog.getMsg('Add layers');

/** @desc Default title for an empty layer. */
var MSG_UNTITLED_LAYER = goog.getMsg('Untitled Layer');

/** @desc Link text to add a new folder to the map. */
var MSG_ADD_NEW_FOLDER = goog.getMsg('Add folder');

/** @desc Link text to return to map list. */
var MSG_BACK_TO_MAP_LIST = goog.getMsg('Back to map list');

/** @desc Link text to documentation on how to use the map editor. */
var MSG_HELP_LINK = goog.getMsg('Help');

/** @desc Default title for an empty folder. */
var MSG_UNTITLED_FOLDER = goog.getMsg('Untitled Folder');

/** @desc Warning message when discarding unsaved changes. */
var MSG_UNSAVED_CHANGES = goog.getMsg(
    'You have unsaved changes that will be lost if you leave' +
    ' the page without clicking the "Save" link.');

/* TODO(rew): This link needs to be updated when the draft document is
   finalized and published in its permanent location. */
/* URL to the help document for editing maps. */
var HELP_LINK_URL = 'https://docs.google.com/document/d/' +
    '1cp9hLYJzGZZtM6IyO2WqIUvolU1WyCadlI_pGGtBGDY/pub';

/**
 * A command toolbar.  For now, this is just a few links, but in future will
 * contain other editing/drawing functions.
 * @param {Element} parentElem The DOM element in which to render the toolbar.
 * @param {cm.MapModel} mapModel The map model.
 * @param {boolean} enableSave True to enable the "Save" function.
 * @param {boolean} devMode True to enable the "Show JSON" function.
 * @param {string} mapListUrl The URL endpoint for the user's map list.
 * @param {boolean} touch True if the map is being edited on a touch device.
 * @param {string=} opt_diffUrl URL used in devMode to diff the current
 *     maproot against the original maproot.
 * @constructor
 */
cm.ToolbarView = function(parentElem, mapModel, enableSave, devMode, mapListUrl,
    touch, opt_diffUrl) {
  var shareEmailLink = cm.ui.createLink(MSG_SHARE_EMAIL_LINK);
  cm.events.forward(shareEmailLink, 'click',
                    goog.global, cm.events.SHARE_EMAIL);

  // TODO(romano): move the toolbars into the inner panel element, which
  // contains the collapse button, map title, description, and layers.
  var toolbarElem = cm.ui.create('div', {'class': cm.css.TOOLBAR},
      cm.ui.createLink(MSG_BACK_TO_MAP_LIST, mapListUrl),
      cm.ui.SEPARATOR_DOT, shareEmailLink);

  var helpLink = cm.ui.createLink(MSG_HELP_LINK, HELP_LINK_URL, '_blank');
  cm.ui.append(toolbarElem, cm.ui.SEPARATOR_DOT, helpLink);

  // Initially, neither the undo nor the redo operation can be done.
  var undoLink = cm.ui.createLink('Undo');
  var redoLink = cm.ui.createLink('Redo');
  goog.dom.classes.add(undoLink, cm.css.DISABLED);
  goog.dom.classes.add(redoLink, cm.css.DISABLED);

  var undoLinkEventToken = cm.events.forward(undoLink, 'click',
      goog.global, cm.events.UNDO);
  var redoLinkEventToken = cm.events.forward(redoLink, 'click',
      goog.global, cm.events.REDO);

  cm.events.listen(goog.global, cm.events.UNDO_REDO_BUFFER_CHANGED,
    function(e) {
      goog.dom.classes.enable(undoLink, cm.css.DISABLED, !e.undo_possible);
      goog.dom.classes.enable(redoLink, cm.css.DISABLED, !e.redo_possible);
  }, this);

  var editToolbarElem = cm.ui.create('div', {'class': cm.css.EDIT_TOOLBAR},
      undoLink, cm.ui.SEPARATOR_DOT, redoLink);

  if (enableSave) {
    var saveLink = cm.ui.createLink('Saved');
    cm.ui.append(editToolbarElem, cm.ui.SEPARATOR_DOT, saveLink);

    // The "Save" link is initially disabled. Changing the model enables it.
    goog.dom.classes.add(saveLink, cm.css.DISABLED);
    cm.events.listen(goog.global, cm.events.MODEL_CHANGED, function() {
      cm.ui.setText(saveLink, 'Save');
      goog.dom.classes.remove(saveLink, cm.css.DISABLED, cm.css.ERROR);
    }, this);

    // Handle clicks on the "Save" link.
    cm.events.listen(saveLink, 'click', function() {
      if (!goog.dom.classes.has(saveLink, cm.css.DISABLED)) {
        cm.ui.setText(saveLink, 'Saving...');
        goog.dom.classes.remove(saveLink, cm.css.ERROR);
        goog.dom.classes.add(saveLink, cm.css.DISABLED);
        cm.events.emit(goog.global, cm.events.SAVE, {model: mapModel});
      }
    });

    // Handle completion of the Save operation.
    cm.events.listen(goog.global, cm.events.SAVE_DONE, function() {
      cm.ui.setText(saveLink, 'Saved');
    }, this);
    cm.events.listen(goog.global, cm.events.SAVE_FAILED, function() {
      // If the save fails, leave the link enabled so the user can click it
      // to try again.  Not the most elegant solution, but good enough for now.
      goog.dom.classes.remove(saveLink, cm.css.DISABLED);
      goog.dom.classes.add(saveLink, cm.css.ERROR);
      cm.ui.setText(saveLink, 'Save failed');
    }, this);

    // This way works for Chrome, Firefox.
    // cm.events.listen only works in Chrome.
    // In Chrome, this event will not get fired if you navigate to another page
    // within this app via the navigation bar.
    window.onbeforeunload = function() {
      if (!goog.dom.classes.has(saveLink, cm.css.DISABLED)) {
        return MSG_UNSAVED_CHANGES;
      }
    };
  }

  var addNewLayerLink = cm.ui.createLink(MSG_ADD_NEW_LAYERS);
  cm.events.forward(addNewLayerLink, 'click', goog.global,
      cm.events.IMPORT);
  cm.ui.append(editToolbarElem, cm.ui.SEPARATOR_DOT,
               addNewLayerLink, cm.ui.SEPARATOR_DOT);

  // TODO(joeysilva): Use INSPECT event to create new folders by using a type
  // FOLDER argument.
  var addNewFolderLink = cm.ui.createLink(MSG_ADD_NEW_FOLDER);
  cm.events.forward(
      addNewFolderLink, 'click', goog.global, cm.events.ADD_LAYERS, {
        layers: [{title: MSG_UNTITLED_FOLDER, type: cm.LayerModel.Type.FOLDER}]
      });
  cm.ui.append(editToolbarElem, addNewFolderLink, cm.ui.SEPARATOR_DOT);

  if (!touch) {
    var arrangeLink = cm.ui.createLink(MSG_ARRANGE_LAYERS_LINK);
    cm.events.forward(arrangeLink, 'click', goog.global, cm.events.ARRANGE);
    cm.ui.append(editToolbarElem, arrangeLink);
  }

  if (devMode) {
    var diffJsonLink = cm.ui.createLink(opt_diffUrl ? 'Diff' : 'Show JSON');
    cm.events.listen(diffJsonLink, 'click', goog.bind(
        this.handleDiffJsonClick_, this, mapModel, opt_diffUrl));
    cm.ui.append(editToolbarElem, cm.ui.SEPARATOR_DOT, diffJsonLink);
  }

  toolbarElem.appendChild(editToolbarElem);
  parentElem.appendChild(toolbarElem);
};

/**
 * Displays a popup showing diffs between the MapRoot JSON of the most recently
 * saved draft as well as any/all published versions of this map, against the
 * current, unsaved draft. Will simply show the current, unsaved draft if no
 * map ID is provided.
 * @param {cm.MapModel} mapModel The map model.
 * @param {string=} opt_diffUrl URL used to retrieve diffs between the current,
 *     currently saved, and published versions of this map.
 * @private
 */
cm.ToolbarView.prototype.handleDiffJsonClick_ =
    function(mapModel, opt_diffUrl) {
  var popup = cm.ui.create('div', {'class': [cm.css.POPUP, cm.css.DIFF]});
  cm.ui.createCloseButton(
      popup, function() { goog.dom.removeNode(popup); });
  cm.ui.showPopup(popup);

  // Define links and content element used by showJson and showDiff methods.
  var showJsonLink, showDiffLink;
  var contentElem = cm.ui.create('div');

  // Method to show JSON. Used by JSON link, and when diffs cannot be loaded.
  var showJson = function() {
    contentElem.innerHTML = goog.string.htmlEscape(
        new goog.format.JsonPrettyPrinter(
            new goog.format.JsonPrettyPrinter.TextDelimiters()).
            format(mapModel.toMapRoot())).
        replace(/ /g, ' ').replace(/\n/g, '<br>');

    showJsonLink && goog.style.setElementShown(showJsonLink, false);
    showDiffLink && goog.style.setElementShown(showDiffLink, true);
    cm.ui.showPopup(popup);
  };

  if (opt_diffUrl) {
    // Request diffs and show them.
    var loading = cm.ui.create('span', {}, 'Loading diff...');
    cm.ui.append(popup, loading);
    goog.net.XhrIo.send(opt_diffUrl, function(e) {
      cm.ui.remove(loading);
      if (e.target.isSuccess()) {
        // Stored diffs, along with method to show one based on the select
        // element's current selection. Used by select element, as well as
        // diff link.
        var htmlDiffs, diffSelectElem;
        var showDiff = function() {
          // TODO(joeysilva): Fix bug where line numbers are compacted.
          contentElem.innerHTML = htmlDiffs[diffSelectElem.selectedIndex];
          goog.style.setElementShown(showJsonLink, true);
          goog.style.setElementShown(showDiffLink, false);
          cm.ui.showPopup(popup);
        };

        cm.ui.append(popup,
            'Diff against: ', diffSelectElem = cm.ui.create('select', {},
                cm.ui.create('option', {}, 'Saved')),
            cm.ui.SEPARATOR_DASH,
            showJsonLink = cm.ui.createLink('Show JSON'),
            showDiffLink = cm.ui.createLink('Show diff'),
            cm.ui.create('br'), cm.ui.create('br'),
            contentElem);

        var response = e.target.getResponseJson();
        htmlDiffs = [response['saved_diff']];
        goog.array.forEach(response['catalog_diffs'], function(entry) {
          cm.ui.append(diffSelectElem,
              cm.ui.create('option', {}, entry['name']));
          htmlDiffs.push(entry['diff']);
        });

        cm.events.listen(diffSelectElem, 'change', showDiff);
        cm.events.listen(showDiffLink, 'click', showDiff);
        showDiff();
      } else {
        cm.ui.append(popup, 'Failed to load diff',
            cm.ui.SEPARATOR_DASH,
            showJsonLink = cm.ui.createLink('Show JSON'),
            cm.ui.create('br'), cm.ui.create('br'),
            contentElem);
      }
      cm.events.listen(showJsonLink, 'click', showJson);

    }, 'POST', 'new_json=' + encodeURIComponent(
        goog.json.serialize(mapModel.toMapRoot())));
  } else {
    // No map ID; just show the JSON.
    cm.ui.append(popup, contentElem);
    showJson();
  }
};
<|endoftext|>


<commit_before>ScriptLoader.load(
    'GridManager'
);
var FILE_COOKIE_NAME = 'NRGNFRPID';

Grid.implement({
    _popImage:function (path, tmplElement) {
        var popUpImg = new Element('img', {'src':'resizer/w298-h224/' + path, 'width':60, 'height':45, 'styles':{
            border:'1px solid gray',
            'border-radius':'10px',
            'z-index':100
        }, 'events':{
            'click':function (e) {
                this.destroy()
            },
            'mouseleave':function (e) {
                this.destroy();
            }
        }}).inject(document.body).position({'relativeTo':tmplElement, 'position':'center'}).set('morph', {duration: 'short', transition: 'linear'});
        var p = popUpImg.getPosition();
        popUpImg.morph({width:298, height:224, left:p.x-112, top:p.y-149});
    },
    iterateFields:function (record, fieldName, row) {
// Пропускаем невидимые поля.
        if (!this.metadata[fieldName].visible ||
            this.metadata[fieldName].type == 'hidden') return;
        var cell = new Element('td').injectInside(row);
        if (fieldName == 'upl_path') {
            cell.setStyles({ 'text-align':'center', 'vertical-align':'middle' });
            var image = new Element('img',{'width':60, 'height':45 }).injectInside(cell);
            var tmt;
            switch (record['upl_internal_type']) {
                case 'folder':
                    image.setProperty('src', 'images/icons/icon_folder.gif');
                    break;
                case 'repo':
                    image.setProperty('src', 'images/icons/icon_repository.gif');
                    break;
                case 'folderup':
                    image.setProperty('src', 'images/icons/icon_folder_up.gif');
                    break;
                case 'video':
                case 'image':
                    image.setProperty('src', 'resizer/w60-h45/' + record[fieldName]).addEvents({
                        'mouseenter':function (e) {
                            var el = $(e.target);
                            el.setStyle('border', '1px solid gray');
                            tmt = this._popImage.delay(700, this, [record[fieldName], el])
                        }.bind(this),
                        'mouseleave':function (e) {
                            var el = $(e.target);
                            el.setStyle('border', '1px solid transparent');
                            if(tmt){
                                clearTimeout(tmt);
                            }
                        }
                    }).setStyles({'border-radius': '5px', 'border':'1px solid transparent'});
                    break;
                default:
                    image.setProperty('src', 'images/icons/icon_undefined.gif');
                    break;
            }

        }
        else {
            var fieldValue = '';
            if (record[fieldName]) {
                var fieldValue = record[fieldName].clean();
            }
            if (fieldValue != '') cell.set('html', fieldValue);
            //if (fieldValue != '') cell.appendText(fieldValue);
            else cell.set('html', ' ');
        }
    }
});
var FileRepository = new Class({
    Extends:GridManager,
    initialize:function (element) {
        this.parent(element);
        this.currentPID = false;
    },
    onDoubleClick:function () {
        this.open();
    },
    onSelect:function () {
        var r = this.grid.getSelectedRecord(), control;
        this.toolbar.enableControls();
        var openBtn = this.toolbar.getControlById('open');
        switch (r.upl_internal_type) {
            case 'folder':
                if (openBtn)openBtn.enable();
                break;
            case 'folderup':
                this.toolbar.disableControls();
                if (openBtn)openBtn.enable();
                this.toolbar.getControlById('addDir').enable();
                this.toolbar.getControlById('add').enable()
                break;
            case 'repo':
                this.toolbar.disableControls();
                if (openBtn)openBtn.enable();
                break;
            default:
                //this.toolbar.getControlById('open').disable();
                break;
        }
    },
    processServerResponse:function (result) {

        if (!this.initialized) {
            this.grid.setMetadata(result.meta);
            this.initialized = true;
        }
        if (!result.data) {
            result.data = [];
        }
        if (this.currentPID)
            Cookie.write(FILE_COOKIE_NAME, this.currentPID, {path:new URI(Energine.base).get('directory'), duration:1});
        /*if (this.currentPID) {
         result.data.unshift({'upl_id':0, 'upl_internal_type':'folderup', 'upl_path':'', 'upl_pid':'', 'upl_title':'...'});
         }*/
        this.grid.setData(result.data);

        if (result.pager)
            this.pageList.build(result.pager.count, result.pager.current, result.pager.records);

        if (!this.grid.isEmpty()) {
            this.toolbar.enableControls();
            this.pageList.enable();
        }

        var controlsEnabledByDefault = ['add'];
        for (var i = 0, l = controlsEnabledByDefault.length; i < l; i++) {
            if (control = this.toolbar.getControlById(controlsEnabledByDefault[i])) control.enable();
        }

        this.grid.build();
        this.overlay.hide();
    },
    open:function () {
        var r = this.grid.getSelectedRecord();
        switch (r.upl_internal_type) {
            case 'repo':
            case 'folder':
                this.currentPID = r.upl_id;
                this.filter.remove();
                this.loadPage(1);
                break;
            case 'folderup':
                this.currentPID = r.upl_id;
                this.loadPage(1);
                break;
            default:
                ModalBox.setReturnValue(r);
                ModalBox.close();
                break;
        }
    },
    add:function () {
        var pid = this.grid.getSelectedRecord().upl_pid;
        if (pid) {
            pid += '/';
        }
        ModalBox.open({
            url:this.singlePath + pid + 'add/',
            onClose:this._processAfterCloseAction.bind(this)
        });
    },
    addDir:function () {
        var pid = this.grid.getSelectedRecord().upl_pid;
        if (pid) {
            pid += '/';
        }
        ModalBox.open({
            url:this.singlePath + pid + 'add-dir/',
            //onClose:this._processAfterCloseAction.bind(this)
            onClose:function (response) {
                if (response && response.result) {
                    this.currentPID = response.data;
                    this._processAfterCloseAction(response);
                }

            }.bind(this)
        });
    },
    uploadZip:function (data) {
        this.request(this.singlePath + 'upload-zip', 'PID=' + this.grid.getSelectedRecord().upl_pid + '&data=' + encodeURIComponent(data.result), function (response) {
            console.log(response)
        });
        //this.singlePath + 'upload-zip',
    },
    loadPage:function (pageNum) {
        this.pageList.disable();
        this.toolbar.disableControls();
        this.overlay.show();
        this.grid.clear();
        var level = '', cookiePID;

        if (this.currentPID === 0) {
            level = '';
        }
        else if (this.currentPID) {
            level = this.currentPID + '/';
        }
        else if (cookiePID = Cookie.read(FILE_COOKIE_NAME)) {
            this.currentPID = cookiePID;
            level = this.currentPID + '/';
        }

        var postBody = '', url = this.singlePath + level + 'get-data/' + 'page-' + pageNum + '/';
        //if (this.langId) postBody += 'languageID=' + this.langId + '&';
        postBody += this.filter.getValue();
        /*if (this.grid.sort.order) {
         url = this.singlePath + 'get-data/' + this.grid.sort.field + '-' +
         this.grid.sort.order + '/page-' + pageNum
         }*/
        this.request(url,
            postBody,
            this.processServerResponse.bind(this),
            null,
            this.processServerError.bind(this)
        );
    }
});
<commit_msg>В репозитории при наведении на thumbnail и задержке выводится увеличенное изображение<commit_after>ScriptLoader.load(
    'GridManager'
);
var FILE_COOKIE_NAME = 'NRGNFRPID';

Grid.implement({
    _popImage:function (path, tmplElement) {
        var popUpImg = new Element('img', {'src':'resizer/w298-h224/' + path, 'width':60, 'height':45, 'styles':{
            border:'1px solid gray',
            'border-radius':'10px',
            'z-index':100
        }, 'events':{
            'click':function (e) {
                this.destroy()
            },
            'mouseleave':function (e) {
                this.destroy();
            }
        }}).inject(document.body).position({'relativeTo':tmplElement, 'position':'center'}).set('morph', {duration: 'short', transition: 'linear'});
        var p = popUpImg.getPosition();
        popUpImg.morph({width:298, height:224, left:p.x-112, top:p.y-149});
    },
    iterateFields:function (record, fieldName, row) {
// Пропускаем невидимые поля.
        if (!this.metadata[fieldName].visible ||
            this.metadata[fieldName].type == 'hidden') return;
        var cell = new Element('td').injectInside(row);
        if (fieldName == 'upl_path') {
            cell.setStyles({ 'text-align':'center', 'vertical-align':'middle' });

            var image = new Element('img');
            var tmt, dimensions = {'width':40, 'height':40};
            switch (record['upl_internal_type']) {
                case 'folder':
                    image.setProperty('src', 'images/icons/icon_folder.gif');
                    break;
                case 'repo':
                    image.setProperty('src', 'images/icons/icon_repository.gif');
                    break;
                case 'folderup':
                    image.setProperty('src', 'images/icons/icon_folder_up.gif');
                    break;
                case 'video':
                case 'image':
                    dimensions = {'width':60, 'height':45};
                    image.setProperty('src', 'resizer/w60-h45/' + record[fieldName]).addEvents({
                        'error': function(){
                            image.setProperty('src', 'images/icons/icon_error_image.gif').removeEvents('mouseenter').removeEvent('mouseleave');
                        },
                        'mouseenter':function (e) {
                            var el = $(e.target);
                            el.setStyle('border', '1px solid gray');
                            tmt = this._popImage.delay(700, this, [record[fieldName], el])
                        }.bind(this),
                        'mouseleave':function (e) {
                            var el = $(e.target);
                            el.setStyle('border', '1px solid transparent');
                            if(tmt){
                                clearTimeout(tmt);
                            }
                        }
                    }).setStyles({'border-radius': '5px', 'border':'1px solid transparent'});
                    break;
                default:
                    image.setProperty('src', 'images/icons/icon_undefined.gif');
                    break;
            }
            image.setProperties(dimensions).injectInside(cell);
        }
        else {
            var fieldValue = '';
            if (record[fieldName]) {
                var fieldValue = record[fieldName].clean();
            }
            if (fieldValue != '') cell.set('html', fieldValue);
            //if (fieldValue != '') cell.appendText(fieldValue);
            else cell.set('html', ' ');
        }
    }
});
var FileRepository = new Class({
    Extends:GridManager,
    initialize:function (element) {
        this.parent(element);
        this.currentPID = false;
    },
    onDoubleClick:function () {
        this.open();
    },
    onSelect:function () {
        var r = this.grid.getSelectedRecord(), control;
        this.toolbar.enableControls();
        var openBtn = this.toolbar.getControlById('open');
        switch (r.upl_internal_type) {
            case 'folder':
                if (openBtn)openBtn.enable();
                break;
            case 'folderup':
                this.toolbar.disableControls();
                if (openBtn)openBtn.enable();
                this.toolbar.getControlById('addDir').enable();
                this.toolbar.getControlById('add').enable()
                break;
            case 'repo':
                this.toolbar.disableControls();
                if (openBtn)openBtn.enable();
                break;
            default:
                //this.toolbar.getControlById('open').disable();
                break;
        }
    },
    processServerResponse:function (result) {

        if (!this.initialized) {
            this.grid.setMetadata(result.meta);
            this.initialized = true;
        }
        if (!result.data) {
            result.data = [];
        }
        if (this.currentPID)
            Cookie.write(FILE_COOKIE_NAME, this.currentPID, {path:new URI(Energine.base).get('directory'), duration:1});
        /*if (this.currentPID) {
         result.data.unshift({'upl_id':0, 'upl_internal_type':'folderup', 'upl_path':'', 'upl_pid':'', 'upl_title':'...'});
         }*/
        this.grid.setData(result.data);

        if (result.pager)
            this.pageList.build(result.pager.count, result.pager.current, result.pager.records);

        if (!this.grid.isEmpty()) {
            this.toolbar.enableControls();
            this.pageList.enable();
        }

        var controlsEnabledByDefault = ['add'];
        for (var i = 0, l = controlsEnabledByDefault.length; i < l; i++) {
            if (control = this.toolbar.getControlById(controlsEnabledByDefault[i])) control.enable();
        }

        this.grid.build();
        this.overlay.hide();
    },
    open:function () {
        var r = this.grid.getSelectedRecord();
        switch (r.upl_internal_type) {
            case 'repo':
            case 'folder':
                this.currentPID = r.upl_id;
                this.filter.remove();
                this.loadPage(1);
                break;
            case 'folderup':
                this.currentPID = r.upl_id;
                this.loadPage(1);
                break;
            default:
                ModalBox.setReturnValue(r);
                ModalBox.close();
                break;
        }
    },
    add:function () {
        var pid = this.grid.getSelectedRecord().upl_pid;
        if (pid) {
            pid += '/';
        }
        ModalBox.open({
            url:this.singlePath + pid + 'add/',
            onClose:this._processAfterCloseAction.bind(this)
        });
    },
    addDir:function () {
        var pid = this.grid.getSelectedRecord().upl_pid;
        if (pid) {
            pid += '/';
        }
        ModalBox.open({
            url:this.singlePath + pid + 'add-dir/',
            //onClose:this._processAfterCloseAction.bind(this)
            onClose:function (response) {
                if (response && response.result) {
                    this.currentPID = response.data;
                    this._processAfterCloseAction(response);
                }

            }.bind(this)
        });
    },
    uploadZip:function (data) {
        this.request(this.singlePath + 'upload-zip', 'PID=' + this.grid.getSelectedRecord().upl_pid + '&data=' + encodeURIComponent(data.result), function (response) {
            console.log(response)
        });
        //this.singlePath + 'upload-zip',
    },
    loadPage:function (pageNum) {
        this.pageList.disable();
        this.toolbar.disableControls();
        this.overlay.show();
        this.grid.clear();
        var level = '', cookiePID;

        if (this.currentPID === 0) {
            level = '';
        }
        else if (this.currentPID) {
            level = this.currentPID + '/';
        }
        else if (cookiePID = Cookie.read(FILE_COOKIE_NAME)) {
            this.currentPID = cookiePID;
            level = this.currentPID + '/';
        }

        var postBody = '', url = this.singlePath + level + 'get-data/' + 'page-' + pageNum + '/';
        //if (this.langId) postBody += 'languageID=' + this.langId + '&';
        postBody += this.filter.getValue();
        /*if (this.grid.sort.order) {
         url = this.singlePath + 'get-data/' + this.grid.sort.field + '-' +
         this.grid.sort.order + '/page-' + pageNum
         }*/
        this.request(url,
            postBody,
            this.processServerResponse.bind(this),
            null,
            this.processServerError.bind(this)
        );
    }
});
<|endoftext|>