$(document).ready(function() {
    var baseUrl = $('script[@src$="media/js/site.js"]').attr('src').replace(/media\/js\/site\.js/, '');

    $('input.datepicker').datepicker();
    
    $('select#timeframe').bind('change', function(e) {
    	$('input.datepicker').val('');
    });
    
    $("table thead th input[@type='checkbox']").bind('change', function(e) {
		if (this.checked) {
			$(this).parent().parent().parent().parent().find("tbody input[@type='checkbox']").attr('checked', 'checked');
			$(this).parent().parent().parent().parent().find("tbody tr").removeClass('disabled');
		} else {
			$(this).parent().parent().parent().parent().find("tbody input[@type='checkbox']").attr('checked', '');
			$(this).parent().parent().parent().parent().find("tbody tr").addClass('disabled');
		}
    });
    
    $("table.import input[@type='checkbox'], table.orders input[@type='checkbox'],").bind('change', function(e) {
		if (this.checked) {
			$(this).parent().parent().removeClass('disabled');
			$(this).parent().parent().find("input[@type='text']").attr('disabled', '');
		} else {
			$(this).parent().parent().addClass('disabled');
			$(this).parent().parent().find("input[@type='text']").attr('disabled', 'disabled');
		}
    });
    
    $("table.import input[@type='text']").bind('change', function(e) {
    	var row     = $(this).parent().parent();
    	var rowId   = row.attr('id');
    	var purpose = $(this).val();
    	
        $.post(checkPaymentUrl,
                {rowId: rowId,
        	     purpose: purpose},
                updatePaymentStatus,
                'json');
    });
    
    $('ul.image-list a').lightBox({fixedNavigation: true,
                                   imageLoading: baseUrl + 'media/images/lightbox/lightbox-ico-loading.gif',
                                   imageBtnClose: baseUrl + 'media/images/lightbox/lightbox-btn-close.gif',
                                   imageBtnPrev: baseUrl + 'media/images/lightbox/lightbox-btn-prev.gif',
                                   imageBtnNext: baseUrl + 'media/images/lightbox/lightbox-btn-next.gif',
                                   imageBlank: baseUrl + 'media/images/lightbox/lightbox-blank.gif',
                                   txtImage: 'Bild',
                                   txtOf: 'von'});

    $("input[@title]").each(function(i) {
        $this = $(this);
        if (typeof($this.val()) == 'undefined') {
            $this.val($this.attr('title'));
        }
        
        $this.parents('form').bind('submit', function(e) {
            $(this).find("input[@title]").each(function(i) {
                if ($(this).val() == $(this).attr('title')) {
                    $(this).val('');
                }
            });
        });
    }).bind('focus', function(e) {
        $this = $(this);
        if ($this.val() == $this.attr('title')) {
            $this.val('');
        }
    }).bind('blur', function(e) {
        $this = $(this);
        if (typeof($this.val()) == 'undefined') {
            $this.val($this.attr('title'));
        }
    });
   
    $('form#xls-download').bind('submit', function(e) {
        // Prevent the form from submitting
        e.preventDefault();
        
        var month = $(this).find("select[@name='month']").val();
        var year  = $(this).find("select[@name='year']").val()
        
        window.open(baseUrl + 'admin/Buchhaltung_' + year + '-' + month + '.xls');
    });
    
    $('form.add-to-cart').bind('submit', function(e) {
        // Prevent the form from submitting
        e.preventDefault();
        
        // Submit the form asynchronous
        $.post($(this).attr('action'),
               {productId: $(this).find("input[@name='productId']").val(),
                quantity:  $(this).find("input[@name='quantity']").val()},
               updateCart,
               'json');
               
        $.scrollTo($('#cart'));
    });
    
    $('form#cart').bind('submit', function(e) {
        // Prevent the form from submitting
        e.preventDefault();
    });
    
    $('a.add-to-cart').bind('click', function(e) {
        var data = $(this).attr('href').split('#');
        
        $.post(data[0],
               {productId: data[1],
                quantity:  1},
               updateCart,
               'json');
               
        $.scrollTo($('#cart'));
    
        return false;
    });
    
    $("form#quantity-cart table input[@type='text']").bind('blur', updateQuantityCart);
    
    updateQuantityCart();
    bindCartUpdate();
});

/**
 * Update the quantity cart
 * 
 * @return void
 */
function updateQuantityCart()
{
    var usualPriceTotal   = 0;
    var currentPriceTotal = 0;
    
    $('form#quantity-cart table tbody tr').each(function(i) {
        var $this = $(this);
        
        var data      = $this.attr('id').split('-');
        var productId = parseInt(data[1]);
        var quantity  = parseInt($this.find("input[@type='text']").val());

        if (isNaN(quantity)) {
            quantity = 0;
        } else {
            quantity = parseInt(quantity);
            
            if (quantity < 0) {
                quantity = 0;
            }
        }
        
        $this.find("input[@type='text']").val(quantity);
        
        var usualPrice   = prices[productId][0].price;
        var currentPrice = usualPrice;
        
        for (var i = 0; i < prices[productId].length; i++) {
            var discount = prices[productId][i];
            
            if (discount.quantity <= quantity) {
                currentPrice = discount.price;
            }
        }
        
        var usualPriceSum   = quantity * usualPrice;
        var currentPriceSum = quantity * currentPrice;
        
        usualPriceTotal   += usualPriceSum;
        currentPriceTotal += currentPriceSum;
        
        $this.find('td.usual-price').html(numberFormat(usualPriceSum, 2, ',', '.') + ' &euro;');
        $this.find('td.current-price').html(numberFormat(currentPriceSum, 2, ',', '.') + ' &euro;');
    });
    
    $('form#quantity-cart table tfoot td.usual-price').html(numberFormat(usualPriceTotal, 2, ',', '.') + ' &euro;');
    $('form#quantity-cart table tfoot td.current-price').html(numberFormat(currentPriceTotal, 2, ',', '.') + ' &euro;');
}

