/* $Id$ */
//-------------------------------------------------------------------------
// FUNCTION: geo
//-------------------------------------------------------------------------

function geo()
{
}


//-------------------------------------------------------------------------
// FUNCTION: $f
//-------------------------------------------------------------------------

function $f(fieldName)
{
    var field = document.getElementsByName(fieldName);

    if (field.length == 1)
    {
        return $(field[0]);
    }
    else if (field.length > 1)
    {
        for (var i = 0; i < field.length; i++)
        {
            if (field[i].checked)
            {
                return $(field[i]);
            }
        }

        return $(field[0]);
    }
    else if (field.length == 0)
    {
        return false;
    }
    else
    {
        return $(field);
    }
}



//-------------------------------------------------------------------------
// FUNCTION: getTarget
//-------------------------------------------------------------------------

function getTarget(evt)
{
    var e = (evt ? evt : (window.event ? window.event : null));
    var target = (e.target) ? e.target : ((e.srcElement) ? e.srcElement : null);

    return target;
}




//-------------------------------------------------------------------------
// FUNCTION: hide
//-------------------------------------------------------------------------

function hide(obj)
{
    if (obj)
    {
        obj.style.display = 'none';
    }
}


//-------------------------------------------------------------------------
// FUNCTION: show
//-------------------------------------------------------------------------

function show(obj)
{
    if (obj.tagName.toLowerCase() == "table" && !window.ie)
    {
        obj.style.display = "table";
    }
    else if (obj.tagName.toLowerCase() == "tr" && !window.ie)
    {
        obj.style.display = "table-row";
    }
    else if (obj.tagName.toLowerCase() == "td" && !window.ie)
    {
        obj.style.display = "table-cell";
    }
    else if (obj.tagName.toLowerCase() == "select" || obj.tagName.toLowerCase() == "input")
    {
        obj.style.display = "inline";
    }
    else
    {
        obj.style.display = "block";
    }
}


//-------------------------------------------------------------------------
// FUNCTION: quantityUp
//-------------------------------------------------------------------------

function quantityUp(itemId)
{
    $('quantity' + itemId).value++;

    getBinPrice();
}


//-------------------------------------------------------------------------
// FUNCTION: quantityDown
//-------------------------------------------------------------------------

function quantityDown(itemId)
{
    if ($('quantity' + itemId).value > 0)
    {
        $('quantity' + itemId).value--;
    }

    getBinPrice();
}


//-------------------------------------------------------------------------
// FUNCTION: standingQuantityUp
//-------------------------------------------------------------------------

function standingquantityUp(itemId)
{
    $('standingquantity' + itemId).value++;

    getBinPrice();
}


//-------------------------------------------------------------------------
// FUNCTION: standingQuantityDown
//-------------------------------------------------------------------------

function standingquantityDown(itemId)
{
    if ($('standingquantity' + itemId).value > 0)
    {
        $('standingquantity' + itemId).value--;
    }

    getBinPrice();
}


//-------------------------------------------------------------------------
// FUNCTION: quantityAdjust
// called when a user manually enters data into a quantity field
//-------------------------------------------------------------------------

function quantityAdjust(itemId)
{
    // if NOT blank, validate. If blank, set to zero.
    if ($('quantity' + itemId).value != "")
    {
        // check for a numeric value and reset to 0 if NOT numeric
        if (isFloat($('quantity' + itemId).value))
        {
        }
        else
        {
            $('quantity' + itemId).value = "0";
        }
    }
    else
    {
        $('quantity' + itemId).value = "0";
    }

    getBinPrice();
}

//-------------------------------------------------------------------------
// FUNCTION: standingquantityAdjust
// called when a user manually enters data into a quantity field
//-------------------------------------------------------------------------

function standingquantityAdjust(itemId)
{
    // if NOT blank, validate. If blank, set to zero.
    if ($('standingquantity' + itemId).value != "")
    {
        // check for a numeric value and reset to 0 if NOT numeric
        if (isNumeric($('standingquantity' + itemId).value))
        {
            getBinPrice();
        }
        else
        {
            $('standingquantity' + itemId).value = "0";
            getBinPrice();
        }
    }
    else
    {
        $('standingquantity' + itemId).value = "0";
        getBinPrice();
    }

}



