/*=================================================
  JAVASCRIPT FUNCTIONS FOR TOSHIBADIRECT DETAIL BTO
  =================================================*/

var ajaxReq = null;
var ajaxXmlDoc = null;

var accessoriesPrice = 0.0;
var warrantiesPrice = 0.0;

var cmpXsellExtendedWarrantiesPoids = new Array();
    cmpXsellExtendedWarrantiesPoids.push('extended_warranty_none~0.00');

var prdXsellextendedWarrantiesPoids = new Array();
prdXsellextendedWarrantiesPoids.push('extended_warranty_none~0.00');

var featuredExtendedWarrantiesPoids = new Array();

var previouslyCheckedWarrantyPoid = '';
var previouslyCheckedWarrantyPrice = '';
var extWarrantyToAddPoid = '';

var preSelectedAccessoryOidsPip = '';

window.onscroll = scroll;

var ajaxResponseProcessed = false;

function scroll() {
    var summaryTop;
    var currentTop;
    try
    {
        summaryTop = document.getElementById('div_customize').offsetTop;
        if (document.documentElement && !document.documentElement.scrollTop) {
                // IE6 +4.01 but no scrolling going on
                currentTop = 0;
       } else if (document.documentElement && document.documentElement.scrollTop) {
                // IE6 +4.01 and user has scrolled
                currentTop = document.documentElement.scrollTop;
       } else if (document.body && document.body.scrollTop) {
                // IE5 or DTD 3.2
                currentTop = document.body.scrollTop;
       }
    }
    catch(error)
    {}

    if (window.pageYOffset != undefined) {
	currentTop = window.pageYOffset; // Firefox, Mozilla, Opera, etc.
    }

    if (currentTop > summaryTop) {
        var leftBottom = jQuery("#customize_cell").offset().top + jQuery("#customize_cell").height();
		var rightBottom = jQuery("#div_summary").offset().top + jQuery("#div_summary").height();
    	if (document.getElementById('div_summary').style.marginTop > (currentTop - summaryTop) + 'px' || rightBottom < leftBottom) {
			// keep summary box at the top of viewport (browser window)
			document.getElementById('div_summary').style.marginTop = currentTop - summaryTop + 'px';
        }
    } else {
        document.getElementById('div_summary').style.marginTop = '0px';
    }
}

function processOnClick(componentType, component, poid, omnitureAccount) {
    // client-side
    ajaxResponseProcessed = false;
    updatePriceDeltas(componentType, component);
    updateSummary(componentType, component);
    selectSquareTradeWarrantyBand();
    // server-side
    processAjax(poid, '');
}

// only show the xsl warranty coverage related to the component warranty length
function showValidWarrCoverageType(compWarrLen) {
    // make sure the xsl warr coverage length selected has the same length of coverage
    // as the standard limited warranty, otherwise uncheck it
    // and check the same warranty type in the correct coverage length
    selectedLength = $(".xslWarrLen > td > input:checked").attr('warrantylength');
    selectedType = $(".xslWarrLen > td > input:checked").attr('warrantytype');
    if ($(".xslWarrLen > td > input[warrantytype='" +selectedType +"'][warrantylength^='" + compWarrLen + " Year" + "']").length > 0) {
        for(var i=0, iMax=$(".xslWarrLen > td > input[warrantytype='" +selectedType +"'][warrantylength^='" + compWarrLen + " Year" + "']").length; i< iMax; i++) {
            if(!$(".xslWarrLen > td > input[warrantytype='" +selectedType +"'][warrantylength^='" + compWarrLen + " Year" + "']")[i].hidden) {
                $(".xslWarrLen > td > input[warrantytype='" +selectedType +"'][warrantylength^='" + compWarrLen + " Year" + "']")[i].click();
                break;
            }
        }
    } else {
        $(".xslWarrLen > td > input[warrantytype='Standard Warranty'][warrantylength^='" + compWarrLen + " Year" + "']").click();
    }

    // hides the whole xsl warranties list and then shows only relevant ones
    $(".xslWarrLen").hide();
    $(".xslWarrLen" + compWarrLen.toString()).show();

    // then just show the correct price band for squaretrade
    selectSquareTradeWarrantyBand();

    // if visible checkboxes are not checked, check the default
    var visibleChecked = 0
    $(".xslWarrLen:visible").each(function() {
        if($(this).find("input:checked").length > 0) {
            visibleChecked++;
        }
    });
    if (visibleChecked == 0) {
        $(".cl" + (compWarrLen-1)).click();
    }
}


var previousPrice = '';

function processOnClickAccessories(inputType, isChecked, xsellOid, price, isCartOnly) {
    var newPrice;
    var oldPrice = document.getElementById('finalPriceTop').innerHTML;

    price = price.replace('$', '');
    if (price.indexOf('FREE') != -1)
    	price = '0.00';

    if (inputType == 'checkbox') {
        if (isChecked) {
            newPrice = addFormattedAmt(oldPrice, price);
            accessoriesPrice = (addFormattedAmt(document.getElementById('totalAccessories').innerHTML, price));
        } else {
            newPrice = subtractFormattedAmt(oldPrice, price);
            accessoriesPrice = (subtractFormattedAmt(document.getElementById('totalAccessories').innerHTML, price));
        }
    } else { // radio
        if (previousPrice == '') {
            newPrice = addFormattedAmt(oldPrice, price);
            accessoriesPrice = (addFormattedAmt(document.getElementById('totalAccessories').innerHTML, price));
        } else {

            oldPrice = subtractFormattedAmt(oldPrice, previousPrice);
            newPrice = addFormattedAmt(oldPrice, price);

            accessoriesPrice = (subtractFormattedAmt(document.getElementById('totalAccessories').innerHTML, previousPrice));
            accessoriesPrice = (addFormattedAmt(accessoriesPrice, price));
        }

        previousPrice = price;
    }

    var xsellChkBoxes = jQuery(".cl" + xsellOid);
    if(xsellChkBoxes && xsellChkBoxes.length && xsellChkBoxes.length >0) {
        for(var v=0; v<xsellChkBoxes.length; v++) {
            xsellChkBoxes[v].checked = isChecked;
        }
    }

    if (isChecked) {
		if (isCartOnly) {
			selectedCartOnly++;
			jQuery(".isCartOnly").show();
		}
	} else {
		if (isCartOnly) {
			selectedCartOnly--;
			if (selectedCartOnly == 0) jQuery(".isCartOnly").hide();
		}
	}


    newPrice = formatAmount(newPrice);

    document.getElementById('totalAccessories').innerHTML =  accessoriesPrice;
    document.getElementById('finalPriceTop').innerHTML = newPrice;
    document.getElementById('finalPriceBottom').innerHTML = newPrice;
    document.getElementById('finalPriceSummary').innerHTML = newPrice;
    previouslyCheckedWarrantyPrice = '';
    calculateAccessoriesTotal();
}

