// JavaScript Document

///////////////////////////////////////////////////////////
//
// 1. Event Handlers
// 2. Page Builders
// 3. Display
// 4. Ajax Getters
// 5. Getters
// 6. Miscellaneous
// 7. Helpers
//
///////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////
//					EVENT HANDLERS						 //
///////////////////////////////////////////////////////////

//DESC: Called when a configuration is selected, it sets the labels and inputs
//ARG: None
//RET: None
function setConfig(){
	var doc = document.forms['form1'];
	var labels = getConfigLines('lines');
	var isempty = document.getElementById('engraveDiv').childNodes.length;
	if (!isempty) {	
		buildAdvancedText(labels);
		addTag(labels,'engraveDiv','nocopy');
		$('#buildertags').show('drop');
		}
	else {
		resetConfig();
		}
	suggestTextHeight();
	testFJS();
	return true;
	}

//DESC: Clicking on the back step displays the previous step
//ARG: None
//RET: None
function clickBackStep(){
	var curStep = getCurrentStep();
	var infopage, part;
	//Only display the previous step if we arent already displaying the 1st step
	if (curStep == 1){
		part = document.forms['form1'].elements['partId'].value;
		switch(part) {
			case "PB":
				infopage = "pushbuttontags.cfm";
				break;
			case "WN1":
			case "WN2":
				infopage = "wallnameplates.cfm";
				break;
			case "DN1":
			case "DN2":
				infopage = "desknameplates.cfm";
				break;
			case "VT":
				infopage = "valvetags.cfm";
				break;
			case "NT":
				infopage = "nametags.cfm";
				break;
			case "FT":
				infopage = "flattags.cfm";
				break;
			default:
				infopage = "index.cfm";
			}
		dcheck('/' + infopage, 'Product');
		}
	else {
		displayStep(curStep-1);
		}
	}

//DESC: Used to display confirm alert before proceeding to link 
//ARG: String
//RET: None
function dcheck(url, pagetitle) {
	var answer = confirm('This item has not been added to your cart\n\nDiscard these settings and return to ' + pagetitle + ' page?');
	if(answer != 0){
		window.location.href = url;
		}
	}

//DESC: Clicking on the add tag button, this calls the function to add a set of inputs
//ARG: None
//RET: None
function clickAdd() {
	var doc = document.forms['form1'];
	var labels = getConfigLines('lines');
	addTag(labels,"engraveDiv");
	redrawme();
	}
	
//DESC: Called when an input or the edit link is clicked on, this function sets the active set of inputs
//ARG: Integer, Boolean
//RET: None
function editElement(divNum, divClass) {
	var divId = 'tag' + divNum;
	//Get the focusDiv value, which holds the id of the div currently used for the preview 
	//If the currently infocus div holds the input we just clicked on, return and do nothing
	//If the currently focused div is different than what we just clicked on, do something
	var focusDiv = document.getElementById('focusDiv');
	if (focusDiv.value == divId){
		return;
		}
	else if(focusDiv.value.length > 0){
		removeDivFocus(document.getElementById(focusDiv.value));
		}
	//Give our new div the focus
	addDivFocus(document.getElementById(divId), divClass);
	focusDiv.value = divId;
	testFJS();
	}
	
//DESC: This function called when a text format link is clicked, changing the appearance based on its value
//ARG: Object
//RET: None
function changeTextFormat(linkObj) {
	var preClass, postClass;
	var formElement = document.forms['form1'].elements[linkObj.id];
	switch(linkObj.className.substring(0,1)) {
		case "u":
			preClass = "underlinelink";
			break;
		case "b":
			preClass = "boldlink";
			break;
		case "i":
			preClass = "italicslink";
			break;
		case "c":
			preClass = "capslink";
			break;
		}
	if(Boolean(parseInt(formElement.value))) {
		formElement.value = 0;
		linkObj.className = preClass + " inactive"; 
		}
	else {
		formElement.value = 1;
		linkObj.className = preClass + " active";
		}
	testFJS();
	}

//DESC: Called when the Caps link is clicked, it changes the class of the button and the texttransform of the inputs
//ARG: Integer
//RET: None
function changeUpCase(lineNum) {
	var formElement = document.forms['form1'].elements['tag_caps_tag1line' + lineNum];
	if(Boolean(parseInt(formElement.value))) {
		formElement.value = 0;
		newtransform = 'none';
		document.getElementById('tag_caps_tag1line' + lineNum).className = "capslink inactive";
		}
	else {
		formElement.value = 1;
		newtransform = 'uppercase';
		document.getElementById('tag_caps_tag1line' + lineNum).className = "capslink active";
		}
	var i = 1;
	while(document.forms['form1'].elements['tag' + i + 'line' + lineNum] != null) {
		document.forms['form1'].elements['tag' + i + 'line' + lineNum].style.textTransform = newtransform;
		i++;
		}
	testFJS();
	}

