if(!window.lim){ var lim = {display:{}}; }
if(!lim.display){ lim.display = {}; }
/**
 * @author Marcelo Miranda Carneiro - mcarneiro@gmail.com
 */
;(function(scope){

	var DynamicCSS = function(){
		var _rulesCounter = 0;

		this.rules = {};
		this.index = 0;
		this.stylesheetNode = document.createElement('style'),
		this.stylesheetNode.type = 'text/css';
		this.stylesheetNode.rel = 'stylesheetNode';
		this.stylesheet = null;
		
		this.addRule = function(/* p_selector, p_value */){
			return this.addRule[arguments[0].constructor].apply(this, arguments);
		};
		this.addRule[String] = function(p_selector, p_value){
			this.rules[p_selector] = {
				index: _rulesCounter,
				value: p_value
			};
			if (this.stylesheet.addRule) {
				this.stylesheet.addRule(p_selector, p_value, _rulesCounter++);
			} else {
				this.stylesheet.insertRule(p_selector+'{'+p_value+'}', _rulesCounter++);
			}
			return this;
		};
		this.addRule[Object] = function(p_rules){
			if(p_rules){
				for(var n in p_rules){
					if(p_rules.hasOwnProperty(n)){
						this.addRule(n, p_rules[n]);
					}
				}
			}
			return this;
		};
		
		this.getRule = function(p_selector){
			return this.rules[p_selector] || {index:-1, value:''};
		};
		
		this.removeRule = function(){
			return this.removeRule[arguments.length > 1 ? 1 : 0].apply(this, arguments);
		};
		this.removeRule[0] = function(p_selector){
			var index = this.getRule(p_selector).index;
			if(index>=0){
				if (this.stylesheet.deleteRule) {
					this.stylesheet.deleteRule(index);
				} else {
					this.stylesheet.removeRule(index);
				}
				for(var n in this.rules){
					if(this.rules.hasOwnProperty(n) && this.rules[n].index > index){
						this.rules[n].index --;
					}
				}
			}
			return this;
		};
		this.removeRule[1] = function(){
			for(var i=0, len=arguments.length; i < len; i++){
				this.removeRule(arguments[i]);
			}
			return this;
		};
		this.removeAllRules = function(){
			for(var n in this.rules){ this.removeRule(n); }
		};
		
		document.getElementsByTagName('head')[0].appendChild(this.stylesheetNode);
		this.stylesheet = document.styleSheets[document.styleSheets.length-1];
	};
	scope.DynamicCSS = DynamicCSS;

})(lim.display);
