﻿// JScript File
var FOR_PURCHASE = 1
var FOR_QUOTE = 2
var FOR_QUOTE_AND_PURCHASE = 4

//Function to do totals on matrix order form
function GetTotal(txtQtyID, txtTotalID, Price)
{
    var Quantity = document.getElementById(txtQtyID).value;
    var Total = parseInt(Quantity) * 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 = "";
    }
}

function qtyField() {
    this.fieldID = "";
    this.minQty = 0;
    this.Property1 = "";
    this.Property2 = "";
    this.getValue = function() { return document.getElementById(this.fieldID).value; }
    this.checkMin = function() {
        var curVal = document.getElementById(this.fieldID).value;
        if (isNaN(curVal) || curVal == '') {
            alert("The quantity specified for the " + this.Property1 + " / " + this.Property2 + " option is not valid");
            return false;
        } else if (curVal < this.minQty) {
            alert("The " + this.Property1 + " / " + this.Property2 + " option requires a minimum quantity of " + this.minQty)
            document.getElementById(this.fieldID).value = this.minQty;
            return false
        }
        return true;
    }
}

function getQtyField(id, min, prop1, prop2) {
    var fieldVal = new qtyField();
    fieldVal.fieldID = id; fieldVal.minQty = min; fieldVal.Property1 = prop1; fieldVal.Property2 = prop2;
    return fieldVal;
}

function OrderFormMinQty(hdnQtyID, qtyFields){
    try{
        var MinQty = document.getElementById(hdnQtyID).value;
        MinQty = (MinQty == '') ? 0 : MinQty;
        var total = 0;
        var fieldMinFailed = false;
        if(qtyFields.length != null){
            for(i=0; i<qtyFields.length; i++){
                var fieldVal = qtyFields[i].getValue();
                if(fieldVal != '' && !isNaN(fieldVal)){
                    total += parseInt(fieldVal, 10);
                    if (!qtyFields[i].checkMin()) {fieldMinFailed = true;}
                }
            }
            if(total < MinQty)
                alert("This product requires a total quantity of " + MinQty + ".")
        }                       
        if(total < 1)
            alert("Please select at least one product.")
    }catch(e){alert(e.message)}
    return (total >= MinQty && total > 0 && !fieldMinFailed);
}

//Function to populate 2nd dropdown box.
function selectChange(controlID, controlToPopulateID, DropdownText, DropdownGroup, DropdownValues, HiddenChildFieldID)
{
	var myEle;
	var x;
	var control = document.getElementById(controlID);
	var controlToPopulate = document.getElementById(controlToPopulateID);
	var isSelected = false;
	
	//make sure fields are not disabled
	control.disabled = false;
	controlToPopulate.disabled = false;

	// Empty the second drop down box of any choices
	for (var q=controlToPopulate.options.length;q>=0;q--) 
		controlToPopulate.options[q]=null;


	// Now loop through the array of individual items
	// Any containing the same child id are added to
	// the second dropdown box

    if (control.value != '') {
        for (x = 0; x < DropdownText.length; x++) {
            if (DropdownGroup[x] == control.value) {
                myEle = CreateOption(DropdownText[x], DropdownValues[x])

                //set hidden value field
                if (!isSelected) {
                    myEle.setAttribute("selected", "true")
                    document.getElementById(HiddenChildFieldID).value = DropdownValues[x];
                    isSelected = true;
                }

                //Add element
                controlToPopulate.appendChild(myEle);
            }
        }
    } else {
        var noneText = control[control.selectedIndex].firstChild.nodeValue;
        var myEl = CreateOption(noneText, '');
        controlToPopulate.appendChild(myEl)
    }	    
		
	//Second dropdown has been filled--now a new item has been selected, update accordingly
	controlToPopulate.onchange();
}

function CreateOption(text, value) {
    var retVal = document.createElement("option");
    retVal.setAttribute("value", value);
    var txt = document.createTextNode(text);
    retVal.appendChild(txt);
    return retVal;
}

