var currPizzaNum = 0;
// Assume start at #0
var crustArray = new Array;
var specialtyArray = new Array;
var drinkArray = new Array;
var extraArray = new Array;
var defaultinstructsaucetype = new Array;
var defaultinstructsauceportion = new Array;
var defaultinstructcheese = new Array;
var defaultinstructbake = new Array;
var defaultinstructcut = new Array;
var defaultinstructpepperoni = new Array;
var defaultinstructtomato = new Array;
var instructsaucetype = new Array;
var instructsauceportion = new Array;
var instructcheese = new Array;
var instructbake = new Array;
var instructcut = new Array;
var instructpepperoni = new Array;
var instructtomato = new Array;
var currToppingType = 0;
//initialize to add toppings to whole pizza
var imagePath = "images/";
var toppingsPath = imagePath + "toppings/";
var maxSingleTopping = 2;
var maxPizzas = 20;
var numToppingLocs = 7;
// Assume 7 absolute max toppings
var origDefCrust = new Array;
var origDefSpecialty = new Array;
var submitCount = 0;
var items = new Array(20);
var numItems;
var tops = new Array(2000);
var origSpecialty = new Array;
var halfReplaceLimit = 4;
var defaultCrust = new Array;
var defaultSpecialty = new Array;
var defaultToppings = new Array;
var origToppings = new Array;
var specialty = new Array;
var specialtyTops = new Array;
var numToppingsAllowed = new Array;
var minToppingsAllowed = new Array;
// deals may require non zero minimum
var numReplaceTops = new Array;
var numRemoveTops = new Array;
var specialtyTopsList = new Array;
var pizzaSauceList = new Array;
var canAddTopFlag = new Array;
var extraToppingPriceEnabledFlag = new Array;
var defaultDrink = new Array;
var defaultExtra = new Array;

for (var i = 0; i < 2000; i++) {
    tops[i] = "--";
    // Blank the topping
}

function initCrust() {
    for (var i = 0; i < maxPizzas; i++) {
        crustArray[i] = defaultCrust[i];
    }
}


function initSpecialty() {

    for (var i = 0; i < maxPizzas; i++) {
        specialtyArray[i] = defaultSpecialty[i];
    }

}


function initializePage() {

    currPizzaNum = 0;
    var defaultFound = 0;


    for (i = 0; i < specialty.length; i++) {
        if (specialty[i] != null && specialty[i] != "") {
            origSpecialty[i] = specialty[i];

            // add to default specialty code
            updatePizzaForSpecialty(i, specialty[i]);
            //            testAlert("pizzaSauceList[0] = " + pizzaSauceList[0]);
            //            updateSauceType(i);
        }
    }
    if (numPizzas > 0) {
        loadPizza(defaultToppings, currPizzaNum);
    }
    var elementsLength = document.Pizza.elements.length;


    var i = 0;
    while (i < elementsLength) {
        //selectType = getSelectType(document.Pizza.elements[i].name);
        //alert(" selectType = " + document.Pizza.elements[i].name );

        if (document.Pizza.elements[i].name.substring(0, 5) == "drink") {
            var selectLength = document.Pizza.elements[i].length;
            drinkNumber = document.Pizza.elements[i].name.substring(5);
            defaultFound = 0;
            if (selectLength > 0) {
                for (j = 0; j < selectLength; j++) {
                    if (document.Pizza.elements[i][j].value == defaultDrink[drinkNumber]) {
                        defaultFound = 1;
                        document.Pizza.elements[i][j].selected = true;
                        handle_select(document.Pizza.elements[i].name);
                    }
                }
            } else {
                drinkArray[drinkNumber] = document.Pizza.elements[i].value;
            }
            if (selectLength > 0 && defaultFound == 0) {
                document.Pizza.elements[i][0].selected = true;
                handle_select(document.Pizza.elements[i].name);
            }
        }
        if (document.Pizza.elements[i].name.substring(0, 5) == "extra") {
            var selectLength = document.Pizza.elements[i].length;
            extraNumber = document.Pizza.elements[i].name.substring(5);
            defaultFound = 0;
            if (selectLength > 0) {
                for (j = 0; j < selectLength; j++) {
                    if (document.Pizza.elements[i][j].value == defaultExtra[extraNumber]) {
                        defaultFound = 1;
                        document.Pizza.elements[i][j].selected = true;
                        handle_select(document.Pizza.elements[i].name);
                    }
                }
            } else {
                extraArray[extraNumber] = document.Pizza.elements[i].value;
            }
            if (selectLength > 0 && defaultFound == 0) {
                document.Pizza.elements[i][0].selected = true;
                handle_select(document.Pizza.elements[i].name);
            }
        }
        if (document.Pizza.elements[i].name.substring(0, 5) == "instr")
        {
            var value = document.Pizza.elements[i].value;
            var defaultStr;

            if (document.Pizza.elements[i].name.substring(0, 11) == "instructcut")
            {
                defaultStr = defaultinstructcut[0];
            }
            else if (document.Pizza.elements[i].name.substring(0, 17) == "instructsaucetype")
            {
                defaultStr = defaultinstructsaucetype[0];
            }
            else if (document.Pizza.elements[i].name.substring(0, 20) == "instructsauceportion")
            {
                defaultStr = defaultinstructsauceportion[0];
            }
            else if (document.Pizza.elements[i].name.substring(0, 14) == "instructcheese")
            {
                defaultStr = defaultinstructcheese[0];
            }
            else if (document.Pizza.elements[i].name.substring(0, 12) == "instructbake")
            {
                defaultStr = defaultinstructbake[0];
            }
            else if (document.Pizza.elements[i].name.substring(0, 17) == "instructpepperoni")
            {
                defaultStr = defaultinstructpepperoni[0];
            }
            else if (document.Pizza.elements[i].name.substring(0, 14) == "instructtomato")
            {
                defaultStr = defaultinstructtomato[0];
            }
            if (value != defaultStr)
            {
                handle_select(document.Pizza.elements[i].name);
            }
            //alert(" value = " + value);
            //alert(" defaultStr = " + defaultStr);


        }


        i++;
    }
}

