/**
 * Event listners for transaction tables
 */
$(document).ready(function () {

    //standard for ajax requests
    $.ajaxSetup({
        beforeSend: function (xml) {
            ajaxBeforeSend(xml);
        },
        complete: function (xml, status) {
            ajaxComplete(xml, status);
        },
        error: function (xml, status) {
            ajaxError(xml, status);
        },
        type: "POST"
    });





    $('.headline .toggler').live('click', function() {
        $(this).parent(2).next().slideToggle();
        $(this).toggleClass("mini");
        
    });





    // Event listeners
    $('.editTrans').live('click', function (e) {
        e.preventDefault();
        editRowShow(this);
    });

    $('.cancel').live('click', function (e) {
        e.preventDefault();
        editRowCancel(this);
    });

    $('.update').live('click', function (e) {
        e.preventDefault();
        editRowUpdate(this);
    });

    $('.editInput').live('click', function (e) {
        e.preventDefault();
        editInput(this);
    });

    $('#update').live('click', function (e) {
        e.preventDefault();
        displayTransTable();
    });

    $('.category').live('click', function () {
        $(this).parent().find('ul').slideToggle();
    });

    $('#dropdown select').live('change', function () {
        updateReport($(this).val());
    });


    $('.categoryTable .categoryRow').live('click', function () {
        $(this).next().toggle();
    });
    
    $('#help').fancybox({
        'transitionIn': 'elastic',
        'transitionOut': 'elastic'
    });
});


function ucFirst(string)
{
    return string.charAt(0).toUpperCase() + string.slice(1);
}


function displayTransTable() {

    var start = $('#datepickerStart').val();
    var end = $('#datepickerEnd').val();

    if (start === "") {
        start = "2000-01-01";
    }

    if (end === "") {
        end = "2020-01-01";
    }


    var date = escape(start + '-' + end);

    transactionsGET(date, function (data) {

        storage.transactions = parseJSON(data);

        if ($('.transTable').size() === 1) {
            $('.transTable').remove();
        }
        renderTransTable(storage.transactions);
    });
}


function editRowShow(clickLink) {
    var parentRow = $(clickLink).parent().parent();
    var transaction = getTransaction(parentRow.attr("rel"), storage.transactions);

    parentRow.after(transactionGetEditRow(transaction));
}

function editRowCancel(row) {
    $(row).parent().parent().remove();
}

function editRowUpdate(row) {
    var tableRow = $(row).parent().parent();

    // set transaction with form values
    var tempTrans = new Transaction();
    tempTrans.parseEditRow(tableRow);


    var data = transactionGetJSON(tempTrans);

    $.ajax({
        type: "POST",
        url: "/api/transactionupdate/format/json",
        data: data,
        dataType: "script",
        success: function (data) {
            if (true) {
                //succesful update
                message(tempTrans.getName() + ' har uppdaterats', "success");
                // remove edit remove
                $(row).parent().parent().remove();

                //set in Storage
                storageSetTransaction(tempTrans, storage.transactions);
                tableRow = $('[rel = t_' + tempTrans.getId() + ']');

                //Perhaps handle offColor
                $(tableRow).replaceWith(transactionGetTableRow(tempTrans, "t"));
            }
            else {
                //do something when failure
            }
        }
    });
}








function renderTransTable(source) {
    var prefix = "t";

    if (source == storage.inputs) prefix = "i";

    var html = "";
    var trans = $(source).sort("date", "asc");


    if (prefix == "t") {
        //regular transtable
        $.each(trans, function () {

            html += transactionGetTableRow(this, prefix);
        });


        header = '<table class="transTable"><colgroup><col><col><col><col><col><col></colgroup>';
        header += '<tbody><tr height="20" class="header"><td>Namn</td><td>amount</td><td>Date</td><td>description</td><td>Category</td><td>Edit</td></tr>';

        footer = '</tbody></table>';

        $("#tableContainer").html(header + html + footer);


        storage.table = $(".transTable").eq(0).tableFilter({
            imagePath: "/img/tablefilter/icons"
        });



        $('.transTable').eq(0).resize(function () {
            renderReport();
        });


    } else {
        // input table
        $.each(trans, function () {
            html += inputGetTableRow(this, prefix);
        });
        header = '<table class="transTable"><colgroup><col><col><col><col><col><col></colgroup>';
        header += '<tbody><tr height="20" class="header"><td>Namn</td><td>amount</td><td>Date</td><td>description</td><td>Category</td><td>Edit</td></tr>';

        footer = '</tbody></table>';
        $("#tableContainer").html(header + html + footer);

        $(".transTable").eq(0).tableFilter({
            imagePath: "/img/tablefilter/icons"
        });
    }

}

//fetch Transaction by id from storage

function getTransaction(id) {
    var temp = -1;


    // Strip t_ if needed
    if (id.substr(0, 2) == 't_') {
        id = id.substr(2);

        //find the transaction
        $.each(storage.transactions, function () {
            if (this.getId() == id) temp = this;
        });
    }

    // Strip t_ if needed
    if (id.substr(0, 2) == 'i_') {
        id = id.substr(2);

        //find the transaction
        $.each(storage.inputs, function () {
            if (this.getId() == id) temp = this;
        });
    }
    return temp;
}
/*
function storageSetTransaction(transaction, source) {
    var id = transaction.getId();

    $.each(source, function () {
        if (this.id == id) {
            this.id = transaction.getId();
            this.name = transaction.getName();
            this.description = transaction.getDescription();
            this.category = transaction.getCategory();
            this.amount = transaction.getAmount();
            this.date = transaction.getDate();
            this.dataString = transaction.getDataString();
            this.dataName = transaction.getDataName();

            // Add the rest... user datastring ...etc
        }
    });
}
*/