// when a user selects a different component of a given component type, this function updates the price delta
// e.g., add $xx.xx or subtract $xx.xx
function updatePriceDeltas(componentType, component) {
    var spans = document.getElementsByTagName('span');

    // the description of the selected component
    var checkedHtml = document.getElementById('span_add_subtract_' + componentType + '_' + component).innerHTML;
    var checkedPrice; // the price of the selected commponent
    var currentHtml; // the description of the current component (first through last)
    var currentPrice = ""; // the price of the current component (first through last)

    checkedPrice = checkedHtml.substr(checkedHtml.indexOf('$') + 1, checkedHtml.indexOf('<'));
    if (checkedHtml.indexOf("FREE") != -1)
        checkedPrice = 0.00;
    var isSubtractChecked = (checkedHtml.substr(1, 8) == 'subtract'); // is the selected component an add or subtract?
    var isSubtractCurrent; // is the current component (first through last) an add or subtract?

    var isCurrentChecked;

    var deltaPrice;

    for (var i = 0; i < spans.length; i++) {
        // only process selected component type
        if (spans[i].id.substring(0, 18 + componentType.length) == 'span_add_subtract_' + componentType) {
            currentHtml = spans[i].innerHTML;

	    currentPrice = currentHtml.substr(currentHtml.indexOf('$') + 1, currentHtml.indexOf('<'));
        isCurrentCartOnly = jQuery("#" + spans[i].id.replace("span_add_subtract_" + componentType, "xsellCartOnly")).html() == "true";
            if (currentHtml.indexOf("FREE") != -1)
            	currentPrice = 0.00;

            isSubtractCurrent = (currentHtml.substr(1, 8) == 'subtract');

            checkedPrice = parseFloat(unformatAmount(checkedPrice));

            if (currentPrice == "")
            	currentPrice = 0.00;
            currentPrice = parseFloat(unformatAmount(currentPrice));



            if (isSubtractCurrent && isSubtractChecked) {
                deltaPrice = (currentPrice - checkedPrice) * -1;
            } else if (!isSubtractCurrent && isSubtractChecked) {
                deltaPrice = checkedPrice + currentPrice;
            } else if (isSubtractCurrent && !isSubtractChecked) {
                deltaPrice = currentPrice * -1 - checkedPrice;
            } else  {
                deltaPrice = currentPrice - checkedPrice;
            }

	        //Since the price can have decimals, removed the rounding.
            //deltaPrice = parseFloat(Math.round(deltaPrice));

            isCurrentChecked = (spans[i].id == document.getElementById('span_add_subtract_' + componentType + '_' + component).id);

            if (isCurrentChecked == true) {
                spans[i].innerHTML = '';
            } else if (isCurrentChecked == false && deltaPrice < 0.0) {
                spans[i].innerHTML = '[subtract <strong>$' + formatCurrency(Math.abs(deltaPrice)) + '</strong>]';
                if (isCurrentCartOnly) spans[i].innerHTML = spans[i].innerHTML + "<div class=\"inCartSplat\">*</div>";
            } else if (isCurrentChecked == false && deltaPrice > 0.0) {
                spans[i].innerHTML = '[add <strong>$' + formatCurrency(deltaPrice) + '</strong>]';
                if (isCurrentCartOnly) spans[i].innerHTML = spans[i].innerHTML + "<div class=\"inCartSplat\">*</div>";
            } else if (isCurrentChecked == false && deltaPrice == 0.0) {
                spans[i].innerHTML = '[<strong>FREE</strong>]';
                if (isCurrentCartOnly) spans[i].innerHTML = spans[i].innerHTML + "<div class=\"inCartSplat\">*</div>";
            }
        }
    }
}

// 1) reset to initial state
// 2) based on hash rebuilt last state
// cmpOidsPipAndXsellsOidsPipAndPreSelXsellsOidsPip is formatted like #cmp123|cmp456|cmp789~xsl123|xsl456|xsl789~pre123|pre456|pre789
function initBto(poid, cmpOidsPipAndXsellsOidsPip) {
    // remove hash character at beginning
    if (cmpOidsPipAndXsellsOidsPip.length > 0) {
        cmpOidsPipAndXsellsOidsPip = cmpOidsPipAndXsellsOidsPip.substring(1, cmpOidsPipAndXsellsOidsPip.length);
    }

    var arrTmp = cmpOidsPipAndXsellsOidsPip.split("~");

    var arrCmpOids = arrTmp[0].split('|');
    var arrXsellsOids = arrTmp[1].split('|');
    var arrPreSelXsellsOids = arrTmp[2].split('|');
    ajaxResponseProcessed = false;
    processAjax(poid, arrTmp[0]); // only one AJAX call, not one per fireClickEvent

    for (var i = 0; i < arrCmpOids.length; i++) {
	//fireClickEvent(document.getElementById(arrCmpOids[i]));

        if (arrCmpOids[i] != '') {
            var tmp = document.getElementById(arrCmpOids[i]).name;
            var componentType = tmp.substring(5, tmp.length); // remove 'comp_'
            var component = document.getElementById(arrCmpOids[i]).id;

            updatePriceDeltas(componentType, component);
            updateSummary(componentType, component);

            document.getElementById(arrCmpOids[i]).checked = true;
        }
    }

    // subtract pre-selected components
    for (var i = 0; i < arrPreSelXsellsOids.length; i++) {
        if (arrPreSelXsellsOids[i] != '') {
            var inputType = document.getElementById(arrPreSelXsellsOids[i]).type;
            var price = document.getElementById('xselllFeaturedPrice_' + arrPreSelXsellsOids[i]).innerHTML;
            var isCartOnly = (document.getElementById('xsellFeaturedCartOnly_' + arrPreSelXsellsOids[i]).innerHTML == "true");

            processOnClickAccessories(inputType, false, arrPreSelXsellsOids[i], price, isCartOnly);

            document.getElementById(arrPreSelXsellsOids[i]).checked = false;
        }
    }


    // add selected components
    if (arrXsellsOids != null) {
        for (var i = 0; i < arrXsellsOids.length; i++) {
            //fireClickEvent(document.getElementById(arrXsellsOids[i]));

            if (arrXsellsOids[i] != '') {
                var inputType = '';
                var price = '';

                //process featured accessories, but exclude recommended xsells and component xsells
                if (document.getElementById('xslFeatured_price_' + arrXsellsOids[i]) && !document.getElementById('xsell_' + arrXsellsOids[i]) && !isCompXsells(arrXsellsOids[i])) {
                    document.getElementById(arrXsellsOids[i]).checked = true;
                    inputType = document.getElementById(arrXsellsOids[i]).type;
                    var price = document.getElementById('xsellFeaturedPrice_' + arrXsellsOids[i]).innerHTML;
                    var isCartOnly = (document.getElementById('xsellFeaturedCartOnly_' + arrXsellsOids[i]).innerHTML == "true");
                    processOnClickAccessories(inputType, true, arrXsellsOids[i], price, isCartOnly);
                    document.getElementById(arrXsellsOids[i]).checked = true;
                } else if (document.getElementById('xsell_' + arrXsellsOids[i]) && !isCompXsells(arrXsellsOids[i] )) {

                    //process xsell accessories but exclude component xsells
                    inputType = document.getElementById('xsell_' + arrXsellsOids[i]).type;
                    document.getElementById('xsell_' + arrXsellsOids[i]).checked = true;
                    if (inputType == 'radio'){
                        var price = document.getElementById('span_add_subtract_ExtWarranty_' + arrXsellsOids[i]).innerHTML;
                        price = price.toLowerCase().replace('[add <strong>', '').replace('</strong>]', '');
                        processWarranties(true, arrXsellsOids[i], price, (document.getElementById('xsellCartOnly_' + arrXsellsOids[i]).innerHTML == "true"));
                        document.getElementById('xsell_' + arrXsellsOids[i]).checked = true;
                    } else if (inputType == 'checkbox') {
                        var price = document.getElementById('xsl_price_' + arrXsellsOids[i]).innerHTML;
                        price = price.toLowerCase().replace('[add <strong>', '').replace('</strong>]', '');
                        processXsellOnClick(true, price, null, arrXsellsOids[i], document.getElementById('xslDesc_' + arrXsellsOids[i]).innerHTML, (document.getElementById('xsellCartOnly_' + arrXsellsOids[i]).innerHTML == "true"));
                    }

                } else if (isCompXsells(arrXsellsOids[i] )) {

                    if (document.getElementById(arrXsellsOids[i])){
                        document.getElementById(arrXsellsOids[i]).checked = true;
                        extWarrantyToAddPoid = arrXsellsOids[i];
                        var price = document.getElementById('span_add_subtract_ExtWarranty_' + arrXsellsOids[i]).innerHTML;
                        price = price.toLowerCase().replace('[add <strong>', '').replace('</strong>]', '');
                        price = price.toLowerCase().replace('[subtract <strong>', '').replace('</strong>]', '');
                        processWarranties(true, arrXsellsOids[i], price, (document.getElementById('xsellCartOnly_' + arrXsellsOids[i]).innerHTML == "true"));
                        document.getElementById(arrXsellsOids[i]).checked = true;
                    }
                }
            }
        }

    }
     calculateAccessoriesTotal();
}

function fireClickEvent(control) {
    if (control == null) {
        return;
    }

    if (document.all) { // IE
        control.fireEvent("onclick");
    } else { // Firefox etc.
        var clickEvent = window.document.createEvent("MouseEvent");
        clickEvent.initEvent("click", false, true);
        control.dispatchEvent(clickEvent);
    }
}

