/*
Copyright (c) 2006 Dusty Davidson - http://www.dustyd.net
(portions Copyright (c) 2005 Angus Turnbull http://www.twinhelix.come)

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the "Software"), 
to deal in the Software without restriction, including without limitation 
the rights to use, copy, modify, merge, publish, distribute, sublicense, 
and/or sell copies of the Software, and to permit persons to whom the Software 
is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in 
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/



/*********************************************************/
/*** Photo Notes Container *******************************/
/*********************************************************/
function PhotoNoteContainer(element, config)
{
    var props = {
        element: element,
        dragresize: null,
        notes: new Array(),
        editing: false,
        width: 600, /* define draggable area: */
        height: 449 /* set in Initialize */
    };

    for (var p in props)
    {
        this[p] = (!config || typeof config[p] == 'undefined') ? props[p] : config[p];
    }
        
}

PhotoNoteContainer.prototype.DeleteNote = function(note)
{
    note.UnSelect();

    /* remove from the DOM */
    this.element.removeChild(note.gui.ElementRect);
    this.element.removeChild(note.gui.ElementNote);
        
    /* remove from the array... */
    this.notes.remove(note);
};

PhotoNoteContainer.prototype.AddNote = function(note)
{
    if(!this.editing)
    {
        /* add the note to the array of notes, and set its container */
        this.notes[this.notes.length] = note;
        note.container = this;

        /* add the note to the DOM */
        this.element.appendChild(note.gui.ElementRect);
        this.element.appendChild(note.gui.ElementNote);    
    }
};

/* hide all of the "text" parts of the notes. Primarily called when hovering a note, at which
    point we want to hide all of the other note texts */
PhotoNoteContainer.prototype.HideAllNoteTexts = function()
{
    for (var i = 0;i<this.notes.length;i++)
        this.notes[i].HideNoteText();
};


PhotoNoteContainer.prototype.DisableAllNotes = function()
{
    for (var i = 0;i<this.notes.length;i++)
        this.notes[i].DisableNote();
};

PhotoNoteContainer.prototype.HideAllNotes = function()
{
    for (var i = 0;i<this.notes.length;i++)
        this.notes[i].HideNote();
};

PhotoNoteContainer.prototype.ShowAllNotes = function()
{
    for (var i = 0;i<this.notes.length;i++)
        this.notes[i].ShowNote();
};

PhotoNoteContainer.prototype.EnableAllNotes = function()
{
    for (var i = 0;i<this.notes.length;i++)
        this.notes[i].EnableNote();
};

PhotoNoteContainer.prototype.FindNote = function(id)
{
    for (var i = 0;i<this.notes.length;i++)
    {
        if(this.notes[i].id == id)
        {
            return this.notes[i];
        }
    }
    return null;
};


/*********************************************************/
/*** Photo Note ******************************************/
/*********************************************************/
function PhotoNote(text,id,author,rect)
{
    var props = {
        text: text,                
        id: id,
        author: author,   
        rect: rect,                    
        selected: false,
        editable: false,
        deletable: false,
        container: null,
        dragresize: null,
        oldRect: null,
        YOffset: 10,
        XOffset: 0,
        onsave: null,
        ondelete: null,
        gui: null,
        queue: 0             
    };

    for (var p in props)
    {
        this[p] = props[p];
    }
    props = null;
    
    this.CreateElements();
}

function Select()
{
    if(!this.container.editing && (this.editable || this.deletable))
    {
        selectedNote = this;
        this.container.HideAllNotes();
        this.container.HideAllNoteTexts();
        this.container.DisableAllNotes();
        this.ShowNote();   
        this.ShowNoteText();
        this.dragresize.select(this.gui.ElementRect);
        this.selected = true;
        this.SetEditable();
    }  
}

PhotoNote.prototype.Select = Select;

function UnSelect()
{
    this.dragresize.deselect(false);
    this.selected = false;
    this.UnSetEditable();
    this.HideNoteText();
    this.HideNote();
    selectedNote = null;
    this.container.ShowAllNotes();
}

