<commit_before>/**
 * Unicorn Admin Template
 * Version 2.2.0
 * Diablo9983 -> diablo9983@gmail.com
**/

$(document).ready(function(){

	$('.data-table').dataTable({
		"bJQueryUI": true,
		"sPaginationType": "full_numbers",
		"sDom": '<""l>t<"F"fp>',
		"aaSorting": [[0,'desc']]
	});

	// var checkboxClass = 'icheckbox_flat-blue';
	// var radioClass = 'iradio_flat-blue';
	// $('input[type=checkbox],input[type=radio]').iCheck({
 //    	checkboxClass: checkboxClass,
 //    	radioClass: radioClass
	// });

	// $('select').select2();

	$("span.icon input:checkbox, th input:checkbox").on('ifChecked || ifUnchecked',function() {
		var checkedStatus = this.checked;
		var checkbox = $(this).parents('.widget-box').find('tr td:first-child input:checkbox');
		checkbox.each(function() {
			this.checked = checkedStatus;
			if (checkedStatus == this.checked) {
				$(this).closest('.' + checkboxClass).removeClass('checked');
			}
			if (this.checked) {
				$(this).closest('.' + checkboxClass).addClass('checked');
			}
		});
	});

	function formatTime(s,bool){
    var t = new Date(s);
    var str;
    if(bool){
      str = t.getFullYear() +"年"+(t.getMonth()+1)+"月"+t.getDate()+"日 "+(parseInt(t.getHours())<10 ? ('0'+t.getHours()) : t.getHours())+":"+(parseInt(t.getMinutes())<10 ? ('0'+t.getMinutes()) : t.getMinutes());
    }else{
      str = t.getFullYear() +"年"+(t.getMonth()+1)+"月"+t.getDate()+"日 ";
    }
    return str;
  }
  $('.re-time').each(function(){
    var time = $(this).attr('data-time');
    if($(this).hasClass('no-hour')){
        $(this).text(formatTime(time,false));
    }else{
        $(this).text(formatTime(time,true));
    }
  })
  $(document).on('click','.dataTables_paginate .ui-button,.dataTables_length select',function(){
    alert(1);
    $('.re-time').each(function(){
      var time = $(this).attr('data-time');
      if($(this).hasClass('no-hour')){
        $(this).text(formatTime(time,false));
      }else{
        $(this).text(formatTime(time,true));
      }
    })
  })
  //- $('.jq-add-list').click(function(){
  //-   $('input[name=listId]').val('');
  //-   $('input[name=listName]').val('');
  //- })
  var uploader;
  $('.jq-add-product').click(function(){
    $('select[name=productList]').val('');
    $('select[name=productList] option').eq(0).attr('selected',true);
    $('input[name=productVersion]').val('');
    $('input[name=productCodeVersion]').val('');
    $('input[name=productStatus]:checked').val('');
    $('.jq-file').show();
    setTimeout(function(){
      uploader = WebUploader.create({
        // swf文件路径
        swf:'/lib/fex-webuploader/dist/Uploader.swf',
        // 文件接收服务端。
        server: '/users/editProduct',
        // 选择文件的按钮。可选。
        // 内部根据当前运行是创建，可能是input元素，也可能是flash.
        pick: {
          id : '#picker',
          multiple : false
        },
        accept:{
          title: 'Zip',
          extensions: 'zip',
          mimeTypes: 'application/x-zip-compressed'
        },
        // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
        resize: false
      });
      uploader.on( 'fileQueued', function( file ) {
       $('.webuploader-pick').text(file.name)
      });

    },500)
  })
  $('.jq-edit-status').click(function(){
    var id = $(this).attr('data-id'),
        status = $(this).attr('data-status');
    $('input[name=editStatusId]').val(id);
    $('input[name=editStatus]').each(function(){
      if($(this).val() == status){
        $(this).prop('checked',true);
      }
    })
  })
  $('.jq-submit-editStatus').click(function(){
    var status=$('input[name=editStatus]:checked').val() || 1,
        id = $('input[name=editStatusId]').val();
      $.post('/users/editStatus', {
        'id': id,
        'status': status
      }, function(data, textStatus, xhr) {
        if(data.status == 1){
          window.location.reload();
        }else{
          alert(data.info);
        }
      }
    )
  })
  //- $('.jq-edit-list').click(function(){
  //-   var _id = $(this).attr('data-id'),
  //-       name = $(this).parent().siblings('.jq-list-name').text();
  //-   $('input[name=listId]').val(_id);
  //-   $('input[name=listName]').val(name);
  //- })
  //- $('.jq-edit-product').click(function(){
  //-   var _id = $(this).attr('data-id'),
  //-       infoId = $(this).parent().siblings('.jq-product-name').attr("data-id"),
  //-       version = $(this).parent().siblings('.jq-product-version').text(),
  //-       codeVersion = $(this).parent().siblings('.jq-product-codeVersion').text(),
  //-       status = $(this).parent().siblings('.jq-product-status').attr('data-status');
  //-   $('.jq-file').hide();
  //-   $('input[name=productId]').val(_id);
  //-   $('select[name=productList] option[value='+infoId+']').attr('selected',true);
  //-   $('input[name=productVersion]').val(version);
  //-   $('input[name=productCodeVersion]').val(codeVersion);
  //-   $('input[name=productStatus]').eq(status-1).prop('checked',true);
  //- })
  $('.jq-submit-list').click(function(){
    var id = $('input[name=listId]').val(),
        name = $('input[name=listName]').val();
    if($('input[name=listName]').val() == ''){
    	alert('请填写项目名称')
    	return false;
    }
    $.post('/users/editList', {
        'id': id,
        'name': name
      }, function(data, textStatus, xhr) {
        if(data.status == 1){
          window.location.reload();
        }else{
          alert(data.info)
        }
      }
    )
  })
  $('.jq-submit-product').click(function(){
    var infoId = $('select[name=productList]').val();
    if($('select[name=productList]').val() == '' || $('input[name=productVersion]').val() == '' || $('input[name=productCodeVersion]').val() ==''){
      alert('请填写完整信息');
      return false;
    }
    if($('.webuploader-pick').text() == '选择文件'){
      alert('请选择文件')
      return false;
    }

    uploader.options.formData.id = $('input[name=productId]').val();
    uploader.options.formData.infoId = $('select[name=productList]').val(),
    uploader.options.formData.infoName = $('select[name=productList]').find('option[value='+infoId+']').text(),
    uploader.options.formData.version = $('input[name=productVersion]').val(),
    uploader.options.formData.codeVersion = $('input[name=productCodeVersion]').val(),
    uploader.options.formData.status = $('input[name=productStatus]:checked').val() || 1;
    uploader.upload();
    //- var id = $('input[name=productId]').val(),
    //-     infoId = $('select[name=productList]').val(),
    //-     infoName = $('select[name=productList]').find('option[value='+infoId+']').text(),
    //-     version = $('input[name=productVersion]').val(),
    //-     codeVesion = $('input[name=productCodeVersion]').val(),
    //-     status = $('input[name=productStatus]:checked').val();
    //- $.post('/users/editProduct', {
    //-       'id'         : id,
    //-       'info'       : {
    //-         'id'       : infoId,
    //-         'name'     : infoName
    //-       },
    //-       'version'    : version,
    //-       'codeVersion': codeVesion,
    //-       'status'     : status
    //-     }, function(data, textStatus, xhr) {
    //-       if(data.status == 1){
    //-         window.location.reload();
    //-       }else{
    //-         alert(data.info)
    //-       }
    //-   }
    //- )
    uploader.on( 'uploadProgress', function( file, percentage ) {
      $('.webuploader-pick').text('上传中···('+(parseInt(percentage * 1000)/10)+'%)')
    });

    // 文件上传成功，给item添加成功class, 用样式标记上传成功。
    uploader.on( 'uploadSuccess', function( file , response ) {
      $('.webuploader-pick').text('上传成功')
    	uploader.reset();
    	window.location.reload();
    });

    // 文件上传失败，显示上传出错。
    uploader.on( 'uploadError', function( file ) {
      $('.webuploader-pick').text('上传失败')
    });

  })

});
<commit_msg>删除调试的代码<commit_after>/**
 * Unicorn Admin Template
 * Version 2.2.0
 * Diablo9983 -> diablo9983@gmail.com
**/

