/**
 * Digitalus Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to info@digitalusmedia.net so we can send you a copy immediately.
 *
 * @category   Digitalus Framework
 * @package    Dig_Jquery
 * @copyright  Copyright (c) 2009,  Digitalus Media USA (digitalusmedia.net)
 * @license    New BSD License
 * @author:    Forrest Lyman
 * 
 */
// buttons
$('#calculate_order').click(function(){calculateOrder()});
$('#send_order').click(function(){submitForm('send', true)});
$('#save_order').click(function(){submitForm('save', true)});
$('#discard_order').click(function(){
    jConfirm('Are you sure you want to discard this order?', 'Confirm Delete', function(r) {
        if(r == true) {
            submitForm('discard', false)
        }
        return false;
    });
});


//product dictionary
window.productGuide = null;
$.get('/product/list', function(data) {
  window.productGuide = data;
  // you dont want to add the rows to the table until the data has loaded
  var rowCount = getOrderTable().find('tr').length;
  if(rowCount < 1) {
      addOrderRow(1);
  }
//$.cookie("chefstat_product_dictionary", data);
});

$('.button.form').click(function(){
    // get the form to submit
    var formId = $(this).attr('rel');
    var buttonImg = $(this).find('img');
    var imgSrc = buttonImg.attr('src');
    buttonImg.attr('src', '/ui/images/ajax-loader.gif');
    // ajax form options
    var options = { 
            success:   function(data){
                buttonImg.attr('src', imgSrc);
                if(data.message) {
                    jAlert(data.message);
                    // form callbacks
                    if(formId == 'purveyor_form') {
                        console.log(data.form_data.id);
                        $('.purveyor_' + data.form_data.id).html(data.form_data.name);
                    }
                } else {
                    var errorMessage = '<p>Sorry, we could not process your form. The following errors occurred:</p>';
                    for (var e in data.errors) {
                        errorMessage += "<img class='error' src='/ui/images/icons/exclamation.png' />" + data.errors[e] + '<br />';
                    }
                    jAlert(errorMessage);
                }
            },
            dataType:  'json'
        }; 
    $('#' + formId).ajaxSubmit(options);
    return false;
});

function formCallbacks(formId)
{
    if(formId == 'purveyor_form') {
        alert('purveyor updated');
    }
}

// links

$('a#add_purveyor').click(function(){addPurveyor();});
$('a#delete_row').click(function(){
    jConfirm('Are you sure you want to remove these rows?', 'Confirm Delete', function(r) {
        if(r == true) {
            $('.delete_row:checked').each(function(){
                $(this).closest('tr').remove();
             });
        }
        return false;
    });
    return false;
});

$('#details').hide();
$('.show_details').click(function(){
    $('#details').fadeIn();
});
$('.hide_details').click(function(){
    $('#details').fadeOut();
});
$('.show_options').click(function(){
    $('#options').fadeIn();
});
$('.hide_options').click(function(){
    $('#options').fadeOut();
});


// make sure that if someone changes the purveyor mid order that it warns them about prices
$('#purveyor').change(function(){
    var currentValue = $(this).val();
    if(currentValue != 0) {
        window.location = '/order/create/purveyor/' + currentValue;
    }
});

$('.confirmDelete').click(function(e){
    e.preventDefault();
    var href = $(this).attr('href');
    jConfirm($(this).attr('title'), 'Confirm Delete', function(r) {
        if(r == true) {
            location.href = href;
        }
        return false;
    });
});

// purveyors

function addPurveyor() {
    jPrompt("Enter the purveyor's name", '', 'Create Purveyor', function(purveyor) {
        if(purveyor) {
            jPrompt('Please enter the email address for ' + purveyor, '', 'Set Email Address', function(email) {
                if(email) {
                    $.post("/purveyor/quick-add", {'name': purveyor, 'email': email},
                        function(data){
                            if(data.error) {
                                jAlert(data.error);
                            }else{
                                window.location = '/order/create/purveyor/' + data.id;
                            }
                        }, "json");
                }
            });
        }
    });
}

// order table rows



// add a new row

$('a#add_row').click(function(){addOrderRow(1)});
$('a#add_multiple_rows').click(function(){
    jPrompt("How many rows would you like to add?", '', 'Add Order Rows', function(r) {
        if( r ) {
            addOrderRow(r);
        };
    });
});

