isDOM=document.getElementById //DOM1 browser (MSIE 5+, Netscape 6, Opera 5+)
isOpera=isOpera5=window.opera && isDOM //Opera 5+
isOpera6=isOpera && window.print //Opera 6+
isOpera7=isOpera && document.readyState //Opera 7+
isMSIE=document.all && document.all.item && !isOpera //Microsoft Internet Explorer 4+
isMSIE5=isDOM && isMSIE //MSIE 5+
isNetscape4=document.layers //Netscape 4.*
isMozilla=isDOM && navigator.appName=="Netscape" //Mozilla или Netscape 6.*

//конструктор объекта - визуализация корзины
//cart_mode - режим отображения корзины
//	0 - допускать редактирования, для страниц магазина
//	1 - только отображения, для оформления заказа
function cartVisualization (cart_alias, global_variable_name, cart_mode) {
	//базовый класс корзины
	this.cart = new cart (cart_alias);
	this.global_variable_name = global_variable_name;

	//кнопка добавления в корзину
	this.add_to_cart = new Image;
	this.add_to_cart.src = 'images/shop/add_to_cart.gif';
	this.add_to_cart_gray = new Image;
	this.add_to_cart_gray.src = 'images/shop/add_to_cart_gray.gif';

	//режим отображения
	this.cart_mode = cart_mode;
}

//отработка состояний корзины - пустая/полная
cartVisualization.prototype.visualizeCart = function (state) {
	if (state == true) {
		//полная
		document.all['cart_empty'].style.display = 'none';
		document.all['cart_non_empty'].style.display = '';
	} else {
		//пустая
		document.all['cart_empty'].style.display = '';
		document.all['cart_non_empty'].style.display = 'none';
	}
}

//добавить в корзину
cartVisualization.prototype.addToCart = function (position_id, special, price, title, art, amount){
	//извлекаем название
	if (typeof (title) == 'undefined')
		eval ('var title = position_' + position_id + ';');

	if (typeof (art) == 'undefined')
		//извлекаем артикул
		eval ('var art = document.all["position_' + position_id + '_art"].innerHTML;');

	if (typeof (amount) == 'undefined')
		amount = 1;

	//добавляем в корзину
	if (this.cart.insertPosition (position_id, special, title, art, price, amount) == true) {
		//добавление прошло успешно

		//отрисовываем графику
		if (this.cart.getPositionsCount () == 1)
			this.visualizeCart (true);

		this.drawCartItem (position_id, special, title, art, price, amount);

		//пересчет
		this.updateOverallCost ();

		return true;
	}
}

//удалить из корзины
cartVisualization.prototype.removeFromCart = function (position_id) {
	//удаляем из корзины
	if (this.cart.removePosition (position_id) === true) {

		//отрисовываем графику begin
		var cart_table = document.getElementById ('cartPositionsTable');
		var position_row = document.getElementById ('position_row_' + position_id);

		if (isMozilla)
			cart_table.childNodes[1].removeChild (position_row);
		else
			cart_table.firstChild.removeChild (position_row);

		//делаем добавление товара активным
		if (document.images['add_to_cart_' + position_id])
			document.images['add_to_cart_' + position_id].src = this.add_to_cart.src;

		if (this.cart.getPositionsCountBySpecialValue (1) == 0) {
			//скрываем заголовок "спецпредложения"
			document.all['cart_special_positions_title_row'].style.display = 'none';
		}

		if (this.cart.getPositionsCountBySpecialValue (0) == 0) {
			//скрываем строку со скидкой для обычных товаров
			document.getElementById ('cart_non_special_positions_discount_row').style.display = 'none';
		}
		//отрисовываем графику end

		if (this.cart.getPositionsCount () == 0) {
			//скрываем корзину
			this.visualizeCart (false);
		} else {
			//пересчет
			this.updateOverallCost ();
		}

	}
	return false;
}


//обновить общую стоимость
cartVisualization.prototype.updateOverallCost = function () {
	//общая стоимость
	var a = this.cart.getOverallCost ();

	document.all['price_common'].innerHTML = number_format (a.overall);

	if (a.discount_constant_multiplier != 0)
	{
		document.all['discount_constant_value'].innerHTML = number_format (a.discount_constant_value);
		document.all['discount_constant_multiplier'].innerHTML = Math.round (a.discount_constant_multiplier * 10000) / 100;
		document.all['discount_constant'].style.display = '';
	} else {
		document.all['discount_constant'].style.display = 'none';
	}

	if (a.discount_ranges_multiplier != 0)
	{
		document.all['discount_ranges_value'].innerHTML = number_format (a.discount_ranges_value);
		document.all['discount_ranges_multiplier'].innerHTML = Math.round (a.discount_ranges_multiplier * 10000) / 100;
		document.all['discount_ranges'].style.display = '';
	} else {
		document.all['discount_ranges'].style.display = 'none';
	}

	document.all['delivery_price'].innerHTML = number_format (a.delivery_price);
}

