<?php

class CatalyzTextFilter {
    static function renderLinksToNodes($content) {
        if (preg_match_all('/#node-([0-9]+)(,([a-z]{2}))?#/', $content, $items)) {
            $patterns = array();
            $replacement = array();
            foreach($items[1] as $index => $nodeId) {
                if (empty($items[3][$index])) {
                    $ContentTree = ContentTree::instance();
                } else {
                    $ContentTree = ContentTree::instance($items[3][$index]);
                }
                $node = $ContentTree->getContentTreeNodeById($nodeId);
                if (!is_null($node)) {
                    $patterns[] = $items[0][$index];
                    $replacement[] = $node->getUrl();
                }
            }
            $content = str_replace($patterns, $replacement, $content);
        }
        return $content;
    }

    /**
     * CatalyzTextFilter::renderCollapseExpand()
     *
     * @param string $content
     * @return string
     */
    public static function renderCollapseExpand($content, $ContentTree = null, $group_element = 'h2', $sub_group_element = 'h3') {
		use_javascript('catalyz/jquery-1.3.2.min.js');

        $return = '<a name="top"></a>';

        if (false !== $group_element_start_tag_pos = strpos($content, sprintf('<%s>', $group_element))) {
            $return .= substr($content, 0, $group_element_start_tag_pos);
            $content = trim(substr($content, $group_element_start_tag_pos));
        }

        $groups = explode(sprintf('<%s>', $group_element), $content);
        if (0 < count($groups)) {
            /*$return .= '<ul>';
			foreach ($groups as $i => $group_html) {
                if ('' != $group_html && false !== $group_element_end_tag_pos = strpos($group_html, sprintf('</%s>', $group_element))) {
                    $group_element_content = substr($group_html, 0, $group_element_end_tag_pos);
					$return .= sprintf('<li><a href="#%s">%s</a></li>', Catalyz::normalizeUrlIdentifier($group_element_content), $group_element_content);
                }
            }
			$return .= '</ul>';*/
            foreach ($groups as $i => $group_html) {
                if ('' != $group_html && false !== $group_element_end_tag_pos = strpos($group_html, sprintf('</%s>', $group_element))) {
                    $group_element_content = substr($group_html, 0, $group_element_end_tag_pos);
                    $return .= sprintf('<a name="%s"></a><%s style="clear: both"><span style="float: left">%s</span><a href="#top" class="top-link">Top</a></%s>', Catalyz::normalizeUrlIdentifier(utf8_encode(html_entity_decode($group_element_content))), $group_element, $group_element_content, $group_element);
                    $group_html = trim(substr($group_html, $group_element_end_tag_pos + strlen($group_element) + 3));

                    if ('' != $group_html && false !== $sub_group_element_start_tag_pos = strpos($group_html, sprintf('<%s>', $sub_group_element))) {
                        $return .= substr($group_html, 0, $sub_group_element_start_tag_pos);
                        $group_html = trim(substr($group_html, $sub_group_element_start_tag_pos));

                        $sub_groups = explode(sprintf('<%s>', $sub_group_element), $group_html);
                        if (0 < count($sub_groups)) {
                            $return .= '<ul>';
                            foreach ($sub_groups as $j => $sub_group_html) {
                                if ('' != $sub_group_html && false !== $sub_group_element_end_tag_pos = strpos($sub_group_html, sprintf('</%s>', $sub_group_element))) {
                                    $li_html = substr($sub_group_html, 0, $sub_group_element_end_tag_pos);
                                    $sub_group_html = trim(substr($sub_group_html, $sub_group_element_end_tag_pos + strlen($sub_group_element) + 3));

                                    $return .= '<li';
                                    if ('' != $sub_group_html) {
                                        $return .= sprintf(' id="li-%d-%d" class="expand" onclick="$(\'#node-%d-%d\').toggle(); $(\'#li-%d-%d\').toggleClass(\'expand\', !$(\'#node-%d-%d\').is(\':visible\')); $(\'#li-%d-%d\').toggleClass(\'collapse\', $(\'#node-%d-%d\').is(\':visible\'));"', $i, $j, $i, $j, $i, $j, $i, $j, $i, $j, $i, $j);
                                    }
                                    $return .= '>';
                                    if ('' != $sub_group_html) {
                                        $return .= '<div onmouseover="this.style.cursor = \'pointer\';" onmouseout="this.style.cursor = \'default\';">' . $li_html . '</div>';
                                    } else {
                                        $return .= $li_html;
                                    }
                                    if ('' != $sub_group_html) {
                                        $return .= sprintf('<div id="node-%d-%d" style="display: none">%s</div>', $i, $j, $sub_group_html);
                                    }
                                    $return .= '</li>';
                                }
                            }
                            $return .= '</ul>';
                        }
                    }
                }
            }
        }

        if (!is_null($ContentTree)) {
            $children = $ContentTree->getCurrentNode()->getVisibleChildren();
            if (0 < count($children)) {
                $return .= '<ul>';
                foreach ($children as $child) {
					$return .= sprintf('<li><a href="%s">%s</a></li>', $child->getUrl(), $child->getTitle());
                }
                $return .= '</ul>';
            }
        }

        return $return;
    }

    /**
     * CatalyzTextFilter::renderLightBoxImages()
     *
     * @param string $content
     * @param string $light_box_class
     * @return string
     */
    public static function renderLightBoxImages($content, $light_box_class = 'lightbox') {
        $return = $content;

    	foreach (array(640=>$light_box_class,320=>'lightboxColumn') as $taille=>$class){
    		if (preg_match_all('|(?P<tag><img class="' . $class . '"[^>]*src="(?P<src>[^"]*)"[^>]*>)|si', $return, $matches)) {
    			use_helper('fancybox');
    			use_helper('sfThumbnail');

    			foreach ($matches['tag'] as $index => $tag) {
    				if (!empty($matches['src'][$index])) {
    					$return= self::renderlink($return, $tag, $matches['src'][$index], $matches['alt'][$index],$taille);
    				}
    			}
    		}
    	}

        return $return;
    }

	protected static function renderlink($content, $tag,$matches_src,$matches_alt,$taille){
		$return = $content;
		$image=sfConfig::get('sf_web_dir').$matches_src;
		if (is_file($image)) {
			$imageSize=getimagesize($image);
			$src = $matches_src;
			$infos=pathinfo($image);

			$extractWidth = $imageSize[0];
			$extractHeight = $imageSize[1];

			if (preg_match('/width="(?P<width>\d+)"/si', $tag, $tag_matches)) {
				$extractWidth=$tag_matches['width'];
			}
			if (preg_match('/height="(?P<height>\d+)"/si', $tag, $tag_matches)) {
				$extractHeight=$tag_matches['height'];
			}

			$src = !empty($matches_src)?$matches_src:'';
			$alt = !empty($matches_alt)?$matches_alt:'';

			if ($extractWidth > $taille || $extractHeight>$taille) {
				$thum = thumbnail_path($src, $taille, $taille);
			}else{
				$thum = $src;
			}

			$light_box_tag = sprintf('<a class="fancybox" rel="group" title="%s" href="%s"><img src="%s" alt="%s" /></a>', $alt, $src, $thum, $alt);
			$return = str_replace($tag, $light_box_tag, $return);
		}

		return $return;
	}
}