$(document).ready(function() {
	totalQuantity = 0;
	totalPrice = 0;
	deliveryPrice = 5;
	discountValue = 0;
	discountPercent = 0;
	discountFixed = 0;

	$('#order-details .ss-q-short').keydown(
		function(event) {
			if (event.keyCode == 13) return false;
			return true;
		});

	$('#order-details #entry_3').keyup(
		function() {
			calculateDeliveryPrice();
			calculatePriceToPay();
		});

	cart = $.namesession.get('cart', new cart());

	populateOrderDetails();
	populatePrices();

	populateCart();
	calculateDeliveryPrice();
	populateDiscount();
	calculatePriceToPay();
});

function populatePrices()
{
	var prices = $('meta[name=prices]').attr("content");

	$.getJSON(prices + '?alt=json-in-script&callback=?',
		function (data) {
		    $.each(data.feed.entry, function (i, entry) {
		        var sku = entry['gsx$код'].$t;
			var price = globalize(entry['gsx$цена'].$t);
		        var category = entry['gsx$категория'].$t;
		        var name = entry['gsx$име'].$t;
		        $('#price-' + sku).text(localize(price));
		        $('#add-' + sku).click(function () {
		            addProduct(sku, name, category, price);
					return false;
		        });
		        $('#add-' + sku).attr('title', name);
		        $('#remove-' + sku).click(function () {
		            removeProduct(sku);
					return false;
		        });
		        $('#remove-' + sku).attr('title', name);
		    });
		});
}

function cart() {
    this.products = [];
}

function product(sku, productName, productCategory, unitPrice, quantity) {
    this.sku = sku;
    this.productName = productName;
    this.productCategory = productCategory;
    this.unitPrice = unitPrice;
    this.quantity = quantity;
}

function populateCart() {
    totalQuantity = 0;
    totalPrice = 0;
    for (i = 0; i < cart.products.length; i++) {
        var productQuantityElement = $('#quantity-' + cart.products[i].sku);
        var productTotalValueElement = $('#total-value-' + cart.products[i].sku);
        productQuantityElement.text(cart.products[i].quantity);
        productQuantityElement.show();
        totalQuantity += cart.products[i].quantity;
        var productPrice = cart.products[i].quantity * cart.products[i].unitPrice;
        totalPrice += productPrice;
		productTotalValueElement.text(localize(productPrice));
    }
    $('#total-quantity').text(totalQuantity);
    $('#total-price, .total-price').text(localize(totalPrice));
	$('#order-details #entry_7').val(localize(totalPrice));
}

function populateOrderDetails() {
	if (cart.products.length > 0) {
		var orderList = $('#order-list');
		if (orderList.length) {
			var orderListHtml = '<ol>';
			var orderText = '';
			for (i = 0; i < cart.products.length; i++) {
				var productPrice = cart.products[i].quantity * cart.products[i].unitPrice;
				var sku = cart.products[i].sku;
				var productName = cart.products[i].productName;
				orderListHtml += '<li id="order-product-';
				orderListHtml += sku;
				orderListHtml += '"><span class="item">'
				orderListHtml += productName;
				orderListHtml += '</span><span class="basket"><a id="quantity-';
				orderListHtml += sku;
				orderListHtml += '" class="product-quantity"></a><a id="remove-';
				orderListHtml += sku
				orderListHtml += '" class="button"';
				orderListHtml += ' title="';
				orderListHtml += productName;
				orderListHtml += ' href="#"><span class="button-cart">Извади от</span></a><span class="price">Цена: <span id="total-value-';
				orderListHtml += sku;
				orderListHtml += '">';
				orderListHtml += localize(productPrice);
				orderListHtml += '</span>лв</span></span><span class="clear-both"></span></li>';
				orderText += cart.products[i].quantity + 'x ' + sku + ' ' + productName + ', ' + localize(cart.products[i].unitPrice) + 'лв = ' + localize(productPrice) + 'лв\n';
			}
			orderListHtml += '</ol>';
			orderList.html(orderListHtml);
			$('#entry_6').val(orderText);
		}

		if(typeof geoplugin_city == 'function') {
			var geolocation = geoplugin_city();
			for (i = 0; i < cities.length; i++) {
				if (cities[i].en == geolocation) {
					$('#order-details #entry_3').val(cities[i].bg);
					break;
				}
			}
		}
	}
	else {
		$('#order-wrapper').hide();
	}
}

function emptyCart()
{
	cart.products = [];
    totalQuantity = 0;
    totalPrice = 0;
 	var orderText = '';

	$('#order-details #entry_6').val(orderText);
    $('#order-details #entry_7').val(localize(totalPrice));
	$('#total-quantity').text(totalQuantity);
    $('#total-price, .total-price').text(localize(totalPrice));
	$('#order-wrapper').hide();
    $.namesession.set('cart', cart);

	calculateDiscount();
	calculatePriceToPay();;
}

