with(CBasketItem = new Function){
	prototype.prev		= undefined;
	prototype.next		= undefined;
	prototype.id		= 0;
	prototype.text		= "";
	prototype.cost		= 0;
	prototype.count		= 0;
	prototype.maxcount	= 0;
}
with(CBasket = new Function){
	prototype._Items		= undefined;	// - Первый элемент
	prototype._ItemsCount	= 0;			// - Число элементов
	prototype._TotalCost	= 0.0;			// - 
	
	prototype._SubmitTime	= [ 12, 00 ];

	//! Добавление элемента ( по исходным данным )
	prototype.addItem = function( data ){
		var exItem = this.getItemById( data.id );
		if( exItem == undefined ){
			var item = new CBasketItem();
			with( item ){
				id			= data.id
				text		= data.text;
				cost		= parseFloat( data.cost );
				count		= parseInt( data.count );
				maxcount	= parseInt( data.maxcount );
			}
			if( this._Items != undefined ){
				item.next		= this._Items;
				item.next.prev	= item;
			}
			this._Items	= item;
			this._ItemsCount++;
		}else{
			//! Такой элемент уже есть, увеличиваем счётчик
			if( exItem.maxcount > 0 && exItem.count >= exItem.maxcount ){ return false; }
			exItem.count++;
		}
		this.updateTotalCost();
		return true;
	}
	//! Получение объекта по ID
	prototype.getItemById = function( id ){
		if( this._Items == undefined ) return undefined;
		var item = this._Items;
		do{
			if( item.id == id ) return item;
			item = item.next;
		}while( item != undefined );
		return undefined;
	}
	//! Удаление элемента по ID
	prototype.removeItemById = function( id ){
		if( this._Items == undefined ) return;
		if( this._Items.id == id ){
			this._ItemsCount--;
			
			if( this._Items.next != undefined ) this._Items.next.prev = undefined;
			this._Items = this._Items.next;
			this.updateTotalCost();
			return;
		}
		var item = this._Items;
		do{
			if( item.id != id ){ item = item.next; continue; }
			// - Удаляем элемент
			if( item.prev != undefined ) item.prev.next = item.next;
			if( item.next != undefined ) item.next.prev = item.prev;
			this._ItemsCount--;
			delete item;
			break;
		}while( item != undefined );
		if( this._ItemsCount == 0 ) this._Items = undefined;
		// - Обвноление стоимости
		this.updateTotalCost();
	}
	
	//! Пересчёт общей стоимости
	prototype.updateTotalCost = function(){
		this._TotalCost = 0.0;
		if( this._Items == undefined ) return;
		var item = this._Items;
		do{
			this._TotalCost += parseFloat( item.cost ) * parseFloat( item.count );
			item = item.next;
		}while( item != undefined );
	}
	
	//! Получение числа элементов
	prototype.getItemsCount = function(){ return this._ItemsCount; }
	
	//! Получение общей стоимости
	prototype.getTotalCost = function(){ 
		this.updateTotalCost();
		return this._TotalCost;
	}
}
var hBasket = new CBasket();

//! Добавление товара в корзину
function basketAdd( id ){
	// - Новый элемент
	$.getJSON( '/basket/add-' + id, function( data ){
		if( data.errorcode != 0 ){
			alert( "Невозможно добавить товар в корзину - " + data.errormsg );
			return;
		}
		// - Добавляем информацию
		if( hBasket.addItem({
			id:			data.item.id,
			text:		data.item.name,
			cost:		data.item.cost,
			count:		1,
			maxcount:	0
		})){
			// - Обновляем блок корзины
			basketUpdateBlock();
			alert( data.item.name + "\nдобавлен в корзину" );
		}else{
			alert( "Невозможно добавить в корзину" );
		}		
	});
}

//! Изменение числа элементов товара в корзине
function basketChangeCount( id ){
	var item = hBasket.getItemById( id );
	if( item == undefined ) return;
	var oldcount = item.count;
	var Reg = /^([0-9]+)$/;
	if( Reg.test( $('#item_' + id + '_count').val() ) ){
		item.count = parseInt( $('#item_' + id + '_count').val() );
		if( item.count < 1 ) item.count = 1;
		
	}else{
		item.count = 1;
	}
	if( item.maxcount > 0 && item.count > item.maxcount ){
		item.count = item.maxcount;
		$('#item_' + id + '_count').val( item.count );
	}
	$('#item_' + id + '_count').val( item.count );
	
	// - Обновляем в корзине
	$.getJSON( '/basket/setcount-' + id + '-' + item.count, function( data ){
		if( data.errorcode != 0 ){
			alert( "Невозможно изменить количество. Попробуйте ещё раз." );
			item.count = oldcount;
		}
		// --- Обновление в интерфейсе
		$('#item_' + id + '_count').val( item.count );
		$('#item_' + id + '_totalcost').text( parseFloat( item.count ) * parseFloat( item.cost ) ); 
		$('#basket_totalcost').text( hBasket.getTotalCost() );
		
		// --- Заказ
		if( $('#orderShippmentCost').text() != '' ){
			$('#orderTotalCost').text( parseFloat( hBasket.getTotalCost() ) + parseFloat( $('#orderShippmentCost').text() ) );
		}
		basketUpdateBlock();
	});
}
function basketPlusCount( id ){
	var NewCount = parseInt( $('#item_' + id + '_count').val() ) + 1;
	$('#item_' + id + '_count').val( NewCount );
	basketChangeCount( id );
}
function basketMinusCount( id ){
	var NewCount = parseInt( $('#item_' + id + '_count').val() ) - 1;
	if( NewCount < 1 ) {
		var item = hBasket.getItemById( id );
		if( item == undefined ) return;
		if( !confirm( 'Вы действительно хотите удалить из корзины\n' + item.text ) ) return;
		basketRemoveItem_Apply(  id );
		return;
	}
	$('#item_' + id + '_count').val( NewCount );
	basketChangeCount( id );
}

//! Удаление выделенных элементов из корзины
function basketRemoveItem(){
	$("input[@id|=chBasketItem][type='checkbox']").each(function(id){
		if( $(this).attr('checked') ){
			var Item = hBasket.getItemById( parseInt( $(this).val() ) );
			if( Item == undefined ) return;
			if( !confirm( 'Вы действительно хотите удалить из корзины\n' + Item.text ) ) return;
			basketRemoveItem_Apply( Item.id );
		}
	});
}

function basketRemoveItem_Apply( id ){
	// - Удаление
	$.getJSON( '/basket/del-' + id, function( data ){
		if( data.errorcode != 0 ){
			alert( "Невозможно удалить из корзины. Попробуйте ещё раз." );
			return;
		}
		// --- Обновление в интерфейсе
		hBasket.removeItemById( id );
		$('#trBasketItem_' + id ).remove();
		$('#basket_totalcost').text( hBasket.getTotalCost() );
		if( hBasket.getItemsCount() == 0 ){
			$('#tblBasketItems').hide();
			$('#panBaketEmpty').show();
		}
		basketUpdateBlock();
	});
}

//! Обновление блока корзины
function basketUpdateBlock(){
	if( hBasket.getItemsCount() > 0 ){
		$('#basketblock_itemcount').text( hBasket.getItemsCount() );
		$('#basketblock_totalcost').text( hBasket.getTotalCost() );
		$('#basketblock_pannotempty').show();
		$('#basketblock_panempty').hide();
	}else{
		$('#basketblock_pannotempty').hide();
		$('#basketblock_panempty').show();
		$('#basketblock_itemcount').text( '' );
	}
}