function updatePizzaForSpecialty(aPizzaNum, aPizzaCode) {
    var s = specialtyTopsList[aPizzaNum];

    while (s.length > 0) {
        var specialtyInfo = getNextParseItem(s, ",");
        s = s.substring(specialtyInfo.length + 1);
        var pizza = getNextParseItem(specialtyInfo, "~");
        specialtyInfo = specialtyInfo.substring(pizza.length + 1);
        var pizzaCode = getNextParseItem(pizza, ":");
        if (aPizzaCode == pizzaCode) {
            var newToppings = new Array;
            newToppings[aPizzaNum] = pizza.substring(pizzaCode.length + 1);
            loadPizza(newToppings, aPizzaNum);
            specialty[aPizzaNum] = pizzaCode;
            specialtyTops[aPizzaNum] = newToppings[aPizzaNum];
            specialtyNumTopsAllowed = getNextParseItem(specialtyInfo, "~");
            specialtyInfo = specialtyInfo.substring(specialtyNumTopsAllowed.length + 1);
            specialtyNumRemoveTops = getNextParseItem(specialtyInfo, "~");
            specialtyInfo = specialtyInfo.substring(specialtyNumRemoveTops.length + 1);
            specialtyNumReplaceTops = getNextParseItem(specialtyInfo, "~");
            if (specialty[aPizzaNum] != 'CYO') {
                numToppingsAllowed[aPizzaNum] = specialtyNumTopsAllowed;
                numRemoveTops[aPizzaNum] = specialtyNumRemoveTops;
                numReplaceTops[aPizzaNum] = specialtyNumReplaceTops;

            }


            //            testShowPizzaParms();
        }
        if (s.length == 0) {
            break;
        }
    }
}

function updateSauceType() {
    var curPizzaType = defaultCrust[currPizzaNum] + defaultSpecialty[currPizzaNum];

    var sauceInstructName = "instructsaucetype" + currPizzaNum;
    var s = pizzaSauceList[currPizzaNum];

    while (s != null && s.length > 0) {
        var sauceInfo = getNextParseItem(s, ",");
        s = s.substring(sauceInfo.length + 1);
        var pizzaType = getNextParseItem(sauceInfo, ":");
        sauceInfo = sauceInfo.substring(pizzaType.length + 1);


        if (pizzaType == curPizzaType) {
            if (document.Pizza[sauceInstructName]) {
                document.Pizza[sauceInstructName].length = 0;
                var defaultSauceType = getNextParseItem(sauceInfo, ":");
                sauceInfo = sauceInfo.substring(defaultSauceType.length + 1);
                var sauceList = sauceInfo;
                // Load sauce instructions from sauceInfo.
                i = 0;
                while (sauceList.length > 0) {
                    var sauceCode = getNextParseItem(sauceList, "|");
                    sauceList = sauceList.substring(sauceCode.length + 1);
                    document.Pizza[sauceInstructName].length = i + 1;
                    document.Pizza[sauceInstructName].options[i].value = sauceCode;
                    document.Pizza[sauceInstructName].options[i].text = getSauceOption(sauceCode);
                    i++;
                }
            } else {
            }
            break;
        }
        if (s.length == 0) {
            break;
        }

    }
    // while

}

function getSauceOption(sauceCode) {
    for (var i = 0; i < sauceList.length; i++) {
        var code = sauceList[i][0];
        //        testAlert("code = " + code);
        if (sauceCode == code) {
            return sauceList[i][1];
        }
    }
}

function loadCrustSetting(s, PizzaNum) {
    crustType = new Array;
    var maxlength = 10;
    var position = 0;
    // parse the crust selection string passed from the html file
    while (s.length != 0) {
        var s1 = getNextParseItem(s, ",");
        var crustCode = getNextParseItem(s1, "|");
        var crustDesc = getNextParseItem(s1.substring(crustCode.length + 1), "|");
        if (s.length == s1.length) {
            // Parsed string is the last one
            s = s.substring(s1.length);
        } else {
            s = s.substring(s1.length + 1);
        }
        crustType[position] = crustDesc;
        position++;
    }
}

function getNextParseItem(s, terminator) {
    var result = "";
    if (s != null && s != "") {
        if (s.indexOf(terminator) < 0) {
            result = s;
        }
        else {
            result = s.substring(0, s.indexOf(terminator));
        }
        return result;
    }
}


