// Global Variables
var alertJSON;
var alertPackageJSON;
var alertQueue = new Array();  //Holds alerts still needing to be run
var alertObjQueue = new Array();  //Holds alert objects still needing to be run
var triggerId = "";

var DEBUG = false;

// -------------------------------------- Getter / Setter functions ------------------------------------------------- //
function setJSON(json) {
    alertJSON = json;
}

function getJSON() {
    return window.alertJSON;
}

function setPackageJSON(json) {
    alertPackageJSON = json;
}

function getPackageJSON() {
    return window.alertPackageJSON;
}

// Queues for waiting alert information (String)
function setAlertQueue(aQueue) {
   alertQueue = aQueue;
}

function getAlertQueue() {
    return window.alertQueue;
}

// Queues for waiting alert information (JSON Objects)
function setAlertObjQueue(aObjQueue) {
   alertObjQueue = aObjQueue;
}

function getAlertObjQueue() {
    return window.alertObjQueue;
}

// Trigger functions added to give access to each alert box to current trigger id.
function setTriggerId(trigger) {
  triggerId = trigger;   
}

function getTriggerId() {
    return window.triggerId;
}
// ------------------------------------- END Getter / Setter functions ---------------------------------------------- //
//-------------------------------------------- Alert Functions -------------------------------------------------------//
// Function for holding previously selected radio buttons for conflicts
function setRadio(radioSet) {
    if(DEBUG) {alert("Radio Change: " + radioSet +
          "\nPrevious: " + $("#previousRadioOption-" + radioSet).val() +
          "\nCurrent: " + $("#currentRadioOption-" + radioSet).val());
    }

    // Get current selected value
    var curr = $("input[name='optionsRadio[" + radioSet + "]']:checked").val();

    // Set previous option to old current
    $("#previousRadioOption-" + radioSet).attr("value", $("#currentRadioOption-" + radioSet).val());

    // Set new option to current
    $("#currentRadioOption-" + radioSet).attr("value", curr);
}

// Checks to see if there are any alerts in queue and runs the top one if there is
function alertManager() {
    var queue = getAlertQueue();
    var objQueue = getAlertObjQueue();
    /*alert("Alerts: " + queue +
          "\nObjects: " + objQueue);*/

    if(DEBUG) { alert("Alert Queue Length: " + queue.length); }

    // Check to see if there is a waiting alert
    if(queue.length > 0) {
        var alertInfo = queue.pop();
        var alertObj = objQueue.pop();

        // Make sure to reset global queues
        setAlertQueue(queue);
        setAlertObjQueue(objQueue);
    
        var alertParts = alertInfo.split("|");
        //alert("Type: " + alertParts[0] + "\nId: " + alertParts[1] + "\nObject: " + alertObj);

        // Run the current alert
        if (alertParts[0] == "CHOICE") {
            alertCHOICE(alertObj, alertParts[1]);
        } else if(alertParts[0] == "INCLUDE") {
            alertINCLUDE(alertObj, alertParts[1]);
        } else if(alertParts[0] == "CONFLICT") {
            alertCONFLICT(alertObj, alertParts[1]);
        } else if(alertParts[0] == "REPLACE" || alertParts[0] == "REMOVE") {
            alertREPLACE(alertObj, alertParts[1]);
        } else if(alertParts[0] == "Package-CONFLICT") {
            alertPackageCONFLICT(alertObj, alertParts[1]);
        } else if(alertParts[0] == "Package-REPLACE") {
            alertPackageREPLACE(alertObj, alertParts[1]);
        } else {
            // If anything else is passed, skip it and check for more alerts.
            alertManager();
        }
    }
}

