/*
 * Sweetwater Cart Class 1.0.0
 * Copyright (c) 2009 Andrey Migalnikov
 */
function Cart(object) {

	this.object = object;
	this.items = [];
	this.cartObject = document.getElementById("cart-table") || null;
	this.loaded = false;

	//Инициализация корзины: загрузка элементов и обновление корзины
	this.init = function() {
		this.items = this.loadItems(this.itemsCookieString());
		this.updateCart();
		this.loaded = true;
	}

	//Структура элемента
	this.item = function(id, price, count) {
		this.id = parseInt(id);
		this.price = price;
		this.count = (typeof count == "undefined") ? 1 : parseInt(count);
	}

	//Преобразование элементов из массива в строку
	this.itemsToString = function() {
		var itemsString = "";
		for ( var index in this.items ) {
			var item = this.items[index];
			itemsString += item.id + "::" + item.price + "::" + item.count + "&&";
		}
		return itemsString;
	}

	//Добавление нового элемента в массив элементов, сохранение изменений и обновление корзины
	this.addItem = function(id, price, count) {
		var item = new this.item(id, price, count);
		if ( this.items.length != 0 ) {
			var findItem = false;
			for ( var index in this.items ) {
				if ( id == this.items[index].id ) {
					findItem = true;
					if ( typeof count == "undefined" )
						this.items[index].count = this.items[index].count + 1;
					else
						this.items[index].count = count;
				}
			}
			if ( findItem == false )
				this.items.push(item);
		}
		else
			this.items.push(item);

		this.saveItems();
		this.updateCart();
	}

	//Удаление элемента из массива, сохранение изменений и обновление корзины
	this.removeItem = function(index) {
		this.items.splice(index, 1);
		this.saveItems();

		// пока исправим там, а вызов updateCart() закомментим
		window.location = window.location
		// this.updateCart();
	}

	//Удаление всех элементов из массива, сохранение изменений и обновление корзины
	this.removeAll = function() {
		this.items = [];
		this.saveItems();
		this.updateCart();
	}

	//Уменьшение количества элементов в корзине с индексом index на единицу
	this.decreaseItemCount = function(index) {
		if ( this.items[index].count == 1 ) {
			this.removeItem(index);
		}
		else {
			this.items[index].count = this.items[index].count - 1;
			this.saveItems();
			this.updateCart();
		}
	}

	//Изменение количества элементов в корзине с индексом index на число count
	this.changeItemCount = function(index, count) {
		count = parseInt(count);
		if ( count <= 0 || isNaN(count) ) {
			this.removeItem(index);
		}
		else {
			this.items[index].count = count;
			this.saveItems();
			this.updateCart();
		}
	}

	//Сохранение изменений в cookies; время жизни cookies = 30 дней
	this.saveItems = function() {
		var date = new Date();
		date.setTime(date.getTime() + (1000 * 60 * 60 * 24 * 30));
		document.cookie = "items=" + this.itemsToString() + "; path=/; expires=" + date.toGMTString();
	}

	//Извлечение строки с элементами из cookies
	this.itemsCookieString = function() {
		for ( var i=0; i<document.cookie.length; i++ ) {
			if ( document.cookie.substring(i, i+6) == "items=" ) {
				var stringEnd = document.cookie.indexOf(";", i+6);
				if ( stringEnd == -1 )
					stringEnd = document.cookie.length;
				return document.cookie.substring(i+6, stringEnd);
			}
		}
		return "";
	}

	//Загрузка элементов из строки в массив
	this.loadItems = function(itemsString) {
		if ( itemsString != "" ) {
			var itemsStringArray = itemsString.substring(0, itemsString.length-1).split("&&")
			var itemsArray = [];
			for ( var i=0; i<itemsStringArray.length; i++ ) {
				var itemString = itemsStringArray[i].split("::");
				var item = new this.item(itemString[0], itemString[1], itemString[2]);
				itemsArray.push(item);
			}
			return itemsArray;
		}
		else
			return new Array();
	}

	//Визуальное обновление корзины, общей суммы заказа(без доставки), стоимости доставки, количества товаров в корзине
	this.updateCart = function() {
		if ( this.cartObject != null ) {
			$(this.cartObject).html("");
			if ( this.items.length != 0 ) {
				var items_string =
					"<tr class='caption'>" +
						"<td width='28%'>Наименование</td>" +
						"<td width='16%'>Количество</td>" +
						"<td width='20%'>Цена за шт.</td>" +
						"<td width='20%'>Общая цена</td>" +
						"<td width='14%' class='no-right-border'><br /></td>" +
					"</tr>";
				for ( var i=0; i<this.items.length; i++ ) {
					var item = this.items[i];
					items_string +=
					"<tr>" +
						"<td class='with-left-border'><a href='/catalog.php?product_id=" + item.id + "'>" + products[i] + "</a></td>" +
						"<td><input type='text' class='count' value='" + item.count + "' onblur='cart.changeItemCount(" + i + ", this.value);' /></td>" +
						"<td>" + item.price + " руб.</td>" +
						"<td>" + item.price * item.count + " руб.</td>" +
						"<td><span class='cancel' onclick='if ( confirm(\"Отменить заказ выбранного товара?\") ) cart.removeItem(" + i + ");'>Отменить</span></td>" +
					"</tr>";
				}
				$(this.cartObject).html(items_string);
			}
			else {
				location.href = "/";
			}
		}
		var totalPriceElement = document.getElementById("cart-total-price") || null;
		var totalDeliveryElement = document.getElementById("cart-total-delivery") || null;
		var totalCount = document.getElementById("cart-total-count") || null;
		var totalOrder = document.getElementById("cart-total-order") || null;

		if ( totalPriceElement != null ) {
			totalPriceElement.innerHTML = this.totalPrice();
		}

		if ( totalDeliveryElement != null ) {
			if ( this.deliveryPrice() == 0 ) {
				$(totalDeliveryElement).html("Бесплатно");
			}
			else {
				$(totalDeliveryElement).html("<b>" +this.deliveryPrice() + "</b>" + " руб.");
			}
		}

		if ( totalCount != null ) {
			totalCount.innerHTML = this.itemsCount();
		}

		if ( totalOrder != null ) {
			totalOrder.innerHTML = this.totalPrice() + this.deliveryPrice();
		}

		var draggableCart = document.getElementById("draggable-cart") || null;

		if ( draggableCart != null ) {
			if ( this.loaded == true && this.itemsCount() != 0 ) {
				$(draggableCart).animate({ opacity : 0.7 }, 100, function() {
					$(this).animate({ opacity : 0.85 }, 100);
				});
			}
			if ( this.itemsCount() == 0 ) {
				if ( this.loaded == false )
					$(draggableCart).css({ opacity : 0 });
				else
					$(draggableCart).animate({ opacity : 0 });
			}
		}
	}

	//Общая сумма заказа(без доставки)
	this.totalPrice = function() {
		var totalPrice = 0;
		for ( var index in this.items ) {
			totalPrice += this.items[index].price * this.items[index].count;
		}
		return totalPrice;
	}

	//Количество товаров в корзине
	this.itemsCount = function() {
		var count = 0;
		for ( var index in this.items ) {
			count += this.items[index].count;
		}
		return parseInt(count);
	}

	//Стоимость доставки
	this.deliveryPrice = function() {
		var deliveryPrice = 0;
		var current_zone = 0;

		var zones = {
			0 : [ 1, 2, 3 ],
			1 : [ 8, 9, 10, 12, 13, 15, 19, 23, 24, 28, 29, 30, 34, 35, 39, 43, 51, 54, 61, 66, 69, 70, 72, 82 ],
			2 : [ 6, 7, 11, 17, 18, 25, 27, 32, 38, 40, 41, 46, 48, 52, 53, 57, 60, 62, 63, 65, 67, 74, 75, 78 ],
			3 : [ 4, 16, 21, 22, 26, 33, 36, 37, 45, 47, 49, 50, 56, 71, 73 ],
			4 : [ 42, 58, 59, 76, 77 ],
			5 : [ 5, 14, 20, 31, 55, 64, 68, 79, 80, 81 ]
		};
        if(this.totalPrice() == 0)
        	return deliveryPrice;

		for ( var key in zones ) {
			for ( var key2 in zones[key] ) {
				if ( form_location.val() == zones[key][key2] ) {
					current_zone = parseInt(key);
				}
			}
		}

		sub_cost = 0;
		base_cost = 0;

		switch ( current_zone ) {
			case 0 :
				base_cost = 300;
				sub_cost = 20;
			break;

			case 1 :
				base_cost = 460;
				sub_cost = 60;
			break;

			case 2 :
				base_cost = 570;
				sub_cost = 80;
			break;

			case 3 :
				base_cost = 630;
				sub_cost = 100;
			break;

			case 4 :
				base_cost = 690;
				sub_cost = 120;
			break;

			case 5 :
				base_cost = 770;
				sub_cost = 140;
			break;
		}

		if ( form_location.val() == 1 ) {
			deliveryPrice = 0;
			if ( this.totalPrice() < 2000 ) {
				deliveryPrice = 250;
			}
		}
		else {
			if ( form_delivery_method.val() == 2 ) {
				deliveryPrice = base_cost+(this.itemsCount()-1)*sub_cost;
			}
			else if ( form_delivery_method.val() == 3 ) {
				deliveryPrice = 300+(this.itemsCount()-1)*50;
			}
		}

		return deliveryPrice;
	}

	//Функция показа уведомления о добавлении товара в корзину
	this.showReport = function( context ) {
		var element = document.createElement("div");
		element.style.position = "absolute";
		element.style.top = "26px";
		element.style.left = "12px";
		element.style.textAlign = "left";
		element.style.color = "#6d8eb6";
		$(element).css({ opacity : 0 });
		element.innerHTML = "Товар&nbsp;добавлен&nbsp;в&nbsp;корзину";
		$(element).animate({ opacity : 1 }, 300).animate({ opacity : 0 }, 600);
		context.appendChild(element);
	}

	//Инициализация корзины при создании экземпляра класса
	this.init();

}