//Function to fill in available quantity field for selectors
function SetQuantity(DropdownID, MinimumID, txtQuantityID, QuantityValues, DropdownValues, DropdownMinimums, DisplayBoxID)
{
    //get refereneces to controls
    var ddlControl = document.getElementById(DropdownID);
    var txtControl = document.getElementById(txtQuantityID);
    var txtMinimum = document.getElementById(MinimumID);
    var txtDisplay = null
    if(DisplayBoxID != '')
        txtDisplay = document.getElementById(DisplayBoxID);
    
    //Loop through available quantites
    for(i=0; i < QuantityValues.length; i++)
    {    
        //if value matches control value, then fill in field
        if(DropdownValues[i] == ddlControl.value)
        {        
            try{    
                if(txtControl && txtControl.value)
                    txtControl.value = QuantityValues[i];
                if(txtMinimum && txtMinimum.value)
                    txtMinimum.value = DropdownMinimums[i];
                if(txtDisplay && txtDisplay.value)
                    txtDisplay.value = DropdownMinimums[i];
            }catch(err){
                //alert(err.description);
            }
        }
    }
}

//Function to fill in available quantity hidden field for selectors to enforce quantities
function SetHiddenQuantity(DropdownID, txtQuantityID, QuantityValues, DropdownValues, DropdownMinimums)
{
    //get refereneces to controls
    var ddlControl = document.getElementById(DropdownID);
    var txtControl = document.getElementById(txtQuantityID);
    
    //xxx get references to min/max
    
    //Loop through available quantites
    for(i=0; i < QuantityValues.length; i++)
    {    
        //if value matches control value, then fill in field
        if(DropdownValues[i] == ddlControl.value)
        {        
            try{    
                txtControl.value = QuantityValues[i];
            }catch(err){
                //alert(err.description);
            }
        }
    }
}

//Function to fill in pricing info on Pricing control
function LoadPricing(txtPriceID, DropdownID, DropdownValues, DropdownPrices)
{
    //get refereneces to controls
    var ddlControl = document.getElementById(DropdownID);
    var txtControl = document.getElementById(txtPriceID);
    
    //Loop through available quantites
    for(i=0; i < DropdownPrices.length; i++)
    {    
        //if value matches control value, then fill in field
        if(DropdownValues[i] == ddlControl.value)
        {        
            try{    
                txtControl.value = "$" + parseFloat(DropdownPrices[i]).toFixed(2); 
            }catch(err){
                //alert(err.description);
            }
        }
    }
}

//defines a sample button
function ButtonDefinition(){
    this.regImg = null;
    this.freeImg = null;
    this.regText = null;
    this.freeText = null;
    
    this.isOK = function () {return typeof(this.regImg) != 'nothing' && typeof(this.freeImg) != 'nothing' && this.regText != '' && this.freeText != ''}    
    this.init = function (regSrc, freeSrc, regTxt, freeTxt) {
        this.regImg = new Image;
        this.regImg.src = regSrc;
        this.freeImg = new Image;
        this.freeImg.src = freeSrc;
        this.regText = regTxt;
        this.freeText = freeTxt;
    }
}