function alertCHOICE(objAlert, triggerId) {
    setTriggerId(triggerId);
    if(DEBUG) {
        alert(" -- CHOICE -- \n" +
              "alertNumber: " + objAlert.alertNumber +
              "\nalertType: " + objAlert.alertType +
              "\nchoiceOptional: " + objAlert.choiceOptional +
              "\nchooseAll: " + objAlert.chooseAll +
              "\nmessage: " + objAlert.message);
    }
    var chooseAll = false;
    var choiceOptional = false;

    //Check to see if we need just one checked, or all checked
    if(objAlert.chooseAll) {
        chooseAll = true;
    }

    //Check to see if we need to use radio or checkbox
    if(objAlert.choiceOptional) {
        choiceOptional = true;
    }

    //Check if we need to run alert
    var runAlert = true;
    $.each(objAlert.choices, function(i, choice){
        var option = document.getElementById("option-" + choice.id);

        // Check if option is disabled, if so, assume checked
        var optionDis = false;
        if (option.disabled) {
            optionDis = true;
        }

        //Must have all options checked
        if(chooseAll) {
            //Check if the choice option is selected or not
            if(optionDis || option.checked) {
                if(DEBUG) { alert("ChooseAll - ON\n" + choice.id + " - " + choice.name + "\nTRUE"); }
                //Continue running the check to determine if we need to run the alert
                runAlert = false;
            } else {
                if(DEBUG) { alert("ChooseAll - ON\n" + choice.id + " - " + choice.name + "\nFALSE"); }
                //One is false, will need to run alert
                runAlert = true;
                return false;
            }
        // Only need one selected
        } else {
            if(choiceOptional) {
                // Check if disabled, if disabled ignore this option
                if (!optionDis) {
                    runAlert = true;
                    //should always run alerts on optional as they may want to change options.
                    return false;
                } else {
                    runAlert = false;
                }
            } else {
                //Check if the choice option is selected or not
                if(optionDis || option.checked) {
                    if(DEBUG) { alert("ChooseAll - OFF\n" + choice.id + " - " + choice.name + "\nTRUE"); }
                    //Short circut if true, don't need to run the alert as we have one
                    runAlert = false;
                    return false;
                } else {
                    if(DEBUG) { alert("ChooseAll - OFF\n" + choice.id + " - " + choice.name + "\nFALSE"); }
                    //Continue running the check to determine if we need to run the alert
                }
            }
        }
    });

    if(DEBUG) { alert("runAlert: " + runAlert); }
    //Check results for alert run
    if(runAlert) {
        //Display the populated message.

        //Set alert title
        document.getElementById("alertDialogCHOICE").title = "Alert - CHOICE";

        //Make sure the alert window is empty
        $("#alertDialogCHOICE").empty();

        //Add in message for alert
        $("#alertDialogCHOICE").append("<p id='alertMessagesCHOICE'>" + objAlert.message + "<br /><br /></p>");

        //Add error message location
        $("#alertMessagesCHOICE").append("<span id='alertErrorCHOICE' style='display:none;'></span>");

        //Add the list
        $("#alertDialogCHOICE").append("<ul id='alertDialogListCHOICE'></ul>");

        //Run the each again to populate the alert box
        $.each(objAlert.choices, function(i, choice) {
            var option = document.getElementById("option-" + choice.id);

            // Check if option is disabled, if so don't display that option
            var optionDis = false;
            if (option.disabled) {
                optionDis = true;
            }

            // If option is disabled do not display it
            if (!optionDis) {                            
                // List all options
                if(chooseAll) {
                    $("#alertDialogListCHOICE").append("<li name='alertItemCHOICE' value='" + choice.id + "'>" + choice.name + "</li>");
                } else {
                    // Checkboxes
                    if(choiceOptional) {
                        if(option.checked) {
                            $("#alertDialogListCHOICE").append("<li><input name='alertCheckboxCHOICE' type='checkbox' value='" + choice.id + "' checked />" + choice.name + "</li>");
                        } else {
                            $("#alertDialogListCHOICE").append("<li><input name='alertCheckboxCHOICE' type='checkbox' value='" + choice.id + "' />" + choice.name + "</li>");
                        }
                    // Radio Buttons
                    } else {
                        if(option.checked) {
                            $("#alertDialogListCHOICE").append("<li><input name='alertRadioCHOICE' type='radio' value='" + choice.id + "' checked />" + choice.name + "</li>");
                        } else {
                            $("#alertDialogListCHOICE").append("<li><input name='alertRadioCHOICE' type='radio' value='" + choice.id + "' />" + choice.name + "</li>");
                        }
                    }
                }
            }
        });

        //Run the dialog box
        $("#alertDialogCHOICE").dialog({
            autoOpen: false,
            modal: true,
            draggable: false,
            resizable: false,
            overlay: {
                opacity: 0.5,
                background: "black"
            },
            buttons: {
                "Decline": function() {
                    // Uncheck triggering option
                    $("#option-" + getTriggerId()).attr("checked", false);
                    $("#option-" + getTriggerId()).parent().parent().parent().removeClass('active');
                    $(this).dialog("close");

                    //On decline, clear the alert manager queues as we no longer need to keep running alerts.
                    var clearArray = new Array();
                    setAlertQueue(clearArray);
                    setAlertObjQueue(clearArray);
                },
                "Accept": function() {
                    var dialogWindow = $(this);
                    if(chooseAll) {
                        $("li[name='alertItemCHOICE']").each(function(i, itemAlert){
                            // Set all options to checked
                            $("#option-" + itemAlert.value).attr("checked", true);
                            $("#option-" + itemAlert.value).parent().parent().parent().addClass('active');
                        });
                        $(dialogWindow).dialog("close");

                        //Rerun the manager to check for other alerts
                        alertManager();
                    } else {
                        if(choiceOptional) {
                            // Set all options to what it is now
                            $("input[name='alertCheckboxCHOICE']").each(function(i, checkAlert){
                                if($(checkAlert).is(':checked')) {
                                    $("#option-" + checkAlert.value).attr("checked", true);
                                    $("#option-" + checkAlert.value).parent().parent().parent().addClass('active');
                                } else {
                                    $("#option-" + checkAlert.value).attr("checked", false);
                                    $("#option-" + checkAlert.value).parent().parent().parent().removeClass('active');
                                }
                            }); 
                            $(dialogWindow).dialog("close");

                            //Rerun the manager to check for other alerts
                            alertManager();
                        } else {
                            // Check to ensure at least one element is selected
                            $("input[name='alertRadioCHOICE']").each(function(i, radioAlert){
                               if($(radioAlert).is(':checked')) {
                                    $("#option-" + radioAlert.value).attr("checked", true);
                                    $("#option-" + radioAlert.value).parent().parent().parent().addClass('active');
                                   $(dialogWindow).dialog("close");

                                    //Rerun the manager to check for other alerts
                                    alertManager();
                               } else {
                                   // Set error text and continue with checks for a checked option
                                   $("#alertErrorCHOICE").text("Please select an option");
                               }
                            });

                            // Show error message
                            $("#alertErrorCHOICE").attr("style", "");
                        }
                    }
                }
            }
        });

        $("#alertDialogCHOICE").dialog("open");
    } else {
        //Rerun the manager to check for other alerts
        alertManager();
    }
}