/**
 * Update payment information
 * 
 * @param  object data
 * @return void
 */
function updatePaymentStatus(data)
{
    var row = $('#' + data.rowId);

    row.find('td.order-name').text(data.name);
    
    row.find('span.status')
       .removeClass('yes')
       .removeClass('no')
       .addClass(data.recognized ? 'yes' : 'no');
}

/**
 * Update the cart with given JSON data
 *
 * @param  object data
 * @return void
 */
function updateCart(data)
{
    var cart  = $('#cart');
    var table = cart.find('table');
    
    if (data.length == 0) {
        cart.find('b').after($('<p>Sie haben keine Produkte im Warenkorb</p>'));
        
        table.remove();
        
        cart.find('p#order').hide();
        
        $('#shipping-costs-info').text('Ab ' + numberFormat(shippingCostsLimit, 2, ',', '.') + ' Euro versandkostenfrei');
        
        return;
    } else if (table.length > 0) {
        table.remove();
    } else {
        cart.find('b + p').remove();
    }
    
    table = $('<table><colgroup><col /><col width="80" /></colgroup><tfoot><tr><td>Summe:</td><td class="price"></td></tr></tfoot><tbody></tbody></table>');
    
    var shippingCostsP = cart.find('p#shipping-costs-info');
    if (shippingCostsP.length > 0) {
    	shippingCostsP.before(table);
    } else {
    	cart.find('p#order').before(table);
    }
    
    cart.find('p#order').show();
    
    var tbody = table.find('tbody');
    tbody.children().remove();
    
    var priceSum = 0;
    for (var i = 0; i < data.length; i++) {
        var product = data[i];
        
        var tr = $('<tr />');
        tr.append($('<td />').append($('<input type="text" />').attr('name', 'product[' + product.id + ']').val(product.quantity))
                             .append($('<span> x ' + product.name + ' </span>'))
                             .append($('<a href="#" class="decrease-from-cart"></a>')));
        tr.append($('<td />').addClass('price').html(numberFormat(product.price, 2, ',', '.') + ' &euro;'));

        tbody.append(tr);
        
        priceSum += product.price;
    }
    
    table.find('tfoot td:last-child').html(numberFormat(priceSum, 2, ',', '.') + ' &euro;');
    
    var shippingCostsPriceLeft = (shippingCostsLimit - priceSum);    
    if (shippingCostsPriceLeft <= 0) {
    	$('#shipping-costs-info').text('Versandkostenfreie Lieferung!');
    } else {
		$('#shipping-costs-info').text('Noch ' + numberFormat(shippingCostsPriceLeft, 2, ',', '.') + ' Euro für versandkostenfreie Lieferung');    	
    }
    
    bindCartUpdate();
}

/**
 * Bind all input fields in the cart to update it
 *
 * @return void
 */
function bindCartUpdate()
{
    $("form#cart input[@type='text']").bind('blur', function(e) {
        var data = {};
    
        var inputs = $("form#cart input[@type='text']");
        inputs.each(function(i) {
            data[$(this).attr('name')] = $(this).val();
        });
        
        $.post($('form#cart').attr('action'),
               data,
               updateCart,
               'json');
    });
    
    $('a.decrease-from-cart').bind('click', function(e) {
        var input = $(this).parent().find('input');
        input.val(parseInt(input.val()) - 1);
        input.blur();
    });
}

/**
 * Number format
 *
 * @param  float number
 * @param  integer decimals
 * @param  string  decPoint
 * @param  string  thousandsSep
 * @return string
 */
function numberFormat(number, decimals, decPoint, thousandsSep)
{
    var exponent  = '';
    var numberstr = number.toString();
    var index     = numberstr.indexOf('e');
    if (index > -1) {
        exponent = numberstr.substring(index);
        number   = parseFloat(numberstr.substring(0, index));
    }
  
    if (decimals != null) {
        var temp = Math.pow(10, decimals);
        number = Math.round(number * temp) / temp;
    }
    
    var sign = number < 0 ? '-' : '';
    var integer = (number > 0 ? Math.floor(number) : Math.abs(Math.ceil(number))).toString();
  
    var fractional = number.toString().substring(integer.length + sign.length);
    decPoint       = decPoint != null ? decPoint : '.';
    fractional     = decimals != null && decimals > 0 || fractional.length > 1 ? (decPoint + fractional.substring(1)) : '';
    
    if (decimals != null && decimals > 0) {
        for (var i = fractional.length - 1, z = decimals; i < z; ++i) {
            fractional += '0';
        }
    }
  
    thousandsSep = (thousandsSep != decPoint || fractional.length == 0) ? thousandsSep : null;
    if (thousandsSep != null && thousandsSep != "") {
        for (i = integer.length - 3; i > 0; i -= 3) {
            integer = integer.substring(0 , i) + thousandsSep + integer.substring(i);
        }
    }
  
    return sign + integer + fractional + exponent;
}

