var bFullyLoaded = false;
var bAPCDisplayPrice = false;
var bDisplayPrices = false;
var bXwarLoaded = false;
var inListView = false;
var doRemoveExtra = true;
var bInitialSubtotal = true;
var bHeightFloatDisplay = false;

var oForm;
var iElementCount;
var selectedI = 0;
var formatPriceCounter = 0;
var currentOptionRowCount = 0;
var oPriceDisplay = [];
var glSelectorID;
var glSelectorControl;
var glSelectorExtra;
var maxNumberOfItem=0;
var currentMaxHeight=0;

var subtotal = new Object;
var itemtotals = new Object;
var currentSelectedInput = new Array();
var totalOptionsQty = 0;
var totalOptionsPrice = 0;
var selectedSections = new Array();

/** Varaibles used for dollarFormat(), can be changed for other coutnries */
var currency = 'USD';
var currencyDecimalSeporator = '.';
var currencyGroupingSeporator = ',';

/** Variables for AJAX pricing **/
var formatPriceWait = '---';
var formatPriceElements = new Object;

var IE = document.all?true:false;

function setWarrantyRows(id, style_value) {
	var counter = 0;
	var warranty_row = document.getElementById(id + '-warranty-header');
	while ( warranty_row ) {
		warranty_row.style.display = style_value;
		warranty_row = document.getElementById(id + '-warranty-tr-' + counter++);
	}	
}

function updateLineItem(id) {
	bInitialBattPrices = false;
	var selector_element = document.getElementById(id);
	if ( selector_element.type == 'checkbox' )
		document.getElementById(id + '-qty').style.visibility = ( selector_element.checked ) ? 'visible' : 'hidden';
	
	//if (bAPCDisplayPrice) {
	//	DWREngine.beginBatch();
	//}
	
	if ( selector_element.checked == false ) {
		setWarrantyRows(id, 'none');
	}

	updateLineItems();
	
	if (bAPCDisplayPrice) {
		
		if (selector_element.checked) {
			if ( selector_element.type == 'radio' ) {
				var i = 0;
				var category = id.substring(0, id.lastIndexOf('-') + 1);
				var element = document.getElementById(category + i); 
				while ( element || i == 0 ) {
					var element_id = category + i;
					if ( id != element_id && document.getElementById(element_id + '-display') ) {
						document.getElementById(element_id + '-display').innerHTML = "&nbsp;";
					}
					element = document.getElementById(category + ++i);
				}
			}
		} else {
			document.getElementById(id + '-display').innerHTML = "&nbsp;";
		}
		
		// Update other prices
		if (bDisplayPrices) {
		updatePriceSubtotal(id);
		updatePriceTotal();
		//DWREngine.endBatch();
		}
	}
	displayOverflow( );
}

function updateLineItems(){
	////
	// Floating cart item list is built here
	////

	// Remove existing items in the cart
	var componentCount = 0;
	var componentDisplay = document.getElementById("component-list");
	removeAllChildren(componentDisplay);
	
	// Loop through each section
	var i = 1;
	totalOptionsQty = 0;
	totalOptionsPrice = 0;
	var cartOptionsCount= $('cartOptionsCount');
	if(cartOptionsCount)
	{
	cartOptionsCount.innerHTML = 0;
	}
	
	var cartOptionsValue= $('cartOptionsValue');
	if(cartOptionsValue)
	{
	cartOptionsValue.innerHTML = '--';
	}
	
	var currentSections = new Array();
	selectedSections = new Array();
	var section = document.getElementById('options_section_category_' + i)
	while (section) {
		
		// Loop through each line item in this section
		var j = 1;
		var quantity = 1;
		var dataPresent = false;
		var section_category = section.innerHTML;
		var section_element = document.getElementById(section_category + '-' + j);
		while (section_element) {
			var section_element_title = document.getElementById(section_element.id + "-title").innerHTML;
			if (section_element.checked && section_element_title.length > 0 && section_element_title != 'None') {
				var id = section_element.id;
				totalOptionsQty++;
				
				if (selectedSections.indexOf(section_category) == -1) {
					selectedSections.push(section_category+'-1');
				}

				if (!dataPresent) {
					// This is the first line item for this section... add a new div
					var divContainer = createOneElement("div", ["class"], ["compTitle"], document.getElementById(id + '-section').value + ':');
					componentDisplay.appendChild(divContainer);
					dataPresent = true;
				}
				
				if (document.getElementById(section_element.id + '-qty')) {
					quantity = document.getElementById(section_element.id + '-qty').value;
				}
				updateLineItems_helper(id, quantity, i, componentCount++, componentDisplay);

				// Loop through warranty items
				var k = 1;
				var section_element_warranty = document.getElementById(id + '-warranty-' + k);
				while ( section_element_warranty ) {
					if ( section_element_warranty.checked ) {
						updateLineItems_helper(section_element_warranty.id, quantity, i, componentCount++, componentDisplay);
						break;
					}
					section_element_warranty = document.getElementById(id + '-warranty-' + ++k);
				}
				
				if (bDisplayPrices) {
					$('cartOptionsCount').innerHTML = totalOptionsQty;
				}
			}
			section_element = document.getElementById(section_category + '-' + ++j);
		}
		section = document.getElementById('options_section_category_' + ++i);
	}

	if(bInitialSubtotal && bDisplayPrices) {
		bInitialSubtotal = false;
		updateInitialPriceSubtotal();
	}
	displayOverflow( );
}

