/*
    RealTown Star plugin
    Allows you to make any hyperlink "starrable"
    by adding an image next to it that can be clicked
    for starring/unstarring the link

    Copyright (c)2007 RealTown(r)
*/



function RT_Star() {
    var star_on = '/images/buttons/star_on.png';
    var star_off = '/images/buttons/star_off.png';
    
    var toggleStar = function(event) {
        
        Event.stop(event);
        var element = Event.findElement(event, 'A');
        var id;
        if(!(id = element.getAttribute('id'))) return false;
        
        // Submit ajax response to the anchor's HREF attribute
        var href = element.getAttribute('href');
        if(!href) return false;
        
        new Ajax.Request(href, {
            method: 'get',
            onSuccess: function(t, json) {
                
                // Find img with class star within this anchor
                var id = 'starimg_' + json.id;
                if(!($(id))) return false;
                $(id).src = json.starred ? star_on : star_off;
                
            },
            onFailure: function(t) {
                alert('There was an error processing the action.\n\nError Message: ' + t.errorText);
            }
        });
        
        return false;
    }
    
    
    
    this.activate = function(element) {
        if(!(element = $(element))) return false;
        Event.observe(element, 'click', toggleStar.bindAsEventListener(RT_Star));
    }
}


RT_Star.prototype = {

    // Find all stars on the page with the given class name
    // and make them clickable
    
    find:       function(selector) {
                    if (typeof(selector) == 'undefined') var selector = '.star';
                    var stars = $$(selector);
                    var star;
                    for (var i = 0; i < stars.length; i++) {
                        star = stars[i];
                        this.activate(star);
                    }
                }
}


if(!window.RT) { window['RT'] = {}; }
window['RT']['star'] = new RT_Star();