$(document).ready(function(){

	$('.data-table').dataTable({
		"bJQueryUI": true,
		"sPaginationType": "full_numbers",
		"sDom": '<""l>t<"F"fp>',
		"aaSorting": [[0,'desc']]
	});

	// var checkboxClass = 'icheckbox_flat-blue';
	// var radioClass = 'iradio_flat-blue';
	// $('input[type=checkbox],input[type=radio]').iCheck({
 //    	checkboxClass: checkboxClass,
 //    	radioClass: radioClass
	// });

	// $('select').select2();

	$("span.icon input:checkbox, th input:checkbox").on('ifChecked || ifUnchecked',function() {
		var checkedStatus = this.checked;
		var checkbox = $(this).parents('.widget-box').find('tr td:first-child input:checkbox');
		checkbox.each(function() {
			this.checked = checkedStatus;
			if (checkedStatus == this.checked) {
				$(this).closest('.' + checkboxClass).removeClass('checked');
			}
			if (this.checked) {
				$(this).closest('.' + checkboxClass).addClass('checked');
			}
		});
	});

	function formatTime(s,bool){
    var t = new Date(s);
    var str;
    if(bool){
      str = t.getFullYear() +"年"+(t.getMonth()+1)+"月"+t.getDate()+"日 "+(parseInt(t.getHours())<10 ? ('0'+t.getHours()) : t.getHours())+":"+(parseInt(t.getMinutes())<10 ? ('0'+t.getMinutes()) : t.getMinutes());
    }else{
      str = t.getFullYear() +"年"+(t.getMonth()+1)+"月"+t.getDate()+"日 ";
    }
    return str;
  }
  $('.re-time').each(function(){
    var time = $(this).attr('data-time');
    if($(this).hasClass('no-hour')){
        $(this).text(formatTime(time,false));
    }else{
        $(this).text(formatTime(time,true));
    }
  })
  $(document).on('click','.dataTables_paginate .ui-button,.dataTables_length select',function(){
    $('.re-time').each(function(){
      var time = $(this).attr('data-time');
      if($(this).hasClass('no-hour')){
        $(this).text(formatTime(time,false));
      }else{
        $(this).text(formatTime(time,true));
      }
    })
  })
  //- $('.jq-add-list').click(function(){
  //-   $('input[name=listId]').val('');
  //-   $('input[name=listName]').val('');
  //- })
  var uploader;
  $('.jq-add-product').click(function(){
    $('select[name=productList]').val('');
    $('select[name=productList] option').eq(0).attr('selected',true);
    $('input[name=productVersion]').val('');
    $('input[name=productCodeVersion]').val('');
    $('input[name=productStatus]:checked').val('');
    $('.jq-file').show();
    setTimeout(function(){
      uploader = WebUploader.create({
        // swf文件路径
        swf:'/lib/fex-webuploader/dist/Uploader.swf',
        // 文件接收服务端。
        server: '/users/editProduct',
        // 选择文件的按钮。可选。
        // 内部根据当前运行是创建，可能是input元素，也可能是flash.
        pick: {
          id : '#picker',
          multiple : false
        },
        accept:{
          title: 'Zip',
          extensions: 'zip',
          mimeTypes: 'application/x-zip-compressed'
        },
        // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
        resize: false
      });
      uploader.on( 'fileQueued', function( file ) {
       $('.webuploader-pick').text(file.name)
      });

    },500)
  })
  $('.jq-edit-status').click(function(){
    var id = $(this).attr('data-id'),
        status = $(this).attr('data-status');
    $('input[name=editStatusId]').val(id);
    $('input[name=editStatus]').each(function(){
      if($(this).val() == status){
        $(this).prop('checked',true);
      }
    })
  })
  $('.jq-submit-editStatus').click(function(){
    var status=$('input[name=editStatus]:checked').val() || 1,
        id = $('input[name=editStatusId]').val();
      $.post('/users/editStatus', {
        'id': id,
        'status': status
      }, function(data, textStatus, xhr) {
        if(data.status == 1){
          window.location.reload();
        }else{
          alert(data.info);
        }
      }
    )
  })
  //- $('.jq-edit-list').click(function(){
  //-   var _id = $(this).attr('data-id'),
  //-       name = $(this).parent().siblings('.jq-list-name').text();
  //-   $('input[name=listId]').val(_id);
  //-   $('input[name=listName]').val(name);
  //- })
  //- $('.jq-edit-product').click(function(){
  //-   var _id = $(this).attr('data-id'),
  //-       infoId = $(this).parent().siblings('.jq-product-name').attr("data-id"),
  //-       version = $(this).parent().siblings('.jq-product-version').text(),
  //-       codeVersion = $(this).parent().siblings('.jq-product-codeVersion').text(),
  //-       status = $(this).parent().siblings('.jq-product-status').attr('data-status');
  //-   $('.jq-file').hide();
  //-   $('input[name=productId]').val(_id);
  //-   $('select[name=productList] option[value='+infoId+']').attr('selected',true);
  //-   $('input[name=productVersion]').val(version);
  //-   $('input[name=productCodeVersion]').val(codeVersion);
  //-   $('input[name=productStatus]').eq(status-1).prop('checked',true);
  //- })
  $('.jq-submit-list').click(function(){
    var id = $('input[name=listId]').val(),
        name = $('input[name=listName]').val();
    if($('input[name=listName]').val() == ''){
    	alert('请填写项目名称')
    	return false;
    }
    $.post('/users/editList', {
        'id': id,
        'name': name
      }, function(data, textStatus, xhr) {
        if(data.status == 1){
          window.location.reload();
        }else{
          alert(data.info)
        }
      }
    )
  })
  $('.jq-submit-product').click(function(){
    var infoId = $('select[name=productList]').val();
    if($('select[name=productList]').val() == '' || $('input[name=productVersion]').val() == '' || $('input[name=productCodeVersion]').val() ==''){
      alert('请填写完整信息');
      return false;
    }
    if($('.webuploader-pick').text() == '选择文件'){
      alert('请选择文件')
      return false;
    }

    uploader.options.formData.id = $('input[name=productId]').val();
    uploader.options.formData.infoId = $('select[name=productList]').val(),
    uploader.options.formData.infoName = $('select[name=productList]').find('option[value='+infoId+']').text(),
    uploader.options.formData.version = $('input[name=productVersion]').val(),
    uploader.options.formData.codeVersion = $('input[name=productCodeVersion]').val(),
    uploader.options.formData.status = $('input[name=productStatus]:checked').val() || 1;
    uploader.upload();
    //- var id = $('input[name=productId]').val(),
    //-     infoId = $('select[name=productList]').val(),
    //-     infoName = $('select[name=productList]').find('option[value='+infoId+']').text(),
    //-     version = $('input[name=productVersion]').val(),
    //-     codeVesion = $('input[name=productCodeVersion]').val(),
    //-     status = $('input[name=productStatus]:checked').val();
    //- $.post('/users/editProduct', {
    //-       'id'         : id,
    //-       'info'       : {
    //-         'id'       : infoId,
    //-         'name'     : infoName
    //-       },
    //-       'version'    : version,
    //-       'codeVersion': codeVesion,
    //-       'status'     : status
    //-     }, function(data, textStatus, xhr) {
    //-       if(data.status == 1){
    //-         window.location.reload();
    //-       }else{
    //-         alert(data.info)
    //-       }
    //-   }
    //- )
    uploader.on( 'uploadProgress', function( file, percentage ) {
      $('.webuploader-pick').text('上传中···('+(parseInt(percentage * 1000)/10)+'%)')
    });

    // 文件上传成功，给item添加成功class, 用样式标记上传成功。
    uploader.on( 'uploadSuccess', function( file , response ) {
      $('.webuploader-pick').text('上传成功')
    	uploader.reset();
    	window.location.reload();
    });

    // 文件上传失败，显示上传出错。
    uploader.on( 'uploadError', function( file ) {
      $('.webuploader-pick').text('上传失败')
    });

  })

});
<|endoftext|>


<commit_before>user_pref("browser.backspace_action", 2);
user_pref("browser.ctrlTab.previews", true);
user_pref("browser.fixup.alternate.enabled", false);
user_pref("browser.newtab.url", "https://www.google.com");
user_pref("browser.showQuitWarning", true);
user_pref("browser.tabs.tabClipWidth", 1);
user_pref("browser.warnOnQuit", true);
user_pref("datareporting.healthreport.service.enabled", false);
user_pref("datareporting.healthreport.uploadEnabled", false);
user_pref("devtools.webconsole.persistlog", true);
user_pref("extensions.pocket.enabled", false);
user_pref("general.useragent.locale", "en-GB");
user_pref("layout.spellcheckDefault", 2);
user_pref("loop.enabled", false);
user_pref("media.block-autoplay-until-in-foreground", true);
user_pref("network.IDN_show_punycode", true);
user_pref("plugins.click_to_play", true);
user_pref("privacy.userContext.enabled", true);
user_pref("privacy.userContext.ui.enabled", true);
user_pref("security.webauth.u2f", true);
user_pref("spellchecker.dictionary", "en-GB");
user_pref("toolkit.telemetry.enabled", false);
<commit_msg>Enable pocket.<commit_after>user_pref("browser.backspace_action", 2);
user_pref("browser.ctrlTab.previews", true);
user_pref("browser.fixup.alternate.enabled", false);
user_pref("browser.newtab.url", "https://www.google.com");
user_pref("browser.showQuitWarning", true);
user_pref("browser.tabs.tabClipWidth", 1);
user_pref("browser.warnOnQuit", true);
user_pref("datareporting.healthreport.service.enabled", false);
user_pref("datareporting.healthreport.uploadEnabled", false);
user_pref("devtools.webconsole.persistlog", true);
user_pref("extensions.pocket.enabled", true);
user_pref("general.useragent.locale", "en-GB");
user_pref("layout.spellcheckDefault", 2);
user_pref("loop.enabled", false);
user_pref("media.block-autoplay-until-in-foreground", true);
user_pref("network.IDN_show_punycode", true);
user_pref("plugins.click_to_play", true);
user_pref("privacy.userContext.enabled", true);
user_pref("privacy.userContext.ui.enabled", true);
user_pref("security.webauth.u2f", true);
user_pref("spellchecker.dictionary", "en-GB");
user_pref("toolkit.telemetry.enabled", false);
<|endoftext|>