//-------------------------------------------------------------------------
// FUNCTION: isNumeric
//-------------------------------------------------------------------------
function isNumeric(sText)

{
   var ValidChars = "0123456789";
   var IsNumber=true;
   var Char;

   for (i = 0; i < sText.length && IsNumber == true; i++)
   {
      Char = sText.charAt(i);

        if (ValidChars.indexOf(Char) == -1)
        {
            IsNumber = false;
        }
   }

    return IsNumber;

}

//-------------------------------------------------------------------------
// FUNCTION: getBinPriceWithMinimum
//-------------------------------------------------------------------------

function getBinPriceWithMinimum()
{
    var orderId = $('orderId');

    var myAjax = new Ajax('/bin/minprice/orderid/' + orderId.value,
    {
        method: 'get',

        onSuccess: function(json_response)
        {
            var response = Json.evaluate(json_response);

            if (response.minimumPrice)
            {
                minimumPrice = response.minimumPrice;
                getBinPrice(minimumPrice);
            }
        }
    }).request();
}


//-------------------------------------------------------------------------
// FUNCTION: getBinPrice
//-------------------------------------------------------------------------

function getBinPrice(minimumPrice)
{
    if (typeof minimumPrice === 'undefined') {
        var bin_price_elem = document.getElementById("bin_price");
        if (bin_price_elem) {
            minimumPrice = bin_price_elem.innerHTML;
        }
    }

    if (!itemsClass)
    {
        var itemsClass = '.itemid';
    }

    if (!totalDiv)
    {
        var totalDiv = 'total';
    }

    var weeklytotal = 0.0;
    var bintotal = 0.0;
    var hst_rate = 0.0;
    var hst_subtotal = 0.0;
    var gst_rate = 0.0;
    var gst_subtotal = 0.0;
    var pst_rate = 0.0;
    var pst_subtotal = 0.0;
    var total_container_deposits = 0.0;

    if ($('weeklyprice'))
    {
        weeklytotal = $('weeklyprice').value.toFloat();
    }

    var items = $$(itemsClass);

    items.forEach(function(item)
    {
        var itemId = item.value;

        var quantity = $('quantity' + itemId).value.toFloat();
        var price = $('price' + itemId).value.toFloat();

        var linetotal = decimal_mul(quantity, price);

        // Hacky way of determining taxes. If it's set, the item is taxable
        // This makes it work properly for historical orders
        var item_hst_rate = $('hstRate' + itemId).value.toFloat();
        if (item_hst_rate) {
            hst_rate = item_hst_rate;
            hst_subtotal = decimal_add(hst_subtotal, linetotal);
        }
        var item_gst_rate = $('gstRate' + itemId).value.toFloat();
        if (item_gst_rate) {
            gst_rate = item_gst_rate;
            gst_subtotal = decimal_add(gst_subtotal, linetotal);
        }
        var item_pst_rate = $('pstRate' + itemId).value.toFloat();
        if (item_pst_rate) {
            pst_rate = item_pst_rate;
            pst_subtotal = decimal_add(pst_subtotal, linetotal);
        }

        var container_deposit = $('container_deposit' + itemId).value.toFloat();

        if (container_deposit) {
            total_container_deposits = decimal_add(total_container_deposits, container_deposit * quantity);
        }

        bintotal = decimal_add(bintotal, linetotal);

        if ($('total' + itemId)) {
            $('total' + itemId).setHTML('$' + linetotal.toFixed(2));
        }

    });



    var standingtotal = 0.00;

    // standing items...
    // So ... much ... duplication
    {
        var items = $$('.standingitemid');

        items.forEach(function(item)
        {
            var itemId = item.value;

            var quantity = $('standingquantity' + itemId).value.toFloat();
            var price = $('standingprice' + itemId).value.toFloat();

            var linetotal = quantity * price;

            // Hacky way of determining taxes. If it's set, the item is taxable
            var item_hst_rate = $('hstRate' + itemId).value.toFloat();
            if (item_hst_rate) {
                hst_rate = item_hst_rate;
                hst_subtotal = decimal_add(hst_subtotal, linetotal);
            }
            var item_gst_rate = $('gstRate' + itemId).value.toFloat();
            if (item_gst_rate) {
                gst_rate = item_gst_rate;
                gst_subtotal = decimal_add(gst_subtotal, linetotal);
            }
            var item_pst_rate = $('pstRate' + itemId).value.toFloat();
            if (item_pst_rate) {
                pst_rate = item_pst_rate;
                pst_subtotal = decimal_add(pst_subtotal, linetotal);
            }

            var container_deposit = $('container_deposit' + itemId).value.toFloat();

            if (container_deposit) {
                total_container_deposits = decimal_add(total_container_deposits, container_deposit * quantity);
            }

            standingtotal = decimal_add(standingtotal, linetotal);

            if ($('standingtotal' + itemId)) {
                $('standingtotal' + itemId).setHTML('$' + linetotal.toFixed(2));
            }

        });
    }

    var totalHST = decimal_mul(hst_rate, hst_subtotal);
    var totalGST = decimal_mul(gst_rate, gst_subtotal);
    var totalPST = decimal_mul(pst_rate, pst_subtotal);
    var totalTax = decimal_sum([totalHST, totalGST, totalPST]);

    if ($('weeklytotal'))
    {
        $('weeklytotal').setHTML('$' + (weeklytotal).toFixed(2) );
    }

    if ($('bintotal'))
    {
        $('bintotal').setHTML('$' + (bintotal).toFixed(2) );
    }

    if ($('standingtotal'))
    {
        $('standingtotal').setHTML('$' + (standingtotal).toFixed(2) );
    }

    var outstanding = 0.00
    if ($('outstandingtotal'))
    {
        var current_total = decimal_sum([bintotal, standingtotal, totalTax]);
        if (current_total < minimumPrice)
        {
            outstanding = decimal_sub(minimumPrice, current_total);
            $('outstandingtotal').setHTML('$' + (outstanding).toFixed(2) );
            $('outstandingtotal').setStyles({'font-size': 20, 'color':'red', 'text-align':'right'});
        }
        else
        {
            $('outstandingtotal').setHTML('$' + (0.00).toFixed(2) );
            $('outstandingtotal').setStyles({'font-size': 12, 'color':'black', 'text-align':'right'});
        }
    }

    if ($('total_hst') && totalHST) {
        $('total_hst_line').style.display = 'table-row';
        $('total_hst').setHTML('$' + (totalHST).toFixed(2) );
    }

    if ($('total_gst') && totalGST) {
        $('total_gst_line').style.display = 'table-row';
        $('total_gst').setHTML('$' + (totalGST).toFixed(2) );
    }

    if ($('total_pst') && totalPST) {
        $('total_pst_line').style.display = 'table-row';
        $('total_pst').setHTML('$' + (totalPST).toFixed(2) );
    }

    if ($('container_deposit_line') && total_container_deposits) {
        $('container_deposit_line').style.display = 'table-row';
        $('container_deposits').setHTML('$' + (total_container_deposits).toFixed(2));
    }


    if ($(totalDiv))
    {

        $(totalDiv).setHTML('$' + decimal_sum([weeklytotal, bintotal, standingtotal, outstanding, totalHST, totalGST, totalPST, total_container_deposits]).toFixed(2) );
        $(totalDiv).setStyles({'font-size': 40, 'text-align':'right'});
    }



}


