<?php
if (function_exists('register_sidebars')) {
	register_sidebars(1, array(
		'before_widget' => '<!--- BEGIN Widget --->',
		'before_title' => '<!--- BEGIN WidgetTitle --->',
		'after_title' => '<!--- END WidgetTitle --->',
		'after_widget' => '<!--- END Widget --->'
	));
}

function art_normalize_widget_style_tokens($content) {
	$bw = '<!--- BEGIN Widget --->';
	$bwt = '<!--- BEGIN WidgetTitle --->';
	$ewt = '<!--- END WidgetTitle --->';
	$bwc = '<!--- BEGIN WidgetContent --->';
	$ewc = '<!--- END WidgetContent --->';
	$ew = '<!--- END Widget --->';
	$result = '';
	$startBlock = 0;
	$endBlock = 0;
	while (true) {
		$startBlock = strpos($content, $bw, $endBlock);
		if (false === $startBlock) {
			$result .= substr($content, $endBlock);
			break;
		}
		$result .= substr($content, $endBlock, $startBlock - $endBlock);
		$endBlock = strpos($content, $ew, $startBlock);
		if (false === $endBlock) {
			$result .= substr($content, $endBlock);
			break;
		}
		$endBlock += strlen($ew);
		$widgetContent = substr($content, $startBlock, $endBlock - $startBlock);
		if ((false == strpos($widgetContent, $bwt))
			xor (false == strpos($widgetContent, $ewt)))
		{
			$widgetContent = str_replace($bwt, '', $widgetContent);
			$widgetContent = str_replace($ewt, '', $widgetContent);
		}
		if (false === strpos($widgetContent, $bwt)) {
			$widgetContent = str_replace($bw, $bw . $bwc, $widgetContent);
		} else {
			$widgetContent = str_replace($ewt, $ewt . $bwc, $widgetContent);
		}
		$result .= str_replace($ew, $ewc . $ew, $widgetContent);
	}
	return $result;
}

function art_sidebar($index = 1)
{
	if (!function_exists('dynamic_sidebar')) return false;
	ob_start();
	$success = dynamic_sidebar($index);
	$content = ob_get_clean();
	if (!$success) return false;
	$content = art_normalize_widget_style_tokens($content);
	$replaces = array(
		'<!--- BEGIN Widget --->' => "<div class=\"Block\">\n<div class=\"Block-content\">",
		'<!--- BEGIN WidgetTitle --->' => "<div class=\"BlockHeader\">\n",
		'<!--- END WidgetTitle --->' => "\n<div class=\"l\"></div>\n<div class=\"r\"><div></div></div>\n</div>\n",
		'<!--- BEGIN WidgetContent --->' => "<div class=\"BlockContent\">\n<div class=\"BlockContent-content\">",
		'<!--- END WidgetContent --->' => "</div>\n</div>\n",
		'<!--- END Widget --->' => "</div>\n<div class=\"Block-tl\"></div>\n<div class=\"Block-tr\"><div></div></div>\n<div class=\"Block-bl\"><div></div></div>\n<div class=\"Block-br\"><div></div></div>\n<div class=\"Block-tc\"></div>\n<div class=\"Block-bc\"></div>\n<div class=\"Block-cl\"></div>\n<div class=\"Block-cr\"></div>\n<div class=\"Block-cc\"></div>\n</div>\n"
	);
	$content = str_replace(array_keys($replaces), array_values($replaces), $content);
	echo $content;
	return true;
}

function art_list_pages_filter($output) {
  return preg_replace('~<li([^>]*)><a([^>]*)>([^<]*)</a></li>~',
    '<li$1><a$2><span><span>$3</span></span></a></li>',
    $output);
}

add_action('wp_list_pages', 'art_list_pages_filter');
