// JavaScript Document

var CSSRule = {
  remove: function() {
    this.parentStyleSheet.deleteRule( this.index());
  },
  replace: function( style ) {
    style = CSS.styleToString( style );
    var index = this.index();
    if ( !this.parentStyleSheet.addRule )
      CSS.extendSheet( this.parentStyleSheet );
    this.parentStyleSheet.addRule( this.selectorText, style, index );
    var result = (this.parentStyleSheet.rules || this.parentStyleSheet.cssRules)[index];
    this.remove();
    return $extend( result, CSSRule );
  },
  index: function() {
    return Array.indexOf( this.parentStyleSheet.rules || this.parentStyleSheet.cssRules, this );
  }
};

var CSS = new new Class({
  findRules: function( target ) {
    var result = new Array;
    Array.each( document.styleSheets, function( sheet, sheetIndex ) {
      CSS.extendSheet( sheet );
      Array.each( sheet.rules || sheet.cssRules, function( rule, ruleIndex ) {
        if ( rule.selectorText!=target )
          return;
        result.push( $extend( rule, CSSRule ));
      });
    });
    return result;
  },
  addRule: function( sheet, selector, style, index ) {
    if ( !sheet && !document.styleSheets )
      document.createStyleSheet();
    if ( !sheet )
      sheet = document.styleSheets[0];
    if ( !index )
      index = 0;
    style = CSS.styleToString( style );
    CSS.extendSheet( sheet ).addRule( selector, style, index );
    return (sheet.rules || sheet.cssRules)[ index ];
  },
  extendSheet: function( sheet ) {
    return sheet.extended ? sheet : $extend( sheet, Browser.ie ?
      // MSIE
      {
        extended: true,
        oldAddRule: sheet.addRule,
        addRule: function( selector, style, index ) {
          style = CSS.styleToString( style );
          return this.oldAddRule( style, index );
        },
        insertRule: function( def, index ) {
          var x = def.match(/([^{]+){([^}]*)}/);
          return this.oldAddRule( x[0], x[1], index );
        }
      } :
      // GECKO
      {
        extended: true,
        addRule: function( selector, style, index ) {
          return this.insertRule( selector + ' {' + CSS.styleToString( style ) + '}', index );
        }
      });
  },
  styleToString: function( style ) {
    if ( $type( style )=='string' )
      return style;
    var result = new Array;
    for ( var prop in style ) {
      result.push( prop+': '+style[prop] );
    }
    return result.join( ';\n' );
  }
});


