// Global killswitch
if (isJsEnabled()) {
  addLoadEvent(eventAutoAttach);
}

/**
 * Attaches the block update behaviour to links tagged with 'updateblock' class.
 */
function eventAutoAttach() {
  var urls = Array();
  var block = $('block-event-0')

  if (block != undefined) {
    var divs = block.getElementsByTagName('div');
    for (i = 0; div = divs[i]; i++) {
      if (div && hasClass(div, 'content')) {		
        var content = div;
        anchors = content.getElementsByTagName('a');
        for (j = 0; anchor = anchors[j]; j++) {
		
          if (anchor && hasClass(anchor, 'updateblock')) {
            urls[anchor] = eregReplace('month', 'block', anchor.href);

            anchor.onclick = function() {
              this.blockUpdater = new blockUpdater(content,urls[this],eventAutoAttach);
              return false;
            }

          }

        }
        break;

      }
    }
  }
}

/**
 * create an instance of this object in the onClick handler for block update links.
 * 
 * could be separated into misc/blockupdater.js
 */

function blockUpdater(element,url,callback) {
  var blockUpdate = this
  element.blockUpdate = this

  this.element = element
  this.callback = callback

  this.oldHTML = this.element.innerHTML

  // Keep block at it's current width/height to make the update less disruptive
  this.styleHeight = element.style.height
  this.styleWidth  = element.style.width
  element.style.height = element.offsetHeight+"px"
  element.style.width  = element.offsetWidth+"px"

  // Clear block contents
  element.innerHTML = '';

  // Insert progressbar
  this.progress = new progressBar('updateprogress');
  this.element.insertBefore(this.progress.element,null);

  // Add cancel link
  cancel = document.createElement("a");
  cancel.textContent = "cancel"
  cancel.innerText = "cancel"
  cancel.className = "cancel-update"
  cancel.href="#"
  cancel.onclick = function() {
    this.parentNode.blockUpdate.update(undefined,undefined,blockUpdate);
    return false;
  }
  this.element.insertBefore(cancel,null);
//  alert(this.element.innerHTML)

  this.dontUpdate = false
  HTTPGet(url, this.update, this)
}

blockUpdater.prototype.update = function (result, xmlHttp, blockUpdate) {
  if(!blockUpdate.dontUpdate) {
    blockUpdate.element.style.height = blockUpdate.styleHeight
    blockUpdate.element.style.width  = blockUpdate.styleWidth

    if (result!=undefined)
      blockUpdate.element.innerHTML = result
    else {
      blockUpdate.element.innerHTML = this.oldHTML
      blockUpdate.dontUpdate = true
    }

    if(blockUpdate.callback != undefined)
      blockUpdate.callback()
  }
}