function removeProduct(sku) {
	totalQuantity = 0;
	totalPrice = 0;
	var orderText = '';
	var productQuantityElement = $('#quantity-' + sku);
	var productTotalValueElement = $('#total-value-' + sku);
	for (i = 0; i < cart.products.length; i++) {
		var productPrice = cart.products[i].quantity * cart.products[i].unitPrice;
        totalQuantity += cart.products[i].quantity;
        totalPrice += cart.products[i].quantity * cart.products[i].unitPrice;
        var productName = cart.products[i].productName;
        if (cart.products[i].sku == sku) {
			totalQuantity -= 1;
			totalPrice -= cart.products[i].unitPrice;
			if (cart.products[i].quantity > 1) {
				cart.products[i].quantity -= 1;
				productPrice = cart.products[i].quantity * cart.products[i].unitPrice;
				productQuantityElement.text(cart.products[i].quantity);
				productTotalValueElement.text(localize(productPrice));
				orderText += cart.products[i].quantity + 'x ' + cart.products[i].sku + ' ' + cart.products[i].productName + ', ' + localize(cart.products[i].unitPrice) + 'лв = ' + localize(productPrice) + 'лв\n';
			}
			else {
				cart.products.splice(i--, 1);
				productQuantityElement.text(0);
				productTotalValueElement.text(0);
				if (!productQuantityElement.hasClass('visible')) {
					productQuantityElement.hide();
				}
				var orderProductElement = $('#order-product-' + sku);
				orderProductElement.remove();
			}
			_gaq.push(['_trackEvent', 'Количка', 'Изваждане на продукт', productName]);
		}
		else {
			orderText += cart.products[i].quantity + 'x ' + cart.products[i].sku + ' ' + cart.products[i].productName + ', ' + localize(cart.products[i].unitPrice) + 'лв = ' + localize(productPrice) + 'лв\n';
		}
	}
	$('#order-details #entry_6').val(orderText);
    $('#order-details #entry_7').val(localize(totalPrice));
	$('#total-quantity').text(totalQuantity);
    $('#total-price, .total-price').text(localize(totalPrice));
	if(cart.products.length == 0) $('#order-wrapper').hide();
    $.namesession.set('cart', cart);

	calculateDeliveryPrice();
	calculateDiscount();
	calculatePriceToPay();
}

function addProduct(sku, productName, productCategory, unitPrice) {
	var isNewProduct = true;
	totalQuantity = 0;
	totalPrice = 0;
	var quantity = 1;
	var productQuantityElement = $('#quantity-' + sku);
	var productTotalValueElement = $('#total-value-' + sku);
 	var orderText = '';
    for (i = 0; i < cart.products.length; i++) {
		var productPrice = cart.products[i].quantity * cart.products[i].unitPrice;
        if (cart.products[i].sku == sku) {
            cart.products[i].quantity += quantity;
			productPrice = cart.products[i].quantity * cart.products[i].unitPrice;
            isNewProduct = false;
			productQuantityElement.text(cart.products[i].quantity);
			productTotalValueElement.text(localize(productPrice));
        }
        totalQuantity += cart.products[i].quantity;
        totalPrice += productPrice;
		orderText += cart.products[i].quantity + 'x ' + cart.products[i].sku + ' ' + cart.products[i].productName + ', ' + localize(cart.products[i].unitPrice) + 'лв = ' + localize(productPrice) + 'лв\n';
	}
	if (isNewProduct) {
		cart.products.push(new product(sku, productName, productCategory, unitPrice, quantity));
 		totalQuantity += quantity;
 		var productPrice = quantity * unitPrice
		totalPrice += productPrice;
		productQuantityElement.text(quantity);
		productTotalValueElement.text(localize(productPrice));
	}
	$('#order-details #entry_6').val(orderText);
	$('#order-details #entry_7').val(localize(totalPrice));
	productQuantityElement.show();
	$('#total-quantity').text(totalQuantity);
	$('#total-price, .total-price').text(localize(totalPrice));
	$.namesession.set('cart', cart);

	calculateDeliveryPrice();
	calculateDiscount();
	calculatePriceToPay();

	_gaq.push(['_trackEvent', 'Количка', 'Добавяне на продукт', productName]);
}

function calculateDeliveryPrice() {
	if (totalPrice < 20) {
		deliveryPrice = 9;
	} 
	else if (totalPrice >= 20 && totalPrice < 50) {
		deliveryPrice = 5;
	}
	else {
		deliveryPrice = 0;
	}
	$('#delivery-price').text(localize(deliveryPrice));
	$('#order-details #entry_8').val(localize(deliveryPrice));
}

