// FWiki Display Code (c) 2004 Angus Turnbull http://www.twinhelix.com
// Released under the GNU General Public License v2.0 or later.



// Common API Code.

var isDOM=document.getElementById?1:0,
 isIE=document.all?1:0,
 isOp=self.opera?1:0;

function addEvent(o, n, f)
{
 var a='addEventListener', h='on'+n;
 if (o[a]) return o[a](n, f, false);
 if (o[h])
 {
  o._c |= 0;
  var b = '_b' + (++o._c);
  o[b] = o[h];
 }
 o[h] = function(e)
 {
  e=e||self.event;
  var r = true;
  if (o[b]) r = o[b](e) != false && r;
  o._f=f;
  r = o._f(e) != false && r;
  return r;
 }
};

if (!self.page) var page = { win:self, minW:0, minH:0, MS:isIE&&!isOp };

page.db = function(p) { with (this.win.document) return (isDOM?documentElement[p]:0)||body[p]||0 };

page.winW=function() { with (this) return Math.max(minW, MS ? db('clientWidth') : win.innerWidth) };
page.winH=function() { with (this) return Math.max(minH, MS ? db('clientHeight') : win.innerHeight) };

page.scrollX=function() { with (this) return MS ? db('scrollLeft') : win.pageXOffset };
page.scrollY=function() { with (this) return MS ? db('scrollTop') : win.pageYOffset };

page.elmPos=function(e,p)
{
 var x=0,y=0,w=p?p:this.win;
 e=e?(e.substr?getRef(e,w):e):p;
 if (e && e.focus && e.href && this.MS && navigator.platform.indexOf('Mac')>-1)
 {
  e.onfocus = new Function('with(event){self.tmpX=clientX-offsetX;' +
   'self.tmpY=clientY-offsetY}');
  e.focus();x=tmpX;y=tmpY;e.blur()
 }
 else while(e){x+=e.offsetLeft;y+=e.offsetTop;e=e.offsetParent}
 return{x:x,y:y};
};


// Show/hide existing tips.

var fwikiHideTimer = null;
var fwikiActiveNote = null;

function fwikiMouseOverOutHandler(evt, isOver)
{
 evt = evt||window.event;
 var note = evt.target||evt.srcElement;
 if (note.nodeType != 1) note = note.parentNode;
 while (note)
 {
  // For the overall note container, swap its classname to show note areas. Timer helps IE.
  if (note && note.className && note.className.match(/^fotonote(Inac|Ac)tive$/))
  {
   clearTimeout(note.areaHideTimer);
   if (isOver) note.className = 'fotonoteActive';
   else note.areaHideTimer = setTimeout('document.getElementById("' + note.id +
    '").className = "fotonoteInactive"', 50);
  }

  // If the note has an ID of the form "fotonote-FOTONOTENAME-NOTENAME", process it.
  if (note && note.id && note.id.match(/^fotonote-([^\-]+)-([^\-]+)$/))
  {
   // Find the first child element, which will be the note in question.
   var child = note.firstChild;
   while (child && child.nodeType != 1) child = child.nextSibling;
   if (!child) return;

   // Clear any hide timeout, and either show the note, or set a timeout for its hide.
   // Record the currently active note for the hide timer to work.
   clearTimeout(fwikiHideTimer);
   if (isOver)
   {
    if (fwikiActiveNote && (child != fwikiActiveNote)) fwikiActiveNote.style.visibility = 'hidden';
    child.style.visibility = 'visible';
    fwikiActiveNote = child;
   }
   else
   {
   // 500 changed to 50
    fwikiHideTimer = setTimeout('if (fwikiActiveNote) { ' +
     'fwikiActiveNote.style.visibility="hidden"; fwikiActiveNote = null }', 50);
   }
  }
  note = note.parentNode;
 }

};










// *** Add/Edit/Delete notes ***

var fwikiActionVerb = '';
var fwikiActionTrigger = null;
var fwikiDragPhoto = null;


function fwikiNoteAction(action, trigger)
{
 // Control the state of the trigger buttons, and set the global fwikiActionVerb variable.
 if (fwikiActionVerb != action)
 {
  if (fwikiActionTrigger && fwikiActionVerb)
  {
   fwikiActionTrigger.className = 'fwikiButton fwiki-'+fwikiActionVerb+'-inactive';
  }
  fwikiActionVerb = action;
  fwikiActionTrigger = trigger;
  if (trigger) trigger.className = 'fwikiButton fwiki-'+action+'-active';
 }
 else
 {
  fwikiActionVerb = '';
  if (trigger) trigger.className = 'fwikiButton fwiki-'+action+'-inactive';
 }
};


