var matrix = {};
var names = new Array();

function valuesByQuantity(elem) {
    var r = {};
    var p = elem.parent();
    r.id = p.parent()[0].id;
    r.company = elem.parent().parent().parent().parent().prev().text();
    r.pricePerKg = p.prev();
    r.price = r.pricePerKg.prev();
    r.weight = r.price.prev();
    r.description = r.weight.prev().text();

    r.quantity = parseFloat(elem.val());
    if (isNaN(r.quantity)) {
        r.quantity = 0;
    }

    r.pricePerKg = parseFloat(r.pricePerKg.text());
    r.price = parseFloat(r.price.text());
    r.weight = parseFloat(r.weight.text());
    return r;
}

function fixTables() {
    $('.header').removeClass('header');
    $('.last').removeClass('last');
    $('.odd').removeClass('odd');

    $("table").find("tr:first").addClass("header");
    $("table").find("th:last").addClass("last");
    $("table").find("tr:not(.hidden-row):last").addClass("last");
    $("table").find("tr:not(.hidden-row)").find("td:last").addClass("last");
    $("table").find("tr:not(.hidden-row):odd").addClass("odd");
}

function foldProds() {
    $('.company-record table').each(function() {
        var filled = $(this).find(':input').filter(function() {return $(this).val() != ""});
        if (filled.length == 0) {
            $(this).hide();
        }
        else {
            $(this).show();
        }
    });
}

function loadNames() {
    $("td.name").each(function(){
        var id = $(this).parent()[0].id;
        var name = $(this).text();
        names.push(id + '$' + name.toLowerCase());
    });
}

function searchProds(s) {
    $('.highlight').removeClass('highlight');
    $('tr').hide()
    foldProds();
    if (s == "") {return};
    s = s.toLowerCase();
    var ids = new Array();
    $.each(names, function(id, val) {
        if (val.indexOf(s) != -1) {
            var id = val.split('$')[0];
            ids.push(id);
            $('#'+id).parent().parent().show();
            $('#'+id).show();
            $('#'+id).addClass('highlight');
        }
    });
    $('#searchResultNumber').text('risultati:' + ids.length);
    return ids;
}

function calculateTotal() {
    var totWeight = 0;
    var totPrice = 0;

    $.each(matrix, function(id, val) {
        var price = val[0];
        var weight = val[1];
        var quantity = val[2];
        totWeight += weight * quantity;        
        totPrice += price * quantity;        
    });

    totWeight /= 1000;
    
    $('#weight .value').text(totWeight);
    $('#price .value').text(totPrice.toFixed(2));
}

function updateMatrix() {
    $(':input.quantity').each(function () {
        if ($(this).val() != "") {
            var v = valuesByQuantity($(this));
            matrix[v.id] = [v.price, v.weight, v.quantity];
        }
    });
    calculateTotal();
}

$(document).ready(function(){
    $('#clear-all').click(function () {
        $(':input.quantity').val("");
        matrix = {};
        calculateTotal();
    });
    // input.quantity hook
    $('input.quantity').keyup(function () {
        var v = valuesByQuantity($(this));

        matrix[v.id] = [v.price, v.weight, v.quantity];
        calculateTotal();
    });

    $('#searchProds').keypress(function (e) {
            // if the user presses enter...
            if (e.keyCode== 13) {
                searchProds($(this).val());
            };
    });

    $('#submitSearch').click(function () {
        searchProds($('#searchProds').val());
    });

    fixTables();
    updateMatrix();

    foldProds();
    $('.company-record .company').click(function() {
        var table = $(this).next();
        var visible = table.find('tr:visible').length;
        var total = table.find('tr').length;

        if (visible < total) {
            table.show();
            table.find('tr').show();
        }
        else if (visible == total) {
            table.find('tr').show();
            table.hide();
        }

    });

    $('#checkout').click(function(event) {
    	$('#actiontype').val('save');
    	$('#checkout-list').submit();
    	event.preventDefault();
    });
    
    $('#new-checkout').click(function(event) {
    	$('#actiontype').val('save-as-new');
    	$('#checkout-list').submit();
    	event.preventDefault();
    });
    
    loadNames();
});


