// build and quote calculations and model/option select
// By Betty and Darin @ Sundog.net

/*
  Changelog:
 var 1.4: (06/20/2006)
 * http://www.opensource.org/licenses/bsd-license.php
See scriptaculous.js for full scriptaculous licence

*/

// Global Variables
var JSON;

// Classes
var bQMenu = {
	collapseOptionMenu: function(node) {
		if (!document.getElementById) return false;
		if (!document.getElementById("build-items")) return false;
		if (!node) node = document.getElementById("build-items");
                                                                 
		if (node.childNodes.length > 0) {
            for (var i=0; i<node.childNodes.length; i++) {
				var child = node.childNodes[i];
                if (child.nodeName == "UL") {
                        child.style.display = "none";
				}
				bQMenu.collapseOptionMenu(child);
			}
		}
	},

	prepareOptionMenu: function() {
		if (!document.getElementById || !document.getElementsByTagName) return false;
		if (!document.getElementById("build-items")) return false;

		var links = document.getElementById("build-items").getElementsByTagName("a");
        for (var i=0; i<links.length; i++) {

            links[i].onclick = function() {
                bQMenu.toggleOptionMenu(this.parentNode.getElementsByTagName("UL")[0], this.href, this.parentNode.getElementsByTagName("div")[1].id);
				return false;
			}
		}
	},

	toggleOptionMenu: function(node, link, divLink) {
		if (!document.getElementById) return false;
		if (!link) return false;
		if (!node) location.href = link.href;

		// Collapse all nodes, and only show clicked node (when clicking top level of menu)
        var divTag = document.getElementById(divLink);
        if (node.style.display == "") {
			// Effect.BlindUp(node, {duration: 0.2});
            divTag.innerHTML = "[+]";
            node.style.display = "none";
		} else {
			// Effect.BlindDown(node, {duration: 0.2});
            //imageTag.src = "../includes/css/css-images/bq_up.gif";
            divTag.innerHTML = "[-]";
            node.style.display = "";
		}
	},

	hideTopOptionLevels: function() {
		if (!document.getElementById) return false;
		if (!(node = document.getElementById("build-items"))) return false;

		if (node.childNodes.length > 0) {
			for (var i=0; i<node.childNodes.length; i++) {
				var child = node.childNodes[i];
				for(var j=0; j<child.childNodes.length; j++) {
					var grandchild = child.childNodes[j];
					if (grandchild.nodeName == "UL") {
						if (grandchild.style.display == '') {
							// Effect.BlindUp(grandchild, {duration: 0.2});
                            grandchild.style.display = "none";
						}
					}
				}
			}
		}
	},

	openFirst: function() {
		if (!document.getElementById && !document.getElementsByTagName && !document.createElement) return;
		if (!document.getElementById('build-items')) { return; }
		var firstmenu = document.getElementById('build-items').getElementsByTagName('ul')[0];
        var firstDiv = document.getElementById('build-items').getElementsByTagName('div')[1];

        if (firstmenu.style.display == "none") {
			firstmenu.style.display = "";
            // Check and see if the first label if for expanding/collapsing text
            if (firstDiv.id.match("expClspLabel")) {
                firstDiv.innerHTML = "[-]";
            }
        }
    },

    // Run for the options page to load the main content
    updateOptions: function() {
        var optionsInputs = document.getElementsByTagName("input");
        var optionsId;
        var newOptionsId;
        for (var i = 0; i < optionsInputs.length; i++) {
            //alert("Type: " + optionsInputs[i].type + "\nClass: " + optionsInputs[i].parentNode.parentNode.className);

            // Check to see if the 'active' class is included
            var optionsClassName = optionsInputs[i].parentNode.parentNode.className;
            var optionsTest = optionsClassName.match("active");
            var activeClass = false;
            if (optionsTest != null) {
                activeClass = true;
            }

            if (optionsInputs[i].type == "radio" && activeClass) {
                // Make sure that we are on an option radio button
                if ((optionsInputs[i].name).match("[radio1]") != null) {
                    // Remove the 'option-' from the id
                    optionsId = optionsInputs[i].id;
                    newOptionsId = optionsId.replace(/option\-/, "");
                    bQ.getBuildItemInfo(newOptionsId, 'option-');
                }
            }
        }
    }
}

// add menu events
addLoadEvent(bQMenu.collapseOptionMenu);
addLoadEvent(bQMenu.prepareOptionMenu);
addLoadEvent(bQMenu.openFirst);
addLoadEvent(bQMenu.updateOptions);