$('#search_orders').click(function(){
    var query = $('#query').val();
    if(query == '') {
        jAlert('Please enter the terms you would like to search for.');
        return false;
    }
    var href = '/order/search/query/' + query;
    location.href = href;
});


// if you change the row structure you must also update the row view partial
// application/views/scripts/order/_order-row.phtml and 

function addOrderRow(count)
{
    var orderTable = getOrderTable()
    for (var i = 1; i <= count; i++) {
        var orderRow = "<tr class='order_row'>";
        orderRow += "<td class='delete'><input type='checkbox' class='delete_row' /></td>";
        orderRow += "<td class='product'><input type='text' name='item_product[]' class='item_product' /></td>";
        orderRow += "<td class='qty'><input type='text' name='item_qty[]' class='item_qty' /></td>";
        orderRow += "<td class='unit'><input type='text' name='item_unit[]' class='item_unit' /></td>";
        orderRow += "<td class='cost'>$<input type='text' name='item_price[]' class='item_price' /></td>";
        orderRow += "<td class='sum'></td>";
        orderRow += "</tr>";
        orderTable.append(orderRow);
        bindProductEvents();
    }
}


function bindProductEvents()
{
    $('.item_product').each(function(){
        $(this).unbind()
            .autocomplete(window.productGuide.split('|')) 
            .change(function(){
                var purveyor = $('#purveyor').val();
                var row = getRowByElement($(this));
                var rowElements = getRowElements(row);
                $.getJSON('/product/details/product/' + rowElements.product.val() + '/purveyor_id/' + purveyor, function(data) {
                    if(data != null) {
                        if(rowElements.unit.val() == ''){
                            rowElements.unit.val(data.unit);
                        }
                        if(rowElements.price.val() == '') {
                            rowElements.price.val(parseFloat(data.price));
                        }
                    }
                });
            });
    });
}

function getRowElements(row)
{
    if(row) {
        rowElements = new Object();
        rowElements.qty = getElementInRow('item_qty', row);
        rowElements.product = getElementInRow('item_product', row);
        rowElements.unit = getElementInRow('item_unit', row);
        rowElements.price = getElementInRow('item_price', row);
        rowElements.sum = getElementInRow('sum', row);
        return rowElements;
    }
    return false;
}

function getRowByElement(element)
{
    return element.closest('tr');
}

function getOrderTable()
{
    return $('table#order tbody');
}

function getElementInRow(elementClass, row)
{
    // console.log('fetching ' + elementClass + ' from ' + row.attr('class'));
    var element = row.find('.' + elementClass);
    // console.log('found ' + element.attr('class'));
    return element;
}

// calculate order
// this function highlights all rows that are not calculatable

function calculateOrder()
{
    var rows = getOrderTable().find('tr');
    var sum = 0;
    rows.each(function(){
        var elements = getRowElements($(this));
        if(elements.qty.val() > 0 && elements.price.val() > 0) {
            var rowSum = (elements.qty.val() * elements.price.val());
            elements.sum.html(formatCurrency(rowSum));
            sum += rowSum;
            highlightRow($(this), false);
        } else {
            highlightRow($(this), true);
        }
    });
    if(sum > 0) {
        $('#sum').html('Order Total: <strong>' + formatCurrency(sum) + '</strong>');
    }
}

function highlightRow(row, highlighted)
{
    if(row) {
        if(highlighted) {
            row.addClass('highlighted');
        } else {
            row.removeClass('highlighted');
        }
    }
}

function formatCurrency(val)
{
    return '$' + val.toFixed(2);
}

function submitForm(action, validate)
{
    var form = getForm();
    if(validate) {
        // validate that the order contains at least one item
        var products = $('.item_product');
        if(products.length == 1) {
            var isValid = false;
            products.each(function(){
                if($(this).val() != '') {
                    var elements = getRowElements(getRowByElement($(this)));
                    if(elements.qty.val() > 0) {
                        isValid = true;
                    }
                }
            });
            if (isValid == false) {
                jAlert('Your order is empty');
                return false;
            }
        }
        
        // validate the purveyor
        var purveyor = $('select#purveyor').val();
        var subject = $('#subject').val();
        if(purveyor < 1) {
            jAlert('You must select a purveyor before you submit the order');
            return false;
        }
    }
    form.attr('action', '/order/' + action);
    form.submit();
}

function getForm()
{
    return $('#order_form');
}


