var greenmarkt = new shop();

function shop() {
	var cursor = this;
	this.personal_discount = 0;
	this.cart_items = {};
	this.uid = null;

	$(function() {
		cursor.renderBase();
		if (document.location.pathname.startsWith('/shop/order'))
			cursor.renderOrder();
		else if (document.location.pathname.startsWith('/shop/cart'))
			cursor.renderCart();
		else if (document.location.pathname.startsWith('/shop/item'))
			cursor.renderItem();
		else if (document.location.pathname.startsWith('/shop/group'))
			cursor.renderGroup();
		else {
			cursor.getNews();
		}
		if (typeof cursor.renderEditable != "undefined")
			cursor.renderEditable();
	})
}

shop.prototype.jtransport = function(url, data, callback, errback) {

	$.post('/jtransport/' + url, data, function(response) {
		if (response.code > 0) {
			if (typeof callback == 'function')
				callback(response.message, response.code);
		} else {
			if (typeof errback == 'function') {
				errback(response.message, response.code);
			} else {
				alertError(response.message)
			}
		}
	}, 'json');
}

/*
 * shop.prototype.login = function(){ $.postExt("/order/cart", options,
 * function(data,status){ if (options) cursor.refreshCart(data.total_sum,
 * data.total_count, options.item_id); else cursor.refreshCart(data.total_sum,
 * data.total_count); }); }
 */
shop.prototype.getNews = function() {
	var cursor = this;
	var last_news = $.cookie('last_news');

	$.postExt("/ajax/news", {
		id : last_news
	}, function(data, status) {
		if (status == 1) {
			$.cookie('last_news', data.id, {
				expires : 365
			});
			alertInfo(data.message);
		}
	});
}

shop.prototype.askRegister = function(callbackfnc) {
	var cursor = this;
	$.msgbox('<h1>Регистрация</h1><br/>Поля отмеченные звёздочкой - обязательны для заполнения. Спасибо.', {
		type : 'prompt',
		inputs : [ {
			type : 'text',
			label : 'имя: *',
			value : '',
			required : 'true'
		}, {
			type : 'text',
			label : 'e-mail: *',
			value : '',
			required : 'true'
		}, {
			type : 'password',
			label : 'пароль:',
			value : '',
		}, {
			type : 'password',
			label : 'пароль ещё раз:',
			value : '',
		}, {
			type : 'text',
			label : 'мобильный телефон: *',
			value : '',
			required : 'true'
		}, {
			type : 'text',
			label : 'icq:',
			value : '',
		}, {
			type : 'text',
			label : 'skype:',
			value : '',
		} ],
		buttons : [ {
			type : 'cancel',
			value : 'Отмена'
		}, {
			type : 'submit',
			value : 'Зарегистрироваться'
		}

		]
	}, function(name, email, password, password2, phone, icq, skype) {
		if (!name || !email || !phone)
			return false;

		var options = {
			email : email,
			password : password,
			password2 : password2,
			name : name,
			icq : icq,
			skype : skype,
			phone : phone
		}

		$.postExt("/user/profile/", options, function(data, status) {
			cursor.uid = data.uid;
			if (typeof callbackfnc == "function")
				callbackfnc.call();
		});
	});
}

shop.prototype.remindPassword = function() {

	var cursor = this;
	$.msgbox('Восстановление пароля', {
		type : 'prompt',
		inputs : [ {
			type : 'text',
			label : 'e-mail:',
			value : '',
			required : 'true'
		} ],
		buttons : [ {
			type : 'cancel',
			value : 'Отмена'
		}, {
			type : 'submit',
			value : 'Выслать пароль'
		}

		]
	}, function(email) {
		if (!email)
			return false;

		var options = {
			email : email,
		}

		$.postExt("/user/remind_password/", options, function(data, status) {
			alertInfo(data);
			// cursor.uid = data.uid;
			// if (typeof callbackfnc == "function") callbackfnc.call();
		});
	});
}

shop.prototype.askLogin = function(callbackfnc) {
	var cursor = this;

	$.msgbox('Если вы что-то уже покупали на сайте ранее, введите свой e-mail и пароль:', {
		type : 'prompt',
		inputs : [ {
			type : 'text',
			label : '',
			value : '',
			required : 'true'
		}, {
			type : 'password',
			label : '',
			value : '',
			required : 'true'
		} ],
		buttons : [ {
			type : 'cancel',
			value : 'Нет, я тут впервые'
		}, {
			type : 'submit',
			value : 'Да'
		},

		]
	}, function(e1, e2) {
		if (!e1)
			cursor.askRegister(function() {

				if (typeof callbackfnc == "function")
					callbackfnc.call();
			})
		else {
			$.postExt("/user/login", {
				email : e1,
				password : e2
			}, function(data) {
				if (typeof callbackfnc == "function")
					callbackfnc.call();
			});
		}
	});
}