function updateLineItems_helper(id, quantity, sectionNumber, cart_item_count, componentDisplay) {
	var componentSku = document.getElementById(id + '-sku').innerHTML;
	var componentLabel = document.getElementById(id + "-title").innerHTML;	
	var mouseovertext = "if (checkMouseEnter(this, event)) { var displayObject = { url: '../configure/includes/quickView.cfm?base_sku=" + componentSku + "', element: this};start(displayObject);return false;}";
	var mouseouttext = "if (checkMouseLeave(this, event)) { start(null,'cancel');return false;}";
	var displayText = "<a name='&lid=cart_remove_"+ componentSku +"' class='removeItem' onClick='confirmRemoval(\"" + id + "\"); return false;'><img src='images/trashcan.gif' width='11' height='14' style='vertical-align: middle;' alt='Remove Item' /></a> " + quantity + 'x <a name="&lid=cart_'+ componentSku +'" class="compLink" onClick="goToSection('+ sectionNumber +'); flashItem(\''+ id +'\');" onmouseover="' + mouseovertext + '" onmouseout="' + mouseouttext + '">' + componentLabel + "</a>";

	// If this has a warranty, show it
	setWarrantyRows(id, '');
	
	// Create main container elements
	divComponentContainer = createOneElement( "div", ["class", "name","id"], ["clear compContainer", "optionItems","optionItems"]);
	if (bDisplayPrices) {
		
		var price = document.getElementById(id + '-price').value;
		
		if ( document.getElementById(id).type == 'checkbox' )
			document.getElementById(id + '-qty').style.visibility = 'visible';		
		if ( !(id in formatPriceElements) || formatPriceElements[id][3] != quantity ) {
			// Either the price is not formatted yet or the quantity changed
			formatPrice(parseFloat(price) * parseFloat(quantity), id, cart_item_count + "_componentPrice", quantity);
		} else {
			document.getElementById(id + "-display").innerHTML = formatPriceElements[id][1]; 
		}
		
		updateOptionTotal(parseFloat(price) * parseFloat(quantity));

		divComponentName = createOneElement( "div", ["class"], ["compName"], displayText );
		divComponentValue = createOneElement( "div", ["class", "id"], ["compValue", formatPriceElements[id][2]], formatPriceElements[id][1]);
		divComponentContainer.appendChild(divComponentName);
		divComponentContainer.appendChild(divComponentValue);
	} else {
		divComponentName = createOneElement( "div", ["class"], ["compNameFull"], displayText );
		divComponentContainer.appendChild(divComponentName);
	}
	// Add to component view
	componentDisplay.appendChild(divComponentContainer);
	displayOverflow( );
}

function updateInitialPriceSubtotal() {
	for (var i=0; i<selectedSections.length; i++) {
		updatePriceSubtotal(selectedSections[i]);
	}
	updatePriceTotal();
}