//-------------------------------------------------------------------------
// FUNCTION: addItemToBin
//-------------------------------------------------------------------------

function addItemToBin(id, data)
{
    var items = $('items');

    var item = new Element('div', {id: 'item' + id, 'class': 'item'});

    item.setHTML('<div class="image"><img src="' + data['s_src'] + '" height="20"></div>');





    var quantityDiv = new Element('div', {'class': 'quantity'});

    var quantityList = new Element('input', {type: 'text', size: '2', name: 'quantity' + id, id: 'quantity' + id, value: 1});

    quantityList.injectInside(quantityDiv);

    var quantityUp = new Element('a', {href: 'javascript:quantityUp(' + id + ', 1)'});
    quantityUp.setHTML('<img src="/images/arrow_up_green.gif" alt="More" width="10" height="10" border="0"> ');
    quantityUp.injectInside(quantityDiv);

    var quantityDown = new Element('a', {href: 'javascript:quantityDown(' + id + ', 1)'});
    quantityDown.setHTML('<img src="/images/arrow_down_green.gif" alt="More" width="10" height="10" border="0">');
    quantityDown.injectInside(quantityDiv);

    quantityDiv.injectInside(item);



    var nameDiv = new Element('div', {'class': 'name'});

    nameDiv.appendText(data['name']);

    nameDiv.injectInside(item);

    var priceDiv = new Element('div', {'class': 'price'});

    var price = beautifyPrice(' ' + data['price'], data['unit_quantity'], data['unit_type']);

    if (data['sale'] && data['sale'] == 1)
    {
        var saleDiv = new Element('div', {'class': 'sale'});
        saleDiv.appendText('SALE');
        saleDiv.injectInside(priceDiv);

        var salepriceDiv = new Element('div', {'class': 'oldprice'});
        var saleprice = beautifyPrice(' ' + data['sale_price'], data['unit_quantity'], data['unit_type']);

        salepriceDiv.appendText(price);
        salepriceDiv.injectInside(priceDiv);
        priceDiv.appendText(saleprice);

    }
    else
    {
        priceDiv.appendText(price);
    }


    priceDiv.injectInside(item);



    var itemInput = new Element('input', {'class': 'itemid', name: 'item' + id, type: 'hidden', value:id});
    itemInput.injectInside(item);

    var priceInput = new Element('input', {'class': 'itemprice',  name: 'price' + id, id: 'price' + id, type: 'hidden', value: data['price']});
    priceInput.injectInside(item);

    var hstInput = new Element('input', {'class': 'itemprice',  name: 'hstRate' + id, id: 'hstRate' + id, type: 'hidden', value: data['hst_tax_rate']});
    hstInput.injectInside(item);

    var gstInput = new Element('input', {'class': 'itemprice',  name: 'gstRate' + id, id: 'gstRate' + id, type: 'hidden', value: data['gst_tax_rate']});
    gstInput.injectInside(item);

    var pstInput = new Element('input', {'class': 'itemprice',  name: 'pstRate' + id, id: 'pstRate' + id, type: 'hidden', value: data['pst_tax_rate']});
    pstInput.injectInside(item);

    var containerdepositInput = new Element('input', {'class': 'itemprice',  name: 'container_deposit' + id, id: 'container_deposit' + id, type: 'hidden', value: data['container_deposit']});
    containerdepositInput.injectInside(item);



    var deleteDiv = new Element('div', {'class': 'removeitem'});

    var deleteItem = new Element('a', {href: 'javascript:removeItem(' + id + ')'});
    deleteItem.setText('Remove');

    deleteItem.injectInside(deleteDiv);

    deleteDiv.injectInside(item);


    item.injectInside(items);

    getBinPrice();
}