<commit_before>// --------------------------------------------------
// Show a loading indicator on all AJAX POST, PUT
// and DELETE.
// --------------------------------------------------
define(function (require) {

	// Dependencies
	var $ = require('jquery')
		, _ = require('underscore')
		, Backbone = require('backbone')
		$doc = $(document)
	;

	// Private static vars
	var app,
		progress = 0, // How many requests have finished
		total = 0; // How many total requests have been made

	// Public view module
	var AjaxProgress = Backbone.View.extend({

		// Constructor
		initialize: function (options) {
			_.bindAll(this);
			app = options.app;

			// Shared vars
			this.$bar = this.$('.progress-bar');
			this.$links = $('.subnav a, .breadcrumbs a');

			// Listen for start and complete
			$doc.ajaxSend(this.send);
			$doc.ajaxComplete(this.complete);
			this.$links.on('click', this.showSpinner);
		},

		// Add progress of a new ajax request, thus making the
		// progress smaller
		send: function() {
			total++;
			this.render();
		},

		// Remove progress of an ajax request cause it finished,
		// thus lengthening the bar
		complete: function() {
			progress++;
			if (progress == total) total = progress = 0; // Totally finished with all requests, so reset
			this.render();
		},

		// when the loader is called from a link click, not an ajax request,
		// show the loader while the sever is responding to the request
		showSpinner: function() {
			// hack to animate to a 99% loader width
			total = 0.01;
			this.render();
		},

		// Update the position of the bar
		render: function() {

			// Show and hide the bar
			if (total > 0) this.$bar.stop(true).css('opacity', 1);
			else if (total === 0) this.$bar.stop(true).delay(800).animate({opacity:0}, function() {
				$(this).css('width', 0);
			});

			// Animate the bar
			var perc = (progress + 1) / (total + 1);
			this.$bar.css('width', (perc*100)+"%");
		}

	});

	// Return view
	return AjaxProgress;

});<commit_msg>loader hits 100% #331<commit_after>// --------------------------------------------------
// Show a loading indicator on all AJAX POST, PUT
// and DELETE.
// --------------------------------------------------
define(function (require) {

	// Dependencies
	var $ = require('jquery')
		, _ = require('underscore')
		, Backbone = require('backbone')
		$doc = $(document)
	;

	// Private static vars
	var app,
		progress = 0, // How many requests have finished
		total = 0; // How many total requests have been made

	// Public view module
	var AjaxProgress = Backbone.View.extend({

		// Constructor
		initialize: function (options) {
			_.bindAll(this);
			app = options.app;

			// Shared vars
			this.$bar = this.$('.progress-bar');
			this.$links = $('.subnav a, .breadcrumbs a');

			// Listen for start and complete
			$doc.ajaxSend(this.send);
			$doc.ajaxComplete(this.complete);
			this.$links.on('click', this.showSpinner);
		},

		// Add progress of a new ajax request, thus making the
		// progress smaller
		send: function() {
			total++;
			this.render();
		},

		// Remove progress of an ajax request cause it finished,
		// thus lengthening the bar
		complete: function() {
			progress++;
			if (progress == total) total = progress = 0; // Totally finished with all requests, so reset
			this.render();
		},

		// when the loader is called from a link click, not an ajax request,
		// show the loader while the sever is responding to the request
		showSpinner: function() {
			// hack to animate to a 99% loader width
			total = 0;
			this.render();
		},

		// Update the position of the bar
		render: function() {

			// Show and hide the bar
			if (total > 0) this.$bar.stop(true).css('opacity', 1);
			else if (total === 0) this.$bar.stop(true).delay(800).animate({opacity:0}, function() {
				$(this).css('width', 0);
			});

			// Animate the bar
			var perc = (progress + 1) / (total + 1);
			this.$bar.css('width', (perc*100)+"%");
		}

	});

	// Return view
	return AjaxProgress;

});<|endoftext|>


<commit_before>define([
  'jquery',
  'underscore',
  'backbone',
  'texchat',

  'libs/bootstrap/bootstrap-modal',
  ], function($, _, Backbone, TeXchat) {

var RoomlistView = Backbone.View.extend({

  template: _.template('\

\

\

Public Room Name	Users

\

\

Loading...
\

\

\

\
  '),

  roomTemplate: _.template('\
  <% rooms.each(function(room) { %>\

\
      <%- room.get("name") %>	\
      <%- room.get("users") %>	\

\
  <% }); %>\
  '),

  className: 'modal hide fade',

  events: {
    'click tr.room': 'onClickRoom'
  },

  initialize: function() {
    _.bindAll(this, 'onClickRoom');

    this.collection.bind('add', this.renderRooms, this);
    this.collection.bind('remove', this.renderRooms, this);
    this.collection.bind('reset', this.renderRooms, this);
  },

  render: function() {
    // set users

    $(this.el).empty();

    // add modal html
    $(this.el).html(this.template({}));

    // setup modal js
    $(this.el).modal({
      keyboard: true,
      backdrop: true,
    });

    // bind remove upon hiding.
    var that = this;
    $(this.el).find('.modal').bind('hidden', function (e) {
      // e.target.remove();
      that.collection.unbind('add', this.renderRooms);
      that.remove();
    });

    return this;
  },

  renderRooms: function() {

    $(this.el).find('tbody').html(this.roomTemplate({
      rooms: this.collection
    }));

    return this;
  },

  show: function() {
    $(this.el).modal('show');
    return this;
  },

  hide: function() {
    $(this.el).modal('hide');
    return this;
  },

  onClickRoom: function(e) {
    // target = tr.  room is in first td.
    var roomname = $(e.currentTarget).find('td').first().text();
    TeXchat.goToRoom(roomname);
    this.hide();
  }

});

return RoomlistView;
});
<commit_msg>Adjusted element refernece in roomlistView.<commit_after>define([
  'jquery',
  'underscore',
  'backbone',
  'texchat',

  'libs/bootstrap/bootstrap-modal',
  ], function($, _, Backbone, TeXchat) {

var RoomlistView = Backbone.View.extend({

  template: _.template('\

\

\

Public Room Name	Users

\

\

Loading...
\

\

\

\
  '),

  roomTemplate: _.template('\
  <% rooms.each(function(room) { %>\

\
      <%- room.get("name") %>	\
      <%- room.get("users") %>	\

\
  <% }); %>\
  '),

  className: 'modal hide fade',

  events: {
    'click tr.room': 'onClickRoom'
  },

  initialize: function() {
    _.bindAll(this, 'onClickRoom');

    this.collection.bind('add', this.renderRooms, this);
    this.collection.bind('remove', this.renderRooms, this);
    this.collection.bind('reset', this.renderRooms, this);
  },

  render: function() {
    // set users

    $(this.el).empty();

    // add modal html
    $(this.el).html(this.template({}));

    // setup modal js
    $(this.el).modal({
      keyboard: true,
      backdrop: true,
    });

    // bind remove upon hiding.
    var that = this;
    $(this.el).bind('hidden', function (e) {
      // e.target.remove();
      that.collection.unbind('add', this.renderRooms);
      that.remove();
    });

    return this;
  },

  renderRooms: function() {

    $(this.el).find('tbody').html(this.roomTemplate({
      rooms: this.collection
    }));

    return this;
  },

  show: function() {
    $(this.el).modal('show');
    return this;
  },

  hide: function() {
    $(this.el).modal('hide');
    return this;
  },

  onClickRoom: function(e) {
    // target = tr.  room is in first td.
    var roomname = $(e.currentTarget).find('td').first().text();
    TeXchat.goToRoom(roomname);
    this.hide();
  }

});

return RoomlistView;
});
<|endoftext|>


<commit_before>window.OccurrenceView = Backbone.View.extend({
    events: {
      "click .fc-event-closebutton": "deleteOcurrence"
    },
    initialize: function() {
      this.calendar = this.options.calendar;
    },
    deleteOcurrence: function(sth) {
      var overlapped = this.model.overlapsWith;
      var options = {success: function() {
        overlapped.forEach(function(o) {
          o.save();
          });
        }
      };
      this.$el.fadeOut(400, this.model.destroy.bind(this.model, options));
      console.log("Deleting ocurrence", this.model);
    }
});