function updatePriceSubtotal(id) {
	// If a warranty radio button triggered this
	// update, remove the warranty part of the id 
	id = id.replace(/-warranty-(?:[0-9]+)$/, '');
	
	var i = 1;
	var subtotal = 0;
	var quantity = 1;
	var tab_section = 0;
	var category = id.substring(0, id.lastIndexOf("-") + 1);
	var line_item_element = document.getElementById(category + i);
	while ( line_item_element ) {
		if (line_item_element.checked) {
			var price = document.getElementById(category + i + '-price').value;
			if (document.getElementById(category + i + '-qty')) {				
				quantity = document.getElementById(category + i + '-qty').value;
			}
			subtotal = parseFloat(subtotal) + parseFloat(price * quantity);
							
			// Check for a warranty
			if(document.getElementById(category + i + '-warranty-' + j)) {
				var j = 1;
				var line_item_warranty = document.getElementById(category + i + '-warranty-' + j);
				while ( line_item_warranty ) {
					if ( line_item_warranty.checked ) {
						subtotal = parseFloat(subtotal) + parseFloat(quantity * document.getElementById(line_item_warranty.id + '-price').value);
						break;
					}
					line_item_warranty = document.getElementById(category + i + '-warranty-' + ++j);
				}
			}
		}
		line_item_element = document.getElementById(category + ++i);
	}

	// Only format the subtotal price if it has changed
	if(document.getElementById(id + '-tab')) {
		tab_section = document.getElementById(id + '-tab').value;
	}
		

	if ( document.getElementById('options_section_subtotal_hidden_' + tab_section).value != subtotal ) {
		document.getElementById('options_section_subtotal_hidden_' + tab_section).value = subtotal;
		if ( id.substring(0, "BATTERY_LIST".length) != "BATTERY_LIST" )
			formatPrice(subtotal, 'options_section_subtotal_' + tab_section);
	} 
	else if ( $('options_section_subtotal_hidden_' + tab_section).value > parseFloat(0) ) {
		if ( id.substring(0, "BATTERY_LIST".length) != "BATTERY_LIST" )
			formatPrice(subtotal, 'options_section_subtotal_' + tab_section);
	}
	
}

function updateOptionTotal( price ) {
	totalOptionsPrice = totalOptionsPrice + parseFloat(price);
	formatPrice(totalOptionsPrice, 'cartOptionsValue');
}

function updatePriceTotal() {
	if (bDisplayPrices) {
		var i = 1;
		var total = parseFloat(document.getElementById('base_sku_price').value);
		var subtotal_element = document.getElementById('options_section_subtotal_hidden_' + i);
		while ( subtotal_element ) {		
			total = parseFloat(total) + parseFloat(subtotal_element.value);
			subtotal_element = document.getElementById('options_section_subtotal_hidden_' + ++i);
		}
		formatPrice(total, 'mainPrice');	
	}
}

/** This function should be called when the pages finishes loading */
function loadAction() {
	oForm = document.getElementById('rackOptionsForm');
	
	if ( document.getElementById("sPricing") )
		bDisplayPrices = ( document.getElementById("sPricing").value == 1 );
	
	if(oForm) {
		iElementCount = oForm.length;
		oPriceDisplay[0] = document.getElementById('oPrice-bottom');
		oPriceDisplay[1] = document.getElementById('oPrice-top');
		oPriceDisplay[2] = document.getElementById('oPrice-float'); /* Floating Cart */

		bFullyLoaded = true;
		
		// Check if pricing display element was not found
		if(oPriceDisplay[0]) {
			bAPCDisplayPrice = true;
		}

		// To ensure the showWarrantyPanel() is finished running, we delay preceding
		// initialization by the corresponding returned delay time from showWarrantyPanel()
		var delay = showWarrantyPanel();
		setTimeout("bXwarLoaded = true; updateLineItems(); if ( bDisplayPrices ) updatePriceTotal();", delay);
	}
}

