jQuery(document).ready(function($) {
    // Do jQuery stuff using $
    function isDefined(variable) {
        return (typeof (window[variable]) == "undefined") ? false : true;
    }

    var jQelementPrefix = ""; //originally intended to speed selection of elements by being more specific, but actually made everything slower

    var curCaseSize = $('form#infinityModel #inputCaseSize').val();
    var curOutput = $('form#infinityModel #chart').val();

    function disableOptionsByCaseSizeOrOutput() { //Goes through and disabled any options not compatible with the particular case
        // console.time("disableOptionsByCaseSizeOrOutput");
        //create an array of checked options
        var aAllOpts = $(jQelementPrefix + ".optionsList input");

        for (y = 0; y < aAllOpts.length; y++) {
            //Current option by its prefix
            curOption = $(aAllOpts[y]).attr("id");

            //Creates name of Javascript variable to see if particular option has limitations (listed at end of this doc.)
            curOptionList = 'opt' + curOption;
            if (isDefined(curOptionList)) //Checks to see if it has limitations
            {
                curRadioGroup = $(aAllOpts[y]).attr("name");
                caseList = eval(curOptionList);
                for (i = 0; i < caseList.length; i++) {
                    //oCheckOption = $(jQelementPrefix + '#' + caseList[i]);
                    if (caseList[i] == curCaseSize || caseList[i] == curOutput) {
                        setOptionToDisabled(curOption);
                        break;
                    }
                }
            }
        }
        // console.timeEnd("disableOptionsByCaseSizeOrOutput");
    }

    function checkDependentOptions() {
        // console.time("checkDependentOptions");

        //Loop through array of options dependent on other options
        for (i = 0; i < dependentOpts.length; i++) {
            var disableCurOption = true;
            var allowedAsOnlyOption = false;
            // Loop through option suffixes to see if this option can remain enabled
            for (j = 0; j < dependentOpts[i].reqs.length; j++) {
                if (dependentOpts[i].reqs[j] != "none") {
                    if ($(jQelementPrefix + '#' + dependentOpts[i].reqs[j] + ':checked').length > 0) {
                        disableCurOption = false;
                        break;
                    }
                } else {
                    allowedAsOnlyOption = true;
                }
            }
            if (allowedAsOnlyOption && disableCurOption) {
                // check to see if there are no options but itself selected
                disableCurOption = false; //enable option assuming it is the only option selected and begin checking for others
                var option_groups = {}
                $(".optionsList input").each(function() { //get list of all group names
                    option_groups[this.name] = true;
                })
                var numberOfSelOptions = 0; //keep track of number of selected options
                for (group in option_groups) { //loop through groups for values
                    var groupValueId = $("input[name=" + group + "]:checked").val();
                    if (groupValueId != "" && groupValueId != undefined) { //found one with a value
                        numberOfSelOptions++;
                        if (numberOfSelOptions > 1) // can only be selected with no option, so if more than one, disable
                        {
                            disableCurOption = true;
                            break;
                        }
                        var selectedOptionSuffix = $('.optionsList input[value=' + groupValueId + ']').attr("id");
                        if (selectedOptionSuffix != dependentOpts[i].suffix) { //if the enabled option is not itself, disable
                            disableCurOption = true;
                            break;
                        }
                    }
                }
            }
            //console.info("allowedAsOnlyOption = " + allowedAsOnlyOption)
            //console.info("length = " + $(jQelementPrefix + ".optionsList input:checked").length)
            //console.info("id = " + $(jQelementPrefix + ".optionsList input:checked").attr("id"))

            if (disableCurOption) {
                setOptionToDisabled(dependentOpts[i].suffix);
            }
        }
        // console.timeEnd("checkDependentOptions");
    }

    function checkOptions() {  //Checks all options on the page to make sure selected options didn't disable or enable any other options
        // console.time("checkOptions");

        //enable all items initially
        $(jQelementPrefix + ".optionsList .disabled input").each(function() {
            $(this).removeAttr("disabled");
            $(this).closest(".disabled").removeClass("disabled");
        });
        //First, disable options by case-size limitations
        disableOptionsByCaseSizeOrOutput();

        //create an array of checked options
        var aSelectedOpts = $(jQelementPrefix + ".optionsList input:checked");

        for (z = 0; z < aSelectedOpts.length; z++) {
            curOption = $(aSelectedOpts[z]).attr("id"); // input's id = option suffix
            if (curOption.substring(0, 2).toLowerCase() != "no") { //avoids checking if selected option is 'none'.
                // get item's group name
                var curGroupName = $(aSelectedOpts[z]).attr("name");
                // get value of group
                var selectedOptionID = $(jQelementPrefix + "input[name$='" + curGroupName + "']:checked").attr("id");

                //Creates name of Javascript variable to see if particular option has limitations (listed at end of this doc.)
                var selectedOption = 'opt' + selectedOptionID;
                //console.info("selectedOption = " + selectedOption);

                if (isDefined(selectedOption)) //Checks to see exception list exists and, if so, get the array values
                {
                    exceptionList = eval(selectedOption);
                    for (i = 0; i < exceptionList.length; i++) {
                        if (exceptionList[i].toUpperCase() != 'LM6A') {
                            //console.info('#' + exceptionList[i] + " should be disabled");
                            //objException = $(jQelementPrefix + '#' + exceptionList[i].toUpperCase()); // current radio button to disable
                            //$(objException).closest('tr').addClass('disabled');
                            //$(objException).attr("disabled", "disabled");
                            setOptionToDisabled(exceptionList[i].toUpperCase());
                        }
                    }

                }
            }
        }
        checkDependentOptions();
        getVersion();
        // console.timeEnd("checkOptions");
    }

    function setOptionToDisabled(optionSuffix) {
        // console.time("setOptionToDisabled");
        //console.info("Disable " + optionSuffix);
        optionToDisable = $(jQelementPrefix + '#' + optionSuffix);

        // Add classes and attr to elements to not allow selection
        $(optionToDisable).closest('tr').addClass('disabled');
        $(optionToDisable).attr("disabled", "disabled");

        //Checks the selected value of radio group and if it is the current one that is now disabled, select "None" option
        if ($(jQelementPrefix + '#' + optionSuffix + ':checked').length > 0) {
            curRadioGroup = $(optionToDisable).attr("name");
            $(jQelementPrefix + "input[name$='" + curRadioGroup + "']").eq(0).attr("checked", true); //check the "None" option.
            $(optionToDisable).attr('checked', false); //uncheck checkbox.
        }
        // console.timeEnd("setOptionToDisabled");

    }

    function getVersion() { //updates Version Model Number and its pricing
        // console.time("getVersion");
        var versionNumber = $("input#baseModel").val(); //Grabs the base model number to create version model number
        var modelQty = $(jQelementPrefix + "#modelQty input").val();
        var price = $(jQelementPrefix + "#basePrice").html();
        var optionPrices = new Array();
        var optionValues = new Array();
        var accPrice = 0;
        var selectedOptionIds = "";

        // Gets the price of all the selected accessories
        /*$(jQelementPrefix + "tr.accTr").each(function() {
        var accQty = $(jQelementPrefix + "#" + $(this).attr("id") + " .accQty").val();
        if (!isNaN(accQty)) {// If a valid number, add to price.
        accPrice += $(jQelementPrefix + "#" + $(this).attr("id") + " .accPrice").html() * $(jQelementPrefix + "#" + $(this).attr("id") + " .accQty").val();
        } else {// If NaN, reset to nothing.
        $(jQelementPrefix + "#" + $(this).attr("id") + " .accQty").val("");
        }
        });*/

        bOneTimeCharge = false;
        $(jQelementPrefix + "#so").val("0");

        //Gets list of all the selected options
        $(jQelementPrefix + ".optionsList input:checked, .headerRow input:checkbox:checked").each(function() {
            if ($(this).val() != "") {
                //creates list of option IDs
                selectedOptionIds += "," + $(this).val();

                // Shoves in the option name into an array
                optionValues.push($(this).attr("id"));

                // gets options cost (for display purposes only)
                //optionPricing = parseFloat($(jQelementPrefix + "#" + $(this).attr("id") + "price, " + jQelementPrefix + "#" + $(this).attr("name") + "price").html()); 
                optionPricing = parseFloat($(jQelementPrefix + "#" + $(this).attr("name") + "price").html());
                if (isNaN(optionPricing)) {
                    optionPricing = parseFloat($(jQelementPrefix + "#" + $(this).attr("id")).closest("tr").children("td.prices").children("." + $(this).attr("name") + "price").html());
                    //console.info("$('" + jQelementPrefix + "#" + $(this).attr("id")+").closest(\"tr\").children(\"td.prices\").children(\".option" + $(this).attr("name") + "price').html()");
                    //console.info("$(this) = " + $(this).attr("id"));
                    //console.info("optionPricing = " + optionPricing);
                }
                //checks for one-time fee to be added (for display purposes only)
                oneTimeCharge = $(jQelementPrefix + "#" + $(this).val() + "price, " + jQelementPrefix + "#" + $(this).attr("name") + "price").closest(".headerRow").next(".headerRow").children("em").eq(0).children("span").html();
                if (oneTimeCharge != null && oneTimeCharge != "") {
                    bOneTimeCharge = true;
                    $(jQelementPrefix + "#so").val("1");
                }
                if (optionPricing > 0 && optionPricing != null) {
                    optionPrices.push(optionPricing);
                }
            }
        });
        optionValues.sort();
        if (selectedOptionIds.length > 0) {
            selectedOptionIds = selectedOptionIds.substr(1);
        }
        curOptionGroup = ""
        //versionPrice = price + accPrice;
        versionPrice = price;

        // Concatenate the options for the version model number 
        for (i = 0; i < optionValues.length; i++) {
            nextOptionGroup = optionValues[i].substring(0, 1);
            if (nextOptionGroup != curOptionGroup) {
                curOptionGroup = nextOptionGroup;
                optionToAdd = optionValues[i];
            } else {
                optionToAdd = optionValues[i].substr(1);
            }
            versionNumber += optionToAdd;
        }
        for (i = 0; i < optionPrices.length; i++) {
            versionPrice = parseFloat(versionPrice) + parseFloat(optionPrices[i]);
        }
        if (bOneTimeCharge) {
            versionPrice += 35;
        }
		
        if (modelQty > 0) {
            versionPrice = versionPrice * modelQty;
        }
        // Add version


        $(jQelementPrefix + "#versionNumber").html("<h2>" + versionNumber + "</h2>");
        $(jQelementPrefix + "input#hfVersionModel").val(versionNumber);
        $(jQelementPrefix + "input#hfOptions").val(selectedOptionIds);
        $(jQelementPrefix + "#subTotal").html("<h2><strong>$" + versionPrice + "</strong></h2>");
        if (bOneTimeCharge) {
            $(jQelementPrefix + "#subTotal").append("<span style='font-size: 10px;'>*One-Time charge added.</span>");
        }
        //console.info("version = " + version);
        // console.timeEnd("getVersion");
    }

    // List of options NOT available with listed options
    optA1 = ['wide-l-goldbox-infinity-t', 'C9'];
    optA3 = ['wide-l-goldbox-infinity-t'];
    optA4 = ['single-l-goldbox-infinity-t'];
    optB1 = ['B4', 'K5', 'L2', 'LM6A'];
    optB2 = ['B5', 'C8', 'L2'];
    optB3 = ['C8'];
    optB4 = ['B1', 'B9', 'C8', 'LM6A'];
    optB5 = ['B2'];
    optB6 = ['C8', 'E6'];
    optB8 = ['C8', 'L2'];
    optB9 = ['B4', 'C8', 'L2', 'LM6A'];
    optC5 = ['single-l-goldbox-infinity-t', 'C9'];
    optC6 = ['single-l-goldbox-infinity-t', 'C9'];
    optC8 = ['B2', 'B3', 'B4', 'B6', 'B8', 'B9', 'E6', 'L1', 'L2', 'L3'];
    optC9 = ['wide-l-goldbox-infinity-t', 'A1', 'J3'];
    optA3 = ['wide-l-goldbox-infinity-t'];
    optE5 = ['wide-l-goldbox-infinity-t'];
    optE6 = ['B6', 'C8', 'L1', 'L2', 'L3'];
    optG3 = ['wide-l-goldbox-infinity-t'];
    optG4 = ['wide-l-goldbox-infinity-t'];
    optG5 = ['H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'H7', 'H8'];
    optH1 = ['G5'];
    optH2 = ['G5'];
    optH3 = ['G5'];
    optH4 = ['G5'];
    optH5 = ['G5'];
    optH6 = ['G5'];
    optH7 = ['G5'];
    optH8 = ['G5'];
    optJ3 = ['wide-l-goldbox-infinity-t', 'E5', 'C5', 'C6', 'C9'];
    optK5 = ['B1', 'LM6A'];
    optL1 = ['C8', 'E6'];
    optL2 = ['B1', 'B2', 'B8', 'B9', 'C8', 'E6'];
    optL3 = ['C8', 'E6'];

    // List of options REQUIRING other options to be selected first;
    // Single vs Wide requirements are listed in the NOT available options list above
    // add 'none' if the option can can also be selected with no options selected.
    var dependentOpts = [
        { suffix: "E5",
            reqs: ['B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B8', 'B9', 'D1', 'D2', 'F1', 'K6']
        }
    ];


    checkOptions();
    $(jQelementPrefix + '.optionsList input, ' + jQelementPrefix + 'input[type=checkbox]').each(function() {
        $(this).click(function() {
            checkOptions();
        });
    });

    $(jQelementPrefix + "tr.accTr input.accQty, " + jQelementPrefix + "#modelQty input").change(function() {
        checkOptions();
    });
});