function processXsellOnClick (isChecked, price, xsellCategory, xsellOid, xsellDesc, isCartOnly){
    var accessorySelected = isAcessorySelected();
    addAccessory(isChecked, xsellOid, xsellDesc, accessorySelected);
    var finalPrice;

    if (isChecked){
        // hide [add price] div
        if (document.getElementById('xsl_price_' + xsellOid))
            document.getElementById('xsl_price_' + xsellOid).style.display = 'none';

        //remove from featured accessory section if the same oid is selected.
        if (document.getElementById(xsellOid)){
            document.getElementById(xsellOid).checked = false;
        }

        accessoriesPrice = (addFormattedAmt(document.getElementById('totalAccessories').innerHTML, price));
        finalPrice = formatAmount(addFormattedAmt(document.getElementById('finalPriceSummary').innerHTML, price));
		if (isCartOnly) {
			selectedCartOnly++;
			jQuery(".isCartOnly").show();
		}
    } else {
        // show [add price] div
        if (document.getElementById('xsl_price_' + xsellOid))
            document.getElementById('xsl_price_' + xsellOid).style.display = 'block';
        accessoriesPrice = (subtractFormattedAmt(document.getElementById('totalAccessories').innerHTML, price));
        finalPrice = formatAmount(subtractFormattedAmt(document.getElementById('finalPriceSummary').innerHTML, price));
		if (isCartOnly) {
        	selectedCartOnly--;
        	if (selectedCartOnly == 0) jQuery(".isCartOnly").hide();
        }
    }
    document.getElementById('totalAccessories').innerHTML =  accessoriesPrice;
    document.getElementById('finalPriceTop').innerHTML = finalPrice;
    document.getElementById('finalPriceBottom').innerHTML = finalPrice;
    document.getElementById('finalPriceSummary').innerHTML = finalPrice;

    calculateAccessoriesTotal();

}

function getXSells(featuredAccessories) {
    var xsells = '';

    // build pipe-separated list, e.g. XXX|YYY|ZZZ. do not include featured Acc again
    for (var i = 0; i < document.detailBtoForm.elements.length; i++) {
        if (document.detailBtoForm.elements[i].id.substring(0, 6) == 'xsell_' &&
            document.detailBtoForm.elements[i].checked && xsells.indexOf('|' + document.detailBtoForm.elements[i].value) == -1) {
            var selXsellOid = document.detailBtoForm.elements[i].value;
            var isAlsoFeatured = false;
            for(var f = 0; f < featuredAccessories.length; f++) {
                if(featuredAccessories[f] == selXsellOid) {
                    isAlsoFeatured = true;
                    break;
                }
            }
            if(isAlsoFeatured) {
                continue;
            }
            xsells += '|' + document.detailBtoForm.elements[i].value;
        }
    }

    // remove first pipe character
    if (xsells.length > 1) {
        xsells = xsells.substring(1, xsells.length);
    }

    return xsells;
}



function getCompXsells() {
    var compXsells = '';

    for (var i = 0; i < cmpXsellExtendedWarrantiesPoids.length; i++) {
        var arrTmp = cmpXsellExtendedWarrantiesPoids[i].split("~");
        if (arrTmp[0] == 'extended_warranty_none')
            continue;

        if (document.getElementById(arrTmp[0]) && document.getElementById(arrTmp[0]).checked) {
             compXsells += '|' + document.getElementById(arrTmp[0]).value;
		}
    }

    // remove first pipe character
        if (compXsells.length > 1) {
            compXsells = compXsells.substring(1, compXsells.length);
        }
        return compXsells;
}

function isCompXsells (oid) {
    for (var i = 0; i < cmpXsellExtendedWarrantiesPoids.length; i++) {
        var arrTmp = cmpXsellExtendedWarrantiesPoids[i].split("~");
        if (arrTmp[0] == oid){
            return true;
		}
    }
    return false;
}

function mergeAccessories (featuredAccessoriesNoDefault, xsells) {
    var accessories = featuredAccessoriesNoDefault;
    if (featuredAccessoriesNoDefault.length > 1 && xsells.length > 1)
        accessories = featuredAccessoriesNoDefault + "|" + xsells;
    else
        accessories = featuredAccessoriesNoDefault + xsells;

    return accessories;
}

function isAcessorySelected(){
    var accessorySelected = false;
    for (i = 0; i < document.detailBtoForm.elements.length; i++) {
        if (document.detailBtoForm.elements[i].type == 'checkbox') {
            var comp = document.detailBtoForm.elements[i].id;
            if (document.detailBtoForm.elements[i].checked){
                accessorySelected = true;
                break;
            }
        }
    }
    return accessorySelected;
}

function addAccessory(isChecked, xsellOid, xsellDesc, accessorySelected){

    /*if (isChecked) { //Add accessory to list
        if (document.getElementById('LI_' + xsellOid) != null && document.getElementById('LI_' + xsellOid).style.display == 'none') {
            document.getElementById('LI_' + xsellOid).innerHTML = '<DIV ID=LI_' + xsellOid + '><LI>' + xsellDesc + '</LI></DIV>';
            document.getElementById('LI_' + xsellOid).style.display = 'block';
        } else {
            document.getElementById('optionalAccessories').innerHTML =
            document.getElementById('optionalAccessories').innerHTML + '<DIV ID=LI_' + xsellOid + ' style=\'display:block;\'><LI>' + xsellDesc + '</LI></DIV>';
        }
    } else { // check boxes - remove current accessory from list
        document.getElementById('LI_' + xsellOid).style.display = 'none';
    }*/

    //If none of the accessory is selected or extended warranty is selected, hide whole accessory list area.
    if (accessorySelected == true || isExtendedWarrantySelected() == true){
        document.getElementById("accessoriesList_Text").style.display = 'none';
    } else {
        document.getElementById("accessoriesList_Text").style.display = 'none';
    }

}

function calculateAccessoriesTotal (){
   var total = "$0.00";

    //calculate featured accessories total
    var featuredAccOids = getFeaturedAccessories();
    var featuredAccOidsArray = [];
    if (featuredAccOids.length > 1) {
        featuredAccOidsArray = featuredAccOids.split("|");
        for (var i = 0; i < featuredAccOidsArray.length; i++) {
            var featuredAccOid = featuredAccOidsArray[i];
            if (document.getElementById("xslFeatured_price_" + featuredAccOidsArray[i])) {
                var price = document.getElementById("xsellFeaturedPrice_" + featuredAccOidsArray[i]).innerHTML;
                total = formatAmount(addFormattedAmt(total, price));
            }
        }
    }

    //calculate prodXsells total
    var prdXsellOids = getXSells(featuredAccOidsArray);
    var cmpXsellOids = getCompXsells();
    var xsellOids = mergeAccessories(prdXsellOids, cmpXsellOids);

    if (xsellOids.length > 1){
        var xsellOidsArray = xsellOids.split("|");
        for (var i = 0; i < xsellOidsArray.length; i++) {
            var xsellOid = xsellOidsArray[i];
            //if already considered in featuredAccOids, skip it
            var isAlsoFeatured = false;
            for(var f = 0; f < featuredAccOidsArray.length; f++) {
                if(featuredAccOidsArray[f] == xsellOid) {
                    isAlsoFeatured = true;
                    break;
                }
            }
            if(isAlsoFeatured) {
                continue;
            }
            /*
            if (isXsellWarranty(xsellOid)){
                var price = xsellWarrantyPrice(xsellOid);
                total = formatAmount(addFormattedAmt(total, removeAddSubtraceFromPrice(price)));
            }
            */
            else if (document.getElementById("xsl_price_" + xsellOid)) {
                var price = document.getElementById("xsl_price_" + xsellOid).innerHTML;
                total = formatAmount(addFormattedAmt(total, removeAddSubtraceFromPrice(price)));
            }
        }
    }

    var xsellWarrAndAccTotal = (addFormattedAmt(document.getElementById('totalWarranties').innerHTML, total));

    var finalPrice = formatAmount(addFormattedAmt(document.getElementById("ListPriceSummary").innerHTML, xsellWarrAndAccTotal));
    document.getElementById('totalAccessories').innerHTML =  removeDollarSign(total);
    document.getElementById('finalPriceTop').innerHTML = finalPrice;
    document.getElementById('finalPriceBottom').innerHTML = finalPrice;
    document.getElementById('finalPriceSummary').innerHTML = finalPrice;
}

function removeDollarSign(price){
    if (price.indexOf("$")>-1){
        var index = price.indexOf("$");
        price = price.substring((index+1), price.length);
        return price;
    } else
        return price;
}

function isXsellWarranty(oid){
    var spans = document.getElementsByTagName('span');
    for (var i = 0; i < spans.length; i++) {
        // only process selected component type
        if (spans[i].id == 'span_add_subtract_' + 'ExtWarranty' + '_' + oid) {
            return true;
        }
    }
    return false;
}

