var noteForm
var notesTable
var searchForm
var searchResultsTable
var noteHover
var noteHoverSides

var notes = new Array()

function notesResize() {
}

function notesInit() {
    noteHoverSides = {
        top: document.getElementById('noteHoverTop'),
        left: document.getElementById('noteHoverLeft'),
        right: document.getElementById('noteHoverRight'),
        bottom: document.getElementById('noteHoverBottom')
    }

    noteForm = document.getElementById('noteForm')
    notesTable = document.getElementById('notesTable').tBodies[0]

    var noteInput = document.getElementById('noteInput')
    if (noteInput) {
        noteInput.onfocus = function() {
            document.onkeypress = ''
        }
        noteInput.onblur = registerControls
    }
    searchForm = document.getElementById('searchForm')
    searchResultsTable = document.getElementById('searchList').tBodies[0]

    noteInput = document.getElementById('searchInput')
    if (noteInput) {
        noteInput.onfocus = function() {
            document.onkeypress = ''
        }
        noteInput.onblur = registerControls
    }
}

function getNotes(x1, y1, x2, y2) {
    var request = initXmlHttp()
    request.open('POST', 'interface/getNotes.php', true)
    request.onreadystatechange = function() { gotNotes(request) }
    request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
    request.send('w=' + world + '&x1=' + x1 + '&y1=' + y1 + '&x2=' + x2 + '&y2=' + y2)
}

function gotNotes(request) {
    if (request.readyState == 4) {
        if (request.status == 200) {
            if (request.responseText) {
                notesTable.parentNode.style.display = 'block'
                var newNotes = request.responseText.split("\n")
                for (var i = 0; i < newNotes.length - 1; i += 7) {
                    if (notesTable.childNodes.length > i / 7)
                        addNote(notesTable.childNodes[i / 7], newNotes[i], newNotes[i+5], newNotes[i+1], newNotes[i+2], newNotes[i+3], newNotes[i+4], new Date(+newNotes[i+6] * 1000))
                    else
                        addNote(null, newNotes[i], newNotes[i+5], newNotes[i+1], newNotes[i+2], newNotes[i+3], newNotes[i+4], new Date(+newNotes[i+6] * 1000))
                }

                var newListLength = ((newNotes.length - 1) / 7)
                while (notesTable.childNodes.length > newListLength) notesTable.removeChild(notesTable.lastChild)
            }
            else {
                notesTable.parentNode.style.display = ''
                while (notesTable.childNodes.length) 
                    notesTable.removeChild(notesTable.firstChild)
            }
        }
    }
}

function getNotesByString() {
    var query = escape(searchForm.query.value)
    var request = initXmlHttp()
    request.open('POST', 'interface/getNotesByString.php', true)
    request.onreadystatechange = function() { gotNotesByString(request) }
    request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
    request.send('w=' + world + '&t=' + query)
}
function gotNotesByString(request) {
    if (request.readyState == 4) {
        if (request.status == 200) {
            if (request.responseText) {
                searchResultsTable.parentNode.style.display = 'block'
                var newNotes = request.responseText.split("\n")
                for (var i = 0; i < newNotes.length - 1; i += 7) {
                    if (searchResultsTable.childNodes.length > i / 7)
                        addSearchResult(searchResultsTable.childNodes[i / 7], newNotes[i], newNotes[i+5], newNotes[i+1], newNotes[i+2], newNotes[i+3], newNotes[i+4], new Date(+newNotes[i+6] * 1000))
                    else
                        addSearchResult(null, newNotes[i], newNotes[i+5], newNotes[i+1], newNotes[i+2], newNotes[i+3], newNotes[i+4], new Date(+newNotes[i+6] * 1000))
                }

                var newListLength = ((newNotes.length - 1) / 7)
                while (searchResultsTable.childNodes.length > newListLength) searchResultsTable.removeChild(searchResultsTable.lastChild)
            }
            else {
                searchResultsTable.parentNode.style.display = ''
                while (searchResultsTable.childNodes.length) 
                    searchResultsTable.removeChld(searchResultsTable.firstChild)
            }
        }
    }
}

function postNote() {
    var noteX = mapX
    var noteX2 = mapX2
    var noteY = mapY
    var noteY2 = mapY2
    if (1 == zoom) {
        noteX = mapX*0.75 + 0.25*mapX2
        noteX2 = mapX*0.25 + 0.75*mapX2
        noteY = mapY*0.75 + 0.25*mapY2
        noteY2 = mapY*0.25 + 0.75*mapY2
    }
    var request = initXmlHttp()
    request.open('POST', 'interface/postNote.php', true)
    request.onreadystatechange = function() { postedNote(request) }
    request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
    request.send('note=' + escape(noteForm.note.value) + '&w=' + world + '&x1=' + noteX + '&y1=' + noteY + '&x2=' + noteX2 + '&y2=' + noteY2)
}

function leftPad(num, nPad) {
    var nChars = num == 0 ? 1 : Math.floor((Math.log(num) / Math.log(10)) + 1)
    var ret = ''
    for (var i = nChars; i < nPad; ++i) ret += '0'
    return ret + num
}