function displayOverflow( ) {
	var maxHeight=0;
	var floater = $('floating-cart');
	var summarybottom = $('summary-bottom');
	var functionsbottom = $('functions-controls-bottom');
	var componentlist= $('component-list');
	var appheader = $('appHeader');
	var controlButton= $('controlButtons');
	var totalSku=$('total-SKU');
	var priceContainer = $('priceContainer');
	var includelist=$('includesList');
	var powerruntime = $('powerruntimeContainer');
	
	if(floater){
		floater.style.display = 'block';
	}
	if (summarybottom) {
		summarybottom.style.display = 'none';
	}
	if (functionsbottom) {
		functionsbottom.firstDescendant().className = "botFunctionsRel";
	}
	
	getViewport();
	
	if (componentlist) {
		componentlist.style.height = "";
		componentlist.style.border = "none";
		componentlist.className = "small-text compList";
	}
	
	var extraPadding = 20;
	var totalHeight = 0;
	if (totalSku) {
		totalHeight = totalSku.offsetHeight;
	} 
	var includelistHeight = 0
	if (includelist) {
		includelistHeight = includelist.offsetHeight;
	}
	var topWhiteSpace = 120;
	if (appheader) {
		topWhiteSpace = appheader.offsetTop + 120;
	}
	var controlButtonHeight = 0;
	var floaterIdentifierY = 0;
	if (controlButton) {
		controlButtonHeight = controlButton.offsetHeight;
		floaterIdentifierY = controlButtonHeight + controlButton.offsetTop;
	}
	var browserSpace = viewportheight-topWhiteSpace-extraPadding;

	if (priceContainer) {
		var priceContainerHeight = priceContainer.offsetHeight;
	} else {
		var priceContainerHeight = 0; 
	}

	if (powerruntime) {
		var powerruntimeHeight = powerruntime.offsetHeight;
	} else {
		var powerruntimeHeight = 0; 
	}
	var cartElHeights = priceContainerHeight+totalHeight+includelistHeight+powerruntimeHeight+controlButtonHeight;
	
	maxHeight= (viewportheight-topWhiteSpace - cartElHeights);
	
	//windowWidth<1000
	if (bShowSummaryCart) {
		if (floater) {
			floater.style.display = 'none';
		}if (summarybottom) {
			summarybottom.style.display = 'block';
		}
		if (functionsbottom) {
			functionsbottom.firstDescendant().className = "botFunctionsAbs";
		}
	}
	//The left space can contains the floating cart, even after adjust
	else {	
		if (browserSpace < floaterIdentifierY && maxHeight < 50) {
			if (floater) {
				floater.style.display = 'none';
		    }
		    if (summarybottom) {
				summarybottom.style.display = 'block';
		    }
			if (functionsbottom) {
				functionsbottom.firstDescendant().className = "botFunctionsAbs";
			}
		}
		else {
			if (floater) {
				floater.style.display = 'block';
		    }
		    if (summarybottom) {
				summarybottom.style.display = 'none';
		    }
			if (functionsbottom) {
				functionsbottom.firstDescendant().className = "botFunctionsRel";
			}
			//The left space can contains the floating cart
			if (browserSpace >= floaterIdentifierY) {
				if (componentlist) {
					componentlist.style.height = "";
					componentlist.style.border = "none";
					componentlist.className = "small-text compList";
				}
			}
			//The left space can not contains the floating cart,but can contains it if the 
			//floating cart is adjusted to an appropriate size
			else {
				var items = document.getElementsByName("optionItems");
				var mHeight = 0;
				for (i = 0; i < items.length; i++) {
					mHeight += items[i].offsetHeight;
				}
				mHeight = mHeight + cartElHeights;		
				//need to adjust		
				if (mHeight > browserSpace) {
					if (componentlist) {
						componentlist.style.height = maxHeight;
						componentlist.style.border = "1px solid #ccc";
					}
				}
				//do not need to adjust
				else {
					if (componentlist) {
						componentlist.style.height = "";
						componentlist.style.border = "none";
						componentlist.className = "small-text compList";
					}
				}
			}
		}
	}
}

function updatePowerDrawCart( value ) {
	if (document.getElementById("powerDrawValueCart")) {
		document.getElementById("powerDrawValueCart").innerHTML = value;
	}
}

function updateDesiredRuntimeCart( value ) {
	if (document.getElementById("desiredRuntimeValueCart")) {
		document.getElementById("desiredRuntimeValueCart").innerHTML = value;
	}
	
}

function formatPrice(price, id, cart_id, quantity)
{
	DWREngine._execute('controllers/OrderOptions.cfc', null, 'formatPrice', price, (formatPriceCounter + "_" + id), formatPrice_cb);
	formatPriceElements[id] = new Array(formatPriceCounter++, formatPriceWait, cart_id, quantity);	
}