function alertCONFLICT(objAlert, triggerId){
    setTriggerId(triggerId);
    if(DEBUG) {
        alert(" -- CONFLICT -- \n" +
              "alertNumber: " + objAlert.alertNumber +
              "\nalertType: " + objAlert.alertType +
              "\nchoiceOptional: " + objAlert.choiceOptional +
              "\nchooseAll: " + objAlert.chooseAll +
              "\nmessage: " + objAlert.message);
    }
    var chooseAll = false;
    var choiceOptional = false;

    //Check to see if we need just one checked, or all checked
    if(objAlert.chooseAll == "true") {
        chooseAll = true;
    }

    //Check to see if we need to use radio or checkbox
    if(objAlert.choiceOptional == "true") {
        choiceOptional = true;
    }

    //Check if we need to run alert
    var runAlert = true;
    $.each(objAlert.choices, function(i, choice){
        var option = document.getElementById("option-" + choice.id);

        // Check if option is disabled, if so, assume checked
        var optionDis = false;
        if (option.disabled) {
            optionDis = true;
        }

        //Must have all options checked
        if(optionDis || option.checked) {
            if(DEBUG) { alert("-- Conflict -- \n" + choice.id + " - " + choice.name + "\nTRUE"); }
            //If one is checked, make sure to run alert
            runAlert = true;
            return false;
        } else {
            if(DEBUG) { alert("-- Conflict -- \n" + choice.id + " - " + choice.name + "\nFALSE"); }
            //If not checked, continue looking for any that are.
            runAlert = false;
        }
    });

    if(DEBUG) { alert("runAlert: " + runAlert); }
    //Check results for alert run
    if(runAlert) {
        //Display the populated message.
        //Set alert title
        document.getElementById("alertDialogCONFLICT").title = "Alert - CONFLICT";

        //Make sure the alert window is empty
        $("#alertDialogCONFLICT").empty();

        //Add in message for alert
        $("#alertDialogCONFLICT").append("<p id='alertMessagesCONFLICT'>" + objAlert.message + "<br /><br /></p>");

        //Add error message location
        $("#alertMessagesCONFLICT").append("<span id='alertErrorCONFLICT' style='display:none;'></span>");

        //Add the list
        $("#alertDialogCONFLICT").append("<ul id='alertDialogListCONFLICT'></ul>");

        //Run the each again to populate the alert box
        $.each(objAlert.choices, function(i, choice){
            // Only list those that are checked
            if($('#option-' + choice.id).is(':checked')){
                // List all options
                $("#alertDialogListCONFLICT").append("<li name='alertItemCONFLICT' value='" + choice.id + "'>" + choice.name + "</li>");
            }
        });

        //Run the dialog box
        $("#alertDialogCONFLICT").dialog({
            autoOpen: false,
            modal: true,
            draggable: false,
            resizable: false,
            overlay: {
                opacity: 0.5,
                background: "black"
            },
            buttons: {
                "Decline": function() {
                    // Check if triggering option is a radio button
                    var option = $('#option-' + getTriggerId());
                    if($(option).is(':radio')) {
                        // Pull out radio button set from name
                        var optName = $(option).attr("name");
                        var selSet = optName.split('[')[1].split(']')[0];

                        // Get previous and current radio selections
                        var currRadio = $('#currentRadioOption-' + selSet).val();
                        var preRadio = $('#previousRadioOption-' + selSet).val();
                        if(preRadio != '' && preRadio != null) {
                            // Set current to unselected
                            $('#option-' + currRadio).parent().parent().parent().removeClass('active');

                            // Set previous to selected
                            $('#option-' + preRadio).attr('checked', true);
                            $('#option-' + preRadio).parent().parent().parent().addClass('active');

                            // Set current to previous and previous to blank
                            $('#currentRadioOption-' + selSet).attr('value', preRadio);
                            $('#previousRadioOption-' + selSet).attr('value', '');
                        }
                    } else {
                        // Uncheck triggering option
                        $(option).attr("checked", false);
                        $(option).parent().parent().parent().removeClass('active');
                    }
                    $(this).dialog("close");

                    //On decline, clear the alert manager queues as we no longer need to keep running alerts.
                    var clearArray = new Array();
                    setAlertQueue(clearArray);
                    setAlertObjQueue(clearArray);
                },
                "Accept": function() {
                    // Uncheck all options causing conflicts
                    $("li[name='alertItemCONFLICT']").each(function(i, itemAlert) {
                        // Check to see if option is a radio button, if so, set to previously set option
                        var option = $("#option-" + itemAlert.value);
                        if($(option).is(":radio")) {
                            // Pull out radio button set from name
                            var optName = $(option).attr("name");
                            var selSet = optName.split('[')[1].split(']')[0];

                            // Get previous and current radio selections
                            var currRadio = $('#currentRadioOption-' + selSet).val();
                            var preRadio = $('#previousRadioOption-' + selSet).val();

                            if(preRadio != '' && preRadio != null) {
                                // Set current to unselected
                                $('#option-' + currRadio).parent().parent().parent().removeClass('active');

                                // Set previous to selected
                                $('#option-' + preRadio).attr('checked', true);
                                $('#option-' + preRadio).parent().parent().parent().addClass('active');

                                // Set current to previous and previous to blank
                                $('currentRadioOption-' + selSet).attr('value', preRadio);
                                $('#previousRadioOption-' + selSet).attr('value', '');
                            }
                        } else {
                            $(option).attr("checked", false);
                            $(option).parent().parent().parent().removeClass('active');
                        }

                    });
                    $(this).dialog("close");
                    
                    //Rerun the manager to check for other alerts
                    alertManager();
                }
            }
        });

        $("#alertDialogCONFLICT").dialog("open");
    } else {
        //Rerun the manager to check for other alerts
        alertManager();
    }
}