function handle_select(selectName) {
    var itemtoadd;
    selectType = getSelectType(selectName);
    selectLetter = selectName.substring(0, 1);
    var itemNum = selectName.substring(selectType.length, selectName.length);
    // todo: change for > 10 items


    //var elementsLength=document.Pizza.elements.length;
    //alert ( "handle_select elementslength = " + elementsLength);

    //var i = 0;
    //while (i < elementsLength)
    //{
    //     selectType = getSelectType(document.Pizza.elements[i].name);
    //     alert("handle_select selectType = " + selectType );
    //    i++;

    //}

    for (var i = 0; i < document.Pizza.elements.length; i++) {
        if (document.Pizza.elements[i].name == selectName) {
            if (selectType == "beverage") {
                drinkArray[itemNum] = document.Pizza.elements[i].value;
            } else if (selectType == "extra") {
                extraArray[itemNum] = document.Pizza.elements[i].value;
            } else if (selectType == "crust") {
                currPizzaNum = itemNum;
                var crustValue = document.Pizza.elements[i].value;
                crustArray[itemNum] = crustValue;
                // this is what saves the current crust size
                defaultCrust[itemNum] = crustArray[itemNum];
                updateSauceType();
            } else if (selectType == "specialty") {
                currPizzaNum = itemNum;
                specialtyValue = document.Pizza.elements[i].value;
                specialtyArray[itemNum] = specialtyValue;
                defaultSpecialty[itemNum] = specialtyArray[itemNum];
                updateSauceType();
                var s = specialtyTopsList[currPizzaNum];
                while (s.length > 0) {
                    var specialtyInfo = getNextParseItem(s, ",");
                    s = s.substring(specialtyInfo.length + 1);
                    var pizza = getNextParseItem(specialtyInfo, "~");
                    specialtyInfo = specialtyInfo.substring(pizza.length + 1);
                    var pizzaCode = getNextParseItem(pizza, ":");
                    if (document.Pizza.elements[i].value == pizzaCode) {
                        var newToppings = new Array;
                        newToppings[currPizzaNum] = pizza.substring(pizzaCode.length + 1);
                        loadPizza(newToppings, currPizzaNum);
                        specialty[currPizzaNum] = pizzaCode;
                        specialtyTops[currPizzaNum] = newToppings[currPizzaNum];
                        specialtyNumTopsAllowed = getNextParseItem(specialtyInfo, "~");
                        numToppingsAllowed[currPizzaNum] = specialtyNumTopsAllowed;
                        specialtyInfo = specialtyInfo.substring(specialtyNumTopsAllowed.length + 1);
                        specialtyNumRemoveTops = getNextParseItem(specialtyInfo, "~");
                        numRemoveTops[currPizzaNum] = specialtyNumRemoveTops;
                        specialtyInfo = specialtyInfo.substring(specialtyNumRemoveTops.length + 1);
                        specialtyNumReplaceTops = getNextParseItem(specialtyInfo, "~");
                        numReplaceTops[currPizzaNum] = specialtyNumReplaceTops;
                        //                        testShowPizzaParms();
                    }
                    if (s.length == 0) {
                        break;
                    }

                }
            } else if (selectType == "whole" || selectType == "first" || selectType == "second") {
                itemtoadd = document.Pizza.elements[i].value;
                if (selectLetter == "w") {
                    addItem(itemtoadd, 0, itemNum);
                } else if (selectLetter == "f") {
                    addItem(itemtoadd, 1, itemNum);
                } else if (selectLetter == "s") {
                    addItem(itemtoadd, 2, itemNum);
                }
                document.Pizza.elements[i][0].selected = true;
                hideInstructions(itemNum);
                window.focus();
            }
            else if (selectType == "instructsaucetype") {
                instructsaucetype[itemNum] = document.Pizza.elements[i].value;
            } else if (selectType == "instructsauceportion") {
                instructsauceportion[itemNum] = document.Pizza.elements[i].value;
            } else if (selectType == "instructcheese") {
                instructcheese[itemNum] = document.Pizza.elements[i].value;
            } else if (selectType == "instructbake") {
                instructbake[itemNum] = document.Pizza.elements[i].value;
            } else if (selectType == "instructcut") {
                instructcut[itemNum] = document.Pizza.elements[i].value;
            } else if (selectType == "instructpepperoni") {
                instructpepperoni[itemNum] = document.Pizza.elements[i].value;
            } else if (selectType == "instructtomato") {
                instructtomato[itemNum] = document.Pizza.elements[i].value;
            }
        }
    }
}

function getSelectType(selectName) {
    var offset = (selectName.length) - 1;
    var s = selectName.substring(selectName.length - 2, selectName.length - 1);
    var isNumber = (s >= "0" && s <= "9");
    if (isNumber) {
        offset--;
    }
    return selectName.substring(0, offset);
}

function loadPizza(defaultTops, aPizzaNum) {
    currPizzaNum = aPizzaNum;
    emptyPizza(currPizzaNum);
    currToppingType = 0;
    defTypeParse = defaultTops[currPizzaNum];
    var nextTop = "";
    var nextStr = defTypeParse;


    while (defTypeParse.indexOf(":") >= 0) {
        nextStr = getNextParseItem(defTypeParse, ":");
        var nextCount = 0;
        baseNum = (currPizzaNum * 100) + (currToppingType * 10);
        defTopsParse = nextStr;
        nextTop = getNextParseItem(defTopsParse, "|")
        while (nextTop != null && nextTop != "") {
            defTopsParse = defTopsParse.substring(nextTop.length + 1);
            tops[baseNum + nextCount] = nextTop;
            nextCount++;
            nextTop = getNextParseItem(defTopsParse, "|")
        }
        defTypeParse = defTypeParse.substring(nextStr.length + 1);
        currToppingType++;
    }
    displayTops();
}
// loadPizza

// displayTops -- Display Toppings
function displayTops() {
    var name = "";
    var nameNum = 0;
    var topName = "";
    for (var i = 0; i < document.images.length; i++) {
        name = document.images[i].name;
        if (name.length == 4 && name.substr(0, 1) == "T") {
            nameNum = parseInt(name.substr(1, 3), 10);
            topName = document.images[i].src;

            topName = topName.substring(topName.lastIndexOf("/") + 1);
            if (topName != getToppingImageName(tops[nameNum])) {
                document.images[i].src = toppingsPath + getToppingImageName(tops[nameNum]);
            }
        }
        if (name.length == 5 && name.substr(0, 1) == "T") {
            nameNum = parseInt(name.substr(1, name.length - 1), 10);
            topName = document.images[i].src;

            topName = topName.substring(topName.lastIndexOf("/") + 1);
            if (topName != getToppingImageName(tops[nameNum])) {
                document.images[i].src = toppingsPath + getToppingImageName(tops[nameNum]);
            }
        }


    }
}

function displaySauceList() {
    var sauceName = "";
    var result = "";
    result = "Available Sauces\n";
    for (var i = 0; i < sauceList.length; i++) {
        sauceName = sauceList[i][0] + ": " + sauceList[i][1];
        result += sauceName + "\n";
    }
    alert(result);
}

function addItem(aTopping, toppingType, pizzaNum) {
    var s = canAddTopping(aTopping, toppingType, pizzaNum);
    currToppingType = toppingType;
    currPizzaNum = pizzaNum;
    if (s != "") {
        alert(s);
    } else {
        var nextTopNum = getNextTopNum(currPizzaNum, currToppingType);
        addTopping(aTopping, nextTopNum);
        defaultToppings[currPizzaNum] = getPizzaToppingString(currPizzaNum);
    }
    adjustTops();
    displayTops();
    //test_showTopsAll(currPizzaNum)
}