//DESC: Called when a new text size is selected. Will Check vaildate the new size
//ARG: 
//RET:
function checkTextSize(){
	testFJS();
	}

///////////////////////////////////////////////////////////
//					  PAGE BUILDERS						 //
///////////////////////////////////////////////////////////

//DESC: Adds a set of inputs with the specified labels to the specified div
//ARG: Array, String
//RET: None
function addTag(labels, div, divClass) {
	var mainContent, additionalContent, focusedText, capsStyle;
	var ni = document.getElementById(div);
	
	var numi = document.getElementById('theValue');
	// increment theValue variable, which holds the top tagid
	var num = (document.getElementById('theValue').value -1)+ 2;
	numi.value = num;
	
	var divIdName = 'tag'+num;
 	var newdiv = document.createElement('div');
	mainContent = '';

	for (var i=0; i<labels.length; i++) {
		capsStyle = 'none';
		if(document.getElementById('tag_caps_tag1line' + i) != null) {
			if(Boolean(parseInt(document.forms['form1'].elements['tag_caps_tag1line' + i].value))) {
				capsStyle = 'uppercase';
				}
			}
		mainContent = mainContent + '<label for="tag'+num+'line'+i+'">'+labels[i]+'</label><a href="javascript:void(0);" tabindex="1000" onClick="copyDown(' + num + ',' + i + ');" class="linkcopydown">Copy Down</a><input type="text" name="tag'+num+'line'+i+'" style="text-transform:' + capsStyle + '" onKeyUp="testFJS(this);" onFocus="editElement('+num+')" autocomplete="off" />';
		}
	
	additionalContent = '<span></span><a href="javascript:void(0);" id="linkRemove' + num + '" class="remove" onClick="removeElement('+num+')">Remove</a><a href="javascript:void(0);" tabindex="1000" class="linkfill" onClick="fillFromPrevious(' + num + ')">Fill From Previous</a><div class="quantlink"><label for="quantity_' + num + '" id="inputQuantity' + num + 'label">Quantity</label><input type="text" value="1" id="inputQuantity' + num + '" name="quantity_' + num + '" onFocus="editElement('+num+')"></div>';

	newdiv.setAttribute('id',divIdName);
	newdiv.innerHTML = additionalContent + mainContent;
	ni.appendChild(newdiv);
	//Set the newly added tag to be the one edited
	editElement(num,divClass);
	testFJS();
	}
	
//DESC: Takes an array of labels and builds the advanced text options part of the page
//ARG: Array
//RET: None
function buildAdvancedText (labels) {
	var putInDiv = 'builderadvanced';
	var preText = '<table cellspacing="0" id="engraver_ad"><thead><tr><th class="adlabel">&nbsp;</th><th class="adbuttons">&nbsp;</th><th class="adsize">Line Height</th><th class="adfont">Font</th></tr></thead><tfoot></tfoot><tbody>';
	var postText = '</tbody></table>';
	var midText = '';
	var sizeOptions = '<option value=".093">3/32 (0.093)</option><option value=".125">1/8 (0.125)</option><option value=".187">3/16 0.187</option><option value=".218">7/32 (0.218)</option><option value=".250">1/4 (0.250)</option><option value=".312">5/16 (0.312)</option><option value=".375">3/8 (0.375)</option><option value=".437">7/16 (0.437)</option><option value=".500">1/2 (0.500)</option><option value=".625">5/8 (0.625)</option><option value=".750">3/4 (0.750)</option><option value="1.00">1 (1.00)</option>';
	for (var i = 0; i < labels.length; i++) {
		midText = midText + '<tr><td><strong>' + labels[i] + '</strong></td><td class="center"><a href="javascript:void(0);" class="underlinelink inactive" id="tag_underline_tag1line' + i + '" onClick="changeTextFormat(this);return false;">u</a><input type="hidden" name="tag_underline_tag1line' + i + '" value="0"><a href="javascript:void(0);" class="boldlink inactive" id="tag_bold_tag1line' + i + '" onClick="changeTextFormat(this);return false;">b</a><input type="hidden" name="tag_bold_tag1line' + i + '" value="0"><a href="javascript:void(0);" class="italicslink inactive" id="tag_italics_tag1line' + i + '" onClick="changeTextFormat(this);return false;">i</a><input type="hidden" name="tag_italics_tag1line' + i + '" value="0"><a href="javascript:void(0);" class="capslink active" id="tag_caps_tag1line' + i + '" onClick="changeUpCase(' + i +');return false;">CAP</a><input type="hidden" name="tag_caps_tag1line' + i + '" value="1"></td> <td class="center"><select id="tag_size_tag1line' + i + '" name="tag_size_tag1line' + i + '" onChange="checkTextSize()">' + sizeOptions +'</select><strong> in.</strong> </td><td class="center"><select id="tag_font_tag1line' + i + '" name="tag_font_tag1line' + i + '" onChange="testFJS()"><option value="Default"> Default</option><option value="Arial"> Arial</option><option value="Times"> Times</option><option value="Verdana"> Verdana</option><option value="Tahoma"> Tahoma</option></select></td></tr>'
		}
	document.getElementById(putInDiv).innerHTML = preText + midText + postText;
	
	}