//-------------------------------------------------------------------------
// FUNCTION: addItemToStandingBin
//-------------------------------------------------------------------------

function addItemToStandingBin(id, data)
{
    var items = $('items');

    var item = new Element('div', {id: 'item' + id, 'class': 'item'});

    item.setHTML('<div class="image"><img src="' + data['s_src'] + '" height="20"></div>');





    var nameDiv = new Element('div', {'class': 'name'});

    nameDiv.appendText(data['name']);

    nameDiv.injectInside(item);


    var itemInput = new Element('input', {'class': 'itemid', name: 'item' + id, type: 'hidden', value:id});
    itemInput.injectInside(item)


    var deleteDiv = new Element('div', {'class': 'removeitem'});

    var deleteItem = new Element('a', {href: 'javascript:removeItem(' + id + ')'});
    deleteItem.setText('Remove');

    deleteItem.injectInside(deleteDiv);

    deleteDiv.injectInside(item);


    item.injectInside(items);
}


//-------------------------------------------------------------------------
// FUNCTION: removeItem
//-------------------------------------------------------------------------

function removeItem(itemId)
{
    $('item' + itemId).remove();
    getBinPrice();
}


//-------------------------------------------------------------------------
// FUNCTION: beautifyPrice
//-------------------------------------------------------------------------