// Return a blank string if addition of the topping is allowed using the business rules, else return error message.
function canAddTopping(aTopping, toppingType, pizzaNum) {
    var result = "";
    // Assume success
    var toppingCount;
    var replaceCount;
    // No more than {maxSingleTopping} toppings of same type
    currToppingType = toppingType;
    currPizzaNum = pizzaNum;
    toppingLimit = getToppingLimit(currPizzaNum);
    if (currToppingType == 0) {
        toppingCount = getToppingCount(currPizzaNum) + 1;
    } else {
        toppingCount = getToppingCount(currPizzaNum) + .5;
    }

    if (getSingleToppingCount(aTopping, toppingType, pizzaNum) > maxSingleTopping) {
        var toppingName = getToppingName(aTopping);
        return "You may only have " + maxSingleTopping + " of the same topping.  " +
               "You may not add a topping of " + toppingName.substring(0, toppingName.length - 1) + " to the " +
               getDecodeToppingType(currToppingType) + ".";
    }
    // Limit to five toppings per half.
    if (getToppingCountForHalf(currPizzaNum) > 7) {
        if (currToppingType == 0) {
            return "You may not add any more whole toppings to the pizza. ";
        } else {
            return "You may not add any more toppings to this half."
        }
    }


    var canAddFlag = canAddTopFlag[currPizzaNum];
    var extraPriceEnabled = extraToppingPriceEnabledFlag[currPizzaNum];


    if (canAddFlag == "false" || extraPriceEnabled == "false")
    {
        if (toppingCount > toppingLimit)
        {
            if (toppingLimit == 1)
            {
                return "You may not have more than 1 topping on either half of this pizza.";
            }
            else
            {
                return "You may not have more than " + getToppingLimit(currPizzaNum) + " toppings on either half of this pizza.";
            }
        }
    }


    var nextTopNum = getNextTopNum(currPizzaNum, currToppingType);
    if (nextTopNum == -1) {
        return getToppingFullMsg(currPizzaNum, currToppingType);
    }
    /*if (isReplaceTop(currPizzaNum, aTopping)){
        if (currToppingType == 0) {
            replaceCount = getReplaceCount(currPizzaNum) + 1;
        } else {
            replaceCount = getReplaceCount(currPizzaNum) + .5;
        }
    }
    if (replaceCount > numReplaceTops[currPizzaNum]) {
        return "You cannot replace more than " + numReplaceTops[currPizzaNum] + " whole toppings on this pizza.";
    } else if (origToppings[currPizzaNum] != "" && countToppingsForHalf(1, currPizzaNum) + countToppingsForHalf(2, currPizzaNum) >= halfReplaceLimit){
        return "You cannot have more than " + halfReplaceLimit + " half toppings on this pizza.";
    } */
    return "";
}

function countToppingsForHalf(aToppingType, aPizzaNum) {
    var halfCount = 0;
    var baseNum = (100 * aPizzaNum) + (10 * aToppingType);
    for (var i = baseNum; i <= baseNum + 9; i++) {
        if (isTopping(tops[i])) {
            halfCount++
        }
    }
    return halfCount;
}


function countOriginalTops(aPizzaNum) {
    var toppingCount = 0;
    var topString = specialtyTops[aPizzaNum];
    var nextTop = getNextParseItem(topString, "|");
    while (nextTop != null) {
        var toppingCounted = false;
        for (var i = 0; i < 3; i++) {
            var baseNum = (100 * aPizzaNum) + (10 * i);
            for (j = baseNum; j <= baseNum + 9; j++) {
                if (nextTop == tops[j]) {
                    if (!toppingCounted) {
                        if (i == 0) {
                            toppingCount++;
                        } else {
                            toppingCount += .5;
                        }
                    }
                    toppingCounted = true;
                    break;
                }

            }

        }
        topString = topString.substring(nextTop.length + 1);
        nextTop = getNextParseItem(topString, "|");

    }
    return toppingCount;
}

function canRemoveTopping(toppingType, pizzaNum, aTopNum) {
    var result = "";
    // Assume success
    var toppingCount;
    currPizzaNum = pizzaNum;
    currToppingType = toppingType;
    if (numToppingsAllowed[currPizzaNum] - countOriginalTops(currPizzaNum) >= numRemoveTops[currPizzaNum]) {
        if (!isReplaceTop(currPizzaNum, tops[aTopNum]) && !isDoubleTop(currPizzaNum, tops[aTopNum])) {
            if (currToppingType == 0) {
                return "You may not remove any more whole toppings from the pizza. ";
            } else {
                return "You may not remove any more toppings from this half."
            }
        }
    }
    return "";
}


function isDoubleTop(aPizzaNum, aTopping) {
    var BaseNum = aPizzaNum * 100;
    var cnt = 0;
    for (var i = BaseNum; i <= BaseNum + 29; i++) {
        if (isTopping(tops[i])) {
            var oneCount = getSingleToppingCount(aTopping, Math.floor((i - BaseNum) / 10), aPizzaNum) - 1;
            cnt = getSingleToppingCount(aTopping, Math.floor((i - BaseNum) / 10), aPizzaNum) - 1;
            if (cnt > 1) {
                if (!doubleTopOk(aPizzaNum, aTopping)) {
                    return true;
                }
            }
        }
    }
    return false;
}

function doubleTopOk(aPizzaNum, aTopping) {
    var cnt = 0;
    var topString = specialtyTops[aPizzaNum];
    var nextTop = getNextParseItem(topString, "|");
    while (nextTop != null) {
        topString = topString.substring(nextTop.length + 1);
        if (nextTop == aTopping) {
            cnt++;
        }
        nextTop = getNextParseItem(topString, "|");
    }
    if (cnt >= 2) {
        return true;
    }
    return false;
}


function countDoubleTops(aPizzaNum) {
    var BaseNum = aPizzaNum * 100;
    var DoubleTops = 0;
    for (var i = BaseNum; i <= BaseNum + 29; i++) {
        if (isTopping(tops[i])) {
            if (isDoubleTop(aPizzaNum, tops[i])) {
                DoubleTops++;
            }
        }
    }
    return DoubleTops / 2;
}

