// Object umiBasket ===============================================================

// contructor
function umiBasket(s_ancestor) {
	if (typeof(s_ancestor) === 'udefined') {
		var s_ancestor = "";
	}
	if (!s_ancestor) {
		this.ancestor = "";
	} else {
		if (s_ancestor.substr(0, 1) === '#') {
			this.ancestor = s_ancestor;
		} else {
			this.ancestor = "#" + s_ancestor.replace(".", "\\.") + " ";
		}
	}
}

umiBasket.instance = null;

umiBasket.getInstance = function(s_ancestor) {
	if (typeof(s_ancestor) === 'udefined') {
		var s_ancestor = false;
	}
	if(!umiBasket.instance) {
		umiBasket.instance = new umiBasket(s_ancestor);
	} else {
		if (!s_ancestor) {
			umiBasket.instance.ancestor = "";
		} else {
			if (s_ancestor.substr(0, 1) === '#') {
				umiBasket.instance.ancestor = s_ancestor;
			} else {
				umiBasket.instance.ancestor = "#" + s_ancestor.replace(".", "\\.") + " ";
			}
		}
	}
	return umiBasket.instance;
}

// ==== default event handlers =================================================

umiBasket.prototype.onAfterAddElement = function (iElementId, iCount) {
	var o_append_link = $(this.ancestor+'[id=addtobasket_area_' + iElementId + ']');
	if (o_append_link && o_append_link.length) {
		o_append_link.html("<a href=\"/eshop/basket/\">В корзине " + iCount +
		" шт.</a> | <a href=\"javascript:umiBasket.getInstance().tryAddElement("+iElementId+");\">+1</a>");
	}

	if (!($(this.ancestor+'[id=basketrow_'+iElementId+']').length)) {
		// add new row in basket
		var arrTempNewItems = new Array();
		var arrTempNewItemsParents = new Array();
		var oNewRows = $(this.ancestor+'[id=basketnewrow]');
		var iCountNewRows = oNewRows.length;
		for (iI = oNewRows.length - 1; iI >=0; iI--) {
			arrTempNewItems[iI] = oNewRows[iI].cloneNode(true);

			var oNextObj = oNewRows[iI];
			oNewRows[iI].id = "basketrow_"+iElementId;

			arrTempNewItemsParents[iI] = oNextObj.parentNode;
		}

		if (iCountNewRows) {
			var s_anc = this.ancestor;

			$(s_anc+'[id=cnewitm_id]').attr('id', "citm_"+iElementId+"_id");
			$(s_anc+'[id=cnewitm_path]').attr('id', "citm_"+iElementId+"_path");
			$(s_anc+'[id=cnewitm_name]').attr('id', "citm_"+iElementId+"_name");
			$(s_anc+'[id=cnewitm_price]').attr('id', "citm_"+iElementId+"_price");
			$(s_anc+'[id=cnewitm_price_total]').attr('id', "citm_"+iElementId+"_price_total");

			var oControls = $(s_anc+'[id=cnewitm_count]');
			oControls.attr('id', "citm_"+iElementId+"_count");
			oControls.bind("change", function() {
				umiBasket.getInstance(s_anc).updateCount(iElementId, this.value);
				return false;
			});

			var oControls = $(s_anc+'[id=cnewitm_remove]');
			oControls.attr('id', "citm_"+iElementId+"_remove");
			oControls.bind("click", function() {
				umiBasket.getInstance(s_anc).tryRemoveBasketItem(iElementId);
				return false;
			});

			// append saved rows
			for (iI = 0; iI < arrTempNewItems.length; iI++) {
				var oParent = arrTempNewItemsParents[iI];
				if (oParent) {
					var o_next_child = oParent.appendChild(arrTempNewItems[iI]);
				}
			}
		}
	}

	this.tryUpdateBasket(false, iElementId);
}