/*
function renderReport() {
    var content = "<h3>Rapport</h3>";
    content += "<table>";
    var transactions = Array();
    //find visible transactions from table and store them in local array transactions
    var rows = $('.transTable').find('tr:visible');
    $.each(rows, function () {
        if ($(this).attr("rel") != undefined) {

            var id = $(this).attr("rel");
            var trans = getTransaction(id, storage.transactions);
            transactions.push(trans);
        }
    });

    var totalAmount = 0;
    var total = 0;
    //loop over all visible transactions
    $.each(transactions, function () {
        totalAmount += parseFloat(this.getAmount());
        total++;
    });

    // categories
    categories = $(transactions).sort("category", "asc");

    var splitCats = new Array();
    var nums = new Array();
    var i = -1;
    var catName = "";

    //Get nums where the cat changes
    $.each(categories, function () {
        i++;
        if (this.getCategory() != catName) {
            nums.push(i);
            catName = this.getCategory();
        }
    });

    //split array on category
    for (i = 1; i < nums.length; i++) {
        splitCats.push(categories.slice(nums[i - 1], nums[i]));
    }

    //perhaps sort them on date...
    var catTable = "";
    totalAmount = 0;
    var totalNum = 0;
    //loop thru all categories
    $.each(splitCats, function () {
        catTable += '<div><span class="category">' + this[0].getCategory() + '</span>';
        var amount = 0;
        var num = 0;
        var innerList = "";

        $.each(this, function () {
            innerList += '<li><span class="name">' + this.getName() + '</span><span class="date">' + this.getDate() + '</span><span class="amount">' + Math.round(this.getAmount()) + '</span></li>';
            amount += parseFloat(this.getAmount());
            totalAmount += parseFloat(this.getAmount());
            num++;
            totalNum++;
        });
        catTable += '<span class="num">' + num + '</span><span class="total">' + Math.round(amount) + '</span><ul style="display:none">' + innerList + '</ul></div>';
    });

    var summary = '<hr/><div><span class="totalCategory">Total</span><span class="num">' + totalNum + '</span><span class="total">' + Math.round(totalAmount) + '</span></div>';

    $('#reports').html(catTable + summary).slideDown();
}
*/

/*
function getTransPackSelectorsFromDate(from) {

    var start = from.moveToFirstDayOfMonth();
    var today = new Date();
    today.moveToFirstDayOfMonth();

    var selectors = Array();

    while (start < today) {

        temp = new Transpackselector();

        temp.setStart(new Date(start));
        temp.setEnd(new Date(start).moveToLastDayOfMonth());
        selectors.push(temp);
        start.addMonths(1);
    }


    // remove last
    return selectors;
}

*/


function categoryPage(category) {

    var start = "2000-01-01";
    var end = "2020-01-01";
    var date = escape(start + '-' + end);

    transactionsGET(date, function (data) {

        storage.transactions = parseJSON(data);

        renderCategoryPage(storage.transactions, category);
    });
}

function renderCategoryPage(source, category) {
    var dropDown = getCategoriesDropDown(category);
    $('#dropdown').html(dropDown);
    updateReport($('#dropdown select').val());
}

function updateReport(category) {

    //find all transactions and create a report
    var transpack = new Transpack();
    var selector = new Transpackselector();
    transpack.setFromSelector(selector, storage.transactions);
 
    
    
    var report = new Report(transpack);

    var reportData = report.getReportData();
    var categoryData;

    // find the category data for requested category
    $(reportData.categories).each(function () {
        if (this.getName() == category) {
            categoryData = this;
        }
    });

    $('#reportsContainer').show();

    if (categoryData.transactions.length > 0) {
        categoryGraph(categoryData.transactions);

        var transHtml = "";

        var month = categoryData.transactions[0].getRealDate().getMonthName();
        $.each(categoryData.transactions, function () {
            if (this.getRealDate().getMonthName() !== month) {
                transHtml += '<hr/>';
                month = this.getRealDate().getMonthName();
            }
            transHtml += '<li><span class="name">' + this.getName() + '</span><span class="date">' + this.getDate() + '</span><span class="amount">' + this.getAmount() + '</span><li>';
        });


        //summary
        $('#summary').html(renderCategorySummary(categoryData));
        $('#summaryContainer').show();

        $('#vendors').html(renderVendors(categoryData.getTransactionsByVendor()));
        $('#vendorsContainer').show();

    }
    else {
        transHtml = "<h3>Inga transaktioner i denna kategori</h3>";
        $('#graph').html("");
        $('#vendorsContainer').hide();
        $('#vendors').html("");
        $('#summaryContainer').hide();
    }
    $('#reports').html('<ul>' + transHtml + '</ul>');




}

/*
function getMonthYear(date) {
    var month = "";

    if (date.getMonth() == 0) month = "jan";
    if (date.getMonth() == 1) month = "feb";
    if (date.getMonth() == 2) month = "mar";
    if (date.getMonth() == 3) month = "apr";
    if (date.getMonth() == 4) month = "maj";
    if (date.getMonth() == 5) month = "jun";
    if (date.getMonth() == 6) month = "jul";
    if (date.getMonth() == 7) month = "aug";
    if (date.getMonth() == 8) month = "sep";
    if (date.getMonth() == 9) month = "okt";
    if (date.getMonth() == 10) month = "nov";
    if (date.getMonth() == 11) month = "dec";

    var year = date.getFullYear();
    year = year.toString();

    return month + '/' + year.substr(2, 2);
}
*/

function refreshCategories() {

    $.ajax({
        type: "GET",
        url: "/categories/readCategories",
        dataType: "json",
        success: function (msg) {
            storage.categories = msg;
            var dropDown = getCategoriesDropDown();
            $('#dropdownEdit').html(dropDown);
        }
    });

}