shop.prototype.splitNum = function(num) {
	var cursor = this;
	info("FUNCTION: splitNum");
	num = Math.round(num);
	var arr_num = (num + "").split("");
	var result = "";
	for (i = 1; i < arr_num.length + 1; i++) {
		result = arr_num[arr_num.length - i] + result;
		if ((i) % 3 == 0)
			result = " " + result;
	}
	return result.trim();
}

shop.prototype.refreshCart = function(sum, count, item_id) {
	var cursor = this;

	info("FUNCTION: refreshCart");
	var arr_sum = sum.split

	$(".shop-cart-body")
			.html(count + ' товаров<br/>на <b>' + cursor.splitNum(sum) + ' <span class="rur2">Р</span></b>');
	if (count > 0)
		$(".cart-order").show();

	if (item_id) {
		$(".shop-cart-body").effect("highlight", {}, 3000);
		$(".group_item_content", "#group" + item_id).css("opacity", "0.1");
		$(".added", "#group" + item_id).effect("highlight", {}, 1000);
	}
}

shop.prototype.cartAction = function(options) {
	var cursor = this;
	info("FUNCTION: cartAction");
	$.postExt("/ajax/cart", options, function(data, status) {
		cursor.uid = data.uid;
		if (options)
			cursor.refreshCart(data.total_sum, data.total_count, options.item_id);
		else
			cursor.refreshCart(data.total_sum, data.total_count);
	});
}

shop.prototype.renderBase = function(options) {
	var cursor = this;
	info("FUNCTION: renderBase");

	$(".pricein").each(function() {
		var pricein = $(this);
		pricein.html(cursor.splitNum(pricein.html()) + '<span class="com">,-</span>');
	})

	// pricein.html(pricein.html().replace(".0", ",-"));

	$(".child", "#side").hide();

	this.debounce = false;

	$("li", "#side").click(function() {

		if (cursor.debounce == true)
			return;

		if ($(this).children().filter(":hidden").length) {
			$(this).children().first().show('normal');
		} else {

			if ($('li', this).size() > 0)
				$(this).children().first().hide('normal');
		}

		cursor.debounce = true;
		window.setTimeout(function() {
			cursor.debounce = false
		}, 300);

	})

	$("#linkto" + greenmarkt.current_group_id).addClass("selected").parents().show();

	$(".addtocart").click(function() {
		var item = $(this);

		var options = {
			item_id : item.attr("cid"),
			// price : item.attr("price") * 1,
			quantity : $("#quant" + item.attr("cid")).val()
		}
		cursor.cartAction(options);
		return false;
	})

	$(".money").each(function() {
		var item = $(this);
		item.html(cursor.splitNum(item.html()));
	})

	$("#openLoginForm").click(function() {
		cursor.askLogin(function() {
			document.location.reload();
		});
		return false;
	})

	$('#user_logout').click(function() {
		$.postExt("/user/logout", null, function(data, status) {
			document.location.reload();
		});
		return false;
	})

	$('#remind_password').click(function() {

		cursor.remindPassword();
		return false;
	})

	$('#toppanelbuttons').toggle(function() {
		$('#toppanelinfo').animate({
			top : 0
		});
	}, function() {
		$('#toppanelinfo').animate({
			top : -117
		});
	})

	cursor.cartAction();
}

shop.prototype.renderGroup = function() {
	var cursor = this;
	$(".numeric").each(function() {
		var item = $(this);
		item.numeric({
			min : 1,
			val : 1,
			max : item.attr("max")
		})
	})

	$(".group_item_content").hover(function() {
		$(this).addClass('hover')
	}, function() {
		$(this).removeClass('hover')
	});

}

shop.prototype.renderItem = function() {
	var cursor = this;

	var item = $(".numeric");

	var allow = Boolean(item.data('allow'));
	if (allow) {
		item.numeric({
			min : 1,
			val : 1
		});

	} else {
		item.numeric({
			min : 1,
			val : 1,
			max : item.data("max")
		}, function() {
			alert("В наличии только " + item.data("max") + " шт.");
		});
	}

}

$.extend({
	postExt : function(url, params, callback, ignore_messages) {
		$.post(url, params, function(msg) {
			if (msg == null)
				alertError("Непредвиденная ошибка");
			else if (ignore_messages || msg.status > 0) {
				if (typeof callback == 'function')
					callback.call(this, msg.data, msg.status);
			} else {
				alertError(msg.data);
			}
		}, 'json').complete(function(msg) {
			if (msg.status != 200)
				alertError(msg.responseText);
		});
	}
});

function alertError(data) {
	$.msgbox(data, {
		type : 'error',
		buttons : [ {
			type : 'submit',
			value : 'ОК'
		} ]
	})
}

function alertInfo(data) {
	$.msgbox(data, {
		type : 'info',
		buttons : [ {
			type : 'submit',
			value : 'ОК'
		} ]
	})
}
function log(data) {
	if (typeof console != "undefined")
		console.log(data);
}

function info(data) {
	if (typeof console != "undefined")
		console.info(data);
}

function error(data) {
	if (typeof console != "undefined")
		console.error(data);
}

String.prototype.startsWith = function(str) {
	return (this.indexOf(str) === 0);
}

