Madtea = {
    show_error: function (msg) {
        msgbox = $('<div class="js_error_box">' + msg + '</div>');
        $(document.body).append(msgbox);
        msgbox.click(function(){$(this).hide()});
        setTimeout(function(){msgbox.hide()}, 3000);
    },

    russian_pluralize: function(value, form1, form2, form5) {
	    n = value
	
	    n = Math.abs(n) % 100;
	    n1 = n % 10;
	
	    if (n > 10 && n < 20)
	       return form5
	    if (n1 > 1 && n1 < 5)
	       return form2
	    if (n1 == 1)
	       return form1
	    return form5
    },
    
    CartSmall: {
        setTotal: function (total) {
            totalBlock = $('#cartSmall .total');
            if (totalBlock.length != 0) {
                totalBlock.text(total);
            
	            var total = parseInt(($('#cartSmall .total').text().replace(/[^0-9]*/, '')));
	            var threshold = parseInt($('#cartSmall .threshold').text().replace(/[^0-9]*/, ''));
	            if (total > threshold) {
	            	$('#cartSmall .threshold').hide();
	            	$('#cartSmall a.order').show();
	            }
            }
        },

        isEmpty: function() {
            return $('#cartSmall').length == 0;
        },

        addItem: function (data) {
            if (Madtea.CartSmall.isEmpty()) {
                window.location = window.location;
                return;
            }
            var countBlock = $('#cartSmall .count');
            var count = parseInt($('span', countBlock).text());
            count += 1;
            countBlock.html('<span>' + count + '</span>' + ' ' + Madtea.russian_pluralize(count, 'упаковка', 'упаковки', 'упаковок') + ' чая');
            //item = '<li>'+ data.fields.product.fields.name + ', '+ data.fields.weight + '&nbsp;гр.</li>';
            //$('#cartSmall .items').append(item);
        }
    },

    Cart: {
        addRemoveClick: function(event) {
            var action = $(this).hasClass('add') ? 'add' : 'remove';
            var input = $('input', $(this).parent());
            var prCode = input.attr('id').split('_')
            var id = prCode[1];
            var weight = prCode[2];

            $.post('/cart/action/' + action + '/' + id + '/', {'weight': weight}, function(data) {
                response = eval('[' + data + ']')[0]
                if (response['status'] != '200') {
                    Madtea.show_error(response['error']);
                } else {
                    Madtea.Cart.setTotal(response.total);
                    if (response.cart_item[0] != null) {
                        Madtea.Cart.updateItem(response.cart_item[0]);
                    } else {
                        Madtea.Cart.removeItem(id, weight);
                    }
                }
            });
        },

        updateItem: function(data) {
            var item = $('.js_cart #i_' + data.fields.product.pk + '_' + data.fields.weight);
            $('.quantity input', item).val(data.fields.quantity);
            $('.price .number', item).text(data.extras.price);
        },

        removeItem: function(id, weight) {
            //reload page if cart empty
            if ($('.js_cart .items tr').length < 4) {
                window.location.href = window.location.href;
            }

            var row = $('.js_cart #i_' + id + '_' + weight);
            row.highlightFade({speed: 'slow', complete: function(){row.remove()}});
        },

        setTotal: function(total) {
            $('.js_cart .price.total span.number').text(total);
            if (total > this.threshold) {
                this.thresholdRow.fadeOut('fast');
                this.nextButton.removeAttr('disabled');
            } else {
                this.thresholdRow.show();
                this.nextButton.attr('disabled', 'disabled');
            }
        },

        init: function() {
            $('.js_cart .quantity a').click(Madtea.Cart.addRemoveClick);
            $('.js_cart input.back').click(function() { document.location = '/' });
            this.threshold = parseInt($('#threshold').text());
            this.thresholdRow = $('.js_cart .threshold');
            this.nextButton = $('.js_cart .buttons .next.button');
        }
    },
    OrderForm: {
        init: function() {
            $('.js_order input.back').click(function(){document.location = '/cart/'});
        }
    }

}

$(document).ready(function(){
    $('.js_weight').click(function() {
       var id = this.id
       id = id.substring(id.lastIndexOf('-') + 1);
       $('#price_'+id ).text($(this).attr('price'))
    });
    $('.js_weight:checked').trigger('click');

    $('.js_buy').click(function(){
        var id = this.form.id        
        id = id.substring(id.lastIndexOf('_') + 1);
        $.post('/cart/action/add/' + id + '/', {'weight': $('.js_weight:checked').val()}, function(data) {
           response = eval('[' + data + ']')[0]
           if (response['status'] != '200') {
               Madtea.show_error(response['error']);
           } else {
               Madtea.CartSmall.addItem(response.cart_item[0]);
               Madtea.CartSmall.setTotal(response.total);
           }
        });
    });

    var login_dialog = $('<div id="dialog"></div>').hide();

	function close_login_dialog() {
		login_dialog.hide();
		login_dialog.empty()
		$(document).unbind('keypress');
		$(document).unbind('click');
	}

    function render_login_form(data) {
       login_dialog.html(data); 
	   form = login_dialog.find('form');
	   $('<span class="pseudo button close">X</span>').click(function () {close_login_dialog()}).appendTo(login_dialog);
	   $('<span class="pseudo button submit">Отправить</span>').click(function () {form.submit()}).appendTo(login_dialog);
       form.ajaxForm(function (new_data) {
            if (new_data == 'loginned')
                window.location.reload()
            else 
                render_login_form(new_data)
       });
    }
    
    $('#login_button').click(function(){
        $.ajax({
          url: '/login/',
          async: false,
          success: function(data) {
            render_login_form(data);
			$(document).keypress(function (event) {
				switch (event.keyCode) {
					case 27:
						close_login_dialog();
						break;
					case 13:
						login_dialog.find('form').submit();
				}
			});
			$(document).click(function (event) {
				ld_left = login_dialog.offset().left;
				ld_rigth = ld_left + login_dialog.width();
				ld_top = login_dialog.offset().top;
				ld_bottom = ld_top + login_dialog.height();
				if (event.pageX < ld_left || event.pageX > ld_rigth || event.pageY < ld_top || event.pageY > ld_bottom)
					close_login_dialog()
			});
            login_dialog.show();
          }
        });
        return false;
    });

	login_dialog.appendTo('body');

    Madtea.Cart.init();
});