function fwikiMouseDownHandler(evt)
{
 // Add a new note. Check to see if we're supposed to be adding them.
 if (fwikiActionVerb != 'add') return;

 evt = evt||window.event;
 var photo = evt.target||evt.srcElement;
 if (photo.nodeType != 1) photo = photo.parentNode;
 while (photo)
 {
  // If the photo has an ID of the form "fotonote-FOTONOTENAME", activate note creation.
  if (photo && photo.id && photo.id.match(/^fotonote-([^\-]+)$/))
  {
   var photoID = RegExp.$1;
   // Create new note and give it appropriate attributes.
   var newArea = document.createElement('div');
   var photoPos = page.elmPos(photo, null);
   photo.dragOrigX = evt.clientX + page.scrollX() - photoPos.x;
   photo.dragOrigY = evt.clientY + page.scrollY() - photoPos.y;
   newArea.style.left = photo.dragOrigX + 'px';
   newArea.style.top = photo.dragOrigY + 'px';
   newArea.style.width = '1px';
   newArea.style.height = '1px';
   newArea.className = 'fotonote-area';
   // Generate a new random ID.
   newArea.setAttribute('id', 'fotonote-' + photoID + '-' + parseInt(Math.random() * 100000));

   // Record this area/note as the currently dragging one for the mousemove handler.
   fwikiDragPhoto = photo;
   photo.dragArea = newArea;
   // Append to the parent of the IMG tag (the container DIV).
   photo.parentNode.appendChild(newArea);

   // Activate the move handler so it resizes until mouseup.
   fwikiNoteAction('drag', null);
   if (!photo.moveEvtSet)
   {
    photo.moveEvtSet = true;
    addEvent(photo, 'mousemove', fwikiMouseMoveHandler);
   }

   // Cancel normal mousedown action.
   if (evt.stopPropagation) evt.stopPropagation();
   if (evt.cancelable && evt.preventDefault) evt.preventDefault();
   return false;
  }
  photo = photo.parentNode;
 }

};

function fwikiMouseMoveHandler(evt)
{
 // Drag a new note area until mouseup event fires.
 if (!fwikiDragPhoto || fwikiActionVerb != 'drag') return;

 evt = evt||window.event;
 var areaPos = page.elmPos(this, null);
 var dragNewX = evt.clientX + page.scrollX() - areaPos.x;
 var dragNewY = evt.clientY + page.scrollY() - areaPos.y;
 with (fwikiDragPhoto)
 {
  dragArea.style.left = Math.min(dragOrigX, dragNewX);
  dragArea.style.top = Math.min(dragOrigY, dragNewY);
  dragArea.style.width = Math.abs(dragNewX - dragOrigX) + 'px';
  dragArea.style.height = Math.abs(dragNewY - dragOrigY) + 'px';


// save the coordinates in the form for new annotations
	document.getElementById('annotationform').style.left = dragOrigX + 20;
	document.getElementById('annotationform').style.top = dragOrigY + 20;
	document.getElementById('coordinates').value = dragOrigX + ',' + dragOrigY + ',' + dragNewX + ',' + dragNewY;
//


 }
 if (evt.stopPropagation) evt.stopPropagation();
 if (evt.cancelable && evt.preventDefault) evt.preventDefault();
 return false;
};

function fwikiMouseUpHandler(evt)
{
 // Stop the dragging, create a new note, and call the edit function to set its contents.
 if (fwikiDragPhoto)
 {
  fwikiDragPhoto.dragActive = false;

  var newNote = document.createElement('div');
  newNote.className = 'fotonote-note';
  newNote.style.position = 'absolute';
  newNote.style.left = '45px';
  newNote.style.top = '45px';
  newNote.style.width = '150px';
  fwikiDragPhoto.dragArea.appendChild(newNote);
  fwikiNoteAction('', null);
  fwikiEditNote(newNote);

  fwikiDragPhoto = null;
 }
};