function formatPrice_cb(results){
	// Sanity check
	if ( results == null || typeof(results) != 'object' || results.length != 3 ) {
		alert("DEBUG: Invalid value passed to callback function");
		return;
	}
	
	// The price counter will be preceding the actual id, with a '_' as seperator
	var id_index = results[1].indexOf("_");
	if (id_index < 0) {
		alert("DEBUG: Price format callback function passed invalid element id");
		return;
	}
	
	// Skip this element if it is not in the element array
	// (must have been removed from the array prior to this ajax call returning)
	var element_id = results[1].substring(id_index + 1);
	if (!(element_id in formatPriceElements)) {
		//alert("DEBUG: Price format callback element not found in array (element ID: " + element_id + ")");
		return;
	}

	// Get the price counter value to see if this is an old callback
	var price_counter = results[1].substring(0, id_index);
	var price_formatted = (results[2] == "") ? results[0] : results[2];
	if (price_counter != formatPriceElements[element_id][0]) {
		//alert("DEBUG: Price format callback function called for old price call (element ID: " + element_id + ", old counter: " + price_counter + ", current counter: " + formatPriceElements[element_id][0] + ")");
		return;
	}
	formatPriceElements[element_id][1] = parsePrice(price_formatted);

	// The special id value of 'mainPrice' refers to the 'oPriceDisplay' object
	// All other id values refer to actual HTML elements ids			
	if (element_id == "mainPrice") {
		for (var i=0; i<oPriceDisplay.length; ++i) {
		  	if(oPriceDisplay[i] != null) {
		  		oPriceDisplay[i].innerHTML = formatPriceElements[element_id][1];
		  	}
		}
	}
	
	// Subtotal prices do not have corresponding prices in the floating cart
	else if ( element_id.substring(0, "options_section_subtotal_".length) == "options_section_subtotal_" || element_id == "cartOptionsValue" ) {
		document.getElementById(element_id).innerHTML = formatPriceElements[element_id][1];
	}
	else {
		
		// Make sure the element exists before we update it
		var price_element = document.getElementById(element_id + '-display');
		if (!price_element) {
			alert("DEBUG: Price format callback function could not find the element to update (id: " + element_id + "-display)");
			return;
		}
		
		// Is the item currently checked?
		if ( $(element_id).checked ) {
			price_element.innerHTML = formatPriceElements[element_id][1];
			
			if ( formatPriceElements[element_id][2] ) {
				document.getElementById(formatPriceElements[element_id][2]).innerHTML = formatPriceElements[element_id][1];
			}
			else {
				alert("DEBUG: Price format callback function could not find cart element to update (id: [" + element_id + "])");
			}
		}
	}
}

function parsePrice( price ) {
	var priceArr = price.split(":");

	if ( priceArr.length > 1 ) {
		return priceArr[1].replace(/^\s+|\s+$/g, '');
	} else {
		return price;
	}
}

function flashItem(value) {
	var input = document.getElementById(value);
	if ( input ) {
		getElementRow(input).style.backgroundColor = '#F8F8DC';
		setTimeout( function() {getElementRow(input).style.backgroundColor = '#fff';;},1500 );
	}
}

function removeItem( value ) {
	
	var removed_element = document.getElementById(value);
	if ( !removed_element ) {
		alert("DEBUG: Could not find element with ID: [" + value + "]");
		return;
	}
	
	//removed_element.checked = false;
	
	// Select 'None' if removing batteries
	if ( value.substring(0, "BATTERY_LIST-".length) == "BATTERY_LIST-" ) {
		document.getElementById("BATTERY_LIST-0").checked = true;
		changeSolution();
	}
		
	// Select 'None' if removing a warranty
	else if ( value.match(/-warranty-(?:[0-9]+)$/) )
		document.getElementById(value.substring(0, value.lastIndexOf("-warranty-")) + "-warranty-0").checked = true;
	else
		removed_element.checked = false;
		
	updateLineItem(value);
}

function confirmRemoval( value ) {
	confirmBox = confirm("This will remove the selected option from your configuration. Are you sure?");
	
	if ( confirmBox == true ) {
		removeItem( value );
	}
	return confirmBox;
}

/** Gets the table row (<TR>) an element is in */
function getElementRow( element ) {
	while (element.tagName!="TR") {element=element.parentNode;}			
	return element;
}

/** Utility function to convert a number to dollarFormat */
function dollarFormat(number)
{
	// Strip out special characters like the dollar ($) sign or the comma (,)
	number = number.toString().replace(/\$|\,/g,'');

	// Make sure the number is a number
	if(isNaN(number))
		number = "0.00";
	
	// Find out if we should have a minus sign (-) in front of number	
	sign = (number == (number = Math.abs(number)));
	
	number = Math.floor(number*100+0.50000000001);
	
	// Find the out what change is
	cents = number%100;
	number = Math.floor(number/100).toString();
	
	// make sure the change is in a double digit format
	if(cents<10)
		cents = "0" + cents;
	
	// put in the commas at every three digits
	for (var i = 0; i < Math.floor((number.length-(1+i))/3); i++)
		number = number.substring(0,number.length-(4*i+3)) + currencyGroupingSeporator + number.substring(number.length-(4*i+3));
	
	// Return the format number
	return (((sign)?'':'-') + '$' + number + currencyDecimalSeporator + cents);
}


/**
 * This is a global variable used to store this browser's style for displaying TBody elements
 */