function alertINCLUDE(objAlert, triggerId){
    setTriggerId(triggerId);
    if(DEBUG) {
        alert(" -- INCLUDE -- \n" +
              "alertNumber: " + objAlert.alertNumber +
              "\nalertType: " + objAlert.alertType +
              "\nchoiceOptional: " + objAlert.choiceOptional +
              "\nchooseAll: " + objAlert.chooseAll +
              "\nmessage: " + objAlert.message);
    }
    var chooseAll = false;
    var choiceOptional = false;

    //Check to see if we need just one checked, or all checked
    if(objAlert.chooseAll == "true") {
        chooseAll = true;
    }

    //Check to see if we need to use radio or checkbox
    if(objAlert.choiceOptional == "true") {
        choiceOptional = true;
    }

    //Check if we need to run alert
    var runAlert = true;
    $.each(objAlert.choices, function(i, choice){
        var option = document.getElementById("option-" + choice.id);

        // Check if option is disabled, if so, assume checked
        var optionDis = false;
        if (option.disabled) {
            optionDis = true;
        }

        //Must have all options checked
        if(optionDis || option.checked) {
            if(DEBUG) { alert("-- Include -- \n" + choice.id + " - " + choice.name + "\nTRUE"); }
            //If one is checked, make sure to run alert
            runAlert = false;
        } else {
            if(DEBUG) { alert("-- Include -- \n" + choice.id + " - " + choice.name + "\nFALSE"); }
            //If not checked, continue looking for any that are.
            runAlert = true;
            return false;
        }
    });

    if(DEBUG) { alert("runAlert: " + runAlert); }
    //Check results for alert run
    if(runAlert) {
        //Display the populated message.
        //Set alert title
        document.getElementById("alertDialogINCLUDE").title = "Alert - INCLUDE";

        //Make sure the alert window is empty
        $("#alertDialogINCLUDE").empty();

        //Add in message for alert
        $("#alertDialogINCLUDE").append("<p id='alertMessagesINCLUDE'>" + objAlert.message + "<br /><br /></p>");

        //Add error message location
        $("#alertMessagesINCLUDE").append("<span id='alertErrorINCLUDE' style='display:none;'></span>");

        //Add the list
        $("#alertDialogINCLUDE").append("<ul id='alertDialogListINCLUDE'></ul>");

        //Run the each again to populate the alert box
        $.each(objAlert.choices, function(i, choice) {
            // Only list those that are checked
            if(!$('#option-' + choice.id).is(':checked')) {
                // List all options
                $("#alertDialogListINCLUDE").append("<li name='alertItemINCLUDE' value='" + choice.id + "'>" + choice.name + "</li>");
            }
        });

        //Run the dialog box
        $("#alertDialogINCLUDE").dialog({
            autoOpen: false,
            modal: true,
            draggable: false,
            resizable: false,
            overlay: {
                opacity: 0.5,
                background: "black"
            },
            buttons: {
                "Decline": function() {
                    // Check if triggering option is a radio button
                    var option = $('#option-' + getTriggerId());
                    // Uncheck triggering option
                    $(option).attr("checked", false);
                    $(option).parent().parent().parent().removeClass('active');
                    $(this).dialog("close");

                    //On decline, clear the alert manager queues as we no longer need to keep running alerts.
                    var clearArray = new Array();
                    setAlertQueue(clearArray);
                    setAlertObjQueue(clearArray);
                },
                "Accept": function() {
                    // Uncheck all options causing conflicts
                    $("li[name='alertItemINCLUDE']").each(function(i, itemAlert) {
                        // Check to see if option is a radio button, if so, set to previously set option
                        var option = $("#option-" + itemAlert.value);
                        $(option).attr("checked", true);
                        $(option).parent().parent().parent().addClass('active');

                    });
                    $(this).dialog("close");

                    //Rerun the manager to check for other alerts
                    alertManager();
                }
            }
        });

        $("#alertDialogINCLUDE").dialog("open");
    } else {
        //Rerun the manager to check for other alerts
        alertManager();
    }
}

