/*
 * 04/28/2002 - ST  - Check parts entered for garbage characters and quotes
 * 12/01/2002 - ST  - And fixed that!
 * 04/17/2004 - ??? - In showAPart, put "-->" after action 1 - to be removed later when storing in MySQL
 * 12/28/2006 - JL  - In partChange(), added auto-selection of first item for action/level 2 (and call descriptionChange())
 *                    and commented out showAPart() since descriptionChange() calls it anyway
 * 12/28/2006 - ??? - Modified addPart() to store the partnumber
 * 12/28/2006 - ??? - Modified finalChange(): changed definition of number:
 *                        box[].value has part number now, no longer index the index
 *                        selectedIndex is used now.
 *                    Also changed URL construction
 * 01/24/2007 - MC  - Require action 2
 * 07/24/2008 - JMH - Changed from document.forms[0] to document.forms["parts"]
 * 09/17/2008 - JMH - Changed from document.forms["parts"] to $("partsForm")
 *                    Code cleanup
 * 10/06/2008 - JMH - Added year/make/model/body code
 * 12/11/2009 - JLB - Some action2 parts require "one or more" action3's
 */

function init() {
	$("partsForm").finishButton.disabled = $("partsForm").finalParts.length <= 1;
}

function initChecklist() {
	if (document.all && document.getElementById) {
		/* Get all labels in unordered lists, if the unordered list has classname "checklist" */
		var labels = $$("ul.checklist label");
		
		/* Assign event handlers to labels */
		for (var j = 0; j < labels.length; j++) {
			var theLabel = labels[j];
			theLabel.onmouseover = function() {
			                           $(this).addClassName("hover");
			                       };
			theLabel.onmouseout = function() {
			                          $(this).removeClassName("hover");
			                      };
		}
	}
}

function showAPart() {
	/* Display current part - called when anything changes */
	
	var box = $("partsForm").parts;
	var part = box.options[box.selectedIndex].text;
	
	var box2 = $("partsForm").descriptions;
	
	if (box2.selectedIndex >= 0) {
		part += " --> " + box2.options[box2.selectedIndex].text;
	}
	
	var numberOptions = 0;
	
	var box3 = $("partsForm").partopts;
	
	for (var i = 0; i < box3.length; i++) {
		if (box3[i].checked) {
			if (numberOptions++ == 0) {
				part += " {" + $F("text" + $F(box3[i]));
			} else {
				part += " " + $F("text" + $F(box3[i]));
			}
		}
	}
	
	if (numberOptions > 0) {
		part += "}";
	}
	
	$("partsForm").aPart.value = part;
}

function noAction2() {
	return true;
}

function addPart() {
	var theForm = $("partsForm");
	
	if(theForm.action3RequiredHidden.value == "true") {
      		var keepLooking = true;
		var box3 = $("partsForm").partopts;
		var optionSelected = false;
		for (i=0;i<box3.length && keepLooking;i++) {
			if (box3[i].checked) {
				optionSelected = true;
				keepLooking = false;
			}
		}
		if(optionSelected == false) {
			alert("More information required.  Please select option(s) from the action 3 list.");
			return false;
		}
	}

	if (theForm.descriptions.selectedIndex == -1) {
		alert("Action 2 required.");
	} else {
		if ($F(theForm.aPart).length == 0) {
			alert("There is nothing to add.");
		} else {
			if (!areLegalCharacters(theForm.aPart)) {
				alert("May not use control characters or quotes in description.");
				return;
			}
			
			/* Added pn_[$("partsForm").parts.selectedIndex][$("partsForm").descriptions.selectedIndex] to store part number in .value field of finalParts */
			$(theForm.finalParts).insert("<option value=\"" + pn_[theForm.parts.selectedIndex][theForm.descriptions.selectedIndex] + "\">" + $F(theForm.aPart) + ($F(theForm.preferredCondition) != "1" ? " [" + theForm.preferredCondition[theForm.preferredCondition.selectedIndex].text + "]" : "") + "</option>");
			
			var id = theForm.parts.selectedIndex;
			id += "|" + theForm.descriptions.selectedIndex + "|";
			
			for (var i = 0; i < theForm.partopts.length; i++) {
				if (theForm.partopts[i].checked) {
					id += i + ",";
				}
			}
			id += "|" + $F(theForm.aPart) + "|" + $F(theForm.preferredCondition);
			
			theForm.finalParts.options[theForm.finalParts.options.length - 1].id = id;
			theForm.finalParts.selectedIndex = -1;
			
			theForm.finishButton.disabled = false;
			
			/* Clear so they cant click twice: */
			theForm.aPart.value = "";
			
			/* Reset the preferredCondition drop-down to its default value */
			for (var i = 0; i < theForm.preferredCondition.options.length; i++) {
				if (theForm.preferredCondition.options[i].defaultSelected) {
					theForm.preferredCondition.value = theForm.preferredCondition.options[i].value;
				}
			}
		}
	}
}