var DISPLAY_TBODY = "none";

/**
 * Opens the PDU selection frame
 * @param {String} zid The current Zone ID
 * @param {String} id The category ID to cancle
 * @param {HTMLElement} control The control elements for the section (usually an <a> tag)
 */
function helpChoosePDU(zid, id, control) {
	var url = "/tools/selector/pdu/bin/main.html?zid="+zid;

	var header = document.getElementById('HeaderSection-'+id);
	var tabID = document.getElementById(id+"-1-tab").value;
	var tbody = document.getElementById('options_section_body_'+tabID);
	var selector = document.getElementById(id+'-selector');
	var extraControls = document.getElementById(id+'-extracontrols');
	
	glSelectorID = id;
	glSelectorControl = control;
	glSelectorExtra = extraControls;
	
	/* CHECK: is the control already active? */
	if(control.className == 'active') { 
		/* Cancel PDU selection */
		cancelChoosePDU(tabID);
		return false; 
	}
	
	if(!selector) {
		var selector = document.createElement("tbody");
		selector.style.width = "100%";
		
		var selectorRow = document.createElement("tr");
		selector.id = id+'-selector';
		var selectorCell = document.createElement("td");
		
		selectorCell.colSpan = header.colSpan;
		
		selectorCell.innerHTML = '<iframe name="_main" src="'+url+'" frameborder="0" scrolling="no" width="100%" height="350"></iframe>';
		
		selectorRow.appendChild( selectorCell );
		selector.appendChild( selectorRow );

		tbody.parentNode.insertBefore(selector, tbody.nextSibling);
		
		if (!IE) {
			selector.appendChild(extraControls);
		}
		
		DISPLAY_TBODY = selector.style.display;
	} else if (!IE) {
		selector.appendChild(extraControls);
	}
	
	document.getElementById('options_section_columnheads_'+tabID).style.visibility = "hidden";
	document.getElementById("optionsSection").className = "sectionMainSelector";
	tbody.style.display = 'none';

	selector.style.display = DISPLAY_TBODY;
	
	control.className = 'active';
	
	x = control.getElementsByTagName('span');
	x[0].innerHTML = 'Cancel Selecting';
	return false;
}
/**
 * Cancels the PDU Selector display
 * @param {tabValue} The ID of the product tab
 */
function cancelChoosePDU( tabValue ) {
	var selector = document.getElementById(glSelectorID+'-selector');

	if (selector) {
		var tabID = document.getElementById(glSelectorID+"-1-tab").value;
		var tbody = document.getElementById('options_section_body_'+tabID);
		var keyText = glSelectorControl.getElementsByTagName('span');
		
		if (tabID == tabValue) {
			document.getElementById('options_section_columnheads_'+tabID).style.visibility = "visible";
			
			if (!IE) {
				tbody.appendChild(glSelectorExtra);
			}
		}
		
		document.getElementById("optionsSection").className = "sectionMain";
		tbody.style.display = DISPLAY_TBODY;
		selector.style.display = 'none';
		
		glSelectorControl.className = 'inactive';
		keyText[0].innerHTML = 'Select';
	}
}

/**
 * Adds an option to a section
 * @param {String} catID The category ID to add the option too
 * @param {String} sku The SKU to add
 * @param {String} model The model name of the option to add
 * @param {float} unitPrice The unit price name of the option to add
 * @param {String} img The image URL name of the option to add
 */
function selectSKU(sku, model, unitPrice, img) {
	var initialEl = document.getElementById(sku+"-techspec");
	var tabID = document.getElementById(glSelectorID+"-1-tab").value;
	
	cancelChoosePDU(tabID);
	
	if (initialEl) {
		document.getElementById(inputID).checked = true;
	} else {
		var firstRow = document.getElementById(glSelectorID+'-1-tr');
		var newRow = new OptionRow(glSelectorID, sku, sku, model, unitPrice, null);
		var totalItems = document.getElementById(glSelectorID+'-totalItems').value;
		newRow = newRow.element;
		
		firstRow.parentNode.insertBefore(newRow, firstRow);
	}
	//calculateTotals();
	updateLineItem(glSelectorID+'-'+totalItems);
}

/** This function will create a single option row
 * 
 * @param {string}parentID The ID of the category, used to generate the ID of this one option 
 * @param {int}optionIndex The option's index. This is used to generate the option's ID, as well as the value passed to the controller for selection
 * @param {string}sku The option's SKU
 * @param {string}model The option's model name
 * @param {float}unitPrice The option's unit price
 * 
 * @return {HTMLElement}An HTMLElement (table row) that contains this option
 * 
 */
