function switchToEdit() {
    $('view').hide()
    $('edit').show()
    $('code').focus()
}

var allOptions = ["nl", "br", "indentNbsp", "surroundWithPre"]

function selectOptions(options) {
    allOptions.each(function(s) {
        $(s).checked = options.indexOf(s) >= 0
    })
    formatForBlog()
}

/*
function forLj() {
    selectOptions(["nl", "surroundWithPre"])
}
*/

function forAnySite() {
    selectOptions(["nl", "surroundWithPre"])
}

///

var styleDataMap = {}

function tokenNamePartsToKey(parts) {
    return parts.join("-")
}

// XXX: add to Array
function take(array, count) {
    var r = []
    for (var i = 0; i < count; ++i) {
        r.push(array[i])
    }
    return r
}

function initializeStyleDataMap() {
    styleDataMap = {}
    styleData.each(function(ts) {
        ts.tokenTypes.each(function(tokenType) {
            var key = tokenNamePartsToKey(tokenType)
            styleDataMap[key] = ts.style
        })
    })
}

function onLoad() {
    initializeStyleDataMap()
    formatForBlog()
}

///

function formatIndent(token, options) {
    if (options.indentNbsp) {
        return token.string.replace(/ /g, "&nbsp;")
    } else {
        return token.string
    }
}

function formatSpace(token, options) {
    if (token.string.length > 1) {
        return token.string.replace(/ /g, "&nbsp;")
    } else {
        return token.string
    }
}

function formatNewline(token, options) {
    var r = ""
    if (options.br) {
        r += "<br/>"
    }
    if (options.nl) {
        r += "\n"
    }
    return r
}

function formatOther(token, options) {
    //debug("token " + token.string + " .. " + token.typeName)
    var style = ""
    for (var i = 1; i <= token.typeNameParts.length; ++i) {
        var key = tokenNamePartsToKey(take(token.typeNameParts, i))
        styleAddition = styleDataMap[key]
        if (styleAddition) {
            if (style.length == 0)
                style = styleAddition
            else
                style = style + "; " + styleAddition
        }
    }
    if (style.length > 0) {
        return "<span style='" + style + "'>" + token.string.escapeHTML() + "</span>"
    } else {
        return token.string.escapeHTML()
    }
}

function doFormat(tokens, options) {
    var result = ""
    tokens.each(function(token) {
        var ff
        if (token.newline) ff = formatNewline
        else if (token.indent) ff = formatIndent
        else if (token.whitespace) ff = formatSpace
        else ff = formatOther
        result += ff(token, options)
    })
    if (options.surroundWithPre) {
        result = "<pre>" + result + "</pre>"
    }
    return result
}


function formatForBlog() {
    var options = new Object()
    allOptions.each(function (o) {
        options[o] = $(o).checked
    })
    
    var formatted = doFormat(tokens, options)
    $('forBlog').value = formatted
}

// vim: set ts=4 sw=4 et:
