String.prototype.space1k = function() {
	var reversed = '', nums = 1;
	var string = this.toString().replace(/[^0-9]/g, '');
	
	for (var i = string.length - 1; i >= 0; i--) {
		if (nums == 4) {
			reversed = ' ' + reversed;
			nums = 1;
		}
		
		reversed = string.substr(i, 1) + reversed;
		nums++;
	}
	
	return reversed;
};

Number.prototype.space1k = function() {
	return this.toString().space1k();
};

$(document).ready(function(){
	/*$('.ajaxform').each(function () {
		var form = $(this);
		var options = {
			dataType: 'json',
			semantic: true,
			url: (form.attr('action') || '') + ((form.attr('action') && form.attr('action').indexOf('?') >= 0) ? '&' : '?') + 'format=js',
			//beforeSubmit: showProcess,
			success: processJson,
			//complete: hideProcess
		}
		form.ajaxForm(options);
	});*/
	
	$(".navigation li[class!=active]").hover(
		function () {
			$(this).addClass("active");
		},
		function () {
			$(this).removeClass("active");
		}
	);
	
	$(".price a.cart").click( function() {
		$(".price .hint").remove();
		$("#hint").clone().insertBefore($(this)).show(); 
		var oCurrentLink = $(this);
		$.ajax({
			url: this.href,
			data: { "_mode": "js" },
			cache: false,
			dataType: 'json',
			success: function(data)
			{
				$("#cart-count").html(data.count);
				$("#cart-total").html(data.sum);
			}
		});
		 
		return false;
	});
	
	if(typeof(aDeliverys)!=='undefined')
	{
		$("input[id^='Order_delivery_id']").click( function() {
			//setDeliveryPrice($(this).attr('value') - 1);
			showHideAddress();
		});
		
		/*if(typeof($('#order_price').html()) !== 'undefined')
		{
			var iOrderPrice = parseInt($('#order_price').html());
			
			if(iOrderPrice > 0)
			{
				iPrice = iOrderPrice;
				iDistance = parseInt($('#order_price').attr('distance'));
				iDeliveryPrice = getDeliveryPrice(parseInt($('#order_price').attr('delivery_id')) - 1, iDistance);
				$('#order_price').html(iOrderPrice + iDeliveryPrice);
			}
		}*/

		//setDeliveryPrice($('#Order_delivery_id option:selected').attr('value') - 1);
		showHideAddress();
	}
	
	$('table.catalog td.count input').keyup( function() {
		recalculate();
		$('.ajaxform').each(function () {
			var form = $(this);
			var options = {
				dataType: 'json',
				semantic: true,
				data: {
					'recalculate': ''
				},
				url: (form.attr('action') || '') + ((form.attr('action') && form.attr('action').indexOf('?') >= 0) ? '&' : '?') + 'format=js'
				//beforeSubmit: showProcess,
				//success: processJson,
				//complete: hideProcess
			}
			form.ajaxForm(options);
		});
		
		$('.ajaxform').submit();
		
		$('.ajaxform').ajaxFormUnbind();
	});
	
	$('table.catalog td.cart a').click(function() {
		if(confirm('Вы действительно хотите удалить товар?'))
		{
			var link = $(this);
			$.ajax({
				async: true,
				cache: false,
				url: this.href + '.js',
				success: function() {
					link.parent().parent().remove();
					recalculate();
				}
			});
		}
		
		return false;
	});
});

function processJson(data, status, form) {
	cont = $(".message");
	cont.empty();
	$("*").removeClass("wrong");
	switch (data.code) {
		case "add":
			alert("WOW");
		break;
		case 200:
			cont.removeClass("error");
			cont.addClass("info");
			cont.append("<div class='title'>" + data.title + "</div>");
			cont.show("blind");
			if (data.clear_form) {
				form.resetForm();
			}
		break;
		case 201:
			window.location = data.url;
		break;
		case 500:
			cont.removeClass("info");
			cont.addClass("error");
			cont.append("<div class='title'>" + data.title + "</div>");
			cont.show("blind");
			$.each(data.errors, function(i, err) {
				form.find("#" + err.field).parent().addClass("wrong");
				$.each(err.msgs, function(i, msg) {
					cont.append("<div>" + msg + "</div>");
				});
			});
		break;
		default:
			alert("Uncknown error!");
	}
}