PhotoNote.prototype.UnSelect = UnSelect;

function Save()
{
    this.oldRect = null;
    this.text = this.gui.TextBox.value;
    var str = this.text.escapeHTML() +BEFORE_AUTHOR_HTML+this.author+AFTER_AUTHOR_HTML;
    this.gui.TextTitle.innerHTML = str;
    this.UnSelect();
}

PhotoNote.prototype.Save = Save;

function Cancel()
{
    //if the note is still new, then we actually want to delete it, not cancel it..
    if(this.id < 0)
    {
        this.container.DeleteNote(this)
    }
    else
    {
       //reset the node to it's old position 
        if(this.oldRect != null)
        {
            this.rect = this.oldRect;                
        }
        this.oldRect = null;               
        this.gui.TextBox.value = this.text;                
        this.PositionNote();
        this.UnSelect();
    }   
}

PhotoNote.prototype.Cancel = Cancel;


function ShowNoteText()
{
    if(!this.container.editing)
    {
        this.container.HideAllNoteTexts();
        this.container.DisableAllNotes();
        this.EnableNote();

        this.gui.ElementRect.style.border='1px solid #D4D82D';
        this.gui.ElementRect.style.margin='0';
        this.gui.ElementNote.style.display='block';
    }
    else /*when editing a note and mouseover tag list to show 2nd note, */
         /*want to display 2nd note without disabling other notes*/
    {
        this.gui.ElementRect.style.border='1px solid #D4D82D';
        this.gui.ElementRect.style.margin='0';
        this.gui.ElementNote.style.display='block';
    }
}

PhotoNote.prototype.ShowNoteText = ShowNoteText;

function DisableNote()
{
    this.dragresize.enabled=false;
}

PhotoNote.prototype.DisableNote = DisableNote;

function EnableNote()
{
    if (this.editable) this.dragresize.enabled=true;
    else this.dragresize.enabled = false;
}

PhotoNote.prototype.EnableNote = EnableNote;

function HideNoteText()
{
    this.gui.ElementRect.style.border='0px solid #D4D82D';
    this.gui.ElementRect.style.margin='1px';
    this.gui.ElementNote.style.display='none';
}

PhotoNote.prototype.HideNoteText = HideNoteText;

function HideNote()
{
    this.gui.ElementRect.style.display='none';
    this.gui.ElementNote.style.display='none';
}

PhotoNote.prototype.HideNote = HideNote;

function ShowNote()
{
    this.gui.ElementRect.style.display='block';
    this.gui.ElementNote.style.display='none';
}

PhotoNote.prototype.ShowNote = ShowNote;

function SetEditable()
{
    this.container.editing = true;
    
    if(this.editable)
    {
        //the first child of the note is the text
        this.gui.TextTitle.style.display = 'none';
        
        //the second child is the edit area...
        this.gui.EditArea.style.display = 'block';
        
        //if this is a "new" note, then hide the delete button
        if(this.id <= 0)
            this.gui.DeleteButton.style.display = 'none';
        else
            this.gui.DeleteButton.style.display = 'inline';   
   }
   /* deletable: if photo owner but not author of note can only del */
   else 
   {
        if(this.deletable)
        {
            this.gui.TextTitle.style.display = 'none';
            this.gui.EditArea.style.display = 'block';
            this.gui.SaveButton.style.display = 'none';
            //this.gui.DeleteButton.style.display = 'inline';
        }
        else
        {
            //the first child of the note is the text
            this.gui.TextTitle.style.display = 'block';
        
            //the second child is the edit area...
            this.gui.EditArea.style.display = 'none';
        }
   }
}

PhotoNote.prototype.SetEditable = SetEditable; 

function UnSetEditable()
{
    this.container.editing = false;
    
    //the first child of the note is the text
    this.gui.TextTitle.style.display = 'block';
        
    //the second child is the edit area...
    this.gui.EditArea.style.display = 'none';
}