//DESC: If a configuration has already been set, this function will change the configuration for all sets of inputs
//ARG: None
//RET: None
function resetConfig() {
	var line, tagId, newlabel, newinput, inputname, inputcounter;
	var labels = getConfigLines('lines');
	var numlines = labels.length;
	// loop through engraveDiv's children, which are individual tags
	var loopDivs = ['engraveDiv','inputDiv'];
	for (var k=0; k<loopDivs.length; k++) {
		for (var i=0; i<document.getElementById(loopDivs[k]).childNodes.length; i++) {
			//Check that the child node is a div (containing a tags inputs), otherwise do nothing
			if (document.getElementById(loopDivs[k]).childNodes[i].tagName == 'DIV') {
				// tagId is the div id of the tags we are looping through
				tagId = document.getElementById(loopDivs[k]).childNodes[i];
				inputcounter = 0;
				// loop through all elements in tag div
				var initialNumber = tagId.childNodes.length;
				for (var j=0; j<initialNumber; j++) {
					// If we haven't encountered the number of inputs we want, go through and edit labels
					if(inputcounter < numlines) {
						switch (tagId.childNodes[j].tagName) {
							case "INPUT":
								if (tagId.childNodes[j].type == 'text') {
									inputcounter++;
									tagId.childNodes[j].style.textTransform = 'uppercase';
									}
								break;
							case "LABEL":
								tagId.childNodes[j].innerHTML = labels[inputcounter];
								break;
							}
						}
					// If the number of inputs is equal to what we want, remove any additional inputs
					else {
						tagId.removeChild(tagId.lastChild);
						}
					}
				// Now add inputs if the inputcounter did not get to the number of lines we want
				while (inputcounter < numlines) {
					inputname = tagId.id + 'line' + inputcounter;
					//We need the tag number to pass it to editElement and doneEditElement, passing a string is problematic the required quotations and the concentated string
					var tagNum = parseInt(tagId.id.substring(3,tagId.id.length));
					newinput = '<label for="' + inputname + '">' + labels[inputcounter] + '</label><a href="javascript:void(0);" onClick="copyDown(' + tagNum + ',' + inputcounter + ');" class="linkcopydown">Copy Down</a><input type="text" name="' + inputname + '" onKeyUp="testFJS()" style="text-transform:uppercase" onFocus="editElement(' + tagNum + ')" onBlur="" />'
					tagId.innerHTML = tagId.innerHTML + newinput;
					inputcounter++;
					}
				}
			}
		}
	buildAdvancedText(labels);
	return true;	
	}
	
//DESC: Removes a specifies div which contains a set of inputs
//ARG: Integer
//RET: None
function removeElement(divNum) {
	var divId = 'tag' + divNum;
	var d = document.getElementById('engraveDiv');
	var olddiv = document.getElementById(divId);
	var c = 0;
	//Check to see if the div has a class of 'copydiv' indicating it is the first div and has the copydown links
	if(olddiv.className.indexOf('copydiv') != -1){
		//Loop through the engrave div and set the second div to be the copydiv now, displaying the copydown links
		for (var i=0; i<document.getElementById('engraveDiv').childNodes.length; i++) {
			if (document.getElementById('engraveDiv').childNodes[i].tagName == 'DIV') {
				c++;
				if(c == 2){
					document.getElementById('engraveDiv').childNodes[i].className = olddiv.className;
					break;
					}
				}
			}
		}
	//Find out how many tag input divs are present, if there is only one, change the class so that the copy down links dont show up
	//UPDATE: Use 4, because each tag div contains a quantity div
	//Also, we are checking the length right before the 2nd to last div is deleted, so were checking for 2 divs
	if (document.getElementById('engraveDiv').getElementsByTagName('DIV').length == 4) {
		document.getElementById('engraveDiv').getElementsByTagName('DIV')[2].className = 'focus nocopy';
		document.getElementById('engraveDiv').getElementsByTagName('DIV')[0].className = 'focus nocopy';
		}
	//$(olddiv).Shrink(50,d.removeChild(olddiv));
	d.removeChild(olddiv);
	redrawme();
	}