function getSingleToppingCount(aTopping, aToppingType, pizzaNum) {
    // returns the max topping count for a half after the addition.
    currPizzaNum = pizzaNum;
    currToppingType = aToppingType;
    var baseNum = currPizzaNum * 100
    var count1st = 0;
    var count2nd = 0;
    // Count toppings
    for (var i = baseNum; i <= baseNum + 29; i++) {
        toppingType = Math.floor((i - baseNum) / 10);
        // another Safari 3.0.4 hack
        if (tops[i] == aTopping && tops[i] != "") {
            if (toppingType == 0 || toppingType == 1)
                count1st++;
            if (toppingType == 0 || toppingType == 2)
                count2nd++;
        }
    }
    // Add count for topping being added
    if (currToppingType == 0) {
        count1st++;
        count2nd++;
    }
    else if (currToppingType == 1) {
        count1st++;
    }
    else if (currToppingType == 2) {
        count2nd++;
    }
    // Return maximum count for a half
    if (count2nd > count1st) {
        return count2nd;
    }
    return count1st;
}

function getToppingCountForHalf(aPizzaNum) {
    // returns the max topping count for a half after the addition.
    var baseNum = currPizzaNum * 100
    var count1st = 0;
    var count2nd = 0;
    var toppingType = 0;

    // Count toppings
    for (var i = baseNum; i <= baseNum + 29; i++) {
        toppingType = Math.floor((i - baseNum) / 10);
        if (isTopping(tops[i])) {
            if (toppingType == 0 || toppingType == 1)
                count1st++;
            if (toppingType == 0 || toppingType == 2)
                count2nd++;
        }
    }

    // Add count for topping to be added
    if (currToppingType == 0) {
        count1st++;
        count2nd++;
    }
    else if (currToppingType == 1) {
        count1st++;
    }
    else if (currToppingType == 2) {
        count2nd++;
    }
    // Return maximum count for a half
    if (count2nd > count1st) {
        return count2nd;
    }
    return count1st;
}

function getToppingLimit(aPizzaNum) {
    if ((numToppingsAllowed[aPizzaNum] == null) || (numToppingsAllowed[aPizzaNum] == "")) {
        return 7;
    } else {
        return numToppingsAllowed[aPizzaNum];
    }
}

//gets the next open position in tops array
function getNextTopNum() {
    var baseNum = currPizzaNum * 100 + currToppingType * 10;
    var rtnValue = -1;
    for (var i = 0; i < numToppingLocs; i++) {
        if (tops[baseNum + i] == "--" || tops[baseNum + i] == "") {
            rtnValue = i;
            break;
        }
    }
    return rtnValue;
}


function getToppingFullMsg(aPizzaNum, aToppingType) {
    if (aToppingType == 0) {
        return "You cannot add any more toppings";
    }
    else if (aToppingType == 1) {
        return "You cannot add any more toppings on the first half of the pizza";
    }
    else { // (aToppingType == 2)
        return "You cannot add any more toppings on the second half of the pizza";
    }
}

//adds the topping to the tops array
function addTopping(aTopping, nextTopNum) {
    var topNum = currPizzaNum * 100 + currToppingType * 10 + parseInt(nextTopNum);
    tops[topNum] = aTopping;
}

//gets the image names for the toppings to correctly display the pizza
function getToppingImageName(aTopping) {
    var s = getToppingName(aTopping);
    var i = s.indexOf(" ");
    while (i != -1) {
        s = s.substring(0, i) + s.substring(i + 1, s.length);
        i = s.indexOf(" ");
    }
    s = s.toLowerCase();
    if (s == "unknown") {
        s = "transparentblank";
    }
    return s + ".gif";
}

//assigns image name according to topping code (i.e. TA is Anchovies)
function getToppingName(topCode) {

        //case "TP4": return "X-Treme Cheese";

    switch (topCode) {
        case "TA":  return "Anchovies2";
        case "TB":  return "Beef2";
        case "TD":  return "Linguica Sausage2";
        case "TF":  return "Italian Salami2";
        case "TG":  return "Green Peppers2";
        case "TH":  return "Ham2";
        case "TI":  return "Spicy Italian Sausage";
        case "TJ":  return "Jalapeno Peppers2";
        case "TK":  return "Bacon2";
        case "TM":  return "Mushrooms2";
        case "TMB":  return "Meatballs";
        case "TN":  return "Pineapple2";
        case "TO":  return "Onions2";
        case "TP":  return "Pepperoni2";
        case "TQ":  return "Red Peppers";
        case "TR":  return "Black Olives2";
        case "TS":  return "Sausage2";
        case "TT":  return "Fresh Tomatoes2";
        case "TV":  return "Green Olives2";
        case "TZ":  return "Banana Peppers2";
        case "TE":  return "Chicken";
        case "TY":  return "greenchiles";
        case "TXC": return "Extra Cheese2";
        case "T3":  return "Provolone";
        case "T5":  return "Steak";
        case "T1":  return "Sweet Sausage";
        case "T2":  return "Smoked Sausage";
        case "TIH": return "Italian Ham";
        case "TRO": return "Red Onions";
        case "TTS": return "Sundried Tomato";
        case "TCL": return "Roasted Garlic";
        case "TAH": return "Artichoke Hearts";
        case "TSK": return "Sauerkraut";
        case "T3C": return "ThreeCheese";
        case "TZE": return "ZestySalami";
        case "TTd": return "Diced Tomato";
        case "TX3": return "Extra Three Cheese";
        case "TP4": return "xtremecheese";
        case "TGa": return "freshgarlic";
        case "TSp": return "freshspinach";
        case "T2c": return "parmesanramanocheese";
        case "TCb": return "canadianbacon";
        case "--":  return "Unknown";
        default:    return "Unknown";
    }
}

function getDecodeToppingType(aToppingType) {
    if (aToppingType == 0) {
        return "whole pizza";
    }
    else if (aToppingType == 1) {
        return "1st half of the pizza";
    }
    else if (aToppingType == 2) {
        return "2nd half of the pizza";
    }
}

function removeItem(aToppingType, aTopNum, pizzaNum) {
    var topstr = "";
    currPizzaNum = pizzaNum;
    currToppingType = aToppingType;
    var topNum = currPizzaNum * 100 + currToppingType * 10 + parseInt(aTopNum);
    var s = canRemoveTopping(currToppingType, currPizzaNum, topNum);
    if (s != "") {
        alert(s);
    } else {
        tops[topNum] = "--";
        cleanCurrToppings();
        defaultToppings[currPizzaNum] = getPizzaToppingString(currPizzaNum);
        displayTops();
    }
    hideInstructions(pizzaNum);
}