var bQ = {
	findBuildItems: function() {
        if (!document.getElementById && !document.getElementsByTagName && !document.createElement) return;
  		if (!document.getElementById('build-items')) { return; }
		var buildList = document.getElementById('build-items');
		var buildItems = buildList.getElementsByTagName('input');
		var selectOptions = document.getElementsByTagName('select');
        var discountValue = bQ.filterNum(getText(document.getElementById('quote-discount')));
        for (var i=0; i<buildItems.length; i++) {
			if (buildItems[i].type != "hidden") {
                addEvent(buildItems[i], 'click', bQ.markActiveItems, false);
            	addEvent(buildItems[i], 'click', bQ.updateQuote, false);
            }
        }
        for(i = 0; i < selectOptions.length; i++) {
            selectOptions[i].style.display = 'none';
        }
        bQ.setDiscountValue(discountValue);

        if(buildList.className == 'options-list') {
            document.getElementById("alertContent").style.display = "none";
            document.getElementById("buttonsAlert").style.display = "none";
            bQ.httpRequest("/buildandquote/ajax_optionalerts.html", "alert");
        }

    },


    markActiveItems: function() {
        if (!document.getElementById('build-items')) { return; }
		var buildList = document.getElementById('build-items');
		var buildItems = buildList.getElementsByTagName('input');

        for (var i = 0; i < buildItems.length; i++) {
            var listItem    = buildItems[i].parentNode.parentNode;
            if(buildItems[i].type == "radio") {
                var optionsId   = buildItems[i].id;
                var optionsList = document.getElementById(optionsId + "-list");
//                alert ("optionsId: " + optionsId + "\noptionsList: "
//                        + optionsList.id + "\nChecked: "
//                        + buildItems[i].checked);
                if(!buildItems[i].checked) { //!= "checkbox" && buildItems[i].type != "hidden") {
                    listItem.className = "";
//                    if (optionsList) { optionsList.style.display = "none"; }
                } else {
                    listItem.className = "active";
                    //Effect.divSwap(buildItems[i].id + '-info','info');
//                    if (optionsList) { optionsList.style.display = ""; }
                }
            }
        }

        for (i = 0; i < buildItems.length; i++) {

            listItem = buildItems[i].parentNode.parentNode;

            if(buildItems[i].type != "hidden") {
                if(!buildItems[i].checked) {
                     if(buildList.className == 'basemodel-list') listItem.className = "";
                } else  {
                    if(buildList.className == 'basemodel-list') listItem.className = "active";

                    var prefix;
                    if(buildItems[i].id.indexOf("uv") != -1) {
                       prefix = 'uv'
                    } else if(buildItems[i].id.indexOf("e") != -1) {
                       prefix = 'e';
                    } else if(buildItems[i].id.indexOf("asl") != -1) {
                       prefix = 'asl';
                    } else if(buildItems[i].id.indexOf("ctl") != -1) {
                       prefix = 'ctl';
                    } else if(buildItems[i].id.indexOf("ml") != -1) {
                       prefix = 'ml';
                    } else if(buildItems[i].id.indexOf("sl") != -1) {
                       prefix = 'sl';
                    } else if(buildItems[i].id.indexOf("vt") != -1) {
                       prefix = 'vt';
                    } else if(buildItems[i].id.indexOf("ct") != -1) {
                        prefix ='ct';
                    }
                    Effect.divSwap(prefix + buildItems[i].value + '-info','info');
               }
            }
        }
	},

    getBuildItemInfo: function(selectedId,opt) {
        var buildList = document.getElementById('build-items');
        var attOnly = document.getElementById('attachOnly');
        var url = "/buildandquote/bq_ajax.html?id="+selectedId;
        
        if (attOnly.value == "true") {
            url = url + "&attachmentsOnly=true";
        }

        bQ.httpRequest(url, "update");
        var buildItems = buildList.getElementsByTagName('input');
        var val = document.getElementById(opt+selectedId);
        var listItem = val.parentNode.parentNode;

        if(val.type != 'checkbox') {
            if(val.checked) { listItem.className = "active"; }
            for (var i=0; i < buildItems.length; i++) {
                if(buildItems[i].type == "radio" && buildItems[i].id != opt+selectedId) {
                        listItem = buildItems[i].parentNode.parentNode;
                        listItem.className = "";
                 }
            }
        } else {
            if (val.checked) {
                listItem.className = "active";
            } else {
                listItem.className = "";
            }
        }

        bQ.setBuildItemId(selectedId);
        if(buildList.className == 'options-list') {
            bQ.newAlertSetup();
        }
    },

    setAlertResult: function(res) {
       JSON = res;
    },
    getAlertResult: function() {
        return JSON;
    },

    alertChildCheck: function(parentId) {
        var data = eval(bQ.getAlertResult());
        var currArray = "";
        var tempArray = "";
        for (var j = 0; j < data.length; j++) {
            var optionId = data[j].optionId;
            if (optionId == parentId) {
                var alertLength = data[j].alerts.length;
                //alert(alertLength);
                for(var k = 0; k < alertLength; k++) {
                    var alertType = data[j].alerts[k].alertType;
                    var alertChoices = data[j].alerts[k].choices;
                    //alert("alertType: " + alertType);
                    if (alertType == "REMOVE") {
                        for(var l = 0; l < alertChoices.length; l++) {
                            currArray = currArray + alertChoices[l].id + '|' + alertChoices[l].name + ';';
                            tempArray = bQ.alertChildCheck(alertChoices[l].id);
                            if (tempArray != '') {
                                currArray = currArray + tempArray;
                            }
                        }
                    } // END 'REMOVE'
                } // END for 'k'
                return currArray;                
            } // END if
        } // END for 'j'
    },

    newAlertSetup: function() {
        var data = eval(bQ.getAlertResult());
        //alert(bQ.getAlertResult());

        // Cycle through all items as passed by the JSON call
        for(var j = 0; j < data.length; j++) {
            var optionId = data[j].optionId;

            // Check if we match current selection
            if (optionId == bQ.getBuildItemId()) {
                
                // Check if we are checking the option or unchecking it
                var check = document.getElementById("option-" + optionId);
                var newValueInput;
                
                // If no messages and a radio button, update 'old value' hidden field
                if (data[j].alerts.length < 1) {
                    if (check.type == "radio") {
                        newValueInput = document.getElementById("old_" + check.name);
                        newValueInput.value = optionId;
                    }
                }

                for(var k = 0; k < data[j].alerts.length; k++) {
                    // Set up all variables
                    var alertDisplay = true;  // used to indicate if we should display alert
                    var alertType = data[j].alerts[k].alertType;
                    var alertOptional = data[j].alerts[k].choiceOptional;
                    var alertChooseAll = data[j].alerts[k].chooseAll;
                    var alertMessage = data[j].alerts[k].message;
                    var alertChoices = data[j].alerts[k].choices;
                    var btnAccept;
                    var btnDecline;
                    var listItem;
                    //alert("Id: " + optionId +
                    //      "\nType: " + alertType +
                    //      "\nChoice Optional: " + alertOptional +
                    //      "\nChoose All: " + alertChooseAll +
                    //      "\nMessage: " + alertMessage)

                    // We are checking an option, so check for choices/conflicts/replacements
                    if (check.checked) {
                        if (alertType == "CHOICE") {
                            btnAccept = document.getElementById('acceptAlert');
                            btnDecline = document.getElementById('declineAlert');
                            btnDecline.style.display = "inline";
                            var alertDiv =  document.getElementById('alertContent');
                            var ulList = alertDiv.getElementsByTagName('ul').item(0);
                            var pTag = document.createElement('p');
                            var choiceId;
                            var choiceName;
                            var label;
                            var alertCheck;
                            var currOption;
                            var m;
                            var n;

                            var choiceElement = document.createElement("input");
                            choiceElement.id = "choiceElement";
                            choiceElement.setAttribute("type", "hidden");

                            Modalbox.setOptionId(optionId);
                            Modalbox.setAlertType(alertType);

                            // Remove all <p> children from ulList before repopulating
                            var pCheck = alertDiv.getElementsByTagName('p');
                            for(n = 0; n < pCheck.length; n++) {
                                alertDiv.removeChild(pCheck[n]);
                            }

                            ulList.innerHTML = "";
                            appendText(pTag, alertMessage);
                            alertDiv.appendChild(pTag);

                            // These are not required fields [checkboxes]
                            if (alertOptional) {
                                //alert("Optional");
                                // Disable the 'Decline' Button
                                btnDecline.style.display = "none";

                                for(m = 0; m < data[j].alerts[k].choices.length; m++) {
                                    choiceId = data[j].alerts[k].choices[m].id;
                                    choiceName = data[j].alerts[k].choices[m].name;
                                    currOption = document.getElementById("option-" + choiceId);

                                    listItem = document.createElement('li');
                                    label = document.createElement('label');

                                    try {
                                        alertCheck = document.createElement('<input type="checkbox" name="alertGroup" />');
                                    } catch(err) {
                                        alertCheck = document.createElement('input');
                                        alertCheck.setAttribute('type','checkbox');
                                        alertCheck.setAttribute('name','alertGroup');
                                    }

                                    // Check for current value of the option, set to checked if checked.
                                    if(currOption.checked) {
                                        alertCheck.setAttribute('checked', true);
                                    }

                                    alertCheck.id = "alertOption" + m;
                                    alertCheck.value = choiceId;

                                    label.setAttribute("for", "alertOption" + m);

                                    appendText(label, choiceName);
                                    listItem.appendChild(alertCheck);
                                    listItem.appendChild(label);
                                    ulList.appendChild(listItem);

                                }

                                choiceElement.setAttribute("value", "optional");
                                ulList.appendChild(choiceElement);

                                // ensure that message displays always with choice
                                alertDisplay = true;

                            } else if (alertChooseAll) {
                                //alert("All");
                                var unchecked = false;
                                for(m = 0; m < data[j].alerts[k].choices.length; m++) {
                                    choiceId = data[j].alerts[k].choices[m].id;
                                    choiceName = data[j].alerts[k].choices[m].name;
                                    currOption = document.getElementById("option-" + choiceId);

                                    // Check if option is checked, if not, set unchecked to true to ensure we display alert
                                    if (!currOption.checked) { unchecked = true; }

                                    listItem = document.createElement('li');
                                    label = document.createElement('label');

                                    label.id = "choice-" + choiceId;

                                    appendText(label, choiceName);
                                    listItem.appendChild(label);
                                    ulList.appendChild(listItem);

                                }

                                choiceElement.setAttribute("value", "all");
                                ulList.appendChild(choiceElement);

                                // if 'unchecked' is still false, no need to display alert
                                if (!unchecked) { alertDisplay = false; }

                                //alert("Unchecked: " + unchecked +
                                //      "\nAlert Display: " + alertDisplay);

                            // Should be required, use radio buttons.  If only one option, only alert.
                            } else {
                                var checked = false;

                                // Check if at least one option is selected, if so, don't show message
                                for(m = 0; m < data[j].alerts[k].choices.length; m++) {
                                    choiceId = data[j].alerts[k].choices[m].id;

                                    currOption = document.getElementById("option-" + choiceId);
                                    if (currOption.checked) {
                                        checked = true;
                                        break;
                                    }
                                }

                                // Set display to false to ensure not showing as we already meet requirments
                                if(checked) {
                                    alertDisplay = false;
                                } else {

                                    // Check if only one option
                                    if(data[j].alerts[k].choices.length = 1) {
                                        choiceId = data[j].alerts[k].choices[0].id;
                                        choiceName = data[j].alerts[k].choices[0].name;
                                        listItem = document.createElement('li');
                                        label = document.createElement('label');

                                        label.id = "choice-" + choiceId;

                                        appendText(label, choiceName);
                                        listItem.appendChild(label);
                                        ulList.appendChild(listItem);

                                        choiceElement.setAttribute("value", "required-one");
                                        ulList.appendChild(choiceElement);
                                    } else {
                                        for(m = 0; m < data[j].alerts[k].choices.length; m++) {
                                            choiceId = data[j].alerts[k].choices[m].id;
                                            choiceName = data[j].alerts[k].choices[m].name;
                                            currOption = document.getElementById("option-" + choiceId);

                                            // Check if option is checked, if not, set unchecked to true to ensure we display alert
                                            if (currOption.checked) { unchecked = true; }

                                            listItem = document.createElement('li');
                                            label = document.createElement('label');
                                            var alertRadio;

                                            try {
                                                alertRadio = document.createElement('<input type="radio" name="alertGroup" />');
                                            } catch(err) {
                                                alertRadio = document.createElement('input');
                                                alertRadio.setAttribute('type','radio');
                                                alertRadio.setAttribute('name','alertGroup');
                                            }

                                            alertRadio.id = "alertOption" + m;
                                            alertRadio.value = choiceId;

                                            // Make sure to have first option selected
                                            if (m = 0) {
                                                alertRadio.setAttribute("selected", "selected");
                                            }

                                            label.setAttribute("for", "alertOption" + m);

                                            appendText(label, choiceName);
                                            listItem.appendChild(alertRadio);
                                            listItem.appendChild(label);
                                            ulList.appendChild(listItem);
                                        }
                                        
                                        choiceElement.setAttribute("value", "required-many");
                                        ulList.appendChild(choiceElement);
                                    }


                                }
                            }

                            // Check if message needs to be displayed
                            if (alertDisplay) {
                                alertDiv.appendChild(ulList);
                                //alertDiv.appendChild(document.getElementById('buttonsAlert'));
                                alertMessage = document.getElementById('alertContent').innerHTML + "<br><br>"+document.getElementById('buttonsAlert').innerHTML;
                                Modalbox.show('Alerts - '+alertType, alertMessage, {width: 400, height:200});
                                alertDiv.removeChild(pTag);
                            }

                        } else if (alertType == "CONFLICT") {
                            //alert("Test -- Conflict");
                            var inputItem;
                            var inputId;
                            var message = false;
                            var triggerId = data[j].optionId;
                            var triggerInput = document.getElementById("option-" + triggerId);

                            for(i=0; i < data[j].alerts[k].choices.length; i++) {
                                inputId = data[j].alerts[k].choices[i].id;
                                inputItem = document.getElementById("option-" + inputId);
                                if (inputItem != null && inputItem.checked) {
                                    //alert("Conflict Name: " + inputItem.id + " Checked: " + inputItem.checked);
                                    if(alertMessage != null) {
                                        message = true;
                                        btnDecline = document.getElementById('declineAlert');
                                        btnDecline.style.display = "none";
                                        alertMessage = alertMessage + "<br><br>"+document.getElementById('buttonsAlert').innerHTML;
                                        Modalbox.setOptionId(optionId);
                                        Modalbox.setAlertType(alertType);
                                        Modalbox.show('Alerts - '+alertType, alertMessage, {width: 300, height:120});
                                    }
                                }
                            }

                            if (!message) {
                                if (triggerInput.type == "radio") {
                                    newValueInput = document.getElementById("old_" + triggerInput.name);
                                    newValueInput.value = triggerId;
                                }
                            }
                        } else if (alertType == "INCLUDE") {
                        } else if (alertType == "REPLACE") {
                            var status = false;
                            for(i=0; i < data[j].alerts[k].choices.length; i++) {
                                var itemToReplace = document.getElementById("option-" + data[j].alerts[k].choices[i].id);
                                var optionIdToReplace = document.getElementById("option-"+ optionId);
                                if(itemToReplace != null && itemToReplace.checked) {
                                    status = true;
                                    Modalbox.setItemToReplace(itemToReplace);
                                }
                                Modalbox.setOptionId(optionIdToReplace);
                                Modalbox.setAlertType(alertType);
                            }
                            if(status) {
                                btnDecline = document.getElementById('declineAlert');
                                btnDecline.style.display = "block";
                                btnDecline.removeAttribute("style");
                                if(alertMessage != null) {
                                    alertMessage = alertMessage + "<br><br>"+document.getElementById('buttonsAlert').innerHTML;
                                    Modalbox.show('Alerts - '+alertType, alertMessage, {width: 300, height:120});
                                } else {
                                    itemToReplace.checked = false;
                                }
                            }
                        }

                    // We are unchecking an option, check for removal conflicts
                    } else {
                        //alert("UNCHECKING: " + alertType);
                        if (alertType == "REMOVE") {

                            // Check for 'REMOVE' status only
                            var choices = bQ.alertChildCheck(optionId);
                            //alert("Choices: " + choices);

                            // If not blank, there was a remove
                            if (choices != "") {
                                // choices format: [id|name;id|name;id|name;]
                                var items = choices.split(";");
                                var ids = new Array();
                                var names = new Array();
                                var option;
                                var itemId;
                                var itemName;
                                var inArray = false;
                                var testChecked;
                                for(var a = 0; a < items.length; a++) {
                                    if(items[a] != '' && items[a] != null) {
                                        option = items[a].split("|");
                                        itemId = option[0];
                                        itemName = option[1];
                                        inArray = false;  // used to check if option is in array

                                        // Check to see if variable is checked, if it isn't, do not alert
                                        testChecked = document.getElementById("option-" + itemId);
                                        if(testChecked.checked) {
                                            // Check to ensure we don't have any duplicate entries
                                            for(var b = 0; b < ids.length; b++) {
                                                if (ids[b] == itemId) { inArray = true; }
                                            }

                                            // If not in array, add to the arrays
                                            if (!inArray) {
                                                ids.push(itemId);
                                                names.push(itemName);
                                            }
                                        } // END !checked.checked
                                    } // END item[a] check
                                }
                                //(names);

                                if (names != null && names != "") {
                                    // --------------------- Populate Alert --------------------- //
                                    btnAccept = document.getElementById('acceptAlert');
                                    btnDecline = document.getElementById('declineAlert');
                                    btnDecline.style.display = "inline";
                                    alertDiv =  document.getElementById('alertContent');
                                    ulList = alertDiv.getElementsByTagName('ul').item(0);
                                    pTag = document.createElement('p');
                                    var labelItem;

                                    ulList.innerHTML = "";
                                    appendText(pTag, alertMessage);
                                    alertDiv.appendChild(pTag);

                                    // Cycle through all dependant children and list them
                                    for(var c = 0; c < names.length; c++) {
                                        listItem = document.createElement("li");
                                        labelItem = document.createElement("label");
                                        appendText(labelItem, names[c]);
                                        labelItem.id = "remove-" + ids[c];
                                        listItem.appendChild(labelItem);
                                        ulList.appendChild(listItem);
                                    }

                                    alertDiv.appendChild(ulList);
                                    alertMessage = document.getElementById('alertContent').innerHTML + "<br><br>"+document.getElementById('buttonsAlert').innerHTML;
                                    Modalbox.setAlertType(alertType);
                                    Modalbox.setOptionId(optionId);
                                    Modalbox.show('Alerts - ' + alertType, alertMessage, {width: 400, height:200});
                                    alertDiv.removeChild(pTag);    
                                    // --------------------- Populate Alert --------------------- //
                                } // END names != null
                            } // END !choices
                        } // END check for REMOVE
                    }
                } // END k
            }
        }
    },

    alertSetup: function() {

        var data = eval(bQ.getAlertResult());
        for(j = 0; j < data.length; j++) {
            var optionId = data[j].optionId;

            if(optionId == bQ.getBuildItemId()) {
                for(k = 0; k < data[j].alerts.length; k++) {
                    var alertType = data[j].alerts[k].alertType;
                    var alertRequired = data[j].alerts[k].choiceOptional;
                    var alertMessage = data[j].alerts[k].message;
                    var alertChooseAll = data[j].alerts[k].chooseAll;
                    var alertRemoveWithItem = data[j].alerts[k].removeWithItem;
                    var btnAccept;
                    var btnDecline;
                    var listItem;

                    if(alertType == "CONFLICT"){
                        for(i=0; i < data[j].alerts[k].choices.length; i++) {
                            var inputItem = document.getElementById("option-" + data[j].alerts[k].choices[i].id);
                            //alert(inputItem);
                            if (inputItem != null && inputItem.checked) {
                                btnDecline = document.getElementById('declineAlert');
                                btnDecline.style.display = "none";
                                if(alertMessage != null) {
                                    alertMessage = alertMessage + "<br><br>"+document.getElementById('buttonsAlert').innerHTML;
                                    Modalbox.show('Alerts - '+alertType, alertMessage, {width: 300, height:120});
                                }
                                var conflictedOption = document.getElementById("option-" + optionId);
                                listItem = conflictedOption.parentNode.parentNode;
                                conflictedOption.checked = false;
                                listItem.className = "";
                                break;
                            }
                        }
                     } else if(alertType == "REPLACE") {
                         var status = false;
                         for(i=0; i < data[j].alerts[k].choices.length; i++) {
                                var itemToReplace = document.getElementById("option-" + data[j].alerts[k].choices[i].id);
                                var optionIdToReplace = document.getElementById("option-"+ optionId);
                                if(itemToReplace != null && itemToReplace.checked) {
                                    status = true;
                                    Modalbox.setItemToReplace(itemToReplace);
                                }

                                Modalbox.setOptionId(optionIdToReplace);
                                Modalbox.setAlertType(alertType);
                        }
                        
                        if(status) {
                            btnDecline = document.getElementById('declineAlert');
                            btnDecline.style.display = "block";
                            btnDecline.removeAttribute("style");
                            if(alertMessage != null) {
                                alertMessage = alertMessage + "<br><br>"+document.getElementById('buttonsAlert').innerHTML;
                                Modalbox.show('Alerts - '+alertType, alertMessage, {width: 300, height:120});
                            } else {
                                itemToReplace.checked = false;
                            }
                        }
                     } else if(alertType == "CHOICE") {
                        if(document.getElementById("option-" + optionId).checked) {
                            btnAccept = document.getElementById('acceptAlert');
                            btnDecline = document.getElementById('declineAlert');
                            btnDecline.style.display = "inline";
                            var alertDiv =  document.getElementById('alertContent');
                            var ulList = alertDiv.getElementsByTagName('ul').item(0);
                            var pTag = document.createElement('p');

                            ulList.innerHTML = "";
                            appendText(pTag, alertMessage);
                            alertDiv.appendChild(pTag);

                            for(m = 0; m < data[j].alerts[k].choices.length; m++) {
                                    var choiceId = data[j].alerts[k].choices[m].id;
                                    var choiceName = data[j].alerts[k].choices[m].name;
                                    //alert ("alertChooseAll:" + alertChooseAll + " alertRemoveWithItem: " + alertRemoveWithItem);

                                    listItem = document.createElement('li');
                                    var label = document.createElement('label');
                                    var alertRadio;

                                    try {
                                        alertRadio = document.createElement('<input type="radio" name="alertGroup" />');
                                    } catch(err) {
                                        alertRadio = document.createElement('input');
                                        alertRadio.setAttribute('type','radio');
                                        alertRadio.setAttribute('name','alertGroup');
                                    }

                                    alertRadio.id = "alertOption"+m;
                                    alertRadio.value = choiceId;

                                    label.setAttribute("for", "alertOption"+m);
                                    //label.appendChild(alertRadio);

                                    appendText(label, choiceName);
                                    listItem.appendChild(alertRadio);
                                    listItem.appendChild(label);
                                    ulList.appendChild(listItem);

                                }

                                alertDiv.appendChild(ulList);

                                //alertDiv.appendChild(document.getElementById('buttonsAlert'));
                                alertMessage = document.getElementById('alertContent').innerHTML + "<br><br>"+document.getElementById('buttonsAlert').innerHTML;
                                Modalbox.show('Alerts - '+alertType, alertMessage, {width: 400, height:200});
                                alertDiv.removeChild(pTag);
                           }
                        }
                    break;
              }
          }
        }
    },

    httpRequest: function(url, callback) {
       var httpObj = false;
        if (typeof XMLHttpRequest != 'undefined') {
            httpObj = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            try{
                httpObj = new ActiveXObject('Msxml2.XMLHTTP');
            } catch(e) {
                try{
                    httpObj = new ActiveXObject('iMicrosoft.XMLHTTP');
                } catch(e) {}
            }
        }
        if (!httpObj) return;

        httpObj.onreadystatechange = function() {
            if (httpObj.readyState == 4) { // when request is complete
                if (httpObj.status == 200) {
                    //alert(httpObj.responseText);
                    if(callback == "alert") {
                        bQ.setAlertResult(httpObj.responseText);
                    } else if (callback == "update" && location.pathname != '/buildandquote/basemodel.html') {
                        bQ.setAlertResult(httpObj.responseText);
                        bQ.updateBuildItemInfo(httpObj.responseText);
                    } else if (location.pathname != '/buildandquote/basemodel.html') {
                        bQ.fillSelect(httpObj.responseText, callback);
                    }

                 } else {
                    var message = httpObj.getResponseHeader("Status");
                    if ((message.length == null) || (message.length <= 0)) {
                        alert("Error! Request status is " + httpObj.status);
                    } else {
                        //alert(message);
                        window.location.href = "/buildandquote/";
                    }
                }
            }
        };
        httpObj.open('GET', url, true);
        httpObj.send(null);
    },

  fillSelect: function(JSON, count) {
   var selectTwo = document.getElementById('select'+count);

    // clear out existing options
    while (selectTwo.options.length) {
        selectTwo.options[0] = null;
    }
    // fill with new options from JSON array
   if(JSON == "[]") document.getElementById('select'+count).style.display = 'none';
   var data = eval(JSON);
    for (var i=0;i < data.length;i++) {
        selectTwo.options[selectTwo.options.length] = new Option(data[i].name, data[i].id);
    }

  },

  onSelectChange: function(i) {
    var buttonAdd = document.getElementById('add_btnId');
        buttonAdd.className = 'add_btn';
    var selectOne = document.getElementById('select'+i);
    i++;
    var selectedOption = selectOne.options[selectOne.selectedIndex].value;
    if (selectedOption != null) {
        document.getElementById('select'+i).style.display = 'block';
        bQ.httpRequest('/buildandquote/bqattach_ajax.html?id='+selectedOption, i);
    } else {
        selectTwo.options[i] = null; //bQ.fillSelect('[]'); // empty array
    }

   },

    createSelectList: function(id) {
        var selectOne = document.getElementById('select0');
        //var buttonAdd = document.getElementById('add_btnId');
        //buttonAdd.className = 'add_btn';
        selectOne.style.display = "block";
        bQ.httpRequest('/buildandquote/bqattach_ajax.html?id='+id, 0);
    },

	updateBuildItemInfo: function(JSON) {  
			var responseArea = document.getElementById('response-area');
        if(responseArea != null) responseArea.style.display = 'block';
				// set up variables for build info elements to populate
				var buildImgEl = document.getElementById('build-img');
				var buildList = document.getElementById('build-items');
        var buildNameEl = document.getElementById('build-name');
        var buildDescEl = document.getElementById('build-desc');
				var buildDiscountEl = document.getElementById('build-discount');
				var buildPriceEl = document.getElementById('build-price');
				var buildTotalEl = document.getElementById('build-total');

				// get response and split string into separate variables
				var data = eval(JSON);
        var imgurl = data[0];
				var name = data[1];
				var	desc = data[2];

        if (desc == null) {
				    desc = "Contact your dealer for more information about this product.";
				}
					
        var price       = Math.abs(data[3]);
				var discount    = Math.abs(data[4]);
        var apAttInfo   = data[5];
        var apAttDiv    = document.getElementById('approvedAttachments');

        if (apAttDiv != null && apAttInfo != null) {
            apAttDiv.innerHTML = apAttInfo;
        }

        // write response variables to user interface
        var buildImgSize;
        var parentAbb = document.getElementById('parentAbb');
        if(imgurl == null) {
             if(parentAbb.value == "asl"){
                buildImgSize = "/images/bq/build_img_asl_na.jpg";
            } else if(parentAbb.value == "e"){
                buildImgSize = "/images/bq/build_img_e_na.jpg";
            } else if(parentAbb.value == "ctl"){
                buildImgSize = "/images/bq/build_img_ctl_na.jpg";
            } else if(parentAbb.value == "ct"){
                buildImgSize = "/images/bq/build_img_tr_na.jpg";
            } else if(parentAbb.value == "ml"){
                buildImgSize = "/images/bq/build_img_ml_na.jpg";
            } else if(parentAbb.value == "sl"){
                buildImgSize = "/images/bq/build_img_sl_na.jpg";
            } else if(parentAbb.value == "uv"){
                buildImgSize = "/images/bq/build_img_uv_na.jpg";
            } else if(parentAbb.value == "vt"){
                buildImgSize = "/images/bq/build_img_vt_na.jpg";
            } else if(parentAbb.value == null || parentAbb.value == ''){
                buildImgSize = "/images/bq/build_img_att_na.jpg";
            } else { buildImgSize = "/images/bq/build_img_default.jpg"; }
        } else {
					buildImgSize = imgurl + "&width=350";
				}

				// hide discount row if there is no discount
				if (buildList.className != 'basemodel-list') {
                    var buildPriceRow = document.getElementById('buildPrice-row');
				    var buildDiscountRow = document.getElementById('buildDiscount-row');
				        if (discount == 0) {
					        buildPriceRow.style.display = 'none';
					        buildDiscountRow.style.display = 'none';
				        }
			    }
				// get build info total for base model
				var quotePrice = document.getElementById('quote-price');
				var quotePriceStr = getText(quotePrice);
                //alert(quotePriceStr);
                replaceText(buildTotalEl, quotePriceStr);

                // calculate build info for options and attachments
				var total = price - discount;

                //alert("Price: " + price + "\nDiscount: " + discount);
                //alert(total.toFixed(2));
                //alert(buildImgEl.id);

                if (buildList.className == 'options-list' || buildList.className == 'attachments-list' ){

                    document.getElementById('build-name').innerHTML = name;
                    document.getElementById('build-desc').innerHTML = desc;
                    buildImgEl.src = buildImgSize;
				}
        
                if(buildImgEl.id != null) {
                    buildImgEl.alt = name;
                }

                if(buildList.className != 'options-list') {
                    replaceText(buildDescEl, desc);
                }

                replaceText(buildPriceEl, bQ.addSeparatorsNF(price.toFixed(2),'.', '.', ','));
				replaceText(buildDiscountEl, bQ.addSeparatorsNF(discount.toFixed(2),'.', '.', ','));
				replaceText(buildTotalEl, bQ.addSeparatorsNF(total.toFixed(2),'.', '.', ','));
                //if (buildList.className == 'attachments-list') bQ.addSelect(name, price, bQ.getBuildItemId());

    },

    updateQuote: function() {

        if (!document.getElementById && !document.getElementsByTagName && !document.createElement) return;
		if (!document.getElementById('build-items')) { return; }

        // setup quote area elements
		var baseEl = document.getElementById('quote-base');
		var optionsEl = document.getElementById('quote-options');
		var attachmentsEl = document.getElementById('quote-attachments');
    var msrpEl = document.getElementById('quote-msrp');
		var discountEl = document.getElementById('quote-discount');
		var priceEl = document.getElementById('quote-price');

		// check class of build-items list to customize quote update
		var buildList = document.getElementById('build-items');
		var buildItems = buildList.getElementsByTagName('input');

        // select base model quote update
		var buildTotal = 0;
        //var buildItemPrice = 0;
        var discountTotal = Math.abs(bQ.getDiscountValue());

        for (var i=0; i<buildItems.length; i++) {

            if (buildItems[i].type != "hidden" && buildItems[i].checked == true) {

                var buildStrings = buildItems[i].parentNode.getElementsByTagName('span');
                var buildString = buildStrings[0].id;
                var buildArray = buildString.split("~");
                var buildItemPrice = Math.abs(buildArray[0]);
                var buildItemDiscount = Math.abs(buildArray[1]);
                var calcYourPrice;


                if (buildList.className == 'basemodel-list') {
					replaceText(baseEl, "$" + bQ.addSeparatorsNF(buildItemPrice.toFixed(2),'.', '.', ','));
					replaceText(msrpEl, "$" + bQ.addSeparatorsNF(buildItemPrice.toFixed(2),'.', '.', ','));
					replaceText(discountEl, "$" + bQ.addSeparatorsNF(buildItemDiscount.toFixed(2),'.', '.', ','));
					if (discountTotal == 0) {
						document.getElementById('discount-row').style.display = "none";
					} else if (discountTotal != 0) {
						document.getElementById('discount-row').style.display = "block";
					}

                    calcYourPrice = buildItemPrice - buildItemDiscount;
					replaceText(priceEl, "$" + bQ.addSeparatorsNF(calcYourPrice.toFixed(2),'.', '.', ','));

					// update total in build info column
					var buildInfoTotalEl = document.getElementById('build-total');
					replaceText(buildInfoTotalEl, "$" + bQ.addSeparatorsNF(calcYourPrice.toFixed(2),'.', '.', ','));
				} else if (buildList.className == 'options-list' || buildList.className == 'attachments-list') {
					buildTotal += buildItemPrice;
                    discountTotal += buildItemDiscount;
				}
			}
			if (buildList.className != 'basemodel-list') {
                var calcMsrp;
                var attValue;
                var baseModelPrice = bQ.filterNum(getText(baseEl));
                if (buildList.className == 'options-list') {
					replaceText(optionsEl, "$" + bQ.addSeparatorsNF(buildTotal.toFixed(2),'.', '.', ','));
					calcMsrp = Math.abs(baseModelPrice) + Math.abs(buildTotal);
				} else if (buildList.className == 'attachments-list') {
                    // Get the attachment value
                    if ((buildItems[i].type == "radio" || buildItems[i].type == "checkbox") && buildItems[i].checked) {
                        attValue = (buildItems[i].id).replace(/attachment\-/, "");
//                        alert("Build Items\nType: " + buildItems[i].type
//                                + "\nChecked: " + buildItems[i].checked
//                                + "\nValue: " + attValue);

                        // Get price for current attachment
                        var url = "/buildandquote/bq_ajax.html?id=" + attValue;
                        //alert(url);
                        //bQ.httpRequest(url, "update");
                        var test = jQuery.get(url);
                        //alert(test.responseText);
                        var jTemp = eval(test.responseText);//bQ.getAlertResult());
                        //alert(jTemp);
                        var price = Math.abs(jTemp[3]);
                        alert(price);
                    }

                    var totalAttachments = bQ.filterNum(getText(attachmentsEl));
                    replaceText(attachmentsEl, "$" + bQ.addSeparatorsNF(totalAttachments,'.', '.', ','));
                    var initOptions = bQ.filterNum(getText(optionsEl));
                    calcMsrp = Math.abs(baseModelPrice) + Math.abs(initOptions) + Math.abs(totalAttachments);
				}
				replaceText(msrpEl, "$" + bQ.addSeparatorsNF(calcMsrp.toFixed(2),'.', '.', ','));
				var calcDiscount = Math.abs(discountTotal);
				replaceText(discountEl, "$" + bQ.addSeparatorsNF(calcDiscount.toFixed(2),'.', '.', ','));
				if (calcDiscount == 0) {
						document.getElementById('discount-row').style.display = "none";
					} else if (calcDiscount != 0) {
						document.getElementById('discount-row').style.display = "block";
					}
				calcYourPrice = Math.abs(calcMsrp) - Math.abs(calcDiscount);
				replaceText(priceEl, "$" + bQ.addSeparatorsNF(calcYourPrice.toFixed(2),'.', '.', ','));
			}

		}
	},

    setPriceDiscount: function(buildItemPrice, buildItemDiscount) {
        this.buildItemPrice = buildItemPrice;
        this.buildItemDiscount = buildItemDiscount;
    },

    setDiscountValue: function(val) {
        spDiscount = val;
    },
    getDiscountValue: function() {
        return spDiscount;
    },

    setBuildItemId: function(id) {
        buildItemId = id;
    },
    getBuildItemId: function() {
        return buildItemId;
    },

    filterNum: function(str) {
		re = /^\$|,/g;
		return str.replace(re, "");
	},

  addTableRow: function(name, price, id) {
    var totalAtt = 0;
    var quoteAtt = document.getElementById('quote-attachments');
    var table = document.getElementById('quote-table');
    var tbody = document.getElementById('quote-table1');
    var newRow = document.createElement("tr");
        newCell = document.createElement("td");
        newCell.addClassName('selection');
        newCell.addClassName('fye');
        newCell.setAttribute("colspan", "2");
    var remove = document.createElement('a');
    var linkText=document.createTextNode('remove');
      remove.appendChild(linkText);
      remove.setAttribute('href', "#");
      remove.onclick = function() {
          tbody.removeChild(newRow);
          bQ.uncheckList(id);
      }
    newtext = document.createTextNode(name+" $"+price.toFixed(2)+" ");
    newCell.appendChild(newtext);
      newCell.appendChild(remove);
    newRow.appendChild(newCell);
    tbody.appendChild(newRow);
     totalAtt += price;
    replaceText(quoteAtt, "$" + bQ.addSeparatorsNF(totalAtt.toFixed(2),'.', '.', ','));
  },

  uncheckList: function(id) {         
    var buildList = document.getElementById('build-items');
	var buildItems = buildList.getElementsByTagName('input');
	for (var i=0; i<buildItems.length; i++) {
        if (buildItems[i].type != "hidden" && buildItems[i].checked == true) {
            var buildItemId = buildItems[i].value;
            if(id == buildItemId) buildItems[i].checked = false;
            bQ.updateQuote();
        }
    }
  },

   addSelect: function(arg1, arg2, arg3) {
       var status = false;
       var buttonAdd = document.getElementById('add_btnId');
       var selectLists = document.getElementsByTagName('select');
       buttonAdd.onclick = function () {
         for(i=0; i < selectLists.length; i++) {
               var hiddenid = 'opt'+(i+1)+'_'+bQ.getBuildItemId();
               var hiddenValue = document.getElementById(hiddenid);
               if(selectLists[i].selectedIndex != -1) hiddenValue.value = eval(selectLists[i].options[selectLists[i].selectedIndex].value);
         }
           if(!status) bQ.addTableRow(arg1, arg2, arg3); status = true;
           bQ.updateQuote();
           var location = document.location; location += "#fye"; document.location.replace(location);
       }
   },


    addSeparatorsNF: function(nStr, inD, outD, sep) {
        nStr += '';
        var dpos = nStr.indexOf(inD);
        var nStrEnd = '';
        if (dpos != -1) {
                nStrEnd = outD + nStr.substring(dpos + 1, nStr.length);
                nStr = nStr.substring(0, dpos);
        }
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(nStr)) {
                nStr = nStr.replace(rgx, '$1' + sep + '$2');
        }
        return nStr + nStrEnd;
	},

	highlightErrors: function() {
		if (!document.getElementById && !document.getElementsByTagName && !document.createElement) return;
		if (!document.getElementById('sendForQuoteForm')) return;
		var sendFormSpans = document.getElementById('sendForQuoteForm').getElementsByTagName('span');
		for (i=0; i<sendFormSpans.length; i++) {
			if (sendFormSpans[i].className == 'error' && sendFormSpans[i].childNodes.length != 0) sendFormSpans[i].parentNode.className = 'validate';
		}
	}
}

