/* Give IE6 a window.XMLHttpRequest */
if (typeof document.body.style.maxHeight == "undefined") {
	window.XMLHttpRequest = function() { return new ActiveXObject('Microsoft.XMLHTTP') }
}
	
// Note: For checkboxes, UpdatePrice() assumes that the clicked checkbox has indeed changed.  Do not call this function if it hasn't changed.
function UpdatePrice(strCat,strProdNumAndQuantity,strType)
{

	var print_summary=document.getElementById("print_summary");
	if(print_summary != null)
	{
		print_summary.href="javascript:void(0)";
		print_summary.style.color = '#DCDCDC';
	}
	var save_choices = document.getElementById("save_choices");
	if(save_choices !=null)
	{
		save_choices.href="javascript:SaveChoices()";
		save_choices.style.color = "";
	}



	var strTag = strCat + '_' + strProdNumAndQuantity;
	var ndeltaval = parseFloat(document.getElementById(strTag + '_delta').attributes["value"].value);		
	var nprodnum = strProdNumAndQuantity.split("_")[0];

	if (strType == 'select')
	{
		var ocatselect = document.getElementById('select_' + strCat);
		
		for (i=0; i < ocatselect.options.length; i++)  
		{
			var suffix = "";
			if (ocatselect.options[i].innerHTML.indexOf('(Recommended)') >= 0) suffix = " (Recommended)";
			var strCurrentOption = ocatselect.options[i].attributes["value"].value;
			var noptionprice = parseFloat(document.getElementById(strCat + '_' + strCurrentOption + '_delta').attributes["value"].value);
			noptionprice = noptionprice - ndeltaval;
			noptionprice = Math.round(noptionprice*100)/100;
			noptionprice = noptionprice.toFixed(2);
								
			var strAdd = '';					
			if (noptionprice > 0){strAdd=' (add $' + noptionprice + ')';}
			else if (noptionprice < 0)
			{
				var ntempprice = noptionprice*-1; 
				strAdd = ' (subtract $' + ntempprice.toFixed(2) + ')';
			}
			
			var strNewText = document.getElementById(strCat + '_' + strCurrentOption + '_text').attributes["value"].value + strAdd + suffix;
			document.getElementById(strCat + '_' + strCurrentOption + '_delta').attributes["value"].value = noptionprice;					
			ocatselect.options[i].innerHTML = strNewText;
			
		}
		if (nprodnum > 0)
		{
			var strhref = "javascript:AdvancedPopPage('/moreinfo?product=" + nprodnum + "','Images','no','no','no','no','yes','yes','no','no','595','595','0','0');"
			document.getElementById('learnmore_' + strCat).attributes["href"].value = strhref;
		}
		else 
		{
			document.getElementById('learnmore_' + strCat).attributes["href"].value = 'javascript:void(0);';
		}
		
	}
	else if (strType == 'radio')
	{
		var oradiogroup = eval('document.configure.radio_' + strCat);

		for (var i=0; i < oradiogroup.length; i++)  
		{ 
			var strCurrentOption = oradiogroup[i].attributes["value"].value;
			var noptionprice = parseFloat(document.getElementById(strCat + '_' + strCurrentOption + '_delta').attributes["value"].value);
			noptionprice = noptionprice - ndeltaval;
			noptionprice = Math.round(noptionprice*100)/100;
			noptionprice = noptionprice.toFixed(2);
			
			var strAdd = '';					
			if (noptionprice > 0){strAdd=' (add $' + noptionprice + ')';}
			else if (noptionprice < 0)
			{
				
				
				var ntempprice = noptionprice*-1; 
				strAdd = ' (subtract $' + ntempprice.toFixed(2) + ')';
			}
			
			var strNewText = document.getElementById(strCat + '_' + strCurrentOption + '_text').attributes["value"].value + strAdd;
			document.getElementById(strCat + '_' + strCurrentOption + '_delta').attributes["value"].value = noptionprice;					
			document.getElementById('radio_' + strCat + '_' + strCurrentOption + '_text').innerHTML = strNewText;					
		} 
/*
		if (nprodnum > 0)
		{
			var strhref = "javascript:AdvancedPopPage('/moreinfo?product=" + nprodnum + "','Images','no','no','no','no','yes','yes','no','no','595','595','0','0');"					
			document.getElementById('learnmore_' + strCat).attributes["href"].value = strhref;
		}
		else 
		{
			document.getElementById('learnmore_' + strCat).attributes["href"].value = 'javascript:void(0);';
		}						
*/
	}
	else if (strType == 'checkbox' && ndeltaval != 0)
	{
		var ocheckbox = document.getElementById('checkbox_' + strTag);
		var strAdd = '';
		
		if (ocheckbox.checked)
		{
			strAdd = ' (subtract $' + ndeltaval.toFixed(2) + ')';
			
			document.getElementById(strTag + '_delta').attributes["value"].value = ndeltaval*-1;				
		}
		else
		{
			var ntempprice = ndeltaval * -1;
			strAdd=' (add $' + ntempprice.toFixed(2) + ')';
			document.getElementById(strTag + '_delta').attributes["value"].value = ndeltaval*-1;					
		}
						
		var strNewText = document.getElementById(strTag + '_text').attributes["value"].value + strAdd;
		document.getElementById('checkbox_' + strTag + '_text').innerHTML = strNewText;

	}

	var ntotal = parseFloat(document.getElementById('totalprice').attributes["value"].value);
	ntotal = ntotal + ndeltaval;

	var ntotalprice = Math.round(ntotal*100)/100;  // rounds to nearest cent
	ntotalprice = ntotalprice.toFixed(2);
						
	document.getElementById('totalprice').attributes["value"].value = ntotalprice;	
	if (ntotalprice == Math.round(ntotalprice)) ntotalprice = Math.round(ntotalprice);  // chop off decimals iff .00
	document.getElementById('totalpricedisplay').innerHTML = addCommas(ntotalprice);
	document.getElementById('totalpricedisplay2').innerHTML = addCommas(ntotalprice);	
	
	//
	// This changes the Help Icon to blank if no item is selected
	//
	eval('var sel=document.configure.select_'+strCat);
	eval('var div_select = "div_'+strCat+'"');
	
	var div_select_style=null;
	if(document.getElementById(div_select)!=null)
		div_select_style=document.getElementById(div_select).style;
		
	if(sel != null && div_select != null && div_select_style!=null && 
		div_select_style.display != null)
		if(sel.options != null && sel.options[sel.selectedIndex].value != '0_0') {
			div_select_style.display = 'block';
		} else {
			div_select_style.display = 'none';
		}
	
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}


