var SERVICE_PREFIX = "http://www.jacuba.com/service/imageresize/-/-/";
var PROCESS_PERIOD = 1000;

function processImage(img) {
    var url = img.src;
    if (url.indexOf(SERVICE_PREFIX) == 0) {
        //we've already processed this...
        var nw = img.offsetWidth;
	var nh = img.offsetHeight;
	if (nw > 0 && nh > 0) {
	    var ow = url.match(/width=(\d+)/);
	    if (ow) ow = parseInt(ow[1]);
	    var oh = url.match(/height=(\d+)/);
	    if (oh) oh = parseInt(oh[1]);
	    if (nw != ow || nh != oh) {
	        img.src = url.replace("width=" + ow, "width=" + nw).replace("height=" + oh, "height=" + nh);
	    }
	}
    } else {
        //measure the image and resize it accurately
        var w = img.offsetWidth;
	var h = img.offsetHeight;
	if (w > 0 && h > 0) {
            img.src = SERVICE_PREFIX + "?url=" + escape(url) +"&algorithm=bicubic&ratio=preserve&quality=0.9&width=" + w + "&height=" + h;
	}
    }
}

function processDocumentImages() {
    var imgs = document.images;
    for (var i = 0; i < imgs.length; i++) {
        processImage(imgs[i]);
    }
}

function startProcessingDocumentImages() {
    processDocumentImages();
    setInterval("processDocumentImages()", PROCESS_PERIOD);
}

function replaceEmail() {
  var el = document.getElementById("email");
  if (!el) return;
  var address = el.innerHTML;
  address = address.replace(" at ", "@").replace(" dot ",".");
  el.innerHTML = "<a href='mailto:" + address + "'>" + address + "</a>";
}

function assignContactAction() {
  var form = document.getElementById("contact_form");
  if (form) {
    form.action = "/nabaztag/transmit";
    form.style.display = "block";
  }
  
  var apology = document.getElementById("contact_apology");
  if (apology) apology.style.display = "none";
}

function displayContactThanks() {
  //small validation check:
  var textarea = document.getElementById("contact_textarea");
  if (textarea.value=="") return false;

  var form = document.getElementById("contact_form");
  if (form) form.style.display = "none";

  var thanks = document.getElementById("contact_thanks");
  if (thanks) thanks.style.display = "block";

  return true;
}

function topPos(el) {
  if (!el) return -1;
  var y = el.offsetTop;
  if (!y) y = 0;
  var p = el.offsetParent;
  return (p ? topPos(p) : 0) + y;
}

function botPos(el) {
  if (!el) return -1;
  return el.offsetHeight + topPos(el);
}

function fixHeight() {
  var topY = topPos( document.getElementById("height-marker-top") );
  if (topY < 0) return;
  var botY = botPos( document.getElementById("height-marker-bottom") );
  if (botY < 0) return;
  var brace = document.getElementById("height-brace");
  if (!brace) return;
  brace.style.minHeight = (botY - topY) + "px";
}

function genericInit() {
  replaceEmail();
  assignContactAction();
  fixHeight();
}
