/* **** wired/stylesheet.js start **** */

if (typeof Wired == 'undefined') var Wired = {};

Wired.Stylesheet = function(styleSheet) {
	this._styleSheet = styleSheet;
};

Wired.Stylesheet.tableCell = function() {
	if (typeof this._tableCell == 'undefined') {
		this._tableCell = 'table-cell';
		try {
			var td = document.createElement('td');
			td.style.display = this._tableCell;
		} catch (e) {
			this._tableCell = 'block';
		}
	}
	return this._tableCell;
};

Wired.Stylesheet.tableRow = function() {
	if (typeof this._tableRow == 'undefined') {
		this._tableRow = 'table-row';
		try {
			var tr = document.createElement('tr');
			tr.style.display = this._tableRow;
		} catch (e) {
			this._tableRow = 'block';
		}
	}
	return this._tableRow;
};

Wired.Stylesheet.addRule = function(selector, property, media) {
	if (typeof media == 'undefined') {
		media = 'screen';
	}
	this.lastStylesheet(media).insertRule(selector, property);
};

Wired.Stylesheet.lastStylesheet = function(media) {
	if (typeof media == 'undefined') {
		media = 'screen';
	}
	var media_regex = new RegExp('all|' + media, 'i');
	for (var i = document.styleSheets.length - 1; i >= 0; i--) {
		var styleSheet = document.styleSheets[i];
		var media = typeof styleSheet.media == 'string'
			? styleSheet.media : (styleSheet.media.mediaText || '');
		if (media.length == 0 || media_regex.test(media)) {
			return new Wired.Stylesheet(styleSheet);
		}
	}
	return null;
};

Wired.Stylesheet.prototype = {
	getStyle: function(selector, property) {
		if (property.indexOf('-') != -1) {
			property = this._camelize(property);
		}
		var selector_regex = new RegExp('(?:^|,)\\s*' + selector + '\\s*(?:$|,)', 'i');
		var rules = this._styleSheet.rules || this._styleSheet.cssRules;
		for (var i = rules.length - 1; i >= 0; i--) {
			var rule = rules[i];
			if (rule.selectorText &&
				selector_regex.test(rule.selectorText) &&
				rule.style[property] != '') {
				return rule.style[property];
			}
		}
		return null;
	},

	insertRule: function(selector, property, index) {
		if (typeof index == 'undefined') {
			index = this.length();
		}
		if (this._styleSheet.addRule) {
			var selectors = selector.split(/\s*,\s*/);
			for (var i = 0; i < selectors.length; i++) {
				this._styleSheet.addRule(selectors[i], '{' + property + '}', index);
			}
			return index;
		} else if (this._styleSheet.insertRule) {
			return this._styleSheet.insertRule(selector + '{' + property + '}', index);
		} else {
			return null;
		}
	},

	length: function() {
		return this._styleSheet.rules    ? this._styleSheet.rules.length
		     : this._styleSheet.cssRules ? this._styleSheet.cssRules.length
		                                 : null;
	},

	_camelize: function(property) {
		return property.replace(/-([a-z])/g, function() { return arguments[1].toUpperCase(); });
	}
};

/* **** wired/stylesheet.js end **** */

