/* Our Code */
var notes;
var selectedNote;
var canEditAlbum = false;
var visible;
var currAuthor;
var newNoteId;

/* +const+ not supported in IE */
var ON_DELETE = 0;
var ON_SAVE = 1;

/* constants for use in displaying tag author */
/* style of .tag-author can be edited in photo.css */
var BEFORE_AUTHOR_HTML = "<br /> <span class=\"tag-author\">";
var AFTER_AUTHOR_HTML = " さん</span>";

function Initialize(id, width, height, author, isAlbumEditor, data)
{
  window.onerror = null; /*suppress error msgs*/
  notes = null;
  
  notes = new PhotoNoteContainer(document.getElementById('picture'));
  notes.width = width;
  notes.height = height; /* for dragging to work properly */
  currAuthor = author;
  canEditAlbum = isAlbumEditor;
  //LoadNotes(id);
  displayNotes(data);
  visible = false;
  document.getElementById('picture').onmouseover = SetNoteVisibility;
  document.getElementById('picture').onmouseout = SetNoteVisibility;
}

function Trim(s) 
{
    // Remove leading spaces and carriage returns
    while ((s.substring(0,1) == ' ') || (s.substring(0,1) == '\n') || (s.substring(0,1) == '\r'))
    { s = s.substring(1,s.length); }
     
    // Remove trailing spaces and carriage returns
    while ((s.substring(s.length-1,s.length) == ' ') || (s.substring(s.length-1,s.length) == '\n') || (s.substring(s.length-1,s.length) == '\r'))
    { s = s.substring(0,s.length-1); }
     
    return s;
}

function LoadNotes(id)
{
    var pars = "photo_id="+id;
    new Ajax.Request('/photo_tags/list',
                    {
                        method: 'post',
                        parameters: pars,
                        evalScripts: true   
                    });
}

// findPos function to fix offsetTop and offsetLeft cross-browser incompatibilities
// Modified version of code originally produced by 
// Peter-Paul Koch (http://www.quirksmode.org)& Alex Tingle (http://blog.firetree.net)
// Code dedicated by authors to public domain 
function findPos(obj)
{
  var curleft = 0;
  var curtop = 0;
  if(obj.offsetParent) {
      while(1) {
        curleft += obj.offsetLeft;
        curtop += obj.offsetTop;
        if(!obj.offsetParent)
          break;
        obj = obj.offsetParent;
      }
  }
  else if(obj.x && obj.y) {
      curleft += obj.x;
      curtop += obj.y;
  }
      
  return [curleft, curtop];
}
  
function MouseWithinPicture(e, top_left_x, top_left_y, width, height)
{
    var posx = 0;
    var posy = 0;
    if (!e) e = window.event;
    
    if (e.pageX || e.pageY)     {
        posx = e.pageX;
        posy = e.pageY;
    }
    else if (e.clientX || e.clientY)    {
        posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
        posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
    }

    if (posx >= top_left_x && posx <= top_left_x + width &&
        posy >= top_left_y && posy <= top_left_y + height)
        return true;
    else
        return false;
}

function SetNoteVisibility(e)
{   
    // if user is currently editing a note, do nothing
    if (selectedNote != null) return;

    // Otherwise, find the mouse coords
    var offset = findPos(document.getElementById('picture'));
    var inside_picture = MouseWithinPicture(e, offset[0], 
                                           offset[1],
                                           notes.width,
                                           notes.height);
    
    if(inside_picture && !visible)
    {
        visible = true;
        notes.ShowAllNotes();
    }
    else if(!inside_picture)
    {
        notes.HideAllNotes();
        visible = false;
    }
}

function displayNotes(noteData) {
    var offset = findPos($('picture'));
    var tags = [];
    noteData.each(function(item) {
            var newNote = new PhotoNote(item.text,item.id,item.author,
                                        new PhotoNoteRect(offset[0]+item.left, offset[1]+item.top,
                                                          item.width, item.height));
            newNote.editable = item.editable;
            newNote.deletable = canEditAlbum;
            newNote.onsave = saveNote;
            newNote.ondelete = deleteNote;
            tags.push(newNote);
        });
    /* sort by size */
    tags.sort(sortBySize);
    tags.each(function(tag) { notes.AddNote(tag) });
    notes.HideAllNotes();
    if(selectedNote != null) {
        selectedNote.ShowNote();
        selectedNote.ShowNoteText();
    }
}