function OptionRow(parentID, optionIndex, sku, model, unitPrice, img) {
	
	this.parentID = parentID;
	this.optionIndex = optionIndex;
	this.sku = sku;
	this.model = model;
	this.unitPrice = unitPrice;
	this.img = img;
	this.id = parentID + '-' + optionIndex;
	this.tItems = 0;
	
	this.tabID = document.getElementById(this.parentID+'-1-tab').value;
	this.descText = document.getElementById(this.parentID+'-1-section').value;
	this.totalItems = document.getElementById(this.parentID+'-totalItems').value;
	this.tItems = parseInt(this.totalItems) + currentOptionRowCount;

	this.currentIdSet = this.parentID + '-' + this.tItems;
	
	/** Is this option checked? @type boolean */
	var isChecked = 'checked';
	
	/** Table row element to be returned @type HTMLElement */
	this.element = document.createElement("tr");
	this.element.id = this.id + '-tr';
	this.element.onmouseover = function() { optionRow.hoverOver(); };
	this.element.onmouseout = function() { optionRow.hoverOut(); };
	
	// Add cell with controls in it (radio button)
	var controlCell = document.createElement("td");
	controlCell.innerHTML = '<input type="hidden" id="' + this.currentIdSet + '-tab" value="' + this.tabID + '" /><input type="hidden" id="' + this.currentIdSet + '-section" value="' + this.descText + '" /><input type="checkbox" name="' + parentID + '" id="' + this.currentIdSet + '" value="' + optionIndex + '" onclick="updateLineItem(\''+this.currentIdSet+'\');" ' + isChecked + ' />'; 
	controlCell.className = 'optionsItem';
	controlCell.id = sku + "-controls";
	this.element.appendChild( controlCell );
	
	// QTY		
	var qtyCell = document.createElement("td");
	qtyCell.innerHTML = '<input name="' + this.currentIdSet + '-qty" value="1" id="' + this.currentIdSet + '-qty" class="qtyField" type="text" size="1" maxlength="2" onchange="calculateTotals();"/>'; 
	qtyCell.className = 'optionsItem';
	this.element.appendChild( qtyCell );
	
	// Add cell with description in it
	var descriptionCell = document.createElement("td");
	var descriptionSpan = document.createElement("span");
	var descriptionA = document.createElement("a");
	descriptionSpan.onmouseover = function() { optionRow.showBubble(); };
	descriptionSpan.onmouseout = function() { optionRow.hideBubble(); };
	descriptionSpan.innerHTML = model;
	descriptionA.appendChild(descriptionSpan);
	descriptionA.id = this.currentIdSet + '-title';
	descriptionA.className = "compLink";
	descriptionA.onClick = "return showProductDetails('" + sku + "');";
	descriptionA.href = "/resource/include/techspec_index.cfm?base_sku=" + sku;
	descriptionA.target = "_blank";
	descriptionCell.appendChild(descriptionA);
	descriptionCell.className = 'optionsItem';
	descriptionCell.colSpan = "2";
	descriptionCell.id = this.sku + "-description"
	this.element.appendChild( descriptionCell );
	this.descriptionCell = descriptionCell;
	
	// Add techspec cell
	var techspecCell = document.createElement("td");
	techspecCell.className = 'optionsItem';
	techspecCell.id = this.sku + "-techspec";
	var techspecCellText = '&nbsp;';
	if(sku != null) {
		var techspecCellText = '<a href="/resource/include/techspec_index.cfm?base_sku=' + sku + '&displayList=ALL&page_type=displaybasic&printer_friendly=yes" onclick="return showProductDetails(\'' + sku + '\')" target="_blank"><img src="/resource/images/pageicon3.gif" border="0" align="absmiddle"/></a> <span id="'+ this.currentIdSet +'-sku">' + sku + '</span>';
	}
	techspecCell.innerHTML = techspecCellText;
	this.element.appendChild( techspecCell );
	
	if(bAPCDisplayPrice) {
		// Add pricing cell 
		var pricingCell = document.createElement("td");
		var price = document.createElement("input");
		var priceText = document.createElement("span");
		price.type = 'hidden';
		price.id = this.currentIdSet + '-price';
		price.name = price.id;
		price.value = unitPrice;
		priceText.innerHTML = (unitPrice!=null)?dollarFormat(unitPrice):'&nbsp;';
		pricingCell.appendChild( price );
		pricingCell.appendChild( priceText );
		pricingCell.className = 'optionsItem';
		pricingCell.id = this.sku + '-unitprice';
		this.element.appendChild( pricingCell );
		
		var displayCell = document.createElement("td");
		var displayCellSpan = document.createElement("span");
		displayCell.className = "optionsItem";
		displayCellSpan.id =  this.currentIdSet + '-display';
		displayCellSpan.className = "optionsItemPrice";
		displayCellSpan.innerHTML = '&nbsp;';
		displayCell.appendChild( displayCellSpan );
		this.element.appendChild( displayCell );

		currentOptionRowCount = currentOptionRowCount + 1;
	}
		
	// Bind event methods to this row element
	var optionRow = this;
	
	// Return this object
	return this;
}

