 
 StyleMap = [];
 MergedStyles   = null;
-BufferedStyles = null;
+Buffer = "";
 
-rewriteCSSURLs = require('css-url-rewriter')
+# replaceRule = (sheet, selector, cssText, index)->
+#     if sheet.removeRule then sheet.removeRule(index) else sheet.deleteRule(index);
+#     rule = if selector then selector + '{' + cssText + '}' else cssText
+#     if sheet.addRule then sheet.addRule(selector, cssText, index) else sheet.insertRule(rule, index);
 
 createStyleSheet = (content="", disabled=false)->
   style = document.createElement('style')

processDocument = (prefix, doc)->
  # Create and initialize a new global stylesheet that will receive merged styles in the right order
  MergedStyles = createStyleSheet("") unless MergedStyles
  BufferedStyles = createStyleSheet("") unless BufferedStyles
  BufferedStyles.disabled=true

  # Under Firefox, you can't change css Rules or the containing
  # style tag or those will be reset when touching anything else.
  # Resort to building an entirely new stylesheet without copying cssRules

  # Clear the Merged Styles
  empty(BufferedStyles.sheet)

  # Promise manipulation ensures stylesheets are loaded in the correct order even if they are async.
  promise = new Promise (resolve, reject)-> resolve()

  # IE doens't support inserting at any position.
  # Reverse stylesheets and insert from the end first.
  _.map doc.styleSheets, (sheet)->
    unless sheet.disabled
      sheet.disabled=true
      t = promise.then ()->
        o = appendStyle(prefix, sheet)
        console.log o
        o
      , (err)-> console.log err
      console.log t
      promise = t

  promise.then ()-> 
    for rule, i in BufferedStyles.sheet.cssRules
      cssText = prefixRule(prefix, BufferedStyles.sheet, rule, i);
      MergedStyles.sheet.insertRule(cssText, MergedStyles.sheet.cssRules.length)
    true

processStyle = (prefix, node)->
  Array.prototype.slice.call(node.querySelectorAll('style:not([data-scoped])')).forEach (node)->
    node.setAttribute('data-scoped',true);
    new ScopedCss(prefix, null, node).process()

module.exports = {
  processDocument: processDocument
  processStyle: processStyle,
  addLink: addLink,
}

  document.head.appendChild(style)
  style

removeStyleSheet = (style)-> style.parentNode?.removeChild(style)

getRules = (sheet)->
  return unless sheet?
  sheet.cssRules || sheet.rules

empty = (sheet)->