// Cleanup the current topping type
function cleanCurrToppings() {
    var baseNum = currPizzaNum * 100;
    for (var i = baseNum; i <= baseNum + 29; i++) {
        //  if (i % 10 != 9 && isTopping(tops[i]) && tops[i + 1] != "--") {
        if (i % 10 != 9 && tops[i] == "--" && tops[i + 1] != "--") {
            swapTops(i);
            // Swap empty topping with next
        }
    }
}

// Swap a topping with the next topping
function swapTops(aTopNum) {
    var s = tops[aTopNum];
    tops[aTopNum] = tops[aTopNum + 1];
    tops[aTopNum + 1] = s;
}

// Adjust toppings (combine halves into a whole topping)
function adjustTops() {
    var baseNum = currPizzaNum * 100;
    for (var i = baseNum + 10; i <= baseNum + 19; i++) {
        if (isTopping(tops[i])) {
            for (var j = baseNum + 20; j < baseNum + 30; j++) {
                if (tops[j] == tops[i]) {
                    // Delete halves and put into whole
                    for (var k = baseNum; k < baseNum + 10; k++) {
                        if (tops[k] == "--" || tops[k] == "") {
                            tops[k] = tops[i];
                            // Add to whole
                            tops[i] = "--";
                            // Delete from 1st half
                            tops[j] = "--";
                            // Delete from 2nd half
                            cleanCurrToppings();
                            return;
                        }
                    }
                }
            }
        }
    }
}

function displaySizeAndCrust(crustCode) {
    switch (crustCode) {
        case "PR10": return "Small Regular (" + crustCode + ")";
        case "PR14": return "Large Regular (" + crustCode + ")";
        case "PR16": return "Extra Large Regular (" + crustCode + ")";
        case "PT14": return "Large Thin (" + crustCode + ")";
        default:     return "Unknown crust and size";
    }
}

function test_showTopsAll() {
    var msg = "Current Pizza:\n";
    var s = "";
    for (var p = 0; p < numPizzas; p++) {
        msg += "Pizza #" + p + ": " + displaySizeAndCrust(crustArray[p]) + "\n";
        for (var i = p * 100; i < (p * 100) + 30; i += 10) {
            s = "";
            for (var j = 0; j < numToppingLocs; j++) {
                s = s + tops[i + j] + "|";
            }
            msg = msg + s + "\n";
        }
    }
    testAlert(msg);
}

function testShowPizzaParms() {
    testAlert("testShowPizzaParms: specialty[currPizzaNum] = " + specialty[currPizzaNum] +
              ", specialtyTops[currPizzaNum] = " + specialtyTops[currPizzaNum] +
              ", numToppingsAllowed[currPizzaNum] = " + numToppingsAllowed[currPizzaNum] +
              ", minToppingsAllowed[currPizzaNum] = " + minToppingsAllowed[currPizzaNum] +
              ", numRemoveTops[currPizzaNum] = " + numRemoveTops[currPizzaNum] +
              ", numReplaceTops[currPizzaNum] = " + numReplaceTops[currPizzaNum]);
}

function testShowInstructs(itemNum) {
    var result = "";
    if (document.Pizza["instructsaucetype" + itemNum]) {
        result += "instructsaucetype[" + itemNum + "] = " + instructsaucetype[itemNum] + "\n";
    }
    result +=
    "instructsauceportion[" + itemNum + "] = " + instructsauceportion[itemNum] + "\n" +
    "instructcheese[" + itemNum + "] = " + instructcheese[itemNum] + "\n" +
    "instructbake[" + itemNum + "] = " + instructbake[itemNum] + "\n" +
    "instructcut[" + itemNum + "] = " + instructcut[itemNum] + "\n";
    if (document.Pizza["instructpepperoni" + itemNum]) {
        result += "instructpepperoni[" + itemNum + "] = " + instructpepperoni[itemNum] + "\n";
    }
    if (document.Pizza["instructtomato" + itemNum]) {
        result += "instructtomato[" + itemNum + "] = " + instructtomato[itemNum] + "\n";
    }
    testAlert(result);
}

function testAlert(s) {
    if (allowTestAlerts != 0) {
        alert(s);
    }
}

function lockSubmit() {
    if (submitCount == 0) {
        submitCount++;
        return true;
    } else {
        return false;
    }
}

//var value = document.Pizza.elements[i].value;
// var defaultStr;

// if (document.Pizza.elements[i].name.substring(0,11) == "instructcut" )
//{
//    defaultStr = defaultinstructcut[0];
//}

function instructString(itemNum) {
    var s = "";
    var useInstructId = "useinstruct" + itemNum;
    //testShowInstructs(itemNum);


    if (document.Pizza[useInstructId]) {
        if (document.Pizza[useInstructId].checked) {


            if (document.Pizza["instructsaucetype" + itemNum])
            {
                if (instructsaucetype[itemNum] != defaultinstructsaucetype[itemNum])
                {
                    s += addPipe(instructsaucetype[itemNum]);
                }
            }
            if (instructsauceportion[itemNum] != defaultinstructsauceportion[itemNum])
            {
                s += addPipe(instructsauceportion[itemNum]);
            }
            if (instructcheese[itemNum] != defaultinstructcheese[itemNum])
            {
                s += addPipe(instructcheese[itemNum]);
            }
            if (instructbake[itemNum] != defaultinstructbake[itemNum])
            {
                s += addPipe(instructbake[itemNum]);
            }
            if (instructcut[itemNum] != defaultinstructcut[itemNum])
            {
                s += addPipe(instructcut[itemNum]);
            }

            if (document.Pizza["instructpepperoni" + itemNum])
            {
                if (instructpepperoni[itemNum] != defaultinstructpepperoni[itemNum])
                {
                    s += addPipe(instructpepperoni[itemNum]);
                }
            }
            if (document.Pizza["instructtomato" + itemNum])
            {
                if (instructtomato[itemNum] != defaultinstructtomato[itemNum])
                {
                    s += addPipe(instructtomato[itemNum]);
                }
            }
        }
    }

    return s;
}

function addPipe(item) {
    var s = "";
    if (!item == "") {
        s = item + "|";
    }

    return s;
}

