// ------------------------------ вывести отформатированную сумму
function formatPrice(val) {
	var val = new String(val);
	val = val.replace(" ", "");
	newval = "";
	for(var i=val.length-1; i >=0; i--) {
		newval = val[i] + newval;
		if((val.length - i) % 3 == 0) {
			newval = " " + newval;
		}
	}
	return newval;
}


// ------------------------------ Корзина
var Cart = {
	
	Fields : {},
	
	Errors : {},
	
	Intervals : {},
	
	HasErrors : function() {
		for(i in Cart.Errors) {
			if(Cart.Errors[i] == true) {
				return true;
			}
		}
		return false;
	},
	
	Init : function() {
		// поля, которые нужно обновлять после успешно проведенного запроса
		$('[basket-element]').each(function() {
			Cart.Fields[$(this).attr("basket-element")] = $(this);
		})
		// события
		$('[basket-event]').each(function() {
			switch($(this).attr('basket-event')) {
				case "add" :
					$(this).click(function() {
						Cart.Add($(this).attr('djem-document'), 1, $(this));
					})
					break;
				case "delete" :
					$(this).click(function() {
						Cart.Delete($(this).attr('djem-document'));
					})
					break;
				case "request" :
					$(this).click(function() {
						$.ajax({
							type: "POST",
							url: "/system/php/service.php",
							data: "goodId=" + $(this).attr('djem-document') + "&_module=basket&_action=requestGood",
							dataType: "json",
							success: function(json){
								if(json.result == "success") {
									Notificator.Success("Внимание!", "Ваша заявка успешно отправлена.");
								} else {
									Notificator.Error("Внимание!", "Произошла ошибка. Попробуйте позже.");
								}
							},
							error: function() {
								Notificator.Error("Внимание!", "Произошла ошибка. Попробуйте позже.");
							}
						})
					})
					break;
			}
		})
	},
	
	UpdateQuantity : function(goodId, goodQuantity, successCallback, errorCallback) {
		$.ajax({
			type: "POST",
			url: "/system/php/service.php",
			data: "goodId=" + (goodId) + "&basket-good-" + (goodId) + "=" + (goodQuantity) + "&_module=basket&_action=updateQuantities",
			dataType: "json",
			success: function(json){
				if(json.result == "success") {
					Notificator.Success("Внимание!", "Товар успешно добавлен в корзину.");
					if(json.count > 0) {
						Cart.Fields['top-info-block-wrapper'].addClass('full');
						Cart.Fields['top-info-block'].html("Товаров в <a href='/rus/personal/basket.phtml'>корзине</a>: " + json.count);
						Cart.Fields['total-items-or-empty-string'].html(json.count);
						Cart.Fields['basket-header-count'].html(json.count);
						Cart.Fields['full-price'].html(formatPrice(json.price));
					} else {
						window.location.reload();
					}
					successCallback.call(null);
				} else {
					var text = "";
					for (i in json) {
						if(i != "result") {
							if(json[i].match(/not-enough-items/)) {
								$data = json[i].split(":");
								text = "Недостаточное количество товара на складе. Доступно " + $data[1] + " шт.";
							} else {
								switch(json[i]) {
									case "no-items" :
										text = i + " : Товар отсутствует на складе.\n";
										break;
									case "quantity-lt-1" :
										text = i + " : Вы пытаетесь заказать отрицательное число единиц товара.\n";
										break;
									case "not-permited" :
										text = i + " : Вы не можете заказать этот товар.\n";
										break;
									default :
										text = i + " : Произошла ошибка при добавлении товара.\n";
										break;
								}
							}
						}
					}
					errorCallback.call(null, text);
				}
			},
			error: function() {
				Notificator.Error("Внимание!", "Произошла ошибка. Попробуйте позже.");
			}
		})
	},
	
	Delete : function(goodId) {
		$.ajax({
			type: "POST",
			url: "/system/php/service.php",
			data: "goodId=" + (goodId) + "&_module=basket&_action=deleteGood",
			dataType: "json",
			success: function(json){
				window.location = "/rus/personal/basket.phtml";
			},
			error: function() {
				Notificator.Error("Внимание!", "Произошла ошибка. Попробуйте позже.");
			}
		})
	},
	
	Add : function(goodId, goodQuantity, element) {
		$.ajax({
			type: "POST",
			url: "/system/php/service.php",
			data: "goodId=" + (goodId) + "&goodQuantity=" + (goodQuantity) + "&_module=basket&_action=addGood",
			dataType: "json",
			success: function(json){
				if(json.result == "success") {
					Notificator.Success("Внимание!", "Товар успешно добавлен в корзину.");
					if(json.count > 0) {
						Cart.Fields['top-info-block-wrapper'].addClass('full');
						Cart.Fields['top-info-block'].html("Товаров в <a href='/rus/personal/basket.phtml'>корзине</a>: " + json.count);
						Cart.Fields['total-items-or-empty-string'].html(json.count);
					} else {
						Cart.Fields['top-info-block'].html("Товаров в <a href='/rus/personal/basket.phtml'>корзине</a>: " + json.count);
						Cart.Fields['total-items-or-empty-string'].html("пустая");
						Cart.Fields['top-info-block-wrapper'].removeClass('full');
					}
				} else {
					var text = "";
					switch(json.reason) {
						case "no-items" :
							text = "Товар отсутствует на складе.";
							break;
						case "quantity-lt-1" :
							text = "Вы пытаетесь заказать отрицательное число единиц товара.";
							break;
						case "not-enough-items" :
							text = "Недостаточное количество товара на складе.";
							break;
						case "not-permited" :
							text = "Вы не можете заказать этот товар.";
							break;
						default :
							text = "Произошла ошибка при добавлении товара.";
							break;
					}
					Notificator.Error("Внимание!", text);
				}
			},
			error: function() {
				Notificator.Error("Внимание!", "Произошла ошибка. Попробуйте позже.");
			}
		})
	}
}

