﻿Splitter = function(divider, content) {
  this.divider = divider;
  this.content = content;

  $(this.divider).bind("mousedown", this, this.mouseDownHandler);

  var backDiv = document.createElement('div');
  this.backDiv = backDiv;
  backDiv.style.display = 'block';
  backDiv.style.position = 'absolute';
  backDiv.style.top = 0;
  backDiv.style.left = 0;
  backDiv.style.zIndex = 998;
  backDiv.style.width = '100%';
  backDiv.style.height = '100%';
  document.body.insertBefore(backDiv, document.body.firstChild);

  $(backDiv).hide();

  this.load();
}

Splitter.prototype = {
  mouseDownHandler: function(event) {
    if (event.data.mouseDown)
      return;

    var backDiv = event.data.backDiv;
    $(backDiv).show();
    if (backDiv.setCapture)
      backDiv.setCapture(false);

    $(backDiv).bind("mousemove", event.data, event.data.onMouseMove);
    $(backDiv).bind("mouseup", event.data, event.data.onMouseUp);

    document.body.style.cursor = "w-resize";
    event.data.mouseDown = true;

    event.preventDefault();
  },

  onMouseUp: function(event) {
    event.data.mouseUpHandler();
  },

  onMouseMove: function(event) {
    event.data.mouseMoveHandler(event.clientX);
  },

  mouseUpHandler: function() {
    if (!this.mouseDown)
      return;

    if (this.backDiv.releaseCapture)
      this.backDiv.releaseCapture();

    $(this.backDiv).unbind("mousemove", this.onMouseMove);
    $(this.backDiv).unbind("mouseup", this.onMouseUp);
    $(this.backDiv).hide();

    document.body.style.cursor = "auto";
    this.mouseDown = false;

    this.save();
  },

  mouseMoveHandler: function(newX) {
    if (!this.mouseDown)
      return;

    var offsetLeft = $(this.content).offset().left;
    if (newX > offsetLeft)
      newX = newX - offsetLeft;
    else
      newX = 1;

    this.setSizes(newX);
    if (window.getSelection != null)
      window.getSelection().removeAllRanges();
  },

  setSizes: function(newX) {
    if (newX < 100)
      newX = 100;
    this.content.style.width = newX;
  },

  load: function() {
    if (!window.navigator.cookieEnabled)
      return;

    var width = GetCookie("width");
    if (width != null) {
      width = parseInt(width);
      this.setSizes(width);
    }
  },

  save: function() {
    if (window.navigator.cookieEnabled) {
      var cookieDate = new Date();
      cookieDate.setFullYear(cookieDate.getFullYear() + 1);
      var path = window.location.pathname;
      var endIndex = path.toLowerCase().indexOf("default.aspx");
      if (endIndex != -1)
        path = path.substring(0, endIndex);
      document.cookie = "width=" + this.content.style.width + ";expires=" + cookieDate.toGMTString() + ";path=" + path;
    }
  }
}