function addToOrder() {
    if (addToOrderCommon()) {
        if (!lockSubmit()) {
            document.Pizza.submit();
        }
    }
}

function addToOrderAndCheckout() {
    if (addToOrderCommon()) {
        if (!lockSubmit()) {
            document.Pizza.docheckout.value = 1;
            document.Pizza.submit();
        }
    }
}

function doSubmit() {
    if (!lockSubmit()) {
        document.Pizza.submit();
    }
    return false;
}

function addToFavoriteAndExit() {
    lockSubmit();
    if (!lockSubmit()) {
        document.Pizza.submit();
    }
    return false;
}

function addToOrderCommon() {
    var s = "";

        for (var itemNo = 0; itemNo < numItems; itemNo++) {
            var i = getDetailNumber(itemNo);
            var itemType = getDetailItemType(itemNo);
            if (itemType == "pizza") {
                if (getCrustSize(i) == null) {
                    if (origDefCrust[i] == null) {
                        s += "PR14";
                    } else {
                        s += origDefCrust[i];
                    }
                } else {
                s += getCrustSize(i);
            }

            if (specialty[i] == null || specialty[i] == "" || specialty[i] == "CYO") {
                s += "0" + Math.round(getToppingCount(i));
            } else {
                s += specialty[i];
            }
            s += ":" + getPizzaToppingString(i);

        // todo: Remove this as soon as test is over.
            // Fix sandwiches
            if (s.substring(0, 6) == "PW06BT") {
                s = "PW07BT" + s.substring(6, s.length);
            }
            if (s.substring(0, 6) == "PW07BI") {
                s = "PW06BI" + s.substring(6, s.length);
            }

            s += instructString(i) + ":";
            s += "1:&,";
        }
        else if (itemType == "beverage") {
            //        for (var i = 0; i < drinkArray.length; i++) {
            s += drinkArray[i] + ":1:&,";
        }
        else if (itemType == "extra") {
            //        for (var i = 0; i < extraArray.length; i++) {
            s += extraArray[i] + ":1:&,";
        }
    }

//        testAlert("add_to_order: productDetail = " + s);
        document.Pizza.productDetail.value = s;
        return lockSubmit();
    }

function getDetailNumber(itemNo) {
    var itemType = getDetailItemType(itemNo);
    var detailName = items[itemNo];
    var detailNameSplit = detailName.split(itemType);
    return detailNameSplit[1];
}

function getDetailItemType(itemNo) {
    var itemType = "unknown";
    var detailName = items[itemNo];
    if (detailName.indexOf("pizza") >= 0) {
        itemType = "pizza";
    } else if (detailName.indexOf("beverage") >= 0) {
        itemType = "beverage";
    } else if (detailName.indexOf("extra") >= 0) {
        itemType = "extra";
    }

    return itemType;
}

function getCrustSize(aPizzaNum) {
    return crustArray[parseInt(aPizzaNum)];
}


function isTopping(arrVal)
{
    // Safari 3.0.4 fix by checking for "" as well as "--"
    if (arrVal != "--" && arrVal != "")
    {
        return 1;
    }
    else
    {
        return 0;
    }

}

function getPizzaToppingString(aPizzaNum) {
    var s = "";
    var baseNum = aPizzaNum * 100
    // Add whole toppings
    for (var i = baseNum; i <= baseNum + 9; i++) {
        if (isTopping(tops[i])) {
            s += tops[i] + "|";
        }
    }
    // Add 1st half topping
    s += ":";
    for (var i = baseNum + 10; i <= baseNum + 19; i++) {
        if (isTopping(tops[i])) {
            s += tops[i] + "|";
        }
    }
    // Add 2nd half topping
    s += ":";
    for (var i = baseNum + 20; i <= baseNum + 29; i++) {
        if (isTopping(tops[i])) {
            s += tops[i] + "|";
        }
    }
    s += ":";
    return s;
}

function getDetailedToppingCount(aPizzaNum) {
    var detailedToppingCount = {
        whole: 0,
        first: 0,
        second: 0
    };
    var baseNum = aPizzaNum * 100;

    for (var wholeIndex = baseNum; wholeIndex <= baseNum + 9; wholeIndex++) {
        if (isTopping(tops[wholeIndex])) {
            detailedToppingCount.first++;
            detailedToppingCount.second++;
        }
    }
    // Add half topping
    for (var firstHalfIndex = baseNum + 10; firstHalfIndex <= baseNum + 19; firstHalfIndex++) {
        if (isTopping(tops[firstHalfIndex])) {
            detailedToppingCount.first += 1;
        }
    }

    for (var secondHalfIndex = baseNum + 20; secondHalfIndex <= baseNum + 29; secondHalfIndex++) {
        if (isTopping(tops[secondHalfIndex])) {
            detailedToppingCount.second += 1;
        }
    }

    detailedToppingCount.whole = (detailedToppingCount.first + detailedToppingCount.second)/2;

    return detailedToppingCount;
}

function getToppingCount(aPizzaNum) {
    var toppingCount = 0;
    var baseNum = aPizzaNum * 100;
    // Add full topping
    for (var i = baseNum; i <= baseNum + 9; i++) {
        if (isTopping(tops[i])) {
            toppingCount++;
        }
    }
    // Add half topping
    for (var i = baseNum + 10; i <= baseNum + 29; i++) {
        if (isTopping(tops[i])) {
            toppingCount += 0.5;
        }
    }
    return toppingCount;
}

function getReplaceCount(aPizzaNum) {
    var s = getPizzaToppingString(aPizzaNum);
    var replaceCount = 0;
    currToppingType = 0;
    while (s.indexOf(":") >= 0) {
        nextStr = getNextParseItem(s, ":");
        baseNum = (currPizzaNum * 100) + (currToppingType * 10);
        theseTops = nextStr;
        nextTop = getNextParseItem(theseTops, "|")
        while (nextTop != null && nextTop != "") {
            theseTops = theseTops.substring(nextTop.length + 1);
            if (isReplaceTop(aPizzaNum, nextTop)) {
                if (currToppingType == 0) {
                    replaceCount++;
                } else {
                    replaceCount = replaceCount + .5;
                }
            }
            nextTop = getNextParseItem(theseTops, "|")
        }
        s = s.substring(nextStr.length + 1);
        currToppingType++;
    }
    return replaceCount;
}

