/* Copyright (c) 2008 Gilberto Saraiva (saraivagilberto@gmail.com || http://slr.projects.pro.br)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Version: 2008.0.1.1 -
 * Under development and testing
 *
 * Requires: jQuery 1.2+
 */

(function( $ ){
  $.cssRule = function (selector, stylename, value) {
    var ss, rules;
   
    // make sure there is a stylesheet available
    if (document.styleSheets.length <= 0) {
      if (document.createStyleSheet) {
        document.createStyleSheet();
      } else {
        var styleTag = document.createElement("style");
        styleTag.type = "text/css";
        document.getElementsByTagName("head")[0].appendChild(styleTag);
      }
    }
   
    // convert the stylename to camel case if necessary
    ccstylename = (stylename || "").replace(/\-(\w)/g, function (m, c) { return (c.toUpperCase()); });
    ccstylename = (ccstylename == 'float') ? 'cssFloat' : ccstylename;
    selector = selector.toLowerCase();
   
    // loop to delete or change the css
    for (var i = 0; i < document.styleSheets.length; i++) {
      ss = document.styleSheets[i];
      rules = ss.cssRules || ss.rules;
      
      for (var j = 0, len = rules.length; j < len; j++) {
        if (rules[j].selectorText && rules[j].selectorText.toLowerCase() == selector) {
          if (value != null) {
            rules[j].style[ccstylename] = value;
          } else {
            if (ss.deleteRule) {
              ss.deleteRule(j);
            } else if (ss.removeRule) {
              ss.removeRule(j);
            } else {
              // poor man's delete
              rules[j].style.cssText = "";
            }
          }
          return;
        }
      }
    }
   
    if (stylename && value) {
      // if the selector wasn't found and isn't supposed to be deleted then add it
      ss = document.styleSheets[0];
      rules = ss.cssRules || ss.rules;
      if (ss.insertRule) {
        ss.insertRule(selector + "{" + stylename + ":" + value + "; }", rules.length);
      } else if (ss.addRule) {
        ss.addRule(selector, stylename + ":" + value + ";", rules.length);
      } else {
        throw new Error("Selector not found and add/insert rule not supported.");
      }
    }
  };
})( jQuery );