window.ScheduleView = Backbone.View.extend({
    el: $("#content"),
    get_templateHTML: function () {
        return template.schedule();
    },
    get_collection: function () {
        return this.collection;
    },
    make_event: function(occurrence) {
        // make a Media.Occurrence into a fullCalendar event
        var attribs = _(occurrence.attributes).clone();

        // Fullcalendar needs unix timestamp for rendering
        attribs.start = moment(attribs.start).unix();
        attribs.end = moment(attribs.end).unix();
        attribs.color = utils.color_scale(occurrence.get("_id"));

        attribs.model = occurrence;
        return attribs;
    },
    all_events: function() {
        return this.get_collection().map(this.make_event);
    },
    historical_events: [
        {
            title: 'WALLKINTUN SALE AL AIRE !',
            start: new Date(2012, 11, 7, 22, 0),
            end:   new Date(2012, 11, 8, 6, 0),
            allDay: false,
        },
    ],
    reload: function() {
        this.calendar.fullCalendar('refetchEvents');
    },
    checkOverlap: function(event) {
        // This checks if an event has any overlapping events on the calendar. It expects the event
        // to have a 'start' and an 'end' properties

        var start = moment(event.start);
        var end = moment(event.end);
        var overlap = this.calendar.fullCalendar('clientEvents', function(ev) {
            if( ev == event)
                return false;
            return ev.start < end && ev.end > start;
        });
        if( overlap.length ) {
            // TODO: choose better?
            overlap = overlap[0];
            var over_start = moment(overlap.start);
            var over_end = moment(overlap.end);
            var duration = end - start;
            if( over_start > start ) {
                // clamp to beginning
                end = over_start.clone();
                start = end.clone();
                start.subtract(duration);
            } else {
                // clamp to end
                start = over_end.clone();
                end = start.clone();
                end.add(duration);
            }
        }
        return {start: start, end: end};
    },
    initialize: function () {
        var self = this;

        self.collection = new Media.Schedule();
        self.playlists = new Media.UniversePageable();

        $(this.el).removeClass("trans Pov").addClass("container-fluid no-Pov");
        $(this.el).html(this.get_templateHTML());

        new UniverseListView({
            collection: this.playlists,
            el: $('#universe', this.el),
            draggable: true,
            pagination: false,
            search_type: 'client'
        });

        this.render();
    },
    events: {
        "click #pushdown"   : "pushdownAll",
        "click #revert"     : "revert"
    },
    displayOverlap: function(bool) {
        if (bool) {
            $('#overlapping-alert').fadeIn();
        } else {
            $('#overlapping-alert').fadeOut();
        };
    },
    pushdownAll: function() {
        var self = this;
        var invalid = this.collection.getInvalid();
        invalid.forEach(function(oc){
            if (!oc.validationError) return // conflict may have already been fixed by other pushdown
            var first = oc.getOverlappingEvents()[0];
            if (oc.get('start') > first.get('start')) {
                self.pushdown(first);
            } else {
                self.pushdown(oc);
            }
        })
    },
    pushdown: function(oc) {
        /* We assume the last dragged object is the one the user
           wants to keep in that position */
        var self = this;
        var overlapping = oc.getOverlappingEvents();
        overlapping.forEach(function(first) {
            start = oc.get('end');
            duration = first.get('end') - first.get('start');
            end = start + duration
            first.save({start: start, end: end});
            // If I stepped over another event, call myself again
            if (first.validationError) {
                self.pushdown(first);
            };
        })
    },
    revert: function() {
        this.collection.fetch({reset: true});
        this.displayOverlap(false);
    },
/*    saveEvent: function (event) {
        // we filter out the event to only store what we really need

        console.log ('saving event:', event);
        var nattr = {
            title:  event.get('title'),
            start:  moment(event.get('start')).valueOf(),
            end:    moment(event.get('end')).valueOf(),
            allDay: event.get('allDay'),
            list:   event.get('list'),
        };

        event.clear({silent:true});
        event.save(nattr);

    },*/
    render: function () {
        console.log ('render calendar', $(this.el));
        var self = this;
        this.collection = this.get_collection();
        this.opts = {"timestamp":1361784505,
                     "timezoneOffset":"0",
                     "timeScale":"agendaWeek",
                     "timeInterval":"30",
                     "weekStartDay":"0"};
        this.calendar = $('#schedule_calendar', this.$el);

        var mainHeight = document.documentElement.clientHeight - 200 - 50;

        var calendarEventSources = [
            function(start, end, callback) {
                self.collection.setQuery({criteria: {in_window: [moment(start).valueOf(), moment(end).valueOf()]}});
                self.collection.fetch({
                    success: function() {
                        console.log("Fetched Schedule!");
                        var events = self.collection.map(self.make_event);
                        console.log('Returning events #', events.length);
                        callback(events)
                    },
                    error: function(e) {
                        throw new Error("Cannot fetch Schedule.");
                    },
                });
            },
        ].concat(self.historical_events);

        this.calendar.fullCalendar({
            header: {
                left: 'prev, next, today',
                center: 'title',
                right: 'agendaDay, agendaWeek, month'
            },
            defaultView: this.opts.timeScale,
            slotMinutes: parseInt(this.opts.timeInterval),
            firstDay: this.opts.weekStartDay,
            editable: true,
            droppable: true,
            allDaySlot: false,
            axisFormat: 'H:mm',
            timeFormat: {
                agenda: 'H:mm{ - H:mm}',
                month: 'H:mm{ - H:mm}'
            },
            contentHeight: mainHeight,
            theme: true,
            lazyFetching: true,
            serverTimestamp: parseInt(this.opts.timestamp, 10),
            serverTimezoneOffset: parseInt(this.opts.timezoneOffset, 10),

            eventSources: calendarEventSources,

            //callbacks (in full-calendar-functions.js)
            viewDisplay: function ( view ) {
                view_name = view.name;

                if(view.name === 'agendaDay' || view.name === 'agendaWeek') {

                    var calendarEl = this;

                    var select = $('<select class="schedule_change_slots input_select"/>')
                        .append('<option value="1">1m</option>')
                        .append('<option value="5">5m</option>')
                        .append('<option value="10">10m</option>')
                        .append('<option value="15">15m</option>')
                        .append('<option value="30">30m</option>')
                        .append('<option value="60">60m</option>')
                        .change(function(){
                            var slotMin = $(this).val();
                            var opt = view.calendar.options;
                            var date = $(calendarEl).fullCalendar('getDate');

                            opt.slotMinutes = parseInt(slotMin);
                            opt.defaultView = view.name;
                            // event sources are not kept in the options, I don't know
                            //  if there's a way to retrieve them
                            opt.eventSources = calendarEventSources;

                            //re-initialize calendar with new slotmin options
                            $(calendarEl)
                                .fullCalendar('destroy')
                                .fullCalendar(opt)
                                .fullCalendar( 'gotoDate', date );

                            /** TODO: save view config
                             *
                            //save slotMin value to db
                            var url = '/Schedule/set-time-interval/format/json';
                            $.post(url, {timeInterval: slotMin});
                            */
                        });

                    var topLeft = $(view.element).find("table.fc-agenda-days > thead th:first");

                    select.width(topLeft.width())
                        .height(topLeft.height());

                    topLeft.empty()
                        .append(select);

                    var slotMin = view.calendar.options.slotMinutes;
                    $('.schedule_change_slots option[value="'+slotMin+'"]').attr('selected', 'selected');
                }

                if(($("#add-show-form").length == 1) && ($("#add-show-form").css('display')=='none') && ($('.fc-header-left > span').length == 5)) {

                    //userType is defined in bootstrap.php, and is derived from the currently logged in user.
                    if(userType == "A" || userType == "P"){
                        makeAddShowButton();
                    }
                }

                /* FIXME
                //save view name to db
                var url = '/Schedule/set-time-scale/format/json';
                $.post(url, {timeScale: view.name});
            */
            },
            dayClick: dayClick,

            eventRender: function (event, element, view) {
                element.tooltip({
                    trigger: 'click',
                    placement: 'left',
/*                    title: function () {
                        console.log ("creating tooltip", model);
                        var model = self.collection.get(event._id);
                        var playlist = model.get('playlist');
                        var target = document.createElement('div');
                        var view = new MediaListView({model: playlist, type: 'playlist-fixed', el: $(target)});
                        return view.el.html();
                    },
*/
                });

                eventRender(event, element, view);

            },

            eventAfterRender: function (event, element, view) {
              var ocurrence = new OccurrenceView({
                el: element,
                id: event._id,
                model: event.model,
                collection: self.collection,
                calendar: self.calendar
              });
              eventAfterRender(event, element, view);
            },
            eventDrop: function(event, dayDelta, minuteDelta, allDay, revertFunc, jsEvent, ui, view) {
                var data = self.checkOverlap(event);
                event.start = data.start.toDate();
                event.end = data.end.toDate();
                self.calendar.fullCalendar('updateEvent', event);
                event.model.save({start: data.start.valueOf(), end: data.end.valueOf()});
            },
            eventResize: eventResize,
            drop: function(date, allDay) {
                var list  = self.playlists.get(this.id);

                console.log ('drop->', self.collection.pluck('end'));

                var start = moment(date);
                var end   = moment(start);

                end.add('ms', list.get('duration'));

                var times = self.checkOverlap({start: start, end: end});

                var event = {
                    title:  list.get('name'),
                    start:  times.start.valueOf(), end: times.end.valueOf(),
                    playlist:   list.get('_id'),
                    allDay: allDay,
                };

                console.log ('to save', event);
                var item = self.collection.create (event);
                console.log (this, list, event, item);
            }
        });

                                             /*
            eventRender: function(event, element) {
                var model = self.collection.where({list: event.list})[0];

                element.tooltip({
                    trigger: 'click',
                    placement: 'left',
                    title: function () {
                        var target = document.createElement('div');
                        var view = new MediaListView({model: model,
                                                      noSearch:true,
                                                      el: target});
                        return view.render().el;
                    },
                });
            }
                                             */

        self.collection.bind('add reset remove change', this.reload, this);
        self.collection.bind('all',   function (e, a) {console.log('got: ' + e, a);}, this);
        self.collection.bind('overlap', this.displayOverlap, this);

        return this;
    },
});
<commit_msg>ScheduleView: server search for Universe.<commit_after>window.OccurrenceView = Backbone.View.extend({
    events: {
      "click .fc-event-closebutton": "deleteOcurrence"
    },
    initialize: function() {
      this.calendar = this.options.calendar;
    },
    deleteOcurrence: function(sth) {
      var overlapped = this.model.overlapsWith;
      var options = {success: function() {
        overlapped.forEach(function(o) {
          o.save();
          });
        }
      };
      this.$el.fadeOut(400, this.model.destroy.bind(this.model, options));
      console.log("Deleting ocurrence", this.model);
    }
});