///////////////////////////////////////////////////////////
//						DISPLAY							 //
///////////////////////////////////////////////////////////

//DESC: Defines a delay with the setTimeout function. This makes sure that the previewtag function is only called when there is a delay of calling the testFJS function
//ARG: None
//RET: None
function testFJS(obj){
	if ( this.zid ) {
		clearTimeout(this.zid);
		}
	//Since Internet Explorer 6 is a horrible horrible piece of crap, we need to pass the object (input) calling the function if we want it to retain focus
var is_ie/*@cc_on = {
  // quirksmode : (document.compatMode=="BackCompat"),
  version : parseFloat(navigator.appVersion.match(/MSIE (.+?);/)[1])
}@*/;
	if (obj != null && is_ie && (is_ie.version < 7)) {
		// IE6, older browsers
		// And, we have an object that we want to retain focus
		var f= function() { previewTag(obj) };
		this.zid = setTimeout(f,200);		
		} 
	else {
		// IE 7, mozilla, safari, opera 9
		this.zid = setTimeout('previewTag()',200);
		}
	}

//DESC: Function that is actually called to send values to the flash movie. Always called via testFJS
//ARG: None
//RET: None
function previewTag(obj){
	var doc = document.forms['form1'];
	var optUnderline = getTextOptions('underline');
	var optBold = getTextOptions('bold');
	var optItalics = getTextOptions('italics');
	var optSize = getTextOptions('size');
	var optFont = getTextOptions('font');
	var optCaps = getTextOptions('caps');
	var tagoptions = getOptions();
	var tagmount = getMount();
	var tagquantity = getTotalQuantity();
	//Get the Height and Width if the inputs are present
	if(doc.elements['width'] != null) {
		var tagwidth = parseFloat(doc.elements['width'].value);
		}
	else { tagwidth = 0 }
	if(doc.elements['height'] != null) {
		var tagheight = parseFloat(doc.elements['height'].value);
		}
	else { tagheight = 0 }
	//Id the diameter is defined, set the width and height to equal the diamter, we are making a circle tag in this case
	if(doc.elements['diameter'] != null) {
		tagwidth = parseFloat(doc.elements['diameter'].value);
		tagheight = parseFloat(doc.elements['diameter'].value)
		}
	var tagcolor = getColorValue("surf");
	var colorid = getColorValue("id");
	var textcolor = getColorValue("core");
	var tagconfig = getConfigLines('id');
	var part = doc.elements['partId'].value;
	var size = doc.elements['selectSize'].value;
	var tagtext = getFocusedText();
	//Convert to all caps if that option is set
	for(var i=0; i<tagtext.length; i++) {
		if(Boolean(parseInt(optCaps[i]))) {
			tagtext[i] = tagtext[i].toUpperCase();
			}
		}
	passtext = tagtext.join('\n');
	//Send everything to the flash movie
	flashProxy.call('showTag', part, size, tagcolor, passtext, optSize, tagwidth, tagheight, tagconfig, textcolor, optUnderline, optBold, optItalics, optFont, tagoptions, tagmount, tagquantity, colorid);
	if(obj != null) obj.focus();
	return;
	}

//DESC: Changes the step that is displayed. A step can be passed as the stepNum variable but if none is passed, the next available step will be displayed. This function also submits the form in the event that there are no more steps to be displayed.
//ARG: Integer
//RET: None
function displayStep(stepNum){

	var stepCounter = getCurrentStep();
	
	//Stops everything if we aren't switching the displayed step, as is sometimes the case when the history frame is loaded
	if(stepNum == stepCounter){return false}

	var curTab = "tab" + stepCounter;
	var curStep = "orderstep" + stepCounter;
	//If stepNum is defined, use that as the next step instead of curStep + 1
	if(stepNum != null){
		stepCounter = stepNum - 1;
		}
	//Displaying the next step, so perform validation
	else{
		//Perform validation
		var message = validateStep(stepCounter);
		//Display message and no mothing more if validation failed
		if(message != ''){
			alert(message);
			return;
			}
		}
		
	var nextTab = "tab" + (stepCounter + 1);
	var nextStep = "orderstep" + (stepCounter + 1);
	var nextNextStep = "orderstep" + (stepCounter + 2);
	//If the next step exists, change the styles to display it
	if (document.getElementById(nextStep) != null) {
		document.getElementById(curStep).style.display = "none";
		document.getElementById(curTab).className = "";
		document.getElementById(nextTab).className = "current";
		document.getElementById(nextStep).style.display = "block";
		//Change the hidden frame holding navigation data
		frames['historyiframe'].location.href = '/builder/history/history.cfm?step=' + (stepCounter+1);
		//If the step after the next step doesnt exist, the next step is last, so display the add to cart button
		if(document.getElementById(nextNextStep) == null){
			document.getElementById('linkNext').className = 'cart';
			}
		else{
			document.getElementById('linkNext').className = 'next';
			}
		testFJS();
		return false;
		}
	//Otherwise submit the form
	else {
		document.forms['form1'].submit();
		return false;
		}
	}

