var SHOPPING_CART_FIELDS = ["id", "name", "image", "price", "count", "type"];
var SHOPPING_CART_IMAGES_FOLDER = "/images/shopping_cart";
var TEMPLATE = '<div class="ProductInCart"><div id="ProductNameLabel[]" class="Caption">[ProductName]</div><div style="background-image: url([ProductImage]);" class="Image"/></div><div class="Edit"/><input id="CountEdit[]" type="text" value="0" size="4" maxlength="4" /></div><div id="UpButton[]" class="UpButton"></div><div id="DownButton[]" class="DownButton"></div><div id="CancelButton[]" class="CancelButton"></div></div>';

var MOSCOW_DELIVERY_PRICE = 100; // R
var MKAD_DELIVERY_PRICE = 300; // R
var MAX_DELIVERY = 300; // USD
var CASH_COURSE = 31;
var CASHLESS_COURSE = 33;

function addToCart(/*Object*/product)/*:Void*/ {
	if (product.name.length > 16) product.name = product.name.substr(0, 14) + '...';
	shoppingCart.addProduct(product);
	//Cartridge
	//Paper
	//Toner
	//Ink
	//Spares
	//Refuelling
}

/*class*/ ProductsCookie = function (name/*:String*/, fields/*:Array*/) {
	call(StorageCookie, this, name, fields);
}
ProductsCookie.prototype = new StorageCookie;

/*public int*/ ProductsCookie.prototype.totalCount = function () {
	var result = 0;
	for (var key in this.records)
		result -= -this.records[key].count;
	return result;
}

/*public int*/ ProductsCookie.prototype.totalPrice = function () {
	var result = 0;
	for (var key in this.records)
		result -= -this.records[key].price * this.records[key].count;
	return roundTo(result, -2);
}

/*public int*/ ProductsCookie.prototype.getPaymentSum = function (deliveryType/*:String*/, paymentType/*:String*/, currency/*:String*/) {
	//if this.
}

/*public int*/ ProductsCookie.prototype.getDeliverySum = function (deliveryType/*:String*/, paymentType/*:String*/, currency/*:String*/) {

}

/*public int*/ ProductsCookie.prototype.getTotalSum = function (deliveryType/*:String*/, paymentType, currency/*:String*/) {

}

/*class*/ ShoppingCart = function (fields/*Array*/, imagesFolder/*:String*/,  name/*:String*/, create/*:Boolean*/) {
	fields = fields || SHOPPING_CART_FIELDS;
	assert(fields, "(ShoppingCart) fields");

	this.imagesFolder = imagesFolder || SHOPPING_CART_IMAGES_FOLDER;
	assert(this.imagesFolder, "(ShoppingCart) this.imagesFolder");

	name = name || "ShoppingCart";

	this._container = document.getElementById(name);
	assert(this._container, "(ShoppingCart) this._container");

	this._productCountLabel = document.getElementById("ProductCountLabel")
	assert(this._productCountLabel, "(ShoppingCart) this._productCountLabel");

	this._productSumLabel = document.getElementById("ProductSumLabel")
	assert(this._productSumLabel, "(ShoppingCart) this._productSumLabel");

	this._products = new ProductsCookie(name, fields);

	var products = this._products.select(), count = 0, sum = 0, temp = "";
	var template = '<div id="ProductRow[]">' + this._template + '</div>';

	for (var key in products)
		temp += template.replace(/\[ProductName\]/, products[key].name).replace(/\[\]/g,products[key].id).replace(/\[ProductImage\]/, this.imagesFolder + "/" + products[key].image);

	document.write(temp);

	for (var key in products)
		this._addSpinEdit(products[key]);

	this.setTotalCounters();
	this._busy = false;
}

ShoppingCart.prototype._template = TEMPLATE; //delete TEMPLATE; ?
ShoppingCart.prototype._busy = true;

var COURSE = 31;

/*private*/ ShoppingCart.prototype.setTotalCounters = function ()/*:Viod*/ {
	this._productCountLabel.innerHTML = this._products.totalCount();
	this._productSumLabel.innerHTML = roundTo(this._products.totalPrice() * COURSE, -2);

	if (this.orderButton)
		if (this._products.totalCount() > 0) {
			this.orderButton.style.display = this.cancelButton.style.display = "block";
			this.help.style.display = "none";
		} else {
			this.orderButton.style.display = this.cancelButton.style.display = "none";
			this.help.style.display = "block";
		}
}

