////////////////////////////////////////////////////////////////////////////////
// Copyright 2006-2008 James Pike

/* from config */
/*
brushSize zoom fgColour bgColour
*/

// global variables
// var cacheBorder = 0

function setCookie(key, value) {
    document.cookie =
        key + '=' + value + '; expires=Thu, 14 March 3001 20:47:11 UTC; path=/'
}

function setCanvasType(aType) {
    setCookie('canvas', aType)
    blaggartLoadCanvas()
}

function restoreContextVariable(key, value) {
    if ('f' == key) fgColour = value
    else if ('b' == key) bgColour = value
    else if ('x' == key) {
        value = +value
        if (! isNaN(value)) mapX = +value
    }
    else if ('y' == key) {
        value = +value
        if (! isNaN(value)) mapY = +value
    }
    else if ('z' == key) {
        value = +value
        if (value >= 1 && value <= 8) zoom = value
    }
}

function restoreContext() {
    var cookies = document.cookie.split(/; */)
    for (var i = 0; i < cookies.length; ++i) {
        var pair = cookies[i].split('=')
        if ('name' == pair[0]) name = pair[1]
        else restoreContextVariable(pair[0], pair[1])
    }

    var hashParams = window.location.hash.substring(1).split('&')
    for (var i = 0; i < hashParams.length; ++i) {
        var pair = hashParams[i].split('=')
        restoreContextVariable(pair[0], pair[1])
    }

    // var getStart = hashParams.indexOf('?')
    // if (getStart != -1) {
    //     var getParams = window.location.href.substring(getStart + 1)
    //     for (var i = 0; i < getParams.length; ++i) {
    //         var pair = getParams[i].split('=')
    //         restoreContextVariable(pair[0], pair[1])
    //     }
    // }
}

function storeLocationContext() {
    window.location.hash = addressParameters()
    setCookie('x', mapX)
    setCookie('y', mapY)
    setCookie('z', zoom)
}

function updateLocation() {
    document.getElementById('coordinates').innerHTML = '<a href="#' + addressParameters() + '">' + "Current Location: (" + mapX + ", " + mapY + ")" + '</a>'
    storeLocationContext()
}

var uniqueId = new Date().getTime()

function addressParameters(x, y, z) {
    return "x=" + (x || mapX) +  '&y=' + (y || mapY) + '&z=' + (z || zoom)
}

function setLocation(_mapX, _mapY) {
    mapX = _mapX
    mapY = _mapY
    mapSubX = 0
    mapSubY = 0
    mapX2 = mapX + mapWidth
    mapY2 = mapY + mapHeight
    updateLocation()
    getNotes(mapX, mapY, mapX2, mapY2)
}   

function setLocationPrecise(_mapX, _mapY) {
    setLocation(Math.floor(_mapX), Math.floor(_mapY));
	mapSubX = niceMod(_mapX, 1)
	mapSubY = niceMod(_mapY, 1)
}   

function setZoom(_zoom) {
    if (_zoom != zoom) {
        zoom = _zoom
        mapWidth = canvasWidth / (tileWidth * zoom)
        mapHeight = canvasHeight / (tileHeight * zoom)
        mapX2 = mapX + mapWidth
        mapY2 = mapY + mapHeight
        notesResize()
        storeLocationContext()
        getNotes(mapX, mapY, mapX2, mapY2)
    }
}

var onloads = []
function onLoad(callback) {
    onloads.push(callback)
}

var debugDiv = null
var blaggart = null

function rand(min, max) {
    return Math.floor(Math.random() * (max - min)) + min
}

function fadeColour(min) {
    var first = Math.floor(Math.random() * 3) 
    var second = Math.floor(Math.random() * 2) + 1
    var third = (first + 3 - second) % 3
    second = (first + second) % 3

    var codes = [ 0, 0, 0 ]
    codes[first] = rand(min, 255)
    var left = codes[first] - 255 + min
    codes[second] = rand(left, 255)
    var left = codes[second] - 255 + min
    codes[third] = rand(left, 255)
    return 'rgb(' + codes[first] + ',' + codes[second] + ',' + codes[third] + ')'
}

function startBlaggartEngine() {
    blaggart = document.getElementById('blaggart')
    debugDiv = document.getElementById('debug')
    for (var i = 0; i < onloads.length; ++i) onloads[i]()
    onloads.length = 0
}

// debugging functions
function printDebug(str) {
    debugDiv.innerHTML = str
}

function minMax(id, link) {
    var tool = document.getElementById(id)
    if ('none' == tool.style.display) {
        link.innerHTML = '-'
        tool.style.display = ''
    }
    else {
        link.innerHTML = '+'
        tool.style.display = 'none'
    }
}

function setActiveStylesheet(title, loc) {
    var a
    for (var i = 0; (a = document.getElementsByTagName("link")[i]); ++i) {
        if (-1 != a.getAttribute("rel").indexOf("style") && a.getAttribute("title")) {
            a.disabled = a.getAttribute("href") != loc
        }
    }
}

function getActiveStylesheet(title) {
    var a
    for (var i = 0; (a = document.getElementsByTagName("link")[i]); ++i) {
        if (-1 != a.getAttribute("rel").indexOf("style") && a.getAttribute("title") && ! a.disabled)
            return a.getAttribute("href")
    }
}


function changeLook() {
    var active = getActiveStylesheet('toolbar')
    if (active == 'css/toolbar-right.css')
        setActiveStylesheet('toolbar', 'css/toolbar-left.css')
    else
        setActiveStylesheet('toolbar', 'css/toolbar-right.css')
}

function blaggartGo(loc) {
    if (/MSIE (\d+\.\d+);/.test(navigator.userAgent))
        window.location.href=loc;
    else if (/webkit/.test(navigator.userAgent.toLowerCase()))
        window.location.href=loc;
    else
        window.location.pathname = loc
}

function blaggartLoadCanvas() {
    var idx = window.location.pathname.lastIndexOf('/')

    if (-1 != idx) blaggartGo(window.location.pathname.substring(0, idx + 1))
    else blaggartReload()
}

function blaggartReload() {
    blaggartGo(window.location.pathname)
}

function logout() {
    setCookie('id','')
    setCookie('session','')
    window.location.reload()
}