// add quote events
addEvent(window, 'load', bQ.findBuildItems, false);
addEvent(window, 'load', bQ.markActiveItems, false);
addEvent(window, 'load', bQ.updateQuote, false);
addEvent(window, 'load', bQ.highlightErrors, false);

if (!window.Modalbox)
   var Modalbox = new Object();

Modalbox.Methods = {

	setOptions: function(options) {
		this.options = {
			overlayClose: true, // Close modal box by clicking on overlay
			width: 400,
			height: 400
		};
		Object.extend(this.options, options || {});
	},

	_init: function() {
		// Define there page content starts (first element after body)
		this.pageContent = document.body.childNodes[0];

		//Create the overlay
		this.MBoverlay = document.createElement("div");
		this.MBoverlay.id = "MB_overlay";


		this.hide = this.hide.bindAsEventListener(this);

		if(this.options.overlayClose)
			Event.observe(this.MBoverlay, "click", this.hide );

		document.body.insertBefore(this.MBoverlay, document.body.firstChild);

		//Create the window
		this.MBwrapper = document.createElement("div");
		this.MBwrapper.id = "MB_wrapper";

		this.MBwindow = document.createElement("div");
		this.MBwindow.id = "MB_window";
		this.MBwindow.style.display = "none";

		this.MBheader = document.createElement("div");
		this.MBheader.id = "MB_header";

		this.MBframe = document.createElement("div");
		this.MBframe.id = "MB_frame";

		this.MBcontent = document.createElement("div");
		this.MBcontent.id = "MB_content";

		this.MBloading = document.createElement("div");
		this.MBloading.id = "MB_loading";
		this.MBloading.appendChild(document.createTextNode("Loading..."));

		this.MBcaption = document.createElement("div");
		this.MBcaption.id = "MB_caption";

		this.MBclose = document.createElement("A");
		this.MBclose.title = "Close window";
		this.MBclose.id = "MB_close";
		this.MBclose.href = "#";
		this.MBclose.innerHTML = "&times;";

		Event.observe(this.MBclose, "click", this.hide );

		this.MBheader.appendChild(this.MBcaption);
		//this.MBheader.appendChild(this.MBclose);
		this.MBframe.appendChild(this.MBheader);
		this.MBcontent.appendChild(this.MBloading);
		this.MBframe.appendChild(this.MBcontent);
		this.MBwindow.appendChild(this.MBframe);
		this.MBwrapper.appendChild(this.MBwindow);

		this._insertAfter(this.MBoverlay, this.MBwrapper, this.pageContent);

		this.isInitialized = true;
	},

	show: function(title, url, options) {
		this.title = title;
		this.url = url;
		this.setOptions(options);

		if(!this.isInitialized)
			this._init();

		// Initial scrolling position of the window. To be used for remove scrolling effect during ModalBox appearing
		this.initScrollX = window.pageXOffset || document.body.scrollLeft || document.documentElement.scrollLeft;
		this.initScrollY = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;

		if (navigator.appVersion.match(/\bMSIE\b/))
		{
			document.body.style.position = "relative";
			document.body.style.height = document.documentElement.clientHeight + "px";
			document.body.style.width = document.documentElement.clientWidth + "px";
		}
		document.body.style.overflow = 'hidden';

		if(!this.MBcaption.childNodes)
			this.MBcaption.appendChild(document.createTextNode(title));
		else
			this.MBcaption.innerHTML = title;

		if(this.MBwindow.style.display == "none") {  // First modal box appearing
			this._toggleSelects();
			this._setOverlay();
			this._setWidth();
			this._setPosition();
			Effect.SlideDown(this.MBwindow, {duration:0.75, afterFinish: this.loadContent.bind(this) } );
		} else {
			this.currentDims = [this.MBwindow.offsetWidth, this.MBwindow.offsetHeight];
			new Effect.ScaleBy(this.MBwindow,
							   (this.options.width - this.currentDims[0]), //New width calculation
							   (this.options.height - this.currentDims[1]), //New height calculation
								{afterFinish: this._loadAfterResize.bind(this),
								beforeStart: function(effect) { effect.element.firstChild.childNodes[1].innerHTML = "Loading..."; effect.element.firstChild.childNodes[1].style.height = "auto"; }
			});
		}

		this._setWidthAndPosition = this._setWidthAndPosition.bindAsEventListener(this);
		this.kbdHandler = this.kbdHandler.bindAsEventListener(this);

		Event.observe(window, "resize", this._setWidthAndPosition );
		Event.observe(document, "keypress", this.kbdHandler );
	},

	hide: function(argument) {
		if(argument) Event.stop(argument); // If an event given as an argument, stop this event
		Effect.SlideUp(this.MBwindow, {duration:0.35, afterFinish: this._deinit.bind(this) } );
	},

	loadContent: function ()
	{
        var url = Modalbox.url;
		var MBcontent = Modalbox.MBcontent;

        var self = this;
        //alert(self);
        //MBcontent.innerHTML = "<span style='color:#000;'>"+url+"</span>"+ "<br><br>"+document.getElementById('buttonsAlert').innerHTML;

        MBcontent.innerHTML = "<span style='color:#000;'>"+url+"</span>";

        var alertUl = document.getElementById('choiceAlert');

        self.moveFocus();
        var btnAccept = document.getElementById('acceptAlert');
        var btnDecline = document.getElementById('declineAlert');
        var alertInputs = alertUl.getElementsByTagName('input');
        var option;
        var listItem;

        // Modify button functions based on type of message
        if (self.type == "REPLACE") {

            btnAccept.onclick = function() {
                self.item.checked = false;
            }

            btnDecline.onclick = function() {
                option = document.getElementById("option-" + self.optId);
                listItem = option.parentNode.parentNode;
                option.checked = "checked";
                listItem.className = "active";
                Effect.SlideUp(self.MBwindow, {duration:0.35, afterFinish: self._deinit.bind(self) } );
            }

        } else if (self.type == "REMOVE") {

            btnAccept.onclick = function() {
                var children = alertUl.getElementsByTagName("label");
                var option;
                var tempId;
                // Get all needed ids and uncheck them
                for(var d = 0; d < children.length; d++) {
                    tempId = children[d].id;
                    tempId = tempId.replace(/remove/, 'option');
                    option = document.getElementById(tempId);
                    listItem = option.parentNode.parentNode;
                    option.checked = false;
                    listItem.className = "";
                }
                Effect.SlideUp(self.MBwindow, {duration:0.35, afterFinish: self._deinit.bind(self) } );
            }

            btnDecline.onclick = function () {
                var option = document.getElementById("option-" + self.optId);
                listItem = option.parentNode.parentNode;
                option.checked = "checked";
                listItem.className = "active";
                Effect.SlideUp(self.MBwindow, {duration:0.35, afterFinish: self._deinit.bind(self) } );
            }

        } else if (self.type == "CHOICE") {
            var choiceType = document.getElementById("choiceElement");
            if (choiceType.value == "optional") {

                btnAccept.onclick = function() {
                    for(var x = 0; x < alertInputs.length; x++) {
                        if (alertInputs[x].type == "checkbox") {
                            var radioOption;
                            var listItem;
                            // Make sure to check those that were selected
                            if(eval(alertInputs[x].checked)) {
                                radioOption = document.getElementById("option-" + eval(alertInputs[x].value));
                                listItem = radioOption.parentNode.parentNode;
                                radioOption.checked = true;
                                listItem.className = "active";
                            // Make sure to uncheck those not selected
                            } else {
                                radioOption = document.getElementById("option-" + eval(alertInputs[x].value));
                                listItem = radioOption.parentNode.parentNode;
                                radioOption.checked = false;
                                listItem.className = "";
                            }
                        }
                    }
                    Effect.SlideUp(self.MBwindow, {duration:0.35, afterFinish: self._deinit.bind(self) } );
                }

            } else if (choiceType.value == "all") {
                //alert("all");
                // Check all required options
                btnAccept.onclick = function() {
                    //alert("Accept - All");
                    var children = alertUl.getElementsByTagName("label");
                    var option;
                    var tempId;
                    // Get all needed ids and uncheck them
                    for(var d = 0; d < children.length; d++) {
                        tempId = children[d].id;
                        tempId = tempId.replace(/choice/, 'option');
                        option = document.getElementById(tempId);
                        listItem = option.parentNode.parentNode;
                        option.checked = true;
                        listItem.className = "active";
                    }

                    Effect.SlideUp(self.MBwindow, {duration:0.35, afterFinish: self._deinit.bind(self) } );
                }

                // Set selection trigger to not checked
                btnDecline.onclick = function() {
                    option = document.getElementById("option-" + self.optId);
                    listItem = option.parentNode.parentNode;
                    option.checked = false;
                    listItem.className = "";
                    Effect.SlideUp(self.MBwindow, {duration:0.35, afterFinish: self._deinit.bind(self) } );                    
                }
            } else if (choiceType.value == "required-one") {

                btnAccept.onclick = function() {
                    var children = alertUl.getElementsByTagName("label");
                    var option;
                    var tempId;
                    tempId = children[0].id;
                    tempId = tempId.replace(/choice/, 'option');
                    option = document.getElementById(tempId);
                    listItem = option.parentNode.parentNode;
                    option.checked = true;
                    listItem.className = "active";
                    Effect.SlideUp(self.MBwindow, {duration:0.35, afterFinish: self._deinit.bind(self) } );
                }

                btnDecline.onclick = function() {
                    option = document.getElementById("option-" + self.optId);
                    listItem = option.parentNode.parentNode;
                    option.checked = false;
                    listItem.className = "";
                    Effect.SlideUp(self.MBwindow, {duration:0.35, afterFinish: self._deinit.bind(self) } );
                }

            } else if (choiceType.value == "required-more") {

                btnAccept.onclick = function() {
                    for(var x = 0; x < alertInputs.length; x++) {
                        if (alertInputs[x].type == "radio") {
                            var radioOption;
                            var listItem;
                            // Make sure to check those that were selected
                            if(eval(alertInputs[x].checked)) {
                                radioOption = document.getElementById("option-" + eval(alertInputs[x].value));
                                listItem = radioOption.parentNode.parentNode;
                                radioOption.checked = true;
                                listItem.className = "active";
                            }
                        }
                    }
                    Effect.SlideUp(self.MBwindow, {duration:0.35, afterFinish: self._deinit.bind(self) } );
                }

                btnDecline.onclick = function() {
                    option = document.getElementById("option-" + self.optId);
                    listItem = option.parentNode.parentNode;
                    option.checked = false;
                    listItem.className = "";
                    Effect.SlideUp(self.MBwindow, {duration:0.35, afterFinish: self._deinit.bind(self) } );
                }

            }
            
        } else if (self.type == "CONFLICT") {
            var oldValue;
            //alert("option-" + self.optId);
            option = document.getElementById("option-" + self.optId);
            var radioOptions = document.getElementsByName(option.name);

            btnAccept.onclick = function() {
                // Check to see if this is a checkbox or radio button, if radio button, set to old value
                if (option.type == "checkbox") {
                    option.checked = false;
                    option.parentNode.parentNode.className = "";

                // option is a radio button, get old value and set equal to that
                } else {
                    oldValue = document.getElementById("old_" + option.name);

                    for (var a = 0; a < radioOptions.length; a++) {
                        if (radioOptions[a].value == oldValue.value) {
                            radioOptions[a].checked = true;
                            radioOptions[a].parentNode.parentNode.className = "active";
                        } else {
                            radioOptions[a].parentNode.parentNode.className = "";
                        }
                    }
                }
                Effect.SlideUp(self.MBwindow, {duration:0.35, afterFinish: self._deinit.bind(self) } );
            }
        }
    },

    setItemToReplace: function(item) {
        this.item = item;
    },

    getItemToReplace: function() {
        return item;
    },

    setOptionId: function(optId) {
        this.optId = optId;
    },

    setAlertType: function(type) {
        this.type = type;
    },
    getOptionId: function() {
        return optId;
    },

    moveFocus: function() {
		// Move focus on content area
		this.MBcontent.focus();

		// If the ModalBox frame containes form elements or links, first of them will bi focused after loading content
		// Trying to find focusable element in loaded content
		this.focusEl = $$("#MB_content input", "#MB_content textarea", "#MB_content select", "#MB_content button", "#MB_content a", "#MB_close").first();
		// Set focus on the first element
		this.focusEl.focus();
	},

	_loadAfterResize: function() {
		this._setWidth();
		this._setPosition();
		this.loadContent();
	},

	kbdHandler: function(e) {
		switch(e.keyCode)
		{
			case Event.KEY_TAB:
				// Find last 'focusable' element in ModalBox content to catch event on it. If no elements found, uses close ModalBox button
				this.lastFocusEl = $$("#MB_close", "#MB_content input", "#MB_content textarea", "#MB_content select", "#MB_content button", "#MB_content a").last();
				if(Event.element(e) == this.lastFocusEl)
				{
					Event.stop(e);
					this.moveFocus();
				}
			break;

			case Event.KEY_ESC:
				this.hide(e);
			break;
		}
	},

	_deinit: function()
	{
		this._toggleSelects();
		Event.stopObserving(this.MBclose, "click", this.hide );
		if(this.options.overlayClose)
			Event.stopObserving(this.MBoverlay, "click", this.hide );
		Event.stopObserving(window, "resize", this._setWidthAndPosition );
		Event.stopObserving(document, "keypress", this.kbdHandler );

		Effect.toggle(this.MBoverlay, 'appear', {duration: 0.35, afterFinish: this._removeElements.bind(this) });
	},

	_removeElements: function () {
		if (navigator.appVersion.match(/\bMSIE\b/))
		{
			document.body.style.position = "";
			document.body.style.height = "";
			document.body.style.width = "";
		}
		document.body.style.overflow = "auto";
		window.scrollTo(this.initScrollX, this.initScrollY);
		Element.remove(this.MBoverlay);
		Element.remove(this.MBwrapper);
		this.isInitialized = false;
	},

	_setOverlay: function () {
		var array_page_size = this._getWindowSize();
		if((navigator.userAgent.toLowerCase().indexOf("firefox") != -1))
			this.MBoverlay.style.width = "100%";
		else
			this.MBoverlay.style.width = array_page_size[0] + "px";

		var max_height = Math.max(this._getScrollTop() + array_page_size[1], this._getScrollTop() + this.options.height + 30);
		this.MBoverlay.style.height = max_height + "px";
	},

	_setWidth: function () {
		var array_page_size = this._getWindowSize();

		//Set size
		this.MBwrapper.style.width = this.options.width + 10 +"px";
		this.MBwindow.style.width = this.options.width + "px";

		this.MBwrapper.style.height = this.options.height + "px";
		this.MBwindow.style.height = this.options.height + "px";
		this.MBcontent.style.height = this.options.height - 42 + "px";
	},

	_setPosition: function () {
		var array_page_size = this._getWindowSize();
		this.MBwrapper.style.left = ((array_page_size[0] - this.MBwrapper.offsetWidth) / 2 ) + "px";
		this.MBwindow.style.left = "0px";
		this.MBwrapper.style.top = this._getScrollTop() + "px";
	},

	_setWidthAndPosition: function () {
		this._setOverlay();
		this._setPosition();
	},

	_getWindowSize: function (){
		var window_width, window_height;
		if (self.innerHeight) {	// all except Explorer
			window_width = self.innerWidth;
			window_height = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			window_width = document.documentElement.clientWidth;
			window_height = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			window_width = document.body.clientWidth;
			window_height = document.body.clientHeight;
		}
		return [window_width, window_height];
	},

	_insertAfter: function(parentNodeLink, insertion, insertionNodeReference) {
		return parentNodeLink.parentNode.insertBefore(insertion, insertionNodeReference);
	},

	_getScrollTop: function () {
		//From: http://www.quirksmode.org/js/doctypes.html
		var theTop;
		if (document.documentElement && document.documentElement.scrollTop)
			theTop = document.documentElement.scrollTop;
		else if (document.body)
			theTop = document.body.scrollTop;
		return theTop;
	},

	// For IE browsers -- hiding all SELECT elements
	_toggleSelects: function() {
		if (navigator.appVersion.match(/\bMSIE\b/))
		{
			var selectsList = this.pageContent.getElementsByTagName("select");
			var selects = $A(selectsList);
			selects.each( function(select) {
				select.style.visibility = (select.style.visibility == "") ? "hidden" : "";
			});
		}
	}
}