window.ScheduleView = Backbone.View.extend({
    el: $("#content"),
    get_templateHTML: function () {
        return template.schedule();
    },
    get_collection: function () {
        return this.collection;
    },
    make_event: function(occurrence) {
        // make a Media.Occurrence into a fullCalendar event
        var attribs = _(occurrence.attributes).clone();

        // Fullcalendar needs unix timestamp for rendering
        attribs.start = moment(attribs.start).unix();
        attribs.end = moment(attribs.end).unix();
        attribs.color = utils.color_scale(occurrence.get("_id"));

        attribs.model = occurrence;
        return attribs;
    },
    all_events: function() {
        return this.get_collection().map(this.make_event);
    },
    historical_events: [
        {
            title: 'WALLKINTUN SALE AL AIRE !',
            start: new Date(2012, 11, 7, 22, 0),
            end:   new Date(2012, 11, 8, 6, 0),
            allDay: false,
        },
    ],
    reload: function() {
        this.calendar.fullCalendar('refetchEvents');
    },
    checkOverlap: function(event) {
        // This checks if an event has any overlapping events on the calendar. It expects the event
        // to have a 'start' and an 'end' properties

        var start = moment(event.start);
        var end = moment(event.end);
        var overlap = this.calendar.fullCalendar('clientEvents', function(ev) {
            if( ev == event)
                return false;
            return ev.start < end && ev.end > start;
        });
        if( overlap.length ) {
            // TODO: choose better?
            overlap = overlap[0];
            var over_start = moment(overlap.start);
            var over_end = moment(overlap.end);
            var duration = end - start;
            if( over_start > start ) {
                // clamp to beginning
                end = over_start.clone();
                start = end.clone();
                start.subtract(duration);
            } else {
                // clamp to end
                start = over_end.clone();
                end = start.clone();
                end.add(duration);
            }
        }
        return {start: start, end: end};
    },
    initialize: function () {
        var self = this;

        self.collection = new Media.Schedule();
        self.playlists = new Media.UniversePageable();

        $(this.el).removeClass("trans Pov").addClass("container-fluid no-Pov");
        $(this.el).html(this.get_templateHTML());

        new UniverseListView({
            collection: this.playlists,
            el: $('#universe', this.el),
            draggable: true,
        });

        this.render();
    },
    events: {
        "click #pushdown"   : "pushdownAll",
        "click #revert"     : "revert"
    },
    displayOverlap: function(bool) {
        if (bool) {
            $('#overlapping-alert').fadeIn();
        } else {
            $('#overlapping-alert').fadeOut();
        };
    },
    pushdownAll: function() {
        var self = this;
        var invalid = this.collection.getInvalid();
        invalid.forEach(function(oc){
            if (!oc.validationError) return // conflict may have already been fixed by other pushdown
            var first = oc.getOverlappingEvents()[0];
            if (oc.get('start') > first.get('start')) {
                self.pushdown(first);
            } else {
                self.pushdown(oc);
            }
        })
    },
    pushdown: function(oc) {
        /* We assume the last dragged object is the one the user
           wants to keep in that position */
        var self = this;
        var overlapping = oc.getOverlappingEvents();
        overlapping.forEach(function(first) {
            start = oc.get('end');
            duration = first.get('end') - first.get('start');
            end = start + duration
            first.save({start: start, end: end});
            // If I stepped over another event, call myself again
            if (first.validationError) {
                self.pushdown(first);
            };
        })
    },
    revert: function() {
        this.collection.fetch({reset: true});
        this.displayOverlap(false);
    },
/*    saveEvent: function (event) {
        // we filter out the event to only store what we really need

        console.log ('saving event:', event);
        var nattr = {
            title:  event.get('title'),
            start:  moment(event.get('start')).valueOf(),
            end:    moment(event.get('end')).valueOf(),
            allDay: event.get('allDay'),
            list:   event.get('list'),
        };

        event.clear({silent:true});
        event.save(nattr);

    },*/
    render: function () {
        console.log ('render calendar', $(this.el));
        var self = this;
        this.collection = this.get_collection();
        this.opts = {"timestamp":1361784505,
                     "timezoneOffset":"0",
                     "timeScale":"agendaWeek",
                     "timeInterval":"30",
                     "weekStartDay":"0"};
        this.calendar = $('#schedule_calendar', this.$el);

        var mainHeight = document.documentElement.clientHeight - 200 - 50;

        var calendarEventSources = [
            function(start, end, callback) {
                self.collection.setQuery({criteria: {in_window: [moment(start).valueOf(), moment(end).valueOf()]}});
                self.collection.fetch({
                    success: function() {
                        console.log("Fetched Schedule!");
                        var events = self.collection.map(self.make_event);
                        console.log('Returning events #', events.length);
                        callback(events)
                    },
                    error: function(e) {
                        throw new Error("Cannot fetch Schedule.");
                    },
                });
            },
        ].concat(self.historical_events);

        this.calendar.fullCalendar({
            header: {
                left: 'prev, next, today',
                center: 'title',
                right: 'agendaDay, agendaWeek, month'
            },
            defaultView: this.opts.timeScale,
            slotMinutes: parseInt(this.opts.timeInterval),
            firstDay: this.opts.weekStartDay,
            editable: true,
            droppable: true,
            allDaySlot: false,
            axisFormat: 'H:mm',
            timeFormat: {
                agenda: 'H:mm{ - H:mm}',
                month: 'H:mm{ - H:mm}'
            },
            contentHeight: mainHeight,
            theme: true,
            lazyFetching: true,
            serverTimestamp: parseInt(this.opts.timestamp, 10),
            serverTimezoneOffset: parseInt(this.opts.timezoneOffset, 10),

            eventSources: calendarEventSources,

            //callbacks (in full-calendar-functions.js)
            viewDisplay: function ( view ) {
                view_name = view.name;

                if(view.name === 'agendaDay' || view.name === 'agendaWeek') {

                    var calendarEl = this;

                    var select = $('<select class="schedule_change_slots input_select"/>')
                        .append('<option value="1">1m</option>')
                        .append('<option value="5">5m</option>')
                        .append('<option value="10">10m</option>')
                        .append('<option value="15">15m</option>')
                        .append('<option value="30">30m</option>')
                        .append('<option value="60">60m</option>')
                        .change(function(){
                            var slotMin = $(this).val();
                            var opt = view.calendar.options;
                            var date = $(calendarEl).fullCalendar('getDate');

                            opt.slotMinutes = parseInt(slotMin);
                            opt.defaultView = view.name;
                            // event sources are not kept in the options, I don't know
                            //  if there's a way to retrieve them
                            opt.eventSources = calendarEventSources;

                            //re-initialize calendar with new slotmin options
                            $(calendarEl)
                                .fullCalendar('destroy')
                                .fullCalendar(opt)
                                .fullCalendar( 'gotoDate', date );

                            /** TODO: save view config
                             *
                            //save slotMin value to db
                            var url = '/Schedule/set-time-interval/format/json';
                            $.post(url, {timeInterval: slotMin});
                            */
                        });

                    var topLeft = $(view.element).find("table.fc-agenda-days > thead th:first");

                    select.width(topLeft.width())
                        .height(topLeft.height());

                    topLeft.empty()
                        .append(select);

                    var slotMin = view.calendar.options.slotMinutes;
                    $('.schedule_change_slots option[value="'+slotMin+'"]').attr('selected', 'selected');
                }

                if(($("#add-show-form").length == 1) && ($("#add-show-form").css('display')=='none') && ($('.fc-header-left > span').length == 5)) {

                    //userType is defined in bootstrap.php, and is derived from the currently logged in user.
                    if(userType == "A" || userType == "P"){
                        makeAddShowButton();
                    }
                }

                /* FIXME
                //save view name to db
                var url = '/Schedule/set-time-scale/format/json';
                $.post(url, {timeScale: view.name});
            */
            },
            dayClick: dayClick,

            eventRender: function (event, element, view) {
                element.tooltip({
                    trigger: 'click',
                    placement: 'left',
/*                    title: function () {
                        console.log ("creating tooltip", model);
                        var model = self.collection.get(event._id);
                        var playlist = model.get('playlist');
                        var target = document.createElement('div');
                        var view = new MediaListView({model: playlist, type: 'playlist-fixed', el: $(target)});
                        return view.el.html();
                    },
*/
                });

                eventRender(event, element, view);

            },

            eventAfterRender: function (event, element, view) {
              var ocurrence = new OccurrenceView({
                el: element,
                id: event._id,
                model: event.model,
                collection: self.collection,
                calendar: self.calendar
              });
              eventAfterRender(event, element, view);
            },
            eventDrop: function(event, dayDelta, minuteDelta, allDay, revertFunc, jsEvent, ui, view) {
                var data = self.checkOverlap(event);
                event.start = data.start.toDate();
                event.end = data.end.toDate();
                self.calendar.fullCalendar('updateEvent', event);
                event.model.save({start: data.start.valueOf(), end: data.end.valueOf()});
            },
            eventResize: eventResize,
            drop: function(date, allDay) {
                var list  = self.playlists.get(this.id);

                console.log ('drop->', self.collection.pluck('end'));

                var start = moment(date);
                var end   = moment(start);

                end.add('ms', list.get('duration'));

                var times = self.checkOverlap({start: start, end: end});

                var event = {
                    title:  list.get('name'),
                    start:  times.start.valueOf(), end: times.end.valueOf(),
                    playlist:   list.get('_id'),
                    allDay: allDay,
                };

                console.log ('to save', event);
                var item = self.collection.create (event);
                console.log (this, list, event, item);
            }
        });

                                             /*
            eventRender: function(event, element) {
                var model = self.collection.where({list: event.list})[0];

                element.tooltip({
                    trigger: 'click',
                    placement: 'left',
                    title: function () {
                        var target = document.createElement('div');
                        var view = new MediaListView({model: model,
                                                      noSearch:true,
                                                      el: target});
                        return view.render().el;
                    },
                });
            }
                                             */

        self.collection.bind('add reset remove change', this.reload, this);
        self.collection.bind('all',   function (e, a) {console.log('got: ' + e, a);}, this);
        self.collection.bind('overlap', this.displayOverlap, this);

        return this;
    },
});
<|endoftext|>