function xsellWarrantyPrice (oid){
    var spans = document.getElementsByTagName('span');
    for (var i = 0; i < spans.length; i++) {
        // only process selected component type
        if (spans[i].id == 'span_add_subtract_' + 'ExtWarranty' + '_' + oid) {
            return spans[i].innerHTML;
        }
    }
    return "0.00";
}


function removeAddSubtraceFromPrice (price){
    price = price.toLowerCase().replace('[add <strong>', '').replace('</strong>]', '');
    price = price.toLowerCase().replace('[subtract <strong>', '').replace('</strong>]', '');
    return price;
}

function clearFeaturedWarranty(){

    for (var i = 0; i < featuredExtendedWarrantiesPoids.length; i++) {
        var arrTmp = featuredExtendedWarrantiesPoids[i].split("~");

        if (document.getElementById(arrTmp[0]) && document.getElementById(arrTmp[0]).checked){
            document.getElementById(arrTmp[0]).checked = false;
            //processOnClickAccessories(document.getElementById(arrTmp[0]).type, false, arrTmp[0], document.getElementById("xsl_price_"+arrTmp[0]).innerHTML);
            previousPrice = '';
        }
    }
}

function processWarranties(isChecked, xsellOid, price, isCartOnly) {
    if (xsellOid != previousWarranty) {
		if (jQuery("#xsellCartOnly_"+previousWarranty).html() == "true") {
			selectedCartOnly--;
			if (selectedCartOnly == 0) jQuery(".isCartOnly").hide();
		}
		previousWarranty = xsellOid;
	}
    clearFeaturedWarranty();
    var finalPrice;
    if (price.indexOf('FREE') != -1)
           price = '0.00';

    if (isChecked) {
        clearExtendedWarrantiesFromAccessorySummary();
        updatePriceDeltas('ExtWarranty', xsellOid);
            if (xsellOid != 'extended_warranty_none') {
                //addAccessory(true, xsellOid, null, true);

                // hide [add price] div
                if (parseInt(xsellOid) < 10)
                    document.getElementById('span_add_subtract_ExtWarranty_' + xsellOid).innerHTML = '[ included in purchase price ]';

                //accessoriesPrice = (addFormattedAmt(document.getElementById('totalAccessories').innerHTML, price));
                warrantiesPrice = (addFormattedAmt(document.getElementById('totalWarranties').innerHTML, price));

                finalPrice = formatAmount(addFormattedAmt(document.getElementById('finalPriceSummary').innerHTML, price));
                //document.getElementById('totalAccessories').innerHTML = accessoriesPrice;
                document.getElementById('totalWarranties').innerHTML = warrantiesPrice;
                document.getElementById('finalPriceTop').innerHTML = finalPrice;
                document.getElementById('finalPriceBottom').innerHTML = finalPrice;
                document.getElementById('finalPriceSummary').innerHTML = finalPrice;

                previouslyCheckedWarrantyPoid = xsellOid;
                previouslyCheckedWarrantyPrice = price;

            }
        //}
		if (isCartOnly) {
			selectedCartOnly++;
			jQuery(".isCartOnly").show();
		}
    } else {
		if (isCartOnly) {
        	selectedCartOnly--;
        	if (selectedCartOnly == 0) jQuery(".isCartOnly").hide();
        }
    }
    calculateAccessoriesTotal();
}

function mergeExtendedWarrantyArray() {
    var newArray = prdXsellextendedWarrantiesPoids;
    for (var i = 0; i < cmpXsellExtendedWarrantiesPoids.length; i++) {
       newArray.push(cmpXsellExtendedWarrantiesPoids[i]);
    }
    return newArray;
}

function clearExtendedWarrantiesFromAccessorySummary(){

    var spans = document.getElementsByTagName('span');
    for (var i = 0; i < spans.length; i++) {
        // only process selected component type
        if (spans[i].id.substring(0, 18 + 11) == 'span_add_subtract_' + 'ExtWarranty') {
            spans[i].style.display = 'block';
        }
    }

    //Subtract previously selected warranty's price from Total.
    if (previouslyCheckedWarrantyPrice != '') { // the first time we don't need to subtract the previous price, because there is no previous price
        warrantiesPrice = (subtractFormattedAmt(document.getElementById('totalWarranties').innerHTML, previouslyCheckedWarrantyPrice));
        var finalPrice = formatAmount(subtractFormattedAmt(document.getElementById('finalPriceSummary').innerHTML, previouslyCheckedWarrantyPrice));
        document.getElementById('totalWarranties').innerHTML = warrantiesPrice;
        document.getElementById('finalPriceTop').innerHTML = finalPrice;
        document.getElementById('finalPriceBottom').innerHTML = finalPrice;
        document.getElementById('finalPriceSummary').innerHTML = finalPrice;
        previouslyCheckedWarrantyPrice = '';
        previouslyCheckedWarrantyPoid = '';
    }
}

function isExtendedWarrantySelected(){
    ExtendedWarrantiesPoids = mergeExtendedWarrantyArray();
    for (var i = 0; i < ExtendedWarrantiesPoids.length; i++) {
        var arrTmp = ExtendedWarrantiesPoids[i].split("~");
        if (document.getElementById(arrTmp[0]) && document.getElementById(arrTmp[0]).checked == true && arrTmp[0] != 'extended_warranty_none') {
            return true;
        }
    }
    return false;
}