function recalculate()
{
	var iValue = 0;
	var iCount = 0;
	
	$('tr', 'table.catalog').each(function() {
		if(typeof($('input', this).val()) == 'undefined')
		{
			return;
		}
		
		var iInputValue = parseInt($('input', this).val().toString().replace(/[^0-9]/g, ''));
		
		if(iInputValue < 0 || isNaN(iInputValue))
		{
			iInputValue = 0;
		}
		
		iCount += iInputValue;
		
		$('input', this).val(iInputValue);
		var iCost = parseInt($('.cost span', this).text().toString().replace(/[^0-9]/g, ''));
		
		if(!isNaN(iCost))
		{
			$('.price span', this).text((iInputValue * iCost).space1k());
			iValue += iInputValue * iCost;
		}
	});
	
	$("#cart-count").html(iCount);
	$("#cart-total").html(iValue);
	
	$('#total span').text(iValue.space1k());
	window.iPrice = iValue;
	//setDeliveryPrice($('#Order_delivery_id option:selected').attr('value') - 1);
}

function showHideAddress()
{
	if($("input[id^='Order_delivery_id']:checked").attr('value') == 1)
	{
		$('#address').hide();
	}
	else
	{
		$('#address').show();
	}
}

function setDeliveryPrice(iSelectedDeliveryNum)
{
	if(isNaN(iSelectedDeliveryNum))
	{
		return;
	}
	
	var text = 'Стоимость доставки ';
	var iDistance = 0;
	
	if(aDeliverys[iSelectedDeliveryNum]['is_distance'])
	{
		$('#delivery_distance').show();
		$('#Order_distance').removeAttr('disabled');
		
		iDistance = getDistance();
	}
	else
	{
		$('#Order_distance').attr('disabled', 'disabled');
		$('#delivery_distance').hide();
	}
	
	var iDeliveryPrice = getDeliveryPrice(iSelectedDeliveryNum, iDistance);
	
	text += '<span>' + iDeliveryPrice + '</span> руб';
	
	$('#DeliveryPrice').html(text);
}

function getDistance()
{	
	iDistance = parseInt($('#Order_distance').attr('value'));
	
	if(iDistance < 0 || isNaN(iDistance))
	{
		iDistance = 0;
	}
	
	$('#Order_distance').attr('value', iDistance);
	return iDistance;
}

function getDeliveryPrice(iSelectedDeliveryNum, iDistance)
{
	iDistance = typeof(iDistance) != 'undefined' ? iDistance : 0;
	var iDeliveryPrice = 0;
	
	if(aDeliverys[iSelectedDeliveryNum]['is_threshold'])
	{
		if(iPrice < aDeliverys[iSelectedDeliveryNum]['threshold_sum'])
		{
			iDeliveryPrice = parseInt(aDeliverys[iSelectedDeliveryNum]['cost1']);
		}
		else
		{
			iDeliveryPrice = parseInt(aDeliverys[iSelectedDeliveryNum]['cost2']);
		}
	}
	else
	{
		iDeliveryPrice = parseInt(aDeliverys[iSelectedDeliveryNum]['cost']);
	}
	
	if(aDeliverys[iSelectedDeliveryNum]['is_distance'])
	{
		if(aDeliverys[iSelectedDeliveryNum]['is_threshold'])
		{
			iDeliveryPrice += parseInt(aDeliverys[iSelectedDeliveryNum]['cost'] * iDistance);
		}
		else
		{
			iDeliveryPrice *= parseInt(iDistance);
		}
	}
	
	return iDeliveryPrice;
}