<commit_before>import React, {Component} from 'react';

class HotelsIndv extends Component {
    render(){
        return (

{this.props.name}

{this.props.rate}

        );
    }
}

export default HotelsIndv;<commit_msg>added link to href<commit_after>import React, {Component} from 'react';

class HotelsIndv extends Component {
    render(){

        return (

{this.props.name.length > 20 ? this.props.name.slice(0,20) + '...' : this.props.name}

{this.props.rate}

        );
    }
}

export default HotelsIndv;<|endoftext|>


<commit_before>

(function() {
  var stylesheet = false;

  function swapDirection() {
    if (!stylesheet){
      var linkList = document.getElementsByTagName('link');
      for (var i = 0;i < linkList.length ;i++){
        if ((/bootstrap/).test(linkList[i].href) && 'stylesheet' == linkList[i].rel){
          stylesheet = linkList[i];
          break;
        }
      }
    }
    if (!stylesheet) return;
    if ((/\-rtl/i).test(stylesheet.href))
      stylesheet.href = stylesheet.href.replace('-rtl','');
    else
      stylesheet.href = stylesheet.href.replace('bootstrap','bootstrap-rtl');
  }
  window.addEventListener('load',function() {
    var swapDirectionDiv = document.createElement('div');
    swapDirectionDiv.setAttribute('style',
    'position: fixed;z-index: 9999;left: -48px; width: 243px; -webkit-transform: rotate(-45deg); top: 48px;' +
    'background-color: white;border: 1px solid #A7A7A7;text-align: center;font-family: sans-serif;' +
    'font-size: 18px;box-shadow: 1px 1px 32px  rgba(0, 0, 0, 0.64);');
    swapDirectionDiv.innerHTML = 'Swap Direction';
    document.body.appendChild(swapDirectionDiv);
    swapDirectionDiv.addEventListener('click',swapDirection);
  });
})();
<commit_msg>fix swap direction<commit_after>

(function() {
  var stylesheet = false;

  function swapDirection() {
    if (!stylesheet){
      var linkList = document.getElementsByTagName('link');
      for (var i = 0;i < linkList.length ;i++){
        if ((/bootstrap/).test(linkList[i].href) && 'stylesheet' == linkList[i].rel){
          stylesheet = linkList[i];
          break;
        }
      }
    }
    if (!stylesheet) return;
    if ((/\-rtl/i).test(stylesheet.href))
      stylesheet.href = stylesheet.href.replace(/\-rtl/i,'');
    else
      stylesheet.href = stylesheet.href.replace(/bootstrap([^\/]*css)/,'bootstrap-rtl$1');
  }
  window.addEventListener('load',function() {
    var swapDirectionDiv = document.createElement('div');
    swapDirectionDiv.setAttribute('style',
    'position: fixed;z-index: 9999;left: -48px; width: 243px; -webkit-transform: rotate(-45deg); top: 48px;' +
    'background-color: white;border: 1px solid #A7A7A7;text-align: center;font-family: sans-serif;' +
    'font-size: 18px;box-shadow: 1px 1px 32px  rgba(0, 0, 0, 0.64);');
    swapDirectionDiv.innerHTML = 'Swap Direction';
    document.body.appendChild(swapDirectionDiv);
    swapDirectionDiv.addEventListener('click',swapDirection);
  });
})();
<|endoftext|>