function alertREPLACE(objAlert, triggerId) {
    setTriggerId(triggerId);
    if(DEBUG) {
        alert(" -- REPLACE -- \n" +
              "alertNumber: " + objAlert.alertNumber +
              "\nalertType: " + objAlert.alertType +
              "\nchoiceOptional: " + objAlert.choiceOptional +
              "\nchooseAll: " + objAlert.chooseAll +
              "\nmessage: " + objAlert.message);
    }
    var chooseAll = false;
    var choiceOptional = false;

    //Check to see if we need just one checked, or all checked
    if(objAlert.chooseAll == "true") {
        chooseAll = true;
    }

    //Check to see if we need to use radio or checkbox
    if(objAlert.choiceOptional == "true") {
        choiceOptional = true;
    }

    //Check if we need to run alert
    var runAlert = true;
    $.each(objAlert.choices, function(i, choice){
        var option = document.getElementById("option-" + choice.id);

        // Check if option is disabled, if so, assume checked
        var optionDis = false;
        if (option.disabled) {
            optionDis = true;
        }

        //Must have all options checked
        if(optionDis || option.checked) {
            if(DEBUG) { alert("-- Include -- \n" + choice.id + " - " + choice.name + "\nTRUE"); }
            //If one is checked, make sure to run alert
            runAlert = true;
            return false;
        } else {
            if(DEBUG) { alert("-- Include -- \n" + choice.id + " - " + choice.name + "\nFALSE"); }
            //If not checked, continue looking for any that are.
            runAlert = false;
        }
    });

    if(DEBUG) { alert("runAlert: " + runAlert); }
    //Check results for alert run
    if(runAlert) {
        //Display the populated message.
        //Set alert title
        document.getElementById("alertDialogREPLACE").title = "Alert - REPLACE";

        //Make sure the alert window is empty
        $("#alertDialogREPLACE").empty();

        //Add in message for alert
        $("#alertDialogREPLACE").append("<p id='alertMessagesREPLACE'>" + objAlert.message + "<br /><br /></p>");

        //Add error message location
        $("#alertMessagesREPLACE").append("<span id='alertErrorREPLACE' style='display:none;'></span>");

        //Add the list
        $("#alertDialogREPLACE").append("<ul id='alertDialogListREPLACE'></ul>");

        //Run the each again to populate the alert box
        $.each(objAlert.choices, function(i, choice) {
            // Only list those that are checked
            if($('#option-' + choice.id).is(':checked')) {
                // List all options
                $("#alertDialogListREPLACE").append("<li name='alertItemREPLACE' value='" + choice.id + "'>" + choice.name + "</li>");
            }
        });

        //Run the dialog box
        $("#alertDialogREPLACE").dialog({
            autoOpen: false,
            modal: true,
            draggable: false,
            resizable: false,
            overlay: {
                opacity: 0.5,
                background: "black"
            },
            buttons: {
                "Decline": function() {
                    // Check if triggering option is a radio button
                    var option = $('#option-' + getTriggerId());
                    // Uncheck triggering option
                    $(option).attr("checked", false);
                    $(option).parent().parent().parent().removeClass('active');
                    $(this).dialog("close");

                    //On decline, clear the alert manager queues as we no longer need to keep running alerts.
                    var clearArray = new Array();
                    setAlertQueue(clearArray);
                    setAlertObjQueue(clearArray);
                },
                "Accept": function() {
                    // Uncheck all options causing conflicts
                    $("li[name='alertItemREPLACE']").each(function(i, itemAlert) {
                        var option = $("#option-" + itemAlert.value);
                        $(option).attr("checked", false);
                        $(option).parent().parent().parent().removeClass('active');

                    });
                    $(this).dialog("close");

                    //Rerun the manager to check for other alerts
                    alertManager();
                }
            }
        });

        $("#alertDialogREPLACE").dialog("open");
    } else {
        //Rerun the manager to check for other alerts
        alertManager();
    }
}

