/**
* Reads the input from the CSS editor and builds it into CSS code
*
* @param	array	Submitted data from css.php?do=edit
* @param	integer	Style ID
* @param	string	Title of style
* @param	array	(ref) Array of extracted CSS colour values
*
* @return	string
*/
function construct_css($css, $styleid, $styletitle, &$csscolors)
{
    global $vbulletin;
    // remove the 'EXTRA' definition and stuff it in at the end :)
    $extra = trim($css['EXTRA']['all']);
    $extra2 = trim($css['EXTRA2']['all']);
    if ($vbulletin->options['storecssasfile']) {
        $extra = preg_replace('#(?<=[^a-z0-9-]|^)url\\((\'|"|)(.*)\\1\\)#iUe', "rewrite_css_file_url('\\2', '\\1')", $extra);
        $extra2 = preg_replace('#(?<=[^a-z0-9-]|^)url\\((\'|"|)(.*)\\1\\)#iUe', "rewrite_css_file_url('\\2', '\\1')", $extra2);
    }
    unset($css['EXTRA'], $css['EXTRA2']);
    // initialise the stylearray
    $cssarray = array();
    // order for writing out CSS variables
    $css_write_order = array('body', '.page', 'td, th, p, li', '.tborder', '.tcat', '.thead', '.tfoot', '.alt1, .alt1Active', '.alt2, .alt2Active', '.inlinemod', '.wysiwyg', 'textarea, .bginput', '.button', 'select', '.smallfont', '.time', '.navbar', '.highlight', '.fjsel', '.fjdpth0', '.fjdpth1', '.fjdpth2', '.fjdpth3', '.fjdpth4', '.panel', '.panelsurround', 'legend', '.vbmenu_control', '.vbmenu_popup', '.vbmenu_option', '.vbmenu_hilite');
    ($hook = vBulletinHook::fetch_hook('css_output_build')) ? eval($hook) : false;
    // loop through the $css_write_order array to make sure we
    // write the css into the template in the correct order
    foreach ($css_write_order as $itemname) {
        unset($links, $thisitem);
        if (is_array($css["{$itemname}"])) {
            foreach ($css["{$itemname}"] as $cssidentifier => $value) {
                if (preg_match('#^\\.(\\w+)#si', $itemname, $match)) {
                    $itemshortname = $match[1];
                } else {
                    $itemshortname = $itemname;
                }
                if ($vbulletin->options['storecssasfile']) {
                    $value = preg_replace('#(?<=[^a-z0-9-]|^)url\\((\'|"|)(.*)\\1\\)#iUe', "rewrite_css_file_url('\\2', '\\1')", $value);
                }
                switch ($cssidentifier) {
                    // do normal links
                    case 'LINK_N':
                        if ($getlinks = construct_link_css($itemname, $cssidentifier, $value)) {
                            $links['normal'] = $getlinks;
                        }
                        break;
                        // do visited links
                    // do visited links
                    case 'LINK_V':
                        if ($getlinks = construct_link_css($itemname, $cssidentifier, $value)) {
                            $links['visited'] = $getlinks;
                        }
                        break;
                        // do hover links
                    // do hover links
                    case 'LINK_M':
                        if ($getlinks = construct_link_css($itemname, $cssidentifier, $value)) {
                            $links['hover'] = $getlinks;
                        }
                        break;
                        // do extra attributes
                    // do extra attributes
                    case 'EXTRA':
                    case 'EXTRA2':
                        if (!empty($value)) {
                            $value = "\t" . str_replace("\r\n", "\r\n\t", $value);
                            $thisitem[] = "{$value}\r\n";
                        }
                        break;
                        // do font bits
                    // do font bits
                    case 'font':
                        if ($getfont = construct_font_css($value)) {
                            $thisitem[] = $getfont;
                        }
                        break;
                        // normal attributes
                    // normal attributes
                    default:
                        $value = trim($value);
                        if ($value != '') {
                            switch ($cssidentifier) {
                                case 'background':
                                    #if (stristr($value, 'url(') === false)
                                    #{
                                    #	$cssidentifier = 'background-color';
                                    #}
                                    $csscolors["{$itemshortname}_bgcolor"] = fetch_color_value($value);
                                    break;
                                case 'color':
                                    $csscolors["{$itemshortname}_fgcolor"] = fetch_color_value($value);
                                    break;
                            }
                            $thisitem[] = "\t{$cssidentifier}: {$value};\r\n";
                        }
                }
            }
        }
        // add the item to the css if it's not blank
        if (sizeof($thisitem) > 0) {
            $cssarray[] = "{$itemname}\r\n{\r\n" . implode('', $thisitem) . "}\r\n" . $links['normal'] . $links['visited'] . $links['hover'];
            if ($itemname == 'select') {
                $optioncss = array();
                if ($optionsize = trim($css["{$itemname}"]['font']['size'])) {
                    $optioncss[] = "\tfont-size: {$optionsize};\r\n";
                }
                if ($optionfamily = trim($css["{$itemname}"]['font']['family'])) {
                    $optioncss[] = "\tfont-family: {$optionfamily};\r\n";
                }
                $cssarray[] = "option, optgroup\r\n{\r\n" . implode('', $optioncss) . "}\r\n";
            } else {
                if ($itemname == 'textarea, .bginput') {
                    $optioncss = array();
                    if ($optionsize = trim($css["{$itemname}"]['font']['size'])) {
                        $optioncss[] = "\tfont-size: {$optionsize};\r\n";
                    }
                    if ($optionfamily = trim($css["{$itemname}"]['font']['family'])) {
                        $optioncss[] = "\tfont-family: {$optionfamily};\r\n";
                    }
                    $cssarray[] = ".bginput option, .bginput optgroup\r\n{\r\n" . implode('', $optioncss) . "}\r\n";
                }
            }
        }
    }
    ($hook = vBulletinHook::fetch_hook('css_output_build_end')) ? eval($hook) : false;
    return trim(implode('', $cssarray) . "{$extra}\r\n{$extra2}");
}
/**
* Reads the input from the CSS editor and builds it into CSS code
*
* @param	array	Submitted data from css.php?do=edit
* @param	integer	Style ID
* @param	string	Title of style
* @param	array	(ref) Array of extracted CSS colour values
*
* @return	string
*/
function construct_css($css, $styleid, $styletitle, &$csscolors)
{
	global $vbulletin;

	// remove the 'EXTRA' definition and stuff it in at the end :)
	$extra = trim($css['EXTRA']['all']);
	$extra2 = trim($css['EXTRA2']['all']);
	unset($css['EXTRA'], $css['EXTRA2']);

	// initialise the stylearray
	$cssarray = array();

	// order for writing out CSS variables
	$css_write_order = array(
		'body',
		'.page',
		'td, th, p, li',
		'.tborder',
		'.tcat',
		'.thead',
		'.tfoot',
		'.alt1, .alt1Active',
		'.alt2, .alt2Active',
		'.inlinemod',
		'.wysiwyg',
		'textarea, .bginput',
		'.button',
		'select',
		'.smallfont',
		'.time',
		'.navbar',
		'.highlight',
		'.fjsel',
		'.fjdpth0',
		'.fjdpth1',
		'.fjdpth2',
		'.fjdpth3',
		'.fjdpth4',

		'.panel',
		'.panelsurround',
		'legend',

		'.vbmenu_control',
		'.vbmenu_popup',
		'.vbmenu_option',
		'.vbmenu_hilite',
	);

	($hook = vBulletinHook::fetch_hook('css_output_build')) ? eval($hook) : false;

	// loop through the $css_write_order array to make sure we
	// write the css into the template in the correct order

	foreach($css_write_order AS $itemname)
	{
		unset($links, $thisitem);
		if (is_array($css["$itemname"]))
		{
			foreach($css["$itemname"] AS $cssidentifier => $value)
			{
				if (preg_match('#^\.(\w+)#si', $itemname, $match))
				{
					$itemshortname = $match[1];
				}
				else
				{
					$itemshortname = $itemname;
				}

				switch ($cssidentifier)
				{
					// do normal links
					case 'LINK_N':
					{
						if ($getlinks = construct_link_css($itemname, $cssidentifier, $value))
						{
							$links['normal'] = $getlinks;
						}
					}
					break;

					// do visited links
					case 'LINK_V':
					{
						if ($getlinks = construct_link_css($itemname, $cssidentifier, $value))
						{
							$links['visited'] = $getlinks;
						}
					}
					break;

					// do hover links
					case 'LINK_M':
					{
						if ($getlinks = construct_link_css($itemname, $cssidentifier, $value))
						{
							$links['hover'] = $getlinks;
						}
					}
					break;

					// do extra attributes
					case 'EXTRA':
					case 'EXTRA2':
					{
						if (!empty($value))
						{
							$value = "\t" . str_replace("\r\n", "\r\n\t", $value);
							$thisitem[] = "$value\r\n";
						}
					}
					break;

					// do font bits
					case 'font':
					{
						if ($getfont = construct_font_css($value))
						{
							$thisitem[] = $getfont;
						}
					}
					break;

					// normal attributes
					default:
					{
						$value = trim($value);
						if ($value != '')
						{
							switch ($cssidentifier)
							{
								case 'background':
								{
									$csscolors["{$itemshortname}_bgcolor"] = fetch_color_value($value);
								}
								break;

								case 'color':
								{
									$csscolors["{$itemshortname}_fgcolor"] = fetch_color_value($value);
								}
								break;
							}
							$thisitem[] = "\t$cssidentifier: $value;\r\n";
						}
					}

				}
			}
		}
		// add the item to the css if it's not blank
		if (sizeof($thisitem) > 0)
		{
			$cssarray[] = "$itemname\r\n{\r\n" . implode('', $thisitem) . "}\r\n" . $links['normal'] . $links['visited'] . $links['hover'];

			if ($itemname == 'select')
			{
				$optioncss = array();
				if ($optionsize = trim($css["$itemname"]['font']['size']))
				{
					$optioncss[] = "\tfont-size: $optionsize;\r\n";
				}
				if ($optionfamily = trim($css["$itemname"]['font']['family']))
				{
					$optioncss[] = "\tfont-family: $optionfamily;\r\n";
				}
				$cssarray[] = "option, optgroup\r\n{\r\n" . implode('', $optioncss) . "}\r\n";
			}
			else if ($itemname == 'textarea, .bginput')
			{
				$optioncss = array();
				if ($optionsize = trim($css["$itemname"]['font']['size']))
				{
					$optioncss[] = "\tfont-size: $optionsize;\r\n";
				}
				if ($optionfamily = trim($css["$itemname"]['font']['family']))
				{
					$optioncss[] = "\tfont-family: $optionfamily;\r\n";
				}
				$cssarray[] = ".bginput option, .bginput optgroup\r\n{\r\n" . implode('', $optioncss) . "}\r\n";
			}
		}
	}

	// generate hex colors
	foreach ($css_write_order AS $itemname)
	{
		if (is_array($css["$itemname"]))
		{
			$itemshortname = (strpos($itemname, '.') === 0 ? substr($itemname, 1) : $itemname);

			foreach($css["$itemname"] AS $cssidentifier => $value)
			{
				switch ($cssidentifier)
				{
					case 'LINK_N':
					case 'LINK_V':
					case 'LINK_M':
					{
						if ($value['color'] != '')
						{
							$csscolors[$itemshortname . '_' . strtolower($cssidentifier) . '_fgcolor'] = fetch_color_value($value['color']);
						}

						if ($value['background'] != '')
						{
							$csscolors[$itemshortname . '_' . strtolower($cssidentifier) . '_bgcolor'] = fetch_color_value($value['background']);
						}
					}
					break;

					// do extra attributes
					case 'EXTRA':
					case 'EXTRA2':
					{
						if (preg_match('#border(-color)?\s*\:\s*([^;]+);#siU', $value, $match))
						{
							$csscolors[$itemshortname . '_border_color'] = fetch_color_value($match[2]);
						}
					}
					break;
				}
			}
		}
	}

	$csscolors_hex = array();

	foreach ($csscolors AS $colorname => $colorvalue)
	{
		$hexcolor = fetch_color_hex_value($colorvalue);

		if ($hexcolor !== false)
		{
			$csscolors_hex[$colorname . '_hex'] = $hexcolor;
		}
	}

	$csscolors = array_merge($csscolors, $csscolors_hex);

	($hook = vBulletinHook::fetch_hook('css_output_build_end')) ? eval($hook) : false;

	return trim(implode('', $cssarray) . "$extra\r\n$extra2");
}