// ------------------------------ Всплывающие уведомления (Messenger style)
var Notificator = {
	
	Html : '<div id=\"digitorum-notificator\" class=\"alert-error\" style=\"position: absolute; bottom: auto; z-index: 99;\"></div>',
	
	ShowTimeout : false,
	
	Calculate : function(instanse) {
		instanse.css({
			"top" : Mouse.LastPosition.y + 20,
			"left" : Mouse.LastPosition.x - instanse.width() / 2
		})
	},
	
	GetInstance : function() {
		var instanse = $('#digitorum-notificator');
		if(instanse.get(0) == undefined) {
			$('body').append(Notificator.Html);
			instanse = $('#digitorum-notificator');
		}
		return instanse;
	},
	
	Hide : function() {
		clearTimeout(Notificator.ShowTimeout);
		var instanse = Notificator.GetInstance();
		instanse.hide();
	},
	
	Show : function(title, text, newClass) {
		var instanse = Notificator.GetInstance();
		Notificator.Hide();
		instanse.attr("class", newClass);
		instanse.html(text);
		Notificator.Calculate(instanse);
		instanse.fadeIn();
		Notificator.ShowTimeout = setTimeout(function() {
			instanse.fadeOut();
		}, '2500')
	},
	
	Success : function(title, text) {
		Notificator.Show(title, text, "alert");
	},
	
	Error : function(title, text) {
		Notificator.Show(title, text, "alert-error");
	}
}

// ------------------------------ Мыша
var Mouse = {
	
	LastPosition : {},
	
	SnifPosition : function(event) {
		if (document.attachEvent != null) { 
			x = window.event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
			y = window.event.clientY + document.documentElement.scrollTop + document.body.scrollTop;
		}
		if (!document.attachEvent && document.addEventListener) {
			x = event.clientX + window.scrollX;
			y = event.clientY + window.scrollY;
		}
		Mouse.LastPosition = {x:x, y:y};
	}
	
}

// ------------------------------ Инициализация
$(document).ready(function() {
	Cart.Init();
	$(document).click(function(event) {
		Mouse.SnifPosition(event);
	})
})
