/*
 *  класс хранит в себе идентификаторы товаров в порядке добавления в корзину
 */
function basket(string, changeFunction)
{
	// список товаров в порядке добавления в корзину
	this.goods = {}

	// список ключей в порядке добавления
	// [номер (начинается с 0)] -> [ключ в хэше goods]
	this.positions = new Array()
	this.length = 0

	this.changeFunction = changeFunction


	// добавим в корзину
	this.add =
		function (data)
		{
			this.load(data)

			if ( this.changeFunction )
			{
				this.changeFunction( this )
			}
		}

	this.createKey =
		function (itemId, sizeId)
		{
			return itemId + '-' + sizeId
		}

	// private
	this.load =
		function ( data )
		{
			var key = this.createKey(data.itemId, data.sizeId)

			if ( this.goods[key] )
			{
				this.goods[key].count++
			}
			else
			{
				this.goods[key] =
					{
						count: 1,
						position: this.length
					}

				this.positions.push(key)

				this.length++
			}
			
			this.goods[key].preorder = data.preorder
		}

	// изменяем количество товара в корзине
	this.changeCount =
		function (data, count)
		{
			var key = this.createKey(data.itemId, data.sizeId)

			this.goods[key].count = count
			if ( this.changeFunction )
			{
				this.changeFunction( this )
			}
		}

	// уберём из корзины
	this.remove =
		function (key)
		{
			if ( this.goods[key] )
			{
				this.positions.splice(this.goods[key].position, 1)
				delete this.goods[key]

				this.length--

				if ( this.changeFunction )
				{
					this.changeFunction( this )
				}
			}
		}
	// преобразуем в строку вида "itemId1-sizeId1*count1!isPreorder_itemId2-sizeId2*count2!isPreorder_..." для отправки в базу
	this.toString =
		function ()
		{
			// скопируем содержимое массива с товарами
			var fromArray = new Array()
			fromArray = fromArray.concat(this.positions)

			var result = new Array()
			var currentKey

			for(var currentIndex = 0, length = fromArray.length ; currentIndex < length ; currentIndex++ )
			{
				currentKey = fromArray[currentIndex]
				result.push( currentKey + '*' + this.goods[currentKey].count + '!' + this.goods[currentKey].preorder )
			}
			result = result.join('_')

			return result
		}
	// загружает данные в поля объекта из строки вида "itemId1-sizeId1*count!isPreorder_itemId2-sizeId2*count!isPreorder_..." для загрузки из кук
	// логическая ошибка — предзаказ для всего количества (теоретически, может быть, что человек купит 10 штук, а в наличии только 5)
	this.fromString =
		function (string)
		{
			var splitted = string.split('_')

			/** @type String */
			var currentPair
			var currentCount

			for( var currentIndex = 0, length = splitted.length ; currentIndex < length; currentIndex++ )
			{
				currentPair = splitted[currentIndex]
				
				currentPair = currentPair.split('!')
				currentPreorder = currentPair[1]
				currentPair = currentPair[0]
				
				currentPair = currentPair.split('*')
				currentCount = currentPair[1]
				currentPair = currentPair[0]
				
				currentPair = currentPair.split('-')

				for( var currentIteration = 0 ; currentIteration < currentCount ; currentIteration++ )
				{
					this.load(
						{
							itemId: currentPair[0],
							sizeId: currentPair[1],
							preorder: currentPreorder
						}
					)
				}
			}
		}

	if ( typeof(string) != 'undefined' && string != null )
	{
		this.fromString(string)
	}
}

var userBasket
$(document).ready(
	function ()
	{
		if ( !loggedIn )
		{
			userBasket =
				new basket(
					$.cookie('userBasket'),
					function ( basketObject )
					{
						$.cookie(
							'userBasket',
							basketObject.toString(),
							{
								expires: 365,
								secure: false,
								path: '/'
							}
						)
					}
				)


			if ( $('.b-basket-summary').length > 0 )
			{
				$('ul.collection li a.b-delete-link').click(
					function ()
					{
						var data = $(this).attr('href')
						data = data.substring(1)
						data = data.split('&')

						var itemId = data[2].split('itemId=')
						itemId = itemId[1]

						var sizeId = data[1].split('sizeId=')
						sizeId = sizeId[1]

						userBasket.remove(
							userBasket.createKey(itemId, sizeId)
						)
						window.location = window.location

						return false
					}
				)

				if ( userBasket.length > 0 )
				{
					$('#mc-basketNotLoggedIn-auth-link').click(
						function ()
						{
							modalLoginContent.select( 'mc-loginForm' )
							return false
						}
					)
				}

				$('#content span.gray-button').each(
					function ()
					{
						if ( userBasket.length > 0 )
						{
							$(this).removeAttr('onclick')
							$(this).click(
								function ()
								{
									tb_show(null, '/?TB_inline&height=300&width=600&inlineId=modal-loginForm&modal=true&showHandler=modalLoginContent.reset()', null)
//									tb_show(null, '/basket/notLoggedIn.html?KeepThis=true&amp;TB_iframe=true&amp;height=300&amp;width=600', null)
									return false
								}
							)
						}
					}
				)
			}

		}

	}
)