function populateDiscount() {
	discountValue = 0;
	discountPercent = 0;
	discountFixed = 0;
	discountMinProducts = 0;
	discountMinPrice = 0;
	discountValidFrom = new Date();
	discountValidFrom.setDate(discountValidFrom.getDate() - 1);
	discountValidUntil = new Date();
	discountValidUntil.setDate(discountValidUntil.getDate() + 1);

	var discountCode = $('#order-details #entry_5').val();
	$('#discount-value').text(0);

	calculateDiscount();
	calculatePriceToPay();

	if (discountCode) {
		$('#order-details #entry_9').val('···');
		$('#loading-discount').show();

		var discountUrl = '/discount/' + discountCode.toLowerCase() + '.js';
		$.getJSON(discountUrl, function(data) {
			isDiscount = true;
			if (data.percent) discountPercent = data.percent;
			if (data.fixed)	discountFixed = data.fixed;
			if (data.minProducts) discountMinProducts = data.minProducts;
			if (data.minPrice) discountMinPrice = data.minPrice;
			if (data.validFrom) discountValidFrom = new Date(data.validFrom);
			if (data.validUntil) discountValidUntil = new Date(data.validUntil);

			$('#discount').text(data.discount);
			$('#loading-discount').hide();

			calculateDiscount();
			calculatePriceToPay();
			_gaq.push(['_trackEvent', 'Отстъпка', 'Калкулиане на отстъпка', data.discount]);
		});
		_gaq.push(['_trackEvent', 'Отстъпка', 'Проверка на код за отстъпка', discountCode]);
	}
	else
	{
		$('#order-details #entry_9').val('Няма');
		$('#loading-discount').hide();
	}
	timeout = setTimeout(function() {
				$('#loading-discount').hide();
				if (discountValue == 0) $('#discount').text('Няма');
			}, 3000);
}

function calculateDiscount()
{
	var today = new Date();
	if (cart.products.length < discountMinProducts || totalPrice < discountMinPrice || today < discountValidFrom || today > discountValidUntil) discountValue = 0;
	else discountValue = totalPrice * discountPercent / 100 + discountFixed;
	if (discountValue <= totalPrice + deliveryPrice) {
		$('#discount-value').text(localize(0 - discountValue));
		$('#order-details #entry_9').val(discountPercent + '% + ' + localize(discountFixed) + 'лв = ' + localize(discountValue) + 'лв');
	}
}

function calculatePriceToPay() {
	priceToPay = totalPrice + deliveryPrice - discountValue;
	$('#order-details #entry_10').val(localize(priceToPay));
	$('#price-to-pay').text(localize(priceToPay));
}

function trackTransaction() {
	if ($('#entry_11').val() == 'test') return;

	var city = $('#order-details #entry_3').val();
	if (city) {
		city = city.toLowerCase();
		var cityEn = '';
		for (i = 0; i < cities.length; i++) {
			if (cities[i].bg.toLowerCase() == city)
			{
				cityEn = cities[i].en;
				break;
			}
		}
	}

	var phone = $('#order-details #entry_1').val().replace(/[^\d]+/g, '');
	if (phone.charAt(0) == '0') $('#order-details #entry_1').val('359' + phone.substring(1));
	var date = new Date();
	date.setHours(0);
	date.setMinutes(0);
	date.setSeconds(0);
	date.setMilliseconds(0);
	var ordinalDay = Math.ceil((date - new Date(date.getFullYear(), 0, 1)) / 86400000) + 1;
	var shortYear = date.getFullYear().toString().slice(2);
	var orderId = shortYear + '-' + ordinalDay + '-' + phone;

	var discountCode = $('#order-details #entry_5').val();
	if (discountCode) discountCode.toLowerCase();
	else discountCode = 'boribel';

	var tax = priceToPay - priceToPay / 1.2;

	_gaq.push(['_addTrans',
		orderId, // order ID - required
		discountCode, // affiliation or store name
		Math.round((priceToPay / 1.95) * 100) / 100, // total - required
		Math.round((tax / 1.95) * 100) / 100, // tax
		Math.round((deliveryPrice / 1.95) * 100) / 100, // shipping
		cityEn, // city
		'', // state or province
		'Bulgaria' // country
	]);
    for (i = 0; i < cart.products.length; i++) {
		var product = cart.products[i];
		_gaq.push(['_addItem',
			orderId, // order ID - required
			product.sku, // SKU/code
			product.productName, // product name
			product.productCategory, // category or variation
			Math.round((product.unitPrice / 1.95) * 100) / 100, // unit price - required
			product.quantity // quantity - required
		]);
	}
	_gaq.push(['_trackTrans']);
}

function localize(number) {
	if (!number.toFixed) number = parseFloat(number);
	if (Math.round(number) != number) {
		return number.toFixed(2).replace('.', ',');
	}
	else {
		return number;
	}
}

function globalize(data)
{
	return parseFloat(data.replace(',', '.'));
}