//DESC: Changes the style class of the div to be focused, also puts the focus in the first input if we set moveFocus to true
//ARG: Object, Boolean
//RET: None
function addDivFocus(focusDiv, divClass) {
	//gaveFocus will be whether focus has been given to an input, we want to set focus on first input
	var gaveFocus = true;
	var giveClass;
	
	if(divClass != null){giveClass = 'focus ' + divClass}
	else if(focusDiv.className.indexOf('copydiv') != -1){giveClass = 'focus copydiv'}
	else if(focusDiv.className.indexOf('nocopy') != -1){giveClass = 'focus nocopy'}
	else{giveClass = 'focus'}
	
	if(focusDiv != null) {
		focusDiv.className = giveClass;
		for(var i=0; i<focusDiv.childNodes.length; i++) {
			if (focusDiv.childNodes[i].tagName == 'INPUT') {
				// DONE TO EACH INPUT
				focusDiv.childNodes[i].readOnly = false;
				}
			}
		}
	}
	
//DESC: Changes the style class of the div previously in focus
//ARG: Object
//RET: None
function removeDivFocus(focusDiv) {
	var giveClass;
	if(focusDiv != null) {
		if(focusDiv.className.indexOf('copy') != -1){giveClass = 'outfocus copydiv'}
		else{giveClass = 'outfocus'}
		focusDiv.className = giveClass;
		for(var i=0; i<focusDiv.childNodes.length; i++) {
			if (focusDiv.childNodes[i].tagName == 'INPUT') {
				focusDiv.childNodes[i].readOnly = true;
				}
			}
		}
	}

//DESC: Used to display or hide a given element, also changes the class of the link used to display/hide the element
//ARG: String, Object
//RET: None
function showHide(elementName, linkObj) {
	elem = document.getElementById(elementName);
	if(elem.style.display == 'block'){
		elem.style.display = 'none';
		elem.className = 'closed';
		linkObj.className = 'closed';
		}
	else{
		elem.style.display = 'block';
		elem.className = 'open';
		linkObj.className = 'open';
		}
	}

//DESC: Used to force the browser to redraw the page, fixes an issue in IE when elements are not correctly displayed
//ARG: None
//RET: None
function redrawme(){
	document.getElementById('tagbox').style.display = 'none';
	document.getElementById('tagbox').style.display = 'block';
	return false;
	}

///////////////////////////////////////////////////////////
//					   AJAX GETTERS						 //
///////////////////////////////////////////////////////////

//Function to find the index in an array of the first entry with a specfic value
//It is used to get the index of a column in the column list
Array.prototype.findIdx = function(value){
	for (var i=0; i<this.length; i++){
		if (this[i] == value) {
			return i;
		}
	}
}

//DESC: Uses CFAJAXPROXY to call the getConfigs method and retrieve configurations for the selected size
//ARG: None
//RET: None
function getConfigs() {
	//create instance of cfajaxproxy cfc 'comp'
	var instance = new comp();
	var size = document.getElementById('selectSize').value;
	instance.setCallbackHandler(getConfigsResult);
	instance.getConfigs(size);
	}

//DESC: This function called when the available configurations is returned. Sets the returned configurations to the config select box
//ARG: Query
//RET: None
function getConfigsResult(res) {
	var c = document.getElementById('config');
	var cV = c.value;
	var found = false;
	
	//Start loop at 1 instead of 0 to exclude the blank option value at the top
	for(var i=1; i<res.DATA.length; i++){
		// if we've found the chosen configuration, we'll set it
		if(res.DATA[i][res.COLUMNS.findIdx('KEY')] == cV){
			found = true;
			break;
		}
	}
	//we'll show a confirm message if we didnt find a match and a config has been selected
	if((!found) && (c.options.selectedIndex != 0)){
		if(!confirm('You have selected a size that does not allow your chosen configuration.\nClick OK to continue with this size and lose your engraving information')) {
			if(document.getElementById('selectSize').tagName == 'SELECT'){
				setCombo('selectSize',document.getElementById('verifiedSize').value);
				testFJS();
			}
			return;
		}
		else{
			document.getElementById('engraveDiv').innerHTML = '';
			document.getElementById('focusDiv').value = '';
		}
	}
	//the verifiedsize hidden input hodl the value that we have verified is ok, we use this to turn back a select
	document.getElementById('verifiedSize').value = document.getElementById('selectSize').value;
	while (document.getElementById('config').childNodes.length > 0){
		document.getElementById('config').removeChild(document.getElementById('config').firstChild);
		}
		
	var mySelect = document.getElementById('config');
	mySelect.options.length = 0;
	//now populate the new options
	for (var i=0; i < res.DATA.length; i++ ) {
		mySelect.options[i] = new Option(res.DATA[i][res.COLUMNS.findIdx('VALUE')],res.DATA[i][res.COLUMNS.findIdx('KEY')]);
		}
	//addOptions("config", configsQuery, "KEY", "VALUE");
	}

