<?php
include_once 'function.staticCounter.php';
include_once 'function.dbImgUrl.php';

/**
 * Вывод картинки (из БД или произвольной) с присвоением размеров, стиля, класса,
 * альтернативного текста, тега-рамки. Возможно простое приведение к размерам
 * или пропорциональне масштабирование, использование fancybox.
 * @param array $params
 * int $params["id"] Индекс картинки в базе данных
 * int $params["htmlId"] Индекс картинки или рамки на странице
 * string $params["url"] Адрес картинки (если не задан ID)
 * string $params["alt"] Альтернативный текст
 * int $params["width"]
 * int $params["height"]
 * string $params["style"] стиль картинки или рамки
 * string $params["class"] класс картинки или рамки
 * boolean $params["scale"] пропорционально масштабировать картинку, даже если заданы и ширина, и высота
 * string $params["scaleWhen"] в каких случаях масштабировать:
 *		tooBig -- вписывать большую картинку в рамку (по умолчанию)
 *		tooSmall -- растягивать маленькую картинку до рамки
 *		always -- всегда
 * boolean $params["crop"] При вписывании в рамку обрезать края (по умолчанию -- оставлять поля).
 * string $params["frameType"] Тип рамки: div, span. При scale=true должен быть задан, иначе не обязателен.
 * boolean $params["fancybox"]
 */
 
function displayImage_checkFrameType($frameType) {
	if ($frameType != "div" && $frameType != "span") {
		throw new Exception("Uncorrect frameType ($frameType), set 'div' or 'span'.");
	}
}
function smarty_function_displayImage($params, $tpl) {
	utls::setHTMLPageOption('highpriority_js_links', '/js/jquery-1.5.1.min.js');
	utls::setHTMLPageOption('js_links', '/js/drawScalledImage.js');
	$alt = $params["alt"];
	$style = $params["style"];
	$class = $params["class"];
	$width = $params["width"];
	$height = $params["height"];
	$crop = $params["crop"];
	$scaleWhen = $params["scaleWhen"];
	$frameType = $params["frameType"];
	$fancybox = $params["fancybox"];
	if (isset($width)) {
		$style .= "; width: ". $width;
	}
	if (isset($height)) {
		$style .= "; height: ". $height;
	}
	if (isset($params["id"])) {
		$url = smarty_function_dbImgUrl(array("id"=>$params["id"]), $tpl);
	} else {
		$url = $params["url"];
	}
	if (isset($params["htmlId"])) {
		$id = $params["htmlId"];
	} else {
		$id = "displayImage_" . smarty_function_staticCounter();
	}
	if ($params["scale"]) {
		if (!isset($frameType)) {
			throw new Exception("Set frameType when scale=true.");
		}
		displayImage_checkFrameType($frameType);
		$result = "";
		if ($fancybox) {
			$result .= "<a href=\"$url\" id=\"fancybox_$id\">";
		}
		$result .= "<$frameType id=\"$id\" style=\"$style\" class=\"$class\"></$frameType>\n";
		if ($fancybox) {
			$result .= "</a>";
		}
		$scaleParameters = json_encode(array(
			"width" => $width,
			"height" => $height,
			"crop" => $crop,
			"scaleWhen" => $scaleWhen
		));
		$result .= '<script type="text/javascript" language="javascript">
	drawScalledImage($("#'.$id.'")[0], "'.$url.'", '.$scaleParameters.', "'.$alt.'");
';
		if ($fancybox) {
			$result .= '$("#fancybox_'.$id.'").fancybox( { "type" : "image" }  );';
		}
		$result .= "</script>\n";
	} else {
		$image = "<img src=\"$url\" alt=\"$alt\"";
		$result = "";
		if ($fancybox) {
			$result .= "<a href=\"$url\" id=\"fancybox_$id\">";
		}
		if (!isset($frameType)) {
			$result .= "$image style=\"$style\" class=\"$class\"";
			if (isset($width)) $result .= ' width="'.$width.'px"';
			if (isset($height)) $result .= ' height="'.$height.'px"';
			$result .= " id=\"$id\"/>";
		} else {
			displayImage_checkFrameType($frameType);
			$result .= "<$frameType class=\"$class\" style=\"$style";
			if (isset($width)) $result .= ' width:"'.$width.'px;"';
			if (isset($height)) $result .= ' height:"'.$height.'px;"';
			$result .= "\" id=\"$id\">$image/></$frameType>\n";
		}
		if ($fancybox) {
			$result .= "</a>";
			$result .= '<script type="text/javascript" language="javascript">
	$("#fancybox_'.$id.'").fancybox( { "type" : "image" }  );
</script>
';
		}
	}
	return $result;
}
?>
