Number.prototype.formatMoney = function() {
	var num = this;
	var str = num.toFixed(2).toString();
	return str.replace('.', ',');
};


$(document).ready(function() {
	$("input[type=checkbox]").fadeTo(0,0);

	$("input[type=checkbox]").mouseover(function(){
		$(this).parent("span").css("background-position", "0 -21px");
	});


	$("input[type=checkbox]").click(
		function() {
			if($(this).is(':checked')){
				$(this).parent("span").css("background-position", "0 -42px");
			} else {
				$(this).parent("span").css("background-position", "0 0");
			}
		});


	$("input[type=checkbox]").mouseout(
		function(){
			if($(this).is(':checked'))
			{
				$(this).parent("span").css("background-position", "0 -42px");
			}
			else {
				$(this).parent("span").css("background-position", "0 0");
			}
		});

	$(".rozwin").click(
		function()
		{
			if($(".shopping-cart-container").css("display")=="none")
			{
				$(".shopping-cart-container").slideDown(400);
				$(".rozwin").css("background-position", "0 -100px");
				$(".rozwin").attr("title", "zwiń");
			}
			else
			{
				$(".shopping-cart-container").slideUp(400);
				$(".rozwin").css("background-position", "-88px -100px");
				$(".rozwin").attr("title", "rozwiń");
			}
		});


	$(".sliding-button").click(
		function()
		{
			$(".slider").slideUp(400);
			$(".sliding-button").each(
				function(){
					$(this).css("background-position", "-111px -99px");
					$(this).attr("title", "rozwiń");
				});
            

			if($(this).parent().siblings(".slider").css("display")=="none")
			{
				$(this).parent().siblings(".slider").slideDown(400);
				$(this).css("background-position", "0 -100px");
				$(this).attr("title", "zwiń");
			}
			else
			{
				$(this).parent().siblings(".slider").slideUp(400);
				$(this).css("background-position", "-111px -99px");
				$(this).attr("title", "rozwiń");
			}
		});

	$(".sliding-container .header").click(
		function()
		{
			$(".slider").slideUp(400);
			$(".sliding-button").each(
				function(){
					$(this).css("background-position", "-111px -99px");
					$(this).attr("title", "rozwiń");
				});


			if($(this).siblings(".slider").css("display")=="none")
			{
				$(this).siblings(".slider").slideDown(400);
				$(this).siblings(".header-right").children(".sliding-button").css("background-position", "0 -100px");
				$(this).siblings(".header-right").children(".sliding-button").attr("title", "zwiń");
			}
			else
			{
				$(this).parent().siblings(".slider").slideUp(400);
				$(this).siblings(".header-right").children(".sliding-button").css("background-position", "-111px -99px");
				$(this).siblings(".header-right").children(".sliding-button").attr("title", "rozwiń");
			}
		});

	$("form fieldset.choose-status input[type=radio]").click(
		function()
		{
			if($(this).val()==1)
			{
				$(this).parent().parent().children("fieldset.data").children(".company").css("display", "none");
			}
			else
			{
				$(this).parent().parent().children("fieldset.data").children(".company").css("display", "block");    
			}
		});

	$('a.do-koszyka').click(function(e) {
		var url = $(this).attr('href');
		$.get(url+'.json', function(data, textStatus, req) {
			data = JSON.parse(data);
			if(data.status == 0) {
				updateCartBox(1);
				alert('Dodano do koszyka');
			}
			else alert('Nie udało się dodać produktu do koszyka');
		},'json');
		return false;
	});
    
	$('a.delete-item').click(function(e) {
		var url = $(this).attr('href');
		var node = $(this).parent();
		$.get(url+'.json', function(data, textStatus, req) {
			data = JSON.parse(data);

			if(data.status == 0) {
				alert('Usunięto z koszyka');
				node.remove();
				calculatePrice($('#shoppingCart'), $('#cartOverallValue').children('span.value'));
				updateCartBox(-1);
			} else alert('Nie udało się dodać produktu do koszyka');
		},'json');
		return false;
	});

	$('#shoppingCart input.quantity').bind('change', function(e) {
		var form = $(this.form);
		var url = form.attr('action') + '.json';
		$.post(url, form.serialize(), function(data, textStatus, req) {
			data = JSON.parse(data);
			if(data.status == 0) {
				calculatePrice($('#shoppingCart'), $('#cartOverallValue').children('span.value'));
			}
		});
	});

	function updateCartBox(amount) {
		var node = $('#productsNumber');
		var str = node.html();
		var current = parseInt(str.substr(1, str.length));
		current += amount;
		node.html('('+current+')');
	}

	function calculatePrice(cart, target) {
		var price = 0;
		cart.children('li').each(function(index, o) {
			var itemPrice = parseFloat($(o).children('div.price').children('span.value').html().replace(',', '.'));
			var amount = parseInt($(o).find('input.quantity').val());
			price += itemPrice * amount;
		});

		target.html(price.formatMoney());
	}

	function calculateShipmentPrice(shipment, target) {
		var shipmentPrice = parseFloat(shipment.html().replace(',', '.'));

		target.html(shipmentPrice.formatMoney());
	}

	function updateOverallPrice(products, shipment, target) {
		var productsPrice = parseFloat(products.html().replace(',', '.'));
		var shipmentPrice = parseFloat(shipment.html().replace(',', '.'));
		var overall = productsPrice + shipmentPrice;
		target.html(overall.formatMoney());
	}

	calculatePrice($('#shoppingCart'), $('#cartOverallValue').children('span.value'));
	calculatePrice($('#shoppingCartOrder'), $('#productsPrice').children('div').children('span.value'));

	$('fieldset.shipping input[type=radio]').click(function(e) {
		calculateShipmentPrice($(this).next().next().children('div.value'), $('#shipmentPrice').children('div').children('span.value'));
		updateOverallPrice($('#productsPrice').children('div').children('span.value'), $('#shipmentPrice').children('div').children('span.value'),
			$('#overallPrice').children('span.value'));
	});
    
	$('form#finalize input[name="pay_type"]').click(function(e) {
		$('#payment-2').attr('checked', 'checked');
	});
    
	setPagerMargin();

	var popularTagsBox = $('#popularTagsBox');
	if(popularTagsBox.length > 0) {
		$.get('/productTags/index', function(data) {
			popularTagsBox.html(data);
		});
	}

	var recommendationBox = $('#recommendationBox');
	if(recommendationBox.length > 0) {
		$.get('/advertisement/index', function(data) {
			recommendationBox.html(data);
		});
	}
	
    var reviewsProductID = $('#reviewsProductID');
	if(reviewsProductID.length > 0) {
		var id = reviewsProductID.val();
        $.get('/productReview/index/product/'+id, function(data) {
			reviewsProductID.replaceWith(data);
		});
	}
    
    $('#reviewAddForm').submit(function(e) {
        var url = $(this).attr('action') + '.json';
        $.post(url, $(this).serialize(), function(data, textStatus, req) { 
            Recaptcha.reload();
            data = JSON.parse(data);
            if(data.status == 0) {
                var reviewList = $('#reviews');
                var template = $('#reviewTemplate');
                var node = template.html();
                node = node.replace("%author%", data.product_review.author);
                node = node.replace("%content%", data.product_review.content);
                reviewList.children('li.no-reviews').remove();
                $('#reviews').prepend(node);
                alert('Opinia została dodana.');
            } else {
                alert('Nie udało się dodać opinii');
            }
        });
        return false;
    });

	var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome')

	if(is_chrome > -1)
	{
		$("form.registration-form label").each(
			function()
			{
				if($(this).attr("for")=="name")
				{
					$(this).css("line-height", "36px");
				}
			});
	}
});

function setPagerMargin()
{
	counter = $("div.pager > a").size();

	blocksWidth = (counter-1)*10;

	$("div.pager a").each(
		function()
		{
			blocksWidth += ($(this).width()+18);
		});
	marginValue = ($(".content").width()-blocksWidth)/2;
	$("div.pager a:first-child").css("margin-left", marginValue+"px");

}

function hidePayments(e, availablePayments) {
    var payments = [1, 2, 3];
    if(e.currentTarget.checked) {
        for(var i=1;i<=3;i++) {
            if(availablePayments.indexOf(i) == -1) {
                $('input#payment-'+ i).parent('div').hide();
            } else {
                $('input#payment-'+ i).parent('div').show();
            }
        }
    }
}