//Function to swap in and out the price blocks on the selector style form.
function ShowPricing(DropdownID, DropdownValues, DropdownPricing, DropdownSample, RequestSampleID, ForceReload, Avail, FieldName, FormButtons, RequestQuoteID, AddToCartID, FreeSamp, objSampBtn)
{
    var PriceCount = 0;
    var ButtonCount = 0;
    
    //get control
    var selControl = document.getElementById(DropdownID); 
    
    //hide all pricing
    for(PriceCount=0; PriceCount < DropdownPricing.length; PriceCount++)
        document.getElementById(DropdownPricing[PriceCount]).style.display = "none";

    //If (none), hide all the buttons and leave
    if (selControl.value == "") {
        if(document.getElementById(RequestSampleID))
            SetDisplayStyle(RequestSampleID, 'none');
        if(document.getElementById(AddToCartID))
            SetDisplayStyle(AddToCartID, 'none');
        if (document.getElementById(RequestQuoteID))
            SetDisplayStyle(AddToCartID, 'none');
        return 0;        
    }
        
    //display the correct one 
    for(PriceCount=0; PriceCount < DropdownPricing.length; PriceCount++)
    {
        //if the value matches the control, show the field
        if(DropdownValues[PriceCount] == selControl.value)
        {
            try{
                //show the pricing block
                document.getElementById(DropdownPricing[PriceCount]).style.display = '';    
                //show/hide the Request Sample button
                if(document.getElementById(RequestSampleID))
                {
                    if(DropdownSample[PriceCount] == true)
                        SetDisplayStyle(RequestSampleID, '');                
                    else
                        SetDisplayStyle(RequestSampleID, 'none');
                }
                //show/hide add to cart
                if(document.getElementById(AddToCartID))
                {
                    if(Avail[PriceCount] == FOR_PURCHASE || Avail[PriceCount] == FOR_QUOTE_AND_PURCHASE)
                        SetDisplayStyle(AddToCartID, '');
                    else
                        SetDisplayStyle(AddToCartID, 'none');
                }
                //Show/hide request quote
                if(document.getElementById(RequestQuoteID))
                {
                    if(Avail[PriceCount] == FOR_QUOTE || Avail[PriceCount] == FOR_QUOTE_AND_PURCHASE)
                        SetDisplayStyle(RequestQuoteID, '');
                    else
                        SetDisplayStyle(RequestQuoteID, 'none');
                }
                //update the sample button's config if it's OK
                if (typeof(objSampBtn) != 'undefined' && objSampBtn.isOK() ){
                    var btnQuote = document.getElementById(RequestSampleID)
                    var btnSurvQuote = document.getElementById(RequestSampleID.replace("ibtn", "ibtnSurvey"))
                    
                    try{
                    if(FreeSamp[PriceCount]){
                        //free sample
                        btnQuote.src = objSampBtn.freeImg.src
                        btnQuote.setAttribute("alt",objSampBtn.freeText)
                        if(btnSurvQuote){
                            btnSurvQuote.src = objSampBtn.freeImg.src
                            btnSurvQuote.setAttribute("alt",objSampBtn.freeText)}
                    }else{
                        //billable
                        btnQuote.src = objSampBtn.regImg.src
                        btnQuote.setAttribute("alt",objSampBtn.regText)
                        if(btnSurvQuote){
                            btnSurvQuote.src = objSampBtn.regImg.src
                            btnSurvQuote.setAttribute("alt",objSampBtn.regText)}}
                    }catch(err){}
                }
                //handle reload if required
                if(ForceReload[PriceCount])
                {
                    //lock all buttons
                    var ButtonCount = 0;
                    for(ButtonCount=0; ButtonCount < FormButtons.length; ButtonCount++)
                    {
                        try
                        {
                            if(document.getElementById(FormButtons[ButtonCount]))
                                document.getElementById(FormButtons[ButtonCount]).disabled = true;
                        }
                        catch(e){}
                    }
                    __doPostBack(FieldName,'MatrixChildChanged_' + selControl.value);
                }
            }catch(err)
            {
                //alert(err.description);
                return false;
            }
        }
    }
    
    
}

function SetDisplayStyle(ID, disp)
{
    //set an object's display
    document.getElementById(ID).style.display = disp;
    
    var intIndex = ID.indexOf("ibtn")
    
    if(intIndex >=0){
        var NewID = ID.replace("ibtn", "ibtnSurvey")
        if(document.getElementById(NewID)){
            document.getElementById(NewID).style.display = disp;
        }
    }    
}

//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;
}

//swaps out the order forms for the hybrid style
function hybridSwap(selVal, arrTables){
    try{
        var i=0;
        var reClean = /[^A-Za-z0-9]/g;
        for(i=0;i<arrTables.length;i++){
            var tblIdParts = arrTables[i].split("_");
            if(tblIdParts[tblIdParts.length -1] == selVal.replace(reClean,""))
                document.getElementById(arrTables[i]).style.display = '';
            else
                document.getElementById(arrTables[i]).style.display = 'none';                
        }
    }catch(err){alert(err.message);}
}

//Verifies that a product has been selected from the matrix property dropdowns
function verifyMatrixSelected(Property1ID, Property2ID, LabelID) {
    var bolProdSelected = true;
    try {
        var Property1Selector = $('#' + Property1ID);
        var Property2Selector = $('#' + Property2ID);
        var lblDisplay = $('#' + LabelID);
        var errMsg = ""
        
        if (Property1Selector.val() == '') {
            var PropertyName = Property1Selector.parent().prev().children('span').html()
            errMsg = PropertyName + '<br />'
            bolProdSelected = false;
        }
        if (Property2Selector.val() == '') {
            var PropertyName = Property2Selector.parent().prev().children('span').html()
            errMsg = errMsg + PropertyName + '<br />'
            bolProdSelected =false
        }

        if (!bolProdSelected) {
            lblDisplay.html(errMsg)
            var pnlPop = lblDisplay.parent()
            pnlPop.dialog({ modal: true, resizable: false });

            lblDisplay.next().bind('click', function(evt) {
                $(evt.target).parent().parent().dialog('destroy');
            })                       
        }
    } catch (err) {alert(err.message);}
    return bolProdSelected;
}
