/**
 * Update cart's items quantity
 * 
 * @param integer qty
 */
function updateCartTotalQty(qty) {
    $('#cartTotalQty').html('(' + qty + ')');
}

/**
 * Update item's quantity
 * 
 * @param eItem Item to update
 * @param integer qty
 */
function updateItemQty(eItem, qty) {
    var eItemQty  = $('.qty',  $(eItem));      /* элемент с количеством товара */
    eItemQty.html(qty);
}

/**
 * Update item's cost
 * 
 * @param eItem Item to update
 * @param integer cost
 */
function updateItemCost(eItem, cost) {
    var eItemCost = $('.cost', $(eItem));      /* элемент c общей стоимостью товара */
    eItemCost.html(cost).format({format:"#,###", locale:"ru"});
}

/**
 * Update item's removability
 * 
 * @param eItem Item to update
 */
function updateItemRemovability(eItem) {
    var itemQty = parseInt($('.qty', $(eItem)).text());  /* количество товара в корзине */
    
    if (itemQty == 0) {
        eItem.addClass('notChecked');
        $('div.remove', eItem).hide('slow');
    } else {
        eItem.removeClass('notChecked');
        $('div.remove', eItem).show('slow');
    }
}

/**
 * Update cart's items cost
 * 
 * @param integer value Value to be added/substracted to/from ammount
 */
function updateCheckoutAmount(value) {
    var eTotalCost = $('.checkout .price .amount'); /* элемент с общей стоимостью товаров */
    var oldTotalCost = parseInt(eTotalCost.text().split(' ').join(''));
    eTotalCost.html(oldTotalCost + value);
    eTotalCost.format({format:"#,###", locale:"ru"});
}

/**
 * Update all necessary DOM elements with the data provided
 * 
 * @param object eItem Item to update
 * @param array data JSON response
 * @param bool substract To substract?
 */
function updateDom(eItem, data, substract) {
    if (data.error) {
        return false;
    }
    
    updateCartTotalQty(data.totalQty);
    
    var itemPrice = parseInt(data.price); /* цена данного товара */
    var itemQty = parseInt(data.qty);     /* количество данного товара в корзине */
    var itemCost  = itemPrice * itemQty;  /* общая стоимость данного товара в корзине */
    
    onCartPage = $('body.cart').length > 0;
    
    if (onCartPage) {
        updateItemQty(eItem, itemQty);
        updateItemCost(eItem, itemCost);
        updateItemRemovability(eItem);
        updateCheckoutAmount(substract ? -itemPrice : itemPrice);
    }
    return true;
}

/**
 * Add an item into the Cart
 * 
 * @param string me Element that invoked action
 */
function cartAdd(me) {
    var eItem = $(me).parents('.item'); /* элемент с товарной позицией */
	$.post('/cart/add', {id: eItem.attr('name')}, function(data){ 
	    if (updateDom(eItem, data)) {
	        var destination = ($('div.checkout').length > 0 ? $('div.checkout') : $('#panel .cart'));
	        $.add2cart(eItem, destination);
	    }
	}, 'json');
}

/**
 * Remove an item from the Cart
 * 
 * @param string me Element that invoked action
 * @param bool all Remove all items
 */
function cartRemove(me, all) {
    if (all == undefined) all = false;
    var eItem = $(me).parents('.item'); /* элемент с товарной позицией */
	$.post('/cart/remove', {'id': eItem.attr('name'), 'all': all}, function(data){
	    updateDom(eItem, data, true);
        var source = ($('div.checkout').length > 0 ? $('div.checkout') : $('#panel .cart'));
        $.add2cart(source, $('div#footer'));
	}, 'json');
}

/**
 * Search items by id or title
 * 
 * @param string text
 */
function search(text) {
	text = $.trim(text);
	document.location.href = '/search/' + jQuery.trim(text);
}

$(document).ready(function(){
	
	$('#searchBtn').click(function(){
		text = $('#searchField').attr('value');
		search(text);
	});
	
	$('#searchForm').submit(function(){
		text = $('#searchField').attr('value');
		search(text);
		// to prevent browser submit
		return false;
	});
	
	/*
	$('#orderPageForm').submit(function(){
		if (jQuery.trim($('#orderPagePhoneField').attr('value')) == '') {
			alert('Пожалуйста, введите Ваш телефон или email.');
			// to prevent browser submit
			return false;
		}
	});
	*/
	
	$('#searchPageFormBtn').click(function(){
		text = $('#searchPageFormField').attr('value');
		search(text);
	});
	
	$('#searchPageForm').submit(function(){
		text = $('#searchPageFormField').attr('value');
		search(text);
		// to prevent browser submit
		return false;
	});
	
});

/**
 * Send order
 */
function makeOrder() {
	$.getJSON('/cart/order', function(data){
		alert(data);
	});
}