function fwikiClickHandler(evt)
{
 evt = evt||window.event;
 var area = evt.target||evt.srcElement;
 if (area.nodeType != 1) area = area.parentNode;
 while (area)
 {
  // If the area has an ID of the form "fotonote-FOTONOTENAME-AREANAME", edit/delete it.
  if (area && area.id && area.id.match(/^fotonote-([^\-]+)-([^\-]+)$/))
  {
   if (fwikiActionVerb == 'del')
   {
    area.parentNode.removeChild(area);
    fwikiNoteAction('', null);
   }
   if (fwikiActionVerb == 'edit')
   {
    var child = area.firstChild;
    while (child && child.nodeType != 1) child = child.nextSibling;
    if (child) fwikiEditNote(child);
    fwikiNoteAction('', null);
   }
   return;
  }
  // If the source element is the controls div, create a credits area.
  if (area && area.className && area.className.match(/fwiki-credits/))
  {
   alert('Fotonotes Copyright/Credit Notice Goes Here.\n\n' +
    'To do: come up with sexy in-page dialog :)\n\n' +
    'Consider an IFRAME with an external file over the photo; internationalisation issues etc.?');
   return;
  }
  // Otherwise loop up the hierarchy.
  area = area.parentNode;
 }
};

function fwikiEditNote(note)
{
 // Pick up existing values for content.
 var title, content, author;
 for (var n = 0; n < note.childNodes.length; n++)
 {
  var fnNode = note.childNodes[n];
  if (fnNode.className == 'fotonote-notetitle') title = fnNode;
  if (fnNode.className == 'fotonote-notecontent') content = fnNode;
  if (fnNode.className == 'fotonote-noteauthor') author = fnNode;
 }



// Reveal annotation form and fill fields
	document.getElementById('annotationform').style.visibility = 'visible';
	document.getElementById('title').value = title.innerHTML.replace(/(\r|\n)+/g, '');
	document.getElementById('author').value = author.innerHTML.replace(/(\r|\n)+/g, '');
	document.getElementById('content').value = content.innerHTML.replace(/(\r|\n)+/g, '');



 // Create nodes as needed.
 if (!title)
 {
  title = document.createElement('span');
  title.className = 'fotonote-notetitle';
  note.appendChild(title);
 }
 if (!content)
 {
  content = document.createElement('span');
  content.className = 'fotonote-notecontent';
  note.appendChild(content);
 }
 if (!author)
 {
  author = document.createElement('span');
  author.className = 'fotonote-noteauthor';
  note.appendChild(author);
 }
 // Obtain new values. Yeah, innerHTML is non-standard :).
 title.innerHTML = prompt('Note Title:', title.innerHTML.replace(/(\r|\n)+/g, ''));
 content.innerHTML = prompt('Note Content:', content.innerHTML.replace(/(\r|\n)+/g, ''));
 author.innerHTML = prompt('Note Author:', author.innerHTML.replace(/(\r|\n)+/g, ''));
};

function fwikiEditNoteOld(note)
{
 // Pick up existing values for content.
 var title, content, author;
 for (var n = 0; n < note.childNodes.length; n++)
 {
  var fnNode = note.childNodes[n];
  if (fnNode.className == 'fotonote-notetitle') title = fnNode;
  if (fnNode.className == 'fotonote-notecontent') content = fnNode;
  if (fnNode.className == 'fotonote-noteauthor') author = fnNode;
 }
 // Create nodes as needed.
 if (!title)
 {
  title = document.createElement('span');
  title.className = 'fotonote-notetitle';
  note.appendChild(title);
 }
 if (!content)
 {
  content = document.createElement('span');
  content.className = 'fotonote-notecontent';
  note.appendChild(content);
 }
 if (!author)
 {
  author = document.createElement('span');
  author.className = 'fotonote-noteauthor';
  note.appendChild(author);
 }
 // Obtain new values. Yeah, innerHTML is non-standard :).
 title.innerHTML = prompt('Note Title:', title.innerHTML.replace(/(\r|\n)+/g, ''));
 content.innerHTML = prompt('Note Content:', content.innerHTML.replace(/(\r|\n)+/g, ''));
 author.innerHTML = prompt('Note Author:', author.innerHTML.replace(/(\r|\n)+/g, ''));
};








// Event handler setup.

if (document.getElementById)
{
 addEvent(document, 'mouseover', new Function('e', 'fwikiMouseOverOutHandler(e, 1)'));
 addEvent(document, 'mouseout', new Function('e', 'fwikiMouseOverOutHandler(e, 0)'));
 if (document.createElement && document.documentElement)
 {
  addEvent(document, 'mousedown', fwikiMouseDownHandler);
  addEvent(document, 'mouseup', fwikiMouseUpHandler);
  addEvent(document, 'click', fwikiClickHandler);
 }
}