umiBasket.prototype.onUpdate = function(oBasketInfo, b_full) {
	if (typeof(b_full) === 'undefined') var b_full = false;

	var iI = 0;
	if (oBasketInfo.basket_items.length == 0) {
		var oSbtns = $(this.ancestor+'input[id=basket-submit]');
		oSbtns.attr("disabled", "disabled");
	}
	if (oBasketInfo.basket_items.length) {
		var o_new_rows = $(this.ancestor+'[id=basketnewrow]');
		if (o_new_rows.length) { // full basket version
			for (var iJ = 0; iJ < oBasketInfo.basket_items.length; iJ++) {
				var oNextItemInfo = oBasketInfo.basket_items[iJ];
				var s_id = oNextItemInfo.id;

				if (b_full || $(this.ancestor+'[id=basketrow_'+s_id+']').css('display') === 'none') {
					$(this.ancestor+'[id=basketrow_'+s_id+']').css('display', "");

					$(this.ancestor+'input[id=citm_'+s_id+'_id]').attr("value", s_id);
					$(this.ancestor+':not(input)[id=citm_'+s_id+'_id]').html(s_id);

					$(this.ancestor+'input[id=citm_'+s_id+'_name]').attr("value", oNextItemInfo.name);
					$(this.ancestor+':not(input)[id=citm_'+s_id+'_name]').html(oNextItemInfo.name);

					$(this.ancestor+'input[id=citm_'+s_id+'_count]').attr("value", oNextItemInfo.count);
					$(this.ancestor+':not(input)[id=citm_'+s_id+'_count]').html(oNextItemInfo.count);

					$(this.ancestor+'input[id=citm_'+s_id+'_price_total]').attr("value", oNextItemInfo.price_total);
					$(this.ancestor+':not(input)[id=citm_'+s_id+'_price_total]').html(oNextItemInfo.price_total);

					$(this.ancestor+'input[id=citm_'+s_id+'_price]').attr("value", oNextItemInfo.price);
					$(this.ancestor+':not(input)[id=citm_'+s_id+'_price]').html(oNextItemInfo.price);

					$(this.ancestor+'a[id=citm_'+s_id+'_path]').attr("href", oNextItemInfo.element_path);
					$(this.ancestor+':not(a)[id=citm_'+s_id+'_path]').html(oNextItemInfo.element_path);
				}
			}
		}
	}

	$(this.ancestor+'input[id=order_total]').attr("value", oBasketInfo.order_total);
	$(this.ancestor+':not(input)[id=order_total]').html(oBasketInfo.order_total);

	$(this.ancestor+'input[id=global_discount]').attr("value", oBasketInfo.global_discount);
	$(this.ancestor+':not(input)[id=global_discount]').html(oBasketInfo.global_discount);

	$(this.ancestor+'input[id=total_count]').attr("value", oBasketInfo.total_count);
	$(this.ancestor+':not(input)[id=total_count]').html(oBasketInfo.total_count);
}

umiBasket.prototype.onAfterRemoveBasketItem = function (iElementId) {
	var oCartRows = $(this.ancestor+'[id=basketrow_'+iElementId+']');
	oCartRows.remove();

	this.tryUpdateBasket(false, 0);
}

// =============================================================================

umiBasket.prototype.tryAddElement = function(iElementId, iCount) {
	$('[id=goodcard_'+iElementId+']').append("<div class=\"vrl\"></div>");
	$('[id=goodcard_'+iElementId+'] .vrl').fadeTo('fast', 0.66);
	this.addElement(iElementId, iCount);
}
umiBasket.prototype.tryRemoveBasketItem = function(iElementId) {
	$(this.ancestor+'[id=basketrow_'+iElementId+']').append("<div class=\"vrl\"></div>");
	$(this.ancestor+'[id=basketrow_'+iElementId+'] .vrl').fadeTo('fast', 0.66);
	this.removeBasketItem(iElementId);
}
umiBasket.prototype.tryUpdateBasket = function(b_full, iElementId) {
	if (typeof(b_full) === 'undefined') var b_full = false;
	if (typeof(iElementId) === 'undefined') var iElementId = 0;

	$('[id=basketsumm]').append("<div class=\"vrl\" id=\"vrl_"+iElementId+"\"></div>");
	$('[id=basketsumm] .vrl[id=vrl_'+iElementId+']').fadeTo('fast', 0.66);

	if (iElementId) {
		$('[id=goodcard_'+iElementId+']').append("<div class=\"vrl_j2\"></div>");
		$('[id=goodcard_'+iElementId+'] .vrl_j2').fadeTo('fast', 0.66);
	}

	this.updateBasket(b_full, iElementId);
}

// ==== json requests jobs =====================================================

