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/production/add_to_cart.gif';
	this.add_to_cart_gray = new Image;
	this.add_to_cart_gray.src = 'images/production/add_to_cart_gray.gif';

	//режим отображения
	this.cart_mode = cart_mode;
}

//отработка состояний корзины - пустая/полная
cartVisualization.prototype.visualizeCart = function (state) {
	if (state == true) {
		//полная
		document.getElementById('cart_empty').style.display = 'none';
		document.getElementById('cart_non_empty').style.display = '';
	} else {
		//пустая
		document.getElementById('cart_empty').style.display = '';
		document.getElementById('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.getElementById("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.getElementById('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.getElementById('price_common').innerHTML = number_format (a.overall);

	if (a.discount_constant_multiplier != 0)
	{
		document.getElementById('discount_constant_value').innerHTML = number_format (a.discount_constant_value);
		document.getElementById('discount_constant_multiplier').innerHTML = Math.round (a.discount_constant_multiplier * 10000) / 100;
		document.getElementById('discount_constant').style.display = '';
	} else {
		document.getElementById('discount_constant').style.display = 'none';
	}

	if (a.discount_ranges_multiplier != 0)
	{
		document.getElementById('discount_ranges_value').innerHTML = number_format (a.discount_ranges_value);
		document.getElementById('discount_ranges_multiplier').innerHTML = Math.round (a.discount_ranges_multiplier * 10000) / 100;
		document.getElementById('discount_ranges').style.display = '';
	} else {
		document.getElementById('discount_ranges').style.display = 'none';
	}

	document.getElementById('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="3" class="cartPositions" width="100%" id="cartPositionsTable">');
	document.write ('			<tr>');
	document.write ('				<th width="100%" style="padding-left:10px;">Artikel</th>');
	document.write ('				<th bgcolor="#FFFFFF"><img src="images/spacer.gif" width="1" height="1"></th>');
	document.write ('				<th>Anzahl</th>');
	document.write ('				<th bgcolor="#FFFFFF"><img src="images/spacer.gif" width="1" height="1"></th>');
	document.write ('				<th nowrap>Einzel-<br>Preis, &euro;</th>');
	//колонки для удаления - только для режима с редактированием
	if (this.cart_mode == 0)
	{
		document.write ('				<th bgcolor="#FFFFFF"><img src="images/spacer.gif" width="1" height="1"></th>');
		document.write ('				<th>&nbsp;</th>');
		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 ('								<span id="discount_constant">Kundenrabatt <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">Mengenrabatt <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 ('			<tr id="cart_special_positions_title_row" style="display:none;" class="specialPositions">');
	document.write ('				<td colspan="' + default_colspan + '" align="center">');
	document.write ('							Schn&auml;ppchen');
	document.write ('				</td>');
	document.write ('			</tr>');

	//пример begin
	document.write ('<tr id="cart_position_example_row" style="display:none;">');
	document.write ('<td style="padding-left:10px;"><b>position title</b><br><span>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" value="1" maxlength="3" style="width:25px"></td>');
	else
		document.write ('<td align="center">position amount</td>');
	document.write ('<td bgcolor="#FFFFFF"><img src="images/spacer.gif" width="1" height="1"></td>');
	document.write ('<td align="right">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/production/remove_from_cart.gif" width="19" height="16" hspace="4" border="0" alt="remove_from_cart"></a></td>');
	}
	document.write ('</tr>');
	//пример end

	document.write ('		</table>');

	document.write ('		<table border="0" width="100%" cellspacing="0" cellpadding="1" align="center" class="prices">');
	document.write ('			<tr><td><img src="images/spacer.gif" width="1" height="7"></td></tr>');
	document.write ('			<tr><td align="right">Versandkosten: &nbsp; <b class="blue"><span id="delivery_price">delivery_price</span> &euro;</b></td></tr>');
	document.write ('			<tr class="common"><td align="right">Gesamtbetrag: &nbsp; <b class="blue"><span id="price_common">price_common</span> &euro;</b></td></tr>');
	document.write ('			<tr><td><img src="images/spacer.gif" width="1" height="7"></td></tr>');
	document.write ('		</table>');

	if (this.cart_mode == 0)
	{
		document.write ('		<div align="right" style="width:100%; margin-right:20px">');
		document.write ('			<input type="submit" class="basketSubmit" value="BESTELLEN" border="0" style="cursor:pointer;" />');
		document.write ('		</div>');
	}

		document.write ('		<div style="width:100%; font-size:10px">');
		document.write ('			* die angegebenen Versandkosten gelten bis zu einem Gesamtgewicht pro Paket von 31,5 kg. H&ouml;here Gewichte werden separat berechnet und auf Anfrage gerne mitgeteilt. Bei Nachnahmebestellungen erh&ouml;ht sich der angezeigte Betrag um weitere Euro 4,50.<br /><br />');
		document.write ('		</div>');


	document.write ('</span>');

	//корзина пуста
	document.write ('<span class="red" id="cart_empty">Ihr Warenkorb ist leer!</span>');

}