TagCloud = function(container, tags_container) {
    this.container = container;
    this.tags_container = tags_container;
    this.tags = [];
}

TagCloud.prototype.add_tags = function(new_tags, level) {
    for (var i = 0; i < new_tags.length; i++) {
        this.tags.push({ tag: new_tags[i], level: level}); 
    }
}

TagCloud.prototype.render = function() {
    this.tags.sort(function(a, b) {
        var x = (a.tag == '.NET' ? 'NET' : a.tag);
        var y = (b.tag == '.NET' ? 'NET' : b.tag);
        if (x == y)
            return 0;
        else
            return x.toLowerCase() > y.toLowerCase() ? 1 : -1; 
    });
    
    out = '<div id="' + this.tags_container.substring(1) + '">';
    for (var i = 0; i < this.tags.length; i++) {
        var tag = this.tags[i];
        out = out + '<span class="tag level-' +  tag.level + '">' + tag.tag + '</span> ';
    } 
    out = out + '</div>';
    
    $(this.container).html(out);
    
    $(this.container + ' span.tag').mouseenter(function() {
        var new_color = null;
        if ($(this).hasClass('level-1'))
            new_color = '#003';
        else if ($(this).hasClass('level-2'))
            new_color = '#005';
        else if ($(this).hasClass('level-3'))
            new_color = '#007';
        else if ($(this).hasClass('level-4'))
            new_color = '#009';
        else if ($(this).hasClass('level-5'))
            new_color = '#00a';
            
        if (new_color != null) {
            $(this).stop();
            $(this).animate({ color:new_color }, 200);
        }
    });
    
    $(this.container + ' span.tag').mouseleave(function() {
        var new_color = null;
        if ($(this).hasClass('level-1'))
            new_color = '#fff';
        else if ($(this).hasClass('level-2'))
            new_color = '#ffc';
        else if ($(this).hasClass('level-3'))
            new_color = '#ff9';
        else if ($(this).hasClass('level-4'))
            new_color = '#ff6';
        else if ($(this).hasClass('level-5'))
            new_color = '#ff3'; 
               
        if (new_color != null) {
            $(this).animate({ color:new_color }, 3000);
        }
    });
}

TagCloud.prototype.resize = function() {
    var cloud = $(this.container);
    var tags = $(this.tags_container);
    
    var increment = 0.5;
    for (var font_size = 5.0; font_size < 30.0; font_size = font_size + increment) {
        cloud.css('font-size', font_size + 'px');
        if (tags.height() > cloud.height()) {
            cloud.css('font-size', (font_size - increment) + 'px');
            break;
        }
    }
}