//изменить количество какго-то элемента
cartVisualization.prototype.changeCartItemAmount = function (position_id, amount) {
	if (isNaN (amount))
		amount = 0;

	this.cart.changePositionAmount (position_id, amount);
	//пересчет
	this.updateOverallCost ();
	return true;
}

//нарисовать элемент корзины
cartVisualization.prototype.drawCartItem = function (position_id, special, title, art, price, amount) {
	//делаем добавление товара неактивным
	if (document.images['add_to_cart_' + position_id])
		document.images['add_to_cart_' + position_id].src = this.add_to_cart_gray.src;

	//пример для изменения
	var position_row = document.getElementById ('cart_position_example_row').cloneNode (true);
	position_row.style.display = '';
	position_row.id = 'position_row_' + position_id;


	//название
	position_row.firstChild.firstChild.innerHTML = title;
	position_row.firstChild.childNodes[2].innerHTML = art;

	//количество
	if (this.cart_mode == 0) {
		//отображение+редактирование
		var amount_input = position_row.childNodes[2].firstChild;
		amount_input.value = amount;
		amount_input.onkeypress = new Function (this.global_variable_name + '.changeCartItemAmount (' + position_id + ', this.value);');
		amount_input.onkeyup = amount_input.onkeypress;
		amount_input.onkeydown = amount_input.onkeypress;
	} else {
		//только отображение
		position_row.childNodes[2].innerHTML = amount;
	}

	//цена
	position_row.childNodes[4].innerHTML = number_format (price);


	//кнопка удаления
	if (this.cart_mode == 0)
		position_row.childNodes[6].firstChild.onclick = new Function (this.global_variable_name + '.removeFromCart (' + position_id + ');');

	//добавляем в таблицу новую позицию
	var cart_table = document.getElementById ('cartPositionsTable');

	if (special == 0) {
		//обычный товар
		//показываем строку со скидкой для обычных товаров
		document.getElementById ('cart_non_special_positions_discount_row').style.display = '';

		//определяеи после какого эл-та добавлять строку
		var before = document.getElementById ('cart_non_special_positions_discount_row');
	} else {
		//спецпредложение
		//показываем заголовок "спецпредложения"
		document.getElementById ('cart_special_positions_title_row').style.display = '';

		//определяеи после какого эл-та добавлять строку
		var before = document.getElementById ('cart_position_example_row');
	}

	//добавляем строку с позицией в таблицу корзины
	if (isMozilla)
		cart_table.childNodes[1].insertBefore (position_row, before);
	else
		cart_table.firstChild.insertBefore (position_row, before);

	return true;
}

//инициализация корзины
cartVisualization.prototype.initializeCart = function () {
	//текущие позиции
	var a = this.cart.getAllPositions ();
	if (a != false) {

		this.visualizeCart (true);
		for (var i = 0; i < a.length; i++) {
			this.drawCartItem (a[i][0], a[i][1], a[i][2], a[i][3], a[i][4], a[i][5]);
		}
		//пересчет
		this.updateOverallCost ();
	}

}

//очистить корзину
cartVisualization.prototype.free = function () {
	this.cart.free ();
}