Object.extend(Modalbox, Modalbox.Methods);

Effect.ScaleBy = Class.create();
Object.extend(Object.extend(Effect.ScaleBy.prototype, Effect.Base.prototype), {
  initialize: function(element, byWidth, byHeight) {
    this.element = $(element)
    var options = Object.extend({
	  scaleFromTop: true,
      scaleMode: 'box',        // 'box' or 'contents' or {} with provided values
      scaleByWidth: byWidth,
	  scaleByHeight: byHeight
    }, arguments[3] || {});
    this.start(options);
  },
  setup: function() {
    this.elementPositioning = this.element.getStyle('position');

    this.originalTop  = this.element.offsetTop;
    this.originalLeft = this.element.offsetLeft;

    this.dims = null;
    if(this.options.scaleMode=='box')
      this.dims = [this.element.offsetHeight, this.element.offsetWidth];
	 if(/^content/.test(this.options.scaleMode))
      this.dims = [this.element.scrollHeight, this.element.scrollWidth];
    if(!this.dims)
      this.dims = [this.options.scaleMode.originalHeight,
                   this.options.scaleMode.originalWidth];

	this.deltaY = this.options.scaleByHeight;
	this.deltaX = this.options.scaleByWidth;
  },
  update: function(position) {
    var currentHeight = this.dims[0] + (this.deltaY * position);
	var currentWidth = this.dims[1] + (this.deltaX * position);

    this.setDimensions(currentHeight, currentWidth);
  },

  setDimensions: function(height, width) {
    var d = {};
    d.width = width + 'px';
    d.height = height + 'px';

	var topd  = (height - this.dims[0])/2;
	var leftd = (width  - this.dims[1])/2;
	if(this.elementPositioning == 'absolute') {
		if(!this.options.scaleFromTop) d.top = this.originalTop-topd + 'px';
		d.left = this.originalLeft-leftd + 'px';
	} else {
		if(!this.options.scaleFromTop) d.top = -topd + 'px';
		d.left = -leftd + 'px';
	}
    this.element.setStyle(d);
  }
});
