/* CSS editting and parsing */

// applies the derived colors to the smart css
// replace $$colorname with #hexvalue
function BuildCSS()
{
	// first get smart css
	var css = document.getElementById("internalcss").value;
	// for each color
	for (var i = 0; i < numcolors; i++)
	{
		// build regex
		var myregex = new RegExp("\\$\\$" + colors[i].name + "\\b", "g");
		// build hex
		var hex = "#" + toHex(colors[i].r) + toHex(colors[i].g) + toHex(colors[i].b);
		// replace
		css = css.replace(myregex, hex);
	}
	// add header
	var header = BuildHeader();
	css = header + css;
	document.getElementById("generatedcss").value = css;
}

// updates the document's css
// three steps are taken:
//  clear the existing css rules
//  insert the custom rules
//  apply the custom rules only to the preview pane
function InjectCSS()
{
	var cssText = document.getElementById("generatedcss").value;

	// the cssText property only works in IE
	if (typeof(document.styleSheets[1].cssText) != "undefined")
	{
		// IE
		document.styleSheets[1].cssText = cssText;
	}
	else
	{
		// other
		// clear all rules
		var cssNode = document.getElementById("dynamiccss");
		while (cssNode.childNodes.length)
		{
			cssNode.removeChild(cssNode.childNodes[0]);
		}
		// add the custom rules
		cssNode.appendChild(document.createTextNode(cssText));
	}

	// make the custom rules apply only to the csscolorizerpreview div by updating the selectors
	var rules;
	if (document.styleSheets[1].cssRules)
	{
		// IE
		rules = document.styleSheets[1].cssRules;
	}
	else
	{
		// other
		rules = document.styleSheets[1].rules;
	}
	for (var i = 0; i < rules.length; i++)
	{
		var oldselectorText = rules[i].selectorText;
		var newselectorText = "#csscolorizerpreview " + oldselectorText;
		var ruleText = rules[i].style.cssText;
		if (document.styleSheets[1].deleteRule)
		{
			// other
			document.styleSheets[1].deleteRule(i);
			document.styleSheets[1].insertRule(newselectorText + "{" + ruleText + "}", 0);
		}
		else
		{
			// IE
			if (ruleText.length > 0)
			{
				document.styleSheets[1].removeRule(i);
				document.styleSheets[1].addRule(newselectorText, ruleText, 0);
			}
			else
			{
				// if the rule is empty, adding it would cause an error
			}
		}
	}
}