// build summary box with default configuration
/*function loadSummary(imagePath, poid) {
    var summary = '';

    summary += '';
    summary += '	<tr class="summaryContTop">';
    summary += '		<td></td>';
    summary += '	</tr>';
    summary += '	<tr class="summaryContMid">';
    summary += '		<td>';
    summary += '		<table class="summaryGreyGrad" cellpadding="0" cellspacing="0" border="0">';
    summary += '			<tr>';
    summary += '				<td>';
    summary += '                    <table width="100%" cellpadding="0" cellspacing="0" border="0">';
    summary += '						<tr>';
    summary += '							<td class="cursor padTop15 padLeft5">';
    summary += '								<div class="red boldTxt font16">Laptop Summary</div>';
    summary += '							</td>';
    summary += '						</tr></table>';
    summary += '						<div style="height:305px; overflow-x:hidden; overflow-y:auto;"><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr>';
    summary += '							<td>';
    summary += '								<div class="margTop10 bordersTopBottom margBottom10 padding10">';
    summary += '									<table align="center" width="95%" cellpadding="0" cellspacing="0" border="0">';
    summary += '										<tr>';
    summary += '											<td class="font14 boldTxt medGreyTxt" align="left">Specifications</td>';
    summary += '											<td class="font11 medGreyTxt" align="right"><span class="red"><img src="/images/ui5/redSquareBullet.gif" />&nbsp;</span>customized</td>';
    summary += '										</tr>';
    summary += '									</table>';
    summary += '								</div>';
    summary += '							</td>';
    summary += '						</tr>';
    summary += '						<tr>';
    summary += '							<td>';
    summary += '								<ul class="font12 noMargins padLeft20 lineHeight18" style="list-style:square;  margin:0px 5px 0px 0px;">';

    var spans = document.getElementsByTagName('span');
    var componentType;

    for (var i = 0; i < spans.length; i++) {
        if (spans[i].id.substring(0, 18) == 'span_comp_default_') {
            componentType = spans[i].id.substring(18, spans[i].id.length);
            componentType = componentType.substring(0, componentType.indexOf("_"));
            summary += '<li id="li_summary_' + componentType + '"><span id="span_summary_' + componentType + '">' + spans[i].innerHTML + '</span></li>';
        }
    }

    summary += '                                </ul>';
    summary += '								<div id="accessoriesList_Text" class="margTop10 bordersTopBottom margBottom10 padding10" style="display:none;">';
    summary += '									<table align="center" width="95%" cellpadding="0" cellspacing="0" border="0">';
    summary += '										<tr>';
    summary += '											<td class="font14 boldTxt medGreyTxt" align="left" colspan="2">Accessories</td>';
    summary += '										</tr>';
    summary += '									</table>';
    summary += '								</div>';
    summary += '                            <ul class="font12 noMargins padLeft20 lineHeight18" style="list-style:square;">';
    summary += '                                <div id="optionalAccessories">';
    summary += '                                </div>';
    summary += '                            </ul>';




    summary += '							</td>';
    summary += '						</tr></table></div>';
    summary += '						<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr>';
    summary += '							<td>';
    summary += '								<table class="margTop10" style="border-top: 1px solid #000;" width="100%" cellpadding="0" cellspacing="5" border="0">';
    summary += '									<tr>';
    summary += '										<td class="trebuchet font11 drkGreyTxt" width="60%" align="left">Laptop Price as Configured:</td>';
    summary += '										<td class="red boldTxt font12" width="40%" align="right"><span id="ListPriceSummary">' + document.getElementById("finalPriceTop").innerHTML + '</span></td>';
    summary += '									</tr>';
    summary += '                                <tr>';
    summary += '                                    <td class="trebuchet font11 drkGreyTxt" width="60%" align="left">Accessories Total:</td>';
    summary += '                                    <td class="red boldTxt font12" width="40%" align="right">$<span id="totalAccessories">' + accessoriesPrice  + '</span></td>';
    summary += '                                </tr>';
    summary += '                                <tr>';
    summary += '                                    <td class="trebuchet font11 drkGreyTxt" width="60%" align="left">Warranty Total:</td>';
    summary += '                                    <td class="red boldTxt font12" width="40%" align="right">$<span id="totalWarranties">' + accessoriesPrice  + '</span></td>';
    summary += '                                </tr>';
    summary += '									<tr>';
    summary += '										<td class="trebuchet font16 boldTxt drkGreyTxt" width="60%" align="left">Your Total:</td>';
    summary += '										<td class="red boldTxt font18" width="40%" align="right"><span id="finalPriceSummary">' + document.getElementById("finalPriceTop").innerHTML + '</span></td>';
    summary += '									</tr>';
    summary += '<tr class="isCartOnly" style="display:none;"><td colspan="2" class="red boldTxt font13" align="right" valign="top">plus additional savings in cart</td></tr>';
    if (offerExpires != "") {
    	summary += '<tr><td colspan="2" class="lucidaSans font12 alignRight"><a href="javascript:showOverlayGeneric(\'offerExpiresOverlay\', \'offerExpiresOverlayHeader\', \'offerExpiresOverlayFooter\');"><span style="color:#888888;">offer expires <span id="offerExpires" class="boldTxt">'+offerExpires+'</span></span></a></td></tr>';
    }
    summary += '								</table>';
    summary += '							</td>';
    summary += '						</tr>';
    summary += '					</table>';
    summary += '				</td>';
    summary += '			</tr>';
    summary += '		</table>';
    summary += '		</td>';
    summary += '	</tr>';
    summary += '	<tr class="summaryContBottom">';
    summary += '		<td></td>';
    summary += '	</tr>';
    summary += '	<tr>';
    summary += '		<td bgcolor="#ffffff">';
    summary += '            <div id=\'summaryBlock_error\' style=\' display:none; padding-bottom:6px;\'>';
    summary += '                <table style=\'background-color:#EBEBEB; padding-left:5px; \'   width=\'97%\' align=\'center\' cellpadding=\'2\' cellspacing=\'0\' border=\'0\'>';
    summary += '                    <tr><td valign=\'top\' width=\'40\' rowspan=\'2\'><img style=\'padding-right:5px;\' src=\'/images/ui3/BTO_ErrorIcon_36px.png\'></td>';
    summary += '                        <td style=\'font-family:Lucida Sans;font-size:12px; color:#CC0000; font-weight: bold; text-align:left;\'> ' +  document.getElementById("ruleViolationErrorHeading").value + '</td>';
    summary += '                    <tr><td style=\'vertical-align:top;\'><div id=\'summaryBlock_error_detail\' style=\'font-family:Lucida Sans;font-size:10px; color:black;text-align:left; display:none;\'>hhhi there</div></td></tr>';
    summary += '                </table>';
    summary += '            </div>';
    summary += '        </td>';
    summary += '	</tr>';
    summary += '	<tr>';
    summary += '		<td bgcolor="#ffffff" align="right"><input type="image" onclick="checkAndSubmit(' + poid + ')" src="' + imagePath + 'btn-addtocart.png" />&nbsp;</td>';
    summary += '	</tr>';
    summary += '</table>';

    document.getElementById('div_summary').innerHTML = summary;
    document.getElementById('finalPriceBottom').innerHTML = document.getElementById('finalPriceSummary').innerHTML;
}  */

// update summary box with custom configuration
function updateSummary(componentType, component) {
    var spans = document.getElementsByTagName('li');

    // change all non-blank (i.e. light gray) backgrounds to blank
    for (var i = 0; i < spans.length; i++) {
        if (spans[i].id.substring(0, 11) == 'li_summary_') {
            if (spans[i].style.backgroundColor != "") {
            	//if the backgroundColor was set, clear it out and set the bullet to red.
                spans[i].style.backgroundColor = "";
                spans[i].style.color = "#c00";
            }
        }
    }

    var span = document.getElementById('span_comp_' + componentType + '_' + component);

    // change the last selected background to light gray (for non-default components) or to blank (for default components)
    // change the bullet to red (for non-default components) or to blank (for default components)
    if (span == null) { // default component
        span = document.getElementById('span_comp_default_' + componentType + '_' + component);
        document.getElementById('li_summary_' + componentType).style.backgroundColor = '';
        document.getElementById('li_summary_' + componentType).style.color = '';
    } else { // non-default component
        document.getElementById('li_summary_' + componentType).style.backgroundColor = '#ddd'; // light gray
        document.getElementById('li_summary_' + componentType).style.color = '#c00'; // dark grey
    }

    // update description
    document.getElementById('li_summary_' + componentType).innerHTML =
        '<span id="span_summary_' + componentType + '">' + span.innerHTML + '</span>';

    document.getElementById('span_summary_' + componentType).style.color = '#000';

}

function processAjax(poid, components) {
    var selcmpcodpip = components;

    if (components == '') {
        selcmpcodpip = getComponents();
    }

    jQuery.ajax({
                type: "POST", /* IE does not cache any more with POST */
                url: "detailBtoAjax.jsp",
                async: false,
                data: {poid:poid,selcmpcodpip:selcmpcodpip},
                success:function(feed){
                    processAjaxResponse(feed);
                }
            }); //end of ajax call
}

function getComponents() {
    var components = '';

    // build pipe-separated list, e.g. XXX|YYY|ZZZ
    for (var i = 0; i < document.detailBtoForm.elements.length; i++) {
        if (document.detailBtoForm.elements[i].name.substring(0, 5) == 'comp_' &&
            document.detailBtoForm.elements[i].type == 'radio' &&
            document.detailBtoForm.elements[i].checked) {
            components += '|' + document.detailBtoForm.elements[i].value;
        }
    }

    // remove first pipe character
    if (components.length > 1) {
        components = components.substring(1, components.length);
    }

    return components;
}

function getFeaturedAccessories() {
    var accessories = '';


    if (document.accessoriesForm != null) {
        // build pipe-separated list, e.g. XXX|YYY|ZZZ
        for (var i = 0; i < document.accessoriesForm.elements.length; i++) {
            if (document.accessoriesForm.elements[i].name.substring(0, 11) == 'accessories' &&
                (document.accessoriesForm.elements[i].type == 'radio' || document.accessoriesForm.elements[i].type == 'checkbox') &&
                document.accessoriesForm.elements[i].checked) {
                accessories += '|' + document.accessoriesForm.elements[i].value;
            }

        }

        // remove first pipe character
        if (accessories.length > 1) {
            accessories = accessories.substring(1, accessories.length);
        }
    }

    return accessories;
}

function processAjaxResponse(xmlStr) {
    var xmlDoc = parseXML(xmlStr);
    ajaxXmlDoc = xmlDoc;
    try {
        updatePricing(xmlDoc);
        processRules(xmlDoc);
        updateTsr(xmlDoc);
        calculateAccessoriesTotal();
        selectSquareTradeWarrantyBand();
        ajaxResponseProcessed = true;
    } catch (ignoreError) {
         //"Unexpected Parsing error.";
    }
}

function parseXML(xmlStr) {
    var xmlDoc;

    try { // Internet Explorer
       xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
       xmlDoc.async = 'false';
       xmlDoc.loadXML(xmlStr);
    } catch (e) {
        try { // Firefox, Mozilla, Opera, etc.
            parser = new DOMParser();
            xmlDoc = parser.parseFromString(xmlStr, 'text/xml');
        } catch (e) {
            alert(e.message);
            return;
        }
    }

    return xmlDoc;
}