///////////////////////////////////////////////////////////
//  					GETTERS 						 //
///////////////////////////////////////////////////////////

//DESC: Puts together a list of selected options for sending to flash movie
//ARG: None
//RET: Comma delimited list
function getOptions(){
	var doc = document.forms['form1'];
	var optionIndex = 1;
	var inputObject = "option_" + optionIndex;
	var optArray = new Array();
	while (doc.elements[inputObject] != null) {
		if(doc.elements[inputObject].checked) {
			optArray.push(optionIndex);
			}
		optionIndex++;
		inputObject = "option_" + optionIndex;
		}
	return optArray.join(",");
	}

//DESC: Gets the selected mount method by finding the first selected mountonfig method
//ARG: None
//RET: Integer
function getMount(){
	var mount = '';
	var cb = document.forms['form1'].elements['mount'];
	if(cb == null){
		return mount;
		}
	for(var i = 0; i < cb.length; i++){
		if(cb[i].checked == true){
			mount = cb[i].value;
			break;
			}
		}
	return mount;
	}

//DESC: Gets the values of a particular text option for each line
//ARG: String
//RET: Array
function getTextOptions(optionName) {
	var retArray = new Array();
	var form = document.forms['form1'];
	var inputPrefix = 'tag_' + optionName + '_tag1line';
	var i = 0;
	while(form.elements[inputPrefix + i] != null) {
		//If we are checking for the font and the selected font is DEFAULT, we will set the default font
		//This is done so we can maintain the value of 'Default' to be submitted in the form
		if(optionName == 'font' && form.elements[inputPrefix + i].value == 'Default'){
			retArray.push('Arial Rounded MT Bold');
			}
		else{
			retArray.push(form.elements[inputPrefix + i].value);
			}
		i++;
		}
	return retArray;
	}

//DESC: Gets the text of the currently focused div
//ARG: None
//RET: Array
function getFocusedText(){
	var retArray = new Array();
	var focusDiv = document.getElementById('focusDiv').value;
	if (focusDiv.length) {
		for(var i=0; i<document.getElementById(focusDiv).childNodes.length; i++) {
			//Make sure that the element is an input 
			if (document.getElementById(focusDiv).childNodes[i].tagName == 'INPUT') {
				//make sure the input is a text box
				if(document.getElementById(focusDiv).childNodes[i].type == 'text') {
					retArray.push(document.getElementById(focusDiv).childNodes[i].value);
					}
				}
			}
		}
	return retArray;
	}
	
//DESC: Gets information on the selected configuration, either labels, number of lines, or the config id
//ARG: String
//RET: Array, Integer
function getConfigLines(returnType) {
	var doc = document.forms['form1'];
	var cv = doc.elements['config'].value;
	var cvArray = cv.split("_");
	var linesArray = cvArray[1].split(",");
	switch(returnType) {
		case "id":
			return cvArray[0];
			break;
		case "numlines":
			return linesArray.length;
			break;
		case "lines":
			return linesArray;
			break
		}
	}

//DESC: Gets information on the selected color, either surface color, core color, or id
//ARG: String
//RET: String
function getColorValue(returnType) {
	var c = document.forms['form1'].elements['color'].value.split("_");
	var retc;
	switch(returnType) {
		case "surf":
			retc = c[0];
			break;
		case "core":
			retc = c[1];
			break;
		case "id":
			retc = c[2];
			break;
		}
	return retc;
	}

//DESC: Gets the currently displayed step 
//ARG: None
//RET: Integer
function getCurrentStep(){
	// Loop through the steps until the step set to display block (current step) is found 
	var stepCounter = 1;
	while (document.getElementById('orderstep' + stepCounter).style.display != "block") {
		stepCounter++;
		}
	return stepCounter;
	}
	