function changeMultiOption(option_name) {
	document.configure.multi_option.value=option_name;
	document.configure.multi_option_changed.value=1;
	var qString = document.configure.action;
	qString = qString.replace(/page/, "jnk");
	qString += "&page=1";
	document.configure.action = qString;

	validateform(document.configure);
	document.configure.submit();
}

//don't need?
//function miscConfigurationToggle(checkbox1) {
//	if (checkbox1.checked == 0) document.getElementById('misc_configuration').style.display = 'none';
//	else document.getElementById('misc_configuration').style.display = 'block';
//}

function updatePartitionInput(arrayNumber, enable){
	document.getElementById('partition_text_' + arrayNumber.toString()).disabled = !enable;
}

// refigure display/non-display of radio buttons
function refreshRaidOptions(arrayNumber, driveQuantity){
	// whenever we set display to none, we also deselect that input\
	
	//TODO: When we have a qty 2 array changing from spare to no-spare, we need to automatically check "unspecified"

	var arrayDiv = document.getElementById('single_' + arrayNumber);
	if (arrayDiv != null){
		if (driveQuantity == 1) arrayDiv.style.display = 'inline';
		else arrayDiv.style.display = 'none';
	}	
	
	var arrayDiv = document.getElementById('unspecified_array_' + arrayNumber);
	if (arrayDiv != null){
		if (driveQuantity > 1) arrayDiv.style.display = 'block';
		else{
			arrayDiv.style.display = 'none';
			arrayDiv.getElementsByTagName('input')[0].checked = false;
		}

	}
	
	arrayDiv = document.getElementById('jbod_' + arrayNumber);
	if (arrayDiv != null){
		if (driveQuantity > 1){
			arrayDiv.style.display = 'block';
		}
		else{
			arrayDiv.getElementsByTagName('input')[0].checked = false;
			arrayDiv.style.display = 'none';
		}
	}

	arrayDiv = document.getElementById('raid0_' + arrayNumber);
	if (arrayDiv != null){
		if (driveQuantity > 1){
			arrayDiv.style.display = 'block';
		}
		else{
			arrayDiv.getElementsByTagName('input')[0].checked = false;
			arrayDiv.style.display = 'none';
		}
	}

	arrayDiv = document.getElementById('raid1_' + arrayNumber);
	if (arrayDiv != null){
		if (driveQuantity % 2 == 0 && driveQuantity >= 2) arrayDiv.style.display = 'block';
		else {
			arrayDiv.getElementsByTagName('input')[0].checked = false;
			arrayDiv.style.display = 'none';
		}
	}
	
	arrayDiv = document.getElementById('raid10_' + arrayNumber);
	if (arrayDiv != null){
		if (driveQuantity % 2 == 0 && driveQuantity >= 4) arrayDiv.style.display = 'block';
			else { 
				arrayDiv.getElementsByTagName('input')[0].checked = false;
				arrayDiv.style.display = 'none';
		}
	}
	
	arrayDiv = document.getElementById('raid5_' + arrayNumber);
	if (arrayDiv != null){
		if (driveQuantity > 2) arrayDiv.style.display = 'block';
		else {
			arrayDiv.getElementsByTagName('input')[0].checked = false;
			arrayDiv.style.display = 'none';
		}
	}

	arrayDiv = document.getElementById('raid6_' + arrayNumber);
	if (arrayDiv != null){
		if (driveQuantity > 3) arrayDiv.style.display = 'block';
		else {
				arrayDiv.getElementsByTagName('input')[0].checked = false;
				arrayDiv.style.display = 'none';
		}
	}
	
	arrayDiv = document.getElementById('raid_see_comments_' + arrayNumber);
	if (arrayDiv != null){
		if (driveQuantity > 1) arrayDiv.style.display = 'block';
		else {
				arrayDiv.getElementsByTagName('input')[0].checked = false;
				arrayDiv.style.display = 'none';
		}
	}
	
}

