/*	Class: Stylsheet
		Handles manipulation of stylesheets in a cross-browser fashion

	Author:
		Neil Jenkins - http://www.nmjenkins.com

	Version:
		1.0 - 2008.02.01
		
	License:
		GNU GPL 2.0: http://creativecommons.org/licenses/GPL/2.0/

	Dependencies:
		MooTools (minimal)

	Browser support:
		Mozilla (Gecko): 1.0+
		Internet Explorer: 6.0+
		Opera: 9.0+
		Safari: 1.0+ (partial support only - insertRule and deleteRule unsupported)

	Usage:
		To manipulate an existing stylesheet, instantiate a new object with the filename as the argument:
			e.g. var sheet = new Stylesheet(filename);
		To create a new stylesheet, simply omit the argument.

	Methods:
		insertRule(String selector, String rules[, Int position])
			e.g. sheet.insertRule('#id','margin: 3px;');
			Inserts this rule into the stylesheet. If no position is supplied, it is inserted at the bottom.
			Returns a reference to this rule
		getRule(String selector);
			e.g. sheet.getRule('#id').style.margin = '3px';
			Returns a rule object which may be manipulated
		deleteRule(String selector)
			e.g. sheet.deleteRule('#id');
			Deletes the first rule in the stylesheet with this selector.
			This function can alternatively take the index number of the rule to delete.
*/
		
var Stylesheet = new Class({

	initialize: function (filename) {
		for (var i = 0; i < document.styleSheets.length; i++) {
			if (document.styleSheets[i].href.substring(document.styleSheets[i].href.lastIndexOf('/') + 1) == filename)
				this.sheet = document.styleSheets[i];
		}
		if (!this.sheet) {
			var s = new Element('style').inject(document.head);
			this.sheet = document.styleSheets[document.styleSheets.length - 1];
		}
		this.cssRules = this.sheet.cssRules || this.sheet.rules;
	},
	
	insertRule: function (selector, rules, position) {
		position = position || this.cssRules.length;
		if (this.sheet.insertRule)
			this.sheet.insertRule(selector + ' {' + rules + '}', position);
		else
			this.sheet.addRule(selector, rules, position);
		return this.cssRules[position];
	},
	
	getRule: function (selector) {
		return this.cssRules[this.getRuleIndex(selector)] || false;
	},
	
	getRuleIndex: function (selector) {
		selector = selector.toLowerCase();
		for (var i = this.cssRules.length - 1; i >= 0; i--) {
			if (this.cssRules[i].selectorText.toLowerCase() == selector)
				return i;
		}
		return false;
	},
	
	deleteRule: function (index) {
		if (typeof(index) == 'string') index = this.getRuleIndex(index);
		if (index === false) return this;

		if (this.sheet.deleteRule)
			this.sheet.deleteRule(index);
		else
			this.sheet.removeRule(index);
		return this;
	}
});