// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

function getTags(field) {
    tag_list = $(field).value;

    // separate the comma-separated tags and exclude tokens that are empty ""
    tags = tag_list.split(/\s*,\s*/g).without("");
    
    return tags.collect(function(t) {
        return t.replace(/(^\s+)|(\s+$)/g, "");
    })
}

function swap(tag, field) {
    var tokens = getTags(field)
    
    if (tokens.find(function(t) { return (t == tag) }) == null) {
        tokens.push(tag);
    } else {
        tokens = tokens.without(tag)
    }
    
    $(field).value = tokens.join(", ")
}

var word_tags = null;
function updateWordTags() {
    var tokens = getTags("word_tag_names")
    
    if (word_tags == null) {
        word_tags = $$(".word_tag")
    }
    word_tags.each(function(tag) {
        Element.removeClassName(tag, "selected_tag")
    })
    
    tokens.each(function(token) {
        var link = token + "_word_tag"
        Element.addClassName(link, "selected_tag")    
    })    
}

function swapColor(tag) {
	swap(tag, 'color_tag_names');
	updateColorPalette('_color_tag');
	updateColorCanvas();
}

var color_tags = null;
function updateColorPalette(link_suffix) {
    var tokens = getTags("color_tag_names")
    
    if (color_tags == null) {
        color_tags = $$(".color_tag")
    }
    color_tags.each(function(tag) {
        Element.removeClassName(tag, "selected_tag")
    })
    
    tokens.each(function(token) {
        var link = token + link_suffix
        Element.addClassName(link, "selected_tag")    
    })
}

function updateColorCanvas() {
    var tokens = getTags("color_tag_names")
    
    color_band_height = 100
    canvas_html = tokens.map( function(color) {
        var html = "<div style='position:absolute;bottom:0;width:100%;"
        html += "height:" + color_band_height + "%;"
        html += "background-color:" + color 
        html += "'>"
        html += "</div>"
        color_band_height -= (100.0 / tokens.length)
        return html
    });
    
    Element.update("color_canvas", canvas_html.join(""));
}