
// SkimpyGimpy:
//
// javascript utility functions for handling mouse events
// on images generated by canvas.py

// find the x,y pixels from lower left corner on the image, for the event.
function clickOffset(image, event, xpixels, ypixels) 
{
	var ox = event["offsetX"];
	var oy = event["offsetY"];
	//al("ox="+ox+" oy="+oy+" test="+(ox===undefined));
	if (ox===undefined) {
		// firefox?
		var p = positionOfElement(image, true);
		ox = event.clientX + window.pageXOffset - p.x;
		oy = event.clientY + window.pageYOffset - p.y;
	}
	var h = image.height;
	var w = image.width;
	// screen pixel offset
	var y = h-oy;
	var x = ox;
	// normalized offset
	var rx = x*1.0/w;
	var ry = y*1.0/h;
	// image pixel offset
	var px = Math.floor(rx*xpixels);
	var py = Math.floor(ry*ypixels);
	//alert("px="+px+" py="+py);
	return {x: x, y: y, rx: rx, ry: ry, px: px, py: py}
}

function coordsToString(dictionary, x, y) {
	var runlengths = dictionary[y];
	//alert(x+" runlengths "+y+" = "+runlengths);
	if (runlengths) {
		for (var i=0; i<runlengths.length; i++) {
      var runlength = runlengths[i];
			var xstart = runlength[0];
			var xend = runlength[1];
			var s = runlength[2];
			if (xstart<=x && xend>x) {
        //alert("found "+xstart+" "+x+" "+xend);
				return s;
			}
      //alert("not found "+xstart+" "+x+" "+xend);
		}
	}
	return null;
}

function bindTracking(imageName, callBackFunction, defaultString, xpixels, ypixels, dictionary) {
	var image = document.getElementById(imageName);
	var lastString = defaultString;
	var lastType = null;
	function mouseMove(e) {
    var eventType = e.type;
		var c = clickOffset(image, e, xpixels, ypixels);
		// temp
		var s = coordsToString(dictionary, c.px, c.py);
		if (!s) {
      s = defaultString;
    }
		if (s) {
      if (s!=lastString || eventType!=lastType) {
			//alert(s+" "+c.px+" "+c.py);
        callBackFunction(s, c.px, c.py, e, image);
			}
			lastString = s;
		} //else if (defaultString) {
      //if (lastString!=defaultString) {
        //callBackFunction(defaultString, c.px, c.py, e, image);
      //}
    lastString = s;
    lastType = eventType;
	}
	var mouseEvents = ["mousemove", "mouseout", "mousedown", "mouseover", "mouseup"];
	try {
    for (var i=0; i<mouseEvents.length; i++) {
      var mouseEvent = mouseEvents[i];
      image.addEventListener(mouseEvent, mouseMove, false);
		}
	} catch (e) {
    for (var i=0; i<mouseEvents.length; i++) {
      var mouseEvent = mouseEvents[i];
      image.attachEvent("on"+mouseEvent, mouseMove);
    }
	}
}


function positionOfElement(element, top) {
   var e = element;
   var x = 0;
   var y = 0;
   while (e!=null) {
      x+= e.offsetLeft;
      y+= e.offsetTop;
      e = e.offsetParent;
   }
   if (top==null) {
      y+= element.offsetHeight
   }
   return {x: x, y: y};
}