function alertPackageCONFLICT(objAlert, triggerId) {
    setTriggerId(triggerId);
    if(DEBUG) {
        alert(" -- Package CONFLICT -- \n" +
              "alertNumber: " + objAlert.alertNumber +
              "\nalertType: " + objAlert.alertType +
              "\nmessage: " + objAlert.message);
    }

    //Will run alert reguardless if needed.  Need to alert that items will be disabled.
    var runAlert = true;
    $.each(objAlert.choices, function(i, choice) {
        var option = document.getElementById("option-" + choice.id);

        // Check if option is disabled, if so, assume checked
        var optionDis = false;
        if (option.disabled) {
            optionDis = true;
        }

        //If one is checked, run the alert
        if(optionDis || option.checked) {
            if(DEBUG) { alert("-- Package CONFLICT -- \n" + choice.id + " - " + choice.name + "\nTRUE"); }
            //If one is checked, make sure to run alert
            runAlert = true;
            return false;
        } else {
            if(DEBUG) { alert("-- Package CONFLICT -- \n" + choice.id + " - " + choice.name + "\nFALSE"); }
            //If not checked, continue looking for any that are.
            runAlert = false;
        }
    });

    //Display the populated message.
    //Set alert title
    document.getElementById("alertDialogCONFLICT").title = "Alert - Packages CONFLICT";

    //Make sure the alert window is empty
    $("#alertDialogCONFLICT").empty();

    //Add in message for alert
    $("#alertDialogCONFLICT").append("<p id='alertMessagesCONFLICT'>" + objAlert.message + "<br /><br /></p>");

    //Add error message location
    $("#alertMessagesCONFLICT").append("<span id='alertErrorCONFLICT' style='display:none;'></span>");

    //Add the list
    $("#alertDialogCONFLICT").append("<ul id='alertDialogListCONFLICT'></ul>");

    //Run the each again to populate the alert box
    $.each(objAlert.choices, function(i, choice) {
        // List all options
        $("#alertDialogListCONFLICT").append("<li name='alertItemCONFLICT' value='" + choice.id + "'>" + choice.name + "</li>");
    });

    //Run the dialog box
    $("#alertDialogCONFLICT").dialog({
        autoOpen: false,
        modal: true,
        draggable: false,
        resizable: false,
        overlay: {
            opacity: 0.5,
            background: "black"
        },
        buttons: {
            "Decline": function() {
                /*
                $("#package-default").attr("checked", true).click();
                $("#package-default").parent().parent().parent().addClass('active');
                $("#package-" + triggerId).parent().parent().parent().removeClass('active');
                */
                var name = $("#package-" + getTriggerId()).attr("name");
                var radioSet = $("input[name='" + name + "']")[0];
                $(radioSet).attr("checked", true)
                $(radioSet).parent().parent().parent().addClass('active');
                $("#package-" + getTriggerId()).parent().parent().parent().removeClass('active');
                $(this).dialog("close");

                //On decline, clear the alert manager queues as we no longer need to keep running alerts.
                var clearArray = new Array();
                setAlertQueue(clearArray);
                setAlertObjQueue(clearArray);
            },
            "Accept": function() {
                // Uncheck all options causing conflicts
                $("li[name='alertItemCONFLICT']").each(function(i, itemAlert) {
                    var option = $("#option-" + itemAlert.value);
                    $(option).attr("checked", false).attr("disabled", true);
                    $(option).parent().parent().parent().removeClass('active');

                });
                $(this).dialog("close");

                //Rerun the manager to check for other alerts
                alertManager();
            }
        }
    });

    $("#alertDialogCONFLICT").dialog("open");
}

