﻿// JScript File

//functions to enforce minimum/maximum quantities
function EnforceMinimum(txtQtyID, hdnMaxID, hdnMinID, BackOrderBehavior, blnIsSample, hdnIsExpiredID)
{
    //Constants
    var BACK_ORDER_ALLOW = 1
    var BACK_ORDER_WARN = 0
    var BACK_ORDER_DISALLOW = 2
        
    //Field objects
    var txtQty = document.getElementById(txtQtyID);
    var hdnMax = document.getElementById(hdnMaxID);
    var hdnMin = document.getElementById(hdnMinID);
    if (document.getElementById(hdnIsExpiredID).value == 'true') { BackOrderBehavior = BACK_ORDER_DISALLOW; }
        
    //Variables
    var intCurrentQty = 0;
    var intMax = 0;
    var intMin = 0;

    //Check for empty quantity
    if (txtQty.value == '') {
        alert("Please fill in a valid quantity.");
        txtQty.value = 1;
        return false;
    }
    //check for isNaN
    if(isNaN(txtQty.value))
    {
        //Quantity is not valid.
        alert("'" + txtQty.value + "' is not a valid quantity.");
        txtQty.value = 1;
        return false;
    }    
    else
    {
        //handles negative numbers--negative quantities should not occur.
        if(hdnMax.value < 0 || isNaN(hdnMax.value))
        {
            hdnMax.value = 0;
        }
        if(hdnMin.value < 0 || isNaN(hdnMin.value))
        {
            hdnMin.value = 0;
        }  
        
        //Fill in variables 
        intCurrentQty = parseInt(txtQty.value);
        intMax = parseInt(hdnMax.value);
        if(!blnIsSample)
        {
            intMin = parseInt(hdnMin.value);
        }
        else
        {
            //Min is 1 for samples
            intMin = 1;
        }

                   
        //Check for invalid quantity 
        if(intCurrentQty < intMin && (intMin < intMax || BackOrderBehavior != BACK_ORDER_DISALLOW))
        {
            //if quantity is less than minimum and less than maximum, reset to minimum and notify.
            txtQty.value = intMin;
            
            alert("You must order at least " + intMin + " of this product.");
            
            return false;
        }    
        else if(intCurrentQty > intMax)
        {
            if(BackOrderBehavior == BACK_ORDER_DISALLOW)
            {
                //if backorder is not allowed, set quantity to max.
                txtQty.value = intMax;
                
                if(hdnMax.value != 1)
                {
                    alert("We're sorry.  There are only " + Number(intMax) + " available.");
                }
                else
                {
                    alert("We're sorry.  There is only 1 available.");
                }
                return false;
            }        
            else if(BackOrderBehavior == BACK_ORDER_WARN)
            {            
            
                //if backorder is allowed but warn is on, do not change quantity but notify that
                //additional quantities will be backordered
                if(intMax != 1)
                {
                    alert("We're sorry.  There are only " + Number(intMax) + " available. Any more will be placed on back order.");
                }
                else
                {
                    alert("We're sorry.  There is only 1 available.  Any more will be placed on back order.");
                }       
            }
        }
    }
    
    //No errors flagged; allow submission to continue
    return true;    
}


/**************************************************/
//Price Level Objects
/**************************************************/
//Object for Price Levels in order form
function PriceLevel() {
    this.lowerBound = 0
    this.upperBound = 0
    this.price = 0
}

//Creates a new price level object so that it can be added in one tidy line.
function GenerateLevel(intLowerBound, intUpperBound, dblPrice) {
    var newLevel = new PriceLevel();
    newLevel.lowerBound = intLowerBound;
    newLevel.upperBound = intUpperBound;
    newLevel.price = dblPrice;
    return newLevel;
}

//Object to wrap an entire set of pricelevels
function PriceLevels() {
    this.productID = 0
    this.arrLevels = new Array();
    this.addLevel = pl_AddLevel;
    this.getPrice = pl_GetPrice;
}

//Member function for the Price Levels object.
//Adds a price level to the array inside the Price Levels object
function pl_AddLevel(PriceLevel) {
    this.arrLevels[this.arrLevels.length] = PriceLevel
}

//Member function of the Price Levels object.
//Looks up a price from the Price Levels based on the quantity.
function pl_GetPrice(qty) {
    try {
        var intLvlCount = 0;
        if (this.arrLevels.length > 0) {
            if (qty < this.arrLevels[0].lowerBound)
                return this.arrLevels[0].price;
            for (intLvlCount = 0; intLvlCount < this.arrLevels.length; intLvlCount++) {
                if (this.arrLevels[intLvlCount].lowerBound <= qty && (isNaN(this.arrLevels[intLvlCount].upperBound) || this.arrLevels[intLvlCount].upperBound >= qty)) {
                    return this.arrLevels[intLvlCount].price;
                }
            }
            return this.arrLevels[this.arrLevels.length - 1].price;
        } else {
            return 0;
        }
    } catch (e) {
        alert(e.message);
    }
    //Failure state; return nothing
    return 0;
}


