<commit_before>var isUploadSuccess = 'hoge';

$(function(){
  var timerID;
  var timerArray = new Array();
  var timer;

  gorgon.image_size = 'large';

  timelineAllLoad();

  if ( gorgon.timer != undefined )
  {
    timer = gorgon.timer;
  }
  else
  {
    timer = 15000;
  }

  timerID = setInterval('timelineDifferenceLoad()', timer);
  if ( gorgon.notify !== undefined )
  {
    $('#timeline-desktopify').desktopify({
      unsupported : function(){
        $('#timeline-desktopify').hide();
      }
    }).trigger('click');
  }

  $('#timeline-submit-button').click( function() {
    $(this).attr('disabled', 'disabled');
    $('#timeline-submit-error').empty();
    $('#timeline-submit-error').hide();
    $('#timeline-submit-loader').show();
    $('#photo-file-name').empty();
    $('#photo-remove').hide();

    var body = $('#timeline-textarea').val();
    body = body.replace(/"/g, '"')

    if (gorgon)
    {
      var publicFlag = 1;
      if ('community' != gorgon.target)
      {
        publicFlag = $('#timeline-public-flag option:selected').val()
      }

      var data = {
        body: body,
        target: gorgon.post.foreign,
        target_id: gorgon.post.foreignId,
        apiKey: openpne.apiKey,
        public_flag: publicFlag
      };
    }
    else
    {
      var data = {
        body: body,
        apiKey: openpne.apiKey
      };
    }

    tweetByData(data);
  });

  $('#timeline-loadmore').click( function() {
    $('#timeline-loadmore').hide();
    $('#timeline-loadmore-loading').show();
    timelineLoadmore();
  });

  $('.timeline-comment-loadmore').live('click', function() {
    var timelineId = $(this).attr('data-timeline-id');
    var commentlist = $('#commentlist-' + timelineId);
    var commentLength = commentlist.children('.timeline-post-comment').length;
    $('#timeline-comment-loader-' + timelineId).show();

    $.ajax({
      type: 'GET',
      url: openpne.apiBase + 'activity/commentSearch.json?apiKey=' + openpne.apiKey,
      data: {
        'timeline_id': timelineId,
        'count': commentLength + 20
      },
      success: function(json){
        commentlist.children().remove();
        $('#timelineCommentTemplate').tmpl(json.data.reverse()).prependTo(commentlist);
        $('#timeline-comment-loader-' + timelineId).hide();

        if (json.data.length < commentLength + 20)
        {
          $('#timeline-comment-loadmore-' + timelineId).hide();
        }
      },
      error: function(XMLHttpRequest, textStatus, errorThrown){
        $(commentlist).hide();
      }
    });
  });

  $('#timeline-submit-upload').change(function() {
    var fileName = $('#timeline-submit-upload').val();
    $('#photo-remove').show();
    if (20 > fileName.length)
    {
      $('#photo-file-name').text(fileName);
    }
    else
    {
      $('#photo-file-name').text(fileName.substring(0, 19) + '…');
    }
  });

  $('#timeline-upload-photo-button').click(function() {
    $('#timeline-submit-upload').click();

  });

  $('#timeline-submit-upload').change(function() {
    if ($.browser.msie)
    {
      return;
    }

    $('#timeline-submit-error').hide();
    $('#timeline-submit-error').empty();

    var size = this.files[0].size;

    if (size >= fileMaxSizeInfo['size']) {
      $('#timeline-submit-error').show();

      var errorMessage = 'ファイルは' + fileMaxSizeInfo['format'] + '以上はアップロードできません';
      $('#timeline-submit-error').text(errorMessage);

      $('#timeline-submit-upload').empty();
      $('#timeline-submit-upload').val('');
      $('#photo-file-name').empty();
    }
  });

  $('#timeline-textarea').keyup( function() {
    lengthCheck($(this), $('#timeline-submit-button'));
  });

  $('.timeline-post-comment-form-input').live('keyup', function() {
    lengthCheck($(this), $('button[data-timeline-id=' + $(this).attr('data-timeline-id') + ']'));
  });

  $('#photo-remove').click( function() {
    $('#timeline-submit-upload').val('');
    $('#photo-file-name').empty();
    $(this).hide();
  });
});

function timelineAllLoad() {

  if (gorgon)
  {
    gorgon.apiKey = openpne.apiKey;
    $.ajax({
      type: 'GET',
      url: openpne.apiBase + 'activity/search.json',
      data: gorgon,
      success: function(response){

        if ($.isEmptyObject(response.data))
        {
          $('#timeline-loading').hide();
          $('#timeline-list').text('タイムラインは投稿されていません。');
          $('#timeline-list').show();
        }
        else
        {
          renderJSON(response, 'all');
        }

      },
      error: function(XMLHttpRequest, textStatus, errorThrown){
        $('#timeline-loading').hide();
        $('#timeline-list').text('タイムラインは投稿されていません。');
        $('#timeline-list').show();
      }
    });
  }
  else
  {
    $.ajax({
      type: 'GET',
      url: openpne.apiBase + 'activity/search.json?apiKey=' + openpne.apiKey,
      success: function(response){

        if ($.isEmptyObject(response.data))
        {
          $('#timeline-loading').hide();
          $('#timeline-list').text('タイムラインは投稿されていません。');
          $('#timeline-list').show();
        }
        else
        {
          renderJSON(response, 'all');
        }

      },
      error: function(XMLHttpRequest, textStatus, errorThrown){
        $('#timeline-loading').hide();
        $('#timeline-list').text('タイムラインは投稿されていません。');
        $('#timeline-list').show();
      }
    });
  }
}

function timelineDifferenceLoad() {
  var lastId = $('#timeline-list').attr('data-last-id');

  if (gorgon)
  {
    gorgon.apiKey = openpne.apiKey;
  }
  else
  {
    gorgon = {
      apiKey: openpne.apiKey
    }
  }
  $.getJSON( openpne.apiBase + 'activity/search.json?count=20&since_id=' + lastId, gorgon, function(json){
    if (json.data)
    {
      renderJSON(json, 'diff');
    }
  });
}

function timelineLoadmore() {
  var loadmoreId = $('#timeline-list').attr('data-loadmore-id');
  loadmoreId = loadmoreId - 1;
  if (gorgon)
  {
    gorgon.apiKey = openpne.apiKey;
  }
  else
  {
    gorgon = {
      apiKey: openpne.apiKey
    }
  }
  gorgon.max_id = loadmoreId;

  $.ajax({
    type: 'GET',
    url: openpne.apiBase + 'activity/search.json',
    data: gorgon,
    success: function(json){
      renderJSON(json, 'more');
    },
    error: function(XMLHttpRequest, textStatus, errorThrown){
      $('#timeline-loadmore-loading').hide();
    }
  });
}

function renderJSON(json, mode) {
  if (undefined == mode)
  {
    mode = 'all';
  }
  if ('all' == mode)
  {
    $('#timeline-list').empty();
  }
  if(json.data && 0 < viewPhoto)
  {
    autoLinker(json);
  }

  $timelineData = $('#timelineTemplate').tmpl(json.data);
  $('.timeline-comment-button', $timelineData).timelineComment();
  $('.timeline-comment-link', $timelineData).click(function(){
    $commentBoxArea = $(this).parent().find('.timeline-post-comment-form');
    $commentBoxArea.show();
    $commentBoxArea.children('.timeline-post-comment-form-input').focus();
  });
  if ('diff' == mode)
  {
    $timelineData.prependTo('#timeline-list');
  }
  else
  {
    $timelineData.appendTo('#timeline-list');
  }
  if ('all' == mode || 'diff' == mode)
  {
    if(json.data[0])
    {
      $('#timeline-list').attr('data-last-id', json.data[0].id);
    }
  }
  if ('all' == mode || 'more' == mode)
  {
    var max = json.data.length - 1;
    if (json.data[max])
    {
      $('#timeline-list').attr('data-loadmore-id', json.data[max].id);
    }
  }
  if(json.data)
  {
    for(i=0;i<json.data.length;i++)
    {
      if(json.data[i].replies)
      {
        $('#timelineCommentTemplate').tmpl(json.data[i].replies.reverse()).prependTo('#commentlist-' +json.data[i].id);
        $('#timeline-post-comment-form-' + json.data[i].id, $timelineData).show();
      }
      if(10 < parseInt(json.data[i].replies_count))
      {
        $('#timeline-comment-loadmore-' + json.data[i].id).show();
      }
    }
  }
  $('button.timeline-post-delete-button').timelineDelete();
  $('.timeline-post-delete-confirm-link').colorbox({
    inline: true,
    width: '610px',
    opacity: '0.8',
    onOpen: function(){
      $($(this).attr('href')).show();
    },
    onCleanup: function(){
      $($(this).attr('href')).hide();
    },
    onClosed: function(){
      timelineAllLoad();
    }
  });
  if ('all' == mode)
  {
    $('#timeline-loading').hide();
  }
  if ('more' == mode)
  {
    $('#timeline-loadmore').show();
    $('#timeline-loadmore-loading').hide();
  }
  $('.timeago').timeago();
}

function convertTag(str) {
  str = str.replace(/&/g,'&');
  str = str.replace(/"/g,'"');
  str = str.replace(/'/g,''');
  str = str.replace(/</g,'<');
  str = str.replace(/>/g,'>');
  return str;
}

function tweetByData(data)
{
  //reference　http://lagoscript.org/jquery/upload/documentation
  $('#timeline-submit-upload').upload(
    openpne.apiBase + 'activity/post.json', data,
    function (res) {
      var resCheck = responceCheck(res);
      if (false !== resCheck)
      {
        $('#timeline-submit-error').text(resCheck);
        $('#timeline-submit-error').show();
        $('#timeline-submit-loader').hide();
        return;
      }

      res = res.replace(/,\"body.*\"/g, '');
      returnData = JSON.parse(res);

      if (returnData.status === "error") {

        var errorMessages = {
          file_size: 'ファイルサイズは' + fileMaxSizeInfo['size'] + 'までです',
          upload: 'アップロードに失敗しました',
          not_image: '画像をアップロードしてください',
          tweet: '投稿に失敗しました'
        };

        var errorType = returnData.type;

        $('#timeline-submit-error').text(errorMessages[errorType]);
        if ($.browser.msie && $.browser.version > 6)
        {
        }
        $('#timeline-submit-error').show();
        $('#timeline-submit-loader').hide();

      } else {
        $('#timeline-submit-error').empty();
        timelineAllLoad();
      }

      $('#timeline-submit-upload').val('');
      $('#timeline-submit-upload').empty();
      $('#timeline-textarea').val('');
      $('#timeline-submit-loader').hide();
      $('#counter').text(MAXLENGTH);

    },
    'text' //なぜかJSON形式でうけとることができなかった
    );
}

function autoLinker(json)
{
  for(i=0;i<json.data.length;i++)
  {
    if (!json.data[i].body_html.match(/img.*src=/))
    {
      if (json.data[i].body.match(/\.(jpg|jpeg|png|gif)/))
      {
        json.data[i].body_html = json.data[i].body.replace(/((http:|https:)\/\/[\x21-\x26\x28-\x7e]+.(jpg|jpeg|png|gif))/gi, '

');
      }
      else if (json.data[i].body.match(/((http:|https:)\/\/www\.youtube\.com\/watch\?v=([a-zA-Z0-9_\-]+))/))
      {
        var youtubeId = json.data[i].body.substring(json.data[i].body.lastIndexOf('v=') + 2, json.data[i].body.length);
        var iframe = '';
        json.data[i].body_html = json.data[i].body.replace(/((http:|https:)\/\/www\.youtube\.com\/watch\?v=([a-zA-Z0-9_\-]+))/gi, '
' + iframe + '
');
      }
      else if (json.data[i].body.match(/((http:|https:)\/\/www\.amazon\..*\/([a-zA-Z0-9_\-]+)\/.*)/))
      {
        var match_id = json.data[i].body.match(/(?:ASIN|product|dp)\/([^\/]+)/i);
        if (match_id) {
          id = RegExp.$1;
        }
        var url = 'http://amazon.openpne.jp/?id=' + id + '&tag=';
        json.data[i].body_html = json.data[i].body.replace(/((http:|https:)\/\/www\.amazon\..*\/([a-zA-Z0-9_\-]+)\/.*)/, '
この部分はインラインフレームを使用しています。
');
      }
      else if (json.data[i].body.match(/((http:|https:)\/\/[\x21-\x26\x28-\x7e]+)/))
      {
        json.data[i].body_html = json.data[i].body.replace(/((http:|https:)\/\/[\x21-\x26\x28-\x7e]+)/gi, '

$1
');
      }
    }
    json.data[i].body_html = json.data[i].body_html.replace(/<br \/>/g, '
');
  }
}

function lengthCheck(obj, target)
{
  if (0 < $.trim(obj.val()).length && 140 >= obj.val().length)
  {
    target.removeAttr('disabled');
  }
  else
  {
    target.attr('disabled', 'disabled');
  }
}

function responceCheck(res)
{
  if (0 <= res.indexOf('\<pre'))
  {
    return 'エラーが発生しました。再度読み込んで下さい。';
  }
  return false;
}
<commit_msg>もっと読むボタンを押した後投稿すると表示されるデータがおかしくなるのを修正<commit_after>var isUploadSuccess = 'hoge';

$(function(){
  var timerID;
  var timerArray = new Array();
  var timer;

  gorgon.image_size = 'large';

  timelineAllLoad();

  if ( gorgon.timer != undefined )
  {
    timer = gorgon.timer;
  }
  else
  {
    timer = 15000;
  }

  timerID = setInterval('timelineDifferenceLoad()', timer);
  if ( gorgon.notify !== undefined )
  {
    $('#timeline-desktopify').desktopify({
      unsupported : function(){
        $('#timeline-desktopify').hide();
      }
    }).trigger('click');
  }

  $('#timeline-submit-button').click( function() {
    $(this).attr('disabled', 'disabled');
    $('#timeline-submit-error').empty();
    $('#timeline-submit-error').hide();
    $('#timeline-submit-loader').show();
    $('#photo-file-name').empty();
    $('#photo-remove').hide();

    var body = $('#timeline-textarea').val();
    body = body.replace(/"/g, '"')

    if (gorgon)
    {
      var publicFlag = 1;
      if ('community' != gorgon.target)
      {
        publicFlag = $('#timeline-public-flag option:selected').val()
      }

      var data = {
        body: body,
        target: gorgon.post.foreign,
        target_id: gorgon.post.foreignId,
        apiKey: openpne.apiKey,
        public_flag: publicFlag
      };
    }
    else
    {
      var data = {
        body: body,
        apiKey: openpne.apiKey
      };
    }

    tweetByData(data);
  });

  $('#timeline-loadmore').click( function() {
    $('#timeline-loadmore').hide();
    $('#timeline-loadmore-loading').show();
    timelineLoadmore();
  });

  $('.timeline-comment-loadmore').live('click', function() {
    var timelineId = $(this).attr('data-timeline-id');
    var commentlist = $('#commentlist-' + timelineId);
    var commentLength = commentlist.children('.timeline-post-comment').length;
    $('#timeline-comment-loader-' + timelineId).show();

    $.ajax({
      type: 'GET',
      url: openpne.apiBase + 'activity/commentSearch.json?apiKey=' + openpne.apiKey,
      data: {
        'timeline_id': timelineId,
        'count': commentLength + 20
      },
      success: function(json){
        commentlist.children().remove();
        $('#timelineCommentTemplate').tmpl(json.data.reverse()).prependTo(commentlist);
        $('#timeline-comment-loader-' + timelineId).hide();

        if (json.data.length < commentLength + 20)
        {
          $('#timeline-comment-loadmore-' + timelineId).hide();
        }
      },
      error: function(XMLHttpRequest, textStatus, errorThrown){
        $(commentlist).hide();
      }
    });
  });

  $('#timeline-submit-upload').change(function() {
    var fileName = $('#timeline-submit-upload').val();
    $('#photo-remove').show();
    if (20 > fileName.length)
    {
      $('#photo-file-name').text(fileName);
    }
    else
    {
      $('#photo-file-name').text(fileName.substring(0, 19) + '…');
    }
  });

  $('#timeline-upload-photo-button').click(function() {
    $('#timeline-submit-upload').click();

  });

  $('#timeline-submit-upload').change(function() {
    if ($.browser.msie)
    {
      return;
    }

    $('#timeline-submit-error').hide();
    $('#timeline-submit-error').empty();

    var size = this.files[0].size;

    if (size >= fileMaxSizeInfo['size']) {
      $('#timeline-submit-error').show();

      var errorMessage = 'ファイルは' + fileMaxSizeInfo['format'] + '以上はアップロードできません';
      $('#timeline-submit-error').text(errorMessage);

      $('#timeline-submit-upload').empty();
      $('#timeline-submit-upload').val('');
      $('#photo-file-name').empty();
    }
  });

  $('#timeline-textarea').keyup( function() {
    lengthCheck($(this), $('#timeline-submit-button'));
  });

  $('.timeline-post-comment-form-input').live('keyup', function() {
    lengthCheck($(this), $('button[data-timeline-id=' + $(this).attr('data-timeline-id') + ']'));
  });

  $('#photo-remove').click( function() {
    $('#timeline-submit-upload').val('');
    $('#photo-file-name').empty();
    $(this).hide();
  });
});

function timelineAllLoad() {

  if (gorgon)
  {
    gorgon.apiKey = openpne.apiKey;
    delete gorgon.max_id;
    $.ajax({
      type: 'GET',
      url: openpne.apiBase + 'activity/search.json',
      data: gorgon,
      success: function(response){

        if ($.isEmptyObject(response.data))
        {
          $('#timeline-loading').hide();
          $('#timeline-list').text('タイムラインは投稿されていません。');
          $('#timeline-list').show();
        }
        else
        {
          renderJSON(response, 'all');
        }

      },
      error: function(XMLHttpRequest, textStatus, errorThrown){
        $('#timeline-loading').hide();
        $('#timeline-list').text('タイムラインは投稿されていません。');
        $('#timeline-list').show();
      }
    });
  }
  else
  {
    $.ajax({
      type: 'GET',
      url: openpne.apiBase + 'activity/search.json?apiKey=' + openpne.apiKey,
      success: function(response){

        if ($.isEmptyObject(response.data))
        {
          $('#timeline-loading').hide();
          $('#timeline-list').text('タイムラインは投稿されていません。');
          $('#timeline-list').show();
        }
        else
        {
          renderJSON(response, 'all');
        }

      },
      error: function(XMLHttpRequest, textStatus, errorThrown){
        $('#timeline-loading').hide();
        $('#timeline-list').text('タイムラインは投稿されていません。');
        $('#timeline-list').show();
      }
    });
  }
}

function timelineDifferenceLoad() {
  var lastId = $('#timeline-list').attr('data-last-id');

  if (gorgon)
  {
    gorgon.apiKey = openpne.apiKey;
  }
  else
  {
    gorgon = {
      apiKey: openpne.apiKey
    }
  }
  $.getJSON( openpne.apiBase + 'activity/search.json?count=20&since_id=' + lastId, gorgon, function(json){
    if (json.data)
    {
      renderJSON(json, 'diff');
    }
  });
}

function timelineLoadmore() {
  var loadmoreId = $('#timeline-list').attr('data-loadmore-id');
  loadmoreId = loadmoreId - 1;
  if (gorgon)
  {
    gorgon.apiKey = openpne.apiKey;
  }
  else
  {
    gorgon = {
      apiKey: openpne.apiKey
    }
  }
  gorgon.max_id = loadmoreId;

  $.ajax({
    type: 'GET',
    url: openpne.apiBase + 'activity/search.json',
    data: gorgon,
    success: function(json){
      renderJSON(json, 'more');
    },
    error: function(XMLHttpRequest, textStatus, errorThrown){
      $('#timeline-loadmore-loading').hide();
    }
  });
}

function renderJSON(json, mode) {
  if (undefined == mode)
  {
    mode = 'all';
  }
  if ('all' == mode)
  {
    $('#timeline-list').empty();
  }
  if(json.data && 0 < viewPhoto)
  {
    autoLinker(json);
  }

  $timelineData = $('#timelineTemplate').tmpl(json.data);
  $('.timeline-comment-button', $timelineData).timelineComment();
  $('.timeline-comment-link', $timelineData).click(function(){
    $commentBoxArea = $(this).parent().find('.timeline-post-comment-form');
    $commentBoxArea.show();
    $commentBoxArea.children('.timeline-post-comment-form-input').focus();
  });
  if ('diff' == mode)
  {
    $timelineData.prependTo('#timeline-list');
  }
  else
  {
    $timelineData.appendTo('#timeline-list');
  }
  if ('all' == mode || 'diff' == mode)
  {
    if(json.data[0])
    {
      $('#timeline-list').attr('data-last-id', json.data[0].id);
    }
  }
  if ('all' == mode || 'more' == mode)
  {
    var max = json.data.length - 1;
    if (json.data[max])
    {
      $('#timeline-list').attr('data-loadmore-id', json.data[max].id);
    }
  }
  if(json.data)
  {
    for(i=0;i<json.data.length;i++)
    {
      if(json.data[i].replies)
      {
        $('#timelineCommentTemplate').tmpl(json.data[i].replies.reverse()).prependTo('#commentlist-' +json.data[i].id);
        $('#timeline-post-comment-form-' + json.data[i].id, $timelineData).show();
      }
      if(10 < parseInt(json.data[i].replies_count))
      {
        $('#timeline-comment-loadmore-' + json.data[i].id).show();
      }
    }
  }
  $('button.timeline-post-delete-button').timelineDelete();
  $('.timeline-post-delete-confirm-link').colorbox({
    inline: true,
    width: '610px',
    opacity: '0.8',
    onOpen: function(){
      $($(this).attr('href')).show();
    },
    onCleanup: function(){
      $($(this).attr('href')).hide();
    },
    onClosed: function(){
      timelineAllLoad();
    }
  });
  if ('all' == mode)
  {
    $('#timeline-loading').hide();
  }
  if ('more' == mode)
  {
    $('#timeline-loadmore').show();
    $('#timeline-loadmore-loading').hide();
  }
  $('.timeago').timeago();
}

function convertTag(str) {
  str = str.replace(/&/g,'&');
  str = str.replace(/"/g,'"');
  str = str.replace(/'/g,''');
  str = str.replace(/</g,'<');
  str = str.replace(/>/g,'>');
  return str;
}

function tweetByData(data)
{
  //reference　http://lagoscript.org/jquery/upload/documentation
  $('#timeline-submit-upload').upload(
    openpne.apiBase + 'activity/post.json', data,
    function (res) {
      var resCheck = responceCheck(res);
      if (false !== resCheck)
      {
        $('#timeline-submit-error').text(resCheck);
        $('#timeline-submit-error').show();
        $('#timeline-submit-loader').hide();
        return;
      }

      res = res.replace(/,\"body.*\"/g, '');
      returnData = JSON.parse(res);

      if (returnData.status === "error") {

        var errorMessages = {
          file_size: 'ファイルサイズは' + fileMaxSizeInfo['size'] + 'までです',
          upload: 'アップロードに失敗しました',
          not_image: '画像をアップロードしてください',
          tweet: '投稿に失敗しました'
        };

        var errorType = returnData.type;

        $('#timeline-submit-error').text(errorMessages[errorType]);
        if ($.browser.msie && $.browser.version > 6)
        {
        }
        $('#timeline-submit-error').show();
        $('#timeline-submit-loader').hide();

      } else {
        $('#timeline-submit-error').empty();
        timelineAllLoad();
      }

      $('#timeline-submit-upload').val('');
      $('#timeline-submit-upload').empty();
      $('#timeline-textarea').val('');
      $('#timeline-submit-loader').hide();
      $('#counter').text(MAXLENGTH);

    },
    'text' //なぜかJSON形式でうけとることができなかった
    );
}

function autoLinker(json)
{
  for(i=0;i<json.data.length;i++)
  {
    if (!json.data[i].body_html.match(/img.*src=/))
    {
      if (json.data[i].body.match(/\.(jpg|jpeg|png|gif)/))
      {
        json.data[i].body_html = json.data[i].body.replace(/((http:|https:)\/\/[\x21-\x26\x28-\x7e]+.(jpg|jpeg|png|gif))/gi, '

');
      }
      else if (json.data[i].body.match(/((http:|https:)\/\/www\.youtube\.com\/watch\?v=([a-zA-Z0-9_\-]+))/))
      {
        var youtubeId = json.data[i].body.substring(json.data[i].body.lastIndexOf('v=') + 2, json.data[i].body.length);
        var iframe = '';
        json.data[i].body_html = json.data[i].body.replace(/((http:|https:)\/\/www\.youtube\.com\/watch\?v=([a-zA-Z0-9_\-]+))/gi, '
' + iframe + '
');
      }
      else if (json.data[i].body.match(/((http:|https:)\/\/www\.amazon\..*\/([a-zA-Z0-9_\-]+)\/.*)/))
      {
        var match_id = json.data[i].body.match(/(?:ASIN|product|dp)\/([^\/]+)/i);
        if (match_id) {
          id = RegExp.$1;
        }
        var url = 'http://amazon.openpne.jp/?id=' + id + '&tag=';
        json.data[i].body_html = json.data[i].body.replace(/((http:|https:)\/\/www\.amazon\..*\/([a-zA-Z0-9_\-]+)\/.*)/, '
この部分はインラインフレームを使用しています。
');
      }
      else if (json.data[i].body.match(/((http:|https:)\/\/[\x21-\x26\x28-\x7e]+)/))
      {
        json.data[i].body_html = json.data[i].body.replace(/((http:|https:)\/\/[\x21-\x26\x28-\x7e]+)/gi, '

$1
');
      }
    }
    json.data[i].body_html = json.data[i].body_html.replace(/<br \/>/g, '
');
  }
}

function lengthCheck(obj, target)
{
  if (0 < $.trim(obj.val()).length && 140 >= obj.val().length)
  {
    target.removeAttr('disabled');
  }
  else
  {
    target.attr('disabled', 'disabled');
  }
}

function responceCheck(res)
{
  if (0 <= res.indexOf('\<pre'))
  {
    return 'エラーが発生しました。再度読み込んで下さい。';
  }
  return false;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2013 salesforce.com, inc.
 *
 * 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
 * distributed 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 the specific language governing permissions and
 * limitations under the License.
 */
({
    PILLS: [
        {id:'pill01',label:"Test Pill 01",icon: {url:'https://ipsumimage.appspot.com/20x20,8888ff?l=1&f=FFFFFF'}},
        {id:'pill02',label:"Test Pill 02",icon: {url:'https://ipsumimage.appspot.com/20x20,ff88cc?l=2&f=FFFFFF'}},
        {id:'pill03',label:"Test Pill 03",icon: {url:'https://ipsumimage.appspot.com/20x20,88cc88?l=3&f=FFFFFF'}}],
    PILLS_CASEINSENSITIVE: [{id:'pill01',label:"TEST PILL 01"},{id:'pill02',label:"TEST PILL 02"},{id:'pill03',label:"Test PILL 03"}],
    PILLS_WITHLONGLENGTH: [
                           {id:'pill01',label:"Pills can be used to provide text for categories or tags, and provide text selection in an auto-complete field",icon: {url:'https://ipsumimage.appspot.com/20x20,8888ff?l=1&f=FFFFFF'}}],

    browsers: ["GOOGLECHROME", "IPHONE", "IPAD", "FIREFOX", "IE9", "IE10", "SAFARI", "ANDROID_PHONE", "ANDROID_TABLET"],
    doNotWrapInAuraRun: true,

    testBlurEventBubble: {
        test: function (cmp) {
            var pillContainer = cmp.find("pillContainer");
            cmp.find("autocomplete").focus();
            var result = cmp.find("event");
            cmp.getElement().getElementsByTagName("input")[0].blur();
            $A.test.addWaitForWithFailureMessage(true, function() {
                return "blur" === result.get("v.value");
            },"blur event didn't bubble");
        }
    },

    testInsertEventBubble: {
        test: function (cmp) {
            var pillContainer = cmp.find("pillContainer");
            pillContainer.insertItems( [this.PILLS[0]] );
            $A.test.assertEquals("pillInserted",cmp.find("event").get("v.value"),"insert event didn't bubble");
        }
    },

    testRemoveEventBubble: {
        test: function (cmp) {
            var pillContainer = cmp.find("pillContainer");
            pillContainer.insertItems( [this.PILLS[0]] );
            pillContainer.find("pill").getElement().getElementsByClassName("deleteIcon")[0].click();
            var that = this;
            $A.test.addWaitForWithFailureMessage(true, function() {
                return cmp.find("event").get("v.value") === "pillRemoved";
            }, "remove event didn't bubble");
        }
    },

    testPillFocusBubble: {
        test: function (cmp) {
            var pillContainer = cmp.find("pillContainer");
            pillContainer.insertItems( [this.PILLS[0]] );
            var pill = pillContainer.find("pill");
            pill.focus()
            $A.test.addWaitForWithFailureMessage(true, function() {
                return "focus" === cmp.find("event").get("v.value");
            },"focus event didn't bubble");
            $A.test.addWaitForWithFailureMessage(true, function() {
                return "ui$pillContainer" === cmp.find("component").get("v.value");
            },"focus event was not from pillContainer");
        }
    },

    testPillBlurBubble: {
        test: function (cmp) {
            var pillContainer = cmp.find("pillContainer");
            pillContainer.insertItems( [this.PILLS[0]] );
            var pill = pillContainer.find("pill");
            pill.focus();
            cmp.find("event").focus();
            $A.test.addWaitForWithFailureMessage(true, function() {
                return "blur" === cmp.find("event").get("v.value");
            },"blur event didn't bubble");
            $A.test.addWaitForWithFailureMessage(true, function() {
                return "ui$pillContainer" === cmp.find("component").get("v.value");
            },"blur event was not from pillContainer");
        }
    },

    _validateIconURLIsPresent: function(cmp, expectedPillsCount) {
    	var that = this;
    	var pillIcons = $A.test.select(".pillIcon");
    	for (i = 0; i < expectedPillsCount; i++) {
    		var expectedURL = that.PILLS[i].icon.url;
    		$A.test.assertEquals(expectedURL,$A.test.getElementAttributeValue(pillIcons[i], "src"),"Icon Url for pill " + i + " is not correct");
    	}
    },

    _initializeWithTwoPills: function (cmp) {
        var pillContainer = cmp.find("pillContainer");
        pillContainer.insertItems([this.PILLS[0],this.PILLS[1]]);
        return pillContainer;
    },

    _initializeWithThreePills: function (cmp) {
        var pillContainer = this._initializeWithTwoPills(cmp);
        pillContainer.insertItems([this.PILLS[2]]);
        return pillContainer;
    },

    _validateTitlePresentInPill: function(pill, isTitlePresent, label){
    	var pillTitle = $A.test.getElementAttributeValue(pill,"title")
    	if(!isTitlePresent){
    		$A.test.assertFalsy(pillTitle,"Title attribute should not be present on the pill")
    	}
    	else{
    		$A.test.assertTruthy(pillTitle,"Title attribute should be present on the pill")
        	$A.test.assertEquals(label, pillTitle, "Title attribute set is incorrect");
    		var pillTextElement = $A.test.select(".pillText")[0];
    		$A.test.assertTrue(pillTextElement.offsetWidth < pillTextElement.scrollWidth, "Pill text should be truncated");
    	}
    }
})<commit_msg>Pills test fix - focus and blur Changing the way the test sets focus and blurs on the pills @rev ctatlah@ @bug W-2926403@<commit_after>/*
 * Copyright (C) 2013 salesforce.com, inc.
 *
 * 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
 * distributed 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 the specific language governing permissions and
 * limitations under the License.
 */
({
    PILLS: [
        {id:'pill01',label:"Test Pill 01",icon: {url:'https://ipsumimage.appspot.com/20x20,8888ff?l=1&f=FFFFFF'}},
        {id:'pill02',label:"Test Pill 02",icon: {url:'https://ipsumimage.appspot.com/20x20,ff88cc?l=2&f=FFFFFF'}},
        {id:'pill03',label:"Test Pill 03",icon: {url:'https://ipsumimage.appspot.com/20x20,88cc88?l=3&f=FFFFFF'}}],
    PILLS_CASEINSENSITIVE: [{id:'pill01',label:"TEST PILL 01"},{id:'pill02',label:"TEST PILL 02"},{id:'pill03',label:"Test PILL 03"}],
    PILLS_WITHLONGLENGTH: [
                           {id:'pill01',label:"Pills can be used to provide text for categories or tags, and provide text selection in an auto-complete field",icon: {url:'https://ipsumimage.appspot.com/20x20,8888ff?l=1&f=FFFFFF'}}],

    browsers: ["GOOGLECHROME", "IPHONE", "IPAD", "FIREFOX", "IE9", "IE10", "SAFARI", "ANDROID_PHONE", "ANDROID_TABLET"],
    doNotWrapInAuraRun: true,

    testBlurEventBubble: {
        test: function (cmp) {
            var pillContainer = cmp.find("pillContainer");
            cmp.find("autocomplete").get('e.focus').fire();
            var result = cmp.find("event");
            cmp.find("autocomplete").get('e.blur').fire();
            $A.test.addWaitForWithFailureMessage(true, function() {
                return "blur" === result.get("v.value");
            },"blur event didn't bubble");
        }
    },

    testInsertEventBubble: {
        test: function (cmp) {
            var pillContainer = cmp.find("pillContainer");
            pillContainer.insertItems( [this.PILLS[0]] );
            $A.test.assertEquals("pillInserted",cmp.find("event").get("v.value"),"insert event didn't bubble");
        }
    },

    testRemoveEventBubble: {
        test: function (cmp) {
            var pillContainer = cmp.find("pillContainer");
            pillContainer.insertItems( [this.PILLS[0]] );
            pillContainer.find("pill").getElement().getElementsByClassName("deleteIcon")[0].click();
            var that = this;
            $A.test.addWaitForWithFailureMessage(true, function() {
                return cmp.find("event").get("v.value") === "pillRemoved";
            }, "remove event didn't bubble");
        }
    },

    testPillFocusBubble: {
        test: function (cmp) {
            var pillContainer = cmp.find("pillContainer");
            pillContainer.insertItems( [this.PILLS[0]] );
            var pill = pillContainer.find("pill");
            pill.get('e.focus').fire();
            $A.test.addWaitForWithFailureMessage(true, function() {
                return "focus" === cmp.find("event").get("v.value");
            },"focus event didn't bubble");
            $A.test.addWaitForWithFailureMessage(true, function() {
                return "ui$pillContainer" === cmp.find("component").get("v.value");
            },"focus event was not from pillContainer");
        }
    },

    testPillBlurBubble: {
        test: function (cmp) {
            var pillContainer = cmp.find("pillContainer");
            pillContainer.insertItems( [this.PILLS[0]] );
            var pill = pillContainer.find("pill");
            pill.get('e.focus').fire();
            pill.get('e.blur').fire();
            $A.test.addWaitForWithFailureMessage(true, function() {
                return "blur" === cmp.find("event").get("v.value");
            },"blur event didn't bubble");
            $A.test.addWaitForWithFailureMessage(true, function() {
                return "ui$pillContainer" === cmp.find("component").get("v.value");
            },"blur event was not from pillContainer");
        }
    },

    _validateIconURLIsPresent: function(cmp, expectedPillsCount) {
    	var that = this;
    	var pillIcons = $A.test.select(".pillIcon");
    	for (i = 0; i < expectedPillsCount; i++) {
    		var expectedURL = that.PILLS[i].icon.url;
    		$A.test.assertEquals(expectedURL,$A.test.getElementAttributeValue(pillIcons[i], "src"),"Icon Url for pill " + i + " is not correct");
    	}
    },

    _initializeWithTwoPills: function (cmp) {
        var pillContainer = cmp.find("pillContainer");
        pillContainer.insertItems([this.PILLS[0],this.PILLS[1]]);
        return pillContainer;
    },

    _initializeWithThreePills: function (cmp) {
        var pillContainer = this._initializeWithTwoPills(cmp);
        pillContainer.insertItems([this.PILLS[2]]);
        return pillContainer;
    },

    _validateTitlePresentInPill: function(pill, isTitlePresent, label){
    	var pillTitle = $A.test.getElementAttributeValue(pill,"title")
    	if(!isTitlePresent){
    		$A.test.assertFalsy(pillTitle,"Title attribute should not be present on the pill")
    	}
    	else{
    		$A.test.assertTruthy(pillTitle,"Title attribute should be present on the pill")
        	$A.test.assertEquals(label, pillTitle, "Title attribute set is incorrect");
    		var pillTextElement = $A.test.select(".pillText")[0];
    		$A.test.assertTrue(pillTextElement.offsetWidth < pillTextElement.scrollWidth, "Pill text should be truncated");
    	}
    }
})<|endoftext|>


<commit_before>import { module, test } from 'qunit';
import { setupApplicationTest } from 'ember-qunit';
import { visit, currentURL } from '@ember/test-helpers';
import Fixtures from '@cardstack/test-support/fixtures';

module('Acceptance | show post', function(hooks) {
  setupApplicationTest(hooks);

  let scenario = new Fixtures({
    create(factory) {
      factory.addResource('content-types', 'posts')
        .withRelated('fields', [
          factory.addResource('fields', 'title').withAttributes({
            fieldType: '@cardstack/core-types::string'
          })
        ]);
      factory.addResource('posts', '1')
        .withAttributes({
          title: 'hello world'
        });
      factory.addResource('grants', 'wide-open')
        .withAttributes({
          mayWriteFields: true,
          mayReadFields: true,
          mayCreateResource: true,
          mayReadResource: true,
          mayUpdateResource: true,
          mayDeleteResource: true
        })
        .withRelated('who', [{ type: 'groups', id: 'everyone' }]);
    },

    destroy() {
      return [{ type: 'posts' }];
    }
  });

  scenario.setupTest(hooks);

  hooks.beforeEach(async function() {
    await this.owner.lookup('service:cardstack-codegen').refreshCode();
  });

  test('visiting /show-post', async function(assert) {
    await visit('/posts/1');
    assert.equal(currentURL(), '/posts/1');
    assert.equal(this.element.querySelector('h1').textContent.trim(), 'hello world');
  });
});
<commit_msg>run codemods on models<commit_after>import { module, test } from 'qunit';
import { setupApplicationTest } from 'ember-qunit';
import { visit, currentURL } from '@ember/test-helpers';
import Fixtures from '@cardstack/test-support/fixtures';

module('Acceptance | show post', function(hooks) {
  setupApplicationTest(hooks);

  let scenario = new Fixtures({
    create(factory) {
      factory.addResource('content-types', 'posts')
        .withRelated('fields', [
          factory.addResource('fields', 'title').withAttributes({
            fieldType: '@cardstack/core-types::string'
          })
        ]);
      factory.addResource('posts', '1')
        .withAttributes({
          title: 'hello world'
        });
      factory.addResource('grants', 'wide-open')
        .withAttributes({
          mayWriteFields: true,
          mayReadFields: true,
          mayCreateResource: true,
          mayReadResource: true,
          mayUpdateResource: true,
          mayDeleteResource: true
        })
        .withRelated('who', [{ type: 'groups', id: 'everyone' }]);
    },

    destroy() {
      return [{ type: 'posts' }];
    }
  });

  scenario.setupTest(hooks);

  hooks.beforeEach(async function() {
    await this.owner.lookup('service:cardstack-codegen').refreshCode();
  });

  test('visiting /show-post', async function(assert) {
    await visit('/posts/1');
    assert.equal(currentURL(), '/posts/1');
    assert.dom(this.element.querySelector('h1')).hasText('hello world');
  });
});
<|endoftext|>


<commit_before>'use babel'

import {CompositeDisposable} from 'atom'
import {LinterUI} from './ui'

export default {
  config: {
    showPanel: {
      type: 'boolean',
      description: 'Show panel on the bottom',
      default: true
    },
    showIssuesFromAllFiles: {
      title: 'Show issues from all files',
      description: 'Display all of the issues in bottom panel instead of only current file ones',
      type: 'boolean',
      default: false
    },
    gutterEnabled: {
      title: 'Highlight Error Lines in Gutter',
      type: 'boolean',
      default: true
    },
    gutterPosition: {
      title: 'Position of Gutter Highlights',
      description: 'Relative to line number gutter',
      type: 'string',
      enum: ['Left', 'Right'],
      default: 'Right'
    },
    underlineIssues: {
      title: 'Underline issues',
      type: 'boolean',
      default: true
    }
  },
  activate: function() {
    this.ui = new LinterUI()
    this.subscriptions = new CompositeDisposable(this.ui)
  },
  deactivate: function() {
    this.subscriptions.dispose()
  },
  provideUI: function() {
    return this.ui
  }
}
<commit_msg>:art: Minor code nit<commit_after>'use babel'

import {CompositeDisposable} from 'atom'
import {LinterUI} from './ui'

export default {
  config: {
    showPanel: {
      type: 'boolean',
      description: 'Show panel on the bottom',
      default: true
    },
    showIssuesFromAllFiles: {
      title: 'Show issues from all files',
      description: 'Display all of the issues in bottom panel instead of only current file ones',
      type: 'boolean',
      default: false
    },
    gutterEnabled: {
      title: 'Highlight Error Lines in Gutter',
      type: 'boolean',
      default: true
    },
    gutterPosition: {
      title: 'Position of Gutter Highlights',
      description: 'Relative to line number gutter',
      type: 'string',
      enum: ['Left', 'Right'],
      default: 'Right'
    },
    underlineIssues: {
      title: 'Underline issues',
      type: 'boolean',
      default: true
    }
  },
  activate: function() {
    this.ui = new LinterUI()
    this.subscriptions = new CompositeDisposable()

    this.subscriptions.add(this.ui)
  },
  deactivate: function() {
    this.subscriptions.dispose()
  },
  provideUI: function() {
    return this.ui
  }
}
<|endoftext|>


<commit_before>'use strict';

define(['angular'], function(angular) {

  var app = angular.module('portal.widgets.services', []);

  app.factory('widgetService', ['$http', '$log', 'SERVICE_LOC', function($http, $log, SERVICE_LOC) {

    /**
     * Get the a single app's full entity file as JSON
     * @param fname The app's fname value (<fname> in entity files)
     * @returns {*}
     */
    var getSingleWidgetData = function getSingleWidgetData(fname) {
      return $http.get(SERVICE_LOC.widgetApi.entry + fname + '.json')
        .then(function(result) {
          if (result.data.entry.layoutObject != undefined) {
            return result.data.entry.layoutObject;
          }
        })
        .catch(function(error) {
          $log.warn('Error getting marketplace entry for ' + fname);
          $log.error(error);
        });
    };

    /**
     * Get additional values/configuration not provided by the widget's basic configuration.
     * Used by Option Link and Custom widgets
     * @param widget
     * @returns {*}
     */
    var getWidgetJson = function(widget) {
      return $http.get(widget.widgetURL, {cache: true})
        .then(function(result) {
          var data = result.data;
          // Consider refactoring to only pull in widgetUrl and only return the raw result -- sorting what to do with
          // the result should be the controller's responsibility
          if (data) {
            if (data.result) {
              widget.widgetData = data.result;
            }
            if (data.content) {
              widget.widgetContent = data.content;
            }
          }
          return data;
        })
        .catch(function(error) {
          $log.error(error);
        })
    };

    /**
     * Get an RSS feed from the provided url as json
     * @param url
     * @returns {*}
     */
    var getRssAsJson = function(url) {
      return $http.get(url, {cache: true})
        .then(function(result) {
          return result.data;
        })
        .catch(function(error) {
          $log.error('Couldn\'t get rss as JSON: ' + error);
        })
    };

    return {
      getSingleWidgetData: getSingleWidgetData,
      getWidgetJson: getWidgetJson,
      getRssAsJson: getRssAsJson
    }

  }]);

  return app;

});
<commit_msg>Adds Error message to unauthorized widget.<commit_after>'use strict';

define(['angular'], function(angular) {

  var app = angular.module('portal.widgets.services', []);

  app.factory('widgetService', ['$http', '$log', 'SERVICE_LOC', function($http, $log, SERVICE_LOC) {

    /**
     * Get the a single app's full entity file as JSON
     * @param fname The app's fname value (<fname> in entity files)
     * @returns {*}
     */
    var getSingleWidgetData = function getSingleWidgetData(fname) {
      return $http.get(SERVICE_LOC.widgetApi.entry + fname + '.json')
        .then(function(result) {
          if (result.data.entry.layoutObject != undefined) {
            return result.data.entry.layoutObject;
          }
        })
        .catch(function(error) {
          return getErrorPage(fname);
          $log.warn('Error getting marketplace entry for ' + fname);
          $log.error(error);
        });
    };

    var getErrorPage = function(fname) {
      var layoutObject={title:fname,
        mdIcon:"md-help", widgetType: "generic",
      widgetConfig:{additionalText: "Please contact your help desk if you feel you should be able to access this content"},
        widgetTemplate:"You do not have permission to access this content. If you feel this is an error, please contact your help desk."}
      return layoutObject;
    }

    /**
     * Get additional values/configuration not provided by the widget's basic configuration.
     * Used by Option Link and Custom widgets
     * @param widget
     * @returns {*}
     */
    var getWidgetJson = function(widget) {
      return $http.get(widget.widgetURL, {cache: true})
        .then(function(result) {
          var data = result.data;
          // Consider refactoring to only pull in widgetUrl and only return the raw result -- sorting what to do with
          // the result should be the controller's responsibility
          if (data) {
            if (data.result) {
              widget.widgetData = data.result;
            }
            if (data.content) {
              widget.widgetContent = data.content;
            }
          }
          return data;
        })
        .catch(function(error) {
          $log.error(error);
        })
    };

    /**
     * Get an RSS feed from the provided url as json
     * @param url
     * @returns {*}
     */
    var getRssAsJson = function(url) {
      return $http.get(url, {cache: true})
        .then(function(result) {
          return result.data;
        })
        .catch(function(error) {
          $log.error('Couldn\'t get rss as JSON: ' + error);
        })
    };

    return {
      getSingleWidgetData: getSingleWidgetData,
      getWidgetJson: getWidgetJson,
      getRssAsJson: getRssAsJson,
      getErrorPage: getErrorPage
    }

  }]);

  return app;

});
<|endoftext|>


<commit_before>jQuery(document).ready(function($) {

  // Email (mailto:) link click
  var anaylticsMailto = function(email) {
    ga('send', {
      hitType: 'event',
      eventCategory: 'Score',
      eventLabel: 'Email',
      eventAction: email,
      eventValue: 5
    });
  }
  $('a[href^="mailto:"]').bind('click', function(e){
    anaylticsMailto($(this).attr('href').replace('mailto:', ''));
  });

  // Phone number (tel:) link click
  var anaylticsPhone = function(phone) {
    ga('send', {
      hitType: 'event',
      eventCategory: 'Score',
      eventLabel: 'Phone',
      eventAction: phone,
      eventValue: 10
    });
  }
  $('a[href^="tel:"]').bind('click', function(e){
    anaylticsPhone($(this).attr('href').replace('tel:', ''));
  });

  // Widget click
  var anaylticsWidgetClick = function(e) {
    var activeClass = 'btn-primary';
    e.preventDefault();
    var title = $(this).attr('data-title') ? $(this).attr('data-title') : $('h1.entry-title').length ? $('h1.entry-title').text() : document.title;
    ga('send', {
      hitType: 'event',
      eventCategory: 'Score',
      eventLabel: 'Heart',
      eventAction: window.location.href,
      eventValue: jQuery(this).hasClass(activeClass) ? -5 : +5
    });

    if (!$(this).hasClass(activeClass)) {
      ga('send', {
        hitType: 'event',
        eventCategory: 'Heart',
        eventLabel: title,
        eventAction: window.location.href,
        eventValue: 1
      });
    }

    $(this).toggleClass(activeClass);
  }
  $('.proudscore-widget').bind('click', anaylticsWidgetClick);

  // Gravity form submission
  var submittedBy;
  var anaylticsSubmission = function(title, action) {
    action = window.location.protocol + '//' + window.location.host + action;
    ga('send', {
      hitType: 'event',
      eventCategory: 'Submission',
      eventLabel: title,
      eventAction: action,
      eventValue: 1
    });
    ga('send', {
      hitType: 'event',
      eventCategory: 'Score',
      eventLabel: 'Submission',
      eventAction: action,
      eventValue: 5
    });
  }
  $('.gform_wrapper form').once('proud-analytics', function() {
    var $self = $(this);
    // Process buttons to deal with multistep forms
    $.each($self.find('input[type="button"]'), function(key, button) {
      $(button).bind('click', function(e) {
        submittedBy = this.value;
      });
    });
    $self.bind('submit', function(e){
      // Allow bound click to complete
      setTimeout(function() {
        if(submittedBy !== 'Next' && submittedBy !== 'Previous') {
          anaylticsSubmission($self.attr('id'), $self.attr('action'));
        }
      }, 0);
    });
  });
  // Emitted by Gravity Forms
  // Documentation: https://www.gravityhelp.com/documentation/article/gform_confirmation_loaded/#source-code
  $(document).bind('gform_confirmation_loaded', function(event, formId){
    anaylticsSubmission('gform_' + formId);
  });

  // Social clicks
  var analyticsSocialClick = function(e) {
    if(e.target.href) {
      var label;
      if(e.target.href.match(/facebook\.com/i)) {
        label = 'Facebook';
      }
      else if(e.target.href.match(/twitter\.com/i)) {
        label = 'Twitter';
      }
      else if(e.target.href.match(/mailto\:/i)) {
        label = 'Email';
      }
      if(label) {
        ga('send', {
          hitType: 'event',
          eventCategory: 'Share',
          eventLabel: label,
          eventAction: window.location.protocol + '//' + window.location.hostname + window.location.pathname,
        });
      }
      ga('send', {
        hitType: 'event',
        eventCategory: 'Score',
        eventLabel: 'Share',
        eventAction: window.location.protocol + '//' + window.location.hostname + window.location.pathname,
        eventValue: 5
      });
    }
  }
  $('.share-dropdown ~ ul.dropdown-menu a').once('social-ga', function() {
    $(this).bind('click', analyticsSocialClick);
  });

  // AddToCalendar click
  var anaylticsCalendarShare = function(title, slug) {
    ga('send', {
      hitType: 'event',
      eventCategory: 'AddEvent',
      eventLabel: title,
      eventAction: slug,
      eventValue: 1
    });
    ga('send', {
      hitType: 'event',
      eventCategory: 'Score',
      eventLabel: 'AddEvent',
      eventAction: slug,
      eventValue: 5
    });
  }
  if ($('.addtocalendar').length) {
    setTimeout(function(){
      $('.atcb-item-link').bind('click', function(e){
        var $parent = $(this).parents('.addtocalendar');
        anaylticsCalendarShare($parent.attr('data-title'), $parent.attr('data-slug'));
      });
    }, 1000);
  }

}); //ready

<commit_msg>Embedded forms: ga does not exist  https://github.com/proudcity/wp-proudcity/issues/1084<commit_after>jQuery(document).ready(function($) {

  // Email (mailto:) link click
  var anaylticsMailto = function(email) {
    if (ga === undefined) {
      return;
    }
    ga('send', {
      hitType: 'event',
      eventCategory: 'Score',
      eventLabel: 'Email',
      eventAction: email,
      eventValue: 5
    });
  }
  $('a[href^="mailto:"]').bind('click', function(e){
    anaylticsMailto($(this).attr('href').replace('mailto:', ''));
  });

  // Phone number (tel:) link click
  var anaylticsPhone = function(phone) {
    if (ga === undefined) {
      return;
    }
    ga('send', {
      hitType: 'event',
      eventCategory: 'Score',
      eventLabel: 'Phone',
      eventAction: phone,
      eventValue: 10
    });
  }
  $('a[href^="tel:"]').bind('click', function(e){
    anaylticsPhone($(this).attr('href').replace('tel:', ''));
  });

  // Widget click
  var anaylticsWidgetClick = function(e) {
    if (ga === undefined) {
      return;
    }
    var activeClass = 'btn-primary';
    e.preventDefault();
    var title = $(this).attr('data-title') ? $(this).attr('data-title') : $('h1.entry-title').length ? $('h1.entry-title').text() : document.title;
    ga('send', {
      hitType: 'event',
      eventCategory: 'Score',
      eventLabel: 'Heart',
      eventAction: window.location.href,
      eventValue: jQuery(this).hasClass(activeClass) ? -5 : +5
    });

    if (!$(this).hasClass(activeClass)) {
      if (ga === undefined) {
        return;
      }
      ga('send', {
        hitType: 'event',
        eventCategory: 'Heart',
        eventLabel: title,
        eventAction: window.location.href,
        eventValue: 1
      });
    }

    $(this).toggleClass(activeClass);
  }
  $('.proudscore-widget').bind('click', anaylticsWidgetClick);

  // Gravity form submission
  var submittedBy;
  var anaylticsSubmission = function(title, action) {
    if (ga === undefined) {
      return;
    }
    action = window.location.protocol + '//' + window.location.host + action;
    ga('send', {
      hitType: 'event',
      eventCategory: 'Submission',
      eventLabel: title,
      eventAction: action,
      eventValue: 1
    });
    ga('send', {
      hitType: 'event',
      eventCategory: 'Score',
      eventLabel: 'Submission',
      eventAction: action,
      eventValue: 5
    });
  }
  $('.gform_wrapper form').once('proud-analytics', function() {
    var $self = $(this);
    // Process buttons to deal with multistep forms
    $.each($self.find('input[type="button"]'), function(key, button) {
      $(button).bind('click', function(e) {
        submittedBy = this.value;
      });
    });
    $self.bind('submit', function(e){
      // Allow bound click to complete
      setTimeout(function() {
        if(submittedBy !== 'Next' && submittedBy !== 'Previous') {
          anaylticsSubmission($self.attr('id'), $self.attr('action'));
        }
      }, 0);
    });
  });
  // Emitted by Gravity Forms
  // Documentation: https://www.gravityhelp.com/documentation/article/gform_confirmation_loaded/#source-code
  $(document).bind('gform_confirmation_loaded', function(event, formId){
    anaylticsSubmission('gform_' + formId);
  });

  // Social clicks
  var analyticsSocialClick = function(e) {
    if(e.target.href && ga !== undefined) {
      var label;
      if(e.target.href.match(/facebook\.com/i)) {
        label = 'Facebook';
      }
      else if(e.target.href.match(/twitter\.com/i)) {
        label = 'Twitter';
      }
      else if(e.target.href.match(/mailto\:/i)) {
        label = 'Email';
      }
      if(label) {
        ga('send', {
          hitType: 'event',
          eventCategory: 'Share',
          eventLabel: label,
          eventAction: window.location.protocol + '//' + window.location.hostname + window.location.pathname,
        });
      }
      ga('send', {
        hitType: 'event',
        eventCategory: 'Score',
        eventLabel: 'Share',
        eventAction: window.location.protocol + '//' + window.location.hostname + window.location.pathname,
        eventValue: 5
      });
    }
  }
  $('.share-dropdown ~ ul.dropdown-menu a').once('social-ga', function() {
    $(this).bind('click', analyticsSocialClick);
  });

  // AddToCalendar click
  var anaylticsCalendarShare = function(title, slug) {
    if (ga === undefined) {
      return;
    }
    ga('send', {
      hitType: 'event',
      eventCategory: 'AddEvent',
      eventLabel: title,
      eventAction: slug,
      eventValue: 1
    });
    ga('send', {
      hitType: 'event',
      eventCategory: 'Score',
      eventLabel: 'AddEvent',
      eventAction: slug,
      eventValue: 5
    });
  }
  if ($('.addtocalendar').length) {
    setTimeout(function(){
      $('.atcb-item-link').bind('click', function(e){
        var $parent = $(this).parents('.addtocalendar');
        anaylticsCalendarShare($parent.attr('data-title'), $parent.attr('data-slug'));
      });
    }, 1000);
  }

}); //ready

<|endoftext|>


<commit_before>import Messages from "./messages"
import * as socket from './socket'
import * as cc from "./chat_channel"
import * as utils from './utils'
import sweetAlert from "./sweetalert.min"
import toastr from 'toastr'

const debug = true;
const animation = `<div class="loading-animation"><div class="bounce1"></div><div class="bounce2"></div><div class="bounce3"></div></div>`

class RoomManager {
  constructor() {
    // $('body').off('click', '.mention-link[data-channel]')
    this.register_events()
  }

  render_room(resp) {
    if (debug) { console.log('render_room', resp) }
    $('.room-link').removeClass("active")
    // $('.messages-box').html(resp.box_html)
    // $('.messages-container .fixed-title h2').html(resp.header_html)
    $('.main-content').html(resp.html)
    ucxchat.channel_id = resp.channel_id
    ucxchat.room = resp.room_title
    ucxchat.display_name = resp.display_name
    ucxchat.room_route = resp.room_route
    if (resp.side_nav_html) {
      $('aside .rooms-list').html(resp.side_nav_html)
    }
    $('.room-title').html(ucxchat.display_name)
    $('.link-room-' + ucxchat.room).addClass("active")
    utils.scroll_bottom()
    roomchan.leave()
    socket.restart_socket()
  }
  toggle_favorite() {
    if (debug) { console.log('toggle_favorite') }
    // roomchan.push("room:favorite", {user_id: ucxchat.user_id, channel_id: ucxchat.channel_id})
    cc.put("/room/favorite")
      .receive("ok", resp => {
        $('.messages-container .fixed-title h2').html(resp.messages_html)
        $('aside .rooms-list').html(resp.side_nav_html)
      })
  }
  add_private(elem) {
    let username = elem.parent().attr('data-username')
    if (debug) { console.log('pvt-msg button clicked...', username) }
    // roomchan.push("room:add-direct", {username: username, user_id: ucxchat.user_id, channel_id: ucxchat.channel_id})
    cc.put("direct/" + username)
      .receive("ok", resp => {
        $('.messages-container .fixed-title h2').html(resp.messages_html)
        $('aside .rooms-list').html(resp.side_nav_html)
        ucxchat.channel_id = resp.channel_id
        ucxchat.room = resp.room
        ucxchat.display_name = resp.display_name
        ucxchat.room_route = resp.room_route
        // flex_bar.close_flex_tab()
        if ($('section.flex-tab').parent().hasClass('opened')) {
          $('section.flex-tab').html('').parent().removeClass('opened')
        }
        roomchan.leave()
        socket.restart_socket()
    })
  }
  update(msg) {
    console.log('update...', msg)
    let fname = msg.field_name
    if ( fname == "topic"  || fname == "title") {
      $('.room-' + fname).html(msg.value)
    } else if (fname == "name") {
      $('.room-title').html(msg.value)
      ucxchat.room = msg.value
      ucxchat.display_name = msg.value
      utils.replace_history()
    }

    $('.current-setting[data-edit="' + msg.field_name + '"]').html(msg.value)
    console.warn('RoomManager.update', msg)
  }
  room_mention(resp) {
    let parent = `a.open-room[data-name="${resp.room}"]`
    let elem = $(parent + ' span.unread')
    console.log('room_manager', resp, elem)
    if (elem.length == []) {
      $(parent).prepend(`<span class="unread">${resp.unread}</span>`)
    } else {
      elem.text(resp.unread)
    }
  }

  register_events() {
    $('body').on('click', 'a.open-room', e => {
      e.preventDefault();
      if (debug) { console.log('clicked a.open-room', e, $(e.currentTarget), $(e.currentTarget).attr('data-room')) }
      utils.page_loading()
      $('.main-content').html(utils.loading_animation())
      this.open_room($(e.currentTarget).attr('data-room'), $(e.currentTarget).attr('data-name'))
    })
    .on('click', 'a.toggle-favorite', e => {
      if (debug) { console.log('click a.toggle-favorite') }
      e.preventDefault();
      this.toggle_favorite()
    })
    .on('click', '.button.pvt-msg', e => {
      if (debug) { console.log('click .button.pvt-msg') }
      e.preventDefault();
      this.add_private(e.currentTarget)
    })
    .on('click', 'button.set-owner', e => {
      let username = $(e.currentTarget).parent().attr('data-username')
      e.preventDefault()
      cc.put("/room/set-owner/" + username)
        .receive("ok", resp => {
        })
        .receive("error", resp => {
          toastr.error(resp.error)
        })
    })
    .on('click', 'button.unset-owner', e => {
      let username = $(e.currentTarget).parent().attr('data-username')
      e.preventDefault()
      cc.put("/room/unset-owner/" + username)
        .receive("ok", resp => {
        })
        .receive("error", resp => {
          toastr.error(resp.error)
        })
    })
    .on('click', 'button.set-moderator', e => {
      let username = $(e.currentTarget).parent().attr('data-username')
      e.preventDefault()
      cc.put("/room/set-moderator/" + username)
        .receive("ok", resp => {
          if (resp.redirect) {
            window.location = resp.redirect
          }
        })
        .receive("error", resp => {
          toastr.error(resp.error)
        })
    })
    .on('click', 'button.unset-moderator', e => {
      let username = $(e.currentTarget).parent().attr('data-username')
      e.preventDefault()
      cc.put("/room/unset-moderator/" + username)
        .receive("ok", resp => {
        })
        .receive("error", resp => {
          toastr.error(resp.error)
        })
    })
    .on('click', 'button.unmute-user', e => {
      let username = $(e.currentTarget).parent().attr('data-username')
      e.preventDefault()
      cc.put("/room/unmute-user/" + username)
        .receive("ok", resp => {
        })
        .receive("error", resp => {
          toastr.error(resp.error)
        })
    })
    .on('click', 'button.unblock-user', e => {
      let username = $(e.currentTarget).parent().attr('data-username')
      e.preventDefault()
      cc.put("/room/unblock-user/" + username)
        .receive("ok", resp => {
        })
        .receive("error", resp => {
          toastr.error(resp.error)
        })
    })
    .on('click', 'button.block-user', e => {
      let username = $(e.currentTarget).parent().attr('data-username')
      e.preventDefault()
      cc.put("/room/block-user/" + username)
        .receive("ok", resp => {
        })
        .receive("error", resp => {
          toastr.error(resp.error)
        })
    })
    .on('click', 'button.mute-user', e => {
      let username = $(e.currentTarget).parent().attr('data-username')
      e.preventDefault()
      sweetAlert({
        title: gettext.are_you_sure,
        text: gettext.the_user_wont_able_type + ' ' + ucxchat.room,
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: gettext.yes_mute_user,
        closeOnConfirm: false
      },
      function(){
        cc.put("/room/mute-user/" + username)
          .receive("ok", resp => {
            swal({
                title: gettext.muted,
                text: gettext.the_user_wont_able_type + ' ' + ucxchat.room,
                type: 'success',
                timer: 2000,
                showConfirmButton: false,
            })
          })
          .receive("error", resp => {
            toastr.error(resp.error)
          })
      });
    })
    .on('click', 'button.remove-user', e => {
      let username = $(e.currentTarget).parent().attr('data-username')
      e.preventDefault()
      sweetAlert({
        title: gettext.are_you_sure,
        text: gettext.the_user_will_be_removed_from + ' ' + ucxchat.room,
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Yes, remove user!",
        closeOnConfirm: false
      },
      function(){
        cc.put("/room/remove-user/" + username)
          .receive("ok", resp => {
            swal({
                title: gettext.removed,
                text: gettext.the_user_was_remove_from + ' ' + ucxchat.room,
                type: 'success',
                timer: 2000,
                showConfirmButton: false,
            })
          })
          .receive("error", resp => {
            toastr.error(resp.error)
          })
      });
    })
    .on('click', 'button.join', e => {
      cc.put("/room/join/" + ucxchat.username)
        .receive("ok", resp => {
        })
        .receive("error", resp => {
          toastr.error(resp.error)
        })
    })
    .on('click', 'a.open-room i.hide-room', e => {
      e.preventDefault()
      let room = $(e.currentTarget).closest('.open-room').data('room')
      // console.log('cliecked open-room', room)
      sweetAlert({
        title: gettext.are_you_sure,
        text: gettext.are_you_sure_you_want_to_hide_the_room + ' "' + room + '"?',
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: gettext.yes_hide_it,
        closeOnConfirm: false
      },
      function(){
        cc.put("/room/hide/" + room)
          .receive("ok", resp => {
            if (resp.redirect) {
              window.location = resp.redirect
            }
            // swal({
            //     timer: 1,
            //     showConfirmButton: false,
            // })
          })
          .receive("error", resp => {
            toastr.error(resp.error)
          })
      });
      return false
    })
    .on('click', 'a.open-room i.leave-room', e => {
      e.preventDefault()
      let room = $(e.currentTarget).closest('.open-room').data('room')
      console.log('cliecked leave-room', room)
      sweetAlert({
        title: gettext.are_you_sure,
        text: gettext.are_you_sure_leave_the_room + ' "' + room + '"?',
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: gettext.yes_leave_it,
        closeOnConfirm: false
      },
      function(){
        cc.put("/room/leave/" + room)
          .receive("ok", resp => {
            swal({
                title: gettext.left_the_room,
                text: gettext.you_have_left_the_room + " " + ucxchat.room,
                type: 'success',
                timer: 500,
                showConfirmButton: false,
            })
          })
          .receive("error", resp => {
            toastr.error(resp.error)
          })
      });
      return false
    })
    .on('click', '.mention-link[data-channel]', (e) => {
      e.preventDefault()
      let target = $(e.currentTarget)
      let room = target.data('channel')
      console.log('clicked channel link', room)
      this.open_room(room, room)
      return false
    })
    // .on('scroll', '.messages-box .wrapper', _.throttle(() => {
    $('.messages-box .wrapper').on('scroll', _.throttle((e) => {
      if (utils.is_scroll_bottom()) {
        console.log('scroller scrolling at bottom' )
      } else {
        console.log('scroller keep scrolling ' )
      }
    }, 150))

    $(window).on('focus', () => {
      this.clear_unread()
      console.log('room_manager focus')
    })

  }

  clear_unread() {
    setTimeout(function() {
      let parent = `a.open-room[data-name="${ucxchat.room}"]`
      $(parent + ' span.unread').remove()
    }, 1000)
  }

  open_room(room, display_name, callback) {
    cc.get("/room/" + room, {display_name: display_name, room: ucxchat.room})
      .receive("ok", resp => {
        console.log('open room response', resp)
        if (resp.redirect) {
          window.location = resp.redirect
        } else {
          this.render_room(resp)
        }
        if (callback) { callback() }
        utils.remove_page_loading()
      })
  }
}

export default RoomManager;
<commit_msg>working on go to message and fetching has_more and has_more_next. added throttle to scroll messages<commit_after>import Messages from "./messages"
import * as socket from './socket'
import * as cc from "./chat_channel"
import * as utils from './utils'
import sweetAlert from "./sweetalert.min"
import toastr from 'toastr'

const debug = true;
const animation = `<div class="loading-animation"><div class="bounce1"></div><div class="bounce2"></div><div class="bounce3"></div></div>`

class RoomManager {
  constructor() {
    // $('body').off('click', '.mention-link[data-channel]')
    this.register_events()
  }

  render_room(resp) {
    if (debug) { console.log('render_room', resp) }
    $('.room-link').removeClass("active")
    // $('.messages-box').html(resp.box_html)
    // $('.messages-container .fixed-title h2').html(resp.header_html)
    $('.main-content').html(resp.html)
    ucxchat.channel_id = resp.channel_id
    ucxchat.room = resp.room_title
    ucxchat.display_name = resp.display_name
    ucxchat.room_route = resp.room_route
    if (resp.side_nav_html) {
      $('aside .rooms-list').html(resp.side_nav_html)
    }
    $('.room-title').html(ucxchat.display_name)
    $('.link-room-' + ucxchat.room).addClass("active")
    utils.scroll_bottom()
    roomchan.leave()
    socket.restart_socket()
  }
  toggle_favorite() {
    if (debug) { console.log('toggle_favorite') }
    // roomchan.push("room:favorite", {user_id: ucxchat.user_id, channel_id: ucxchat.channel_id})
    cc.put("/room/favorite")
      .receive("ok", resp => {
        $('.messages-container .fixed-title h2').html(resp.messages_html)
        $('aside .rooms-list').html(resp.side_nav_html)
      })
  }
  add_private(elem) {
    let username = elem.parent().attr('data-username')
    if (debug) { console.log('pvt-msg button clicked...', username) }
    // roomchan.push("room:add-direct", {username: username, user_id: ucxchat.user_id, channel_id: ucxchat.channel_id})
    cc.put("direct/" + username)
      .receive("ok", resp => {
        $('.messages-container .fixed-title h2').html(resp.messages_html)
        $('aside .rooms-list').html(resp.side_nav_html)
        ucxchat.channel_id = resp.channel_id
        ucxchat.room = resp.room
        ucxchat.display_name = resp.display_name
        ucxchat.room_route = resp.room_route
        // flex_bar.close_flex_tab()
        if ($('section.flex-tab').parent().hasClass('opened')) {
          $('section.flex-tab').html('').parent().removeClass('opened')
        }
        roomchan.leave()
        socket.restart_socket()
    })
  }
  update(msg) {
    console.log('update...', msg)
    let fname = msg.field_name
    if ( fname == "topic"  || fname == "title") {
      $('.room-' + fname).html(msg.value)
    } else if (fname == "name") {
      $('.room-title').html(msg.value)
      ucxchat.room = msg.value
      ucxchat.display_name = msg.value
      utils.replace_history()
    }

    $('.current-setting[data-edit="' + msg.field_name + '"]').html(msg.value)
    console.warn('RoomManager.update', msg)
  }
  room_mention(resp) {
    let parent = `a.open-room[data-name="${resp.room}"]`
    let elem = $(parent + ' span.unread')
    console.log('room_manager', resp, elem)
    if (elem.length == []) {
      $(parent).prepend(`<span class="unread">${resp.unread}</span>`)
    } else {
      elem.text(resp.unread)
    }
  }

  register_events() {
    $('body').on('click', 'a.open-room', e => {
      e.preventDefault();
      if (debug) { console.log('clicked a.open-room', e, $(e.currentTarget), $(e.currentTarget).attr('data-room')) }
      utils.page_loading()
      $('.main-content').html(utils.loading_animation())
      this.open_room($(e.currentTarget).attr('data-room'), $(e.currentTarget).attr('data-name'))
    })
    .on('click', 'a.toggle-favorite', e => {
      if (debug) { console.log('click a.toggle-favorite') }
      e.preventDefault();
      this.toggle_favorite()
    })
    .on('click', '.button.pvt-msg', e => {
      if (debug) { console.log('click .button.pvt-msg') }
      e.preventDefault();
      this.add_private(e.currentTarget)
    })
    .on('click', 'button.set-owner', e => {
      let username = $(e.currentTarget).parent().attr('data-username')
      e.preventDefault()
      cc.put("/room/set-owner/" + username)
        .receive("ok", resp => {
        })
        .receive("error", resp => {
          toastr.error(resp.error)
        })
    })
    .on('click', 'button.unset-owner', e => {
      let username = $(e.currentTarget).parent().attr('data-username')
      e.preventDefault()
      cc.put("/room/unset-owner/" + username)
        .receive("ok", resp => {
        })
        .receive("error", resp => {
          toastr.error(resp.error)
        })
    })
    .on('click', 'button.set-moderator', e => {
      let username = $(e.currentTarget).parent().attr('data-username')
      e.preventDefault()
      cc.put("/room/set-moderator/" + username)
        .receive("ok", resp => {
          if (resp.redirect) {
            window.location = resp.redirect
          }
        })
        .receive("error", resp => {
          toastr.error(resp.error)
        })
    })
    .on('click', 'button.unset-moderator', e => {
      let username = $(e.currentTarget).parent().attr('data-username')
      e.preventDefault()
      cc.put("/room/unset-moderator/" + username)
        .receive("ok", resp => {
        })
        .receive("error", resp => {
          toastr.error(resp.error)
        })
    })
    .on('click', 'button.unmute-user', e => {
      let username = $(e.currentTarget).parent().attr('data-username')
      e.preventDefault()
      cc.put("/room/unmute-user/" + username)
        .receive("ok", resp => {
        })
        .receive("error", resp => {
          toastr.error(resp.error)
        })
    })
    .on('click', 'button.unblock-user', e => {
      let username = $(e.currentTarget).parent().attr('data-username')
      e.preventDefault()
      cc.put("/room/unblock-user/" + username)
        .receive("ok", resp => {
        })
        .receive("error", resp => {
          toastr.error(resp.error)
        })
    })
    .on('click', 'button.block-user', e => {
      let username = $(e.currentTarget).parent().attr('data-username')
      e.preventDefault()
      cc.put("/room/block-user/" + username)
        .receive("ok", resp => {
        })
        .receive("error", resp => {
          toastr.error(resp.error)
        })
    })
    .on('click', 'button.mute-user', e => {
      let username = $(e.currentTarget).parent().attr('data-username')
      e.preventDefault()
      sweetAlert({
        title: gettext.are_you_sure,
        text: gettext.the_user_wont_able_type + ' ' + ucxchat.room,
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: gettext.yes_mute_user,
        closeOnConfirm: false
      },
      function(){
        cc.put("/room/mute-user/" + username)
          .receive("ok", resp => {
            swal({
                title: gettext.muted,
                text: gettext.the_user_wont_able_type + ' ' + ucxchat.room,
                type: 'success',
                timer: 2000,
                showConfirmButton: false,
            })
          })
          .receive("error", resp => {
            toastr.error(resp.error)
          })
      });
    })
    .on('click', 'button.remove-user', e => {
      let username = $(e.currentTarget).parent().attr('data-username')
      e.preventDefault()
      sweetAlert({
        title: gettext.are_you_sure,
        text: gettext.the_user_will_be_removed_from + ' ' + ucxchat.room,
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Yes, remove user!",
        closeOnConfirm: false
      },
      function(){
        cc.put("/room/remove-user/" + username)
          .receive("ok", resp => {
            swal({
                title: gettext.removed,
                text: gettext.the_user_was_remove_from + ' ' + ucxchat.room,
                type: 'success',
                timer: 2000,
                showConfirmButton: false,
            })
          })
          .receive("error", resp => {
            toastr.error(resp.error)
          })
      });
    })
    .on('click', 'button.join', e => {
      cc.put("/room/join/" + ucxchat.username)
        .receive("ok", resp => {
        })
        .receive("error", resp => {
          toastr.error(resp.error)
        })
    })
    .on('click', 'a.open-room i.hide-room', e => {
      e.preventDefault()
      let room = $(e.currentTarget).closest('.open-room').data('room')
      // console.log('cliecked open-room', room)
      sweetAlert({
        title: gettext.are_you_sure,
        text: gettext.are_you_sure_you_want_to_hide_the_room + ' "' + room + '"?',
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: gettext.yes_hide_it,
        closeOnConfirm: false
      },
      function(){
        cc.put("/room/hide/" + room)
          .receive("ok", resp => {
            if (resp.redirect) {
              window.location = resp.redirect
            }
            // swal({
            //     timer: 1,
            //     showConfirmButton: false,
            // })
          })
          .receive("error", resp => {
            toastr.error(resp.error)
          })
      });
      return false
    })
    .on('click', 'a.open-room i.leave-room', e => {
      e.preventDefault()
      let room = $(e.currentTarget).closest('.open-room').data('room')
      console.log('cliecked leave-room', room)
      sweetAlert({
        title: gettext.are_you_sure,
        text: gettext.are_you_sure_leave_the_room + ' "' + room + '"?',
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: gettext.yes_leave_it,
        closeOnConfirm: false
      },
      function(){
        cc.put("/room/leave/" + room)
          .receive("ok", resp => {
            swal({
                title: gettext.left_the_room,
                text: gettext.you_have_left_the_room + " " + ucxchat.room,
                type: 'success',
                timer: 500,
                showConfirmButton: false,
            })
          })
          .receive("error", resp => {
            toastr.error(resp.error)
          })
      });
      return false
    })
    .on('click', '.mention-link[data-channel]', (e) => {
      e.preventDefault()
      let target = $(e.currentTarget)
      let room = target.data('channel')
      console.log('clicked channel link', room)
      this.open_room(room, room)
      return false
    })
    $('.messages-box .wrapper').on('scroll', _.throttle((e) => {
      if (utils.is_scroll_bottom()) {
        console.log('scroller scrolling at bottom' )
      } else {
        console.log('scroller keep scrolling ' )
      }
    }, 150))

    $(window).on('focus', () => {
      this.clear_unread()
      console.log('room_manager focus')
    })

  }

  clear_unread() {
    setTimeout(function() {
      let parent = `a.open-room[data-name="${ucxchat.room}"]`
      $(parent + ' span.unread').remove()
    }, 1000)
  }

  open_room(room, display_name, callback) {
    cc.get("/room/" + room, {display_name: display_name, room: ucxchat.room})
      .receive("ok", resp => {
        console.log('open room response', resp)
        if (resp.redirect) {
          window.location = resp.redirect
        } else {
          this.render_room(resp)
        }
        if (callback) { callback() }
        utils.remove_page_loading()
      })
  }
}

export default RoomManager;
<|endoftext|>


<commit_before>'use babel';

// AnySyn package (https://github.com/mark-hahn/anysyn)

import * as SubAtom from 'sub-atom';

let log = console.log.bind(console);

export let config = {
  regexes: {
    title: 'Regexes to match file paths to syntax plugins',
    description: 'Format is regex:plugin-name, separate with commas',
    type: 'array',
    default: ['.*/anysyn1.js:coffee', '.*/anysyn2.js:coffee'],
    items: { type: 'string' }
  }
}

export let activate = () => {
  this.subs = new SubAtom;

  log('AnySyn activated');
  this.syntaxServices = [];
  atom.config.observe('anysyn.regexes', () => this.parseRegexes());
  this.opener = (filePath, options) => {
    log('opener', {filePath, options});
    for (regexMatch of this.regexMatches) {
      if (regexMatch.regex.test(filePath)) {
        for (service of this.syntaxServices) {
          if (service.name === regexMatch.plugin) {
            found = true;
            this.loadFile(filePath, service);
            return new atom.TextEditor;
          }
        }
        log(`AnySyn, Plugin not found: ${regexMatch.plugin}`);
      }
    }
  }
  atom.workspace.addOpener(this.opener);
  this.subs.add(this.opener);
}

export let addSyntax = (syntaxService) => {
  log('addSyntax', syntaxService.name);
  syntaxServices.push(syntaxService);
}

export let deActivate = () =>  {
  this.subs.dispose();
  log('AnySyn deActivated');
}

// ------------ Private ------------

this.parseRegexes = () => {
  this.regexMatches = [];
  for (regex of atom.config.get('anysyn.regexes')) {
    let [regexStr, plugin] = regex.split(':');
    if (typeof regexStr !== 'string' || typeof plugin !== 'string')
      log(`AnySyn: Configuration parse error for ${regexStr}:${plugin}`);
    this.regexMatches.push({regex: new RegExp(regexStr), plugin});
  }
  log('this.regexMatches', this.regexMatches);
}

this.loadFile = (filePath, service) => {
  log('loadFile', {filePath, service});
}

<commit_msg>added checkeditor<commit_after>'use babel';

// AnySyn package (https://github.com/mark-hahn/anysyn)

import SubAtom from 'sub-atom';

const log = console.log.bind(console);
const self = {};

export const config = {
  regexes: {
    title:       'Regexes to match file paths to syntax plugins',
    description: 'Format is regex:plugin-name, separate with commas',
    type:        'array',
    default:    ['.*/anysyn1.js:coffee', '.*/anysyn2.js:coffee'],
    items: {
      type: 'string'
    }
  }
}

export const activate = () => {
  self.subs = new SubAtom;
  self.syntaxServices = [];
  self.subs.add(atom.config.observe('anysyn.regexes', () => self.parseRegexes()));
  self.subs.add(atom.workspace.observeTextEditors((editor) => self.checkEditor(editor)));
}

export const addSyntax = (syntaxService) => {
  log('addSyntax', syntaxService.name);
  self.syntaxServices.push(syntaxService);
}

export const deActivate = () =>  {
  // self.subs.disposeAll();
  // log('AnySyn deActivated');
}

// ------------ Private --------------

self.parseRegexes = () => {
  self.regexMatches = [];
  for (regex of atom.config.get('anysyn.regexes')) {
    const [regexStr, plugin] = regex.split(':');
    if (typeof regexStr !== 'string' || typeof plugin !== 'string')
      log(`AnySyn: Configuration parse error for ${regexStr}:${plugin}`);
      continue;
    self.regexMatches.push({regex: new RegExp(regexStr), plugin});
  }
  log('self.regexMatches', self.regexMatches);
}

self.checkEditor = (editor) => {
  log('checkEditor', {editor});
  let filePath = editor.getPath();
  for (regexMatch of self.regexMatches) {
    if (regexMatch.regex.test(filePath)) {
      for (service of self.syntaxServices) {
        if (service.name === regexMatch.plugin) {
          self.loadFile(editor, filePath, service);
          return
        }
      }
      log(`AnySyn, Plugin not found: ${regexMatch.plugin}`);
    }
  }
}

self.loadFile = (editor, filePath, service) => {
  log('loadFile', {editor, filePath, service});
}
<|endoftext|>


<commit_before>//Power is connected to pin4 (5V), ground is pin6, tx (output) is pin 8,
// rx (input) is pin10

var SerialPort = require('serialport').SerialPort;
var serialPort = new SerialPort('/dev/ttyAMA0', {
	baudRate: 9600
});
var EMIC = (function() {
var isOpen = false;
var isReady = true;

var emic = {};
emic.init = function () {

	console.log('Successfully loaded SerialPort module');

	console.log('Successfully initialised /dev/ttyAMA0');

	serialPort.on('open', function () {
		console.log('Port is open')
		isOpen = true;
		serialPort.on('data', function(msg) {
			msg = msg.toString('ascii');
			console.log(msg);
			serialPort.flush();
			if (msg == ':') {
				isReady = true
				console.log('Emic is ready for an instruction')
			}
		});
		serialPort.write(':P1\r')
		serialPort.write('[:PHONE ON] [:nv] [:dv gn 75] [wiy<400,20>wih<300,25>sh<100>yu<200>ax<200,27>meh<200,25>riy<200,24>krih<300,22>s<100>mah<300>s<100>wih<400>wih<300,27>sh<100>yu<200>ax<200,29>meh<200,27>riy<200,25>krih<300,24>s<100>mah<300,20>s<100>wih<400>wih<300,29>sh<100>yu<200>ax<200,30>meh<200,29>riy<200,27>KRIH<300,25>S<100>MAH<300,22>S<100>AE<100,20>N<50>D<50>AX<200>HXAE<400,22>PIY<400,27>NUW<400,24>YXIR<600,25>_<100>]. [GUH<300,20>D<100>TAY<400,25>DIH<200>NX<100>Z<100>TUW<400>YU<800,24>WER<400>EH<400,25>VRR<400,24>YU<400,22>AR<800,20>GUH<300,27>D<100>TAY<400,29>DIH<200,27>NX<100>Z<100>FOR<400,25>KRIH<300,32>S<100>MAH<300,20>S<100>AE<100>N<50>D<50>AX<200>HXAE<400,22>PIY<400,27>NUW<400,24>YXIR<600,25>_<100>].

[WIY<400,20>WIH<300,25>SH<100>YU<200>AX<200,27>MER<200,25>RIY<200,24>KRIH<300,22>S<100>MAH<300>S<100>WIY<400>WIH<300,27>SH<100>YU<200>AX<200,29>MEH<200,27>RIY<200,25>KRIH<300,24>S<100>MAH<300,20>S<100>WIY<400>WIH<300,29>SH<100>YU<200>AX<200,30>MEH<200,29>RIY<200,27>KRIH<300,25>S<100>MAH<300,22>S<100>AE<100,20>N<50>D<50>AX<200>HXAE<400,22>PIY<400,27>NUW<400,24>YXIR<800,25>].');
	});
};
emic.speak = function (data) {
	data = data.toString('ascii');
	while (isOpen == false) {};
	if (data.length > 1000) {
		console.log('Error: Message exceeds the character limit');
	} else {
		//serialPort.write(':SHello World to all\r');
		serialPort.write(':S' + data + '\r');
		console.log(':S' + data + '\r');
		isReady = false
		console.log('Emic is busy')
	};
};

emic.demo = function (id) {
	id = id.toString('ascii');
	if (id == '0' || id == '1' || id == '2') {
		serialPort.write(':D' + id + '\r');
	} else {
		console.log('Error: Invalid Command');
	};
};

emic.stopNow = function () {
	serialPort.write(':X\r');
}

emic.pause = function () {
	serialPort.write(':Z\r');
};

emic.voice = function (id) {
	var idN = id.parseInt();
	if (idN >= 0 && idN <= 8) {
		id.toString('ascii');
		serialPort.write(':N' + id + '\r');
	} else {
		console.log('Error: Invalid Command');
	};
};

emic.volume = function (level) {
	var levelN = id.parseInt();
	if (levelN >= -48 && levelN <= 18) {
		level = level.toString('ascii');
		serialPort.write(':V' + level + '\r');
	} else {
		console.log('Error: Invalid Command');
	};
};

emic.rate = function (wpm) {
	var wpmN = wpm.parseInt();
	if (wpmN >= 75 && wpmN <= 600) {
		wpm = wpm.toString('ascii');
		serialPort.write(':W' + wpm + '\r');
	} else {
		console.log('Error: Invalid Command');
	};
};

emic.parser = function (id) {
	id = id.toString('ascii');
	if (parser == '0' || parser == '1' || parser == '2') {
		serialPort.write(':P' + id + '\r');
	} else {
		console.log('Error: Invalid Command');
	};
};

emic.revert = function () {
	serialPort.write(':R\r');
};

emic.callCurrentSettings = function () {
	serialPort.write(':C\r');
};

emic.callVersionInfo = function () {
	serialPort.write(':I\r');
};

emic.callCommands = function () {
	serialPort.write(':I\r');
};
return emic
}());

/*function writeLog(logFile, output){
	var logf = new File(logFile);
	logf.writeln(output);
	logf.close()*/

module.exports = EMIC;

<commit_msg>update<commit_after>//Power is connected to pin4 (5V), ground is pin6, tx (output) is pin 8,
// rx (input) is pin10

var SerialPort = require('serialport').SerialPort;
var serialPort = new SerialPort('/dev/ttyAMA0', {
	baudRate: 9600
});
var EMIC = (function() {
var isOpen = false;
var isReady = true;

var emic = {};
emic.init = function () {

	console.log('Successfully loaded SerialPort module');

	console.log('Successfully initialised /dev/ttyAMA0');

	serialPort.on('open', function () {
		console.log('Port is open')
		isOpen = true;
		serialPort.on('data', function(msg) {
			msg = msg.toString('ascii');
			console.log(msg);
			serialPort.flush();
			if (msg == ':') {
				isReady = true
				console.log('Emic is ready for an instruction')
			}
		});
		serialPort.write(':P1\r')
		serialPort.drain();
		serialPort.write('[:PHONE ON] [:nv] [:dv gn 75] [wiy<400,20>wih<300,25>sh<100>yu<200>ax<200,27>meh<200,25>riy<200,24>krih<300,22>s<100>mah<300>s<100>wih<400>wih<300,27>sh<100>yu<200>ax<200,29>meh<200,27>riy<200,25>krih<300,24>s<100>mah<300,20>s<100>wih<400>wih<300,29>sh<100>yu<200>ax<200,30>meh<200,29>riy<200,27>KRIH<300,25>S<100>MAH<300,22>S<100>AE<100,20>N<50>D<50>AX<200>HXAE<400,22>PIY<400,27>NUW<400,24>YXIR<600,25>_<100>]. [GUH<300,20>D<100>TAY<400,25>DIH<200>NX<100>Z<100>TUW<400>YU<800,24>WER<400>EH<400,25>VRR<400,24>YU<400,22>AR<800,20>GUH<300,27>D<100>TAY<400,29>DIH<200,27>NX<100>Z<100>FOR<400,25>KRIH<300,32>S<100>MAH<300,20>S<100>AE<100>N<50>D<50>AX<200>HXAE<400,22>PIY<400,27>NUW<400,24>YXIR<600,25>_<100>]. [WIY<400,20>WIH<300,25>SH<100>YU<200>AX<200,27>MER<200,25>RIY<200,24>KRIH<300,22>S<100>MAH<300>S<100>WIY<400>WIH<300,27>SH<100>YU<200>AX<200,29>MEH<200,27>RIY<200,25>KRIH<300,24>S<100>MAH<300,20>S<100>WIY<400>WIH<300,29>SH<100>YU<200>AX<200,30>MEH<200,29>RIY<200,27>KRIH<300,25>S<100>MAH<300,22>S<100>AE<100,20>N<50>D<50>AX<200>HXAE<400,22>PIY<400,27>NUW<400,24>YXIR<800,25>].');
	});
};
emic.speak = function (data) {
	data = data.toString('ascii');
	while (isOpen == false) {};
	if (data.length > 1000) {
		console.log('Error: Message exceeds the character limit');
	} else {
		//serialPort.write(':SHello World to all\r');
		serialPort.write(':S' + data + '\r');
		console.log(':S' + data + '\r');
		isReady = false
		console.log('Emic is busy')
	};
};

emic.demo = function (id) {
	id = id.toString('ascii');
	if (id == '0' || id == '1' || id == '2') {
		serialPort.write(':D' + id + '\r');
	} else {
		console.log('Error: Invalid Command');
	};
};

emic.stopNow = function () {
	serialPort.write(':X\r');
}

emic.pause = function () {
	serialPort.write(':Z\r');
};

emic.voice = function (id) {
	var idN = id.parseInt();
	if (idN >= 0 && idN <= 8) {
		id.toString('ascii');
		serialPort.write(':N' + id + '\r');
	} else {
		console.log('Error: Invalid Command');
	};
};

emic.volume = function (level) {
	var levelN = id.parseInt();
	if (levelN >= -48 && levelN <= 18) {
		level = level.toString('ascii');
		serialPort.write(':V' + level + '\r');
	} else {
		console.log('Error: Invalid Command');
	};
};

emic.rate = function (wpm) {
	var wpmN = wpm.parseInt();
	if (wpmN >= 75 && wpmN <= 600) {
		wpm = wpm.toString('ascii');
		serialPort.write(':W' + wpm + '\r');
	} else {
		console.log('Error: Invalid Command');
	};
};

emic.parser = function (id) {
	id = id.toString('ascii');
	if (parser == '0' || parser == '1' || parser == '2') {
		serialPort.write(':P' + id + '\r');
	} else {
		console.log('Error: Invalid Command');
	};
};

emic.revert = function () {
	serialPort.write(':R\r');
};

emic.callCurrentSettings = function () {
	serialPort.write(':C\r');
};

emic.callVersionInfo = function () {
	serialPort.write(':I\r');
};

emic.callCommands = function () {
	serialPort.write(':I\r');
};
return emic
}());

/*function writeLog(logFile, output){
	var logf = new File(logFile);
	logf.writeln(output);
	logf.close()*/

module.exports = EMIC;

<|endoftext|>


<commit_before>/* eslint-env browser */
import React, {useState} from 'react';
import {Canvas} from 'react-three-fiber';
import {Stage2D, BitmapText2D, BitmapText2DBlock, TextureAtlas} from 'picimo-r3f';
import {number, withKnobs, text, select, boolean} from '@storybook/addon-knobs';

export default {
  title: 'BitmapText2D',
  decorators: [withKnobs],
};

const PROJECTION = {
  width: 640,
  height: 400,
  fit: 'contain',
  distance: 1000,
  far: 10000,
};

const HELLO = `HELLO
STORYBOOK!`;

export const demo = () => {
  const [usedCount, setUsedCount] = useState(0);
  return (

        <Canvas gl2 pixelRatio={window.devicePixelRatio} style={{minHeight: '400px'}}>
          <Stage2D plane="xy" type="parallax" projection={PROJECTION}>

            { boolean('show <BitmapText2DB>', true) && (
              <BitmapText2D onFrame={bt2d => setUsedCount(bt2d.bitmapChars.usedCount)}>
                <TextureAtlas
                  attach="fontAtlas"
                  src={select('texture-atlas', ['comic-schrift.json', 'rbmfs.json'], 'comic-schrift.json')}
                />

                { boolean('show <BitmapText2DBlock>', true) && (
                  <BitmapText2DBlock
                    fontSize={number('fontSize', 100)}
                    lineGap={number('lineGap', 10)}
                    maxWidth={number('maxWidth', 0)}
                    text={text('text', HELLO)}
                    hAlign={select('hAlign', ['center', 'left', 'right'], 'center')}
                    vAlign={select('vAlign', ['top', 'baseline', 'center', 'bottom'], 'center')}
                  />
                )}
              </BitmapText2D>
            )}

          </Stage2D>
        </Canvas>

char count: {usedCount}

  );
};
<commit_msg>fix eslint issue<commit_after>/* eslint-env browser */
import React, {useState} from 'react';
import {Canvas} from 'react-three-fiber';
import {Stage2D, BitmapText2D, BitmapText2DBlock, TextureAtlas} from 'picimo-r3f';
import {number, withKnobs, text, select, boolean} from '@storybook/addon-knobs';

export default {
  title: 'BitmapText2D',
  decorators: [withKnobs],
};

const PROJECTION = {
  width: 640,
  height: 400,
  fit: 'contain',
  distance: 1000,
  far: 10000,
};

const HELLO = `HELLO
STORYBOOK!`;

const Story = () => {
  const [usedCount, setUsedCount] = useState(0);
  return (

        <Canvas gl2 pixelRatio={window.devicePixelRatio} style={{minHeight: '400px'}}>
          <Stage2D plane="xy" type="parallax" projection={PROJECTION}>

            { boolean('show <BitmapText2DB>', true) && (
              <BitmapText2D onFrame={bt2d => setUsedCount(bt2d.bitmapChars.usedCount)}>
                <TextureAtlas
                  attach="fontAtlas"
                  src={select('texture-atlas', ['comic-schrift.json', 'rbmfs.json'], 'comic-schrift.json')}
                />

                { boolean('show <BitmapText2DBlock>', true) && (
                  <BitmapText2DBlock
                    fontSize={number('fontSize', 100)}
                    lineGap={number('lineGap', 10)}
                    maxWidth={number('maxWidth', 0)}
                    text={text('text', HELLO)}
                    hAlign={select('hAlign', ['center', 'left', 'right'], 'center')}
                    vAlign={select('vAlign', ['top', 'baseline', 'center', 'bottom'], 'center')}
                  />
                )}
              </BitmapText2D>
            )}

          </Stage2D>
        </Canvas>

char count: {usedCount}

  )
};

export const demo = Story;
<|endoftext|>