cartVisualization.prototype.drawCart = function () {
	//корзина НЕ пуста
	document.write ('<span id="cart_non_empty" style="display:none;">');

	if (this.cart_mode == 0) {
		var default_colspan = 7;
		document.write ('	<input type="hidden" name="positions_cookie_variable"/>');
	} else {
		var default_colspan = 5;
	}

	document.write ('		<table border="0" cellspacing="0" cellpadding="0" class="cartPositions" width="100%" id="cartPositionsTable">');
	document.write ('			<tr>');
	document.write ('				<th>' + translate ('position_title') + '</th>');
	document.write ('				<td bgcolor="#FFFFFF"><img src="images/spacer.gif" width="1" height="1"></td>');
	document.write ('				<th>' + translate ('position_amount') + '</th>');
	document.write ('				<td bgcolor="#FFFFFF"><img src="images/spacer.gif" width="1" height="1"></td>');
	document.write ('				<th nowrap>' + translate ('position_price') + ', &euro;</th>');
	//колонки для удаления - только для режима с редактированием
	if (this.cart_mode == 0)
	{
		document.write ('				<td bgcolor="#FFFFFF"><img src="images/spacer.gif" width="1" height="1"></td>');
		document.write ('				<td>&nbsp;</td>');
		document.write ('			</tr>');
	}

	document.write ('			<tr id="cart_non_special_positions_discount_row" style="display:none;">');
	document.write ('				<td colspan="' + default_colspan + '" align="center">');
	document.write ('					<table border="0" cellspacing="4" cellpadding="0">');
	document.write ('						<tr>');
	document.write ('							<td align="right">');
	document.write ('								<span id="discount_constant">' + translate ('discont_by_client') + ' <span id="discount_constant_multiplier">discount_constant_multiplier</span>%: <b class="blue"><span id="discount_constant_value">discount_constant_value</span> &euro;</b><br/></span>');
	document.write ('								<span id="discount_ranges">' + translate ('discount_by_price') + ' <span id="discount_ranges_multiplier">discount_ranges_multiplier</span>%: <b class="blue"><span id="discount_ranges_value">discount_ranges_value</span> &euro;</b>');
	document.write ('							</td>');
	document.write ('						</tr>');
	document.write ('					</table>');
	document.write ('				</td>');
	document.write ('			</tr>');

	document.write ('			<tr id="cart_special_positions_title_row" style="display:none;">');
	document.write ('				<td colspan="' + default_colspan + '" align="center" class="v">');
	document.write ('					<table border="0" cellspacing="0" cellpadding="0" class="cartPositions" width="100%">');
	document.write ('						<tr>');
	document.write ('							<td width="50%" background="images/shop/special_back.gif">&nbsp;</td>');
	document.write ('							<td nowrap>&nbsp;<span class="red"><b>' + translate ('special_offers') + ' </b></span>&nbsp;</td>');
	document.write ('							<td width="50%" background="images/shop/special_back.gif">&nbsp;</td>');
	document.write ('						</tr>');
	document.write ('					</table>');
	document.write ('				</td>');
	document.write ('			</tr>');

	//пример begin
	document.write ('<tr id="cart_position_example_row" style="display:none;">');
	document.write ('<td class="v"><b>position title</b><br><span class="black">position article</span></td>');
	document.write ('<td bgcolor="#FFFFFF"><img src="images/spacer.gif" width="1" height="1"></td>');
	//кол-во позиций
	if (this.cart_mode == 0)
		document.write ('<td align="center"><input name="textfield" type="text" class="positionAmount" value="1" maxlength="3"></td>');
	else
		document.write ('<td align="center" class="v">position amount</td>');
	document.write ('<td bgcolor="#FFFFFF"><img src="images/spacer.gif" width="1" height="1"></td>');
	document.write ('<td align="right" class="v">position price</td>');
	//колонки для удаления - только для режима с редактированием
	if (this.cart_mode == 0)
	{
		document.write ('<td bgcolor="#FFFFFF"><img src="images/spacer.gif" width="1" height="1"></td>');
		document.write ('<td align="center"><a href="javascript:void null" onclick=""><img src="images/shop/remove_from_cart.gif" width="28" height="17" hspace="4" border="0" alt="' + translate ('remove_from_cart') + '"></a></td>');
	}
	document.write ('</tr>');
	//пример end

	document.write ('		</table>');

	document.write ('		<br/>');
	document.write ('		<table border="0" cellspacing="0" cellpadding="2" align="center">');
	document.write ('			<tr><td align="right">' + translate ('order_delivery_price') + ': </td><td align="right"><b class="blue"><span id="delivery_price">delivery_price</span> &euro;</b></td></tr>');
	document.write ('			<tr><td align="right">' + translate ('order_common_price') + ': </td><td align="right"><b class="blue"><span id="price_common">price_common</span> &euro;</b></td></tr>');
	document.write ('		</table>');
	document.write ('		<br/>');

	if (this.cart_mode == 0)
	{
		document.write ('		<div align="center">');
		document.write ('			<input type="image" src="images/shop/order_' + locale + '.gif" border="0"/>');
		document.write ('			<p align="left"><small>* die angegebenen Versandkosten gelten bis zu einem Gesamtgewicht pro Paket von 3 kg Inland und 2 kg Ausland bei Standardpaketen. Bei h&ouml;heren Gewichten, soweit vorhanden, entsprechende Versandzone unter Rubrik "Land" anklicken. Nicht ausgewiesene Versandzonengewichtsklassen werden separat berechnet und auf Anfrage gerne mitgeteilt.</small></p>');
		document.write ('		</div>');
	}

	document.write ('</span>');

	//корзина пуста
	document.write ('<span class="gray" id="cart_empty"><b>' + translate ('your_cart_free') + '</b></span>');

}