function beautifyPrice(price, unitQuantity, type)
{
    var priceHTML = '';
    var typeName = '';
    var quantity = 1;

    switch (type)
    {
        case 'NONE':
        {
            if (unitQuantity == 1)
            {
                priceHTML = '$' + number_format(price, 2) + ' each';
            }
            else
            {
                priceHTML = '$' + number_format(price, 2) + ' for ' + unitQuantity;
            }
        }
        break;

        case 'g':
        case 'lb':
        case 'kg':
        {
            if (unitQuantity == 1)
            {
                priceHTML = '$' + number_format(price, 2) + '/' + type;
            }
            else
            {
                priceHTML = '$' + number_format(price, 2) + '/' + unitQuantity + type;
            }

            typeName = type + ((type != '' && (quantity * unitQuantity)) ? 's' : '');
        }
        break;

        case '12':
        case '6':
        {
            if (unitQuantity == 1)
            {
                priceHTML = '$' + number_format(price, 2) + '/' + (type == 12 ? 'dozen' : 'half dozen');
            }
            else
            {
                priceHTML = '$' + number_format(price, 2) + '/' + unitQuantity + ' ' + (type == 12 ? 'dozen' : 'half dozen');
            }


            typeName = (type == 12) ? 'dozen' : 'half dozen';
        }
        break;


        default:
        {
            priceHTML = '$' + number_format(price, 2) + '/' + unitQuantity + type;
            typeName = type + ((type != '' && (quantity * unitQuantity)) ? 's' : '');
        }
    }

    return priceHTML;
}


//-------------------------------------------------------------------------
// FUNCTION: number_format
//-------------------------------------------------------------------------

function number_format(amount)
{
    var i = parseFloat(amount);
    if(isNaN(i)) { i = 0.00; }
    var minus = '';
    if(i < 0) { minus = '-'; }
    i = Math.abs(i);
    i = parseInt((i + .005) * 100);
    i = i / 100;
    s = new String(i);
    if(s.indexOf('.') < 0) { s += '.00'; }
    if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
    s = minus + s;
    return s;
}


// Add reduce for old versions of Javascript
if ( !Array.prototype.reduce ) {
  Array.prototype.reduce = function reduce(accumulator){
        var i, l = this.length, curr;

        if(typeof accumulator !== "function") // ES5 : "If IsCallable(callbackfn) is false, throw a TypeError exception."
          throw new TypeError("First argument is not callable");

        if((l == 0 || l === null) && (arguments.length <= 1))// == on purpose to test 0 and false.
          throw new TypeError("Array length is 0 and no second argument");

        if(arguments.length <= 1){
          curr = this[0]; // Increase i to start searching the secondly defined element in the array
          i = 1; // start accumulating at the second element
        }
        else{
          curr = arguments[1];
        }

        for(i = i || 0 ; i < l ; ++i){
          if(i in this)
            curr = accumulator.call(undefined, curr, this[i], i, this);
        }

        return curr;
      };
  }



// decimal arithmetic
function decimal_mul(a, b)
{
    return (Math.round(parseFloat(a) * 100) * Math.round(parseFloat(b) * 100) / 10000);
}

function decimal_add(a, b)
{
    return ((Math.round(parseFloat(a) * 100) + Math.round(parseFloat(b) * 100)) / 100);
}

function decimal_sub(a, b)
{
    return ((Math.round(parseFloat(a) * 100) - Math.round(parseFloat(b) * 100)) / 100);
}

function decimal_sum(arr)
{
    return arr.reduce(function(x, y, index, array) {
        return decimal_add(x, y);
    });
}