umiBasket.prototype.addElement = function(iElementId, iCount) {

	if (typeof(iCount) == "undefined") iCount = 1;
	if (typeof(iElementId) !== 'undefined') {
		var s_anc = this.ancestor;
		var hdl = function(oResponce) {
			iElementId = oResponce.iElementId;
			iCount = oResponce.iCount;
			umiBasket.getInstance(s_anc).onAfterAddElement(iElementId, iCount);
		}

		lLt.getInstance().execRemoteJs("/eshop/json_add_to_basket/"+iElementId+"/"+iCount+"/?", hdl, "umiBasket.getInstance('"+s_anc.replace("\\", "\\\\")+"').addElementReqComplete", "'"+iElementId+"'");
	}
}

umiBasket.prototype.updateBasket = function(b_full, iElementId) {

	if (typeof(b_full) === 'undefined') var b_full = false;
	if (typeof(iElementId) === 'undefined') var iElementId = 0;

	var s_anc = this.ancestor;
	var hdl = function(oResponce) {
		umiBasket.getInstance(s_anc).onUpdate(oResponce, b_full);
	}

	var o_new_rows = $(this.ancestor+'[id=basketnewrow]');
	if (o_new_rows.length) { // full basket version
		lLt.getInstance().execRemoteJs("/eshop/json_get_basket/?", hdl, "umiBasket.getInstance('"+s_anc.replace("\\", "\\\\")+"').updateBasketReqComplete", "'"+iElementId+"'");
	} else {
		lLt.getInstance().execRemoteJs("/eshop/json_get_basket_short/?", hdl, "umiBasket.getInstance('"+s_anc.replace("\\", "\\\\")+"').updateBasketReqComplete", "'"+iElementId+"'");
	}
}

umiBasket.prototype.updateCount = function(iElementId, iCount) {
	if (typeof(iCount) == "undefined") iCount = 1;
	if (typeof(iElementId) !== 'undefined') {
		var s_anc = this.ancestor;
		var hdl = function(oResponce) {
			umiBasket.getInstance(s_anc).tryUpdateBasket(true, iElementId);
		}
		lLt.getInstance().execRemoteJs("/eshop/json_update_count/"+iElementId+"/"+iCount+"/?", hdl, "umiBasket.getInstance('"+s_anc.replace("\\", "\\\\")+"').updateCountReqComplete", "'"+iElementId+"'");
	}
}

umiBasket.prototype.removeBasketItem = function(iElementId) {

	if (typeof(iElementId) !== "undefined") {
		var s_anc = this.ancestor;
		var hdl = function(oResponce) {
			umiBasket.getInstance(s_anc).onAfterRemoveBasketItem(iElementId);
		}

		lLt.getInstance().execRemoteJs("/eshop/json_remove_from_basket/"+iElementId+"/?", hdl, "umiBasket.getInstance('"+s_anc.replace("\\", "\\\\")+"').removeBasketItemReqComplete", "'"+iElementId+"'");
	}
}

// ====

umiBasket.prototype.addElementReqComplete = function(s_status, s_element_id) {
	if (s_status !== 'success') {
		alert("Товар\""+($('a[name=a_'+s_element_id+']').text())+"\" не удалось добавить в корзину (ошибка связи с сервером). Попробуйте еще раз.");
	}
	$('#goodcard_'+s_element_id+' .vrl').remove();
}
umiBasket.prototype.updateBasketReqComplete = function(s_status, s_init_element) {
	if (typeof(s_init_element) === 'undefined') var s_init_element = 0;
	if (s_status !== 'success') {
		alert("Не удалось обновить данные корзины (ошибка связи с сервером). Данные будут обновлены при перезагрузке страницы или переходе на другую страницу сайта.");
	}
	$('[id=basketsumm] .vrl[id=vrl_'+s_init_element+']').remove();
	if (s_init_element) {
		$('#goodcard_'+s_init_element+' .vrl_j2').remove();
	}
}
umiBasket.prototype.updateCountReqComplete = function(s_status, s_element_id) {
	if (s_status !== 'success') {
		alert("Не удалось пересчитать товар\""+($('a[name=a_'+s_element_id+']').text())+"\" (ошибка связи с сервером). Попробуйте еще раз.");
	}
}
umiBasket.prototype.removeBasketItemReqComplete = function(s_status, s_element_id) {
	if (s_status !== 'success') {
		alert("Не удалось удалить товар\""+($('a[name=a_'+s_element_id+']').text())+"\" из корзины (ошибка связи с сервером). Попробуйте еще раз.");
	}
	$(this.ancestor+'[id=basketrow_'+s_element_id+'] .vrl').remove();
}