// when a user selects a different component of a given component type, this function updates the pricing data
function updatePricing(xmlDoc) {
    // XPath query is not supported in Internet Explorer
    // var finalPrice = xmlDoc.evaluate('cdet-ajax/pricing/final-price', xmlDoc, null, XPathResult.STRING_TYPE, null).stringValue;

    var listPrice = xmlDoc.getElementsByTagName('list-price')[0].childNodes[0].nodeValue;
    var componentDiscount = xmlDoc.getElementsByTagName('component-discount')[0].childNodes[0].nodeValue;
    var adjustedPrice = xmlDoc.getElementsByTagName('adjusted-price')[0].childNodes[0].nodeValue;
    var instantDiscount = xmlDoc.getElementsByTagName('instant-discount')[0].childNodes[0].nodeValue;
    var couponDiscount = xmlDoc.getElementsByTagName('coupon-discount')[0].childNodes[0].nodeValue;
    var configInstantDiscount = xmlDoc.getElementsByTagName('config-instant-discount')[0].childNodes[0].nodeValue;
    var configCouponDiscount = xmlDoc.getElementsByTagName('config-coupon-discount')[0].childNodes[0].nodeValue;
    var finalPrice = xmlDoc.getElementsByTagName('final-price')[0].childNodes[0].nodeValue;
    var isInstant = xmlDoc.getElementsByTagName('is-instant')[0].childNodes[0].nodeValue;
    var isCoupon = xmlDoc.getElementsByTagName('is-coupon')[0].childNodes[0].nodeValue;
    var isConfigInstant = xmlDoc.getElementsByTagName('is-config-instant')[0].childNodes[0].nodeValue;
    var isConfigCoupon = xmlDoc.getElementsByTagName('is-config-coupon')[0].childNodes[0].nodeValue;
    var isCartOnly = xmlDoc.getElementsByTagName('is-cart-only')[0].childNodes[0].nodeValue;

	adjustedPrice = adjustedPrice.replace(/[^\d^\.]/g, "") * 1;
	var runningPrice = adjustedPrice;
	instantDiscount = instantDiscount.replace(/[^\d^\.]/g, "") * 1;
	couponDiscount = couponDiscount.replace(/[^\d^\.]/g, "") * 1;
	configInstantDiscount = configInstantDiscount.replace(/[^\d^\.]/g, "") * 1;
	configCouponDiscount = configCouponDiscount.replace(/[^\d^\.]/g, "") * 1;
	finalPrice = finalPrice.replace(/[^\d^\.]/g, "") * 1;

    document.getElementById("div_listPrice").innerHTML = formatAmount(listPrice);
    var sqt_listPrice = listPrice.replace(/[^\d^\.]/g, "") * 1;
    var sqt_componentDiscount = componentDiscount.replace(/[^\d^\.]/g, "") * 1;
    document.getElementById("div_listLessInstant").innerHTML = sqt_listPrice-instantDiscount-sqt_componentDiscount;

    if (isCartOnly != 'true') {
    	if (instantDiscount > runningPrice) instantDiscount = runningPrice;
	    runningPrice -= instantDiscount;
	}
    if (couponDiscount > runningPrice) couponDiscount = runningPrice;
	runningPrice -= couponDiscount;
    if (configInstantDiscount > runningPrice) configInstantDiscount = runningPrice;
	runningPrice -= configInstantDiscount;
    if (configCouponDiscount > runningPrice) configCouponDiscount = runningPrice;
	runningPrice -= configCouponDiscount;

    if (componentDiscount > 0.0) {
        document.getElementById('div_componentRebate').innerHTML = '-' + formatAmount(componentDiscount);
        if(componentRebateLabel == null) {
            document.getElementById('div_componentRebateLabel').innerHTML = 'Component Rebate:';
        } else {
            document.getElementById('div_componentRebateLabel').innerHTML = componentRebateLabel + ":";
        }
    } else {
        document.getElementById('div_componentRebate').innerHTML = '';
        document.getElementById('div_componentRebateLabel').innerHTML = '';
    }

    if (adjustedPrice != listPrice) {
        document.getElementById('div_adjustedPrice').innerHTML = formatAmount(formatCurrency(adjustedPrice));
        if(adjustedPriceLabel == null) {
            document.getElementById('div_adjustedPriceLabel').innerHTML = 'Base List Price:';
        } else {
            document.getElementById('div_adjustedPriceLabel').innerHTML = adjustedPriceLabel + ":";
        }
    } else {
        document.getElementById('div_adjustedPrice').innerHTML = '';
        document.getElementById('div_adjustedPriceLabel').innerHTML = '';
    }

    if (isInstant == 'true') {
		if (isCartOnly == 'true') {
			finalPrice += instantDiscount;
			document.getElementById('div_instantRebate').innerHTML = "<a href=\"javascript:showOverlayGeneric('cartSavingsOverlay', 'cartSavingsOverlayHeader', 'cartSavingsOverlayFooter');\"><span class=\"boldTxt lucidaSans font12 red\">See Savings in Cart &raquo;</span></a>";
		} else {
        	document.getElementById('div_instantRebate').innerHTML = '-' + formatAmount(formatCurrency(instantDiscount));
		}
        if(instantSavingsLabel == null) {
            document.getElementById('div_instantRebateLabel').innerHTML = 'Instant Rebate:';
        } else {
            document.getElementById('div_instantRebateLabel').innerHTML = instantSavingsLabel + ":";
        }
    } else {
        document.getElementById('div_instantRebate').innerHTML = '';
        document.getElementById('div_instantRebateLabel').innerHTML = '';
    }

    if (isCoupon == 'true') {
        document.getElementById('div_coupons').innerHTML = '-' + formatAmount(formatCurrency(couponDiscount));
        if(couponDiscountLabel == null) {
            document.getElementById('div_couponsLabel').innerHTML = 'Coupons:';
        } else {
            document.getElementById('div_couponsLabel').innerHTML = couponDiscountLabel + ':';
        }
    } else {
        document.getElementById('div_coupons').innerHTML = '';
        document.getElementById('div_couponsLabel').innerHTML = '';
    }

    if (isConfigInstant == 'true') {
        document.getElementById('div_configInstantDiscount').innerHTML = '-' + formatAmount(formatCurrency(configInstantDiscount));
        if(configInstantSavingsLabel == null) {
            document.getElementById('div_configInstantDiscountLabel').innerHTML = 'Configuration Instant Discount:';
        } else {
            document.getElementById('div_configInstantDiscountLabel').innerHTML = configInstantSavingsLabel + ':';
        }
    } else {
        document.getElementById('div_configInstantDiscount').innerHTML = '';
        document.getElementById('div_configInstantDiscountLabel').innerHTML = '';
    }

    if (isConfigCoupon == 'true') {
        document.getElementById('div_configCouponDiscount').innerHTML = '-' + formatAmount(formatCurrency(configCouponDiscount));
        if(configCouponLabel == null) {
            document.getElementById('div_configCouponDiscountLabel').innerHTML = 'Configuration Coupon Discount:';
        } else {
            document.getElementById('div_configCouponDiscountLabel').innerHTML = configCouponLabel + ':';
        }
    } else {
        document.getElementById('div_configCouponDiscount').innerHTML = '';
        document.getElementById('div_configCouponDiscountLabel').innerHTML = '';
    }
    document.getElementById('ListPriceSummary').innerHTML = formatAmount(formatCurrency(finalPrice));
    finalPrice = formatAmount(addFormattedAmt(formatAmount(finalPrice), formatAmount(accessoriesPrice)));

    document.getElementById('finalPriceTop').innerHTML = formatCurrency(finalPrice);
    document.getElementById('finalPriceBottom').innerHTML = formatCurrency(finalPrice);
    document.getElementById('finalPriceSummary').innerHTML = formatCurrency(finalPrice);
    try { lpSendData('page','BTO_CustomizePrice',finalPrice); } catch (e) {}
}