function sortBySize(a, b)
{
    return b.rect.width*b.rect.height - a.rect.width*a.rect.height;
}

function HighlightNote(id)
{
  if (selectedNote != null && selectedNote.id == id) return;
  note = notes.FindNote(id);
  if(note == null) return;
  note.ShowNote();
  note.ShowNoteText();
  note = null;
}

function LowlightNote(id)
{
  if (selectedNote != null && selectedNote.id == id) return;
  note = notes.FindNote(id);
  if(note == null) return;
  note.HideNote();
  note.HideNoteText();
  note = null;
}

function AddNote(photoId)
{
    if(selectedNote != null) {
        selectedNote.UnSelect();
    }
    
    var offset = findPos(document.getElementById('picture'));
    var newNote = new PhotoNote('タグを入力してください...',-1,currAuthor, 
                                    new PhotoNoteRect(offset[0]+10, offset[1]+10,50,50));
    newNote.onsave = saveNote;
    newNote.ondelete = deleteNote;
    newNote.queue = 0;
    newNote.photoId = photoId;
    
    notes.AddNote(newNote);
    newNote.editable = true;
    newNote.Select();
    newNote = null;
}

function finishSave()
{
  var ids = getID(ON_SAVE);
  if(ids[0] == -1 && ids[1] == -1) {
    return 1;
  }
    
  new Effect.Highlight('tags');
  return 1; 
}

function finishDelete()
{
  new Effect.Highlight('tags');
  return 1;
}

function getID(operation)
{
    var old_id = $('old_tag_id').innerHTML; 
    var new_id = $('new_tag_id').innerHTML;
    var queue = $('queue').innerHTML;
    
    if(operation == ON_SAVE) {
        note = notes.FindNote(old_id);
        /* Note is being updated by another ajax call, jump ship */
        if(note == null) {
            revokeSave(new_id);
            return [-1, -1];
        }
        else if(queue != note.queue) {
            return [-1, -1];
        }
        
        note.id = new_id;
    }
    return [old_id, new_id];
}

function saveNote(note)
{
    /* Update note id for this transaction */
    if(note.id < 0)
        note.id--;
    note.queue++;
    
    /* create string of parameters */
    /* store coordinates relative to container */
    var offset = findPos(document.getElementById('picture'));
    var left_rel = note.rect.left - offset[0];
    var top_rel = note.rect.top - offset[1];
    var pars = "text=" + Trim(note.gui.TextBox.value) 
       +"&corner_x="+left_rel+"&corner_y="+top_rel
       +"&width="+note.rect.width+"&height="+note.rect.height+"&id="+note.id
       +"&queue="+note.queue + "&photo_id=" + note.photoId;

    var action;
    if (note.id < 0) {
        action = '/photo_tags/create';
    } else {
        action = '/photo_tags/update';
    }
    /* Spin off Ajax update */
    new Ajax.Request(action,
                     {
                         method: 'post',
                         parameters: pars,
                         onComplete: function() {
                             if (newNoteId) {
                                 note.id = newNoteId;
                                 newNoteId = null;
                             }
                         },
                         evalScripts: true
                     });
    return 1; 
}

function revokeSave(id)
{
    var pars = "note_id=" + id;
    
    new Ajax.Updater('tags', '/photos/del_tag/',
                     {
                        method: 'post',
                        parameters: pars,
                        onComplete: finishRevoke
                     });
    return 1;
}

function finishRevoke()
{
    new Effect.Highlight('tags');
    return 1;
}

/*
function hideNoteById(noteId) {
    var note = this.notes.notes.find(function(note) { note.id = noteId });
    if (note) {
        this.notes.deleteNote(note);
    }
}
*/

function deleteNote(note)
{
    var pars = "id="+note.id;
    new Ajax.Request('/photo_tags/destroy',
                     {
                        method: 'post',
                        parameters: pars,
                        evalScripts: true
                     });
    return 1;
}