/*private*/ ShoppingCart.prototype.deleteProduct = function (id/*:Number*/)/*:Viod*/ {
	if (this._busy) return; else this._busy = true;
	var product = this._products.select(id);
	this._products.remove(id);
	var div = document.getElementById("ProductRow" + product.id);
	div.parentNode.removeChild(div);

	this.setTotalCounters();
	this.save();
	this._busy = false;
}

/*private*/ ShoppingCart.prototype._addSpinEdit = function (product/*:Object*/)/*:Viod*/ {
	product.__spinEdit = new SpinEdit("CountEdit" + product.id, "UpButton" + product.id,
		"DownButton" + product.id);
	product.__spinEdit.owner = this;
	product.__spinEdit.min = 1;
	product.__spinEdit.onchange = this._spinEditChange;
	product.__spinEdit.edit.value = product.count;
	product.__spinEdit.product = product;

	var cancelButton = document.getElementById("CancelButton" + product.id);
	cancelButton.productId = product.id;
	addEventListener(cancelButton, "click", this, this.cancelButtonClick);
	//onclick="shoppingCart.deleteProduct([])id="[]""
}

/*private*/ ShoppingCart.prototype.cancelButtonClick = function (sender) {
	this.deleteProduct(sender.productId);
}

ShoppingCart.prototype.addProduct = function (product/*:Object*/)/*:Viod*/ {
	if (!navigator.cookieEnabled) return alert("Ваш браузер не поддерживает файлы cookie.");
	if (this._busy) return; else this._busy = true;

	assert(product.id, "ShoppingCart.addProduct\nproduct.id");
	assert(product.name, "ShoppingCart.addProduct\nproduct.name");
	assert(product.price, "ShoppingCart.addProduct\nproduct.price");

	if (!product.image) product.image = '';
	if (!product.count) product.count = 1;
	// Если продукта с данным ID еще нет в корзине.
	if (this._products.insert(product)) {

		// Создаем div.
		var div = document.createElement("div");
		// Добавляем в него клон шаблона.

		this._container.appendChild(div);
		div.innerHTML = this._template.replace(/\[ProductName\]/,product.name).replace(/\[\]/g,product.id).replace(/\[ProductImage\]/, this.imagesFolder + "/" + product.image);
		div.setAttribute("id", "ProductRow" + product.id);

		this._addSpinEdit(product);

	// Если продукт с данным ID уже есть в корзине.
	} else {
		this._products.select(product.id).__spinEdit.edit.value = this._products.select(product.id).count -= -product.count;
	}

	this.setTotalCounters();
	this.save();
	this._busy = false;
}

/*private void*/ ShoppingCart.prototype._spinEditChange = function (/*SpinEdit*/ sender) {
	this._busy = true;
	sender.product.count = sender.edit.value;
	this.setTotalCounters();
	this.save();
	this._busy = false;
}

/*private*/ ShoppingCart.prototype.empty = function ()/*:Void*/ {
	if (this._busy) return; else this._busy = true;
	this._container.innerHTML = "";
	this._products.remove();
	this.setTotalCounters();
	this.save();
	this._busy = false;
}

ShoppingCart.prototype.isEmpty = function ()/*:Boolean*/ {
	return this._products.getLength() == 0;
}

ShoppingCart.prototype.save = function ()/*:Void*/ {
	this._products.set("/");
}

ShoppingCart.prototype.addButtons = function ()/*:Void*/ {
	if (this.cancelButton = document.getElementById("CancelButton"))
		addEventListener(this.cancelButton, "click", this, this.empty);

	if (this.orderButton = document.getElementById("OrderButton"))
		addEventListener(this.orderButton, "click", this, this.save);
	assert(this.orderButton, "(ShoppingCart.addButtons) this.orderButton")

	this.help = document.getElementById("Help");

	if (this.isEmpty()) {
		if (this.orderButton) this.orderButton.style.display = "none";
		if (this.cancelButton) this.cancelButton.style.display = "none";
	} else {
		if (this.help) this.help.style.display = "none";
	}
}

assert(addToCart, "(shop.js) addToCart");

var SHOP_JS = EVENTS_JS && COOKIES_JS && MATH_JS && SPINEDIT_JS;