function isReplaceTop(aPizzaNum, aTopping) {
    specialtyToppings = specialtyTops[currPizzaNum];
    var nextTop = getNextParseItem(specialtyToppings, "|");
    while (nextTop != null && nextTop != "") {
        specialtyToppings = specialtyToppings.substring(nextTop.length + 1);
        if (aTopping == nextTop) {
            return false;
        }
        nextTop = getNextParseItem(specialtyToppings, "|");
    }
    return true;
}

function clearPizza(pizzaNum) {
    currPizzaNum = pizzaNum;
    baseNum = currPizzaNum * 100;
    crustBox = "crust" + pizzaNum;
    selectBox = "specialty" + pizzaNum;
    crustArray[currPizzaNum] = origDefCrust[currPizzaNum];
    specialtyArray[currPizzaNum] = origDefSpecialty[currPizzaNum];
    for (var i = 0; i < document.Pizza.elements.length; i++) {
        if (document.Pizza.elements[i].name == crustBox) {
            for (n = 0; n < document.Pizza.elements[i].length; n++) {
                if (crustArray[currPizzaNum] == document.Pizza.elements[i][n].value) {
                    document.Pizza.elements[i][n].selected = true;
                    handle_select(crustBox);
                }
            }
        }
        if (document.Pizza.elements[i].name == selectBox) {
            for (var n = 0; n < document.Pizza.elements[i].length; n++) {
                if (specialtyArray[currPizzaNum] == document.Pizza.elements[i][n].value) {
                    document.Pizza.elements[i][n].selected = true;
                    handle_select(selectBox);
                }
            }
        }

    }
    for (var i = baseNum; i <= baseNum + 29; i++) {
        tops[i] = "--";
    }
    defaultToppings[currPizzaNum] = "";
    specialty[currPizzaNum] = origSpecialty[currPizzaNum];
    loadPizza(origToppings, currPizzaNum);
    displayTops();
    //  test_showTopsAll(currPizzaNum);
}

function emptyPizza(pizzaNum) {
    currPizzaNum = pizzaNum;
    baseNum = currPizzaNum * 100;
    crustBox = "crust" + pizzaNum;
    for (var i = 0; i < document.Pizza.elements.length; i++) {
        if (document.Pizza.elements[i].name == crustBox) {
            for (n = 0; n < document.Pizza.elements[i].length; n++) {
                if (crustArray[currPizzaNum] == document.Pizza.elements[i][n].value) {
                    document.Pizza.elements[i][n].selected = true;
                    handle_select(crustBox);
                }
            }
        }
    }
    for (i = baseNum; i <= baseNum + 29; i++) {
        tops[i] = "--";
    }
    displayTops();
    //  test_showTopsAll(currPizzaNum);
}

function findElement(aName) {
    var found = false;
    for (var i = 0; i < document.Pizza.elements.length; i++) {
        if (document.Pizza.elements[i].name == aName) {
            found = true;
            break;
        }
    }
}

function hasPepperoni(aPizzaNum) {
    return hasTheTopping(aPizzaNum, "TP");
}

function hasTomato(aPizzaNum) {
    return hasTheTopping(aPizzaNum, "TT");
}

function hasTheTopping(aPizzaNum, aTopping) {
    var result = false;
    var halfCount = 0;
    var baseNum = 0;
    var s = "";
    for (var toppingType = 0; toppingType <= 2; toppingType++) {
        baseNum = (100 * aPizzaNum) + (10 * toppingType);
        for (var i = baseNum; i <= baseNum + 9; i++) {
            if (tops[i] == aTopping) {
                result = true;
                break;
            }
        }
    }

    return result;
}

function hideInstructions(pizzaNum) {
    var instructId = "dealinstruct" + pizzaNum;
    var useInstructId = "useinstruct" + pizzaNum;


    if (document.Pizza[useInstructId]) {
        var useInstructChecked = document.Pizza[useInstructId].checked;
        var state = (useInstructChecked) ? "block" : "none";

        hideToppingInstructions(pizzaNum, "pepperoni", hasPepperoni(pizzaNum) && useInstructChecked);
        hideToppingInstructions(pizzaNum, "tomato", hasTomato(pizzaNum) && useInstructChecked);

        if (document.layers) {
            document.layers[instructId].display = state;
        }
        else if (document.all) {
            document.all[instructId].style.display = state;
        }
        else if (document.getElementById) {
            document.getElementById(instructId).style.display = state;
        }
    }
}

function hideToppingInstructions(pizzaNum, aTopping, isVisible) {
    var instructId = "instruct" + aTopping + pizzaNum;
    if (document.Pizza[instructId]) {
        var visible = (isVisible) ? "visible" : "hidden";
        if (document.getElementById) {
            document.getElementById(instructId).style.visibility = visible;
            // DOM3 = IE5, NS6
        } else if (document.layers) {
            document[instructId].visibility = visible;
            // Netscape 4
        } else {
            document.all[instructId].style.visibility = visible;
            // IE 4
        }
    }

}

function hideToppings(pizzaNum) {
    var toViewId = "updatetoppings" + pizzaNum;
    if (document.Pizza[toViewId]) {
        var toViewChecked = document.Pizza[toViewId].checked;
        var state = (toViewChecked) ? "block" : "none";

        var hideId = "dealtoppinggroup" + pizzaNum;
        if (document.layers) {
            document.layers[hideId].display = state;
        }
        else if (document.all) {
            document.all[hideId].style.display = state;
        }
        else if (document.getElementById) {
            document.getElementById(hideId).style.display = state;
        }
    }

}
// deprecated - no longer used - min toppings reflected in pricing engine on server side
function minimumToppings() {
    var result = "";
    for (var ndx = 0; ndx < numPizzas; ndx++) {
        if (getToppingCount(ndx) < getMinimumToppingCount(ndx)) {
            result = "You must have " + getMinimumToppingCount(ndx) + " toppings on either half of this pizza.";
            break;
        }
    }
    return result;
}

function getMinimumToppingCount(aPizzaNum) {
    return minToppingsAllowed[aPizzaNum];
}