PhotoNote.prototype.UnSetEditable = UnSetEditable;

function TextTimeOut()
{
    try
    {
      this.gui.TextBox.focus();
      this.gui.TextBox.select();
    }
    catch(e) {}
}

function HighlightTextbox()
{
    // get the textarea and select the text...
    if(this.gui.EditArea.style.display=='block')
    {
        setTimeout(TextTimeOut, 200);
    }
}

PhotoNote.prototype.HighlightTextbox = HighlightTextbox;

function DeleteElements()
{
    RecursiveFree(this.gui.ElementRect);
    
    /*this.dragresize.isElement = null;
    this.dragresize.isHandle = null;
    this.dragresize.ondragfocus = null;
    this.dragresize.ondragblur = null;
    this.dragresize.ondragstart = null;
    this.dragresize.ondragend = null;
    this.dragresize.ondragmove = null;
        
    this.gui.ElementRect = null;
    this.gui.ElementNote = null;
    this.gui.EditArea = null;
    this.gui.TextBox = null;
    this.gui.TextTitle.innerHTML = null;
    this.gui.TextTitle = null;
    this.gui.DeleteButton = null;
    this.gui.SaveButton = null;
    
    delete this.dragresize;
    this.dragresize = null;
    
    delete this.gui;
    this.gui = null;*/
}

PhotoNote.prototype.DeleteElements = DeleteElements;