//DESC: Gets the total quantity of tags in the current job
//ARG: None
//RET: Integer
function getTotalQuantity(){
	var quantity = 0;
	var tagdiv, quantdiv, quantinput;
	//We need to loop through the inputs instead of just access by id because we could have deleted some, resulting in non-sequential quantity inputs
	for (var i=0; i<document.getElementById('engraveDiv').getElementsByTagName('DIV').length; i++) {
		tagdiv = document.getElementById('engraveDiv').getElementsByTagName('DIV')[i];
		for(var j=0; j<tagdiv.getElementsByTagName('DIV').length; j++){
			quantdiv = tagdiv.getElementsByTagName('DIV')[j];
			for(var k=0; k<quantdiv.getElementsByTagName('INPUT').length; k++){
				quantinput = quantdiv.getElementsByTagName('INPUT')[k];
				quantity += Number(quantinput.value);
				}
			}
		}
	if(quantity == 0) quantity = 1;
	return quantity;
	}

///////////////////////////////////////////////////////////
//					MISCELLANEOUS						 //
///////////////////////////////////////////////////////////

//DESC: Gets the height of a tag, if available, the number of lines and sets the text height to maximum size
//ARG: None
//RET: None
function suggestTextHeight() {
	var height, sugHeight, so;
	var numLines = getConfigLines('numlines');
	var size = document.forms['form1'].elements['selectSize'].value;
	switch(size) {
		case '4':
			height = document.forms['form1'].elements['height'].value;
			break;
		case '52':
			height = document.forms['form1'].elements['diameter'].value - .25;
			break;
		case '23':
			height = 1;
			break;
		case '24':
			height = 1.25;
			break;
		case '25':
			height = 1.5;
			break;
		case '27':
			height = 2.0;
			break;
		case '28':
			height = 0.75;
			break;
		case '29':
			height = 1;
			break;
		case '30':
			height = 1;
			break;
		case '31':
			height = 1.5;
			break;
		case '32':
			height = 1.5;
			break;
		case '33':
			height = 2;
			break;
		case '34':
			height = 2;
			break;
		case '35':
			height = 1;
			break;
		case '36':
			height = 1;
			break;
		case '37':
			height = 1;
			break;
		case '38':
			height = 1.5;
			break;
		case '39':
			height = 1.5;
			break;
		case '40':
			height = 1;
			break;
		case '41':
			height = 2;
			break;
		case '42':
			height = 2;
			break;
		case '43':
			height = 4;
			break;
		case '44':
			height = 4;
			break;
		case '45':
			height = 1;
			break;
		case '46':
			height = 1.5;
			break;
		case '47':
			height = 1.5;
			break;
		case '48':
			height = 1.5;
			break;
		case '49':
			height = 2;
			break;
		case '50':
			height = 2;
			break;
		case '51':
			height = 2;
			break;
		default:
			//set height to 0 and we will check for this and give a static suggested height
			//this is what we will do in cases of pushbuttons, their sizes arent in the
			//swicth statement so in cases of pushbuttons, the height variable will be 0
			height = 0;
		}
	if(height == 0) {
		sugHeight = .126;
		}
	else {
		sugHeight = (height * .5) / numLines;
		}
	for(var i = 0; i < numLines; i++) {
		so = document.forms['form1'].elements['tag_size_tag1line' + i];
		for(var j=0; j<so.options.length; j++) {
			if(parseFloat(so.options[j].value) < sugHeight) {
				so.options[j].selected = true;
				}
			}
		}
	}
	
//DESC: Takes a step number and validates all the attributes in the step, returning a message, which is empty with validation success
//ARG: Integer
//RET: String
function validateStep(stepNum){
	// Get an array of the attributes in the step
	var aA = document.getElementById('validateStep'+stepNum).value.split(",");
	var message = '';
	
	// Loop through the attributes and validate each, setting the message variable if validation fails
	for(var i = 0; i < aA.length; i++){
		switch(aA[i]) {
			case 'color':
				if(document.getElementById('color').selectedIndex == 0){
					message = message + "You must select a color\n";	
				}
				break;
			case 'size_1':
				if(!_CF_hasValue(document.forms['form1'].elements['width'],"TEXT") || !_CF_checkrange(document.forms['form1'].elements['width'].value, .25, 24)){
					message = message + "Enter a width between .25 in and 24 in\n";	
				}
				if(!_CF_hasValue(document.forms['form1'].elements['height'],"TEXT") || !_CF_checkrange(document.forms['form1'].elements['height'].value, .25, 16)){
					message = message + "Enter a height between .25 in and 16 in\n";	
				}
				break;
			case 'size_2':
			case 'size_3':
				if(document.getElementById('selectSize').selectedIndex == 0){
					message = message + "You must select a size\n";	
				}
				break;
			case 'size_4':
				if(!_CF_hasValue(document.forms['form1'].elements['diameter'],"TEXT") || !_CF_checkrange(document.forms['form1'].elements['diameter'].value, 1, 12)){
					message = message + "Enter a diameter between 1 in and 12 in\n";	
				}
				break;
			case 'engraving':
				if(document.getElementById('config').selectedIndex == 0){
					message = message + "You must select a configuration\n";	
				}
				var q = 1;
				var iP;
				while(document.forms['form1'].elements['quantity_' + q] != null) {
					iP = document.forms['form1'].elements['quantity_' + q];
					//Check if the value of the quantity is a number
					if(!_CF_hasValue(iP, 'TEXT') || !_CF_checkinteger(iP.value) || !_CF_numberrange(iP.value, 1)){
						message = message + "Please Select a Numeric Quantity for Tag " + q + " Greater than 0.\n";			   
						}
					q++;
				}
			}
		}
	return message;
	}