function textCounter(field, countfield, maxlimit) {
	if (field.value.length > maxlimit) // if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
	
	// otherwise, update 'characters left' counter
	else countfield.value = maxlimit - field.value.length;
}

function findPosition(obj)
{
	var curleft = curtop = 0;
	while (obj && obj.offsetParent)
	{
		curleft += obj.offsetLeft;
		curtop += obj.offsetTop;
		obj = obj.offsetParent;
	}
	return [curleft,curtop];
}

function getScroll()
{
	var x,y;
	if (self.pageYOffset) // all except Explorer
	{
		x = self.pageXOffset;
		y = self.pageYOffset;
	}
	else if (document.documentElement && document.documentElement.scrollTop)
		// Explorer 6 Strict
	{
		x = document.documentElement.scrollLeft;
		y = document.documentElement.scrollTop;
	}
	else if (document.body) // all other Explorers
	{
		x = document.body.scrollLeft;
		y = document.body.scrollTop;
	}
	return[x,y];
}

function CreateGalleryDiv(categoryCode, request)
{
	function DestroyCurrentGalleryDiv() { DestroyGalleryDiv(categoryCode); }

	if(request.readyState == 4 && request.status == 200 && request.responseText != null)
	{
		document.getElementById("segment_" + categoryCode).removeChild(document.getElementById(categoryCode + 'gallerywait'));
		var fadediv = document.createElement('div');
		fadediv.setAttribute('id', 'darkBackgroundLayer');
		fadediv.className = 'darkenBackground';
		fadediv.onclick = DestroyCurrentGalleryDiv;
		document.body.appendChild(fadediv);

		var segmentPosition = findPosition(document.getElementById("segment_" + categoryCode));
		var scrollPosition = getScroll();

		var newdiv = document.createElement('div');
		newdiv.setAttribute('id', categoryCode + 'gallery');
		newdiv.style.position = 'absolute';
		newdiv.style.left = segmentPosition[0] + 'px';
		newdiv.style.top = (scrollPosition[1] + 5) + 'px';
		newdiv.style.background='#FFFFFF';

		if (typeof document.body.style.maxHeight == "undefined") {
			// only in IE6, older browsers
			/* Give the div a "border" on the inside in IE6, since the fading doesn't work. */
			newdiv.style.background='#156797';
			newdiv.style.padding = '7px';
		}


		var closeDiv = document.createElement('div');  // this goes inside newDiv
		closeDiv.onclick = DestroyCurrentGalleryDiv;
		closeDiv.style.position = 'absolute';
		closeDiv.style.border = 'solid 1px White';
		closeDiv.style.padding = '3px 6px 3px 6px';
		closeDiv.style.fontSize = '14px';
		closeDiv.style.fontWeight = 'bold';
		closeDiv.style.background = 'Red';
		closeDiv.style.color = 'White';
		closeDiv.style.right = '0';
		closeDiv.style.top = '0';
		closeDiv.style.cursor = 'pointer';
		closeDiv.appendChild(document.createTextNode('X'));
		
		newdiv.innerHTML = request.responseText;
		newdiv.appendChild(closeDiv)

		document.body.appendChild(newdiv);

		//re-include js files from the gallery, since IE won't load them automatically (even with defer="true").
		var scripts = newdiv.getElementsByTagName("script");
		for (i = 0; i < scripts.length; i++)
		{
			if (scripts[i].src)
			{
				var h = document.getElementsByTagName('head')[0];
				var s = document.createElement('script');
				s.type = 'text/javascript';
				s.src = scripts[i].src;
				h.appendChild(s);
			}
		}

		//Unfortunately, the zIndex of fadediv doesn't appear to be readable at this point.
		//It returns 0 instead of the correct 20.
		newdiv.style.zIndex = 21;
	}
}