//Update product total
function GetTotal(txtQtyID, txtTotalID, Price) {
    try {
        var Quantity = document.getElementById(txtQtyID).value;
        var Total = parseInt(Quantity, 10) * parseFloat(Price);

         //If the amount is greater than zero, display in matrix.
        if (Quantity != 0 && Price != 0 && !isNaN(Total)) {
            document.getElementById(txtTotalID).value = "$" + Total.toFixed(2);
        }
        else {
            if (isNaN(Total) && document.getElementById(txtQtyID).value != "") {
                alert("'" + Quantity + "' is not a valid quantity");
                document.getElementById(txtQtyID).value = "";
            }
            document.getElementById(txtTotalID).value = "";
        }
    } catch (ex) { alert('Error in GetTotal: ' + ex.message); }
}

//Update Unitprice and product total
function UpdatePriceandTotal(txtQtyID, txtUnitPriceID, txtPriceID, txtTotalID, txtLnkCharges, pID) {

    var $qty = $('#' + txtQtyID);

    if ($qty.length == 0 || isNaN($qty.val()) || parseFloat($qty.val()) <= 0) {
        alert("Quantity must be greater than 0.");
        return;
    }
     
    $.get("/AJAX.aspx", { IsCompass: 'True', fn: 'GetProductSubTotals', productID: pID, clientID: 0, quantity: $qty.val() })
        .success(function(result) {
            //get result of linked price
            var $res = $(result);
            if ($res.length != 0) {
                //call func to update textboxes
                var $children = $res.children();

                var item = document.getElementById(txtUnitPriceID);
                if (item !== null) { item.value = "$" + parseFloat($children.children('unitprice').text()).toFixed(2); }

                item = document.getElementById(txtPriceID);
                if (item !== null) { item.value = "$" + parseFloat($children.children('price').text()).toFixed(2); }

                item = document.getElementById(txtTotalID);
                if (item !== null) { item.value = "$" + parseFloat($children.children('subtotal').text()).toFixed(2); }

                item = document.getElementById(txtLnkCharges);
                if (item !== null) { item.value = "$" + parseFloat($children.children('charges').text()).toFixed(2); }
                
            }
            else {
                //set everything to 0 if got nothign back
                 var item = document.getElementById(txtUnitPriceID);
                if (item !== null) { item.value = "$0.00"; }

                item = document.getElementById(txtPriceID);
                if (item !== null) { item.value = "$0.00"; }

                item = document.getElementById(txtTotalID);
                if (item !== null) { item.value = "$0.00"; }

                item = document.getElementById(txtLnkCharges);
                if (item !== null) { item.value = "$0.00"; }
            }
        })
        .error(function(result, status, err) {
            //since we didn't get any totals, just update the values to 0
            var item = document.getElementById(txtUnitPriceID);
            if (item !== null) { item.value = "$0.00"; }

            item = document.getElementById(txtPriceID);
            if (item !== null) { item.value = "$0.00"; }

            item = document.getElementById(txtTotalID);
            if (item !== null) { item.value = "$0.00"; }

            item = document.getElementById(txtLnkCharges);
            if (item !== null) { item.value = "$0.00"; }
            
        });

}

function UpdateMatrixSubtotal(orderFormTableID, pID) {
    //get linked charges for product

    $.get("/AJAX.aspx", { IsCompass: 'True', fn: 'GetLinkedChargesTotal', productID: pID, clientID: 0 })
        .success(function(result) {
            //get result of linked price
            var $res = $(result);
            if ($res.length != 0) {
                //call func to update textboxes
                cb_UpdateMatrixSubtotal(orderFormTableID, parseFloat($res.children().first().text()));
            }
        })
        .error(function(result, status, err) {
            //since we didn't get the charge total, just update the other values
            cb_UpdateMatrixSubtotal(orderFormTableID, 0);
        });
    
}

//Update Unitprice and product total for hybrid and standard order forms
function cb_UpdateMatrixSubtotal(orderFormTableID, chargeTotal) {

    //get table (going straight to the <tbody> element)
    var $Table = $(document.getElementById(orderFormTableID)).children();
    if ($Table.length == 0) { return; }

    //check for sub total and exit if it's not in here
    var $subTotal = $Table.find('input[type=text].SubTotalDisplayTextBox');
    if ($subTotal.length == 0) { return; }

    var total = 0;

    $Table.children('tr.trMatrixPriceRow').each(function() {
        //get text box value and add to total 
        var $txt = $(this).children().eq(5).children().first();
        if ($txt.length != 0 && $txt.val() != "") {
            total += parseFloat($txt.val().replace("$", ""));
        }
        $txt = null;
    });

    if (isNaN(chargeTotal)) { chargeTotal = 0; }

    //set Price
    $Table.children('tr.trSubPrice').children().last().children().first().val('$' + total.toFixed(2));

    //set charge total
    $Table.children('tr.trAddlCharges').children().last().children().first().val('$' + chargeTotal.toFixed(2));
    
    //set sub total value
    $subTotal.val("$" + (chargeTotal + total).toFixed(2));

    $subTotal = null;
    $Table = null;

}