OptionRow.prototype.showBubble = function () {
	var displayObject = { 
		url: '../configure/includes/quickView.cfm?base_sku=' + this.sku,
		element: this.descriptionCell
	}
	start(displayObject);
	return false;
}

OptionRow.prototype.hideBubble = function () {
	start(null,'cancel');
	return false;
}

OptionRow.prototype.hoverOver = function () {
    this.element.style.backgroundColor = '#eee'; 
};

OptionRow.prototype.hoverOut = function () {
    this.element.style.backgroundColor = '#fff';
};

/**
 * Opens a description pop-up window
 * @param {string} option_desc: The description to display
 */
function OpenDesc(name, desc) {
	var URL = "includes/help.cfm?name="+name+"&desc="+desc;
	window.open(URL,"dWin", 'height=250,width=400,menubar=no,scrollbars=yes,screenx=10,screeny=10,top=10,left=10');
	return false;
}


// Preload the blank product icon
var blankIcon = new Image(64,64);
blankIcon.src="/resource/images/invisible.gif";

// Global variable for tracking section icons
var iconMap = new Object();

/**
 * 
 * @param {string} id
 * @param {string} sku
 * @param {URL} img
 */
function displaySKUDetails(e, id, sku, img) {
	var imgCell = document.getElementById(id+'-img');
	var aImg = imgCell.getElementsByTagName('img');
	var aDiv = imgCell.getElementsByTagName('div');
	
	var lastImg = aImg[0];
		
	if(sku == '&nbsp;' | sku == '') {
		imgCell.style.backgroundColor = 'white';
		e.style.backgroundColor = 'white';
		aDiv[0].innerHTML = '&nbsp;';
		aImg[0].src = iconMap[ id ];
		aImg[0].className = 'defaultInfo';
	} else {

		// Capture the current icon
		iconMap[ id ] = lastImg.src;
		
		// Swap the image with a blank one to avoid problems if the new icon takes a long time to load later
		aImg[0].src = blankIcon.src;
		
		imgCell.style.backgroundColor = '#eeeeee';
		e.style.backgroundColor = '#eeeeee';
		aDiv[0].innerHTML = sku;
		aImg[0].src = img;
		aImg[0].className = 'productInfo';
	}	
}

function showWarrantyPanel() 			
{
	var countXwar = 0;
	var delay = 0;

	for(j=0; j<document.OptionsForm.length; j++)
	{
		if(document.OptionsForm.elements[j].name == '107,248,187,344' && document.OptionsForm.elements[j].checked)
		{
			var controlElementID = document.OptionsForm.elements[j].name + '-' + document.OptionsForm.elements[j].value;
			var skuElementID = document.OptionsForm.elements[j].name + '-' + document.OptionsForm.elements[j].value + '-sku-href';
			//sku = document.getElementById(skuElementID).innerHTML;
			//control = document.getElementById(controlElementID);
			//refreshXWarr(sku, control);
			//countXwar = countXwar + 1;
		}
	}

	if (countXwar == 0)
		delay = 0;
	else if(countXwar >= 1 && countXwar <= 2)
		delay = 1000;
	else if(countXwar >= 3 && countXwar <= 4)
		delay = 2000;
	else if(countXwar == 5)
		delay = 2500;
	else if(countXwar == 6)
		delay = 3500;
	else
		delay = 4000;

	return delay;
}

function IsNumeric(text)
{
   var ValidChars = "0123456789";
   var IsInteger=true;
   var Char;
 
   for (i = 0; i < text.length && IsInteger == true; i++) 
      { 
      if (ValidChars.indexOf(text.charAt(i)) == -1) 
         {	
		 IsInteger = false;
         }
      }
   return IsInteger;
}