<commit_before>enyo.kind({
	name:"App",
	kind:"Control",
	hatsize: 48,
	hatmargin: 8,
	rows: 10,
	score: 0,
	canplay: true,
	moves: [],
	components:[
		{name:"bottom", classes:"overlap center bottom"},
		{name:"hats", style:"display: none;", components: [
			{kind:"Image", onload:"loadHandler", src:"images/game_bear.png"},
			{kind:"Image", onload:"loadHandler", src:"images/game_bunny_02.png"},
			{kind:"Image", onload:"loadHandler", src:"images/game_carrot.png"},
			{kind:"Image", onload:"loadHandler", src:"images/game_lemon.png"},
			{kind:"Image", onload:"loadHandler", src:"images/game_panda.png"},
			{kind:"Image", onload:"loadHandler", src:"images/game_piratePig.png"},
		]},
		// why can't there just be one standard that isn't wav?
		{name:"sounds", style:"display: none;", components:[
			{name:"three", kind:"Audio", src:["sounds/3.ogg", "sounds/3.mp3", "sounds/3.wav"], onEnded: "endedHandler"},
			{name:"four", kind:"Audio", src:["sounds/4.ogg", "sounds/4.mp3", "sounds/4.wav"], onEnded: "endedHandler"},
			{name:"fiveplus", kind:"Audio", src:["sounds/5.ogg", "sounds/5.mp3", "sounds/5.wav"], onEnded: "endedHandler"},
			{name:"whiff", kind:"Audio", src:["sounds/whiff.ogg", "sounds/whiff.mp3", "sounds/whiff.wav"], onEnded:"endedHandler"},
			{name:"theme", kind:"Audio", src:["sounds/theme.ogg", "sounds/theme.mp3", "sounds/theme.wav"], onEnded:"endedHandler"}
		]},
		{name:"title", style:"width: 560px; height: 100px;", classes:"hcenter banner", components:[
			{name:"score", classes:"score", content:"0"},
		]},
		{name:"backgroundbox", kind:"Canvas", attributes:{height:"560px", width:"560px"}, classes:"overlap hcenter", components:[
			{name:"background", kind:"canvas.Rectangle", bounds:{t:0, l:0, w:560, h:560}, color:"rgba(255,255,255,0.9)"},
		]},
		{name:"selectbox", kind:"Canvas", attributes:{height:"560px", width:"560px"}, classes:"overlap hcenter", components:[
			{name:"selector", kind:"Selector", color:"red"}
		]},
		{name:"hatbox", kind:"Canvas", attributes:{height:"560px", width:"560px"}, classes:"overlap hcenter border", ontap:"hatTap"}
	],
	create: function() {
		this.inherited(arguments);
		this.addClass("bg");
		// sounds only occur on user actions on ios
		if (navigator.userAgent.match(/i(?:pad|phone)/i)) {
			this.ios = true;
		}
	},
	loadHandler: function() {
		this.loaded = (this.loaded || 0) + 1;
		if (this.loaded == this.$.hats.getClientControls().length) {
			this.initHats();
		}
	},
	endedHandler: function() {
		enyo.job.stop(this.id + "enableSound");
		this.canplay = true;
	},
	getImage: function(inIndex) {
		return this.$.hats.getClientControls()[inIndex].hasNode();
	},
	getType: function() {
		return enyo.irand(this.$.hats.getClientControls().length);
	},
	scale: function() {
		var b = Math.min(window.innerWidth, window.innerHeight - (this.hatsize + this.hatmargin));
		if (b < this.rows * 44) {
			this.hatsize = 28;
			this.hatmargin = 4;
		} else if (b < this.rows * 56) {
			this.hatsize = 38;
			this.hatmargin = 6;
		} else if (b > this.rows * 100) {
			this.hatsize = 62;
			this.hatmargin = 10;
		} else {
			this.hatsize = 48;
			this.hatmargin = 8;
		}
		var s = (this.hatsize + this.hatmargin) * this.rows;
		this.$.title.applyStyle("width", s + "px");
		this.$.title.applyStyle("height", s/10 + "px");
		this.$.score.applyStyle("line-height", s/10 + "px");
		this.$.background.bounds.w = s;
		this.$.background.bounds.h = s;
		this.$.selector.setSize(this.hatsize);
		this.$.selector.setMargin(this.hatmargin);
		var hc = this.$.hatbox.getClientControls();
		for (var i = 0, h; h = hc[i]; i++) {
			h.setSize(this.hatsize);
			h.setMargin(this.hatmargin);
			h.iChanged();
			h.jChanged();
		}
		for (var i = 0, c; c = ["background", "select", "hat"][i]; i++) {
			this.$[c+"box"].setAttribute("width", s);
			this.$[c+"box"].setAttribute("height", s);
			this.$[c+"box"].update();
		}
	},
	initHats: function() {
		this.scale();
		this.$.hatbox.destroyClientControls();
		var col;
		this.map = [];
		var src, t, l;
		for (var i = 0; i < this.rows; i++) {
			// i = which column = x = left
			col = this.map[i] = [];
			for (var j = 0; j < this.rows; j++) {
				// j = which row = y = top
				var nhat = this.newHat(i,j);
				col.push(nhat);
			}
		}
		this.playSound(-1);
		this.start();
		this.splatMatches(this.checkMatches());
		this.$.hatbox.update();
	},
	start: function() {
		this.pulse = setInterval(enyo.bind(this, "heartbeat"), 30);
	},
	stop: function() {
		clearInterval(this.pulse);
	},
	playSound: function(inNum, inUserEvent) {
		var iosplay = this.ios ? inUserEvent : true;
		if (this.canplay && iosplay) {
			this.canplay = false;
			var n;
			var delay = 0;
			if (inNum >= 5) {
				n = this.$.fiveplus;
				delay = 2800;
			} else if (inNum == 4) {
				n = this.$.four;
				delay = 800;
			} else if (inNum <= 3 && inNum > 0) {
				n = this.$.three;
				delay = 100;
			} else if (inNum == -1) {
				n = this.$.theme;
				delay = 6000;
			} else {
				n = this.$.whiff;
				delay = 2000;
			}
			if (n && n.play) {
				n.play();
				enyo.job(this.id+"enableSound", enyo.bind(this,"endedHandler"), delay);
			}
		}
	},
	hatTap: function(inSender, inEvent) {
		var t = inEvent.target;
		var x = inEvent.pageX - t.offsetLeft;
		var y = inEvent.pageY - t.offsetTop;
		var col = Math.floor(x / (this.hatsize + this.hatmargin));
		var row = Math.floor(y / (this.hatsize + this.hatmargin));
		var oh = this.map[col][row];
		var matches = 0;
		if (oh.animating) {
			return;
		}
		if (!this.selected) {
			this.selected = oh;
			this.$.selector.show(col, row);
		} else {
			var d = this.selected.distance(oh);
			// manhattan distance
			var md = Math.abs(d.di) + Math.abs(d.dj);
			if (md == 1) {
				matches = this.exchange(this.selected, oh);
			}
			// don't play sound if you tap the selected square again
			if (md != 0) {
				this.playSound(matches, true);
			}
			this.selected = null;
			this.$.selector.hide();
		}
		this.$.selectbox.update();
	},
	distance: function(inHatA, inHatB) {
		return Math.abs(inHatA.i - inHatB.i) + Math.abs(inHatA.j - inHatB.j);
	},
	exchange: function(inA, inB) {
		var d = inA.distance(inB);
		var na = {i: inA.i + d.di, j: inA.j + d.dj};
		var nb = {i: inB.i - d.di, j: inB.j - d.dj};
		this.map[na.i][na.j] = inA;
		this.map[nb.i][nb.j] = inB;
		var matches = this.checkMatches();
		if (matches.length) {
			if (d.di) {
				this.moves.push(inA.moveX(d.di));
				this.moves.push(inB.moveX(-d.di));
			} else {
				this.moves.push(inA.moveY(d.dj));
				this.moves.push(inB.moveY(-d.dj));
			}
		}
		this.map[inA.i][inA.j] = inA;
		this.map[inB.i][inB.j] = inB;
		return matches.length;
	},
	checkMatches: function() {
		var matches = [];
		this._checkMatches(
			enyo.bind(this,"get"),
			enyo.bind(this,"make"),
			matches
		);
		this._checkMatches(
			enyo.bind(this,"rget"),
			enyo.bind(this,"rmake"),
			matches
		);
		return matches;
	},
	get: function(a,b) {
		return this.map[a][b].type;
	},
	rget: function(a,b) {
		return this.map[b][a].type;
	},
	make: function(a,b) {
		return {i:a,j:b};
	},
	rmake: function(a,b) {
		return {i:b,j:a};
	},
	_checkMatches: function(get, make, matches) {
		for (var i=0, t, c, k0; i<this.rows; i++) {
			c = 0;
			t = -1;
			for (var j=0, tt; j<this.rows; j++) {
				tt = get(i, j);
				if (t == -1) {
					t = tt;
					continue;
				}
				if (tt == t) {
					c++;
				}
				if (tt != t || j == this.rows-1) {
					k0 = j - c - 1;
					if (c >= 2) {
						if (j == this.rows-1 && tt == t) {
							k0++;
						}
						this.score += Math.pow(c,2) * 50;
						for (var k=k0; c>-1; k++,c--) {
							matches.push(make(i, k));
						}
					}
					c = 0;
					t = tt;
				}
			}
		}
	},
	splatMatches: function(inMatches) {
		for (var i=0, m; m=inMatches[i]; i++) {
			this.splat(m.i, m.j);
		}
		if (inMatches.length) {
			this.playSound(inMatches.length);
		}
		this.$.score.setContent(this.score);
	},
	splat: function(i, j) {
		var hat0 = this.map[i][j];
		if (hat0.animating) {
			return;
		}
		this.map[hat0.i][hat0.j] = null;
		for (var i=hat0.i, j=hat0.j-1; j>=0; j--) {
			var hat = this.map[i][j];
			if (hat) {
				this.map[i][j] = null;
				this.map[i][j+1] = hat;
				this.moves.push(hat.moveDown());
			}
		}
		var nhat = this.map[hat0.i][0] = this.newHat(hat0.i, -1);
		this.moves.push(nhat.moveDown());
		this.moves.push(hat0.splat());
	},
	heartbeat: function() {
		if (this.moves.length) {
			var live = [];
			for (var i = 0, m; m = this.moves[i]; i++) {
				if (m.move()) {
					live.push(m);
				}
			}
			this.moves = live;
			if (this.moves.length == 0) {
				this.splatMatches(this.checkMatches());
			}
			this.$.hatbox.update();
		}
	},
	newHat: function(i,j) {
		var type = this.getType()
		var image = this.getImage(type);
		return this.$.hatbox.createComponent({kind: "Hat", i: i, j: j, owner: this, image:image, type:type, bounds:{}, size:this.hatsize, margin:this.hatmargin});
	},
	resizeHandler: function() {
		enyo.job(this.id + "resize", enyo.bind(this, "rescale"), 100);
	},
	rescale: function() {
		this.stop();
		this.scale();
		this.start();
	},
	touchstartHandler: function() {
		if (this.ios && !this.iosfirstsound) {
			this.iosfirstsound = true;
			this.playSound(-1, true);
		}
	}
});
<commit_msg>38x38 blocks<commit_after>enyo.kind({
	name:"App",
	kind:"Control",
	hatsize: 48,
	hatmargin: 8,
	rows: 10,
	score: 0,
	canplay: true,
	moves: [],
	components:[
		{name:"bottom", classes:"overlap center bottom"},
		{name:"hats", style:"display: none;", components: [
			{kind:"Image", onload:"loadHandler", src:"images/game_bear.png"},
			{kind:"Image", onload:"loadHandler", src:"images/game_bunny_02.png"},
			{kind:"Image", onload:"loadHandler", src:"images/game_carrot.png"},
			{kind:"Image", onload:"loadHandler", src:"images/game_lemon.png"},
			{kind:"Image", onload:"loadHandler", src:"images/game_panda.png"},
			{kind:"Image", onload:"loadHandler", src:"images/game_piratePig.png"},
		]},
		// why can't there just be one standard that isn't wav?
		{name:"sounds", style:"display: none;", components:[
			{name:"three", kind:"Audio", src:["sounds/3.ogg", "sounds/3.mp3", "sounds/3.wav"], onEnded: "endedHandler"},
			{name:"four", kind:"Audio", src:["sounds/4.ogg", "sounds/4.mp3", "sounds/4.wav"], onEnded: "endedHandler"},
			{name:"fiveplus", kind:"Audio", src:["sounds/5.ogg", "sounds/5.mp3", "sounds/5.wav"], onEnded: "endedHandler"},
			{name:"whiff", kind:"Audio", src:["sounds/whiff.ogg", "sounds/whiff.mp3", "sounds/whiff.wav"], onEnded:"endedHandler"},
			{name:"theme", kind:"Audio", src:["sounds/theme.ogg", "sounds/theme.mp3", "sounds/theme.wav"], onEnded:"endedHandler"}
		]},
		{name:"title", style:"width: 560px; height: 100px;", classes:"hcenter banner", components:[
			{name:"score", classes:"score", content:"0"},
		]},
		{name:"backgroundbox", kind:"Canvas", attributes:{height:"560px", width:"560px"}, classes:"overlap hcenter", components:[
			{name:"background", kind:"canvas.Rectangle", bounds:{t:0, l:0, w:560, h:560}, color:"rgba(255,255,255,0.9)"},
		]},
		{name:"selectbox", kind:"Canvas", attributes:{height:"560px", width:"560px"}, classes:"overlap hcenter", components:[
			{name:"selector", kind:"Selector", color:"red"}
		]},
		{name:"hatbox", kind:"Canvas", attributes:{height:"560px", width:"560px"}, classes:"overlap hcenter border", ontap:"hatTap"}
	],
	create: function() {
		this.inherited(arguments);
		this.addClass("bg");
		// sounds only occur on user actions on ios
		if (navigator.userAgent.match(/i(?:pad|phone)/i)) {
			this.ios = true;
		}
	},
	loadHandler: function() {
		this.loaded = (this.loaded || 0) + 1;
		if (this.loaded == this.$.hats.getClientControls().length) {
			this.initHats();
		}
	},
	endedHandler: function() {
		enyo.job.stop(this.id + "enableSound");
		this.canplay = true;
	},
	getImage: function(inIndex) {
		return this.$.hats.getClientControls()[inIndex].hasNode();
	},
	getType: function() {
		return enyo.irand(this.$.hats.getClientControls().length);
	},
	scale: function() {
		var b = Math.min(window.innerWidth, window.innerHeight - (this.hatsize + this.hatmargin));
		if (b < this.rows * 38) {
			this.hatsize = 28;
			this.hatmargin = 4;
		} else if (b < this.rows * 56) {
			this.hatsize = 32;
			this.hatmargin = 6;
		} else if (b > this.rows * 100) {
			this.hatsize = 62;
			this.hatmargin = 10;
		} else {
			this.hatsize = 48;
			this.hatmargin = 8;
		}
		var s = (this.hatsize + this.hatmargin) * this.rows;
		this.$.title.applyStyle("width", s + "px");
		this.$.title.applyStyle("height", s/10 + "px");
		this.$.score.applyStyle("line-height", s/10 + "px");
		this.$.background.bounds.w = s;
		this.$.background.bounds.h = s;
		this.$.selector.setSize(this.hatsize);
		this.$.selector.setMargin(this.hatmargin);
		var hc = this.$.hatbox.getClientControls();
		for (var i = 0, h; h = hc[i]; i++) {
			h.setSize(this.hatsize);
			h.setMargin(this.hatmargin);
			h.iChanged();
			h.jChanged();
		}
		for (var i = 0, c; c = ["background", "select", "hat"][i]; i++) {
			this.$[c+"box"].setAttribute("width", s);
			this.$[c+"box"].setAttribute("height", s);
			this.$[c+"box"].update();
		}
	},
	initHats: function() {
		this.scale();
		this.$.hatbox.destroyClientControls();
		var col;
		this.map = [];
		var src, t, l;
		for (var i = 0; i < this.rows; i++) {
			// i = which column = x = left
			col = this.map[i] = [];
			for (var j = 0; j < this.rows; j++) {
				// j = which row = y = top
				var nhat = this.newHat(i,j);
				col.push(nhat);
			}
		}
		this.playSound(-1);
		this.start();
		this.splatMatches(this.checkMatches());
		this.$.hatbox.update();
	},
	start: function() {
		this.pulse = setInterval(enyo.bind(this, "heartbeat"), 30);
	},
	stop: function() {
		clearInterval(this.pulse);
	},
	playSound: function(inNum, inUserEvent) {
		var iosplay = this.ios ? inUserEvent : true;
		if (this.canplay && iosplay) {
			this.canplay = false;
			var n;
			var delay = 0;
			if (inNum >= 5) {
				n = this.$.fiveplus;
				delay = 2800;
			} else if (inNum == 4) {
				n = this.$.four;
				delay = 800;
			} else if (inNum <= 3 && inNum > 0) {
				n = this.$.three;
				delay = 100;
			} else if (inNum == -1) {
				n = this.$.theme;
				delay = 6000;
			} else {
				n = this.$.whiff;
				delay = 2000;
			}
			if (n && n.play) {
				n.play();
				enyo.job(this.id+"enableSound", enyo.bind(this,"endedHandler"), delay);
			}
		}
	},
	hatTap: function(inSender, inEvent) {
		var t = inEvent.target;
		var x = inEvent.pageX - t.offsetLeft;
		var y = inEvent.pageY - t.offsetTop;
		var col = Math.floor(x / (this.hatsize + this.hatmargin));
		var row = Math.floor(y / (this.hatsize + this.hatmargin));
		var oh = this.map[col][row];
		var matches = 0;
		if (oh.animating) {
			return;
		}
		if (!this.selected) {
			this.selected = oh;
			this.$.selector.show(col, row);
		} else {
			var d = this.selected.distance(oh);
			// manhattan distance
			var md = Math.abs(d.di) + Math.abs(d.dj);
			if (md == 1) {
				matches = this.exchange(this.selected, oh);
			}
			// don't play sound if you tap the selected square again
			if (md != 0) {
				this.playSound(matches, true);
			}
			this.selected = null;
			this.$.selector.hide();
		}
		this.$.selectbox.update();
	},
	distance: function(inHatA, inHatB) {
		return Math.abs(inHatA.i - inHatB.i) + Math.abs(inHatA.j - inHatB.j);
	},
	exchange: function(inA, inB) {
		var d = inA.distance(inB);
		var na = {i: inA.i + d.di, j: inA.j + d.dj};
		var nb = {i: inB.i - d.di, j: inB.j - d.dj};
		this.map[na.i][na.j] = inA;
		this.map[nb.i][nb.j] = inB;
		var matches = this.checkMatches();
		if (matches.length) {
			if (d.di) {
				this.moves.push(inA.moveX(d.di));
				this.moves.push(inB.moveX(-d.di));
			} else {
				this.moves.push(inA.moveY(d.dj));
				this.moves.push(inB.moveY(-d.dj));
			}
		}
		this.map[inA.i][inA.j] = inA;
		this.map[inB.i][inB.j] = inB;
		return matches.length;
	},
	checkMatches: function() {
		var matches = [];
		this._checkMatches(
			enyo.bind(this,"get"),
			enyo.bind(this,"make"),
			matches
		);
		this._checkMatches(
			enyo.bind(this,"rget"),
			enyo.bind(this,"rmake"),
			matches
		);
		return matches;
	},
	get: function(a,b) {
		return this.map[a][b].type;
	},
	rget: function(a,b) {
		return this.map[b][a].type;
	},
	make: function(a,b) {
		return {i:a,j:b};
	},
	rmake: function(a,b) {
		return {i:b,j:a};
	},
	_checkMatches: function(get, make, matches) {
		for (var i=0, t, c, k0; i<this.rows; i++) {
			c = 0;
			t = -1;
			for (var j=0, tt; j<this.rows; j++) {
				tt = get(i, j);
				if (t == -1) {
					t = tt;
					continue;
				}
				if (tt == t) {
					c++;
				}
				if (tt != t || j == this.rows-1) {
					k0 = j - c - 1;
					if (c >= 2) {
						if (j == this.rows-1 && tt == t) {
							k0++;
						}
						this.score += Math.pow(c,2) * 50;
						for (var k=k0; c>-1; k++,c--) {
							matches.push(make(i, k));
						}
					}
					c = 0;
					t = tt;
				}
			}
		}
	},
	splatMatches: function(inMatches) {
		for (var i=0, m; m=inMatches[i]; i++) {
			this.splat(m.i, m.j);
		}
		if (inMatches.length) {
			this.playSound(inMatches.length);
		}
		this.$.score.setContent(this.score);
	},
	splat: function(i, j) {
		var hat0 = this.map[i][j];
		if (hat0.animating) {
			return;
		}
		this.map[hat0.i][hat0.j] = null;
		for (var i=hat0.i, j=hat0.j-1; j>=0; j--) {
			var hat = this.map[i][j];
			if (hat) {
				this.map[i][j] = null;
				this.map[i][j+1] = hat;
				this.moves.push(hat.moveDown());
			}
		}
		var nhat = this.map[hat0.i][0] = this.newHat(hat0.i, -1);
		this.moves.push(nhat.moveDown());
		this.moves.push(hat0.splat());
	},
	heartbeat: function() {
		if (this.moves.length) {
			var live = [];
			for (var i = 0, m; m = this.moves[i]; i++) {
				if (m.move()) {
					live.push(m);
				}
			}
			this.moves = live;
			if (this.moves.length == 0) {
				this.splatMatches(this.checkMatches());
			}
			this.$.hatbox.update();
		}
	},
	newHat: function(i,j) {
		var type = this.getType()
		var image = this.getImage(type);
		return this.$.hatbox.createComponent({kind: "Hat", i: i, j: j, owner: this, image:image, type:type, bounds:{}, size:this.hatsize, margin:this.hatmargin});
	},
	resizeHandler: function() {
		enyo.job(this.id + "resize", enyo.bind(this, "rescale"), 100);
	},
	rescale: function() {
		this.stop();
		this.scale();
		this.start();
	},
	touchstartHandler: function() {
		if (this.ios && !this.iosfirstsound) {
			this.iosfirstsound = true;
			this.playSound(-1, true);
		}
	}
});
<|endoftext|>