function deletePart() {
	var theForm = $("partsForm");
	var box = theForm.finalParts;
	
	var number = box.selectedIndex;
	
	if (number != 0) {
		Element.remove(box.descendants()[number]);
		if (box.length == 1) {
			theForm.finishButton.disabled = true;
		}
	}
}

function descriptionChange() {
	var number = $F($("partsForm").parts);
	
	if (!number) {
		return;
	}
	
	/* list = d_ for this particular part */
	var list = d_[number];
	
	$("partsForm").action3RequiredHidden.value = 
		action3Required_[$("partsForm").parts.selectedIndex][$("partsForm").descriptions.selectedIndex];

	var number2 = $F($("partsForm").descriptions);
	
	if (!number2) {
		/* number2 = selected description for a given part */
		return;
	}
	
	/* Pointer to options */
	var offset = number2 * 2 + 1;
	
	var listOptions = o_[list[offset]];
	
	Element.remove($("partsList"));
	$("partoptions").insert("<ul id=\"partsList\" class=\"checklist\"></ul>");
	
	var myRoot = $("partsList");
	if (listOptions.length == 0) {
		/* Fix the bug where going from a part with options to a part
		   without options causes the part not to show up in the Action 4 box */
		$("partsForm").partopts = {};
	} else {
		for (var i = 0; i < listOptions.length; i++) {
			myRoot.insert("<li><label id=\"label" + i + "\" for=\"option" + i + "\" onclick=\"optionChange()\"><input type=\"checkbox\" name=\"partopts\" id=\"option" + i + "\" value=\"" + i + "\" />" + listOptions[i] + "</label><input type=\"hidden\" id=\"text" + i + "\" value=\"" + listOptions[i] + "\" /></li>");
		}
	}
	initChecklist();
	showAPart();
}

function partChange() {
	var number = $F($("partsForm").parts);
	
	if (!number) {
		return;
	}
	
	var list = d_[number];
	var box2 = $("partsForm").descriptions;
	
	while (box2.options.length) {
		box2.options[0] = null;
	}
	
	for (var i = 0; i < list.length; i += 2) {
		box2.options[i/2] = new Option(list[i], i/2);
	}
	
	$("partsForm").descriptions.selectedIndex = 0;
	descriptionChange();
}

function optionChange() {
	showAPart();
}

function optionTestIt() {
	optionTest = true;
	lgth = document.forms['testform'].testselect.options.length - 1;
	document.forms['testform'].testselect.options[lgth] = null;
	if (document.forms['testform'].testselect.options[lgth]) {
		optionTest = false;
	}
}

function editOrDelete() {
	if ($("partsForm").finalParts.selectedIndex != 0) {
		getMyLightbox().start();
	}
}

function editPart() {
	var theForm = $("partsForm");

	var box = theForm.finalParts;
	var number = box.selectedIndex;
	//var count = 0;
	var values = new String(box.options[number].id);
	
	var index = values.indexOf('|');
	var lastIndex = values.lastIndexOf('|');
	
	var first = values.substring(0, index);
	values = values.substring(index + 1);
	index = values.indexOf('|');
	
	var second = values.substring(0, index);
	values = values.substring(index + 1);
	index = values.indexOf('|');
	
	var third = values.substring(0, index);
	values = values.substring(index + 1);
	index = values.indexOf('|');
	
	var fourth = values.substring(0, index);
	
	var fifth = values.substring(index + 1);
	
	theForm.parts.options[first].selected = true;
	partChange();
	
	theForm.descriptions.options[second].selected = true;
	
	var cur = '';
	
	for (var i = 0; i < third.length; i++) {
		if (third.charAt(i) != ',') {
			cur += third.charAt(i);
		} else {
			theForm.partopts[cur].checked = true;
			cur = "";
		}
	}
	theForm.aPart.value = fourth;
	
	theForm.preferredCondition.value = fifth;
	
	Element.remove(box.descendants()[number]);
	
	if (box.length == 1) {
		theForm.finishButton.disabled = true;
	}
}

