<commit_before>nforge.namespace('markdown');

var renderMarkdown = function(text) {
  text = text
    .replace(/```(\w+)(?:\r\n|\r|\n)((\r|\n|.)*?)(\r|\n)```/gm, function(match, p1, p2) {
    try {
      return '
' + hljs(p2, p1).value + '
';
    } catch (e) {
      return '
' + hljs(p2).value + '
';
    }
  });

  return new Showdown.converter().makeHtml(text);
};

var getFileList = function(target, urlToGetFileList, fn) {
  var form = $('<form>')
    .attr('method', 'get')
    .attr('action', urlToGetFileList);
  resourceType = target.attr('resourceType');
  resourceId = target.attr('resourceId');
  if (resourceType !== undefined) {
    form.append('<input type="hidden" name="containerType" value="' + resourceType + '">');
  }
  if (resourceId !== undefined) {
    form.append('<input type="hidden" name="containerId" value="' + resourceId + '">');
  }
  form.ajaxForm({ success: fn });
  form.submit();
};

var editor = function (textarea) {
  var previewDiv, previewSwitch;

  previewDiv = $('
');
  previewDiv.attr('div', 'preview');
  previewDiv.css('display', 'none');

  previewSwitch = $('
');
  previewSwitch.append($('<input type="radio" name="edit-mode" value="edit" checked>Edit</input>'));
  previewSwitch.append($('<input type="radio" name="edit-mode" value="preview">Preview</input>'));
  previewSwitch.change(function() {
    var val = $('input:radio[name=edit-mode]:checked').val();
    if (val == 'preview') {
      previewDiv.html(renderMarkdown(textarea.val()));
      textarea.css('display', 'none');
      previewDiv.css('display', '');
    } else {
      textarea.css('display', '');
      previewDiv.css('display', 'none');
    }
  });

  textarea.before(previewSwitch);
  textarea.before(previewDiv);
};

var viewer = function (target) {
  target.html(renderMarkdown(target.text()));
};

var fileUploader = function (textarea, action) {
  var setProgressBar = function(value) {
    progressbar.css("width", value + "%");
    progressbar.text(value + "%");
  };

  var createFileItem = function(file, link) {
    var fileitem, filelink, filesize, insertButton, deleteButton;

    fileitem = $('
');
    fileitem.attr('tabindex', 0);

    filelink = $('');
    filelink.attr('href', file.url);
    filelink.text(file.name);
    filesize = $('').text('(' + humanize.filesize(file.size) + ')');

    insertButton = $('<input type="button">');
    insertButton.attr('id', file.name);
    insertButton.attr('value', '본문에 삽입');
    insertButton.addClass('insertInto label label-info');
    insertButton.click(function() { insertLinkInto(textarea, link); });

    deleteButton = $('');
    deleteButton.attr('name', 'submit');
    deleteButton.addClass('fileDeleteBtn close');
    deleteButton.text('x');
    deleteButton.click(function() {
      var form = $('<form>')
        .attr('method', 'post')
        .attr('enctype', 'multipart/form-data')
        .attr('action', file.url);
      form.append('<input type="hidden" name="_method" value="delete">');
      form.ajaxForm({
        success: function() {
          fileitem.remove();
          textarea.val(textarea.val().split(link).join(''));
          setProgressBar(0);
          notification.text(file.name + ' is deleted successfully.');
        }
      });
      form.submit();
    });

    fileitem.append(filelink);
    fileitem.append(filesize);
    fileitem.append(insertButton);
    fileitem.append(deleteButton);

    return fileitem;
  };

  var createFileList = function(title) {
    var filelist, div

    filelist = $('
');
    filelist.attr('id', 'filelist');
    filelist.addClass('files');

    div = $('
');
    div.addClass('attachment-list');
    div.append($('' + title + ''));
    div.append(filelist);

    return div;
  };

  var _getFileNameOnly = function(filename) {
    var fakepath = 'fakepath';
    var fakepathPostion = filename.indexOf(fakepath);
    if (fakepathPostion > -1) {
      filename = filename.substring(fakepath.length + fakepathPostion + 1);
    }
    return filename;
  };

  var _replaceFileInputControl = function() {
    progress.before(createAttachment());
  };

  var insertLinkInto = function(textarea, link) {
    var pos = textarea.prop('selectionStart');
    var text = textarea.val();
    textarea.val(text.substring(0, pos) + link + text.substring(pos));
  };

  var isImageType = function(mimeType) {
    if (mimeType && mimeType.substr(0, mimeType.indexOf('/')) == 'image') {
      return true;
    } else {
      return false;
    }
  };

  var createFileLink = function(name, url, mimeType) {
    if (isImageType(mimeType)) {
      return '';
    } else {
      return '[' + name + '](' + url + ')';
    }
  };

  var fileUploadOptions = {
    beforeSubmit: function() {
      var filename = _getFileNameOnly(attachment.val());

      // show message box
      if (filename === "") {
        notification.text('Choose a file to be attached.');
        return false;
      }

      return true;
    },

    success: function(responseBody, statusText, xhr) {
      var file, link;
      file = responseBody;

      if (!(file instanceof Object) || !file.name || !file.url) {
        notification.text('Failed to upload - Server error.');
        _replaceFileInputControl();
        setProgressBar(0);
        return;
      }

      _replaceFileInputControl();

      link = createFileLink(file.name, file.url, file.mimeType)
      if (isImageType(file.mimeType)) {
        insertLinkInto(textarea, link);
      }

      tempFileList.css('display', '');
      tempFileList.append(createFileItem(file, link));

      setProgressBar(100);
    },

    error: function(responseBody, statusText, xhr) {
      notification.text('Failed to upload.');
      _replaceFileInputControl();
      setProgressBar(0);
    },

    uploadProgress: function(event, position, total, percentComplete) {
      setProgressBar(percentComplete);
    }
  };

  var createAttachment = function() {
    var attachment = $('<input type="file" name="filePath">');

    attachment.click(function(event) {
      setProgressBar(0);
    });

    attachment.change(function(event) {
      if (attachment.val() !== "") {
        var filename = _getFileNameOnly(attachment.val());
        var form = $('<form>')
          .attr('method', 'post')
          .attr('enctype', 'multipart/form-data')
          .attr('action', action);
        form.append(attachment);
        form.ajaxForm(fileUploadOptions);
        form.submit();
      }
    });

    return attachment;
  }

  var fileAttachment, attachment, progressbar, progress, attachmentList,
      tempFileList, notification;

  if (!textarea || !action) {
    throw new Error('textarea and action is required.');
  }

  attachment = createAttachment();
  progressbar = $('
');
  progress = $('
').append(progressbar);
  attachmentList = createFileList('Attachments');
  tempFileList = createFileList('Temporary files (attached if you save)');
  notification = $('
');

  attachmentList.css('display', 'none');
  tempFileList.css('display', 'none');

  getFileList(textarea, action, function(responseBody, statusText, xhr) {
    var addFiles = function(files, targetList) {
      if (files) {
        for (var i = 0; i < files.length; i++) {
          var file = files[i];
          var link = createFileLink(file.name, file.url, file.mimeType);
          targetList.css('display', '');
          targetList.append(createFileItem(file, link));
        }
      }
    };

    addFiles(responseBody.attachments, attachmentList);
    addFiles(responseBody.tempFiles, tempFileList);
  });

  fileAttachment = textarea.siblings('.file-attachment');
  if (fileAttachment.length <= 0) {
    fileAttachment = textarea.parent().siblings('.file-attachment');
  }
  if (fileAttachment.length <= 0) {
    fileAttachment = $('
').addClass('file-attachment');
    textarea.after(fileAttachment);
  }

  fileAttachment
    .append(notification)
    .append(attachment)
    .append(progress)
    .append(attachmentList)
    .append(tempFileList);
}

var fileDownloader = function (div, urlToGetFileList) {
  var createFileItem = function(file) {
    var link = $('')
        .prop('href', file.url)
        .append($('').addClass('icon-download'))
        .append($('
').text(file.name).html());

    return $('
').append(link);
  }

  var filelist = $('
');
  var addFiles = function(responseBody, statusText, xhr) {
    var files = responseBody.attachments;
    for (var i = 0; i < files.length; i++) {
      filelist.css('display', '');
      filelist.append(createFileItem(files[i]));
    }
  }

  getFileList(div, urlToGetFileList, addFiles);

  div.after(filelist);
}

nforge.markdown.enable = function() {
  var that = {
    init: function(targets, action) {
      for(var i = 0; i < targets.length; i++) {
        var target = targets[i];
        var tagname = target.tagName.toLowerCase();
        if (tagname == 'textarea' || tagname == 'input'
                || target.contentEditable == 'true') {
          editor($(target));
          fileUploader($(target), action);
        } else {
          viewer($(target));
          fileDownloader($(target), action);
        }
      }
    }
  };

  return that;
}
<commit_msg>uploader: Fix dynamic form doesn't work in IE.<commit_after>nforge.namespace('markdown');

var renderMarkdown = function(text) {
  text = text
    .replace(/```(\w+)(?:\r\n|\r|\n)((\r|\n|.)*?)(\r|\n)```/gm, function(match, p1, p2) {
    try {
      return '
' + hljs(p2, p1).value + '
';
    } catch (e) {
      return '
' + hljs(p2).value + '
';
    }
  });

  return new Showdown.converter().makeHtml(text);
};

var getFileList = function(target, urlToGetFileList, fn) {
  var form = $('<form>')
    .attr('method', 'get')
    .attr('action', urlToGetFileList);
  resourceType = target.attr('resourceType');
  resourceId = target.attr('resourceId');
  if (resourceType !== undefined) {
    form.append('<input type="hidden" name="containerType" value="' + resourceType + '">');
  }
  if (resourceId !== undefined) {
    form.append('<input type="hidden" name="containerId" value="' + resourceId + '">');
  }
  form.ajaxForm({ success: fn });
  form.submit();
};

var editor = function (textarea) {
  var previewDiv, previewSwitch;

  previewDiv = $('
');
  previewDiv.attr('div', 'preview');
  previewDiv.css('display', 'none');

  previewSwitch = $('
');
  previewSwitch.append($('<input type="radio" name="edit-mode" value="edit" checked>Edit</input>'));
  previewSwitch.append($('<input type="radio" name="edit-mode" value="preview">Preview</input>'));
  previewSwitch.change(function() {
    var val = $('input:radio[name=edit-mode]:checked').val();
    if (val == 'preview') {
      previewDiv.html(renderMarkdown(textarea.val()));
      textarea.css('display', 'none');
      previewDiv.css('display', '');
    } else {
      textarea.css('display', '');
      previewDiv.css('display', 'none');
    }
  });

  textarea.before(previewSwitch);
  textarea.before(previewDiv);
};

var viewer = function (target) {
  target.html(renderMarkdown(target.text()));
};

var fileUploader = function (textarea, action) {
  var setProgressBar = function(value) {
    progressbar.css("width", value + "%");
    progressbar.text(value + "%");
  };

  var createFileItem = function(file, link) {
    var fileitem, filelink, filesize, insertButton, deleteButton;

    fileitem = $('
');
    fileitem.attr('tabindex', 0);

    filelink = $('');
    filelink.attr('href', file.url);
    filelink.text(file.name);
    filesize = $('').text('(' + humanize.filesize(file.size) + ')');

    insertButton = $('<input type="button">');
    insertButton.attr('id', file.name);
    insertButton.attr('value', '본문에 삽입');
    insertButton.addClass('insertInto label label-info');
    insertButton.click(function() { insertLinkInto(textarea, link); });

    deleteButton = $('');
    deleteButton.attr('name', 'submit');
    deleteButton.addClass('fileDeleteBtn close');
    deleteButton.text('x');
    deleteButton.click(function() {
      var form = $('<form>')
        .attr('method', 'post')
        .attr('enctype', 'multipart/form-data')
        .attr('action', file.url)
        .css('display', 'none');
      form.append('<input type="hidden" name="_method" value="delete">');
      $('body').append(form);
      form.ajaxForm({
        success: function() {
          fileitem.remove();
          textarea.val(textarea.val().split(link).join(''));
          setProgressBar(0);
          notification.text(file.name + ' is deleted successfully.');
        }
      });
      form.submit();
    });

    fileitem.append(filelink);
    fileitem.append(filesize);
    fileitem.append(insertButton);
    fileitem.append(deleteButton);

    return fileitem;
  };

  var createFileList = function(title) {
    var filelist, div

    filelist = $('
');
    filelist.attr('id', 'filelist');
    filelist.addClass('files');

    div = $('
');
    div.addClass('attachment-list');
    div.append($('' + title + ''));
    div.append(filelist);

    return div;
  };

  var _getFileNameOnly = function(filename) {
    var fakepath = 'fakepath';
    var fakepathPostion = filename.indexOf(fakepath);
    if (fakepathPostion > -1) {
      filename = filename.substring(fakepath.length + fakepathPostion + 1);
    }
    return filename;
  };

  var _replaceFileInputControl = function() {
    progress.before(createAttachment());
  };

  var insertLinkInto = function(textarea, link) {
    var pos = textarea.prop('selectionStart');
    var text = textarea.val();
    textarea.val(text.substring(0, pos) + link + text.substring(pos));
  };

  var isImageType = function(mimeType) {
    if (mimeType && mimeType.substr(0, mimeType.indexOf('/')) == 'image') {
      return true;
    } else {
      return false;
    }
  };

  var createFileLink = function(name, url, mimeType) {
    if (isImageType(mimeType)) {
      return '';
    } else {
      return '[' + name + '](' + url + ')';
    }
  };

  var fileUploadOptions = {
    beforeSubmit: function() {
      var filename = _getFileNameOnly(attachment.val());

      // show message box
      if (filename === "") {
        notification.text('Choose a file to be attached.');
        return false;
      }

      return true;
    },

    success: function(responseBody, statusText, xhr) {
      var file, link;
      file = responseBody;

      if (!(file instanceof Object) || !file.name || !file.url) {
        notification.text('Failed to upload - Server error.');
        _replaceFileInputControl();
        setProgressBar(0);
        return;
      }

      _replaceFileInputControl();

      link = createFileLink(file.name, file.url, file.mimeType)
      if (isImageType(file.mimeType)) {
        insertLinkInto(textarea, link);
      }

      tempFileList.css('display', '');
      tempFileList.append(createFileItem(file, link));

      setProgressBar(100);
    },

    error: function(responseBody, statusText, xhr) {
      notification.text('Failed to upload.');
      _replaceFileInputControl();
      setProgressBar(0);
    },

    uploadProgress: function(event, position, total, percentComplete) {
      setProgressBar(percentComplete);
    }
  };

  var createAttachment = function() {
    var attachment = $('<input type="file" name="filePath">');

    attachment.click(function(event) {
      setProgressBar(0);
    });

    attachment.change(function(event) {
      if (attachment.val() !== "") {
        var filename = _getFileNameOnly(attachment.val());
        var form = $('<form>')
          .attr('method', 'post')
          .attr('enctype', 'multipart/form-data')
          .attr('action', action)
          .css('display', 'none');
        form.append(attachment);
        $('body').append(form);
        form.ajaxForm(fileUploadOptions);
        form.submit();
      }
    });

    return attachment;
  }

  var fileAttachment, attachment, progressbar, progress, attachmentList,
      tempFileList, notification;

  if (!textarea || !action) {
    throw new Error('textarea and action is required.');
  }

  attachment = createAttachment();
  progressbar = $('
');
  progress = $('
').append(progressbar);
  attachmentList = createFileList('Attachments');
  tempFileList = createFileList('Temporary files (attached if you save)');
  notification = $('
');

  attachmentList.css('display', 'none');
  tempFileList.css('display', 'none');

  getFileList(textarea, action, function(responseBody, statusText, xhr) {
    var addFiles = function(files, targetList) {
      if (files) {
        for (var i = 0; i < files.length; i++) {
          var file = files[i];
          var link = createFileLink(file.name, file.url, file.mimeType);
          targetList.css('display', '');
          targetList.append(createFileItem(file, link));
        }
      }
    };

    addFiles(responseBody.attachments, attachmentList);
    addFiles(responseBody.tempFiles, tempFileList);
  });

  fileAttachment = textarea.siblings('.file-attachment');
  if (fileAttachment.length <= 0) {
    fileAttachment = textarea.parent().siblings('.file-attachment');
  }
  if (fileAttachment.length <= 0) {
    fileAttachment = $('
').addClass('file-attachment');
    textarea.after(fileAttachment);
  }

  fileAttachment
    .append(notification)
    .append(attachment)
    .append(progress)
    .append(attachmentList)
    .append(tempFileList);
}

var fileDownloader = function (div, urlToGetFileList) {
  var createFileItem = function(file) {
    var link = $('')
        .prop('href', file.url)
        .append($('').addClass('icon-download'))
        .append($('
').text(file.name).html());

    return $('
').append(link);
  }

  var filelist = $('
');
  var addFiles = function(responseBody, statusText, xhr) {
    var files = responseBody.attachments;
    for (var i = 0; i < files.length; i++) {
      filelist.css('display', '');
      filelist.append(createFileItem(files[i]));
    }
  }

  getFileList(div, urlToGetFileList, addFiles);

  div.after(filelist);
}

nforge.markdown.enable = function() {
  var that = {
    init: function(targets, action) {
      for(var i = 0; i < targets.length; i++) {
        var target = targets[i];
        var tagname = target.tagName.toLowerCase();
        if (tagname == 'textarea' || tagname == 'input'
                || target.contentEditable == 'true') {
          editor($(target));
          fileUploader($(target), action);
        } else {
          viewer($(target));
          fileDownloader($(target), action);
        }
      }
    }
  };

  return that;
}
<|endoftext|>


<commit_before>'use strict';

starChat.Stream = (function () {
    var Stream = function (packetProcessor) {
        this.packetProcessor_ = packetProcessor;
        this.continuingErrorNum_ = 0;
        this.ajax_ = null;
    };
    Stream.prototype.start = function (view) {
        if (this.ajax_) {
            console.error('An ajax object already exists!');
            return;
        }
        this.continuingErrorNum_ = 0;
        var self = this;
        var session = view.session();
        var streamReadIndex = 0;
        var url = '/users/' + encodeURIComponent(session.userName()) + '/stream';
        var startStream = function () {
            if (self.ajax_) {
                self.ajax_.abort();
                self.ajax_ = null;
            }
            self.start(view);
        };
        var callbacks = {
            onprogress: function () {
                console.log('Reading stream...');
                // TODO: Reconnecting if overflow
                var xhr = this;
                var text = xhr.responseText;
                var subText = text.substring(streamReadIndex);
                while (true) {
                    var tokenLength = subText.search("\n");
                    if (tokenLength === -1) {
                        break;
                    }
                    streamReadIndex += tokenLength + 1;
                    var token = subText.substring(0, tokenLength);
                    subText = subText.substring(tokenLength + 1);
                    try {
                        var packet = JSON.parse(token);
                    } catch (e) {
                        console.log(e);
                        continue;
                    }
                    self.continuingErrorNum_ = 0;
                    self.packetProcessor_.process(packet, view);
                }
                view.update();
            },
            success: function (data, textStatus, jqXHR) {
                self.continuingErrorNum_ = 0;
                setTimeout(startStream, 0);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.error('Stream Error!');
                console.error(textStatus);
                self.continuingErrorNum_++;
                if (20 <= self.ontinuingErrorNum_) {
                    console.error('Too many errors!');
                    // TODO: implement showing error message
                    return;
                }
                setTimeout(startStream, 1000);
            },
        };
        console.log('Connecting stream...');
        this.ajax_ = starChat.ajax(session.userName(), session.password(),
                                   url,
                                   'GET',
                                   callbacks);
    };
    Stream.prototype.stop = function () {
        if (!this.ajax_) {
            return;
        }
        this.continuingErrorNum_ = 0;
        this.ajax_.abort();
        this.ajax_ = null;
    };
    return Stream;
})();
<commit_msg>Moved resetting error counts<commit_after>'use strict';

starChat.Stream = (function () {
    var Stream = function (packetProcessor) {
        this.packetProcessor_ = packetProcessor;
        this.continuingErrorNum_ = 0;
        this.ajax_ = null;
    };
    Stream.prototype.start = function (view) {
        if (this.ajax_) {
            console.error('An ajax object already exists!');
            return;
        }
        this.continuingErrorNum_ = 0;
        var self = this;
        var session = view.session();
        var streamReadIndex = 0;
        var url = '/users/' + encodeURIComponent(session.userName()) + '/stream';
        var startStream = function () {
            if (self.ajax_) {
                self.ajax_.abort();
                self.ajax_ = null;
            }
            self.start(view);
        };
        var callbacks = {
            onprogress: function () {
                console.log('Reading stream...');
                self.continuingErrorNum_ = 0;
                // TODO: Reconnecting if overflow
                var xhr = this;
                var text = xhr.responseText;
                var subText = text.substring(streamReadIndex);
                while (true) {
                    var tokenLength = subText.search("\n");
                    if (tokenLength === -1) {
                        break;
                    }
                    streamReadIndex += tokenLength + 1;
                    var token = subText.substring(0, tokenLength);
                    subText = subText.substring(tokenLength + 1);
                    try {
                        var packet = JSON.parse(token);
                    } catch (e) {
                        console.log(e);
                        continue;
                    }
                    self.packetProcessor_.process(packet, view);
                }
                view.update();
            },
            success: function (data, textStatus, jqXHR) {
                self.continuingErrorNum_ = 0;
                setTimeout(startStream, 0);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.error('Stream Error!');
                console.error(textStatus);
                self.continuingErrorNum_++;
                if (20 <= self.ontinuingErrorNum_) {
                    console.error('Too many errors!');
                    // TODO: implement showing error message
                    return;
                }
                setTimeout(startStream, 1000);
            },
        };
        console.log('Connecting stream...');
        this.ajax_ = starChat.ajax(session.userName(), session.password(),
                                   url,
                                   'GET',
                                   callbacks);
    };
    Stream.prototype.stop = function () {
        if (!this.ajax_) {
            return;
        }
        this.continuingErrorNum_ = 0;
        this.ajax_.abort();
        this.ajax_ = null;
    };
    return Stream;
})();
<|endoftext|>


<commit_before><commit_msg>hue offset<commit_after><|endoftext|>


<commit_before>(function() {
  d3.selection.prototype.moveToFront = function() {
      return this.each(function(){
        this.parentNode.appendChild(this);
      });
  };

  d3.selection.prototype.moveToBack = function() {
      return this.each(function() {
          var firstChild = this.parentNode.firstChild;
          if (firstChild) {
              this.parentNode.insertBefore(this, firstChild);
          }
      });
  };

  BridgesVisualizer.defaultColors = d3.scaleOrdinal(d3.schemeCategory20);

  BridgesVisualizer.strokeWidthRange = d3.scaleLinear().domain([1,10]).range([1,15]).clamp(true);
  //scale values between 1 and 100 to a reasonable range
  BridgesVisualizer.scaleSize = d3.scaleLinear().domain([1,50]).range([10,500]);
  BridgesVisualizer.shapeEdge = d3.scaleLinear().domain([1,50]).range([0.5,3.3]);
  BridgesVisualizer.selfEdge = d3.scaleLinear().domain([1,50]).range([3,13]);

  // Define the div for the tooltip
  BridgesVisualizer.tooltip = d3.select("body").append("div")
      .attr("class", "tooltip")
      .classed("shown", false)
      .style("pointer-events", "none")
      .style("opacity", 0);

  // Offsets for text labels for visualization types
  BridgesVisualizer.textOffsets = {
    "graph": { "x": 10, "y": -5 },
    "tree": { "x": 200, "y": -15 },
    "default": { "x": 0, "y": 0}
  };

  BridgesVisualizer.treeDashArray = "3px, 3px";

  // Keep track of the center of the default vis window
  BridgesVisualizer.visCenter = function() {
    return [document.getElementById("vis0").clientWidth/3 || 0,
            document.getElementById("vis0").clientHeight/2 || 0];
  };

  // Default scale and transform values for each data structure
  BridgesVisualizer.defaultTransforms = {
    "Alist": { "scale": 0.4, "translate": [20, 100]},
    "array": { "scale": 0.5, "translate": [50, 100]},
    "Array2D": { "scale": 0.4, "translate": [50, 50]},
    "Array3D": { "scale": 0.4, "translate": [20, 100]},
    "list": { "scale": 0.3, "translate": [50, -5]},
    "llist": { "scale": 0.3, "translate": [50, -5]},
    "dllist": { "scale": 0.3, "translate": [50, -5]},
    "cdllist": { "scale": 0.3, "translate": [50, -5]},
    "cllist": { "scale": 0.3, "translate": [50, -5]},
    "equirectangular": { "scale": 1, "translate": [BridgesVisualizer.visCenter()[0]/3, BridgesVisualizer.visCenter()[1]/4]},
    "albersUsa": { "scale": 1, "translate": [BridgesVisualizer.visCenter()[0]/3, BridgesVisualizer.visCenter()[1]/4]},
    "nodelink": { "scale": 0.5, "translate": BridgesVisualizer.visCenter()},
    "graph": { "scale": 0.5, "translate": [BridgesVisualizer.visCenter()[0]/2, BridgesVisualizer.visCenter()[1]/2] },
    // "tree": { "scale": 0.9, "translate": [document.getElementById("vis0").clientWidth/2, 50]}
    "tree": { "scale": 0.9, "translate": [BridgesVisualizer.visCenter()[0], BridgesVisualizer.visCenter()[1]/2] }
  };

  BridgesVisualizer.getDefaultTransforms = function(visType) {
    if(BridgesVisualizer.defaultTransforms[visType]) {
      return BridgesVisualizer.defaultTransforms[visType];
    } else {
      return {"scale": 0.9, "translate": [50, 100]};
    }
  };

  // function to return color depending on the style of representation
  BridgesVisualizer.getColor = function(color) {
    if(Array.isArray(color))
      return "rgba(" + color[0] + "," + color[1] + "," + color[2] + "," + color[3] + ")";
    return color;
  };

  //this array holds the assignments types; it's used to handle the mixed assignements
  BridgesVisualizer.assignmentTypes = [];

  //this boolean is used to deactivate the tooltip when all labels are shown (key 'L')
  BridgesVisualizer.tooltipEnabled = true;
  BridgesVisualizer.showingNodeLabels = false;
  BridgesVisualizer.showingLinkLabels = false;

  BridgesVisualizer.centerTextHorizontallyInRect = function(obj, width){
      return (width - obj.getComputedTextLength()) / 2;
  };

  //add three ellipsis(...) if the text length is greater than 5
  BridgesVisualizer.getShortText = function(text){
      if(text && text.length > 5){
        return text.substr(0,4)+"...";
      }else{
        return text;
      }
  };

  // bind linebreaks to text elements
  BridgesVisualizer.insertLinebreaks = function (d, i) {
      var el = d3.select(this);
      var words = d3.select(this).text().split('\n');
      el.text('');

      for (var j = 0; j < words.length; j++) {
          var tspan = el.append('tspan').text(words[j]);
          if (j > 0)
              tspan.attr('x', 0).attr('dy', '15');
      }
  };

  // bind linebreaks to link labels
  BridgesVisualizer.insertLinkLinebreaks = function (d, i) {
      var el = d3.select(this);
      var words = d3.select(this).text().split('\n');
      el.text('');

      for (var j = 0; j < words.length; j++) {
          var tspan = el.append('tspan').text(words[j]);

          if(j>0) {
            tspan.attr('dy', '15');
          }
      }
  };

  //TODO, need unique ID for local storage
  BridgesVisualizer.getTransformObjectFromLocalStorage = function(visID) {

  };

  BridgesVisualizer.addMarkerDefs = function(svg) {
    var markers = [
       { id: 0, name: 'circle', path: 'M 0, 0  m -5, 0  a 5,5 0 1,0 10,0  a 5,5 0 1,0 -10,0', viewbox: '-6 -6 12 12' },
       { id: 1, name: 'square', path: 'M 0,0 m -5,-5 L 5,-5 L 5,5 L -5,5 Z', viewbox: '-5 -5 10 10' },
       { id: 2, name: 'arrow', path: 'M 0,0 m -5,-5 L 5,0 L -5,5 Z', viewbox: '-5 -5 10 10' },
       { id: 2, name: 'stub', path: 'M 0,0 m -1,-5 L 1,-5 L 1,5 L -1,5 Z', viewbox: '-1 -5 2 10' }
    ];

    // var defs = d3.select("#assignmentCanvas").append('svg:defs');
    var defs = svg.append('svg:defs');

    var marker = defs.selectAll('marker')
     .data(markers)
     .enter()
     .append('svg:marker')
       .attr('id', function(d){ return 'marker_' + d.name; })
       .attr("markerUnits", "userSpaceOnUse")
      //  .attr("markerUnits", "strokeWidth")
       .attr('markerHeight', 5)
       .attr('markerWidth', 5)
       .style("pointer-events", "none")
       .attr('orient', 'auto')
       .attr('refX', 0)
       .attr('refY', 0)
       .attr('viewBox', function(d){ return d.viewbox; })
       .append('svg:path')
         .attr('d', function(d){ return d.path; })
         .attr('fill', function(d,i) { return "#ccc"; });
  };

  // Add newly-styled markers to the defs for the given svg
  // BridgesVisualizer.marker = function(svg, color, otherAttr) {
  //     console.log('making marker', color);
  //     var val;
  //     svg.select("svg:defs").selectAll("marker")
  //          .data([val])
  //          .enter().append("svg:marker")
  //          .attr("id", String)
  //          .attr("viewBox", "0 -5 10 10")
  //          .attr("refX", 20)
  //          .attr("refY", 0)
  //          .attr("markerWidth", 6)
  //          .attr("markerHeight", 6)
  //          .attr("orient", "auto")
  //          .style("fill", color)
  //          .append("svg:path")
  //          .attr("d", "M0,-5L10,0L0,5");
  //     return "url(#" +val+ ")";
  // };

  // function to return the transformObject saved positions
  BridgesVisualizer.getTransformObjectFromCookie = function(visID) {
          var name = "vis"+visID+"-"+location.pathname + "=";
          // var name = cname + "=";
          var ca = document.cookie.split(';');
          // console.log(ca);
          for(var i=0; i<ca.length; i++) {
              var c = ca[i];
              while (c.charAt(0)==' ') {
                  c = c.substring(1);
              }
              if (c.indexOf(name) === 0) {
                  // return c.substring(name.length, c.length);
                  var cookieStringValue = c.substring(name.length, c.length);
                  var cookieJSONValue;
                  try{
                      cookieJSONValue = JSON.parse(cookieStringValue);
                  }catch(err){
                      console.log(err, cookieStringValue);
                  }

                  if(cookieJSONValue){
                    if(cookieJSONValue.hasOwnProperty("translatex") &&
                       cookieJSONValue.hasOwnProperty("translatey") &&
                       cookieJSONValue.hasOwnProperty("scale")){
                         var finalTranslate = [parseFloat(cookieJSONValue.translatex), parseFloat(cookieJSONValue.translatey)];
                         var finalScale = [parseFloat(cookieJSONValue.scale)];
                         return {"translate":finalTranslate, "scale":finalScale};
                    }
                  }else{
                    return undefined;
                  }
              }
          }
          return "";
  };

  BridgesVisualizer.textMouseover = function(label) {
      function addLineBreaks(str) {
        str = str.split("\n");
        str = str.join("<br>");
        return str;
      }

      if(!BridgesVisualizer.tooltipEnabled || label === "") return;
      BridgesVisualizer.tooltip.transition()
          .duration(200)
          .style("opacity", 0.9);
      BridgesVisualizer.tooltip.html(addLineBreaks(label))
          .style("left", (d3.event.pageX) + "px")
          .style("top", (d3.event.pageY) + "px");
      };

  BridgesVisualizer.textMouseout = function(d) {
      BridgesVisualizer.tooltip.transition()
          .duration(500)
          .style("opacity", 0);
  };

  BridgesVisualizer.shapeLookup = function(shape) {
    switch(shape) {
      case 'circle':
        return d3.symbolCircle;
      case 'square':
        return d3.symbolSquare;
      case 'diamond':
        return d3.symbolDiamond;
      case 'triangle':
        return d3.symbolTriangle;
      case 'cross':
        return d3.symbolCross;
      case 'star':
        return d3.symbolStar;
      case 'wye':
        return d3.symbolWye;
      default:
        return d3.symbolCircle;
    }
  };

  BridgesVisualizer.projLookup = function(proj) {
    switch(proj) {
      case 'equirectangular':
        return d3.geoEquirectangular();
      default:
        return d3.geoEquirectangular();
    }
  };

  BridgesVisualizer.displayNodeLabels = function() {
    if(d3.event) d3.event.preventDefault();
    if(!BridgesVisualizer.showingNodeLabels) {
        d3.selectAll(".nodeLabel").style("display","block").style("opacity","1");
        BridgesVisualizer.showingNodeLabels = true;
    } else {
        d3.selectAll(".nodeLabel").style("display","none").style("opacity","0");
        BridgesVisualizer.showingNodeLabels = false;
    }
    BridgesVisualizer.redraw();
  };

  BridgesVisualizer.displayLinkLabels = function() {
    if(d3.event) d3.event.preventDefault();
    if(!BridgesVisualizer.showingLinkLabels) {
        d3.selectAll(".linkLabel").style("display", "block");
        d3.selectAll(".selfLinkLabel").style("display", "block");
        BridgesVisualizer.showingLinkLabels = true;
    } else {
        d3.selectAll(".linkLabel").style("display", "none");
        d3.selectAll(".selfLinkLabel").style("display", "none");
        BridgesVisualizer.showingLinkLabels = false;
    }
    BridgesVisualizer.redraw();
  };

  // trigger redrawing of visualizations where appropriate
  BridgesVisualizer.redraw = function() {
    for(var vis in this.visualizations) {
      if(this.visualizations[vis].draw)
        this.visualizations[vis].draw();
    }
  };

  $("body").on("keydown", function(event) {
      if(event.which == "76"){
        BridgesVisualizer.displayNodeLabels();
        BridgesVisualizer.displayLinkLabels();
      }
  });

})();
<commit_msg>SVG link markers scale with line stroke width<commit_after>(function() {
  d3.selection.prototype.moveToFront = function() {
      return this.each(function(){
        this.parentNode.appendChild(this);
      });
  };

  d3.selection.prototype.moveToBack = function() {
      return this.each(function() {
          var firstChild = this.parentNode.firstChild;
          if (firstChild) {
              this.parentNode.insertBefore(this, firstChild);
          }
      });
  };

  BridgesVisualizer.defaultColors = d3.scaleOrdinal(d3.schemeCategory20);

  BridgesVisualizer.strokeWidthRange = d3.scaleLinear().domain([1,10]).range([1,15]).clamp(true);
  //scale values between 1 and 100 to a reasonable range
  BridgesVisualizer.scaleSize = d3.scaleLinear().domain([1,50]).range([10,500]);
  BridgesVisualizer.shapeEdge = d3.scaleLinear().domain([1,50]).range([0.5,3.3]);
  BridgesVisualizer.selfEdge = d3.scaleLinear().domain([1,50]).range([3,13]);

  // Define the div for the tooltip
  BridgesVisualizer.tooltip = d3.select("body").append("div")
      .attr("class", "tooltip")
      .classed("shown", false)
      .style("pointer-events", "none")
      .style("opacity", 0);

  // Offsets for text labels for visualization types
  BridgesVisualizer.textOffsets = {
    "graph": { "x": 10, "y": -5 },
    "tree": { "x": 200, "y": -15 },
    "default": { "x": 0, "y": 0}
  };

  BridgesVisualizer.treeDashArray = "3px, 3px";

  // Keep track of the center of the default vis window
  BridgesVisualizer.visCenter = function() {
    return [document.getElementById("vis0").clientWidth/3 || 0,
            document.getElementById("vis0").clientHeight/2 || 0];
  };

  // Default scale and transform values for each data structure
  BridgesVisualizer.defaultTransforms = {
    "Alist": { "scale": 0.4, "translate": [20, 100]},
    "array": { "scale": 0.5, "translate": [50, 100]},
    "Array2D": { "scale": 0.4, "translate": [50, 50]},
    "Array3D": { "scale": 0.4, "translate": [20, 100]},
    "list": { "scale": 0.3, "translate": [50, -5]},
    "llist": { "scale": 0.3, "translate": [50, -5]},
    "dllist": { "scale": 0.3, "translate": [50, -5]},
    "cdllist": { "scale": 0.3, "translate": [50, -5]},
    "cllist": { "scale": 0.3, "translate": [50, -5]},
    "equirectangular": { "scale": 1, "translate": [BridgesVisualizer.visCenter()[0]/3, BridgesVisualizer.visCenter()[1]/4]},
    "albersUsa": { "scale": 1, "translate": [BridgesVisualizer.visCenter()[0]/3, BridgesVisualizer.visCenter()[1]/4]},
    "nodelink": { "scale": 0.5, "translate": BridgesVisualizer.visCenter()},
    "graph": { "scale": 0.5, "translate": [BridgesVisualizer.visCenter()[0]/2, BridgesVisualizer.visCenter()[1]/2] },
    // "tree": { "scale": 0.9, "translate": [document.getElementById("vis0").clientWidth/2, 50]}
    "tree": { "scale": 0.9, "translate": [BridgesVisualizer.visCenter()[0], BridgesVisualizer.visCenter()[1]/2] }
  };

  BridgesVisualizer.getDefaultTransforms = function(visType) {
    if(BridgesVisualizer.defaultTransforms[visType]) {
      return BridgesVisualizer.defaultTransforms[visType];
    } else {
      return {"scale": 0.9, "translate": [50, 100]};
    }
  };

  // function to return color depending on the style of representation
  BridgesVisualizer.getColor = function(color) {
    if(Array.isArray(color))
      return "rgba(" + color[0] + "," + color[1] + "," + color[2] + "," + color[3] + ")";
    return color;
  };

  //this array holds the assignments types; it's used to handle the mixed assignements
  BridgesVisualizer.assignmentTypes = [];

  //this boolean is used to deactivate the tooltip when all labels are shown (key 'L')
  BridgesVisualizer.tooltipEnabled = true;
  BridgesVisualizer.showingNodeLabels = false;
  BridgesVisualizer.showingLinkLabels = false;

  BridgesVisualizer.centerTextHorizontallyInRect = function(obj, width){
      return (width - obj.getComputedTextLength()) / 2;
  };

  //add three ellipsis(...) if the text length is greater than 5
  BridgesVisualizer.getShortText = function(text){
      if(text && text.length > 5){
        return text.substr(0,4)+"...";
      }else{
        return text;
      }
  };

  // bind linebreaks to text elements
  BridgesVisualizer.insertLinebreaks = function (d, i) {
      var el = d3.select(this);
      var words = d3.select(this).text().split('\n');
      el.text('');

      for (var j = 0; j < words.length; j++) {
          var tspan = el.append('tspan').text(words[j]);
          if (j > 0)
              tspan.attr('x', 0).attr('dy', '15');
      }
  };

  // bind linebreaks to link labels
  BridgesVisualizer.insertLinkLinebreaks = function (d, i) {
      var el = d3.select(this);
      var words = d3.select(this).text().split('\n');
      el.text('');

      for (var j = 0; j < words.length; j++) {
          var tspan = el.append('tspan').text(words[j]);

          if(j>0) {
            tspan.attr('dy', '15');
          }
      }
  };

  //TODO, need unique ID for local storage
  BridgesVisualizer.getTransformObjectFromLocalStorage = function(visID) {

  };

  BridgesVisualizer.addMarkerDefs = function(svg) {
    var markers = [
       { id: 0, name: 'circle', path: 'M 0, 0  m -5, 0  a 5,5 0 1,0 10,0  a 5,5 0 1,0 -10,0', viewbox: '-6 -6 12 12' },
       { id: 1, name: 'square', path: 'M 0,0 m -5,-5 L 5,-5 L 5,5 L -5,5 Z', viewbox: '-5 -5 10 10' },
       { id: 2, name: 'arrow', path: 'M 0,0 m -5,-5 L 5,0 L -5,5 Z', viewbox: '-5 -5 10 10' },
       { id: 2, name: 'stub', path: 'M 0,0 m -1,-5 L 1,-5 L 1,5 L -1,5 Z', viewbox: '-1 -5 2 10' }
    ];

    // var defs = d3.select("#assignmentCanvas").append('svg:defs');
    var defs = svg.append('svg:defs');

    var marker = defs.selectAll('marker')
     .data(markers)
     .enter()
     .append('svg:marker')
       .attr('id', function(d){ return 'marker_' + d.name; })
       .attr("markerUnits", "strokeWidth")
       .attr('markerHeight', 3)
       .attr('markerWidth', 2)
       .style("pointer-events", "none")
       .attr('orient', 'auto')
       .attr('refX', 0)
       .attr('refY', 0)
       .attr('viewBox', function(d){ return d.viewbox; })
       .append('svg:path')
         .attr('d', function(d){ return d.path; })
         .attr('fill', function(d,i) { return "#ccc"; });
  };

  // Add newly-styled markers to the defs for the given svg
  // BridgesVisualizer.marker = function(svg, color, otherAttr) {
  //     console.log('making marker', color);
  //     var val;
  //     svg.select("svg:defs").selectAll("marker")
  //          .data([val])
  //          .enter().append("svg:marker")
  //          .attr("id", String)
  //          .attr("viewBox", "0 -5 10 10")
  //          .attr("refX", 20)
  //          .attr("refY", 0)
  //          .attr("markerWidth", 6)
  //          .attr("markerHeight", 6)
  //          .attr("orient", "auto")
  //          .style("fill", color)
  //          .append("svg:path")
  //          .attr("d", "M0,-5L10,0L0,5");
  //     return "url(#" +val+ ")";
  // };

  // function to return the transformObject saved positions
  BridgesVisualizer.getTransformObjectFromCookie = function(visID) {
          var name = "vis"+visID+"-"+location.pathname + "=";
          // var name = cname + "=";
          var ca = document.cookie.split(';');
          // console.log(ca);
          for(var i=0; i<ca.length; i++) {
              var c = ca[i];
              while (c.charAt(0)==' ') {
                  c = c.substring(1);
              }
              if (c.indexOf(name) === 0) {
                  // return c.substring(name.length, c.length);
                  var cookieStringValue = c.substring(name.length, c.length);
                  var cookieJSONValue;
                  try{
                      cookieJSONValue = JSON.parse(cookieStringValue);
                  }catch(err){
                      console.log(err, cookieStringValue);
                  }

                  if(cookieJSONValue){
                    if(cookieJSONValue.hasOwnProperty("translatex") &&
                       cookieJSONValue.hasOwnProperty("translatey") &&
                       cookieJSONValue.hasOwnProperty("scale")){
                         var finalTranslate = [parseFloat(cookieJSONValue.translatex), parseFloat(cookieJSONValue.translatey)];
                         var finalScale = [parseFloat(cookieJSONValue.scale)];
                         return {"translate":finalTranslate, "scale":finalScale};
                    }
                  }else{
                    return undefined;
                  }
              }
          }
          return "";
  };

  BridgesVisualizer.textMouseover = function(label) {
      function addLineBreaks(str) {
        str = str.split("\n");
        str = str.join("<br>");
        return str;
      }

      if(!BridgesVisualizer.tooltipEnabled || label === "") return;
      BridgesVisualizer.tooltip.transition()
          .duration(200)
          .style("opacity", 0.9);
      BridgesVisualizer.tooltip.html(addLineBreaks(label))
          .style("left", (d3.event.pageX) + "px")
          .style("top", (d3.event.pageY) + "px");
      };

  BridgesVisualizer.textMouseout = function(d) {
      BridgesVisualizer.tooltip.transition()
          .duration(500)
          .style("opacity", 0);
  };

  BridgesVisualizer.shapeLookup = function(shape) {
    switch(shape) {
      case 'circle':
        return d3.symbolCircle;
      case 'square':
        return d3.symbolSquare;
      case 'diamond':
        return d3.symbolDiamond;
      case 'triangle':
        return d3.symbolTriangle;
      case 'cross':
        return d3.symbolCross;
      case 'star':
        return d3.symbolStar;
      case 'wye':
        return d3.symbolWye;
      default:
        return d3.symbolCircle;
    }
  };

  BridgesVisualizer.projLookup = function(proj) {
    switch(proj) {
      case 'equirectangular':
        return d3.geoEquirectangular();
      default:
        return d3.geoEquirectangular();
    }
  };

  BridgesVisualizer.displayNodeLabels = function() {
    if(d3.event) d3.event.preventDefault();
    if(!BridgesVisualizer.showingNodeLabels) {
        d3.selectAll(".nodeLabel").style("display","block").style("opacity","1");
        BridgesVisualizer.showingNodeLabels = true;
    } else {
        d3.selectAll(".nodeLabel").style("display","none").style("opacity","0");
        BridgesVisualizer.showingNodeLabels = false;
    }
    BridgesVisualizer.redraw();
  };

  BridgesVisualizer.displayLinkLabels = function() {
    if(d3.event) d3.event.preventDefault();
    if(!BridgesVisualizer.showingLinkLabels) {
        d3.selectAll(".linkLabel").style("display", "block");
        d3.selectAll(".selfLinkLabel").style("display", "block");
        BridgesVisualizer.showingLinkLabels = true;
    } else {
        d3.selectAll(".linkLabel").style("display", "none");
        d3.selectAll(".selfLinkLabel").style("display", "none");
        BridgesVisualizer.showingLinkLabels = false;
    }
    BridgesVisualizer.redraw();
  };

  // trigger redrawing of visualizations where appropriate
  BridgesVisualizer.redraw = function() {
    for(var vis in this.visualizations) {
      if(this.visualizations[vis].draw)
        this.visualizations[vis].draw();
    }
  };

  $("body").on("keydown", function(event) {
      if(event.which == "76"){
        BridgesVisualizer.displayNodeLabels();
        BridgesVisualizer.displayLinkLabels();
      }
  });

})();
<|endoftext|>


<commit_before>/*global popit:false console:false */
define(['jquery', 'Backbone', 'underscore'], function($, Backbone, _) {
  "use strict";

  var EditView = Backbone.View.extend({
    events: {
      'click .entity-enter-edit-mode': 'enterEditMode',
      'click .entity-leave-edit-mode': 'cancelEdit',
      'click .entity-save-changes': 'saveChanges',
      'click .entity-delete': 'deleteConfirm'
    },

    constructor: function(options) {
      Backbone.View.apply(this, arguments);
      this.fields = options.fields || [];
      $('.edit-form').hide();
    },

    enterEditMode: function(e) {
      e.preventDefault();
      $('.view-mode').hide();
      $('.edit-mode').show();
      $('article.entity').hide();
      $('.edit-form .entity-details').easytabs('select', window.location.hash);
      $('.edit-form').show();
      $('.entity').addClass('editing');

      var inputToFocus = $(e.target).data('input-selector');
      if (inputToFocus !== '') {
        $(inputToFocus).focus();
      }
    },

    cancelEdit: function(e) {
      e.preventDefault();
      this.leaveEditMode();
    },

    saveChanges: function(arg) {
      this.toggleSavingButton();
      $('form.entity').submit();
    },

    leaveEditMode: function() {
      $('.view-mode').show();
      $('.edit-mode').hide();
      $('.edit-form').hide();
      $('article.entity').show();
      $('.entity').removeClass('editing');
      this.resetErrorStates();
    },

    resetErrorStates: function() {
      $('.edit-mode-error').hide();
      $('.has-error').removeClass('has-error');
      $('.alert.backbone-error').slideUp(100);
    },

    toggleSavingButton: function(){
      var newHtml;
      var $btn = $('.entity-save-changes');
      if($btn.is('.btn-loading')){
        newHtml = $btn.html().replace('Saving changes', 'Save changes');
        $btn.removeClass('btn-loading');
        $btn.html(newHtml);
      } else {
        newHtml = $btn.html().replace('Save changes', 'Saving changes');
        $btn.addClass('btn-loading');
        $btn.html(newHtml);
      }
    },

    deleteConfirm: function() {
      if ( window.confirm('Are you sure you want to delete ' + popit.model.get('name')) ) {
        this.deleteObject();
      }
    },

    deleteObject: function() {
      var _this = this;
      popit.model.destroy({
        success: function() {
          window.location = '/' + popit.type + 's';
        },
        error: function(model, response) {
          _this.showBackboneError('There was a problem deleting this ' + popit.type + '.');
        }
      });
    },

    showBackboneError: function(msg) {
      var $alert = $('

' + msg + ' Please try again.

');
      $alert.hide().insertBefore('.entity').slideDown(100);
    }
  });

  return EditView;
});
<commit_msg>Always match active tab when switching to edit view<commit_after>/*global popit:false console:false */
define(['jquery', 'Backbone', 'underscore'], function($, Backbone, _) {
  "use strict";

  var EditView = Backbone.View.extend({
    events: {
      'click .entity-enter-edit-mode': 'enterEditMode',
      'click .entity-leave-edit-mode': 'cancelEdit',
      'click .entity-save-changes': 'saveChanges',
      'click .entity-delete': 'deleteConfirm'
    },

    constructor: function(options) {
      Backbone.View.apply(this, arguments);
      this.fields = options.fields || [];
      $('.edit-form').hide();
    },

    enterEditMode: function(e) {
      e.preventDefault();
      $('.view-mode').hide();
      $('.edit-mode').show();
      $('article.entity').hide();
      var tab = $('.person-view .entity-details li.active');
      if ( tab ) {
        $('.edit-form .entity-details').easytabs('select', tab.children('a').attr('href'));
      }
      $('.edit-form').show();
      $('.entity').addClass('editing');

      var inputToFocus = $(e.target).data('input-selector');
      if (inputToFocus !== '') {
        $(inputToFocus).focus();
      }
    },

    cancelEdit: function(e) {
      e.preventDefault();
      this.leaveEditMode();
    },

    saveChanges: function(arg) {
      this.toggleSavingButton();
      $('form.entity').submit();
    },

    leaveEditMode: function() {
      $('.view-mode').show();
      $('.edit-mode').hide();
      $('.edit-form').hide();
      $('article.entity').show();
      $('.entity').removeClass('editing');
      this.resetErrorStates();
    },

    resetErrorStates: function() {
      $('.edit-mode-error').hide();
      $('.has-error').removeClass('has-error');
      $('.alert.backbone-error').slideUp(100);
    },

    toggleSavingButton: function(){
      var newHtml;
      var $btn = $('.entity-save-changes');
      if($btn.is('.btn-loading')){
        newHtml = $btn.html().replace('Saving changes', 'Save changes');
        $btn.removeClass('btn-loading');
        $btn.html(newHtml);
      } else {
        newHtml = $btn.html().replace('Save changes', 'Saving changes');
        $btn.addClass('btn-loading');
        $btn.html(newHtml);
      }
    },

    deleteConfirm: function() {
      if ( window.confirm('Are you sure you want to delete ' + popit.model.get('name')) ) {
        this.deleteObject();
      }
    },

    deleteObject: function() {
      var _this = this;
      popit.model.destroy({
        success: function() {
          window.location = '/' + popit.type + 's';
        },
        error: function(model, response) {
          _this.showBackboneError('There was a problem deleting this ' + popit.type + '.');
        }
      });
    },

    showBackboneError: function(msg) {
      var $alert = $('

' + msg + ' Please try again.

');
      $alert.hide().insertBefore('.entity').slideDown(100);
    }
  });

  return EditView;
});
<|endoftext|>


<commit_before>var WorkspaceService = new function() {
	var instance = null;
	var ajaxService = null;
	var authService = null;
	var loggingService = null;

	var functions = {
		addFolderToMenu: function( jsonObject, $list ) {
			for ( key in jsonObject ) {
				if ( isNaN( key ) ) {
					var $sublist = $( "
" );

					$( "
" )
						.append( $("", { class: "fa fa-folder subfolder" } ) )
						.append( $( "", { html: key } ) )
						.append( $( "", { class: "new-folder" } ) )
						.find( ".new-folder" )
							.append( $( "", { class: "fa fa-folder" } ) )
							.append( $( "", { class: "fa fa-plus" } ) )
						.end()
						.append( $sublist )
						.appendTo( $list );

					this.addFolderToMenu( jsonObject[ key ], $sublist );
				}
			}

			for ( key in jsonObject ) {
				if ( !isNaN( key ) ) {
					$( "
" )
						.append( $( "", { class: "fa fa-file" } ) )
						.append( $( "", { html: jsonObject[ key ] } ) )
						.appendTo( $list );
				}
			}
		}
		, buildMenu: function( jsonObject ) {
			var $menu = $( "
 ", { class: "menu flexbox-v" } )
				.append( $( "
", { class: "search" } ) )
				.append( $( "
", { class: "content flexible-v" } ) )
				.append( $( "
", { class: "control center inflexible" } ) );

			$menu.find( ".search" )
				.append( $( "
" ) )
				.find( ":last-child" )
					.append( $( "
", { class: "search-container" } ) )
					.find( "> :last-child" )
						.append( $( "", { class: "fa fa-search" } ) )
						.end()
					.append( $( "
", { class: "pattern-container" } ) )
					.find( "> :last-child" )
						.append( $( "<input>", { class: "pattern" } ) );

			$menu.find( ".content" )
				.append( $( "
", { class: "directoryStructure" } ));

			$menu.find( ".control" )
				.append( $( "", { class: "fa fa-angle-double-up" } ));

			$menu.find( ".directoryStructure" )
				.append( $( "
", { class: "root" } ) )
				.find( ":last-child" )
					.append( $( "", { class: "fa fa-folder" } ) )
					.append( $( "", { html: "root" } ) )
					.append( $( "", { class: "new-folder" } ) )
					.find( ".new-folder" )
						.append( $( "", { class: "fa fa-folder" } ) )
						.append( $( "", { class: "fa fa-plus" } ) )
					.end()
					.append( $( "
" ) );

			this.addFolderToMenu( jsonObject, $menu.find( ".directoryStructure li ul" ) );

			var parent = this;

			$( ".container .menu" ).remove();
			$( ".container" ).append($menu);
			$( ".container .menu .control" ).click( function() {
				$( ".container .menu" ).remove();
			} );
			$( ".container .menu .search input" ).keyup( parent.filterMenu );
			$( ".container .menu .search-container ").mouseover( function() {
				$( ".tip-search" ).show();
			} );
			$( ".container .menu .search-container ").mouseout( function() {
				$( ".tip-search" ).hide();
			} );
			$( ".container .menu .new-folder" ).click( parent.displayNewFolder );
		}
		, displayMenu: function() {
			var parent = this;

			ajaxService.GET({
				url: "?menu/list"
				, fnSuccess: parent.processDisplayMenu
				, fnFailure: loggingService.recoverableError
			});
		}
		, displayNewFolder: function() {
			var parent = this;

			ajaxService.GET({
				url: "public/views/prompt.html"
				, fnSuccess: function( rawHtml ) { parent.processDisplayNewDirectory( parent, rawHtml ); }
				, fnFailure: loggingService.recoverableError
			});
		}
		, filterMenu: function( event ) {
			var $filter = $( this );
			var pattern = $filter.val().trim().replace( /[%]/g, "[\\S]*" ).replace( /[_]/g, "[\\S]" );
			var $menu = $( ".container .menu .content .directoryStructure .root > ul" );

			try {
				$menu.find( "li" ).show();

				if ( pattern.length > 0 ) {
					if ( pattern.charAt( 0 ) != "^" ) {
						pattern = "^"+ pattern;
					}

					if ( pattern.charAt( pattern.length - 1 ) != "$" ) {
						pattern += "$";
					}

					var matcher = new RegExp( pattern );

					$menu.find( "li" ).hide();

					$menu.find( ".fa-file" ).next().each( function() {
						if ( matcher.test( $( this ).html() ) ) {
							var $parent = $( this ).parent();

							do {
								$parent.show();

								$parent = $parent.parent().parent();
							} while ( $parent.prop( "tagName" ) == "LI" );
						}
					} );

					$menu.find( ".fa-folder" ).next().each( function() {
						if ( matcher.test( $( this ).html() ) ) {
							var $parent = $( this ).parent();

							$parent.find( "li" ).show();

							do {
								$parent.show();

								$parent = $parent.parent().parent();
							} while ( $parent.prop( "tagName" ) == "LI" );
						}
					} );
				}
			} catch ( e ) {
				$menu.find( "li" ).hide();
			}
		}
		, processDisplayMenu: function( jsonString ) {
			try {
				Require.all( jsonString );

				var jsonObject = $.parseJSON( jsonString );

				Require.all( jsonObject, "files", "responseCode" );

				var parent = this;

				var fnBuildMenu = function() {
					parent.buildMenu( jsonObject.files );
				};

				var fnRedirectToLogin = function() {
					authService.displayLogin();
					loggingService.displayInfo( "Session Expired" );
				};

				authService.processResponseCode({
					responseCode: jsonObject.responseCode
					, fnAuthorized: fnBuildMenu
					, fnUnauthorized: fnRedirectToLogin
				});
			} catch ( error ) {
				loggingService.recoverableError( error );
			}
		}
		, processDisplayNewDirectory: function( object, rawHtml ) {
			try {
				Require.all( rawHtml );

				var $relatedDirectory = $( object ).parent();
				var $parent = $( "
", { class: "existing-directory center" } );
				var $directoryInput = $( "
<input type='text' placeholder='new directory' id='directory' value='' />
" );
				var directories = new Array();

				while ( $relatedDirectory.find( "> .fa-folder" ).length ) {
					directories.push( $relatedDirectory.find( "> .fa-folder" ).next().html() );
					$relatedDirectory = $relatedDirectory.parent().parent();
				}

				var $prompt = $( rawHtml );
				$prompt.addClass( "prompt-container-overlay" );
				$prompt.find( ".title" ).append( $( "", { class: "fa fa-times close" } ) );
				$prompt.find( ".content" ).append( $( "
", { class: "existing-directory center" } ) );
				$prompt.find( ".content" ).append( $directoryInput );

				$( ".container" ).append( $prompt );
				$directoryInput.find( "#directory" ).focus();

				$prompt.find( ".close" ).click( function() {
					$prompt.remove();
				} );
			} catch ( error ) {
				loggingService.recoverableError( error );
			}
		}
		, processDisplayWorkspace: function( rawHtml ) {
			var parent = this;
console.log( parent );
			try {
				Require.all( rawHtml );

				$( ".container" ).html( rawHtml );
				$( ".container .menuIndicator" ).mouseover( parent.displayMenu );
				$( ".container .logout" ).click( authService.logout );
			} catch ( error ) {
				loggingService.unrecoverableError( error );
			}
		}
	};

	var buildApi = function( functions ) {
		ajaxService = AjaxService.getInstance();
		authService = AuthService.getInstance();
		loggingService = LoggingService.getInstance();

		return {
			displayWorkspace: function() {
				ajaxService.GET({
					url: "public/views/workspace.html"
					, fnSuccess: functions.processDisplayWorkspace
					, fnFailure: loggingService.unrecoverableError
				});
			}
		};
	};

	return {
		getInstance: function() {
			if ( instance != null ) {
				return instance;
			}

			instance = buildApi( functions );

			return instance;
		}
		, getTestInstance: function() {
			var functionsClone = Require.clone( functions );
			var instance = buildApi( functionsClone );

			instance.privateFunctions = functionsClone;

			return instance;
		}
	};
}();

/*

var EDITOR = {
	actionCreateFilePrompt: function(path, ajaxService){
		ajaxService.GET('public/views/prompt.html', {
			fnSuccess: function(data){ EDITOR.processFileCreatePrompt(data, path, ajaxService); }
			,fnFailure: EDITOR.recoverableError
		});
	}
	,actionSubmitCreateFilePrompt: function(e, path, ajaxService){
		if (EDITOR.KeyTest.isEnter(e)){
			var filename = $('.prompt #filename').val();
			var filenamePattern = /^[a-zA-Z][a-zA-Z0-9._-]*[.][a-zA-Z0-9]+$/;

			if (filenamePattern.test(filename)){
				path.push(filename);

				ajaxService.POST('?file/create', { file: path }, {
					fnSuccess: function(data){
						EDITOR.displayInfo(data);

						$('.prompt-container').remove();
					}
					,fnFailure: EDITOR.recoverableError
				});
			} else {
				EDITOR.displayError("Invalid filename");
			}
		}
	}
	,buildFile: function($parent, path, file, ajaxService){
		//var $delete = $('');
		var $li = $('

');
		//var $newFile = $('');
		//var $newFolder = $('');
		var $ul = $('

');

		//$newFile.click(THIS.actionNewFile(path, key));
		//$newFolder.click(THIS.actionNewFolder(path, key));
		//$delete.click(THIS.actionDeleteFolder(path, key));
		//$li.click(THIS.actionToggleExpansion);

		path.push(file);

		$li.append(file)
			//.append(' ').append($newFile)
			//.append(' ').append($newFolder)
			//.append(' ').append($delete)
			.append($ul);

		$parent.append($li);
	}
	,buildFolder: function($parent, path, folder, files, ajaxService){
		//var $delete = $('');
		var $li = $('

');
		var $newFile = $('');
		//var $newFolder = $('');
		var $ul = $('

');

		path.push(folder);

		$newFile.click(function(){ EDITOR.actionCreateFilePrompt(path, ajaxService); });
		//$newFolder.click(THIS.actionNewFolder(path, key));
		//$delete.click(THIS.actionDeleteFolder(path, key));
		//$li.click(THIS.actionToggleExpansion);

		$li.append(folder).append($newFile)
			//.append(' ').append($newFolder)
			//.append(' ').append($delete)
			.append($ul);

		EDITOR.buildFileList($ul, path, files, ajaxService);

		$parent.append($li);
	}
	,buildRootFolder: function($parent, ajaxService){
		var $li = $('

');
		var $newFile = $('');
		//var $newFolder = $('');
		var $ul = $('

');

		//$newFile.click(THIS.actionNewFile(null, 'root'));
		//$newFolder.click(THIS.actionNewFolder(null, 'root'));

		$li.append('root').append($newFile)
			//.append(' ').append($newFolder)
			.append($ul);

		$parent.append($li);

		return $ul;
	}
	,processApplicationEntry: function(jsonString, ajaxService){
		try {
			var response = $.parseJSON(jsonString);

			Require.all(response, 'responseCode');

			if (response.responseCode == 'UNAUTHORIZED'){
				EDITOR.displayLogin(ajaxService);
			} else if (response.responseCode == 'AUTHORIZED'){
				EDITOR.displayWorkspace(ajaxService);
			} else {
				EDITOR.unrecoverableError();
			}
		} catch (e){
			console.log(e);
			EDITOR.unrecoverableError();
		}
	}
	,processFileCreatePrompt: function(data, path, ajaxService){
		var $prompt = $(data);
		var $content = $prompt.find('.content');

		$prompt.find('.title').html('New File');
		$content.append(
			'
'
				+'<input type="text" placeholder="filename" id="filename" value="" />'
			+'
');

		$('.container').append($prompt);
		$('.prompt .input input').keyup(function(e){ EDITOR.actionSubmitCreateFilePrompt(e, path, ajaxService); });
		$('.prompt .input input:first').focus();
	}
};

*/
<commit_msg>Added wrapper to display menu<commit_after>var WorkspaceService = new function() {
	var instance = null;
	var ajaxService = null;
	var authService = null;
	var loggingService = null;

	var functions = {
		addFolderToMenu: function( jsonObject, $list ) {
			for ( key in jsonObject ) {
				if ( isNaN( key ) ) {
					var $sublist = $( "
" );

					$( "
" )
						.append( $("", { class: "fa fa-folder subfolder" } ) )
						.append( $( "", { html: key } ) )
						.append( $( "", { class: "new-folder" } ) )
						.find( ".new-folder" )
							.append( $( "", { class: "fa fa-folder" } ) )
							.append( $( "", { class: "fa fa-plus" } ) )
						.end()
						.append( $sublist )
						.appendTo( $list );

					this.addFolderToMenu( jsonObject[ key ], $sublist );
				}
			}

			for ( key in jsonObject ) {
				if ( !isNaN( key ) ) {
					$( "
" )
						.append( $( "", { class: "fa fa-file" } ) )
						.append( $( "", { html: jsonObject[ key ] } ) )
						.appendTo( $list );
				}
			}
		}
		, buildMenu: function( jsonObject ) {
			var $menu = $( "
 ", { class: "menu flexbox-v" } )
				.append( $( "
", { class: "search" } ) )
				.append( $( "
", { class: "content flexible-v" } ) )
				.append( $( "
", { class: "control center inflexible" } ) );

			$menu.find( ".search" )
				.append( $( "
" ) )
				.find( ":last-child" )
					.append( $( "
", { class: "search-container" } ) )
					.find( "> :last-child" )
						.append( $( "", { class: "fa fa-search" } ) )
						.end()
					.append( $( "
", { class: "pattern-container" } ) )
					.find( "> :last-child" )
						.append( $( "<input>", { class: "pattern" } ) );

			$menu.find( ".content" )
				.append( $( "
", { class: "directoryStructure" } ));

			$menu.find( ".control" )
				.append( $( "", { class: "fa fa-angle-double-up" } ));

			$menu.find( ".directoryStructure" )
				.append( $( "
", { class: "root" } ) )
				.find( ":last-child" )
					.append( $( "", { class: "fa fa-folder" } ) )
					.append( $( "", { html: "root" } ) )
					.append( $( "", { class: "new-folder" } ) )
					.find( ".new-folder" )
						.append( $( "", { class: "fa fa-folder" } ) )
						.append( $( "", { class: "fa fa-plus" } ) )
					.end()
					.append( $( "
" ) );

			this.addFolderToMenu( jsonObject, $menu.find( ".directoryStructure li ul" ) );

			var parent = this;

			$( ".container .menu" ).remove();
			$( ".container" ).append($menu);
			$( ".container .menu .control" ).click( function() {
				$( ".container .menu" ).remove();
			} );
			$( ".container .menu .search input" ).keyup( parent.filterMenu );
			$( ".container .menu .search-container ").mouseover( function() {
				$( ".tip-search" ).show();
			} );
			$( ".container .menu .search-container ").mouseout( function() {
				$( ".tip-search" ).hide();
			} );
			$( ".container .menu .new-folder" ).click( parent.displayNewFolder );
		}
		, displayMenu: function() {
			var parent = this;

			ajaxService.GET({
				url: "?menu/list"
				, fnSuccess: parent.processDisplayMenu
				, fnFailure: loggingService.recoverableError
			});
		}
		, displayNewFolder: function() {
			var parent = this;

			ajaxService.GET({
				url: "public/views/prompt.html"
				, fnSuccess: function( rawHtml ) { parent.processDisplayNewDirectory( parent, rawHtml ); }
				, fnFailure: loggingService.recoverableError
			});
		}
		, filterMenu: function( event ) {
			var $filter = $( this );
			var pattern = $filter.val().trim().replace( /[%]/g, "[\\S]*" ).replace( /[_]/g, "[\\S]" );
			var $menu = $( ".container .menu .content .directoryStructure .root > ul" );

			try {
				$menu.find( "li" ).show();

				if ( pattern.length > 0 ) {
					if ( pattern.charAt( 0 ) != "^" ) {
						pattern = "^"+ pattern;
					}

					if ( pattern.charAt( pattern.length - 1 ) != "$" ) {
						pattern += "$";
					}

					var matcher = new RegExp( pattern );

					$menu.find( "li" ).hide();

					$menu.find( ".fa-file" ).next().each( function() {
						if ( matcher.test( $( this ).html() ) ) {
							var $parent = $( this ).parent();

							do {
								$parent.show();

								$parent = $parent.parent().parent();
							} while ( $parent.prop( "tagName" ) == "LI" );
						}
					} );

					$menu.find( ".fa-folder" ).next().each( function() {
						if ( matcher.test( $( this ).html() ) ) {
							var $parent = $( this ).parent();

							$parent.find( "li" ).show();

							do {
								$parent.show();

								$parent = $parent.parent().parent();
							} while ( $parent.prop( "tagName" ) == "LI" );
						}
					} );
				}
			} catch ( e ) {
				$menu.find( "li" ).hide();
			}
		}
		, processDisplayMenu: function( jsonString ) {
			try {
				Require.all( jsonString );

				var jsonObject = $.parseJSON( jsonString );

				Require.all( jsonObject, "files", "responseCode" );

				var parent = this;

				var fnBuildMenu = function() {
					parent.buildMenu( jsonObject.files );
				};

				var fnRedirectToLogin = function() {
					authService.displayLogin();
					loggingService.displayInfo( "Session Expired" );
				};

				authService.processResponseCode({
					responseCode: jsonObject.responseCode
					, fnAuthorized: fnBuildMenu
					, fnUnauthorized: fnRedirectToLogin
				});
			} catch ( error ) {
				loggingService.recoverableError( error );
			}
		}
		, processDisplayNewDirectory: function( object, rawHtml ) {
			try {
				Require.all( rawHtml );

				var $relatedDirectory = $( object ).parent();
				var $parent = $( "
", { class: "existing-directory center" } );
				var $directoryInput = $( "
<input type='text' placeholder='new directory' id='directory' value='' />
" );
				var directories = new Array();

				while ( $relatedDirectory.find( "> .fa-folder" ).length ) {
					directories.push( $relatedDirectory.find( "> .fa-folder" ).next().html() );
					$relatedDirectory = $relatedDirectory.parent().parent();
				}

				var $prompt = $( rawHtml );
				$prompt.addClass( "prompt-container-overlay" );
				$prompt.find( ".title" ).append( $( "", { class: "fa fa-times close" } ) );
				$prompt.find( ".content" ).append( $( "
", { class: "existing-directory center" } ) );
				$prompt.find( ".content" ).append( $directoryInput );

				$( ".container" ).append( $prompt );
				$directoryInput.find( "#directory" ).focus();

				$prompt.find( ".close" ).click( function() {
					$prompt.remove();
				} );
			} catch ( error ) {
				loggingService.recoverableError( error );
			}
		}
		, processDisplayWorkspace: function( rawHtml ) {
			var parent = this;
console.log( parent );
			try {
				Require.all( rawHtml );

				$( ".container" ).html( rawHtml );
				$( ".container .menuIndicator" ).mouseover( parent.displayMenu );
				$( ".container .logout" ).click( authService.logout );
			} catch ( error ) {
				loggingService.unrecoverableError( error );
			}
		}
	};

	var buildApi = function( functions ) {
		ajaxService = AjaxService.getInstance();
		authService = AuthService.getInstance();
		loggingService = LoggingService.getInstance();

		return {
			displayWorkspace: function() {
				ajaxService.GET({
					url: "public/views/workspace.html"
					, fnSuccess: function( data ) { functions.processDisplayWorkspace( data ); }
					, fnFailure: loggingService.unrecoverableError
				});
			}
		};
	};

	return {
		getInstance: function() {
			if ( instance != null ) {
				return instance;
			}

			instance = buildApi( functions );

			return instance;
		}
		, getTestInstance: function() {
			var functionsClone = Require.clone( functions );
			var instance = buildApi( functionsClone );

			instance.privateFunctions = functionsClone;

			return instance;
		}
	};
}();

/*

var EDITOR = {
	actionCreateFilePrompt: function(path, ajaxService){
		ajaxService.GET('public/views/prompt.html', {
			fnSuccess: function(data){ EDITOR.processFileCreatePrompt(data, path, ajaxService); }
			,fnFailure: EDITOR.recoverableError
		});
	}
	,actionSubmitCreateFilePrompt: function(e, path, ajaxService){
		if (EDITOR.KeyTest.isEnter(e)){
			var filename = $('.prompt #filename').val();
			var filenamePattern = /^[a-zA-Z][a-zA-Z0-9._-]*[.][a-zA-Z0-9]+$/;

			if (filenamePattern.test(filename)){
				path.push(filename);

				ajaxService.POST('?file/create', { file: path }, {
					fnSuccess: function(data){
						EDITOR.displayInfo(data);

						$('.prompt-container').remove();
					}
					,fnFailure: EDITOR.recoverableError
				});
			} else {
				EDITOR.displayError("Invalid filename");
			}
		}
	}
	,buildFile: function($parent, path, file, ajaxService){
		//var $delete = $('');
		var $li = $('

');
		//var $newFile = $('');
		//var $newFolder = $('');
		var $ul = $('

');

		//$newFile.click(THIS.actionNewFile(path, key));
		//$newFolder.click(THIS.actionNewFolder(path, key));
		//$delete.click(THIS.actionDeleteFolder(path, key));
		//$li.click(THIS.actionToggleExpansion);

		path.push(file);

		$li.append(file)
			//.append(' ').append($newFile)
			//.append(' ').append($newFolder)
			//.append(' ').append($delete)
			.append($ul);

		$parent.append($li);
	}
	,buildFolder: function($parent, path, folder, files, ajaxService){
		//var $delete = $('');
		var $li = $('

');
		var $newFile = $('');
		//var $newFolder = $('');
		var $ul = $('

');

		path.push(folder);

		$newFile.click(function(){ EDITOR.actionCreateFilePrompt(path, ajaxService); });
		//$newFolder.click(THIS.actionNewFolder(path, key));
		//$delete.click(THIS.actionDeleteFolder(path, key));
		//$li.click(THIS.actionToggleExpansion);

		$li.append(folder).append($newFile)
			//.append(' ').append($newFolder)
			//.append(' ').append($delete)
			.append($ul);

		EDITOR.buildFileList($ul, path, files, ajaxService);

		$parent.append($li);
	}
	,buildRootFolder: function($parent, ajaxService){
		var $li = $('

');
		var $newFile = $('');
		//var $newFolder = $('');
		var $ul = $('

');

		//$newFile.click(THIS.actionNewFile(null, 'root'));
		//$newFolder.click(THIS.actionNewFolder(null, 'root'));

		$li.append('root').append($newFile)
			//.append(' ').append($newFolder)
			.append($ul);

		$parent.append($li);

		return $ul;
	}
	,processApplicationEntry: function(jsonString, ajaxService){
		try {
			var response = $.parseJSON(jsonString);

			Require.all(response, 'responseCode');

			if (response.responseCode == 'UNAUTHORIZED'){
				EDITOR.displayLogin(ajaxService);
			} else if (response.responseCode == 'AUTHORIZED'){
				EDITOR.displayWorkspace(ajaxService);
			} else {
				EDITOR.unrecoverableError();
			}
		} catch (e){
			console.log(e);
			EDITOR.unrecoverableError();
		}
	}
	,processFileCreatePrompt: function(data, path, ajaxService){
		var $prompt = $(data);
		var $content = $prompt.find('.content');

		$prompt.find('.title').html('New File');
		$content.append(
			'
'
				+'<input type="text" placeholder="filename" id="filename" value="" />'
			+'
');

		$('.container').append($prompt);
		$('.prompt .input input').keyup(function(e){ EDITOR.actionSubmitCreateFilePrompt(e, path, ajaxService); });
		$('.prompt .input input:first').focus();
	}
};

*/
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2012, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
 */

/*global YUI, YSLOW*/
/*jslint white: true, onevar: true, undef: true, newcap: true, nomen: true, regexp: true, plusplus: true, bitwise: true, continue: true, browser: true, maxerr: 50, indent: 4 */

YUI().use(function (iY) {
    var sbY = YUI({
        win: window,
        doc: document
    });

    // sandbox YUI
    iY.Get.script = function () {
        return sbY.Get.script.apply(sbY, arguments);
    };

    iY.use('features', 'node-base', 'node-style', 'yql', 'jsonp-url', 'yslow-config', function (Y) {
        var
            iwin, idoc, fetchCount, fetchTotal, iframeNode,

            win = Y.config.win,
            doc = Y.config.doc,
            config = Y.namespace('YSLOW').config,
            arrayEach = Y.Array.each,
            encode = win.encodeURIComponent,

            URL_MAX_LEN = Y.UA.ie && Y.UA.ie < 7 ? 1800 : 6000,
            YQL_REQ_TABLE = config.table ? 'use "' + config.table + '";' : '',
            YQL_REQ_URL_LEN = 230 + encode(YQL_REQ_TABLE).length,
            YQL_REQ_SEP_LEN = 9, //%22%2C%22 = ","
            YQL_REQ_UA = win.navigator.userAgent,
            YQL_REQ_UA_LEN = encode('"' + YQL_REQ_UA + '"').length,

            yscontext = new YSLOW.context(doc),
            reIgnore = /^(chrome\-extension|data|chrome|javascript|about|resource|jar|file):/i,
            iframe = Y.one('#YSLOW-bookmarklet');

        if (config.yql) {
            Y.YQLRequest.BASE_URL = ':/' + '/' + config.yql;
        }

        // init YSlow iframe
        YSLOW.bookmarklet = true;
        iframeNode = Y.Node.getDOMNode(iframe);
        iframeNode.style.cssText = 'display:block;background:#fff;' +
            'border:1px solid #000;position:fixed;bottom:0;left:0;height:50%;' +
            'width:100%;z-index:2147483647;_position:absolute;_height:350px;';
        iwin = iframeNode.contentWindow;
        idoc = iwin.document;
        idoc.body.innerHTML = '

';
        iwin.panelNode = idoc.getElementById('yslowDiv');

        // make mobile viewport wider
        if (Y.one('meta[name=viewport]')) {
            iframe.setStyles({
                position: 'absolute',
                width: '974px'
            });
        }

        // make YSLOW compatible
        YSLOW.controller.init();
        idoc.ysview = new YSLOW.view(iwin, yscontext);
        idoc.yslowContext = yscontext;

        function closeYSlow(e) {
            e.preventDefault();
            try {
                delete win.YSLOW;
            } catch (err) {
                win.YSLOW = null;
            }
            iframe.remove();
        }

        function fullScreen(e) {
            var target = e.target.ancestor('li', true),
                fs = target.hasClass('restore');

            e.preventDefault();
            iframe.setStyle('height', (fs ? 50 : 100) + '%');
            target.toggleClass('restore');
        }

        // YUI control for YSLOW inside an iframe
        YUI({win: iwin, doc: idoc}).use('features', 'node-base', 'node-style', function (iY) {
            var create = iY.Node.create,
                closeBtn = create('
' +
                    'XClose
'),
                fsBtn = create('
' +
                    '∧Expand' +
                    '∨Restore' +
                    '
');

            iY.Get.css(config.host + config.css);
            closeBtn.on('click', closeYSlow);
            fsBtn.on('click', fullScreen);
            // start in fullscreen mode on mobile, but ipad
            if (Y.UA.mobile) {
                if (!Y.UA.ipad) {
                    fsBtn.addClass('restore');
                    iframe.setStyle('height', '100%');
                } else {
                    iframe.setStyle('width', '100%');
                }
            }
            iY.one('#tbActions').insert(fsBtn, 1);
            iY.one('#tbActions').append(closeBtn);

            // remove buttons
            // TODO: put them back once tools are working
            iY.one('#ysToolButton').remove();
            iY.one('#printLink').remove();
        });

        function buildComponentSet(comps) {
            var i, comp, len,
                baseHref = YSLOW.peeler.getBaseHref(doc),
                cset = new YSLOW.ComponentSet(doc);

            for (i = 0, len = comps.length; i < len; i += 1) {
                comp = comps[i];
                cset.addComponent(comp.href, comp.type,
                    comp.base ? comp.base : baseHref, {
                        obj: comp.obj,
                        component: comp,
                        comp: comp
                    });
            }

            return cset;
        }

        function breakDownUrls(urls) {
            var len = YQL_REQ_URL_LEN + YQL_REQ_UA_LEN,
                chunk = [],
                res = [];

            arrayEach(urls, function (url) {
                len += encode(url).length + YQL_REQ_SEP_LEN;
                if (len <= URL_MAX_LEN || !chunk.length) {
                    chunk.push(url);
                } else {
                    res.push('"' + chunk.join('","') + '"');
                    len = YQL_REQ_URL_LEN + YQL_REQ_UA_LEN +
                        encode(url).length + YQL_REQ_SEP_LEN;
                    chunk = [url];
                }
            });
            res.push('"' + chunk.join('","') + '"');

            return res;
        }

        function peelDone(cset) {
            YSLOW.util.event.fire('componentFetchProgress', {
                'total': fetchTotal + 2,
                'current': fetchTotal + 2,
                'last_component_url': 'Done'
            });
            yscontext.component_set = cset;
            YSLOW.util.event.fire('peelComplete', {
                'component_set': cset
            });
            cset.notifyPeelDone();
        }

        // set cookies for components in the same domain as main document
        function setSameDomainCookies(cset) {
            var i, len, comp,
                getHostname = YSLOW.util.getHostname,
                docDomain = getHostname(cset.doc_comp.url),
                comps = cset.components,
                cookies = cset.cookies;

            for (i = 0, len = comps.length; i < len; i += 1) {
                comp = comps[i];
                if (getHostname(comp.url) === docDomain &&
                        comp.cookie.length < cookies.length) {
                    comp.cookie = cookies;
                }
            }
        }

        function showError() {
            idoc.ysview.openDialog(idoc, 400, 150,
                'Ooops! An error occured fetching page components. ' +
                'Plese try again.', null, 'OK', function () {
                    idoc.ysview.setSplashView(true, true, true);
                    idoc.ysview.closeDialog(idoc);
                });
        }

        function parseYQL(r, hash, comps) {
            var cset,
                query = r.query,
                res = query && query.results;

            if (!res || r.error) {
                return showError();
            }

            YSLOW.util.event.fire('componentFetchProgress', {
                'total': fetchTotal + 2,
                'current': fetchTotal - fetchCount,
                'last_component_url': YSLOW.util.plural('%num% component%s% fetched',
                    (query && query.count) || 0)
            });

            res = res && res.resources;
            arrayEach(res, function (v) {
                // find and get comp from comps hash
                var comp,
                    redir = v.redirect,
                    rawHeaders = '';

                // check for redirect
                if (redir) {
                    redir = [].concat(redir);
                    comp = hash[redir[0].url];
                    arrayEach(redir, function (red) {
                        var headerName,
                            headers = {};
                        for (headerName in red.headers) {
                            if (red.headers.hasOwnProperty(headerName)) {
                                headers[headerName.toLowerCase()] = red.headers[headerName];
                            }
                        }
                        comps.push({
                            url: red.url,
                            href: red.url,
                            rawHeaders: 'Location: ' + headers.location + '\n',
                            status: red.status,
                            headers: headers,
                            type: 'redirect'
                        });
                    });
                } else {
                    comp = hash[v.url];
                }
                comp.href = comp.url = v.url;

                // build raw headers
                Y.Object.each(v.headers, function (v, k) {
                    rawHeaders += k + ': ' + v + '\n';
                });
                comp.rawHeaders = rawHeaders;

                comp.status = v.status;
                comp.headers = v.headers;
                comp.content = v.content;
            });

            if (!(fetchCount -= 1)) {
                cset = buildComponentSet(comps);
                YSLOW.util.event.fire('componentFetchProgress', {
                    'total': fetchTotal + 2,
                    'current': fetchTotal + 1,
                    'last_component_url': 'Checking post onload components'
                });
                cset.inline = YSLOW.util.getInlineTags(doc);
                cset.domElementsCount = YSLOW.util.countDOMElements(doc);
                cset.cookies = YSLOW.util.getDocCookies(doc);
                setSameDomainCookies(cset);
                cset.components = YSLOW.util.setInjected(doc,
                    cset.components, cset.doc_comp.body);
                cset.setAfterOnload(peelDone);
            }
        }

        function request(hash, comps, urls) {
            urls = breakDownUrls(urls);
            fetchCount = fetchTotal = urls.length;

            arrayEach(urls, function (url) {
                Y.YQL(YQL_REQ_TABLE +
                    'select * from data.headers where url in (' + url + ') and ua="' +
                    YQL_REQ_UA + '";', {
                        on: {
                            success: parseYQL,
                            failure: showError,
                            timeout: showError
                        },
                        args: [hash, comps]
                    });
            });
        }

        function fetchResult(result) {
            var i, comp, url, len,
                hash = {},
                urls = [],
                comps = [];

            for (i = 0, len = result.length; i < len; i += 1) {
                comp = result[i];
                url = comp.href;
                if (url && !reIgnore.test(url)) {
                    hash[url] = comp;
                    comps.push(comp);
                    urls.push(url);
                } else if (!url) {
                    comps.push(comp);
                }
            }

            return request(hash, comps, urls);
        }

        YSLOW.controller.run = function (win, yscontext, autorun) {
            YSLOW.util.event.fire('peelStart');
            fetchResult(YSLOW.peeler.peel(doc));
        };

        YSLOW.util.event.addListener('peelStart', function () {
            idoc.ysview.genProgressView();
        });
        YSLOW.util.event.addListener('peelProgress', function (progress) {
            idoc.ysview.updateProgressView('peel', progress);
        });
        YSLOW.util.event.addListener('componentFetchProgress', function (progress) {
            idoc.ysview.updateProgressView('fetch', progress);
        });
        YSLOW.util.event.addListener('componentFetchDone', function () {
            idoc.ysview.show();
        });

        idoc.ysview.setSplashView(true, true, true);
    });
});
<commit_msg>using YUI array/obj forEach<commit_after>/**
 * Copyright (c) 2012, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
 */

/*global YUI, YSLOW*/
/*jslint white: true, onevar: true, undef: true, newcap: true, nomen: true, regexp: true, plusplus: true, bitwise: true, continue: true, browser: true, maxerr: 50, indent: 4 */

YUI().use(function (iY) {
    var sbY = YUI({
        win: window,
        doc: document
    });

    // sandbox YUI
    iY.Get.script = function () {
        return sbY.Get.script.apply(sbY, arguments);
    };

    iY.use('features', 'node-base', 'node-style', 'yql', 'jsonp-url', 'yslow-config', function (Y) {
        var
            iwin, idoc, fetchCount, fetchTotal, iframeNode,

            win = Y.config.win,
            doc = Y.config.doc,
            config = Y.namespace('YSLOW').config,
            arrayEach = Y.Array.each,
            objEach = Y.Object.each,
            encode = win.encodeURIComponent,

            URL_MAX_LEN = Y.UA.ie && Y.UA.ie < 7 ? 1800 : 6000,
            YQL_REQ_TABLE = config.table ? 'use "' + config.table + '";' : '',
            YQL_REQ_URL_LEN = 230 + encode(YQL_REQ_TABLE).length,
            YQL_REQ_SEP_LEN = 9, //%22%2C%22 = ","
            YQL_REQ_UA = win.navigator.userAgent,
            YQL_REQ_UA_LEN = encode('"' + YQL_REQ_UA + '"').length,

            yscontext = new YSLOW.context(doc),
            reIgnore = /^(chrome\-extension|data|chrome|javascript|about|resource|jar|file):/i,
            iframe = Y.one('#YSLOW-bookmarklet');

        if (config.yql) {
            Y.YQLRequest.BASE_URL = ':/' + '/' + config.yql;
        }

        // init YSlow iframe
        YSLOW.bookmarklet = true;
        iframeNode = Y.Node.getDOMNode(iframe);
        iframeNode.style.cssText = 'display:block;background:#fff;' +
            'border:1px solid #000;position:fixed;bottom:0;left:0;height:50%;' +
            'width:100%;z-index:2147483647;_position:absolute;_height:350px;';
        iwin = iframeNode.contentWindow;
        idoc = iwin.document;
        idoc.body.innerHTML = '

';
        iwin.panelNode = idoc.getElementById('yslowDiv');

        // make mobile viewport wider
        if (Y.one('meta[name=viewport]')) {
            iframe.setStyles({
                position: 'absolute',
                width: '974px'
            });
        }

        // make YSLOW compatible
        YSLOW.controller.init();
        idoc.ysview = new YSLOW.view(iwin, yscontext);
        idoc.yslowContext = yscontext;

        function closeYSlow(e) {
            e.preventDefault();
            try {
                delete win.YSLOW;
            } catch (err) {
                win.YSLOW = null;
            }
            iframe.remove();
        }

        function fullScreen(e) {
            var target = e.target.ancestor('li', true),
                fs = target.hasClass('restore');

            e.preventDefault();
            iframe.setStyle('height', (fs ? 50 : 100) + '%');
            target.toggleClass('restore');
        }

        // YUI control for YSLOW inside an iframe
        YUI({win: iwin, doc: idoc}).use('features', 'node-base', 'node-style', function (iY) {
            var create = iY.Node.create,
                closeBtn = create('
' +
                    'XClose
'),
                fsBtn = create('
' +
                    '∧Expand' +
                    '∨Restore' +
                    '
');

            iY.Get.css(config.host + config.css);
            closeBtn.on('click', closeYSlow);
            fsBtn.on('click', fullScreen);
            // start in fullscreen mode on mobile, but ipad
            if (Y.UA.mobile) {
                if (!Y.UA.ipad) {
                    fsBtn.addClass('restore');
                    iframe.setStyle('height', '100%');
                } else {
                    iframe.setStyle('width', '100%');
                }
            }
            iY.one('#tbActions').insert(fsBtn, 1);
            iY.one('#tbActions').append(closeBtn);

            // remove buttons
            // TODO: put them back once tools are working
            iY.one('#ysToolButton').remove();
            iY.one('#printLink').remove();
        });

        function buildComponentSet(comps) {
            var i, comp, len,
                baseHref = YSLOW.peeler.getBaseHref(doc),
                cset = new YSLOW.ComponentSet(doc);

            for (i = 0, len = comps.length; i < len; i += 1) {
                comp = comps[i];
                cset.addComponent(comp.href, comp.type,
                    comp.base ? comp.base : baseHref, {
                        obj: comp.obj,
                        component: comp,
                        comp: comp
                    });
            }

            return cset;
        }

        function breakDownUrls(urls) {
            var len = YQL_REQ_URL_LEN + YQL_REQ_UA_LEN,
                chunk = [],
                res = [];

            arrayEach(urls, function (url) {
                len += encode(url).length + YQL_REQ_SEP_LEN;
                if (len <= URL_MAX_LEN || !chunk.length) {
                    chunk.push(url);
                } else {
                    res.push('"' + chunk.join('","') + '"');
                    len = YQL_REQ_URL_LEN + YQL_REQ_UA_LEN +
                        encode(url).length + YQL_REQ_SEP_LEN;
                    chunk = [url];
                }
            });
            res.push('"' + chunk.join('","') + '"');

            return res;
        }

        function peelDone(cset) {
            YSLOW.util.event.fire('componentFetchProgress', {
                'total': fetchTotal + 2,
                'current': fetchTotal + 2,
                'last_component_url': 'Done'
            });
            yscontext.component_set = cset;
            YSLOW.util.event.fire('peelComplete', {
                'component_set': cset
            });
            cset.notifyPeelDone();
        }

        // set cookies for components in the same domain as main document
        function setSameDomainCookies(cset) {
            var i, len, comp,
                getHostname = YSLOW.util.getHostname,
                docDomain = getHostname(cset.doc_comp.url),
                comps = cset.components,
                cookies = cset.cookies;

            for (i = 0, len = comps.length; i < len; i += 1) {
                comp = comps[i];
                if (getHostname(comp.url) === docDomain &&
                        comp.cookie.length < cookies.length) {
                    comp.cookie = cookies;
                }
            }
        }

        function showError() {
            idoc.ysview.openDialog(idoc, 400, 150,
                'Ooops! An error occured fetching page components. ' +
                'Plese try again.', null, 'OK', function () {
                    idoc.ysview.setSplashView(true, true, true);
                    idoc.ysview.closeDialog(idoc);
                });
        }

        function parseYQL(r, hash, comps) {
            var cset,
                query = r.query,
                res = query && query.results;

            if (!res || r.error) {
                return showError();
            }

            YSLOW.util.event.fire('componentFetchProgress', {
                'total': fetchTotal + 2,
                'current': fetchTotal - fetchCount,
                'last_component_url': YSLOW.util.plural('%num% component%s% fetched',
                    (query && query.count) || 0)
            });

            res = res && res.resources;
            arrayEach(res, function (v) {
                // find and get comp from comps hash
                var comp,
                    redir = v.redirect,
                    rawHeaders = '';

                // check for redirect
                if (redir) {
                    redir = [].concat(redir);
                    comp = hash[redir[0].url];
                    arrayEach(redir, function (red) {
                        var headers = {};

                        objEach(red.headers, function (value, key) {
                            headers[key.toLowerCase()] = value;
                        });
                        comps.push({
                            url: red.url,
                            href: red.url,
                            rawHeaders: 'Location: ' + headers.location + '\n',
                            status: red.status,
                            headers: headers,
                            type: 'redirect'
                        });
                    });
                } else {
                    comp = hash[v.url];
                }
                comp.href = comp.url = v.url;

                // build raw headers
                objEach(v.headers, function (v, k) {
                    rawHeaders += k + ': ' + v + '\n';
                });
                comp.rawHeaders = rawHeaders;

                comp.status = v.status;
                comp.headers = v.headers;
                comp.content = v.content;
            });

            if (!(fetchCount -= 1)) {
                cset = buildComponentSet(comps);
                YSLOW.util.event.fire('componentFetchProgress', {
                    'total': fetchTotal + 2,
                    'current': fetchTotal + 1,
                    'last_component_url': 'Checking post onload components'
                });
                cset.inline = YSLOW.util.getInlineTags(doc);
                cset.domElementsCount = YSLOW.util.countDOMElements(doc);
                cset.cookies = YSLOW.util.getDocCookies(doc);
                setSameDomainCookies(cset);
                cset.components = YSLOW.util.setInjected(doc,
                    cset.components, cset.doc_comp.body);
                cset.setAfterOnload(peelDone);
            }
        }

        function request(hash, comps, urls) {
            urls = breakDownUrls(urls);
            fetchCount = fetchTotal = urls.length;

            arrayEach(urls, function (url) {
                Y.YQL(YQL_REQ_TABLE +
                    'select * from data.headers where url in (' + url + ') and ua="' +
                    YQL_REQ_UA + '";', {
                        on: {
                            success: parseYQL,
                            failure: showError,
                            timeout: showError
                        },
                        args: [hash, comps]
                    });
            });
        }

        function fetchResult(result) {
            var i, comp, url, len,
                hash = {},
                urls = [],
                comps = [];

            for (i = 0, len = result.length; i < len; i += 1) {
                comp = result[i];
                url = comp.href;
                if (url && !reIgnore.test(url)) {
                    hash[url] = comp;
                    comps.push(comp);
                    urls.push(url);
                } else if (!url) {
                    comps.push(comp);
                }
            }

            return request(hash, comps, urls);
        }

        YSLOW.controller.run = function (win, yscontext, autorun) {
            YSLOW.util.event.fire('peelStart');
            fetchResult(YSLOW.peeler.peel(doc));
        };

        YSLOW.util.event.addListener('peelStart', function () {
            idoc.ysview.genProgressView();
        });
        YSLOW.util.event.addListener('peelProgress', function (progress) {
            idoc.ysview.updateProgressView('peel', progress);
        });
        YSLOW.util.event.addListener('componentFetchProgress', function (progress) {
            idoc.ysview.updateProgressView('fetch', progress);
        });
        YSLOW.util.event.addListener('componentFetchDone', function () {
            idoc.ysview.show();
        });

        idoc.ysview.setSplashView(true, true, true);
    });
});
<|endoftext|>