function selectSquareTradeWarrantyBand() {
    // select the squaretrade price band that fits the price
    // if one of the sqt price band was previously selected, deselect. And select the one that fits the price.
    var finalprice = $("#div_listLessInstant").text().replace(/[^\d^\.]/g, "") * 1;
    var n = $(".squareTrade > td > input:checked").length;  // counts if any of the price bands were checked

    $(".squareTrade").each(function () {
        var minprice = $(this).attr('minprice').replace(/[^\d^\.]/g, "") * 1;
        var maxprice = $(this).attr('maxprice').replace(/[^\d^\.]/g, "") * 1;
        var stdwarrlen = $(this).attr('standardwarrlen');
        var warrtype = $(this).find('input').attr('warrantytype');

        if (finalprice >= minprice && finalprice <= maxprice) {
            // get the standard warr length
            if (stdwarrlen == $("input[name='comp_Standard Warranty']:checked").attr("standardwarrlen") &&
                    warrtype == $(this).find('input').attr('warrantytype')) {
                $(this).css("display", "table-row");
                if (n > 0) {
                    $(this).find('input').click();
                }
            }
            else {
                $(this).css("display", "none");
            }
        } else {
            $(this).css("display", "none");
        }
    })
}

function processChooseOne(currentCheckbox, category) {
    if (category == 'xsell_Extended_Service_Plans' && currentCheckbox.checked == true ) {
        var elements = document.getElementsByName('xsell_Extended_Service_Plans');
	for (var i = 0; i < elements.length; i++) {
            if (currentCheckbox.id != elements[i].id && elements[i].checked == true) {
                elements[i].checked = false;
            }
        }
    }
    calculateAccessoriesTotal ();
}

//firefox has 4k limit, so using textContent for firefox. textContent doens't work for IE, so still using nodeValue for IE.
function getNodeText(xmlNode)
{
    if (!xmlNode)
        return '';
    if (typeof(xmlNode.textContent) != "undefined")  //Firefox will return textContent
        return xmlNode.textContent;
    return xmlNode.firstChild.nodeValue;   //IE will return nodeValue
}

// when a user selects a different component of a given component type, this function alerts the user of rule violations
function processRules(xmlDoc) {

    //clean up error blocks
    if (document.detailBtoForm.srcCompError.value.length > 0) {
        srcCompArray = document.detailBtoForm.srcCompError.value.split(",");
        for (k=0; k<srcCompArray.length; k++){
            document.getElementById(srcCompArray[k]+"_staticMsg").style.display = 'none';
            document.getElementById(srcCompArray[k]+"_errorMsg").innerHTML = "";
            document.detailBtoForm.srcCompError.value = "";
        }
    }

    if (document.detailBtoForm.tgtCompError.value.length > 0) {
        tgtCompArray = document.detailBtoForm.tgtCompError.value.split(",");
        for (k=0;k<tgtCompArray.length;k++){
            document.getElementById(tgtCompArray[k]+"_staticMsg").style.display = 'none';
            document.getElementById(tgtCompArray[k]+"_errorMsg").innerHTML = "";
            document.detailBtoForm.tgtCompError.value = "";
        }
    }

    document.getElementById("summaryBlock_error").style.display = 'none';
    document.getElementById("summaryBlock_error_detail").innerHTML = "";

    document.getElementById("ruleViolation_error").style.display = 'none';
    document.getElementById("ruleViolation_error_detail").innerHTML = "";

    // XPath query is not supported in Internet Explorer
    // var finalPrice = xmlDoc.evaluate('cdet-ajax/pricing/final-price', xmlDoc, null, XPathResult.STRING_TYPE, null).stringValue;
    var ruleViolationCounter = 0;
    var ruleViolations = false;
    var combinedRuleViolationMessage = "";

    while (true) {
        if (xmlDoc.getElementsByTagName('rule-type')[ruleViolationCounter] != null) {
            //var ruleSourceDesc = xmlDoc.getElementsByTagName('rule-source-desc')[ruleViolationCounter].childNodes[0].nodeValue;
            //var ruleTargetDesc = xmlDoc.getElementsByTagName('rule-target-desc')[ruleViolationCounter].childNodes[0].nodeValue;
            var ruleType = xmlDoc.getElementsByTagName('rule-type')[ruleViolationCounter].childNodes[0].nodeValue;
            //var ruleCustomMsg = '';

            if (xmlDoc.getElementsByTagName('rule-custom-message')[ruleViolationCounter].childNodes[0] != null) {
                ruleCustomMsg = xmlDoc.getElementsByTagName('rule-custom-message')[ruleViolationCounter].childNodes[0].nodeValue;
                combinedRuleViolationMessage = combinedRuleViolationMessage + ((combinedRuleViolationMessage.length > 0) ? "<br>" : "") + ruleCustomMsg;
            }

			if (xmlDoc.getElementsByTagName('rule-violation-source')[ruleViolationCounter].childNodes[0] != null) {
                var ruleViolationSrces = new Array();
                ruleViolationSrces = xmlDoc.getElementsByTagName('rule-violation-source')[ruleViolationCounter].childNodes[0].nodeValue.split("_");
                for(var s=0, sMax=ruleViolationSrces.length; s<sMax; s++) {
                    var ruleViolationSrc = ruleViolationSrces[s]
                    for (var i in btoCompArray) {
                        if (i==ruleViolationSrc)
                            ruleViolationSrc = btoCompArray[i];
                    }

                    document.getElementById(ruleViolationSrc+"_staticMsg").style.display = 'block';
                    document.getElementById(ruleViolationSrc+"_errorMsg").innerHTML = document.getElementById(ruleViolationSrc+"_errorMsg").innerHTML + (document.getElementById(ruleViolationSrc+"_errorMsg").innerHTML.length > 1 ? "<br>" : "")+ruleCustomMsg;
                    document.getElementById("srcCompError").value = document.getElementById("srcCompError").value + (document.getElementById("srcCompError").value.length > 0 ? "," : "") +  ruleViolationSrc;
                }
            }

            if (xmlDoc.getElementsByTagName('rule-violation-target')[ruleViolationCounter].childNodes[0] != null) {
                ruleViolationTgt = xmlDoc.getElementsByTagName('rule-violation-target')[ruleViolationCounter].childNodes[0].nodeValue;
                for (var i in btoCompArray) {
                    if (i==ruleViolationTgt)
                        ruleViolationTgt = btoCompArray[i];
                }

                document.getElementById(ruleViolationTgt+"_staticMsg").style.display = 'block';
                document.getElementById(ruleViolationTgt+"_errorMsg").innerHTML = document.getElementById(ruleViolationTgt+"_errorMsg").innerHTML + (document.getElementById(ruleViolationTgt+"_errorMsg").innerHTML.length > 1 ? "<br>" : "")+ruleCustomMsg;
                document.getElementById("tgtCompError").value = document.getElementById("tgtCompError").value + (document.getElementById("tgtCompError").value.length > 0 ? "," : "") +  ruleViolationTgt; ;
            }



            if (ruleType == 1) { // FORCE_SELECT
                //if (ruleCustomMsg != '') {
                   // alert(ruleCustomMsg);
                //} else {
                //    alert('If you select ' + ruleSourceDesc + ' you need to select ' + ruleTargetDesc + '.');
                //}

                ruleViolations = true;
            } else if (ruleType == 2) { // SOURCE_SELECTED_TARGET_VISIBLE
                //if (ruleCustomMsg != '') {
                    //alert(ruleCustomMsg);
                //} else {
                //    alert('To select ' + ruleSourceDesc + ' you need to select ' + ruleTargetDesc + '.');
                //}

                ruleViolations = true;
            } else if (ruleType == 3) { // SOURCE_SELECTED_TARGET_INVISIBLE
                //if (ruleCustomMsg != '') {
                   // alert(ruleCustomMsg);
                //} else {
                //    alert('You cannot select ' + ruleSourceDesc + ' when you select ' + ruleTargetDesc + '.');
                //}

                ruleViolations = true;
            }

            ruleViolationCounter++;
        } else {
            break;
        }
    }

     //if ruleViolation occured, disable all radio buttons (except for errored components) ..else enable all.
    if (ruleViolations == true){

        document.getElementById("summaryBlock_error").style.display = 'block';
        document.getElementById("summaryBlock_error_detail").style.display = 'block';
        document.getElementById("summaryBlock_error_detail").innerHTML = document.getElementById("summaryBlock_error_detail").innerHTML + (document.getElementById("summaryBlock_error_detail").innerHTML.length > 1 ? "<br>" : "")+combinedRuleViolationMessage;

        document.getElementById("ruleViolation_error").style.display = 'block';
        document.getElementById("ruleViolation_error_detail").style.display = 'block';
        document.getElementById("ruleViolation_error_detail").innerHTML = document.getElementById("ruleViolation_error_detail").innerHTML + (document.getElementById("ruleViolation_error_detail").innerHTML.length > 1 ? "<br>" : "")+combinedRuleViolationMessage;;

        if (document.getElementById("srcCompError").value.length > 1 || document.getElementById("tgtCompError").value.length > 1){
            srcCompArray = document.getElementById("srcCompError").value.split(",");
            tgtCompArray = document.getElementById("tgtCompError").value.split(",");

            for(i=0; i<document.detailBtoForm.elements.length; i++){
                if (document.detailBtoForm.elements[i].type == 'radio') {
                    var comp = document.detailBtoForm.elements[i].id;
                    for (var z in btoCompArray) {
                        var existInSource = false;
                        var existInTarget = false;
                        if (z==comp){

                            //check for the component in source array
                            for(p=0; p<srcCompArray.length; p++){
                                if (srcCompArray[p]==btoCompArray[z])
                                    existInSource = true;
                            }

                            //check for the component in target array
                            for(q=0; q<tgtCompArray.length; q++){
                                if(tgtCompArray[q]==btoCompArray[z])
                                    existInTarget = true;
                            }

                            if (existInSource != true && existInTarget != true)
                                document.detailBtoForm.elements[i].disabled = true;
                            else
                                document.detailBtoForm.elements[i].disabled = false;

                        }
                    }
                }
            }
        }
    }  else {
        for(i=0; i<document.detailBtoForm.elements.length; i++){
                if (document.detailBtoForm.elements[i].type == 'radio') {
                    document.detailBtoForm.elements[i].disabled = false;
                }
            }
    }

    return ruleViolations;
}