function alertPackageREPLACE(objAlert, triggerId) {
    setTriggerId(triggerId);
    if(DEBUG) {
        alert(" -- Package REPLACE -- \n" +
              "alertNumber: " + objAlert.alertNumber +
              "\nalertType: " + objAlert.alertType +
              "\nmessage: " + objAlert.message);
    }

    //Will run alert reguardless if needed.  Need to alert that items will be disabled.
    var runAlert = true;
    $.each(objAlert.choices, function(i, choice) {
        var option = document.getElementById("option-" + choice.id);

        // Check if option is disabled, if so, assume checked
        var optionDis = false;
        if (option.disabled) {
            optionDis = true;
        }

        //If one is checked, run the alert
        if(optionDis || option.checked) {
            if(DEBUG) { alert("-- Package REPLACE -- \n" + choice.id + " - " + choice.name + "\nTRUE"); }
            //If one is checked, make sure to run alert
            runAlert = true;
            return false;
        } else {
            if(DEBUG) { alert("-- Package REPLACE -- \n" + choice.id + " - " + choice.name + "\nFALSE"); }
            //If not checked, continue looking for any that are.
            runAlert = false;
        }
    });

    //Display the populated message.
    //Set alert title
    document.getElementById("alertDialogREPLACE").title = "Alert - Packages REPLACE";

    //Make sure the alert window is empty
    $("#alertDialogREPLACE").empty();

    //Add in message for alert
    $("#alertDialogREPLACE").append("<p id='alertMessagesREPLACE'>" + objAlert.message + "<br /><br /></p>");

    //Add error message location
    $("#alertMessagesREPLACE").append("<span id='alertErrorREPLACE' style='display:none;'></span>");

    //Add the list
    $("#alertDialogREPLACE").append("<ul id='alertDialogListREPLACE'></ul>");

    //Run the each again to populate the alert box
    $.each(objAlert.choices, function(i, choice) {
        // List all options
        $("#alertDialogListREPLACE").append("<li name='alertItemREPLACE' value='" + choice.id + "'>" + choice.name + "</li>");
    });

    //Run the dialog box
    $("#alertDialogREPLACE").dialog({
        autoOpen: false,
        modal: true,
        draggable: false,
        resizable: false,
        overlay: {
            opacity: 0.5,
            background: "black"
        },
        buttons: {
            "Decline": function() {
                /*
                $("#package-default").attr("checked", true).click();
                $("#package-default").parent().parent().parent().addClass('active');
                $("#package-" + triggerId).parent().parent().parent().removeClass('active');
                */
                var name = $("#package-" + getTriggerId()).attr("name");
                var radioSet = $("input[name='" + name + "']")[0];
                $(radioSet).attr("checked", true)
                $(radioSet).parent().parent().parent().addClass('active');
                $("#package-" + getTriggerId()).parent().parent().parent().removeClass('active');
                $(this).dialog("close");

                //On decline, clear the alert manager queues as we no longer need to keep running alerts.
                var clearArray = new Array();
                setAlertQueue(clearArray);
                setAlertObjQueue(clearArray);
            },
            "Accept": function() {
                // Uncheck all options causing conflicts
                $("li[name='alertItemREPLACE']").each(function(i, itemAlert) {
                    var option = $("#option-" + itemAlert.value);
                    $(option).attr("checked", false).attr("disabled", true);
                    $(option).parent().parent().parent().removeClass('active');

                });
                $(this).dialog("close");

                //Rerun the manager to check for other alerts
                alertManager();
            }
        }
    });

    $("#alertDialogREPLACE").dialog("open");
}
//-------------------------------------- END Alert Choice Functions --------------------------------------------------//
//--------------------------------------------- Alert Functions ------------------------------------------------------//
function getAlertInfo() {
    var alertURL = "ajax_optionalerts.html";
    //var alertURL = "/includes/js/bq/jsonTest.js";
    //Alert information retrieval
    $.getJSON(alertURL, function(data){
        setJSON(data);
    });
}

function getPackageAlertInfo() {
    var alertPackageURL = "ajax_packageoptions.html";
    //var alertPackageURL = "/includes/js/bq/jsonTestPackages.js";
    //Package Alert information
    $.getJSON(alertPackageURL, function(data){
        setPackageJSON(data);        
    });
}

// This function takes an array of sorted alert info and alert objects queue and sorts objects to match sorted alert array.
function alertObjSort(alertQueue, alertObjQueue) {
    var alertQLen = alertQueue.length;
    var alertQOLen = alertObjQueue.length;
    var alertParts = new Array();
    var alertObjOrder = "";
    var alertObj = new Object();
    var newAlertQ = new Array();
    var newAlertQObj = new Array();
    for(var i=0; i < alertQLen; i++) {
        alertParts = alertQueue[i].split("|");
        /*alert("Parts: " +
              "\n1: " + alertParts[0] +
              "\n2: " + alertParts[1] +
              "\n3: " + alertParts[2]);*/
        for(var j=0; j < alertQOLen; j++) {
            alertObjOrder = alertObjQueue[j++];
            alertObj = alertObjQueue[j];
            if (alertParts[2] == alertObjOrder) {
                newAlertQObj.push(alertObj);
                break;
            }
        }

        newAlertQ.push(alertParts[0] + "|" + alertParts[1]);
    }
    /*alert("newAlertQueue:\n" + newAlertQ +
          "\nnewAlertQObj:\n" + newAlertQObj);*/

    setAlertQueue(newAlertQ);
    setAlertObjQueue(newAlertQObj);
    alertManager();
}