function CreateElements()
{
    this.gui = new PhotoNoteGUI();

    var newArea = document.createElement('div');
    this.dragresize = new DragResize('dragresize', { allowBlur: false });
    newArea.className = 'fn-area';
    newArea.id = 'fn-area-new';

    var newAreaBlack = document.createElement('div');
    newAreaBlack.className = 'fn-area-blackborder';
    var newAreaWhite = document.createElement('div');
    newAreaWhite.className = 'fn-area-whiteborder';
    
    
    var currentNote = this;


    var newAreaInner = document.createElement('div');
    newAreaInner.className = 'fn-area-inner';
    newAreaWhite.appendChild(newAreaInner);


    //attach mouse events to this element...
    newAreaInner.onmouseover = function() {
            currentNote.ShowNoteText();
        };
    newAreaInner.onmouseout = function() {
            if(!currentNote.selected)
            {
                currentNote.HideNoteText();
            }
        };
    newAreaInner.onmousedown = function() {
            if(!currentNote.selected)
            {
                currentNote.Select();
            }
        };

    
    newAreaBlack.appendChild(newAreaWhite);
    newArea.appendChild(newAreaBlack);
    
    // add the notes area
    var noteArea = document.createElement('div');
    noteArea.className = 'fn-note';
    
    var titleArea = document.createElement('div');
    titleArea.className = 'fn-note-text';
    var t = document.createTextNode(this.text);
    titleArea.appendChild(t);
    noteArea.appendChild(titleArea);
    
    var editArea = document.createElement('div');
    editArea.className = 'fn-note-edit';
    
    var editAreaText = document.createElement('div');
    editAreaText.className = 'fn-note-edit-text';
    
    var newTextbox = document.createElement('textarea');
    newTextbox.value = this.text;
    editAreaText.appendChild(newTextbox);
    editArea.appendChild(editAreaText);
    
    var buttonsDiv = document.createElement('div');
    var newButtonOK = document.createElement('input');
    newButtonOK.type='button';
    newButtonOK.className = 'Butt';
    newButtonOK.value='SAVE';
    newButtonOK.onclick = function() {
            
            
            if(currentNote.onsave) 
            {
                var res = currentNote.onsave(currentNote);
                if(res > 0)
                {
                    currentNote.Save();
                }
                else
                {
                    currentNote.Cancel();                        
                }
            }
            else
            {
                currentNote.Cancel();                        
            }
        
             
        };
    buttonsDiv.appendChild(newButtonOK);
    
    var newButtonDelete = document.createElement('input');
    newButtonDelete.type='button';
    newButtonDelete.className = 'CancelButt';
    newButtonDelete.value='DELETE';
    newButtonDelete.onclick = function() {
            if(currentNote.ondelete) 
            {
                var res = currentNote.ondelete(currentNote);
                if(res)
                {
                    currentNote.container.DeleteNote(currentNote);
                }
                else
                {
                    alert("error deleting note");
                }
            }
            else
            {
                alert("ondelete must be implemented in order to *actually* delete");
            }
        };
    buttonsDiv.appendChild(newButtonDelete);
    
    var newButtonCancel = document.createElement('input');
    newButtonCancel.type='button';
    newButtonCancel.className = 'CancelButt';
    newButtonCancel.value='CANCEL';
    newButtonCancel.onclick = function() {
            currentNote.Cancel();            
            
        };
    buttonsDiv.appendChild(newButtonCancel);

    editArea.appendChild(buttonsDiv);
    noteArea.appendChild(editArea);
    

    /********* DRAG & RESIZE EVENTS **********************/
    this.dragresize.isElement = function(elm)
        {
            if(elm.className == 'fn-area')
            {
                /* edit to change draggable area */
                var offset = findPos(document.getElementById('picture'));
                this.maxRight = offset[0] + currentNote.container.width;
                this.maxBottom = offset[1] + currentNote.container.height;
                this.minTop = offset[1];
                this.minLeft = offset[0];
                return true;
            }
        };
    this.dragresize.isHandle = function(elm)
        {
            if(elm.className == 'fn-area')
                return true;
        };
    this.dragresize.ondragfocus = function()
        {
            currentNote.gui.ElementRect.style.cursor = 'move';
        };
    this.dragresize.ondragblur = function()
        {
            currentNote.gui.ElementRect.style.cursor = 'pointer';
        };
    this.dragresize.ondragstart = function()
        {
            if(currentNote.oldRect == null)
            {
                var r = currentNote.rect;
                currentNote.oldRect = new PhotoNoteRect(r.left,r.top,r.width,r.height);
            }
        };
    this.dragresize.ondragend = function()
        {
            //window.status = 'LKSFDLKJDFSLKJFDLKJ';
            currentNote.HighlightTextbox();
        };
    this.dragresize.ondragmove = function() {
            currentNote.rect.left = parseInt(this.element.style.left);
            currentNote.rect.top = parseInt(this.element.style.top);
            currentNote.rect.width = parseInt(this.element.style.width);
            currentNote.rect.height = parseInt(this.element.style.height);
            currentNote.PositionNote();
        };

    this.dragresize.apply(document);
    
    /* setup the GUI object */
    this.gui.ElementRect = newArea;
    this.gui.ElementNote = noteArea;
    this.gui.EditArea = editArea;
    this.gui.TextBox = newTextbox;
    this.gui.TextTitle = titleArea;
    this.gui.TextTitle.innerHTML += (BEFORE_AUTHOR_HTML+this.author+AFTER_AUTHOR_HTML);
    this.gui.DeleteButton = newButtonDelete;
    this.gui.SaveButton = newButtonOK;
    
    /* position the note text below the note area */
    this.PositionNote();   
}

PhotoNote.prototype.CreateElements = CreateElements;

