
var SiteAttitude = new Object();

Object.extend(SiteAttitude, {
    sheets: [],

    append: function(sheet){
        this.sheets.push(sheet);
    },

    start: function(){
        for( var i=0; sheet=this.sheets[i]; i++ )
            this.update(sheet);
    },

    update: function(sheet){ // based on behaviour: http://bennolan.com/behaviour/
        for( selector in sheet ){
            var combs = selector.split(',');

            for( c=0; comb=combs[c]; c++ ){
                var elements = this.getSelector(comb.replace(/^\s*|\s*$/g,"")) || null;
                for( var i=0; element=elements[i]; i++ )
                    sheet[selector](element);
            }
        }
    },

    getSelector: function(selector){
        var args    = selector.split(' ');
        var params  = [];

        for( var j=0; arg=args[j]; j++ ){
            params[j] = param = new Array();

            if( args[j].indexOf('#')>-1 ){
                var bits        = arg.split('#');
                param['tag']    = bits[0] || '*';
                param['id']     = bits[1];
            }else if( args[j].indexOf('.')>-1 ){
                var bits        = arg.split('.');
                param['tag']    = bits[0] || '*';
                param['class']  = bits[1];
            }else{
                param['tag'] = arg;
            }
        }

        this.filter = [document];

        for( var k=0; param=params[k] ;k++ ){
            if( k==0 && param['id'] ){
                if( param['tag']=='*' || $(param['id']).tagName.toLowerCase()==param['tag'] )
                    this.filter = [$(param['id'])];
                else
                    return [];

                continue;
            }

            this.filter = this.getElementsWithTagName(param['tag']);

            if( param['class'] )
                this.filter = this.getElementsWithClassName(param['class']);
            else if( param['id'] )
                this.filter = this.getElementsWithId(param['id']);
        }

        return this.filter;
    },

    getElementsWithId: function(id){
        var found = [];
        for( var i=0; el=this.filter[i]; i++ ){
            if( el.id==id )
                found.push(el);
        }

        return found;
    },

    getElementsWithClassName: function(className){
        var found = [];

        for( var i=0; el=this.filter[i]; i++ ){
            if( Element.hasClassName(el, className) )
                found.push(el);
        }

        return found;
    },

    getElementsWithTagName: function(tagName){
        var found = [];

        for( var i=0; el=this.filter[i]; i++ ){
            var tagNames = el.getElementsByTagName(tagName);

            for( var j=0; tag=tagNames[j]; j++ )
                found.push(tag);
        }

        return found;
    }
});