var popupGalleryLinkIsEnabled = true;

function DestroyGalleryDiv(categoryCode)
{
	document.body.removeChild(document.getElementById(categoryCode + 'gallery'));
	document.body.removeChild(document.getElementById('darkBackgroundLayer'));
	popupGalleryLinkIsEnabled = true;  // just in case we never got to the end of PopUpGallery()
}

//function CallbackWrapper()
//{
//	CreateGalleryDiv('PR', this);
//}

function ShowWait(categoryCode)
{
	var waitdiv = document.createElement('div');
	waitdiv.setAttribute('id', categoryCode + 'gallerywait');
	waitdiv.appendChild(document.createTextNode("Loading gallery, please wait"));
	waitdiv.style.color = 'Green';
	document.getElementById("segment_" + categoryCode).appendChild(waitdiv);
}


function PopupGallery(category, page)
{ 
	if (popupGalleryLinkIsEnabled){
		popupGalleryLinkIsEnabled = false;
		ShowWait(category);
		var client = new XMLHttpRequest();
		//Firefox and IE have differing opinions of the meaning of "this" inside the callback
		//(the function itself or the XMLHttpRequest, respectively), 
		//so it's passed as a parameter.
		client.onreadystatechange = function () { CreateGalleryDiv(category, client); }
		client.open('GET', '/fragment.aspx?id=' + page + '&in_configurator=1&segment=' + category, true);
		client.send(null);
	}
}

function AddProduct(product_number, category, description, price)
{
	var idTag = category + '_' + product_number + '_1';
	var existingOption = document.getElementById('checkbox_' + idTag);
	var isAlreadyChecked = false;
	if (existingOption)
	{
		isAlreadyChecked = existingOption.checked;
		existingOption.checked = true;
	}
	else
	{
		var formInput = document.createElement('input');
		formInput.type = 'checkbox'
		formInput.name = 'checkbox_' + category;
		formInput.setAttribute('id', 'checkbox_' + idTag);
		formInput.value = product_number + '_1';
		formInput.checked = true;
		formInput.onclick = function() { UpdatePrice(category, formInput.value, 'checkbox'); }
		var productDisplay = document.createElement('span');
		productDisplay.innerHTML = description;
		productDisplay.setAttribute('id', 'checkbox_' + idTag + '_text');
		var segmentBlock = document.getElementById('segment_' + category);
		var galleryLink = document.getElementById("gallery_link_" + category);
		segmentBlock.insertBefore(formInput, galleryLink);
		//IE resets checked to false when the element is added to the document.
		//"checked" is still set before adding the element so that it's pre-checked in other browsers.
		formInput.checked = true;
		segmentBlock.insertBefore(productDisplay, galleryLink);
		segmentBlock.insertBefore(document.createElement('br'), galleryLink);

		var deltaInput = document.createElement('input');
		deltaInput.type = 'hidden';
		deltaInput.name = idTag + '_delta';
		deltaInput.setAttribute('id', deltaInput.name);
		deltaInput.value = price;
		var originalDescription = document.createElement('input');
		originalDescription.type='hidden';
		originalDescription.setAttribute('id', idTag + '_text');
		originalDescription.value = description;
		var externalFlag = document.createElement('input');
		externalFlag.type = 'hidden';
		externalFlag.name = idTag + '_external';
		externalFlag.value = 1;
		var mainForm = document.getElementById('configure');
		mainForm.appendChild(originalDescription);
		mainForm.appendChild(deltaInput);
		mainForm.appendChild(externalFlag);
	}

	if (!isAlreadyChecked) {
		UpdatePrice(category, product_number + '_1', 'checkbox');
	}
	
	DestroyGalleryDiv(category);
}
	