function cancelLightBox() {
	$("partsForm").finalParts.selectedIndex = -1;
}

function getModels() {
	var theForm = $('vehicleInfo_Form');
	var processingImg = $('modelsProcessing');
	
	if ($F(theForm.year) != "" && theForm.make.selectedIndex != 0) {
		processingImg.setStyle({visibility: 'visible'});
		
		var myAJAXRequest = new Ajax.Request("/includes/csi_common/jsp/AJAX_Utility.jsp", {
		                                     parameters: {
		                                                  Live_getModels: 'true',
		                                                  makeParam: theForm.make[theForm.make.selectedIndex].value,
		                                                  yearParam: $F(theForm.year)
		                                                 },
		                                     onSuccess:  function(transport) {
		                                                     var models = transport.responseXML.getElementsByTagName("response")[0].getElementsByTagName("model");
		                                                     
		                                                     $('models').update('<option>-- Select Model --</option>');
		                                                     var selectedIndex = 0;
		                                                     for (var i = 0; i < models.length; i++) {
		                                                         if (selectedIndex == 0 && $F(theForm.selectedModel) == models[i].firstChild.nodeValue) {
		                                                             selectedIndex = i + 1;
		                                                         }
		                                                         $('models').insert("<option" + ($F(theForm.selectedModel) == models[i].firstChild.nodeValue ? " selected=\"selected\"" : "") + ">" + models[i].firstChild.nodeValue + "</option>");
		                                                     }
		                                                     if (selectedIndex != 0) {
		                                                         theForm.otherModel.value = $F(theForm.selectedModel);
		                                                     } else {
		                                                         theForm.otherModel.value = "";
		                                                     }
		                                                     $('models').selectedIndex = selectedIndex;
		                                                     getBodies();
		                                                 },
		                                     onComplete: function(transport) {
		                                                     processingImg.setStyle({visibility: 'hidden'});
		                                                 }
		                                   });
	}
}

function getBodies() {
	var theForm = $('vehicleInfo_Form');
	var processingImg = $('bodiesProcessing');
	
	processingImg.setStyle({visibility: 'visible'});
	
	var myAJAXRequest = new Ajax.Request("/includes/csi_common/jsp/AJAX_Utility.jsp", {
	                                     parameters: {
	                                                  Live_getBodies: 'true',
	                                                  model: $F(theForm.model)
	                                                 },
	                                     onSuccess:  function(transport) {
	                                                     var bodies = transport.responseXML.getElementsByTagName("response")[0].getElementsByTagName("body");
	                                                     $('bodies').update("<option>-- Select Body --</option>");
	                                                     var selectedIndex = 0;
	                                                     for (var i = 0; i < bodies.length; i++) {
	                                                         if (selectedIndex == 0 && $F(theForm.selectedBody) == bodies[i].firstChild.nodeValue) {
	                                                             selectedIndex = i + 1;
	                                                         }
	                                                         $('bodies').insert("<option" + ($F(theForm.selectedBody) == bodies[i].firstChild.nodeValue ? " selected=\"selected\"" : "") + ">" + bodies[i].firstChild.nodeValue + "</option>");
	                                                     }
	                                                     if (selectedIndex != 0) {
	                                                         theForm.otherBody.value = $F(theForm.selectedBody);
	                                                     } else {
	                                                         theForm.otherBody.value = "";
	                                                     }
	                                                     $('bodies').selectedIndex = selectedIndex;
	                                                     theForm.selectedBody.value = "";
	                                                 },
	                                     onComplete: function(transport) {
	                                                     processingImg.setStyle({visibility: 'hidden'});
	                                                 }
	                                   });
}