///////////////////////////////////////////////////////////
//  					HELPERS							 //
///////////////////////////////////////////////////////////
function setCombo(comboId, myValue){
	var comboElem = document.getElementById(comboId);
	for(var i=0; i<comboElem.options.length; i++) {
		if(comboElem.options[i].value == myValue) {
			comboElem.options[i].selected = true;
			break;
		}
	}
}

function setConfigCombo(myValue){
	var comboElem = document.getElementById('config');
	for(var i=0; i<comboElem.options.length; i++) {
		var a = comboElem.options[i].value.split("_");
		if(parseFloat(a[0]) == myValue) {
			comboElem.options[i].selected = true;
			break;
		}
	}
}

function setColorCombo(myValue){
	var comboElem = document.getElementById('color');
	for(var i=0; i<comboElem.options.length; i++) {
		var a = comboElem.options[i].value.split("_");
		if(parseFloat(a[2]) == myValue) {
			comboElem.options[i].selected = true;
			break;
		}
	}
}

function copyDown(divNum,lineNum) {
	var copyValue = document.forms['form1'].elements['tag'+divNum+'line'+lineNum].value;
	var labels = getConfigLines('lines');
	var numlines = labels.length
	for (var i=0; i<document.getElementById('engraveDiv').childNodes.length; i++) {
		//Check that the child node is a div (containing a tags inputs), otherwise do nothing
		if (document.getElementById('engraveDiv').childNodes[i].tagName == 'DIV') {
			// tagId is the div id of the tags we are looping through
			tagId = document.getElementById('engraveDiv').childNodes[i];
			inputcounter = 0;
			// loop through all elements in tag div
			var initialNumber = tagId.childNodes.length;
			for (var j=0; j<initialNumber; j++) {
				// If we haven't encountered the number of inputs we want, go through and edit labels
				if(inputcounter < numlines) {
					if(tagId.childNodes[j].tagName == "INPUT") {
						if (tagId.childNodes[j].type == 'text') {
							if(inputcounter == lineNum){
								tagId.childNodes[j].value = copyValue;
								}
							inputcounter++;
							}
						}
					}
				}
			}
		}
	}
	
function fillFromPrevious(divNum) {
	var pasteId = 'tag' + divNum;
	var copyId;
	for (var i=0; i<document.getElementById('engraveDiv').childNodes.length; i++) {
		//Check that the child node is a div (containing a tags inputs), otherwise do nothing
		if(document.getElementById('engraveDiv').childNodes[i].tagName == 'DIV') {
			//If we have found the element that should have values filled to and we have a value for the copy from tag
			if((document.getElementById('engraveDiv').childNodes[i].id == pasteId) && (copyId != null)){
				//Loop through the inputs in the divs to copy and paste them
				for(var j=0; j<document.getElementById(copyId).childNodes.length; j++){
					if(document.getElementById(copyId).childNodes[j].tagName == 'INPUT') {
						document.getElementById(pasteId).childNodes[j].value = document.getElementById(copyId).childNodes[j].value;
						}	
					}
				break;
				}
			//The copyId will represent the id of the div right before the div to have values filled, once it is found
			copyId = document.getElementById('engraveDiv').childNodes[i].id;
			}
		}
	}
	
function newHelpWindow(infotype,infoid,secid) {
	var url = "/help/information.cfm?infotype=";
	url += infotype;
	if (infoid != "none") {
		url = url + "&infoid=" + infoid;
		}
	if (secid != "none") {
		url = url + "&secondaryid=" + secid;
		}
	infowindow = window.open(url, "Info", "width=500,height=400");
	infowindow.focus();
	}
