/*********** EYES - Javascript Eyes That Follow ***********\

This file is based on eyes.js by David King,
Courtesy of http://oopstudios.com/
License: http://oopstudios.com/site/oopstudios_nice_licence.html
(As of 22 June 2009 this is a pointer to the GNU GPL, version 3.)
Modified for G-N-U GmbH by Peter Gerwinski, http://www.peter.gerwinski.de

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

 Head over
\**********************************************************/

EYES = {};
EYES.stack = [];
//
// Stores the element
//
EYES.follow = function (pupil_id) {
  var pupil = document.getElementById (pupil_id);
  pupil.cx = parseInt (pupil.style.left) + 2;
  pupil.cy = parseInt (pupil.style.bottom) + 5;
  EYES.stack.push (pupil);
};
EYES.mousemove = function (e) {
  if (!EYES.stack.length) {
    return;
  }
  //
  // Cheers to quirksmode for mouse position lark!
  //  http://www.quirksmode.org/js/events_properties.html#position
  //
  var mouseX = mouseY = 0;
  if (!e) var e = window.event;
  if (e.pageX || e.pageY) 	{
    mouseX = e.pageX;
    mouseY = e.pageY;
  } else if (e.clientX || e.clientY) 	{
    mouseX = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
    mouseY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
  }
  //
  // Loop through all the defined eyes and calc them!
  //
  for (var e=0, l=EYES.stack.length; e<l; e++) {
    var pupil = EYES.stack[e];
    // Calculate it's position on the page
    //  (quirksmode based)
    var elX = elY = 0;
    if (pupil.offsetParent) {
      obj = pupil;
      do {
        elX += obj.offsetLeft;
        elY += obj.offsetTop;
      } while (obj = obj.offsetParent);
    }
    // Compare to the mouse position
    var difX = mouseX - elX;
    var difY = mouseY - elY;
    var dist = Math.sqrt ((difX * difX) + (difY * difY));
    difX = difX / dist;
    difY = difY / dist;
    dist = 5.0 * (dist > 200.0 ? 1.0 : 0.005 * dist);
    // What's the pupil position?
    var newX = pupil.cx + Math.round (difX * dist);
    var newY = pupil.cy - Math.round (difY * dist);
    pupil.style.left = newX + "px";
    pupil.style.bottom = newY + "px";
  }
};
//
// Automatically add the mouse event to the document
//
if (window.attachEvent) document.attachEvent ("onmousemove", EYES.mousemove);
else document.addEventListener ("mousemove", EYES.mousemove, false);