function dateFormat(d) {
    return leftPad(d.getYear() + (+d.getYear() < 2000 ? 1900 : 0), 4) + 
        '/' + leftPad(d.getMonth(), 2) + '/' + leftPad(d.getDate(), 2) + ' ' + 
        leftPad(d.getHours(), 2) + ':' + leftPad(d.getMinutes(), 2) + ':' + 
        leftPad(d.getSeconds(), 2)
}

function Note(node, x, y, width, height) {
    this.node = node
    this.x = x
    this.y = y
    this.width = width
    this.height = height
}

function displayNoteHover(note) {
    var tileZoomWidth = tileWidth * zoom
    var tileZoomHeight = tileHeight * zoom
    var highlightX = (note.x - (mapX + mapSubX)) * tileZoomWidth 
    var highlightY = (note.y - (mapY + mapSubY)) * tileZoomHeight
    var highlightMaxX = highlightX + note.width * tileZoomWidth
    var highlightMaxY = highlightY + note.height * tileZoomHeight
    
    //this part is visible!
    highlightX = Math.max(highlightX, 0)
    highlightY = Math.max(highlightY, 0)
    highlightMaxX = Math.min(highlightMaxX, canvasWidth)
    highlightMaxY = Math.min(highlightMaxY, canvasHeight)
    
    var highlightW = highlightMaxX - highlightX
    var highlightH = highlightMaxY - highlightY

    noteHoverSides.top.style.left = '0px'
    noteHoverSides.top.style.top = '0px'
    noteHoverSides.top.style.width = canvasWidth + 'px'
    noteHoverSides.top.style.height = highlightY + 'px'
    noteHoverSides.top.style.display = 'block'

    noteHoverSides.left.style.left = '0px'
    noteHoverSides.left.style.top = highlightY + 'px'
    noteHoverSides.left.style.width = highlightX + 'px'
    noteHoverSides.left.style.height = highlightH + 'px'
    noteHoverSides.left.style.display = 'block'

    noteHoverSides.right.style.left = highlightMaxX +'px'
    noteHoverSides.right.style.top = highlightY + 'px'
    noteHoverSides.right.style.width = (canvasWidth - highlightMaxX) + 'px'
    noteHoverSides.right.style.height = highlightH + 'px'
    noteHoverSides.right.style.display = 'block'

    noteHoverSides.bottom.style.left = '0px'
    noteHoverSides.bottom.style.top = highlightMaxY + 'px'
    noteHoverSides.bottom.style.width = canvasWidth + 'px'
    noteHoverSides.bottom.style.height = (canvasHeight - highlightMaxY) + 'px'
    noteHoverSides.bottom.style.display = 'block'
}

function hideNoteHover() {
    noteHoverSides.top.style.display = 'none'
    noteHoverSides.left.style.display = 'none'
    noteHoverSides.right.style.display = 'none'
    noteHoverSides.bottom.style.display = 'none'
}

function attachNoteHoverEvent(note) {
    note.node.onmouseover = function() {
        var hover = displayNoteHover(note)
        note.node.onmouseover = null
        note.node.onmouseout = function() {
            hideNoteHover();
            attachNoteHoverEvent(note)
        }
    }
}

function addNoteAbstract(table, row, friend, note, x1, y1, x2, y2, theDate) {
    if (! row) {
        row = document.createElement('tr') 
        // table.insertBefore(row, table.firstChild)
        table.appendChild(row)
        if (1 == table.childNodes.length % 2) {
            row.className = 'odd'
        }

        var nameCell = document.createElement('td')
        nameCell.className = 'name'
        nameCell.innerHTML = friend
        row.appendChild(nameCell)

        var noteCell = document.createElement('td')
        noteCell.className = 'note'
        noteCell.innerHTML = note
        row.appendChild(noteCell)

        var dateCell = document.createElement('td')
        dateCell.className = 'date'
        dateCell.innerHTML = dateFormat(theDate)
        row.appendChild(dateCell)
    }
    else {
        row.cells[0].innerHTML = friend
        row.cells[1].innerHTML = note
        row.cells[2].innerHTML = dateFormat(theDate)
    }

    return row
}

function addNote(row, friend, note, x1, y1, x2, y2, theDate) {
    row = addNoteAbstract(notesTable, row, friend, note, x1, y1, x2, y2, theDate)
    attachNoteHoverEvent(new Note(row, x1, y1, x2 - x1, y2 - y1))
}

function addSearchResult(row, friend, note, x1, y1, x2, y2, theDate) {
    row = addNoteAbstract(searchResultsTable, row, friend, note, x1, y1, x2, y2, theDate)

    var noteZoom = Math.floor(Math.max(mapWidth/(x2 - x1), mapHeight/(y2 - y1)));
    var noteURL  = '?unique' + (++uniqueId) + '#' + addressParameters(x1, y1, noteZoom)

    if (row.cells.length < 4) {
        var viewCell = document.createElement('td')
        viewCell.className = 'view'
        viewCell.innerHTML = '<a href="' + noteURL + '">view</a>'
        row.appendChild(viewCell)
    }
    else row.cells[3].innerHTML = '<a href="' + noteURL + '">view</a>'
}

function postedNote(request) {
    if (request.readyState == 4) {
        if (request.status == 200) {
            // move the note to the display area
            notesTable.parentNode.style.display = 'block'
            addNote(null, name, noteForm.note.value, mapX, mapY, mapX2, mapY2, new Date())
            noteForm.note.value = ''
        }
        else {
            // TODO: log error somehow
        }
    }
}