// This function takes in an array of choices and sorts them to be in the order: CHOICE/INCLUDE, REPLACE, and CONFLICT
// Reversing the order will ensure that entries pop'd off in order of CONFLICT, REPLACE, and CHOICE/INCLUDE
function alertQueueSort(alertQueue, alertObjQueue) {
    //alert("Before Sort:\n" + alertQueue);
    var conflictArray = new Array();
    var replaceArray = new Array();
    var choiceArray = new Array();
    var queueAlert = "";
    var qLen = alertQueue.length;
    for (var i=0; i < qLen; i++) {
        queueAlert = alertQueue.pop();
        /*alert("Element: " + queueAlert +
                "\nSearch CON: " + queueAlert.search(/CONFLICT/) +
                "\nSearch REP: " + queueAlert.search(/REPLACE/) +
                "\nSearch CHO: " + queueAlert.search(/CHOICE/));*/
        if (queueAlert.search(/CONFLICT/) > -1) {
            conflictArray.push(queueAlert);
        } else if (queueAlert.search(/REPLACE/) > -1) {
            replaceArray.push(queueAlert);
        } else {
            choiceArray.push(queueAlert);
        }
        /*alert("CONFLICT: " + conflictArray +
                "\nREPLACE: " + replaceArray +
                "\nCHOICE: " + choiceArray);*/
    }
    var tempArray = new Array();
    tempArray = choiceArray.concat(replaceArray,conflictArray);
    //alert("After Sort:\n" + tempArray);
    alertObjSort(tempArray, alertObjQueue);
}

function checkAlert(id) {
    if(DEBUG) { alert("-- checkAlert Running --\nId: " + id +
                      "\nChecked: " + $("#option-" + id).is(':checked')); }
    var alertsQueue = new Array();
    var alertObjs = new Array();
    var ind = 1; // Used to determine order in array for when sorted, both arrays can be sorted equally.

    // Only run if we are checking the option, backend will handle any problems of unchecking
    if($("#option-" + id).is(':checked')) {
        //$.getJSON("/includes/js/bq/jsonTest.js", function(data) {
        $.each(getJSON(), function(i, selOpt) {
            if(selOpt.optionId == id) {
                if (selOpt.alerts != null || selOpt.alerts != '') {
                    $.each(selOpt.alerts, function(j, optAlert) {
                        // Populate an Array of all needed alerts
                        alertsQueue.push(optAlert.alertType + "|" + id + "|" + ind);
                        alertObjs.push(ind);
                        alertObjs.push(selOpt.alerts[j]);
                        ind++;
                    });

                    if(DEBUG) {
                        alert("-- Queues --\n" +
                              "AlertsInfo: " + alertsQueue +
                              "\nAlertsObj: " + alertObjs);
                    }

                    alertQueueSort(alertsQueue, alertObjs);
                }
            }
        });
    }
}

function checkPackageAlert(id) {
    if(DEBUG) { alert("-- checkAlert Running --\nId: " + id +
                      "\nChecked: " + $("#package-" + id).is(':checked')); }
    var alertsQueue = new Array();
    var alertObjs = new Array();
    var ind = 1; // Used to determine order in array for when sorted, both arrays can be sorted equally.

    // Only run if we are checking the option, backend will handle any problems of unchecking
    if($("#package-" + id).is(':checked')) {
        //$.getJSON("/includes/js/bq/jsonTest.js", function(data) {
        $.each(getPackageJSON(), function(i, selOpt) {
            if(selOpt.packageId == id) {
                if (selOpt.alerts != null || selOpt.alerts != '') {
                    $.each(selOpt.alerts, function(j, optAlert) {
                        // Populate an Array of all needed alerts
                        alertsQueue.push("Package-" + optAlert.alertType + "|" + id + "|" + ind);
                        alertObjs.push(ind)
                        alertObjs.push(selOpt.alerts[j]);
                        ind++;
                    });

                    if(DEBUG) {
                        alert("-- Package Queues --\n" +
                              "PackageAlertsInfo: " + alertsQueue +
                              "\nPackageAlertsObj: " + alertObjs);
                    }

                    alertQueueSort(alertsQueue, alertObjs);
                }
            }
        });
    }
}
//------------------------------------------- END Alert Functions ----------------------------------------------------//