function PositionNote()
{
    /* outer most box */
    this.gui.ElementRect.style.left  = this.rect.left + 'px';
    this.gui.ElementRect.style.top  = this.rect.top + 'px';
    this.gui.ElementRect.style.width  = this.rect.width + 'px';
    this.gui.ElementRect.style.height  = this.rect.height + 'px';
    
    if (this.gui.ElementRect.firstChild == null) 
    {
        //window.status = 'null!!';
        return; /* weird IE problems */
    }
    //else
        //window.status = 'not null';
    // black border
    this.gui.ElementRect.firstChild.style.width  = parseInt(this.gui.ElementRect.style.width) - 2 + 'px';
    this.gui.ElementRect.firstChild.style.height  = parseInt(this.gui.ElementRect.style.height) - 2 + 'px';        
    
    // white border
    this.gui.ElementRect.firstChild.firstChild.style.width  = parseInt(this.gui.ElementRect.style.width) - 4 + 'px';
    this.gui.ElementRect.firstChild.firstChild.style.height  = parseInt(this.gui.ElementRect.style.height) - 4 + 'px';        

    // inner box
    this.gui.ElementRect.firstChild.firstChild.firstChild.style.width  = parseInt(this.gui.ElementRect.style.width) - 6 + 'px';
    this.gui.ElementRect.firstChild.firstChild.firstChild.style.height  = parseInt(this.gui.ElementRect.style.height) - 6 + 'px';        
 
    this.gui.ElementNote.style.left  = this.rect.left + this.XOffset + 'px';
    this.gui.ElementNote.style.top  = this.rect.top + this.YOffset + this.rect.height + 'px';
   
}

PhotoNote.prototype.PositionNote = PositionNote;





/*********************************************************/
/*** Photo Note GUI Object *******************************/
/*********************************************************/
function PhotoNoteGUI()
{
    this.ElementRect = null;
    
    // the note text area...
    this.ElementNote = null;
    this.TextTitle = null;
    this.EditArea = null;
    this.TextBox = null;
    
    // buttons
    this.DeleteButton = null;
    this.SaveButton = null;
}



/*********************************************************/
/*** Rectangle *******************************************/
/*********************************************************/
function PhotoNoteRect(left,top,width,height)
{
    this.left = left;
    this.top = top;
    this.width = width;
    this.height = height;
}

/* for debugging purposes */
PhotoNoteRect.prototype.toString = function()
{
    return 'left: ' + this.left + ', top: ' + this.top + ', width: ' + this.width + ', height: ' + this.height;
}



// *** Common API Code ***
// (c) 2005 Angus Turnbull http://www.twinhelix.come
if (typeof addEvent != 'function')
{
 var addEvent = function(o, t, f, l)
 {
  var d = 'addEventListener', n = 'on' + t, rO = o, rT = t, rF = f, rL = l;
  if (o[d] && !l) return o[d](t, f, false);
  if (!o._evts) o._evts = {};
  if (!o._evts[t])
  {
   o._evts[t] = o[n] ? { b: o[n] } : {};
   o[n] = new Function('e',
    'var r = true, o = this, a = o._evts["' + t + '"], i; for (i in a) {' +
     'o._f = a[i]; r = o._f(e||window.event) != false && r; o._f = null;' +
     '} return r');
   if (t != 'unload') addEvent(window, 'unload', function() {
    removeEvent(rO, rT, rF, rL);
   });
  }
  if (!f._i) f._i = addEvent._i++;
  o._evts[t][f._i] = f;
 };
 
 addEvent._i = 1;
 
 var removeEvent = function(o, t, f, l)
 {
  var d = 'removeEventListener';
  if (o[d] && !l) return o[d](t, f, false);
  if (o._evts && o._evts[t] && f._i) delete o._evts[t][f._i];
 };
}


// Optional cancelEvent() function you can call within your event handlers to
// stop them performing the normal browser action or kill the event entirely.
// Pass an event object, and the second "c" parameter cancels event bubbling.
function cancelEvent(e, c)
{
 e.returnValue = false;
 if (e.preventDefault) e.preventDefault();
 if (c)
 {
  e.cancelBubble = true;
  if (e.stopPropagation) e.stopPropagation();
 }
};


/* Extend the Array object with some useful features 
   http://www.ditchnet.org/wp/?p=8
*/

Array.prototype.clear = function () {
    this.length = 0;
};

Array.prototype.remove = function (element) {
    var result = false;
    var array = [];
    for (var i = 0; i < this.length; i++) {
        if (this[i] == element) {
            result = true;
        } else {
            array.push(this[i]);
        }
    }
    this.clear();
    for (var i = 0; i < array.length; i++) {
        this.push(array[i]);
    }
    array = null;
    return result;
};