// for telephone service rep user only, update additional fields
function updateTsr(xmlDoc) {
    try {
    if (document.getElementById("div_selcmpcodpip") != null) {
        document.getElementById("div_selcmpcodpip").innerHTML = '';
    }

    if (document.getElementById("div_fgpn") != null) {
        document.getElementById("div_fgpn").innerHTML = '';
    }

    if (document.getElementById("div_selcmpcodpip") != null) {
        var selcmpcodpip = xmlDoc.getElementsByTagName('selcmpcodpip')[0].childNodes[0].nodeValue;
        document.getElementById("div_selcmpcodpip").innerHTML = selcmpcodpip;
    }

    if (document.getElementById("div_fgpn") != null) {
        var fgpn = xmlDoc.getElementsByTagName('fgpn')[0].childNodes[0].nodeValue;
        document.getElementById("div_fgpn").innerHTML = fgpn;
    }
    }catch(e){}
}

// decode xml special characters
function decodeXml(str) {
    return str.replace(/&amp;/g, '&').replace(/&quot;/g, '"').replace(/&apos;/g, '\'').replace(/&lt;/g, '<').replace(/&gt;/g, '>');
}

// decode special characters so they are readable in dialog box
function decode(str) {
    var tmp = decodeXml(str);
    return tmp.replace(/&reg;/g, '�').replace(/&#153;/g, '(TM)');
}

// add $1,234.56 to $2,345.67
function addFormattedAmt(fmtAmt1, fmtAmt2) {
    return formatCurrency(parseFloat(unformatAmount(fmtAmt1)) +
                          parseFloat(unformatAmount(fmtAmt2)));
}

// subtract $1,234.56 from $2,345.67
function subtractFormattedAmt(fmtAmt1, fmtAmt2) {
    return formatCurrency(parseFloat(unformatAmount(fmtAmt1)) -
                          parseFloat(unformatAmount(fmtAmt2)));
}

function formatAmount(amount) {
        return '$' + amount;
}

// 1,234.00
function formatCurrency(num) {
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
    num = '0';
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
    cents = '0' + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
    num = num.substring(0,num.length-(4*i+3))+','+
    num.substring(num.length-(4*i+3));
    return (((sign)?'':'-') + num + '.' + cents);
}

function ruleViolationExists (){
        if (document.getElementById("summaryBlock_error").style.display == 'block')
            return true;
    }

function checkAndSubmit(poid) {
    if (ajaxResponseProcessed != true)
        return false;
    if (ruleViolationExists()){
        alert( document.getElementById("summaryBlock_error_detail").innerHTML.replace("<br>","\n").replace("<BR>","\n"));
        document.getElementById(document.getElementById("srcCompError").value.split(",")[0]+"_ErrorTable").focus();
        return false;
    }
    if (check(poid)) {
        doReportingBto(poid);
    	document.detailBtoForm.submit();
    }
}

// Analytics
function doReportingBto(poid) {
    if (ajaxResponseProcessed != true){
        return false;
    }

    if (ruleViolationExists()){
        alert( document.getElementById("summaryBlock_error_detail").innerHTML.replace("<br>","\n").replace("<BR>","\n"));
        document.getElementById(document.getElementById("srcCompError").value.split(",")[0]+"_ErrorTable").focus();
        return false;
    }
    try {
        var selectedComps = $("#div_selcmpcodpip").html().replace(/\|$/, "");
		var omniSelComps = "";
		var selCompsArray = selectedComps.split("|");
		for(var ii=0, j=selCompsArray.length; ii<j; ii++) {
			var originalDeltaEle = document.getElementById('origDelta_' + selCompsArray[ii]);
			var originalDelta = 0;
			if(originalDeltaEle)
				originalDelta = originalDeltaEle.innerHTML;
			if(parseInt(originalDelta, 10) != 0) {
				omniSelComps = omniSelComps + ";" + selCompsArray[ii] + ";;;event29=" + originalDelta + ",";
			} else {
				omniSelComps = omniSelComps + ";" + selCompsArray[ii] + ",";
			}
		}
		omniSelComps = omniSelComps.replace(/,$/, "");
		var btoPriceWithXsells = eval(unformatAmount(document.getElementById("finalPriceBottom").innerHTML));
		var finalBtoPrice = eval(btoPriceWithXsells - accessoriesPrice);
		var omtr=s_gi(s_account);
		var tmpLinkVars = omtr.linkTrackVars;
		var tmpLinkEvents = omtr.linkTrackEvents;
		omtr.linkTrackVars='products,events';
		omtr.linkTrackEvents='event14,event16,event18,event29,event30';
		omtr.events="event14,event16,event18,event29,event30";
		omtr.products= ";" + poid + ";;;event16=" + finalBtoPrice + ";event30=" + finalBtoPrice + ";," + omniSelComps;
		omtr.tl(this,'o', 'Add BTO to Cart');
		omtr.linkTrackVars=tmpLinkVars;
		omtr.linkTrackEvents=tmpLinkEvents;
		omtr.events="";
    } catch (e) {
    }
}

function check(poid) {
    if (ajaxXmlDoc != null && processRules(ajaxXmlDoc) != false) {
        return false;
    } else if(!ajaxXmlDoc.getElementsByTagName('list-price')[0]) {
        alert("Unexpected Error");
        document.getElementById("summaryBlock_error_detail").style.display = 'block';
        document.getElementById("summaryBlock_error_detail").innerHTML = "Unexpected error";
        return false;
    }else if (ajaxResponseProcessed != true){
        return false;
    }


    var components = getComponents();
    var featuredAccessories = getFeaturedAccessories();
    var xsells = getXSells(featuredAccessories.split("|"));
    var compXsells = getCompXsells();
    var featuredAccessoriesNoDefault = featuredAccessories.replace('default', '');

    var accessories = mergeAccessories (featuredAccessoriesNoDefault, xsells);
    accessories = mergeAccessories (accessories, compXsells);

    // 'default' is a radio button to unselect other choices
    // it is not used for the accessories page, but it is used for the back button

    document.detailBtoForm.selcmpcodpip.value = components;
    document.detailBtoForm.selxsloidpip.value = accessories ;

    if (preSelectedAccessoryOidsPip.length > 0) {
        preSelectedAccessoryOidsPip = preSelectedAccessoryOidsPip.substring(0, preSelectedAccessoryOidsPip.length - 1);
    }

    featuredAccessories = mergeAccessories (featuredAccessories, xsells);
    featuredAccessories =  mergeAccessories (featuredAccessories, compXsells);

    window.location.hash = components + '~' + featuredAccessories + '~' + preSelectedAccessoryOidsPip;

    return true;
}

function unformatAmount(amt) {
    if(typeof(amt) == "undefined" || !amt) {
        return 0;
    } else if(typeof(amt) == "number") {
        return amt;
    }
    return amt.replace('$', '').replace(',', '');
}
